blob: 66ba853da2fe98b236312534e1b146ddd8a62e21 [file] [log] [blame]
Chris Lattnerb0133452009-06-21 20:16:42 +00001//===- AsmParser.cpp - Parser for Assembly Files --------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This class implements the parser for assembly files.
11//
12//===----------------------------------------------------------------------===//
13
Daniel Dunbar2af16532010-09-24 01:59:56 +000014#include "llvm/ADT/APFloat.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000015#include "llvm/ADT/APInt.h"
16#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/None.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000018#include "llvm/ADT/SmallString.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000019#include "llvm/ADT/SmallVector.h"
20#include "llvm/ADT/STLExtras.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000021#include "llvm/ADT/StringMap.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000022#include "llvm/ADT/StringRef.h"
Daniel Dunbareb6bb322009-07-27 23:20:52 +000023#include "llvm/ADT/Twine.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000024#include "llvm/MC/MCAsmInfo.h"
Reid Klecknera5b1eef2016-08-26 17:58:37 +000025#include "llvm/MC/MCCodeView.h"
Daniel Dunbarca29e4d2009-06-23 22:01:43 +000026#include "llvm/MC/MCContext.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000027#include "llvm/MC/MCDirectives.h"
Evan Cheng11424442011-07-26 00:24:13 +000028#include "llvm/MC/MCDwarf.h"
Daniel Dunbar115e4d62009-08-31 08:06:59 +000029#include "llvm/MC/MCExpr.h"
Chad Rosier8bce6642012-10-18 15:49:34 +000030#include "llvm/MC/MCInstPrinter.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000031#include "llvm/MC/MCInstrDesc.h"
Chad Rosier8bce6642012-10-18 15:49:34 +000032#include "llvm/MC/MCInstrInfo.h"
Rafael Espindolae28610d2013-12-09 20:26:40 +000033#include "llvm/MC/MCObjectFileInfo.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000034#include "llvm/MC/MCParser/AsmCond.h"
35#include "llvm/MC/MCParser/AsmLexer.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000036#include "llvm/MC/MCParser/MCAsmLexer.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000037#include "llvm/MC/MCParser/MCAsmParser.h"
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +000038#include "llvm/MC/MCParser/MCAsmParserExtension.h"
Pete Cooper80d21cb2015-06-22 19:35:57 +000039#include "llvm/MC/MCParser/MCAsmParserUtils.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000040#include "llvm/MC/MCParser/MCParsedAsmOperand.h"
Benjamin Kramerb3e8a6d2016-01-27 10:01:28 +000041#include "llvm/MC/MCParser/MCTargetAsmParser.h"
Evan Cheng76792992011-07-20 05:58:47 +000042#include "llvm/MC/MCRegisterInfo.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000043#include "llvm/MC/MCSection.h"
Daniel Dunbarca29e4d2009-06-23 22:01:43 +000044#include "llvm/MC/MCStreamer.h"
Daniel Dunbarae7ac012009-06-29 23:43:14 +000045#include "llvm/MC/MCSymbol.h"
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +000046#include "llvm/MC/MCTargetOptions.h"
Daniel Sanders9f6ad492015-11-12 13:33:00 +000047#include "llvm/MC/MCValue.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000048#include "llvm/Support/Casting.h"
Davide Italiano7c9fc732016-07-27 05:51:56 +000049#include "llvm/Support/CommandLine.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000050#include "llvm/Support/Dwarf.h"
Benjamin Kramer4efe5062012-01-28 15:28:41 +000051#include "llvm/Support/ErrorHandling.h"
Jim Grosbach76346c32011-06-29 16:05:14 +000052#include "llvm/Support/MathExtras.h"
Kevin Enderbye233dda2010-06-28 21:45:58 +000053#include "llvm/Support/MemoryBuffer.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000054#include "llvm/Support/SMLoc.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000055#include "llvm/Support/SourceMgr.h"
Chris Lattner36e02122009-06-21 20:54:55 +000056#include "llvm/Support/raw_ostream.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000057#include <algorithm>
58#include <cassert>
Nick Lewycky0de20af2010-12-19 20:43:38 +000059#include <cctype>
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +000060#include <climits>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000061#include <cstddef>
62#include <cstdint>
Benjamin Kramerd59664f2014-04-29 23:26:49 +000063#include <deque>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000064#include <memory>
Davide Italiano7c9fc732016-07-27 05:51:56 +000065#include <sstream>
Chad Rosier8bce6642012-10-18 15:49:34 +000066#include <string>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000067#include <tuple>
68#include <utility>
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000069#include <vector>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000070
Chris Lattnerb0133452009-06-21 20:16:42 +000071using namespace llvm;
72
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +000073MCAsmParserSemaCallback::~MCAsmParserSemaCallback() = default;
Nick Lewyckyac612272012-10-19 07:00:09 +000074
Davide Italiano7c9fc732016-07-27 05:51:56 +000075static cl::opt<unsigned> AsmMacroMaxNestingDepth(
76 "asm-macro-max-nesting-depth", cl::init(20), cl::Hidden,
77 cl::desc("The maximum nesting depth allowed for assembly macros."));
78
Daniel Dunbar86033402010-07-12 17:54:38 +000079namespace {
Eugene Zelenko33d7b762016-08-23 17:14:32 +000080
Eli Benderskya313ae62013-01-16 18:56:50 +000081/// \brief Helper types for tracking macro definitions.
82typedef std::vector<AsmToken> MCAsmMacroArgument;
83typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +000084
85struct MCAsmMacroParameter {
86 StringRef Name;
87 MCAsmMacroArgument Value;
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +000088 bool Required = false;
89 bool Vararg = false;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +000090
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +000091 MCAsmMacroParameter() = default;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +000092};
93
Eli Benderskya313ae62013-01-16 18:56:50 +000094typedef std::vector<MCAsmMacroParameter> MCAsmMacroParameters;
95
96struct MCAsmMacro {
97 StringRef Name;
98 StringRef Body;
99 MCAsmMacroParameters Parameters;
100
101public:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000102 MCAsmMacro(StringRef N, StringRef B, MCAsmMacroParameters P)
103 : Name(N), Body(B), Parameters(std::move(P)) {}
Eli Benderskya313ae62013-01-16 18:56:50 +0000104};
105
Daniel Dunbar43235712010-07-18 18:54:11 +0000106/// \brief Helper class for storing information about an active macro
107/// instantiation.
108struct MacroInstantiation {
Daniel Dunbar43235712010-07-18 18:54:11 +0000109 /// The location of the instantiation.
110 SMLoc InstantiationLoc;
111
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000112 /// The buffer where parsing should resume upon instantiation completion.
113 int ExitBuffer;
114
Daniel Dunbar43235712010-07-18 18:54:11 +0000115 /// The location where parsing should resume upon instantiation completion.
116 SMLoc ExitLoc;
117
Nico Weber155dccd12014-07-24 17:08:39 +0000118 /// The depth of TheCondStack at the start of the instantiation.
119 size_t CondStackDepth;
120
Daniel Dunbar43235712010-07-18 18:54:11 +0000121public:
Rafael Espindola9eef18c2014-08-27 19:49:03 +0000122 MacroInstantiation(SMLoc IL, int EB, SMLoc EL, size_t CondStackDepth);
Daniel Dunbar43235712010-07-18 18:54:11 +0000123};
124
Eli Friedman0f4871d2012-10-22 23:58:19 +0000125struct ParseStatementInfo {
Jim Grosbach4b905842013-09-20 23:08:21 +0000126 /// \brief The parsed operands from the last parsed statement.
David Blaikie960ea3f2014-06-08 16:18:35 +0000127 SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> ParsedOperands;
Eli Friedman0f4871d2012-10-22 23:58:19 +0000128
Jim Grosbach4b905842013-09-20 23:08:21 +0000129 /// \brief The opcode from the last parsed instruction.
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000130 unsigned Opcode = ~0U;
Eli Friedman0f4871d2012-10-22 23:58:19 +0000131
Jim Grosbach4b905842013-09-20 23:08:21 +0000132 /// \brief Was there an error parsing the inline assembly?
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000133 bool ParseError = false;
Chad Rosier149e8e02012-12-12 22:45:52 +0000134
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000135 SmallVectorImpl<AsmRewrite> *AsmRewrites = nullptr;
Eli Friedman0f4871d2012-10-22 23:58:19 +0000136
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +0000137 ParseStatementInfo() = delete;
Eli Friedman0f4871d2012-10-22 23:58:19 +0000138 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000139 : AsmRewrites(rewrites) {}
Eli Friedman0f4871d2012-10-22 23:58:19 +0000140};
141
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000142/// \brief The concrete assembly parser instance.
143class AsmParser : public MCAsmParser {
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000144private:
145 AsmLexer Lexer;
146 MCContext &Ctx;
147 MCStreamer &Out;
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000148 const MCAsmInfo &MAI;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000149 SourceMgr &SrcMgr;
Benjamin Kramer47f5e302011-10-16 10:48:29 +0000150 SourceMgr::DiagHandlerTy SavedDiagHandler;
151 void *SavedDiagContext;
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000152 std::unique_ptr<MCAsmParserExtension> PlatformParser;
Rafael Espindola82065cb2011-04-11 21:49:50 +0000153
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000154 /// This is the current buffer index we're lexing from as managed by the
155 /// SourceMgr object.
Alp Tokera55b95b2014-07-06 10:33:31 +0000156 unsigned CurBuffer;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000157
158 AsmCond TheCondState;
159 std::vector<AsmCond> TheCondStack;
160
Jim Grosbach4b905842013-09-20 23:08:21 +0000161 /// \brief maps directive names to handler methods in parser
Eli Bendersky17233942013-01-15 22:59:42 +0000162 /// extensions. Extensions register themselves in this map by calling
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000163 /// addDirectiveHandler.
Eli Bendersky17233942013-01-15 22:59:42 +0000164 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
Daniel Dunbar828984f2010-07-18 18:38:02 +0000165
Jim Grosbach4b905842013-09-20 23:08:21 +0000166 /// \brief Map of currently defined macros.
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000167 StringMap<MCAsmMacro> MacroMap;
Daniel Dunbarc1f58ec2010-07-18 18:47:21 +0000168
Jim Grosbach4b905842013-09-20 23:08:21 +0000169 /// \brief Stack of active macro instantiations.
Daniel Dunbar43235712010-07-18 18:54:11 +0000170 std::vector<MacroInstantiation*> ActiveMacros;
171
Jim Grosbach4b905842013-09-20 23:08:21 +0000172 /// \brief List of bodies of anonymous macros.
Benjamin Kramer1df3a1f2013-08-04 09:06:29 +0000173 std::deque<MCAsmMacro> MacroLikeBodies;
174
Daniel Dunbar828984f2010-07-18 18:38:02 +0000175 /// Boolean tracking whether macro substitution is enabled.
Eli Benderskyc2f6f922013-01-14 18:08:41 +0000176 unsigned MacrosEnabledFlag : 1;
Daniel Dunbar828984f2010-07-18 18:38:02 +0000177
Toma Tabacu217116e2015-04-27 10:50:29 +0000178 /// \brief Keeps track of how many .macro's have been instantiated.
179 unsigned NumOfMacroInstantiations;
180
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000181 /// The values from the last parsed cpp hash file line comment if any.
Tim Northoverc0bef992016-04-13 19:46:54 +0000182 struct CppHashInfoTy {
183 StringRef Filename;
Andrew Kaylorca196472016-04-21 20:09:35 +0000184 int64_t LineNumber = 0;
Tim Northoverc0bef992016-04-13 19:46:54 +0000185 SMLoc Loc;
Andrew Kaylorca196472016-04-21 20:09:35 +0000186 unsigned Buf = 0;
Tim Northoverc0bef992016-04-13 19:46:54 +0000187 };
188 CppHashInfoTy CppHashInfo;
189
190 /// \brief List of forward directional labels for diagnosis at the end.
191 SmallVector<std::tuple<SMLoc, CppHashInfoTy, MCSymbol *>, 4> DirLabels;
192
Kevin Enderby0fd064c2013-06-21 20:51:39 +0000193 /// When generating dwarf for assembly source files we need to calculate the
194 /// logical line number based on the last parsed cpp hash file line comment
Vladimir Medic9bad0d332013-08-20 13:33:18 +0000195 /// and current line. Since this is slow and messes up the SourceMgr's
Kevin Enderby0fd064c2013-06-21 20:51:39 +0000196 /// cache we save the last info we queried with SrcMgr.FindLineNumber().
197 SMLoc LastQueryIDLoc;
Alp Tokera55b95b2014-07-06 10:33:31 +0000198 unsigned LastQueryBuffer;
Kevin Enderby0fd064c2013-06-21 20:51:39 +0000199 unsigned LastQueryLine;
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000200
Devang Patela173ee52012-01-31 18:14:05 +0000201 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000202 unsigned AssemblerDialect = ~0U;
Devang Patela173ee52012-01-31 18:14:05 +0000203
Jim Grosbach4b905842013-09-20 23:08:21 +0000204 /// \brief is Darwin compatibility enabled?
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000205 bool IsDarwin = false;
Preston Gurd05500642012-09-19 20:36:12 +0000206
Jim Grosbach4b905842013-09-20 23:08:21 +0000207 /// \brief Are we parsing ms-style inline assembly?
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000208 bool ParsingInlineAsm = false;
Chad Rosier49963552012-10-13 00:26:04 +0000209
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000210public:
Jim Grosbach345768c2011-08-16 18:33:49 +0000211 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Sanne Wouda29338752017-02-08 14:48:05 +0000212 const MCAsmInfo &MAI, unsigned CB);
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000213 AsmParser(const AsmParser &) = delete;
214 AsmParser &operator=(const AsmParser &) = delete;
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000215 ~AsmParser() override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000216
Craig Topper59be68f2014-03-08 07:14:16 +0000217 bool Run(bool NoInitialTextSection, bool NoFinalize = false) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000218
Craig Topper59be68f2014-03-08 07:14:16 +0000219 void addDirectiveHandler(StringRef Directive,
220 ExtensionDirectiveHandler Handler) override {
Eli Bendersky29b9f472013-01-16 00:50:52 +0000221 ExtensionDirectiveMap[Directive] = Handler;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000222 }
223
Toma Tabacu11e14a92015-04-21 11:50:52 +0000224 void addAliasForDirective(StringRef Directive, StringRef Alias) override {
225 DirectiveKindMap[Directive] = DirectiveKindMap[Alias];
226 }
227
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000228 /// @name MCAsmParser Interface
229 /// {
230
Craig Topper59be68f2014-03-08 07:14:16 +0000231 SourceMgr &getSourceManager() override { return SrcMgr; }
232 MCAsmLexer &getLexer() override { return Lexer; }
233 MCContext &getContext() override { return Ctx; }
234 MCStreamer &getStreamer() override { return Out; }
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000235
Reid Klecknera5b1eef2016-08-26 17:58:37 +0000236 CodeViewContext &getCVContext() { return Ctx.getCVContext(); }
237
Craig Topper59be68f2014-03-08 07:14:16 +0000238 unsigned getAssemblerDialect() override {
Devang Patela173ee52012-01-31 18:14:05 +0000239 if (AssemblerDialect == ~0U)
Eric Christophera7c32732012-12-18 00:30:54 +0000240 return MAI.getAssemblerDialect();
Devang Patela173ee52012-01-31 18:14:05 +0000241 else
242 return AssemblerDialect;
243 }
Craig Topper59be68f2014-03-08 07:14:16 +0000244 void setAssemblerDialect(unsigned i) override {
Devang Patela173ee52012-01-31 18:14:05 +0000245 AssemblerDialect = i;
246 }
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000247
Nirav Dave2364748a2016-09-16 18:30:20 +0000248 void Note(SMLoc L, const Twine &Msg, SMRange Range = None) override;
249 bool Warning(SMLoc L, const Twine &Msg, SMRange Range = None) override;
250 bool printError(SMLoc L, const Twine &Msg, SMRange Range = None) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000251
Craig Topper59be68f2014-03-08 07:14:16 +0000252 const AsmToken &Lex() override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000253
Yunzhong Gao27ea29b2016-09-02 23:15:29 +0000254 void setParsingInlineAsm(bool V) override {
255 ParsingInlineAsm = V;
256 Lexer.setParsingMSInlineAsm(V);
257 }
Craig Topper59be68f2014-03-08 07:14:16 +0000258 bool isParsingInlineAsm() override { return ParsingInlineAsm; }
Chad Rosier8bce6642012-10-18 15:49:34 +0000259
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000260 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
Chad Rosier8bce6642012-10-18 15:49:34 +0000261 unsigned &NumOutputs, unsigned &NumInputs,
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000262 SmallVectorImpl<std::pair<void *,bool>> &OpDecls,
Chad Rosier8bce6642012-10-18 15:49:34 +0000263 SmallVectorImpl<std::string> &Constraints,
Chad Rosier8bce6642012-10-18 15:49:34 +0000264 SmallVectorImpl<std::string> &Clobbers,
Craig Topper59be68f2014-03-08 07:14:16 +0000265 const MCInstrInfo *MII, const MCInstPrinter *IP,
266 MCAsmParserSemaCallback &SI) override;
Chad Rosier49963552012-10-13 00:26:04 +0000267
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000268 bool parseExpression(const MCExpr *&Res);
Craig Topper59be68f2014-03-08 07:14:16 +0000269 bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
270 bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) override;
271 bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
Toma Tabacu7bc44dc2015-06-25 09:52:02 +0000272 bool parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
273 SMLoc &EndLoc) override;
Craig Topper59be68f2014-03-08 07:14:16 +0000274 bool parseAbsoluteExpression(int64_t &Res) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000275
Petr Hosek4cb08ce2016-09-23 19:25:15 +0000276 /// \brief Parse a floating point expression using the float \p Semantics
277 /// and set \p Res to the value.
278 bool parseRealValue(const fltSemantics &Semantics, APInt &Res);
279
Jim Grosbach4b905842013-09-20 23:08:21 +0000280 /// \brief Parse an identifier or string (as a quoted identifier)
Eli Bendersky0cf0cb92013-01-12 00:05:00 +0000281 /// and set \p Res to the identifier contents.
Craig Topper59be68f2014-03-08 07:14:16 +0000282 bool parseIdentifier(StringRef &Res) override;
283 void eatToEndOfStatement() override;
Eli Bendersky0cf0cb92013-01-12 00:05:00 +0000284
Nirav Davef43cc9f2016-10-10 15:24:54 +0000285 bool checkForValidSection() override;
Nirav Davea645433c2016-07-18 15:24:03 +0000286
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000287 /// }
288
289private:
Michael Zuckerman763e60e2017-05-04 10:37:00 +0000290 bool isAltmacroString(SMLoc &StrLoc, SMLoc &EndLoc);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +0000291 bool parseStatement(ParseStatementInfo &Info,
292 MCAsmParserSemaCallback *SI);
Marina Yatsina5f5de9f2016-03-07 18:11:16 +0000293 bool parseCurlyBlockScope(SmallVectorImpl<AsmRewrite>& AsmStrRewrites);
Craig Topper3c76c522015-09-20 23:35:59 +0000294 bool parseCppHashLineFilenameComment(SMLoc L);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000295
Jim Grosbach4b905842013-09-20 23:08:21 +0000296 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +0000297 ArrayRef<MCAsmMacroParameter> Parameters);
Rafael Espindola34b9c512012-06-03 23:57:14 +0000298 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +0000299 ArrayRef<MCAsmMacroParameter> Parameters,
Toma Tabacu217116e2015-04-27 10:50:29 +0000300 ArrayRef<MCAsmMacroArgument> A, bool EnableAtPseudoVariable,
Craig Topper3c76c522015-09-20 23:35:59 +0000301 SMLoc L);
Daniel Dunbar43235712010-07-18 18:54:11 +0000302
Eli Benderskya313ae62013-01-16 18:56:50 +0000303 /// \brief Are macros enabled in the parser?
Jim Grosbach4b905842013-09-20 23:08:21 +0000304 bool areMacrosEnabled() {return MacrosEnabledFlag;}
Eli Benderskya313ae62013-01-16 18:56:50 +0000305
306 /// \brief Control a flag in the parser that enables or disables macros.
Jim Grosbach4b905842013-09-20 23:08:21 +0000307 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
Eli Benderskya313ae62013-01-16 18:56:50 +0000308
309 /// \brief Lookup a previously defined macro.
310 /// \param Name Macro name.
311 /// \returns Pointer to macro. NULL if no such macro was defined.
Jim Grosbach4b905842013-09-20 23:08:21 +0000312 const MCAsmMacro* lookupMacro(StringRef Name);
Eli Benderskya313ae62013-01-16 18:56:50 +0000313
314 /// \brief Define a new macro with the given name and information.
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000315 void defineMacro(StringRef Name, MCAsmMacro Macro);
Eli Benderskya313ae62013-01-16 18:56:50 +0000316
317 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
Jim Grosbach4b905842013-09-20 23:08:21 +0000318 void undefineMacro(StringRef Name);
Eli Benderskya313ae62013-01-16 18:56:50 +0000319
320 /// \brief Are we inside a macro instantiation?
Jim Grosbach4b905842013-09-20 23:08:21 +0000321 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
Eli Benderskya313ae62013-01-16 18:56:50 +0000322
Vladimir Medic9bad0d332013-08-20 13:33:18 +0000323 /// \brief Handle entry to macro instantiation.
Eli Benderskya313ae62013-01-16 18:56:50 +0000324 ///
325 /// \param M The macro.
326 /// \param NameLoc Instantiation location.
Jim Grosbach4b905842013-09-20 23:08:21 +0000327 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
Eli Benderskya313ae62013-01-16 18:56:50 +0000328
329 /// \brief Handle exit from macro instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +0000330 void handleMacroExit();
Eli Benderskya313ae62013-01-16 18:56:50 +0000331
David Majnemer91fc4c22014-01-29 18:57:46 +0000332 /// \brief Extract AsmTokens for a macro argument.
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +0000333 bool parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg);
Eli Benderskya313ae62013-01-16 18:56:50 +0000334
335 /// \brief Parse all macro arguments for a given macro.
Jim Grosbach4b905842013-09-20 23:08:21 +0000336 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
Eli Benderskya313ae62013-01-16 18:56:50 +0000337
Jim Grosbach4b905842013-09-20 23:08:21 +0000338 void printMacroInstantiations();
339 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
Nirav Dave2364748a2016-09-16 18:30:20 +0000340 SMRange Range = None) const {
341 ArrayRef<SMRange> Ranges(Range);
Chris Lattner72845262011-10-16 05:47:55 +0000342 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
Benjamin Kramerc7583112010-09-27 17:42:11 +0000343 }
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000344 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
Benjamin Kramerc7583112010-09-27 17:42:11 +0000345
Jim Grosbach4b905842013-09-20 23:08:21 +0000346 /// \brief Enter the specified file. This returns true on failure.
347 bool enterIncludeFile(const std::string &Filename);
348
349 /// \brief Process the specified file for the .incbin directive.
Kevin Enderby109f25c2011-12-14 21:47:48 +0000350 /// This returns true on failure.
Petr Hosek2f4ac442016-09-23 00:41:06 +0000351 bool processIncbinFile(const std::string &Filename, int64_t Skip = 0,
352 const MCExpr *Count = nullptr, SMLoc Loc = SMLoc());
Daniel Dunbar43235712010-07-18 18:54:11 +0000353
Dmitri Gribenko5485acd2012-09-14 14:57:36 +0000354 /// \brief Reset the current lexer position to that given by \p Loc. The
Daniel Dunbar43235712010-07-18 18:54:11 +0000355 /// current token is not set; clients should ensure Lex() is called
356 /// subsequently.
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000357 ///
Alp Tokera55b95b2014-07-06 10:33:31 +0000358 /// \param InBuffer If not 0, should be the known buffer id that contains the
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000359 /// location.
Alp Tokera55b95b2014-07-06 10:33:31 +0000360 void jumpToLoc(SMLoc Loc, unsigned InBuffer = 0);
Daniel Dunbar43235712010-07-18 18:54:11 +0000361
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000362 /// \brief Parse up to the end of statement and a return the contents from the
363 /// current token until the end of the statement; the current token on exit
364 /// will be either the EndOfStatement or EOF.
Craig Topper59be68f2014-03-08 07:14:16 +0000365 StringRef parseStringToEndOfStatement() override;
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000366
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000367 /// \brief Parse until the end of a statement or a comma is encountered,
368 /// return the contents from the current token up to the end or comma.
Jim Grosbach4b905842013-09-20 23:08:21 +0000369 StringRef parseStringToComma();
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000370
Jim Grosbach4b905842013-09-20 23:08:21 +0000371 bool parseAssignment(StringRef Name, bool allow_redef,
Jim Grosbachb7b750d2012-09-13 23:11:31 +0000372 bool NoDeadStrip = false);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000373
Ahmed Bougacha457852f2015-04-28 00:17:39 +0000374 unsigned getBinOpPrecedence(AsmToken::TokenKind K,
375 MCBinaryExpr::Opcode &Kind);
376
Jim Grosbach4b905842013-09-20 23:08:21 +0000377 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
378 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
379 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000380
Jim Grosbach4b905842013-09-20 23:08:21 +0000381 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
Rafael Espindola63760ba2010-10-28 20:02:27 +0000382
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000383 bool parseCVFunctionId(int64_t &FunctionId, StringRef DirectiveName);
384 bool parseCVFileId(int64_t &FileId, StringRef DirectiveName);
385
Eli Bendersky17233942013-01-15 22:59:42 +0000386 // Generic (target and platform independent) directive parsing.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000387 enum DirectiveKind {
Eli Bendersky4d21fa02013-01-10 23:40:56 +0000388 DK_NO_DIRECTIVE, // Placeholder
389 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
Daniel Sanders9f6ad492015-11-12 13:33:00 +0000390 DK_RELOC,
David Woodhoused6de0d92014-02-01 16:20:59 +0000391 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_OCTA,
Petr Hosek731bb9c2016-08-23 21:34:53 +0000392 DK_DC, DK_DC_A, DK_DC_B, DK_DC_D, DK_DC_L, DK_DC_S, DK_DC_W, DK_DC_X,
Petr Hosek4cb08ce2016-09-23 19:25:15 +0000393 DK_DCB, DK_DCB_B, DK_DCB_D, DK_DCB_L, DK_DCB_S, DK_DCB_W, DK_DCB_X,
Petr Hosek85b2f672016-09-23 21:53:36 +0000394 DK_DS, DK_DS_B, DK_DS_D, DK_DS_L, DK_DS_P, DK_DS_S, DK_DS_W, DK_DS_X,
David Woodhoused6de0d92014-02-01 16:20:59 +0000395 DK_SINGLE, DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
Eli Bendersky96522722013-01-11 22:55:28 +0000396 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
Eli Bendersky4d21fa02013-01-10 23:40:56 +0000397 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
Kevin Enderby3aeada22013-08-28 17:50:59 +0000398 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL,
Lang Hamesf9033bb2016-04-11 18:33:45 +0000399 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER,
Lang Hames1b640e02016-03-15 01:43:05 +0000400 DK_PRIVATE_EXTERN, DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
Eli Bendersky4d21fa02013-01-10 23:40:56 +0000401 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
402 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +0000403 DK_IF, DK_IFEQ, DK_IFGE, DK_IFGT, DK_IFLE, DK_IFLT, DK_IFNE, DK_IFB,
Sid Manning51c35602015-03-18 14:20:54 +0000404 DK_IFNB, DK_IFC, DK_IFEQS, DK_IFNC, DK_IFNES, DK_IFDEF, DK_IFNDEF,
405 DK_IFNOTDEF, DK_ELSEIF, DK_ELSE, DK_ENDIF,
Eli Bendersky17233942013-01-15 22:59:42 +0000406 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000407 DK_CV_FILE, DK_CV_FUNC_ID, DK_CV_INLINE_SITE_ID, DK_CV_LOC, DK_CV_LINETABLE,
408 DK_CV_INLINE_LINETABLE, DK_CV_DEF_RANGE, DK_CV_STRINGTABLE,
409 DK_CV_FILECHECKSUMS,
Eli Bendersky17233942013-01-15 22:59:42 +0000410 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
411 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
412 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
413 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
414 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +0000415 DK_CFI_REGISTER, DK_CFI_WINDOW_SAVE,
Michael Zuckerman56704612017-05-01 13:20:12 +0000416 DK_MACROS_ON, DK_MACROS_OFF, DK_ALTMACRO, DK_NOALTMACRO,
Nico Weber155dccd12014-07-24 17:08:39 +0000417 DK_MACRO, DK_EXITM, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000418 DK_SLEB128, DK_ULEB128,
Nico Weber404012b2014-07-24 16:26:06 +0000419 DK_ERR, DK_ERROR, DK_WARNING,
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000420 DK_END
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000421 };
422
Jim Grosbach4b905842013-09-20 23:08:21 +0000423 /// \brief Maps directive name --> DirectiveKind enum, for
Eli Bendersky17233942013-01-15 22:59:42 +0000424 /// directives parsed by this class.
425 StringMap<DirectiveKind> DirectiveKindMap;
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000426
427 // ".ascii", ".asciz", ".string"
Jim Grosbach4b905842013-09-20 23:08:21 +0000428 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
Daniel Sanders9f6ad492015-11-12 13:33:00 +0000429 bool parseDirectiveReloc(SMLoc DirectiveLoc); // ".reloc"
Nirav Dave1a9044b2016-10-24 14:35:29 +0000430 bool parseDirectiveValue(StringRef IDVal,
431 unsigned Size); // ".byte", ".long", ...
432 bool parseDirectiveOctaValue(StringRef IDVal); // ".octa", ...
433 bool parseDirectiveRealValue(StringRef IDVal,
434 const fltSemantics &); // ".single", ...
Jim Grosbach4b905842013-09-20 23:08:21 +0000435 bool parseDirectiveFill(); // ".fill"
436 bool parseDirectiveZero(); // ".zero"
Eric Christophera7c32732012-12-18 00:30:54 +0000437 // ".set", ".equ", ".equiv"
Jim Grosbach4b905842013-09-20 23:08:21 +0000438 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
439 bool parseDirectiveOrg(); // ".org"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000440 // ".align{,32}", ".p2align{,w,l}"
Jim Grosbach4b905842013-09-20 23:08:21 +0000441 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000442
Eli Bendersky17233942013-01-15 22:59:42 +0000443 // ".file", ".line", ".loc", ".stabs"
Jim Grosbach4b905842013-09-20 23:08:21 +0000444 bool parseDirectiveFile(SMLoc DirectiveLoc);
445 bool parseDirectiveLine();
446 bool parseDirectiveLoc();
447 bool parseDirectiveStabs();
Eli Bendersky17233942013-01-15 22:59:42 +0000448
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000449 // ".cv_file", ".cv_func_id", ".cv_inline_site_id", ".cv_loc", ".cv_linetable",
450 // ".cv_inline_linetable", ".cv_def_range"
Reid Kleckner2214ed82016-01-29 00:49:42 +0000451 bool parseDirectiveCVFile();
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000452 bool parseDirectiveCVFuncId();
453 bool parseDirectiveCVInlineSiteId();
Reid Kleckner2214ed82016-01-29 00:49:42 +0000454 bool parseDirectiveCVLoc();
455 bool parseDirectiveCVLinetable();
David Majnemer6fcbd7e2016-01-29 19:24:12 +0000456 bool parseDirectiveCVInlineLinetable();
David Majnemer408b5e62016-02-05 01:55:49 +0000457 bool parseDirectiveCVDefRange();
Reid Kleckner2214ed82016-01-29 00:49:42 +0000458 bool parseDirectiveCVStringTable();
459 bool parseDirectiveCVFileChecksums();
460
Eli Bendersky17233942013-01-15 22:59:42 +0000461 // .cfi directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000462 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +0000463 bool parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +0000464 bool parseDirectiveCFISections();
465 bool parseDirectiveCFIStartProc();
466 bool parseDirectiveCFIEndProc();
467 bool parseDirectiveCFIDefCfaOffset();
468 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
469 bool parseDirectiveCFIAdjustCfaOffset();
470 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
471 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
472 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
473 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
474 bool parseDirectiveCFIRememberState();
475 bool parseDirectiveCFIRestoreState();
476 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
477 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
478 bool parseDirectiveCFIEscape();
479 bool parseDirectiveCFISignalFrame();
480 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
Eli Bendersky17233942013-01-15 22:59:42 +0000481
482 // macro directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000483 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
Nico Weber155dccd12014-07-24 17:08:39 +0000484 bool parseDirectiveExitMacro(StringRef Directive);
Jim Grosbach4b905842013-09-20 23:08:21 +0000485 bool parseDirectiveEndMacro(StringRef Directive);
486 bool parseDirectiveMacro(SMLoc DirectiveLoc);
487 bool parseDirectiveMacrosOnOff(StringRef Directive);
Michael Zuckerman56704612017-05-01 13:20:12 +0000488 // alternate macro mode directives
489 bool parseDirectiveAltmacro(StringRef Directive);
Eli Benderskyf483ff92012-12-20 19:05:53 +0000490 // ".bundle_align_mode"
Jim Grosbach4b905842013-09-20 23:08:21 +0000491 bool parseDirectiveBundleAlignMode();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000492 // ".bundle_lock"
Jim Grosbach4b905842013-09-20 23:08:21 +0000493 bool parseDirectiveBundleLock();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000494 // ".bundle_unlock"
Jim Grosbach4b905842013-09-20 23:08:21 +0000495 bool parseDirectiveBundleUnlock();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000496
Eli Bendersky17233942013-01-15 22:59:42 +0000497 // ".space", ".skip"
Jim Grosbach4b905842013-09-20 23:08:21 +0000498 bool parseDirectiveSpace(StringRef IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +0000499
Petr Hosek4cb08ce2016-09-23 19:25:15 +0000500 // ".dcb"
501 bool parseDirectiveDCB(StringRef IDVal, unsigned Size);
502 bool parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &);
Petr Hosek85b2f672016-09-23 21:53:36 +0000503 // ".ds"
504 bool parseDirectiveDS(StringRef IDVal, unsigned Size);
Petr Hosek4cb08ce2016-09-23 19:25:15 +0000505
Eli Bendersky17233942013-01-15 22:59:42 +0000506 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
Jim Grosbach4b905842013-09-20 23:08:21 +0000507 bool parseDirectiveLEB128(bool Signed);
Eli Bendersky17233942013-01-15 22:59:42 +0000508
Jim Grosbach4b905842013-09-20 23:08:21 +0000509 /// \brief Parse a directive like ".globl" which
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000510 /// accepts a single symbol (which should be a label or an external).
Jim Grosbach4b905842013-09-20 23:08:21 +0000511 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000512
Jim Grosbach4b905842013-09-20 23:08:21 +0000513 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000514
Jim Grosbach4b905842013-09-20 23:08:21 +0000515 bool parseDirectiveAbort(); // ".abort"
516 bool parseDirectiveInclude(); // ".include"
517 bool parseDirectiveIncbin(); // ".incbin"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000518
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +0000519 // ".if", ".ifeq", ".ifge", ".ifgt" , ".ifle", ".iflt" or ".ifne"
520 bool parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind);
Benjamin Kramer62c18b02012-05-12 11:18:42 +0000521 // ".ifb" or ".ifnb", depending on ExpectBlank.
Jim Grosbach4b905842013-09-20 23:08:21 +0000522 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000523 // ".ifc" or ".ifnc", depending on ExpectEqual.
Jim Grosbach4b905842013-09-20 23:08:21 +0000524 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
Sid Manning51c35602015-03-18 14:20:54 +0000525 // ".ifeqs" or ".ifnes", depending on ExpectEqual.
526 bool parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +0000527 // ".ifdef" or ".ifndef", depending on expect_defined
Jim Grosbach4b905842013-09-20 23:08:21 +0000528 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
529 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
530 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
531 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
Craig Topper59be68f2014-03-08 07:14:16 +0000532 bool parseEscapedString(std::string &Data) override;
Daniel Dunbar55f16672010-09-17 02:47:07 +0000533
Jim Grosbach4b905842013-09-20 23:08:21 +0000534 const MCExpr *applyModifierToExpr(const MCExpr *E,
Daniel Dunbar55f16672010-09-17 02:47:07 +0000535 MCSymbolRefExpr::VariantKind Variant);
Rafael Espindola47b7dac2012-05-12 16:31:10 +0000536
Rafael Espindola34b9c512012-06-03 23:57:14 +0000537 // Macro-like directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000538 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
539 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +0000540 raw_svector_ostream &OS);
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +0000541 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
Jim Grosbach4b905842013-09-20 23:08:21 +0000542 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
543 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
544 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
Chad Rosier8bce6642012-10-18 15:49:34 +0000545
Chad Rosierc7f552c2013-02-12 21:33:51 +0000546 // "_emit" or "__emit"
Jim Grosbach4b905842013-09-20 23:08:21 +0000547 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
Chad Rosierc7f552c2013-02-12 21:33:51 +0000548 size_t Len);
549
550 // "align"
Jim Grosbach4b905842013-09-20 23:08:21 +0000551 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000552
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000553 // "end"
554 bool parseDirectiveEnd(SMLoc DirectiveLoc);
555
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +0000556 // ".err" or ".error"
557 bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +0000558
Nico Weber404012b2014-07-24 16:26:06 +0000559 // ".warning"
560 bool parseDirectiveWarning(SMLoc DirectiveLoc);
561
Eli Bendersky17233942013-01-15 22:59:42 +0000562 void initializeDirectiveKindMap();
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000563};
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000564
565} // end anonymous namespace
Daniel Dunbar86033402010-07-12 17:54:38 +0000566
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000567namespace llvm {
568
569extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbarab058b82010-07-12 21:23:32 +0000570extern MCAsmParserExtension *createELFAsmParser();
Michael J. Spencerc8dbdfd2010-10-09 11:01:07 +0000571extern MCAsmParserExtension *createCOFFAsmParser();
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000572
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000573} // end namespace llvm
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000574
Chris Lattnerc35681b2010-01-19 19:46:13 +0000575enum { DEFAULT_ADDRSPACE = 0 };
576
David Blaikie9f380a32015-03-16 18:06:57 +0000577AsmParser::AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Sanne Wouda29338752017-02-08 14:48:05 +0000578 const MCAsmInfo &MAI, unsigned CB = 0)
David Blaikie9f380a32015-03-16 18:06:57 +0000579 : Lexer(MAI), Ctx(Ctx), Out(Out), MAI(MAI), SrcMgr(SM),
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000580 CurBuffer(CB ? CB : SM.getMainFileID()), MacrosEnabledFlag(true) {
Nirav Dave2364748a2016-09-16 18:30:20 +0000581 HadError = false;
Benjamin Kramer47f5e302011-10-16 10:48:29 +0000582 // Save the old handler.
583 SavedDiagHandler = SrcMgr.getDiagHandler();
584 SavedDiagContext = SrcMgr.getDiagContext();
585 // Set our own handler which calls the saved handler.
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000586 SrcMgr.setDiagHandler(DiagHandler, this);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000587 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar86033402010-07-12 17:54:38 +0000588
Daniel Dunbarc5011082010-07-12 18:12:02 +0000589 // Initialize the platform / file format parser.
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000590 switch (Ctx.getObjectFileInfo()->getObjectFileType()) {
591 case MCObjectFileInfo::IsCOFF:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000592 PlatformParser.reset(createCOFFAsmParser());
593 break;
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000594 case MCObjectFileInfo::IsMachO:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000595 PlatformParser.reset(createDarwinAsmParser());
596 IsDarwin = true;
597 break;
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000598 case MCObjectFileInfo::IsELF:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000599 PlatformParser.reset(createELFAsmParser());
600 break;
Dan Gohman18eafb62017-02-22 01:23:18 +0000601 case MCObjectFileInfo::IsWasm:
602 llvm_unreachable("Wasm parsing not supported yet");
603 break;
Daniel Dunbarc5011082010-07-12 18:12:02 +0000604 }
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000605
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000606 PlatformParser->Initialize(*this);
Eli Bendersky17233942013-01-15 22:59:42 +0000607 initializeDirectiveKindMap();
Toma Tabacu217116e2015-04-27 10:50:29 +0000608
609 NumOfMacroInstantiations = 0;
Chris Lattner351a7ef2009-09-27 21:16:52 +0000610}
611
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000612AsmParser::~AsmParser() {
Saleem Abdulrasool6eae1e62014-05-21 17:53:18 +0000613 assert((HadError || ActiveMacros.empty()) &&
614 "Unexpected active macro instantiation!");
Sanne Wouda29338752017-02-08 14:48:05 +0000615
616 // Restore the saved diagnostics handler and context for use during
617 // finalization.
618 SrcMgr.setDiagHandler(SavedDiagHandler, SavedDiagContext);
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000619}
620
Jim Grosbach4b905842013-09-20 23:08:21 +0000621void AsmParser::printMacroInstantiations() {
Daniel Dunbar43235712010-07-18 18:54:11 +0000622 // Print the active macro instantiation stack.
Jim Grosbach4b905842013-09-20 23:08:21 +0000623 for (std::vector<MacroInstantiation *>::const_reverse_iterator
624 it = ActiveMacros.rbegin(),
625 ie = ActiveMacros.rend();
626 it != ie; ++it)
627 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
Chris Lattner03b80a42011-10-16 05:43:57 +0000628 "while in macro instantiation");
Daniel Dunbar43235712010-07-18 18:54:11 +0000629}
630
Nirav Dave2364748a2016-09-16 18:30:20 +0000631void AsmParser::Note(SMLoc L, const Twine &Msg, SMRange Range) {
632 printPendingErrors();
633 printMessage(L, SourceMgr::DK_Note, Msg, Range);
Saleem Abdulrasool69c7caf2014-01-07 02:28:31 +0000634 printMacroInstantiations();
635}
636
Nirav Dave2364748a2016-09-16 18:30:20 +0000637bool AsmParser::Warning(SMLoc L, const Twine &Msg, SMRange Range) {
Colin LeMahieufe36f832015-07-27 22:39:14 +0000638 if(getTargetParser().getTargetOptions().MCNoWarn)
639 return false;
Joerg Sonnenberger29815912014-08-26 18:39:50 +0000640 if (getTargetParser().getTargetOptions().MCFatalWarnings)
Nirav Dave2364748a2016-09-16 18:30:20 +0000641 return Error(L, Msg, Range);
642 printMessage(L, SourceMgr::DK_Warning, Msg, Range);
Jim Grosbach4b905842013-09-20 23:08:21 +0000643 printMacroInstantiations();
Joerg Sonnenberger74ba2622011-05-19 18:00:13 +0000644 return false;
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +0000645}
646
Nirav Dave2364748a2016-09-16 18:30:20 +0000647bool AsmParser::printError(SMLoc L, const Twine &Msg, SMRange Range) {
Daniel Dunbar43325c42010-09-09 22:42:56 +0000648 HadError = true;
Nirav Dave2364748a2016-09-16 18:30:20 +0000649 printMessage(L, SourceMgr::DK_Error, Msg, Range);
Jim Grosbach4b905842013-09-20 23:08:21 +0000650 printMacroInstantiations();
Chris Lattner2adc9e72009-06-21 21:22:11 +0000651 return true;
652}
653
Jim Grosbach4b905842013-09-20 23:08:21 +0000654bool AsmParser::enterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergeraf5f23e2011-06-01 13:10:15 +0000655 std::string IncludedFile;
Alp Tokera55b95b2014-07-06 10:33:31 +0000656 unsigned NewBuf =
657 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
658 if (!NewBuf)
Sean Callanan7a77eae2010-01-21 00:19:58 +0000659 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +0000660
Sean Callanan7a77eae2010-01-21 00:19:58 +0000661 CurBuffer = NewBuf;
Rafael Espindola8026bd02014-07-06 14:17:29 +0000662 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Sean Callanan7a77eae2010-01-21 00:19:58 +0000663 return false;
664}
Daniel Dunbar43235712010-07-18 18:54:11 +0000665
Sylvestre Ledru149e2812013-05-14 23:36:24 +0000666/// Process the specified .incbin file by searching for it in the include paths
Benjamin Kramerbde91762012-06-02 10:20:22 +0000667/// then just emitting the byte contents of the file to the streamer. This
Kevin Enderby109f25c2011-12-14 21:47:48 +0000668/// returns true on failure.
Petr Hosek2f4ac442016-09-23 00:41:06 +0000669bool AsmParser::processIncbinFile(const std::string &Filename, int64_t Skip,
670 const MCExpr *Count, SMLoc Loc) {
Kevin Enderby109f25c2011-12-14 21:47:48 +0000671 std::string IncludedFile;
Alp Tokera55b95b2014-07-06 10:33:31 +0000672 unsigned NewBuf =
673 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
674 if (!NewBuf)
Kevin Enderby109f25c2011-12-14 21:47:48 +0000675 return true;
676
Kevin Enderbyad41ab52011-12-14 22:34:45 +0000677 // Pick up the bytes from the file and emit them.
Petr Hosek2f4ac442016-09-23 00:41:06 +0000678 StringRef Bytes = SrcMgr.getMemoryBuffer(NewBuf)->getBuffer();
679 Bytes = Bytes.drop_front(Skip);
680 if (Count) {
681 int64_t Res;
682 if (!Count->evaluateAsAbsolute(Res))
683 return Error(Loc, "expected absolute expression");
684 if (Res < 0)
685 return Warning(Loc, "negative count has no effect");
686 Bytes = Bytes.take_front(Res);
687 }
688 getStreamer().EmitBytes(Bytes);
Kevin Enderby109f25c2011-12-14 21:47:48 +0000689 return false;
690}
691
Alp Tokera55b95b2014-07-06 10:33:31 +0000692void AsmParser::jumpToLoc(SMLoc Loc, unsigned InBuffer) {
693 CurBuffer = InBuffer ? InBuffer : SrcMgr.FindBufferContainingLoc(Loc);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000694 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(),
695 Loc.getPointer());
Daniel Dunbar43235712010-07-18 18:54:11 +0000696}
697
Sean Callanan7a77eae2010-01-21 00:19:58 +0000698const AsmToken &AsmParser::Lex() {
Nirav Dave1180e6892016-06-02 17:15:05 +0000699 if (Lexer.getTok().is(AsmToken::Error))
700 Error(Lexer.getErrLoc(), Lexer.getErr());
701
Nirav Dave53a72f42016-07-11 12:42:14 +0000702 // if it's a end of statement with a comment in it
703 if (getTok().is(AsmToken::EndOfStatement)) {
704 // if this is a line comment output it.
705 if (getTok().getString().front() != '\n' &&
706 getTok().getString().front() != '\r' && MAI.preserveAsmComments())
707 Out.addExplicitComment(Twine(getTok().getString()));
708 }
709
Sean Callanan7a77eae2010-01-21 00:19:58 +0000710 const AsmToken *tok = &Lexer.Lex();
Nirav Dave53a72f42016-07-11 12:42:14 +0000711
712 // Parse comments here to be deferred until end of next statement.
Nirav Davefd910412016-06-17 16:06:17 +0000713 while (tok->is(AsmToken::Comment)) {
Nirav Dave53a72f42016-07-11 12:42:14 +0000714 if (MAI.preserveAsmComments())
715 Out.addExplicitComment(Twine(tok->getString()));
Nirav Davefd910412016-06-17 16:06:17 +0000716 tok = &Lexer.Lex();
717 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000718
Sean Callanan7a77eae2010-01-21 00:19:58 +0000719 if (tok->is(AsmToken::Eof)) {
720 // If this is the end of an included file, pop the parent file off the
721 // include stack.
722 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
723 if (ParentIncludeLoc != SMLoc()) {
Jim Grosbach4b905842013-09-20 23:08:21 +0000724 jumpToLoc(ParentIncludeLoc);
Nirav Davefd910412016-06-17 16:06:17 +0000725 return Lex();
Sean Callanan7a77eae2010-01-21 00:19:58 +0000726 }
727 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000728
Sean Callanan7a77eae2010-01-21 00:19:58 +0000729 return *tok;
Sean Callanan686ed8d2010-01-19 20:22:31 +0000730}
731
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000732bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar322fec62010-03-13 02:20:57 +0000733 // Create the initial section, if requested.
Daniel Dunbar322fec62010-03-13 02:20:57 +0000734 if (!NoInitialTextSection)
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000735 Out.InitSections(false);
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000736
Chris Lattner36e02122009-06-21 20:54:55 +0000737 // Prime the lexer.
Sean Callanan686ed8d2010-01-19 20:22:31 +0000738 Lex();
Daniel Dunbar43325c42010-09-09 22:42:56 +0000739
740 HadError = false;
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000741 AsmCond StartingCondState = TheCondState;
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +0000742 SmallVector<AsmRewrite, 4> AsmStrRewrites;
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000743
Kevin Enderby6469fc22011-11-01 22:27:22 +0000744 // If we are generating dwarf for assembly source files save the initial text
745 // section and generate a .file directive.
746 if (getContext().getGenDwarfForAssembly()) {
Eric Christopher445c9522016-10-14 05:47:37 +0000747 MCSection *Sec = getStreamer().getCurrentSectionOnly();
Rafael Espindola2f9bdd82015-05-27 20:52:32 +0000748 if (!Sec->getBeginSymbol()) {
749 MCSymbol *SectionStartSym = getContext().createTempSymbol();
750 getStreamer().EmitLabel(SectionStartSym);
751 Sec->setBeginSymbol(SectionStartSym);
752 }
Rafael Espindolae0746792015-05-21 16:52:32 +0000753 bool InsertResult = getContext().addGenDwarfSection(Sec);
754 assert(InsertResult && ".text section should not have debug info yet");
Rafael Espindolafa160c72015-05-21 17:09:22 +0000755 (void)InsertResult;
David Blaikiec714ef42014-03-17 01:52:11 +0000756 getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective(
757 0, StringRef(), getContext().getMainFileName()));
Kevin Enderby6469fc22011-11-01 22:27:22 +0000758 }
759
Chris Lattner73f36112009-07-02 21:53:43 +0000760 // While we have input, parse each statement.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000761 while (Lexer.isNot(AsmToken::Eof)) {
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +0000762 ParseStatementInfo Info(&AsmStrRewrites);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +0000763 if (!parseStatement(Info, nullptr))
Jim Grosbach4b905842013-09-20 23:08:21 +0000764 continue;
Michael J. Spencer530ce852010-10-09 11:00:50 +0000765
Nirav Dave2364748a2016-09-16 18:30:20 +0000766 // If we have a Lexer Error we are on an Error Token. Load in Lexer Error
767 // for printing ErrMsg via Lex() only if no (presumably better) parser error
768 // exists.
769 if (!hasPendingError() && Lexer.getTok().is(AsmToken::Error)) {
Nirav Dave1180e6892016-06-02 17:15:05 +0000770 Lex();
771 }
772
Nirav Dave2364748a2016-09-16 18:30:20 +0000773 // parseStatement returned true so may need to emit an error.
774 printPendingErrors();
775
776 // Skipping to the next line if needed.
777 if (!getLexer().isAtStartOfStatement())
778 eatToEndOfStatement();
Chris Lattner73f36112009-07-02 21:53:43 +0000779 }
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000780
Nirav Dave2364748a2016-09-16 18:30:20 +0000781 // All errors should have been emitted.
782 assert(!hasPendingError() && "unexpected error from parseStatement");
783
Oliver Stannard21718282016-07-26 14:19:47 +0000784 getTargetParser().flushPendingInstructions(getStreamer());
785
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000786 if (TheCondState.TheCond != StartingCondState.TheCond ||
787 TheCondState.Ignore != StartingCondState.Ignore)
Nirav Dave2364748a2016-09-16 18:30:20 +0000788 printError(getTok().getLoc(), "unmatched .ifs or .elses");
Kevin Enderbye5930f12010-07-28 20:55:35 +0000789 // Check to see there are no empty DwarfFile slots.
David Blaikie8bf66c42014-04-01 07:35:52 +0000790 const auto &LineTables = getContext().getMCDwarfLineTables();
791 if (!LineTables.empty()) {
792 unsigned Index = 0;
793 for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) {
794 if (File.Name.empty() && Index != 0)
Nirav Dave2364748a2016-09-16 18:30:20 +0000795 printError(getTok().getLoc(), "unassigned file number: " +
796 Twine(Index) +
797 " for .file directives");
David Blaikie8bf66c42014-04-01 07:35:52 +0000798 ++Index;
799 }
Kevin Enderbye5930f12010-07-28 20:55:35 +0000800 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000801
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000802 // Check to see that all assembler local symbols were actually defined.
803 // Targets that don't do subsections via symbols may not want this, though,
804 // so conservatively exclude them. Only do this if we're finalizing, though,
805 // as otherwise we won't necessarilly have seen everything yet.
Tim Northover6b3169b2016-04-11 19:50:46 +0000806 if (!NoFinalize) {
807 if (MAI.hasSubsectionsViaSymbols()) {
808 for (const auto &TableEntry : getContext().getSymbols()) {
809 MCSymbol *Sym = TableEntry.getValue();
810 // Variable symbols may not be marked as defined, so check those
811 // explicitly. If we know it's a variable, we have a definition for
812 // the purposes of this check.
813 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
814 // FIXME: We would really like to refer back to where the symbol was
815 // first referenced for a source location. We need to add something
816 // to track that. Currently, we just point to the end of the file.
Nirav Dave2364748a2016-09-16 18:30:20 +0000817 printError(getTok().getLoc(), "assembler local symbol '" +
818 Sym->getName() + "' not defined");
Tim Northover6b3169b2016-04-11 19:50:46 +0000819 }
820 }
821
822 // Temporary symbols like the ones for directional jumps don't go in the
823 // symbol table. They also need to be diagnosed in all (final) cases.
Tim Northoverc0bef992016-04-13 19:46:54 +0000824 for (std::tuple<SMLoc, CppHashInfoTy, MCSymbol *> &LocSym : DirLabels) {
825 if (std::get<2>(LocSym)->isUndefined()) {
826 // Reset the state of any "# line file" directives we've seen to the
827 // context as it was at the diagnostic site.
828 CppHashInfo = std::get<1>(LocSym);
Nirav Dave2364748a2016-09-16 18:30:20 +0000829 printError(std::get<0>(LocSym), "directional label undefined");
Tim Northoverc0bef992016-04-13 19:46:54 +0000830 }
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000831 }
832 }
833
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000834 // Finalize the output stream if there are no errors and if the client wants
835 // us to.
Jack Carter13d5f752013-10-04 22:52:31 +0000836 if (!HadError && !NoFinalize)
Daniel Dunbar9df5f332009-08-21 08:34:18 +0000837 Out.Finish();
838
Oliver Stannard07b43d32015-11-17 09:58:07 +0000839 return HadError || getContext().hadError();
Chris Lattner36e02122009-06-21 20:54:55 +0000840}
841
Nirav Davef43cc9f2016-10-10 15:24:54 +0000842bool AsmParser::checkForValidSection() {
Eric Christopher445c9522016-10-14 05:47:37 +0000843 if (!ParsingInlineAsm && !getStreamer().getCurrentSectionOnly()) {
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000844 Out.InitSections(false);
Nirav Davef43cc9f2016-10-10 15:24:54 +0000845 return Error(getTok().getLoc(),
846 "expected section directive before assembly directive");
Daniel Dunbare5444a82010-09-09 22:42:59 +0000847 }
Nirav Davef43cc9f2016-10-10 15:24:54 +0000848 return false;
Daniel Dunbare5444a82010-09-09 22:42:59 +0000849}
850
Jim Grosbach4b905842013-09-20 23:08:21 +0000851/// \brief Throw away the rest of the line for testing purposes.
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000852void AsmParser::eatToEndOfStatement() {
Jim Grosbach4b905842013-09-20 23:08:21 +0000853 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Nirav Dave1180e6892016-06-02 17:15:05 +0000854 Lexer.Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +0000855
Chris Lattnere5074c42009-06-22 01:29:09 +0000856 // Eat EOL.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000857 if (Lexer.is(AsmToken::EndOfStatement))
Nirav Dave1180e6892016-06-02 17:15:05 +0000858 Lexer.Lex();
Chris Lattnere5074c42009-06-22 01:29:09 +0000859}
860
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000861StringRef AsmParser::parseStringToEndOfStatement() {
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000862 const char *Start = getTok().getLoc().getPointer();
863
Jim Grosbach4b905842013-09-20 23:08:21 +0000864 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Nirav Davefd910412016-06-17 16:06:17 +0000865 Lexer.Lex();
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000866
867 const char *End = getTok().getLoc().getPointer();
868 return StringRef(Start, End - Start);
869}
Chris Lattner78db3622009-06-22 05:51:26 +0000870
Jim Grosbach4b905842013-09-20 23:08:21 +0000871StringRef AsmParser::parseStringToComma() {
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000872 const char *Start = getTok().getLoc().getPointer();
873
874 while (Lexer.isNot(AsmToken::EndOfStatement) &&
Jim Grosbach4b905842013-09-20 23:08:21 +0000875 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
Nirav Davefd910412016-06-17 16:06:17 +0000876 Lexer.Lex();
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000877
878 const char *End = getTok().getLoc().getPointer();
879 return StringRef(Start, End - Start);
880}
881
Jim Grosbach4b905842013-09-20 23:08:21 +0000882/// \brief Parse a paren expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +0000883/// NOTE: This assumes the leading '(' has already been consumed.
884///
885/// parenexpr ::= expr)
886///
Jim Grosbach4b905842013-09-20 23:08:21 +0000887bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
888 if (parseExpression(Res))
889 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000890 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner7fdbce72009-06-22 06:32:03 +0000891 return TokError("expected ')' in parentheses expression");
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000892 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +0000893 Lex();
Chris Lattner7fdbce72009-06-22 06:32:03 +0000894 return false;
895}
Chris Lattner78db3622009-06-22 05:51:26 +0000896
Jim Grosbach4b905842013-09-20 23:08:21 +0000897/// \brief Parse a bracket expression and return it.
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +0000898/// NOTE: This assumes the leading '[' has already been consumed.
899///
900/// bracketexpr ::= expr]
901///
Jim Grosbach4b905842013-09-20 23:08:21 +0000902bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
903 if (parseExpression(Res))
904 return true;
Nirav Davea645433c2016-07-18 15:24:03 +0000905 EndLoc = getTok().getEndLoc();
906 if (parseToken(AsmToken::RBrac, "expected ']' in brackets expression"))
907 return true;
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +0000908 return false;
909}
910
Jim Grosbach4b905842013-09-20 23:08:21 +0000911/// \brief Parse a primary expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +0000912/// primaryexpr ::= (parenexpr
913/// primaryexpr ::= symbol
914/// primaryexpr ::= number
Chris Lattner6b55cb92010-04-14 04:40:28 +0000915/// primaryexpr ::= '.'
Chris Lattner7fdbce72009-06-22 06:32:03 +0000916/// primaryexpr ::= ~,+,- primaryexpr
Jim Grosbach4b905842013-09-20 23:08:21 +0000917bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Kevin Enderby0017d8a2013-01-22 21:09:20 +0000918 SMLoc FirstTokenLoc = getLexer().getLoc();
919 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
920 switch (FirstTokenKind) {
Chris Lattner78db3622009-06-22 05:51:26 +0000921 default:
922 return TokError("unknown token in expression");
Eric Christopher104af062011-04-12 00:03:13 +0000923 // If we have an error assume that we've already handled it.
924 case AsmToken::Error:
925 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000926 case AsmToken::Exclaim:
Sean Callanan686ed8d2010-01-19 20:22:31 +0000927 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +0000928 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000929 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +0000930 Res = MCUnaryExpr::createLNot(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000931 return false;
Daniel Dunbar24764322010-08-24 19:13:42 +0000932 case AsmToken::Dollar:
Hans Wennborgce69d772013-10-18 20:46:28 +0000933 case AsmToken::At:
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +0000934 case AsmToken::String:
Daniel Dunbard20cda02009-10-16 01:34:54 +0000935 case AsmToken::Identifier: {
Daniel Dunbar24764322010-08-24 19:13:42 +0000936 StringRef Identifier;
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000937 if (parseIdentifier(Identifier)) {
Nirav Daved0463322016-10-12 13:58:07 +0000938 // We may have failed but $ may be a valid token.
939 if (getTok().is(AsmToken::Dollar)) {
David Majnemer0c58bc62013-09-25 10:47:21 +0000940 if (Lexer.getMAI().getDollarIsPC()) {
Nirav Daved0463322016-10-12 13:58:07 +0000941 Lex();
David Majnemer0c58bc62013-09-25 10:47:21 +0000942 // This is a '$' reference, which references the current PC. Emit a
943 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +0000944 MCSymbol *Sym = Ctx.createTempSymbol();
David Majnemer0c58bc62013-09-25 10:47:21 +0000945 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +0000946 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None,
Jack Carter721726a2013-10-04 21:26:15 +0000947 getContext());
David Majnemer0c58bc62013-09-25 10:47:21 +0000948 EndLoc = FirstTokenLoc;
949 return false;
Ted Kremenek297febe2014-03-06 22:13:17 +0000950 }
951 return Error(FirstTokenLoc, "invalid token in expression");
David Majnemer0c58bc62013-09-25 10:47:21 +0000952 }
Kevin Enderby0017d8a2013-01-22 21:09:20 +0000953 }
David Peixotto8ad70b32013-12-04 22:43:20 +0000954 // Parse symbol variant
955 std::pair<StringRef, StringRef> Split;
956 if (!MAI.useParensForSymbolVariant()) {
David Majnemer6a5b8122014-06-19 01:25:43 +0000957 if (FirstTokenKind == AsmToken::String) {
958 if (Lexer.is(AsmToken::At)) {
Nirav Davefd910412016-06-17 16:06:17 +0000959 Lex(); // eat @
David Majnemer6a5b8122014-06-19 01:25:43 +0000960 SMLoc AtLoc = getLexer().getLoc();
961 StringRef VName;
962 if (parseIdentifier(VName))
963 return Error(AtLoc, "expected symbol variant after '@'");
964
965 Split = std::make_pair(Identifier, VName);
966 }
967 } else {
968 Split = Identifier.split('@');
969 }
David Peixotto8ad70b32013-12-04 22:43:20 +0000970 } else if (Lexer.is(AsmToken::LParen)) {
Nirav Davefd910412016-06-17 16:06:17 +0000971 Lex(); // eat '('.
David Peixotto8ad70b32013-12-04 22:43:20 +0000972 StringRef VName;
973 parseIdentifier(VName);
Nirav Davea645433c2016-07-18 15:24:03 +0000974 // eat ')'.
975 if (parseToken(AsmToken::RParen,
976 "unexpected token in variant, expected ')'"))
977 return true;
David Peixotto8ad70b32013-12-04 22:43:20 +0000978 Split = std::make_pair(Identifier, VName);
979 }
Daniel Dunbar24764322010-08-24 19:13:42 +0000980
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000981 EndLoc = SMLoc::getFromPointer(Identifier.end());
982
Daniel Dunbard20cda02009-10-16 01:34:54 +0000983 // This is a symbol reference.
Hans Wennborgce69d772013-10-18 20:46:28 +0000984 StringRef SymbolName = Identifier;
Weiming Zhaocf26d562016-12-01 18:00:36 +0000985 if (SymbolName.empty())
986 return true;
987
Hans Wennborgce69d772013-10-18 20:46:28 +0000988 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Hans Wennborg69918bc2013-10-17 01:13:02 +0000989
Hans Wennborg7ddcdc82013-10-18 02:14:40 +0000990 // Lookup the symbol variant if used.
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000991 if (!Split.second.empty()) {
Hans Wennborg7ddcdc82013-10-18 02:14:40 +0000992 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Hans Wennborgce69d772013-10-18 20:46:28 +0000993 if (Variant != MCSymbolRefExpr::VK_Invalid) {
994 SymbolName = Split.first;
David Peixotto8ad70b32013-12-04 22:43:20 +0000995 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
Hans Wennborgce69d772013-10-18 20:46:28 +0000996 Variant = MCSymbolRefExpr::VK_None;
997 } else {
Saleem Abdulrasoola25e1e42014-01-26 22:29:43 +0000998 return Error(SMLoc::getFromPointer(Split.second.begin()),
999 "invalid variant '" + Split.second + "'");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001000 }
1001 }
Daniel Dunbar55992562010-03-15 23:51:06 +00001002
Jim Grosbach6f482002015-05-18 18:43:14 +00001003 MCSymbol *Sym = getContext().getOrCreateSymbol(SymbolName);
Hans Wennborgce69d772013-10-18 20:46:28 +00001004
Daniel Dunbard20cda02009-10-16 01:34:54 +00001005 // If this is an absolute variable reference, substitute it now to preserve
1006 // semantics in the face of reassignment.
Vedant Kumar86dbd922015-08-31 17:44:53 +00001007 if (Sym->isVariable() &&
1008 isa<MCConstantExpr>(Sym->getVariableValue(/*SetUsed*/ false))) {
Daniel Dunbar55992562010-03-15 23:51:06 +00001009 if (Variant)
Daniel Dunbar8a3c3f22010-11-08 17:53:02 +00001010 return Error(EndLoc, "unexpected modifier on variable reference");
Daniel Dunbar55992562010-03-15 23:51:06 +00001011
Vedant Kumar86dbd922015-08-31 17:44:53 +00001012 Res = Sym->getVariableValue(/*SetUsed*/ false);
Daniel Dunbard20cda02009-10-16 01:34:54 +00001013 return false;
1014 }
1015
1016 // Otherwise create a symbol ref.
Chad Rosier9245e122017-01-19 20:06:32 +00001017 Res = MCSymbolRefExpr::create(Sym, Variant, getContext(), FirstTokenLoc);
Chris Lattner78db3622009-06-22 05:51:26 +00001018 return false;
Daniel Dunbard20cda02009-10-16 01:34:54 +00001019 }
David Woodhousef42a6662014-02-01 16:20:54 +00001020 case AsmToken::BigNum:
1021 return TokError("literal value out of range for directive");
Kevin Enderby0510b482010-05-17 23:08:19 +00001022 case AsmToken::Integer: {
1023 SMLoc Loc = getTok().getLoc();
1024 int64_t IntVal = getTok().getIntVal();
Jim Grosbach13760bd2015-05-30 01:25:56 +00001025 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001026 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001027 Lex(); // Eat token.
Kevin Enderby0510b482010-05-17 23:08:19 +00001028 // Look for 'b' or 'f' following an Integer as a directional label
1029 if (Lexer.getKind() == AsmToken::Identifier) {
1030 StringRef IDVal = getTok().getString();
Ulrich Weigandd4120982013-06-20 16:24:17 +00001031 // Lookup the symbol variant if used.
1032 std::pair<StringRef, StringRef> Split = IDVal.split('@');
1033 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
1034 if (Split.first.size() != IDVal.size()) {
1035 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Arnaud A. de Grandmaisonc97727a2014-03-21 21:54:46 +00001036 if (Variant == MCSymbolRefExpr::VK_Invalid)
Ulrich Weigandd4120982013-06-20 16:24:17 +00001037 return TokError("invalid variant '" + Split.second + "'");
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001038 IDVal = Split.first;
Ulrich Weigandd4120982013-06-20 16:24:17 +00001039 }
Jim Grosbach4b905842013-09-20 23:08:21 +00001040 if (IDVal == "f" || IDVal == "b") {
1041 MCSymbol *Sym =
Jim Grosbach6f482002015-05-18 18:43:14 +00001042 Ctx.getDirectionalLocalSymbol(IntVal, IDVal == "b");
Jim Grosbach13760bd2015-05-30 01:25:56 +00001043 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00001044 if (IDVal == "b" && Sym->isUndefined())
Tim Northover6b3169b2016-04-11 19:50:46 +00001045 return Error(Loc, "directional label undefined");
Tim Northoverc0bef992016-04-13 19:46:54 +00001046 DirLabels.push_back(std::make_tuple(Loc, CppHashInfo, Sym));
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001047 EndLoc = Lexer.getTok().getEndLoc();
Kevin Enderby0510b482010-05-17 23:08:19 +00001048 Lex(); // Eat identifier.
1049 }
1050 }
Chris Lattner78db3622009-06-22 05:51:26 +00001051 return false;
Kevin Enderby0510b482010-05-17 23:08:19 +00001052 }
Bill Wendlingcdbf17b2011-01-25 21:26:41 +00001053 case AsmToken::Real: {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001054 APFloat RealVal(APFloat::IEEEdouble(), getTok().getString());
Bob Wilson813bdf62011-02-03 23:17:47 +00001055 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Jim Grosbach13760bd2015-05-30 01:25:56 +00001056 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001057 EndLoc = Lexer.getTok().getEndLoc();
Bill Wendlingcdbf17b2011-01-25 21:26:41 +00001058 Lex(); // Eat token.
1059 return false;
1060 }
Chris Lattner6b55cb92010-04-14 04:40:28 +00001061 case AsmToken::Dot: {
1062 // 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();
Chris Lattner6b55cb92010-04-14 04:40:28 +00001065 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +00001066 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001067 EndLoc = Lexer.getTok().getEndLoc();
Chris Lattner6b55cb92010-04-14 04:40:28 +00001068 Lex(); // Eat identifier.
1069 return false;
1070 }
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001071 case AsmToken::LParen:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001072 Lex(); // Eat the '('.
Jim Grosbach4b905842013-09-20 23:08:21 +00001073 return parseParenExpr(Res, EndLoc);
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +00001074 case AsmToken::LBrac:
1075 if (!PlatformParser->HasBracketExpressions())
1076 return TokError("brackets expression not supported on this target");
1077 Lex(); // Eat the '['.
Jim Grosbach4b905842013-09-20 23:08:21 +00001078 return parseBracketExpr(Res, EndLoc);
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001079 case AsmToken::Minus:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001080 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001081 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001082 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +00001083 Res = MCUnaryExpr::createMinus(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001084 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001085 case AsmToken::Plus:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001086 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001087 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001088 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +00001089 Res = MCUnaryExpr::createPlus(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001090 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001091 case AsmToken::Tilde:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001092 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001093 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001094 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +00001095 Res = MCUnaryExpr::createNot(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001096 return false;
Daniel Sanders3feeb9c2016-08-08 11:50:25 +00001097 // MIPS unary expression operators. The lexer won't generate these tokens if
1098 // MCAsmInfo::HasMipsExpressions is false for the target.
1099 case AsmToken::PercentCall16:
1100 case AsmToken::PercentCall_Hi:
1101 case AsmToken::PercentCall_Lo:
1102 case AsmToken::PercentDtprel_Hi:
1103 case AsmToken::PercentDtprel_Lo:
1104 case AsmToken::PercentGot:
1105 case AsmToken::PercentGot_Disp:
1106 case AsmToken::PercentGot_Hi:
1107 case AsmToken::PercentGot_Lo:
1108 case AsmToken::PercentGot_Ofst:
1109 case AsmToken::PercentGot_Page:
1110 case AsmToken::PercentGottprel:
1111 case AsmToken::PercentGp_Rel:
1112 case AsmToken::PercentHi:
1113 case AsmToken::PercentHigher:
1114 case AsmToken::PercentHighest:
1115 case AsmToken::PercentLo:
1116 case AsmToken::PercentNeg:
1117 case AsmToken::PercentPcrel_Hi:
1118 case AsmToken::PercentPcrel_Lo:
1119 case AsmToken::PercentTlsgd:
1120 case AsmToken::PercentTlsldm:
1121 case AsmToken::PercentTprel_Hi:
1122 case AsmToken::PercentTprel_Lo:
1123 Lex(); // Eat the operator.
1124 if (Lexer.isNot(AsmToken::LParen))
1125 return TokError("expected '(' after operator");
1126 Lex(); // Eat the operator.
1127 if (parseExpression(Res, EndLoc))
1128 return true;
1129 if (Lexer.isNot(AsmToken::RParen))
1130 return TokError("expected ')'");
1131 Lex(); // Eat the operator.
1132 Res = getTargetParser().createTargetUnaryExpr(Res, FirstTokenKind, Ctx);
1133 return !Res;
Chris Lattner78db3622009-06-22 05:51:26 +00001134 }
1135}
Chris Lattner7fdbce72009-06-22 06:32:03 +00001136
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001137bool AsmParser::parseExpression(const MCExpr *&Res) {
Chris Lattnere17df0b2010-01-15 19:39:23 +00001138 SMLoc EndLoc;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001139 return parseExpression(Res, EndLoc);
Chris Lattner528d00b2010-01-15 19:28:38 +00001140}
1141
Daniel Dunbar55f16672010-09-17 02:47:07 +00001142const MCExpr *
Jim Grosbach4b905842013-09-20 23:08:21 +00001143AsmParser::applyModifierToExpr(const MCExpr *E,
Daniel Dunbar55f16672010-09-17 02:47:07 +00001144 MCSymbolRefExpr::VariantKind Variant) {
Joerg Sonnenbergerb822af42013-08-27 20:23:19 +00001145 // Ask the target implementation about this expression first.
1146 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
1147 if (NewE)
1148 return NewE;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001149 // Recurse over the given expression, rebuilding it to apply the given variant
1150 // if there is exactly one symbol.
1151 switch (E->getKind()) {
1152 case MCExpr::Target:
1153 case MCExpr::Constant:
Craig Topper353eda42014-04-24 06:44:33 +00001154 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001155
1156 case MCExpr::SymbolRef: {
1157 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
1158
1159 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001160 TokError("invalid variant on expression '" + getTok().getIdentifier() +
1161 "' (already modified)");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001162 return E;
1163 }
1164
Jim Grosbach13760bd2015-05-30 01:25:56 +00001165 return MCSymbolRefExpr::create(&SRE->getSymbol(), Variant, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001166 }
1167
1168 case MCExpr::Unary: {
1169 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +00001170 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001171 if (!Sub)
Craig Topper353eda42014-04-24 06:44:33 +00001172 return nullptr;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001173 return MCUnaryExpr::create(UE->getOpcode(), Sub, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001174 }
1175
1176 case MCExpr::Binary: {
1177 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +00001178 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
1179 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001180
1181 if (!LHS && !RHS)
Craig Topper353eda42014-04-24 06:44:33 +00001182 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001183
Jim Grosbach4b905842013-09-20 23:08:21 +00001184 if (!LHS)
1185 LHS = BE->getLHS();
1186 if (!RHS)
1187 RHS = BE->getRHS();
Daniel Dunbar55f16672010-09-17 02:47:07 +00001188
Jim Grosbach13760bd2015-05-30 01:25:56 +00001189 return MCBinaryExpr::create(BE->getOpcode(), LHS, RHS, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001190 }
1191 }
Daniel Dunbarbaad46c2010-09-17 16:34:24 +00001192
Craig Toppera2886c22012-02-07 05:05:23 +00001193 llvm_unreachable("Invalid expression kind!");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001194}
1195
Michael Zuckerman763e60e2017-05-04 10:37:00 +00001196/// This function checks if the next token is <string> type or arithmetic.
1197/// string that begin with character '<' must end with character '>'.
1198/// otherwise it is arithmetics.
1199/// If the function returns a 'true' value,
1200/// the End argument will be filled with the last location pointed to the '>'
1201/// character.
1202
1203/// There is a gap between the AltMacro's documentation and the single quote implementation.
1204/// GCC does not fully support this feature and so we will not support it.
1205/// TODO: Adding single quote as a string.
1206bool AsmParser::isAltmacroString(SMLoc &StrLoc, SMLoc &EndLoc) {
1207 assert((StrLoc.getPointer() != NULL) &&
1208 "Argument to the function cannot be a NULL value");
1209 const char *CharPtr = StrLoc.getPointer();
1210 while ((*CharPtr != '>') && (*CharPtr != '\n') &&
1211 (*CharPtr != '\r') && (*CharPtr != '\0')){
1212 CharPtr++;
1213 }
1214 if (*CharPtr == '>') {
1215 EndLoc = StrLoc.getFromPointer(CharPtr + 1);
1216 return true;
1217 }
1218 return false;
1219}
1220
Jim Grosbach4b905842013-09-20 23:08:21 +00001221/// \brief Parse an expression and return it.
Michael J. Spencer530ce852010-10-09 11:00:50 +00001222///
Jim Grosbachbd164242011-08-20 16:24:13 +00001223/// expr ::= expr &&,|| expr -> lowest.
1224/// expr ::= expr |,^,&,! expr
1225/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1226/// expr ::= expr <<,>> expr
1227/// expr ::= expr +,- expr
1228/// expr ::= expr *,/,% expr -> highest.
Chris Lattner7fdbce72009-06-22 06:32:03 +00001229/// expr ::= primaryexpr
1230///
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001231bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001232 // Parse the expression.
Craig Topper353eda42014-04-24 06:44:33 +00001233 Res = nullptr;
Jim Grosbach4b905842013-09-20 23:08:21 +00001234 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001235 return true;
1236
Daniel Dunbar55f16672010-09-17 02:47:07 +00001237 // As a special case, we support 'a op b @ modifier' by rewriting the
1238 // expression to include the modifier. This is inefficient, but in general we
1239 // expect users to use 'a@modifier op b'.
1240 if (Lexer.getKind() == AsmToken::At) {
1241 Lex();
1242
1243 if (Lexer.isNot(AsmToken::Identifier))
1244 return TokError("unexpected symbol modifier following '@'");
1245
1246 MCSymbolRefExpr::VariantKind Variant =
Jim Grosbach4b905842013-09-20 23:08:21 +00001247 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001248 if (Variant == MCSymbolRefExpr::VK_Invalid)
1249 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1250
Jim Grosbach4b905842013-09-20 23:08:21 +00001251 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001252 if (!ModifiedRes) {
1253 return TokError("invalid modifier '" + getTok().getIdentifier() +
1254 "' (no symbols present)");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001255 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001256
Daniel Dunbar55f16672010-09-17 02:47:07 +00001257 Res = ModifiedRes;
1258 Lex();
1259 }
1260
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001261 // Try to constant fold it up front, if possible.
1262 int64_t Value;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001263 if (Res->evaluateAsAbsolute(Value))
1264 Res = MCConstantExpr::create(Value, getContext());
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001265
1266 return false;
Chris Lattner7fdbce72009-06-22 06:32:03 +00001267}
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001268
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001269bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Craig Topper353eda42014-04-24 06:44:33 +00001270 Res = nullptr;
Jim Grosbach4b905842013-09-20 23:08:21 +00001271 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
Daniel Dunbar7c82d562009-08-31 08:08:17 +00001272}
1273
Toma Tabacu7bc44dc2015-06-25 09:52:02 +00001274bool AsmParser::parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
1275 SMLoc &EndLoc) {
1276 if (parseParenExpr(Res, EndLoc))
1277 return true;
1278
1279 for (; ParenDepth > 0; --ParenDepth) {
1280 if (parseBinOpRHS(1, Res, EndLoc))
1281 return true;
1282
1283 // We don't Lex() the last RParen.
1284 // This is the same behavior as parseParenExpression().
1285 if (ParenDepth - 1 > 0) {
Nirav Davea645433c2016-07-18 15:24:03 +00001286 EndLoc = getTok().getEndLoc();
1287 if (parseToken(AsmToken::RParen,
1288 "expected ')' in parentheses expression"))
1289 return true;
Toma Tabacu7bc44dc2015-06-25 09:52:02 +00001290 }
1291 }
1292 return false;
1293}
1294
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001295bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
Daniel Dunbarf3636452009-08-31 08:07:22 +00001296 const MCExpr *Expr;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001297
Daniel Dunbar75630b32009-06-30 02:10:03 +00001298 SMLoc StartLoc = Lexer.getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001299 if (parseExpression(Expr))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001300 return true;
1301
Jim Grosbach13760bd2015-05-30 01:25:56 +00001302 if (!Expr->evaluateAsAbsolute(Res))
Daniel Dunbar75630b32009-06-30 02:10:03 +00001303 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001304
1305 return false;
1306}
1307
David Majnemer0993e0b2015-10-26 03:15:34 +00001308static unsigned getDarwinBinOpPrecedence(AsmToken::TokenKind K,
1309 MCBinaryExpr::Opcode &Kind,
1310 bool ShouldUseLogicalShr) {
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001311 switch (K) {
Daniel Dunbar940cda22009-08-31 08:07:44 +00001312 default:
Jim Grosbach4b905842013-09-20 23:08:21 +00001313 return 0; // not a binop.
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001314
Jim Grosbach4b905842013-09-20 23:08:21 +00001315 // Lowest Precedence: &&, ||
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001316 case AsmToken::AmpAmp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001317 Kind = MCBinaryExpr::LAnd;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001318 return 1;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001319 case AsmToken::PipePipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001320 Kind = MCBinaryExpr::LOr;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001321 return 1;
1322
Jim Grosbach4b905842013-09-20 23:08:21 +00001323 // Low Precedence: |, &, ^
1324 //
1325 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001326 case AsmToken::Pipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001327 Kind = MCBinaryExpr::Or;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001328 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001329 case AsmToken::Caret:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001330 Kind = MCBinaryExpr::Xor;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001331 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001332 case AsmToken::Amp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001333 Kind = MCBinaryExpr::And;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001334 return 2;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001335
Jim Grosbach4b905842013-09-20 23:08:21 +00001336 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001337 case AsmToken::EqualEqual:
1338 Kind = MCBinaryExpr::EQ;
1339 return 3;
1340 case AsmToken::ExclaimEqual:
1341 case AsmToken::LessGreater:
1342 Kind = MCBinaryExpr::NE;
1343 return 3;
1344 case AsmToken::Less:
1345 Kind = MCBinaryExpr::LT;
1346 return 3;
1347 case AsmToken::LessEqual:
1348 Kind = MCBinaryExpr::LTE;
1349 return 3;
1350 case AsmToken::Greater:
1351 Kind = MCBinaryExpr::GT;
1352 return 3;
1353 case AsmToken::GreaterEqual:
1354 Kind = MCBinaryExpr::GTE;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001355 return 3;
1356
Jim Grosbach4b905842013-09-20 23:08:21 +00001357 // Intermediate Precedence: <<, >>
Jim Grosbachbd164242011-08-20 16:24:13 +00001358 case AsmToken::LessLess:
1359 Kind = MCBinaryExpr::Shl;
1360 return 4;
1361 case AsmToken::GreaterGreater:
David Majnemer0993e0b2015-10-26 03:15:34 +00001362 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
Jim Grosbachbd164242011-08-20 16:24:13 +00001363 return 4;
1364
Jim Grosbach4b905842013-09-20 23:08:21 +00001365 // High Intermediate Precedence: +, -
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001366 case AsmToken::Plus:
1367 Kind = MCBinaryExpr::Add;
Jim Grosbachbd164242011-08-20 16:24:13 +00001368 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001369 case AsmToken::Minus:
1370 Kind = MCBinaryExpr::Sub;
Jim Grosbachbd164242011-08-20 16:24:13 +00001371 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001372
Jim Grosbach4b905842013-09-20 23:08:21 +00001373 // Highest Precedence: *, /, %
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001374 case AsmToken::Star:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001375 Kind = MCBinaryExpr::Mul;
Jim Grosbachbd164242011-08-20 16:24:13 +00001376 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001377 case AsmToken::Slash:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001378 Kind = MCBinaryExpr::Div;
Jim Grosbachbd164242011-08-20 16:24:13 +00001379 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001380 case AsmToken::Percent:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001381 Kind = MCBinaryExpr::Mod;
Jim Grosbachbd164242011-08-20 16:24:13 +00001382 return 6;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001383 }
1384}
1385
David Majnemer0993e0b2015-10-26 03:15:34 +00001386static unsigned getGNUBinOpPrecedence(AsmToken::TokenKind K,
1387 MCBinaryExpr::Opcode &Kind,
1388 bool ShouldUseLogicalShr) {
1389 switch (K) {
1390 default:
1391 return 0; // not a binop.
1392
1393 // Lowest Precedence: &&, ||
1394 case AsmToken::AmpAmp:
1395 Kind = MCBinaryExpr::LAnd;
1396 return 2;
1397 case AsmToken::PipePipe:
1398 Kind = MCBinaryExpr::LOr;
1399 return 1;
1400
1401 // Low Precedence: ==, !=, <>, <, <=, >, >=
1402 case AsmToken::EqualEqual:
1403 Kind = MCBinaryExpr::EQ;
1404 return 3;
1405 case AsmToken::ExclaimEqual:
1406 case AsmToken::LessGreater:
1407 Kind = MCBinaryExpr::NE;
1408 return 3;
1409 case AsmToken::Less:
1410 Kind = MCBinaryExpr::LT;
1411 return 3;
1412 case AsmToken::LessEqual:
1413 Kind = MCBinaryExpr::LTE;
1414 return 3;
1415 case AsmToken::Greater:
1416 Kind = MCBinaryExpr::GT;
1417 return 3;
1418 case AsmToken::GreaterEqual:
1419 Kind = MCBinaryExpr::GTE;
1420 return 3;
1421
1422 // Low Intermediate Precedence: +, -
1423 case AsmToken::Plus:
1424 Kind = MCBinaryExpr::Add;
1425 return 4;
1426 case AsmToken::Minus:
1427 Kind = MCBinaryExpr::Sub;
1428 return 4;
1429
1430 // High Intermediate Precedence: |, &, ^
1431 //
1432 // FIXME: gas seems to support '!' as an infix operator?
1433 case AsmToken::Pipe:
1434 Kind = MCBinaryExpr::Or;
1435 return 5;
1436 case AsmToken::Caret:
1437 Kind = MCBinaryExpr::Xor;
1438 return 5;
1439 case AsmToken::Amp:
1440 Kind = MCBinaryExpr::And;
1441 return 5;
1442
1443 // Highest Precedence: *, /, %, <<, >>
1444 case AsmToken::Star:
1445 Kind = MCBinaryExpr::Mul;
1446 return 6;
1447 case AsmToken::Slash:
1448 Kind = MCBinaryExpr::Div;
1449 return 6;
1450 case AsmToken::Percent:
1451 Kind = MCBinaryExpr::Mod;
1452 return 6;
1453 case AsmToken::LessLess:
1454 Kind = MCBinaryExpr::Shl;
1455 return 6;
1456 case AsmToken::GreaterGreater:
1457 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1458 return 6;
1459 }
1460}
1461
1462unsigned AsmParser::getBinOpPrecedence(AsmToken::TokenKind K,
1463 MCBinaryExpr::Opcode &Kind) {
1464 bool ShouldUseLogicalShr = MAI.shouldUseLogicalShr();
1465 return IsDarwin ? getDarwinBinOpPrecedence(K, Kind, ShouldUseLogicalShr)
1466 : getGNUBinOpPrecedence(K, Kind, ShouldUseLogicalShr);
1467}
1468
Jim Grosbach4b905842013-09-20 23:08:21 +00001469/// \brief Parse all binary operators with precedence >= 'Precedence'.
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001470/// Res contains the LHS of the expression on input.
Jim Grosbach4b905842013-09-20 23:08:21 +00001471bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
Chris Lattner528d00b2010-01-15 19:28:38 +00001472 SMLoc &EndLoc) {
Chad Rosier9245e122017-01-19 20:06:32 +00001473 SMLoc StartLoc = Lexer.getLoc();
Eugene Zelenko33d7b762016-08-23 17:14:32 +00001474 while (true) {
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001475 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001476 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001477
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001478 // If the next token is lower precedence than we are allowed to eat, return
1479 // successfully with what we ate already.
1480 if (TokPrec < Precedence)
1481 return false;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001482
Sean Callanan686ed8d2010-01-19 20:22:31 +00001483 Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +00001484
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001485 // Eat the next primary expression.
Daniel Dunbarf3636452009-08-31 08:07:22 +00001486 const MCExpr *RHS;
Jim Grosbach4b905842013-09-20 23:08:21 +00001487 if (parsePrimaryExpr(RHS, EndLoc))
1488 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001489
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001490 // If BinOp binds less tightly with RHS than the operator after RHS, let
1491 // the pending operator take RHS as its LHS.
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001492 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001493 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Jim Grosbach4b905842013-09-20 23:08:21 +00001494 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1495 return true;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001496
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001497 // Merge LHS and RHS according to operator.
Chad Rosier9245e122017-01-19 20:06:32 +00001498 Res = MCBinaryExpr::create(Kind, Res, RHS, getContext(), StartLoc);
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001499 }
1500}
1501
Chris Lattner36e02122009-06-21 20:54:55 +00001502/// ParseStatement:
1503/// ::= EndOfStatement
Chris Lattnere5074c42009-06-22 01:29:09 +00001504/// ::= Label* Directive ...Operands... EndOfStatement
1505/// ::= Label* Identifier OperandList* EndOfStatement
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001506bool AsmParser::parseStatement(ParseStatementInfo &Info,
1507 MCAsmParserSemaCallback *SI) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001508 assert(!hasPendingError() && "parseStatement started with pending error");
Nirav Davefd910412016-06-17 16:06:17 +00001509 // Eat initial spaces and comments
1510 while (Lexer.is(AsmToken::Space))
1511 Lex();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001512 if (Lexer.is(AsmToken::EndOfStatement)) {
Nirav Davefd910412016-06-17 16:06:17 +00001513 // if this is a line comment we can drop it safely
1514 if (getTok().getString().front() == '\r' ||
1515 getTok().getString().front() == '\n')
1516 Out.AddBlankLine();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001517 Lex();
Chris Lattner36e02122009-06-21 20:54:55 +00001518 return false;
Chris Lattner36e02122009-06-21 20:54:55 +00001519 }
Nirav Dave9263ae32016-08-02 19:17:54 +00001520 if (Lexer.is(AsmToken::Hash)) {
1521 // Seeing a hash here means that it was an end-of-line comment in
1522 // an asm syntax where hash's are not comment and the previous
1523 // statement parser did not check the end of statement. Relex as
1524 // EndOfStatement.
1525 StringRef CommentStr = parseStringToEndOfStatement();
1526 Lexer.Lex();
1527 Lexer.UnLex(AsmToken(AsmToken::EndOfStatement, CommentStr));
1528 return false;
1529 }
Nirav Davefd910412016-06-17 16:06:17 +00001530 // Statements always start with an identifier.
Sean Callanan936b0d32010-01-19 21:44:56 +00001531 AsmToken ID = getTok();
Daniel Dunbaree4465c2009-07-28 16:38:40 +00001532 SMLoc IDLoc = ID.getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001533 StringRef IDVal;
Kevin Enderby0510b482010-05-17 23:08:19 +00001534 int64_t LocalLabelVal = -1;
Nirav Davefd910412016-06-17 16:06:17 +00001535 if (Lexer.is(AsmToken::HashDirective))
Jim Grosbach4b905842013-09-20 23:08:21 +00001536 return parseCppHashLineFilenameComment(IDLoc);
Kevin Enderbyfa3c6f12010-12-24 00:12:02 +00001537 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderby0510b482010-05-17 23:08:19 +00001538 if (Lexer.is(AsmToken::Integer)) {
1539 LocalLabelVal = getTok().getIntVal();
1540 if (LocalLabelVal < 0) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001541 if (!TheCondState.Ignore) {
1542 Lex(); // always eat a token
1543 return Error(IDLoc, "unexpected token at start of statement");
1544 }
Kevin Enderby0510b482010-05-17 23:08:19 +00001545 IDVal = "";
Eli Bendersky88024712013-01-16 19:32:36 +00001546 } else {
Kevin Enderby0510b482010-05-17 23:08:19 +00001547 IDVal = getTok().getString();
1548 Lex(); // Consume the integer token to be used as an identifier token.
1549 if (Lexer.getKind() != AsmToken::Colon) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001550 if (!TheCondState.Ignore) {
1551 Lex(); // always eat a token
1552 return Error(IDLoc, "unexpected token at start of statement");
1553 }
Kevin Enderby0510b482010-05-17 23:08:19 +00001554 }
1555 }
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001556 } else if (Lexer.is(AsmToken::Dot)) {
1557 // Treat '.' as a valid identifier in this context.
1558 Lex();
1559 IDVal = ".";
Colin LeMahieu8a0453e2015-11-09 00:31:07 +00001560 } else if (Lexer.is(AsmToken::LCurly)) {
1561 // Treat '{' as a valid identifier in this context.
1562 Lex();
1563 IDVal = "{";
1564
1565 } else if (Lexer.is(AsmToken::RCurly)) {
1566 // Treat '}' as a valid identifier in this context.
1567 Lex();
1568 IDVal = "}";
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001569 } else if (parseIdentifier(IDVal)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001570 if (!TheCondState.Ignore) {
1571 Lex(); // always eat a token
1572 return Error(IDLoc, "unexpected token at start of statement");
1573 }
Chris Lattner926885c2010-04-17 18:14:27 +00001574 IDVal = "";
1575 }
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001576
Chris Lattner926885c2010-04-17 18:14:27 +00001577 // Handle conditional assembly here before checking for skipping. We
1578 // have to do this so that .endif isn't skipped in a ".if 0" block for
1579 // example.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001580 StringMap<DirectiveKind>::const_iterator DirKindIt =
Jim Grosbach4b905842013-09-20 23:08:21 +00001581 DirectiveKindMap.find(IDVal);
1582 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1583 ? DK_NO_DIRECTIVE
1584 : DirKindIt->getValue();
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001585 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001586 default:
1587 break;
1588 case DK_IF:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001589 case DK_IFEQ:
1590 case DK_IFGE:
1591 case DK_IFGT:
1592 case DK_IFLE:
1593 case DK_IFLT:
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00001594 case DK_IFNE:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001595 return parseDirectiveIf(IDLoc, DirKind);
Jim Grosbach4b905842013-09-20 23:08:21 +00001596 case DK_IFB:
1597 return parseDirectiveIfb(IDLoc, true);
1598 case DK_IFNB:
1599 return parseDirectiveIfb(IDLoc, false);
1600 case DK_IFC:
1601 return parseDirectiveIfc(IDLoc, true);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00001602 case DK_IFEQS:
Sid Manning51c35602015-03-18 14:20:54 +00001603 return parseDirectiveIfeqs(IDLoc, true);
Jim Grosbach4b905842013-09-20 23:08:21 +00001604 case DK_IFNC:
1605 return parseDirectiveIfc(IDLoc, false);
Sid Manning51c35602015-03-18 14:20:54 +00001606 case DK_IFNES:
1607 return parseDirectiveIfeqs(IDLoc, false);
Jim Grosbach4b905842013-09-20 23:08:21 +00001608 case DK_IFDEF:
1609 return parseDirectiveIfdef(IDLoc, true);
1610 case DK_IFNDEF:
1611 case DK_IFNOTDEF:
1612 return parseDirectiveIfdef(IDLoc, false);
1613 case DK_ELSEIF:
1614 return parseDirectiveElseIf(IDLoc);
1615 case DK_ELSE:
1616 return parseDirectiveElse(IDLoc);
1617 case DK_ENDIF:
1618 return parseDirectiveEndIf(IDLoc);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001619 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001620
Eli Bendersky88024712013-01-16 19:32:36 +00001621 // Ignore the statement if in the middle of inactive conditional
1622 // (e.g. ".if 0").
Chad Rosiereda70b32012-10-20 00:47:08 +00001623 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001624 eatToEndOfStatement();
Chris Lattner926885c2010-04-17 18:14:27 +00001625 return false;
1626 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001627
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001628 // FIXME: Recurse on local labels?
1629
1630 // See what kind of statement we have.
1631 switch (Lexer.getKind()) {
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001632 case AsmToken::Colon: {
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001633 if (!getTargetParser().isLabel(ID))
1634 break;
Nirav Davef43cc9f2016-10-10 15:24:54 +00001635 if (checkForValidSection())
1636 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00001637
Chris Lattner36e02122009-06-21 20:54:55 +00001638 // identifier ':' -> Label.
Sean Callanan686ed8d2010-01-19 20:22:31 +00001639 Lex();
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001640
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001641 // Diagnose attempt to use '.' as a label.
1642 if (IDVal == ".")
1643 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1644
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001645 // Diagnose attempt to use a variable as a label.
1646 //
1647 // FIXME: Diagnostics. Note the location of the definition as a label.
1648 // FIXME: This doesn't diagnose assignment to a symbol which has been
1649 // implicitly marked as external.
Kevin Enderby0510b482010-05-17 23:08:19 +00001650 MCSymbol *Sym;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001651 if (LocalLabelVal == -1) {
1652 if (ParsingInlineAsm && SI) {
Nico Weber67e715f2015-06-19 23:43:47 +00001653 StringRef RewrittenLabel =
1654 SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true);
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00001655 assert(!RewrittenLabel.empty() &&
Nico Weber67e715f2015-06-19 23:43:47 +00001656 "We should have an internal name here.");
Craig Topper7d5b2312015-10-10 05:25:02 +00001657 Info.AsmRewrites->emplace_back(AOK_Label, IDLoc, IDVal.size(),
1658 RewrittenLabel);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001659 IDVal = RewrittenLabel;
1660 }
Jim Grosbach6f482002015-05-18 18:43:14 +00001661 Sym = getContext().getOrCreateSymbol(IDVal);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001662 } else
Jim Grosbach6f482002015-05-18 18:43:14 +00001663 Sym = Ctx.createDirectionalLocalSymbol(LocalLabelVal);
Nirav Dave9263ae32016-08-02 19:17:54 +00001664 // End of Labels should be treated as end of line for lexing
1665 // purposes but that information is not available to the Lexer who
1666 // does not understand Labels. This may cause us to see a Hash
1667 // here instead of a preprocessor line comment.
1668 if (getTok().is(AsmToken::Hash)) {
1669 StringRef CommentStr = parseStringToEndOfStatement();
1670 Lexer.Lex();
1671 Lexer.UnLex(AsmToken(AsmToken::EndOfStatement, CommentStr));
1672 }
1673
Nirav Dave8ea792d2016-07-13 14:03:12 +00001674 // Consume any end of statement token, if present, to avoid spurious
1675 // AddBlankLine calls().
1676 if (getTok().is(AsmToken::EndOfStatement)) {
1677 Lex();
1678 }
1679
Daniel Dunbare73b2672009-08-26 22:13:22 +00001680 // Emit the label.
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +00001681 if (!getTargetParser().isParsingInlineAsm())
Rafael Espindolabe991572017-02-10 15:13:12 +00001682 Out.EmitLabel(Sym, IDLoc);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001683
Kevin Enderbye7739d42011-12-09 18:09:40 +00001684 // If we are generating dwarf for assembly source files then gather the
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001685 // info to make a dwarf label entry for this label if needed.
Kevin Enderbye7739d42011-12-09 18:09:40 +00001686 if (getContext().getGenDwarfForAssembly())
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001687 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1688 IDLoc);
Kevin Enderbye7739d42011-12-09 18:09:40 +00001689
Tim Northover1744d0a2013-10-25 12:49:50 +00001690 getTargetParser().onLabelParsed(Sym);
1691
Eli Friedman0f4871d2012-10-22 23:58:19 +00001692 return false;
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001693 }
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001694
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001695 case AsmToken::Equal:
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001696 if (!getTargetParser().equalIsAsmAssignment())
1697 break;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001698 // identifier '=' ... -> assignment statement
Sean Callanan686ed8d2010-01-19 20:22:31 +00001699 Lex();
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001700
Jim Grosbach4b905842013-09-20 23:08:21 +00001701 return parseAssignment(IDVal, true);
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001702
1703 default: // Normal instruction or directive.
1704 break;
Chris Lattner36e02122009-06-21 20:54:55 +00001705 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001706
1707 // If macros are enabled, check to see if this is a macro instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00001708 if (areMacrosEnabled())
1709 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1710 return handleMacroEntry(M, IDLoc);
Eli Bendersky38274122013-01-14 23:22:36 +00001711 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001712
Michael J. Spencer530ce852010-10-09 11:00:50 +00001713 // Otherwise, we have a normal instruction or directive.
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001714
Eli Bendersky17233942013-01-15 22:59:42 +00001715 // Directives start with "."
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001716 if (IDVal[0] == '.' && IDVal != ".") {
Eli Bendersky17233942013-01-15 22:59:42 +00001717 // There are several entities interested in parsing directives:
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001718 //
Eli Bendersky17233942013-01-15 22:59:42 +00001719 // 1. The target-specific assembly parser. Some directives are target
1720 // specific or may potentially behave differently on certain targets.
1721 // 2. Asm parser extensions. For example, platform-specific parsers
1722 // (like the ELF parser) register themselves as extensions.
1723 // 3. The generic directive parser implemented by this class. These are
1724 // all the directives that behave in a target and platform independent
1725 // manner, or at least have a default behavior that's shared between
1726 // all targets and platforms.
Akira Hatanakad3590752012-07-05 19:09:33 +00001727
Oliver Stannard21718282016-07-26 14:19:47 +00001728 getTargetParser().flushPendingInstructions(getStreamer());
1729
Nirav Dave2364748a2016-09-16 18:30:20 +00001730 SMLoc StartTokLoc = getTok().getLoc();
1731 bool TPDirectiveReturn = getTargetParser().ParseDirective(ID);
1732
1733 if (hasPendingError())
1734 return true;
1735 // Currently the return value should be true if we are
1736 // uninterested but as this is at odds with the standard parsing
1737 // convention (return true = error) we have instances of a parsed
1738 // directive that fails returning true as an error. Catch these
1739 // cases as best as possible errors here.
1740 if (TPDirectiveReturn && StartTokLoc != getTok().getLoc())
1741 return true;
1742 // Return if we did some parsing or believe we succeeded.
1743 if (!TPDirectiveReturn || StartTokLoc != getTok().getLoc())
Akira Hatanakad3590752012-07-05 19:09:33 +00001744 return false;
1745
Alp Tokercb402912014-01-24 17:20:08 +00001746 // Next, check the extension directive map to see if any extension has
Eli Bendersky17233942013-01-15 22:59:42 +00001747 // registered itself to parse this directive.
Jim Grosbach4b905842013-09-20 23:08:21 +00001748 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1749 ExtensionDirectiveMap.lookup(IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +00001750 if (Handler.first)
1751 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1752
1753 // Finally, if no one else is interested in this directive, it must be
1754 // generic and familiar to this class.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001755 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001756 default:
1757 break;
1758 case DK_SET:
1759 case DK_EQU:
1760 return parseDirectiveSet(IDVal, true);
1761 case DK_EQUIV:
1762 return parseDirectiveSet(IDVal, false);
1763 case DK_ASCII:
1764 return parseDirectiveAscii(IDVal, false);
1765 case DK_ASCIZ:
1766 case DK_STRING:
1767 return parseDirectiveAscii(IDVal, true);
1768 case DK_BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001769 case DK_DC_B:
1770 return parseDirectiveValue(IDVal, 1);
1771 case DK_DC:
1772 case DK_DC_W:
Jim Grosbach4b905842013-09-20 23:08:21 +00001773 case DK_SHORT:
1774 case DK_VALUE:
1775 case DK_2BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001776 return parseDirectiveValue(IDVal, 2);
Jim Grosbach4b905842013-09-20 23:08:21 +00001777 case DK_LONG:
1778 case DK_INT:
1779 case DK_4BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001780 case DK_DC_L:
1781 return parseDirectiveValue(IDVal, 4);
Jim Grosbach4b905842013-09-20 23:08:21 +00001782 case DK_QUAD:
1783 case DK_8BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001784 return parseDirectiveValue(IDVal, 8);
1785 case DK_DC_A:
Konstantin Zhuravlyovdc77b2e2017-04-17 17:41:25 +00001786 return parseDirectiveValue(
1787 IDVal, getContext().getAsmInfo()->getCodePointerSize());
David Woodhoused6de0d92014-02-01 16:20:59 +00001788 case DK_OCTA:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001789 return parseDirectiveOctaValue(IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001790 case DK_SINGLE:
1791 case DK_FLOAT:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001792 case DK_DC_S:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001793 return parseDirectiveRealValue(IDVal, APFloat::IEEEsingle());
Jim Grosbach4b905842013-09-20 23:08:21 +00001794 case DK_DOUBLE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001795 case DK_DC_D:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001796 return parseDirectiveRealValue(IDVal, APFloat::IEEEdouble());
Jim Grosbach4b905842013-09-20 23:08:21 +00001797 case DK_ALIGN: {
1798 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1799 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1800 }
1801 case DK_ALIGN32: {
1802 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1803 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1804 }
1805 case DK_BALIGN:
1806 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1807 case DK_BALIGNW:
1808 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1809 case DK_BALIGNL:
1810 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1811 case DK_P2ALIGN:
1812 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1813 case DK_P2ALIGNW:
1814 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1815 case DK_P2ALIGNL:
1816 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1817 case DK_ORG:
1818 return parseDirectiveOrg();
1819 case DK_FILL:
1820 return parseDirectiveFill();
1821 case DK_ZERO:
1822 return parseDirectiveZero();
1823 case DK_EXTERN:
1824 eatToEndOfStatement(); // .extern is the default, ignore it.
1825 return false;
1826 case DK_GLOBL:
1827 case DK_GLOBAL:
1828 return parseDirectiveSymbolAttribute(MCSA_Global);
1829 case DK_LAZY_REFERENCE:
1830 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1831 case DK_NO_DEAD_STRIP:
1832 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1833 case DK_SYMBOL_RESOLVER:
1834 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1835 case DK_PRIVATE_EXTERN:
1836 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1837 case DK_REFERENCE:
1838 return parseDirectiveSymbolAttribute(MCSA_Reference);
1839 case DK_WEAK_DEFINITION:
1840 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1841 case DK_WEAK_REFERENCE:
1842 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1843 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1844 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1845 case DK_COMM:
1846 case DK_COMMON:
1847 return parseDirectiveComm(/*IsLocal=*/false);
1848 case DK_LCOMM:
1849 return parseDirectiveComm(/*IsLocal=*/true);
1850 case DK_ABORT:
1851 return parseDirectiveAbort();
1852 case DK_INCLUDE:
1853 return parseDirectiveInclude();
1854 case DK_INCBIN:
1855 return parseDirectiveIncbin();
1856 case DK_CODE16:
1857 case DK_CODE16GCC:
Nirav Davefd910412016-06-17 16:06:17 +00001858 return TokError(Twine(IDVal) +
1859 " not currently supported for this target");
Jim Grosbach4b905842013-09-20 23:08:21 +00001860 case DK_REPT:
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00001861 return parseDirectiveRept(IDLoc, IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001862 case DK_IRP:
1863 return parseDirectiveIrp(IDLoc);
1864 case DK_IRPC:
1865 return parseDirectiveIrpc(IDLoc);
1866 case DK_ENDR:
1867 return parseDirectiveEndr(IDLoc);
1868 case DK_BUNDLE_ALIGN_MODE:
1869 return parseDirectiveBundleAlignMode();
1870 case DK_BUNDLE_LOCK:
1871 return parseDirectiveBundleLock();
1872 case DK_BUNDLE_UNLOCK:
1873 return parseDirectiveBundleUnlock();
1874 case DK_SLEB128:
1875 return parseDirectiveLEB128(true);
1876 case DK_ULEB128:
1877 return parseDirectiveLEB128(false);
1878 case DK_SPACE:
1879 case DK_SKIP:
1880 return parseDirectiveSpace(IDVal);
1881 case DK_FILE:
1882 return parseDirectiveFile(IDLoc);
1883 case DK_LINE:
1884 return parseDirectiveLine();
1885 case DK_LOC:
1886 return parseDirectiveLoc();
1887 case DK_STABS:
1888 return parseDirectiveStabs();
Reid Kleckner2214ed82016-01-29 00:49:42 +00001889 case DK_CV_FILE:
1890 return parseDirectiveCVFile();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00001891 case DK_CV_FUNC_ID:
1892 return parseDirectiveCVFuncId();
1893 case DK_CV_INLINE_SITE_ID:
1894 return parseDirectiveCVInlineSiteId();
Reid Kleckner2214ed82016-01-29 00:49:42 +00001895 case DK_CV_LOC:
1896 return parseDirectiveCVLoc();
1897 case DK_CV_LINETABLE:
1898 return parseDirectiveCVLinetable();
David Majnemer6fcbd7e2016-01-29 19:24:12 +00001899 case DK_CV_INLINE_LINETABLE:
1900 return parseDirectiveCVInlineLinetable();
David Majnemer408b5e62016-02-05 01:55:49 +00001901 case DK_CV_DEF_RANGE:
1902 return parseDirectiveCVDefRange();
Reid Kleckner2214ed82016-01-29 00:49:42 +00001903 case DK_CV_STRINGTABLE:
1904 return parseDirectiveCVStringTable();
1905 case DK_CV_FILECHECKSUMS:
1906 return parseDirectiveCVFileChecksums();
Jim Grosbach4b905842013-09-20 23:08:21 +00001907 case DK_CFI_SECTIONS:
1908 return parseDirectiveCFISections();
1909 case DK_CFI_STARTPROC:
1910 return parseDirectiveCFIStartProc();
1911 case DK_CFI_ENDPROC:
1912 return parseDirectiveCFIEndProc();
1913 case DK_CFI_DEF_CFA:
1914 return parseDirectiveCFIDefCfa(IDLoc);
1915 case DK_CFI_DEF_CFA_OFFSET:
1916 return parseDirectiveCFIDefCfaOffset();
1917 case DK_CFI_ADJUST_CFA_OFFSET:
1918 return parseDirectiveCFIAdjustCfaOffset();
1919 case DK_CFI_DEF_CFA_REGISTER:
1920 return parseDirectiveCFIDefCfaRegister(IDLoc);
1921 case DK_CFI_OFFSET:
1922 return parseDirectiveCFIOffset(IDLoc);
1923 case DK_CFI_REL_OFFSET:
1924 return parseDirectiveCFIRelOffset(IDLoc);
1925 case DK_CFI_PERSONALITY:
1926 return parseDirectiveCFIPersonalityOrLsda(true);
1927 case DK_CFI_LSDA:
1928 return parseDirectiveCFIPersonalityOrLsda(false);
1929 case DK_CFI_REMEMBER_STATE:
1930 return parseDirectiveCFIRememberState();
1931 case DK_CFI_RESTORE_STATE:
1932 return parseDirectiveCFIRestoreState();
1933 case DK_CFI_SAME_VALUE:
1934 return parseDirectiveCFISameValue(IDLoc);
1935 case DK_CFI_RESTORE:
1936 return parseDirectiveCFIRestore(IDLoc);
1937 case DK_CFI_ESCAPE:
1938 return parseDirectiveCFIEscape();
1939 case DK_CFI_SIGNAL_FRAME:
1940 return parseDirectiveCFISignalFrame();
1941 case DK_CFI_UNDEFINED:
1942 return parseDirectiveCFIUndefined(IDLoc);
1943 case DK_CFI_REGISTER:
1944 return parseDirectiveCFIRegister(IDLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00001945 case DK_CFI_WINDOW_SAVE:
1946 return parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +00001947 case DK_MACROS_ON:
1948 case DK_MACROS_OFF:
1949 return parseDirectiveMacrosOnOff(IDVal);
1950 case DK_MACRO:
1951 return parseDirectiveMacro(IDLoc);
Michael Zuckerman56704612017-05-01 13:20:12 +00001952 case DK_ALTMACRO:
1953 case DK_NOALTMACRO:
1954 return parseDirectiveAltmacro(IDVal);
Nico Weber155dccd12014-07-24 17:08:39 +00001955 case DK_EXITM:
1956 return parseDirectiveExitMacro(IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001957 case DK_ENDM:
1958 case DK_ENDMACRO:
1959 return parseDirectiveEndMacro(IDVal);
1960 case DK_PURGEM:
1961 return parseDirectivePurgeMacro(IDLoc);
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00001962 case DK_END:
1963 return parseDirectiveEnd(IDLoc);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00001964 case DK_ERR:
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00001965 return parseDirectiveError(IDLoc, false);
1966 case DK_ERROR:
1967 return parseDirectiveError(IDLoc, true);
Nico Weber404012b2014-07-24 16:26:06 +00001968 case DK_WARNING:
1969 return parseDirectiveWarning(IDLoc);
Daniel Sanders9f6ad492015-11-12 13:33:00 +00001970 case DK_RELOC:
1971 return parseDirectiveReloc(IDLoc);
Petr Hosek4cb08ce2016-09-23 19:25:15 +00001972 case DK_DCB:
1973 case DK_DCB_W:
1974 return parseDirectiveDCB(IDVal, 2);
1975 case DK_DCB_B:
1976 return parseDirectiveDCB(IDVal, 1);
1977 case DK_DCB_D:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001978 return parseDirectiveRealDCB(IDVal, APFloat::IEEEdouble());
Petr Hosek4cb08ce2016-09-23 19:25:15 +00001979 case DK_DCB_L:
1980 return parseDirectiveDCB(IDVal, 4);
1981 case DK_DCB_S:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001982 return parseDirectiveRealDCB(IDVal, APFloat::IEEEsingle());
Petr Hosek731bb9c2016-08-23 21:34:53 +00001983 case DK_DC_X:
Petr Hosek4cb08ce2016-09-23 19:25:15 +00001984 case DK_DCB_X:
Petr Hosek731bb9c2016-08-23 21:34:53 +00001985 return TokError(Twine(IDVal) +
1986 " not currently supported for this target");
Petr Hosek85b2f672016-09-23 21:53:36 +00001987 case DK_DS:
1988 case DK_DS_W:
1989 return parseDirectiveDS(IDVal, 2);
1990 case DK_DS_B:
1991 return parseDirectiveDS(IDVal, 1);
1992 case DK_DS_D:
1993 return parseDirectiveDS(IDVal, 8);
1994 case DK_DS_L:
1995 case DK_DS_S:
1996 return parseDirectiveDS(IDVal, 4);
1997 case DK_DS_P:
1998 case DK_DS_X:
1999 return parseDirectiveDS(IDVal, 12);
Eli Friedman20b02642010-07-19 04:17:25 +00002000 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002001
Jim Grosbach758e0cc2012-05-01 18:38:27 +00002002 return Error(IDLoc, "unknown directive");
Chris Lattnere5074c42009-06-22 01:29:09 +00002003 }
Chris Lattner36e02122009-06-21 20:54:55 +00002004
Chad Rosierc7f552c2013-02-12 21:33:51 +00002005 // __asm _emit or __asm __emit
2006 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
2007 IDVal == "_EMIT" || IDVal == "__EMIT"))
Jim Grosbach4b905842013-09-20 23:08:21 +00002008 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
Chad Rosierc7f552c2013-02-12 21:33:51 +00002009
2010 // __asm align
2011 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
Jim Grosbach4b905842013-09-20 23:08:21 +00002012 return parseDirectiveMSAlign(IDLoc, Info);
Eli Friedman0f4871d2012-10-22 23:58:19 +00002013
Coby Tayree3847be92017-04-04 17:57:23 +00002014 if (ParsingInlineAsm && (IDVal == "even" || IDVal == "EVEN"))
Michael Zuckerman02ecd432015-12-13 17:07:23 +00002015 Info.AsmRewrites->emplace_back(AOK_EVEN, IDLoc, 4);
Nirav Davef43cc9f2016-10-10 15:24:54 +00002016 if (checkForValidSection())
2017 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00002018
Chris Lattner7cbfa442010-05-19 23:34:33 +00002019 // Canonicalize the opcode to lower case.
Eli Bendersky88024712013-01-16 19:32:36 +00002020 std::string OpcodeStr = IDVal.lower();
Chad Rosierf0e87202012-10-25 20:41:34 +00002021 ParseInstructionInfo IInfo(Info.AsmRewrites);
Nirav Dave2364748a2016-09-16 18:30:20 +00002022 bool ParseHadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, ID,
2023 Info.ParsedOperands);
2024 Info.ParseError = ParseHadError;
Chris Lattnere5074c42009-06-22 01:29:09 +00002025
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002026 // Dump the parsed representation, if requested.
2027 if (getShowParsedOperands()) {
2028 SmallString<256> Str;
2029 raw_svector_ostream OS(Str);
2030 OS << "parsed instruction: [";
Eli Friedman0f4871d2012-10-22 23:58:19 +00002031 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002032 if (i != 0)
2033 OS << ", ";
Eli Friedman0f4871d2012-10-22 23:58:19 +00002034 Info.ParsedOperands[i]->print(OS);
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002035 }
2036 OS << "]";
2037
Jim Grosbach4b905842013-09-20 23:08:21 +00002038 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002039 }
2040
Nirav Dave2364748a2016-09-16 18:30:20 +00002041 // Fail even if ParseInstruction erroneously returns false.
2042 if (hasPendingError() || ParseHadError)
2043 return true;
2044
Oliver Stannard8b273082014-06-19 15:52:37 +00002045 // If we are generating dwarf for the current section then generate a .loc
2046 // directive for the instruction.
Nirav Dave2364748a2016-09-16 18:30:20 +00002047 if (!ParseHadError && getContext().getGenDwarfForAssembly() &&
Oliver Stannard8b273082014-06-19 15:52:37 +00002048 getContext().getGenDwarfSectionSyms().count(
Eric Christopher445c9522016-10-14 05:47:37 +00002049 getStreamer().getCurrentSectionOnly())) {
Saleem Abdulrasool4d6ed7c2014-12-24 06:32:43 +00002050 unsigned Line;
2051 if (ActiveMacros.empty())
2052 Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
2053 else
Frederic Riss16238d92015-06-25 21:57:33 +00002054 Line = SrcMgr.FindLineNumber(ActiveMacros.front()->InstantiationLoc,
2055 ActiveMacros.front()->ExitBuffer);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002056
Eli Bendersky88024712013-01-16 19:32:36 +00002057 // If we previously parsed a cpp hash file line comment then make sure the
2058 // current Dwarf File is for the CppHashFilename if not then emit the
2059 // Dwarf File table for it and adjust the line number for the .loc.
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00002060 if (!CppHashInfo.Filename.empty()) {
David Blaikiec714ef42014-03-17 01:52:11 +00002061 unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
Tim Northoverc0bef992016-04-13 19:46:54 +00002062 0, StringRef(), CppHashInfo.Filename);
David Blaikiec714ef42014-03-17 01:52:11 +00002063 getContext().setGenDwarfFileNumber(FileNumber);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002064
Jim Grosbach4b905842013-09-20 23:08:21 +00002065 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
2066 // cache with the different Loc from the call above we save the last
2067 // info we queried here with SrcMgr.FindLineNumber().
2068 unsigned CppHashLocLineNo;
Tim Northoverc0bef992016-04-13 19:46:54 +00002069 if (LastQueryIDLoc == CppHashInfo.Loc &&
2070 LastQueryBuffer == CppHashInfo.Buf)
Jim Grosbach4b905842013-09-20 23:08:21 +00002071 CppHashLocLineNo = LastQueryLine;
2072 else {
Tim Northoverc0bef992016-04-13 19:46:54 +00002073 CppHashLocLineNo =
2074 SrcMgr.FindLineNumber(CppHashInfo.Loc, CppHashInfo.Buf);
Jim Grosbach4b905842013-09-20 23:08:21 +00002075 LastQueryLine = CppHashLocLineNo;
Tim Northoverc0bef992016-04-13 19:46:54 +00002076 LastQueryIDLoc = CppHashInfo.Loc;
2077 LastQueryBuffer = CppHashInfo.Buf;
Jim Grosbach4b905842013-09-20 23:08:21 +00002078 }
Tim Northoverc0bef992016-04-13 19:46:54 +00002079 Line = CppHashInfo.LineNumber - 1 + (Line - CppHashLocLineNo);
Eli Bendersky88024712013-01-16 19:32:36 +00002080 }
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002081
Jim Grosbach4b905842013-09-20 23:08:21 +00002082 getStreamer().EmitDwarfLocDirective(
2083 getContext().getGenDwarfFileNumber(), Line, 0,
2084 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
2085 StringRef());
Kevin Enderby6469fc22011-11-01 22:27:22 +00002086 }
2087
Daniel Dunbarce0c1e12010-05-04 00:33:07 +00002088 // If parsing succeeded, match the instruction.
Nirav Dave2364748a2016-09-16 18:30:20 +00002089 if (!ParseHadError) {
Tim Northover26bb14e2014-08-18 11:49:42 +00002090 uint64_t ErrorInfo;
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +00002091 if (getTargetParser().MatchAndEmitInstruction(
2092 IDLoc, Info.Opcode, Info.ParsedOperands, Out, ErrorInfo,
2093 getTargetParser().isParsingInlineAsm()))
Nirav Dave2364748a2016-09-16 18:30:20 +00002094 return true;
Chad Rosier49963552012-10-13 00:26:04 +00002095 }
Chris Lattnera2a9d162010-09-11 16:18:25 +00002096 return false;
Chris Lattnerb0133452009-06-21 20:16:42 +00002097}
Chris Lattnerbedf6c22009-06-24 04:43:34 +00002098
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00002099// Parse and erase curly braces marking block start/end
2100bool
2101AsmParser::parseCurlyBlockScope(SmallVectorImpl<AsmRewrite> &AsmStrRewrites) {
2102 // Identify curly brace marking block start/end
2103 if (Lexer.isNot(AsmToken::LCurly) && Lexer.isNot(AsmToken::RCurly))
2104 return false;
2105
2106 SMLoc StartLoc = Lexer.getLoc();
2107 Lex(); // Eat the brace
2108 if (Lexer.is(AsmToken::EndOfStatement))
2109 Lex(); // Eat EndOfStatement following the brace
2110
2111 // Erase the block start/end brace from the output asm string
2112 AsmStrRewrites.emplace_back(AOK_Skip, StartLoc, Lexer.getLoc().getPointer() -
2113 StartLoc.getPointer());
2114 return true;
2115}
2116
Jim Grosbach4b905842013-09-20 23:08:21 +00002117/// parseCppHashLineFilenameComment as this:
Kevin Enderby72553612011-09-13 23:45:18 +00002118/// ::= # number "filename"
Craig Topper3c76c522015-09-20 23:35:59 +00002119bool AsmParser::parseCppHashLineFilenameComment(SMLoc L) {
Kevin Enderby72553612011-09-13 23:45:18 +00002120 Lex(); // Eat the hash token.
Nirav Davefd910412016-06-17 16:06:17 +00002121 // Lexer only ever emits HashDirective if it fully formed if it's
2122 // done the checking already so this is an internal error.
2123 assert(getTok().is(AsmToken::Integer) &&
2124 "Lexing Cpp line comment: Expected Integer");
Kevin Enderby72553612011-09-13 23:45:18 +00002125 int64_t LineNumber = getTok().getIntVal();
Kevin Enderby72553612011-09-13 23:45:18 +00002126 Lex();
Nirav Davefd910412016-06-17 16:06:17 +00002127 assert(getTok().is(AsmToken::String) &&
2128 "Lexing Cpp line comment: Expected String");
Kevin Enderby72553612011-09-13 23:45:18 +00002129 StringRef Filename = getTok().getString();
Nirav Davefd910412016-06-17 16:06:17 +00002130 Lex();
Nirav Dave2364748a2016-09-16 18:30:20 +00002131
Kevin Enderby72553612011-09-13 23:45:18 +00002132 // Get rid of the enclosing quotes.
Jim Grosbach4b905842013-09-20 23:08:21 +00002133 Filename = Filename.substr(1, Filename.size() - 2);
Kevin Enderby72553612011-09-13 23:45:18 +00002134
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002135 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
Tim Northoverc0bef992016-04-13 19:46:54 +00002136 CppHashInfo.Loc = L;
2137 CppHashInfo.Filename = Filename;
2138 CppHashInfo.LineNumber = LineNumber;
2139 CppHashInfo.Buf = CurBuffer;
Kevin Enderby72553612011-09-13 23:45:18 +00002140 return false;
2141}
2142
Jim Grosbach4b905842013-09-20 23:08:21 +00002143/// \brief will use the last parsed cpp hash line filename comment
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002144/// for the Filename and LineNo if any in the diagnostic.
2145void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002146 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002147 raw_ostream &OS = errs();
2148
2149 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
Craig Topper3c76c522015-09-20 23:35:59 +00002150 SMLoc DiagLoc = Diag.getLoc();
Alp Tokera55b95b2014-07-06 10:33:31 +00002151 unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2152 unsigned CppHashBuf =
Tim Northoverc0bef992016-04-13 19:46:54 +00002153 Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashInfo.Loc);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002154
Jim Grosbach4b905842013-09-20 23:08:21 +00002155 // Like SourceMgr::printMessage() we need to print the include stack if any
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002156 // before printing the message.
Alp Tokera55b95b2014-07-06 10:33:31 +00002157 unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2158 if (!Parser->SavedDiagHandler && DiagCurBuffer &&
2159 DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002160 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
2161 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002162 }
2163
Eric Christophera7c32732012-12-18 00:30:54 +00002164 // If we have not parsed a cpp hash line filename comment or the source
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002165 // manager changed or buffer changed (like in a nested include) then just
2166 // print the normal diagnostic using its Filename and LineNo.
Tim Northoverc0bef992016-04-13 19:46:54 +00002167 if (!Parser->CppHashInfo.LineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002168 DiagBuf != CppHashBuf) {
Benjamin Kramer47f5e302011-10-16 10:48:29 +00002169 if (Parser->SavedDiagHandler)
2170 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
2171 else
Craig Topper353eda42014-04-24 06:44:33 +00002172 Diag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002173 return;
2174 }
2175
Eric Christophera7c32732012-12-18 00:30:54 +00002176 // Use the CppHashFilename and calculate a line number based on the
Tim Northoverc0bef992016-04-13 19:46:54 +00002177 // CppHashInfo.Loc and CppHashInfo.LineNumber relative to this Diag's SMLoc
2178 // for the diagnostic.
2179 const std::string &Filename = Parser->CppHashInfo.Filename;
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002180
2181 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
2182 int CppHashLocLineNo =
Tim Northoverc0bef992016-04-13 19:46:54 +00002183 Parser->SrcMgr.FindLineNumber(Parser->CppHashInfo.Loc, CppHashBuf);
Jim Grosbach4b905842013-09-20 23:08:21 +00002184 int LineNo =
Tim Northoverc0bef992016-04-13 19:46:54 +00002185 Parser->CppHashInfo.LineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002186
Jim Grosbach4b905842013-09-20 23:08:21 +00002187 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
2188 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
Chris Lattner72845262011-10-16 05:47:55 +00002189 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002190
Benjamin Kramer47f5e302011-10-16 10:48:29 +00002191 if (Parser->SavedDiagHandler)
2192 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
2193 else
Craig Topper353eda42014-04-24 06:44:33 +00002194 NewDiag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002195}
2196
Rafael Espindola2c064482012-08-21 18:29:30 +00002197// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
2198// difference being that that function accepts '@' as part of identifiers and
2199// we can't do that. AsmLexer.cpp should probably be changed to handle
2200// '@' as a special case when needed.
2201static bool isIdentifierChar(char c) {
Guy Benyei83c74e92013-02-12 21:21:59 +00002202 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
2203 c == '.';
Rafael Espindola2c064482012-08-21 18:29:30 +00002204}
2205
Rafael Espindola34b9c512012-06-03 23:57:14 +00002206bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00002207 ArrayRef<MCAsmMacroParameter> Parameters,
Toma Tabacu217116e2015-04-27 10:50:29 +00002208 ArrayRef<MCAsmMacroArgument> A,
Craig Topper3c76c522015-09-20 23:35:59 +00002209 bool EnableAtPseudoVariable, SMLoc L) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00002210 unsigned NParameters = Parameters.size();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002211 bool HasVararg = NParameters ? Parameters.back().Vararg : false;
Benjamin Kramer513e7442014-02-20 13:36:32 +00002212 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
Rafael Espindola1134ab232011-06-05 02:43:45 +00002213 return Error(L, "Wrong number of arguments");
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002214
Preston Gurd05500642012-09-19 20:36:12 +00002215 // A macro without parameters is handled differently on Darwin:
2216 // gas accepts no arguments and does no substitutions
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002217 while (!Body.empty()) {
2218 // Scan for the next substitution.
2219 std::size_t End = Body.size(), Pos = 0;
2220 for (; Pos != End; ++Pos) {
2221 // Check for a substitution or escape.
Benjamin Kramer513e7442014-02-20 13:36:32 +00002222 if (IsDarwin && !NParameters) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00002223 // This macro has no parameters, look for $0, $1, etc.
2224 if (Body[Pos] != '$' || Pos + 1 == End)
2225 continue;
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002226
Rafael Espindola1134ab232011-06-05 02:43:45 +00002227 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00002228 if (Next == '$' || Next == 'n' ||
2229 isdigit(static_cast<unsigned char>(Next)))
Rafael Espindola1134ab232011-06-05 02:43:45 +00002230 break;
2231 } else {
2232 // This macro has parameters, look for \foo, \bar, etc.
2233 if (Body[Pos] == '\\' && Pos + 1 != End)
2234 break;
2235 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002236 }
2237
2238 // Add the prefix.
2239 OS << Body.slice(0, Pos);
2240
2241 // Check if we reached the end.
2242 if (Pos == End)
2243 break;
2244
Benjamin Kramer513e7442014-02-20 13:36:32 +00002245 if (IsDarwin && !NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002246 switch (Body[Pos + 1]) {
2247 // $$ => $
Rafael Espindola1134ab232011-06-05 02:43:45 +00002248 case '$':
2249 OS << '$';
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002250 break;
2251
Jim Grosbach4b905842013-09-20 23:08:21 +00002252 // $n => number of arguments
Rafael Espindola1134ab232011-06-05 02:43:45 +00002253 case 'n':
2254 OS << A.size();
2255 break;
2256
Jim Grosbach4b905842013-09-20 23:08:21 +00002257 // $[0-9] => argument
Rafael Espindola1134ab232011-06-05 02:43:45 +00002258 default: {
2259 // Missing arguments are ignored.
Jim Grosbach4b905842013-09-20 23:08:21 +00002260 unsigned Index = Body[Pos + 1] - '0';
Rafael Espindola1134ab232011-06-05 02:43:45 +00002261 if (Index >= A.size())
2262 break;
2263
2264 // Otherwise substitute with the token values, with spaces eliminated.
Craig Topper84008482015-10-10 05:38:14 +00002265 for (const AsmToken &Token : A[Index])
2266 OS << Token.getString();
Rafael Espindola1134ab232011-06-05 02:43:45 +00002267 break;
2268 }
2269 }
2270 Pos += 2;
2271 } else {
2272 unsigned I = Pos + 1;
Toma Tabacu217116e2015-04-27 10:50:29 +00002273
2274 // Check for the \@ pseudo-variable.
2275 if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End)
Rafael Espindola1134ab232011-06-05 02:43:45 +00002276 ++I;
Toma Tabacu217116e2015-04-27 10:50:29 +00002277 else
2278 while (isIdentifierChar(Body[I]) && I + 1 != End)
2279 ++I;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002280
Jim Grosbach4b905842013-09-20 23:08:21 +00002281 const char *Begin = Body.data() + Pos + 1;
2282 StringRef Argument(Begin, I - (Pos + 1));
Rafael Espindola1134ab232011-06-05 02:43:45 +00002283 unsigned Index = 0;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002284
Toma Tabacu217116e2015-04-27 10:50:29 +00002285 if (Argument == "@") {
2286 OS << NumOfMacroInstantiations;
2287 Pos += 2;
Preston Gurd05500642012-09-19 20:36:12 +00002288 } else {
Toma Tabacu217116e2015-04-27 10:50:29 +00002289 for (; Index < NParameters; ++Index)
2290 if (Parameters[Index].Name == Argument)
2291 break;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002292
Toma Tabacu217116e2015-04-27 10:50:29 +00002293 if (Index == NParameters) {
2294 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
2295 Pos += 3;
2296 else {
2297 OS << '\\' << Argument;
2298 Pos = I;
2299 }
2300 } else {
2301 bool VarargParameter = HasVararg && Index == (NParameters - 1);
Craig Topper84008482015-10-10 05:38:14 +00002302 for (const AsmToken &Token : A[Index])
Michael Zuckerman56704612017-05-01 13:20:12 +00002303 // For altmacro mode, you can write '%expr'.
2304 // The prefix '%' evaluates the expression 'expr'
2305 // and uses the result as a string (e.g. replace %(1+2) with the string "3").
2306 // Here, we identify the integer token which is the result of the
2307 // absolute expression evaluation and replace it with its string representation.
2308 if ((Lexer.IsaAltMacroMode()) &&
2309 (*(Token.getString().begin()) == '%') && Token.is(AsmToken::Integer))
2310 // Emit an integer value to the buffer.
2311 OS << Token.getIntVal();
Toma Tabacu217116e2015-04-27 10:50:29 +00002312 // We expect no quotes around the string's contents when
2313 // parsing for varargs.
Michael Zuckerman56704612017-05-01 13:20:12 +00002314 else if (Token.isNot(AsmToken::String) || VarargParameter)
Craig Topper84008482015-10-10 05:38:14 +00002315 OS << Token.getString();
Toma Tabacu217116e2015-04-27 10:50:29 +00002316 else
Craig Topper84008482015-10-10 05:38:14 +00002317 OS << Token.getStringContents();
Toma Tabacu217116e2015-04-27 10:50:29 +00002318
2319 Pos += 1 + Argument.size();
2320 }
Preston Gurd05500642012-09-19 20:36:12 +00002321 }
Rafael Espindola1134ab232011-06-05 02:43:45 +00002322 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002323 // Update the scan point.
Rafael Espindola1134ab232011-06-05 02:43:45 +00002324 Body = Body.substr(Pos);
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002325 }
Daniel Dunbar43235712010-07-18 18:54:11 +00002326
Rafael Espindola1134ab232011-06-05 02:43:45 +00002327 return false;
2328}
Daniel Dunbar43235712010-07-18 18:54:11 +00002329
Nico Weber2a8f9222014-07-24 16:29:04 +00002330MacroInstantiation::MacroInstantiation(SMLoc IL, int EB, SMLoc EL,
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002331 size_t CondStackDepth)
Rafael Espindolaf43a94e2014-08-17 22:48:55 +00002332 : InstantiationLoc(IL), ExitBuffer(EB), ExitLoc(EL),
Nico Weber155dccd12014-07-24 17:08:39 +00002333 CondStackDepth(CondStackDepth) {}
Daniel Dunbar43235712010-07-18 18:54:11 +00002334
Jim Grosbach4b905842013-09-20 23:08:21 +00002335static bool isOperator(AsmToken::TokenKind kind) {
2336 switch (kind) {
2337 default:
2338 return false;
2339 case AsmToken::Plus:
2340 case AsmToken::Minus:
2341 case AsmToken::Tilde:
2342 case AsmToken::Slash:
2343 case AsmToken::Star:
2344 case AsmToken::Dot:
2345 case AsmToken::Equal:
2346 case AsmToken::EqualEqual:
2347 case AsmToken::Pipe:
2348 case AsmToken::PipePipe:
2349 case AsmToken::Caret:
2350 case AsmToken::Amp:
2351 case AsmToken::AmpAmp:
2352 case AsmToken::Exclaim:
2353 case AsmToken::ExclaimEqual:
Jim Grosbach4b905842013-09-20 23:08:21 +00002354 case AsmToken::Less:
2355 case AsmToken::LessEqual:
2356 case AsmToken::LessLess:
2357 case AsmToken::LessGreater:
2358 case AsmToken::Greater:
2359 case AsmToken::GreaterEqual:
2360 case AsmToken::GreaterGreater:
2361 return true;
Preston Gurd05500642012-09-19 20:36:12 +00002362 }
2363}
2364
David Majnemer16252452014-01-29 00:07:39 +00002365namespace {
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002366
David Majnemer16252452014-01-29 00:07:39 +00002367class AsmLexerSkipSpaceRAII {
2368public:
2369 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
2370 Lexer.setSkipSpace(SkipSpace);
2371 }
2372
2373 ~AsmLexerSkipSpaceRAII() {
2374 Lexer.setSkipSpace(true);
2375 }
2376
2377private:
2378 AsmLexer &Lexer;
2379};
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002380
2381} // end anonymous namespace
David Majnemer16252452014-01-29 00:07:39 +00002382
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002383bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
2384
2385 if (Vararg) {
2386 if (Lexer.isNot(AsmToken::EndOfStatement)) {
2387 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002388 MA.emplace_back(AsmToken::String, Str);
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002389 }
2390 return false;
2391 }
2392
Rafael Espindola768b41c2012-06-15 14:02:34 +00002393 unsigned ParenLevel = 0;
Preston Gurd05500642012-09-19 20:36:12 +00002394
David Majnemer16252452014-01-29 00:07:39 +00002395 // Darwin doesn't use spaces to delmit arguments.
2396 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
Rafael Espindola768b41c2012-06-15 14:02:34 +00002397
Scott Egertona1fa68a2016-02-11 13:48:49 +00002398 bool SpaceEaten;
2399
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002400 while (true) {
Scott Egertona1fa68a2016-02-11 13:48:49 +00002401 SpaceEaten = false;
David Majnemer16252452014-01-29 00:07:39 +00002402 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002403 return TokError("unexpected token in macro instantiation");
Preston Gurd05500642012-09-19 20:36:12 +00002404
Scott Egertona1fa68a2016-02-11 13:48:49 +00002405 if (ParenLevel == 0) {
Preston Gurd05500642012-09-19 20:36:12 +00002406
Scott Egertona1fa68a2016-02-11 13:48:49 +00002407 if (Lexer.is(AsmToken::Comma))
2408 break;
2409
2410 if (Lexer.is(AsmToken::Space)) {
2411 SpaceEaten = true;
Nirav Dave1180e6892016-06-02 17:15:05 +00002412 Lexer.Lex(); // Eat spaces
Scott Egertona1fa68a2016-02-11 13:48:49 +00002413 }
Preston Gurd05500642012-09-19 20:36:12 +00002414
2415 // Spaces can delimit parameters, but could also be part an expression.
2416 // If the token after a space is an operator, add the token and the next
2417 // one into this argument
David Majnemer91fc4c22014-01-29 18:57:46 +00002418 if (!IsDarwin) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002419 if (isOperator(Lexer.getKind())) {
Scott Egertona1fa68a2016-02-11 13:48:49 +00002420 MA.push_back(getTok());
Nirav Dave1180e6892016-06-02 17:15:05 +00002421 Lexer.Lex();
Preston Gurd05500642012-09-19 20:36:12 +00002422
Scott Egertona1fa68a2016-02-11 13:48:49 +00002423 // Whitespace after an operator can be ignored.
2424 if (Lexer.is(AsmToken::Space))
Nirav Dave1180e6892016-06-02 17:15:05 +00002425 Lexer.Lex();
Scott Egertona1fa68a2016-02-11 13:48:49 +00002426
2427 continue;
Preston Gurd05500642012-09-19 20:36:12 +00002428 }
2429 }
Scott Egertona1fa68a2016-02-11 13:48:49 +00002430 if (SpaceEaten)
2431 break;
Preston Gurd05500642012-09-19 20:36:12 +00002432 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002433
Jim Grosbach4b905842013-09-20 23:08:21 +00002434 // handleMacroEntry relies on not advancing the lexer here
Rafael Espindola768b41c2012-06-15 14:02:34 +00002435 // to be able to fill in the remaining default parameter values
2436 if (Lexer.is(AsmToken::EndOfStatement))
2437 break;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002438
2439 // Adjust the current parentheses level.
2440 if (Lexer.is(AsmToken::LParen))
2441 ++ParenLevel;
2442 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
2443 --ParenLevel;
2444
2445 // Append the token to the current argument list.
2446 MA.push_back(getTok());
Nirav Dave1180e6892016-06-02 17:15:05 +00002447 Lexer.Lex();
Rafael Espindola768b41c2012-06-15 14:02:34 +00002448 }
Preston Gurd05500642012-09-19 20:36:12 +00002449
Rafael Espindola768b41c2012-06-15 14:02:34 +00002450 if (ParenLevel != 0)
Rafael Espindola3e5eb422012-08-21 15:55:04 +00002451 return TokError("unbalanced parentheses in macro argument");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002452 return false;
2453}
2454
2455// Parse the macro instantiation arguments.
Jim Grosbach4b905842013-09-20 23:08:21 +00002456bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
Vladimir Medic9bad0d332013-08-20 13:33:18 +00002457 MCAsmMacroArguments &A) {
Rafael Espindola768b41c2012-06-15 14:02:34 +00002458 const unsigned NParameters = M ? M->Parameters.size() : 0;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002459 bool NamedParametersFound = false;
2460 SmallVector<SMLoc, 4> FALocs;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002461
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002462 A.resize(NParameters);
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002463 FALocs.resize(NParameters);
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002464
Rafael Espindola768b41c2012-06-15 14:02:34 +00002465 // Parse two kinds of macro invocations:
2466 // - macros defined without any parameters accept an arbitrary number of them
2467 // - macros defined with parameters accept at most that many of them
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002468 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002469 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
2470 ++Parameter) {
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002471 SMLoc IDLoc = Lexer.getLoc();
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002472 MCAsmMacroParameter FA;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002473
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002474 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00002475 if (parseIdentifier(FA.Name))
2476 return Error(IDLoc, "invalid argument identifier for formal argument");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002477
Nirav Dave2364748a2016-09-16 18:30:20 +00002478 if (Lexer.isNot(AsmToken::Equal))
2479 return TokError("expected '=' after formal parameter identifier");
2480
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002481 Lex();
2482
2483 NamedParametersFound = true;
2484 }
Michael Zuckerman56704612017-05-01 13:20:12 +00002485 bool Vararg = HasVararg && Parameter == (NParameters - 1);
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002486
Nirav Dave2364748a2016-09-16 18:30:20 +00002487 if (NamedParametersFound && FA.Name.empty())
2488 return Error(IDLoc, "cannot mix positional and keyword arguments");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002489
Michael Zuckerman763e60e2017-05-04 10:37:00 +00002490 SMLoc StrLoc = Lexer.getLoc();
2491 SMLoc EndLoc;
Michael Zuckerman56704612017-05-01 13:20:12 +00002492 if (Lexer.IsaAltMacroMode() && Lexer.is(AsmToken::Percent)) {
Michael Zuckerman56704612017-05-01 13:20:12 +00002493 const MCExpr *AbsoluteExp;
2494 int64_t Value;
2495 /// Eat '%'
2496 Lex();
2497 if (parseExpression(AbsoluteExp, EndLoc))
2498 return false;
2499 if (!AbsoluteExp->evaluateAsAbsolute(Value))
2500 return Error(StrLoc, "expected absolute expression");
2501 const char *StrChar = StrLoc.getPointer();
2502 const char *EndChar = EndLoc.getPointer();
2503 AsmToken newToken(AsmToken::Integer, StringRef(StrChar , EndChar - StrChar), Value);
2504 FA.Value.push_back(newToken);
Michael Zuckerman763e60e2017-05-04 10:37:00 +00002505 } else if (Lexer.IsaAltMacroMode() && Lexer.is(AsmToken::Less) &&
2506 isAltmacroString(StrLoc, EndLoc)) {
2507 const char *StrChar = StrLoc.getPointer();
2508 const char *EndChar = EndLoc.getPointer();
2509 jumpToLoc(EndLoc, CurBuffer);
2510 /// Eat from '<' to '>'
2511 Lex();
2512 AsmToken newToken(AsmToken::String, StringRef(StrChar, EndChar - StrChar));
2513 FA.Value.push_back(newToken);
2514 } else if(parseMacroArgument(FA.Value, Vararg))
Michael Zuckerman56704612017-05-01 13:20:12 +00002515 return true;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002516
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002517 unsigned PI = Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002518 if (!FA.Name.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002519 unsigned FAI = 0;
2520 for (FAI = 0; FAI < NParameters; ++FAI)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002521 if (M->Parameters[FAI].Name == FA.Name)
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002522 break;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002523
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002524 if (FAI >= NParameters) {
Nirav Davefd910412016-06-17 16:06:17 +00002525 assert(M && "expected macro to be defined");
Nirav Dave2364748a2016-09-16 18:30:20 +00002526 return Error(IDLoc, "parameter named '" + FA.Name +
2527 "' does not exist for macro '" + M->Name + "'");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002528 }
2529 PI = FAI;
2530 }
2531
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002532 if (!FA.Value.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002533 if (A.size() <= PI)
2534 A.resize(PI + 1);
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002535 A[PI] = FA.Value;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002536
2537 if (FALocs.size() <= PI)
2538 FALocs.resize(PI + 1);
2539
2540 FALocs[PI] = Lexer.getLoc();
Preston Gurd242ed3152012-09-19 20:29:04 +00002541 }
Jim Grosbach206661622012-07-30 22:44:17 +00002542
Preston Gurd242ed3152012-09-19 20:29:04 +00002543 // At the end of the statement, fill in remaining arguments that have
2544 // default values. If there aren't any, then the next argument is
2545 // required but missing
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002546 if (Lexer.is(AsmToken::EndOfStatement)) {
2547 bool Failure = false;
2548 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2549 if (A[FAI].empty()) {
2550 if (M->Parameters[FAI].Required) {
2551 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2552 "missing value for required parameter "
2553 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2554 Failure = true;
2555 }
2556
2557 if (!M->Parameters[FAI].Value.empty())
2558 A[FAI] = M->Parameters[FAI].Value;
2559 }
2560 }
2561 return Failure;
2562 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002563
2564 if (Lexer.is(AsmToken::Comma))
2565 Lex();
2566 }
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002567
2568 return TokError("too many positional arguments");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002569}
2570
Jim Grosbach4b905842013-09-20 23:08:21 +00002571const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002572 StringMap<MCAsmMacro>::iterator I = MacroMap.find(Name);
2573 return (I == MacroMap.end()) ? nullptr : &I->getValue();
Eli Bendersky38274122013-01-14 23:22:36 +00002574}
2575
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002576void AsmParser::defineMacro(StringRef Name, MCAsmMacro Macro) {
2577 MacroMap.insert(std::make_pair(Name, std::move(Macro)));
Eli Bendersky38274122013-01-14 23:22:36 +00002578}
2579
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002580void AsmParser::undefineMacro(StringRef Name) { MacroMap.erase(Name); }
Eli Bendersky38274122013-01-14 23:22:36 +00002581
Jim Grosbach4b905842013-09-20 23:08:21 +00002582bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
Davide Italiano7c9fc732016-07-27 05:51:56 +00002583 // Arbitrarily limit macro nesting depth (default matches 'as'). We can
2584 // eliminate this, although we should protect against infinite loops.
2585 unsigned MaxNestingDepth = AsmMacroMaxNestingDepth;
2586 if (ActiveMacros.size() == MaxNestingDepth) {
2587 std::ostringstream MaxNestingDepthError;
2588 MaxNestingDepthError << "macros cannot be nested more than "
2589 << MaxNestingDepth << " levels deep."
2590 << " Use -asm-macro-max-nesting-depth to increase "
2591 "this limit.";
2592 return TokError(MaxNestingDepthError.str());
2593 }
Daniel Dunbar43235712010-07-18 18:54:11 +00002594
Eli Bendersky38274122013-01-14 23:22:36 +00002595 MCAsmMacroArguments A;
Jim Grosbach4b905842013-09-20 23:08:21 +00002596 if (parseMacroArguments(M, A))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002597 return true;
Daniel Dunbar43235712010-07-18 18:54:11 +00002598
Rafael Espindola1134ab232011-06-05 02:43:45 +00002599 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2600 // to hold the macro body with substitutions.
2601 SmallString<256> Buf;
2602 StringRef Body = M->Body;
Rafael Espindola34b9c512012-06-03 23:57:14 +00002603 raw_svector_ostream OS(Buf);
Rafael Espindola1134ab232011-06-05 02:43:45 +00002604
Toma Tabacu217116e2015-04-27 10:50:29 +00002605 if (expandMacro(OS, Body, M->Parameters, A, true, getTok().getLoc()))
Rafael Espindola1134ab232011-06-05 02:43:45 +00002606 return true;
2607
Eli Bendersky38274122013-01-14 23:22:36 +00002608 // We include the .endmacro in the buffer as our cue to exit the macro
Rafael Espindola34b9c512012-06-03 23:57:14 +00002609 // instantiation.
2610 OS << ".endmacro\n";
2611
Rafael Espindola3560ff22014-08-27 20:03:13 +00002612 std::unique_ptr<MemoryBuffer> Instantiation =
2613 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola1134ab232011-06-05 02:43:45 +00002614
Daniel Dunbar43235712010-07-18 18:54:11 +00002615 // Create the macro instantiation object and add to the current macro
2616 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002617 MacroInstantiation *MI = new MacroInstantiation(
2618 NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Daniel Dunbar43235712010-07-18 18:54:11 +00002619 ActiveMacros.push_back(MI);
2620
Toma Tabacu217116e2015-04-27 10:50:29 +00002621 ++NumOfMacroInstantiations;
2622
Daniel Dunbar43235712010-07-18 18:54:11 +00002623 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00002624 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00002625 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar43235712010-07-18 18:54:11 +00002626 Lex();
2627
2628 return false;
2629}
2630
Jim Grosbach4b905842013-09-20 23:08:21 +00002631void AsmParser::handleMacroExit() {
Daniel Dunbar43235712010-07-18 18:54:11 +00002632 // Jump to the EndOfStatement we should return to, and consume it.
Jim Grosbach4b905842013-09-20 23:08:21 +00002633 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
Daniel Dunbar43235712010-07-18 18:54:11 +00002634 Lex();
2635
2636 // Pop the instantiation entry.
2637 delete ActiveMacros.back();
2638 ActiveMacros.pop_back();
2639}
2640
Jim Grosbach4b905842013-09-20 23:08:21 +00002641bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
Jim Grosbachb7b750d2012-09-13 23:11:31 +00002642 bool NoDeadStrip) {
Pete Cooper80d21cb2015-06-22 19:35:57 +00002643 MCSymbol *Sym;
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002644 const MCExpr *Value;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002645 if (MCParserUtils::parseAssignmentExpression(Name, allow_redef, *this, Sym,
2646 Value))
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002647 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002648
Pete Cooper80d21cb2015-06-22 19:35:57 +00002649 if (!Sym) {
2650 // In the case where we parse an expression starting with a '.', we will
2651 // not generate an error, nor will we create a symbol. In this case we
2652 // should just return out.
Anders Waldenborg84809572014-02-17 20:48:32 +00002653 return false;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002654 }
David Majnemer58cb80c2014-12-24 10:27:50 +00002655
Daniel Dunbarae7ac012009-06-29 23:43:14 +00002656 // Do the assignment.
Daniel Dunbarb7b20972009-08-31 08:09:09 +00002657 Out.EmitAssignment(Sym, Value);
Jim Grosbachb7b750d2012-09-13 23:11:31 +00002658 if (NoDeadStrip)
2659 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2660
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002661 return false;
2662}
2663
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002664/// parseIdentifier:
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002665/// ::= identifier
2666/// ::= string
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002667bool AsmParser::parseIdentifier(StringRef &Res) {
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002668 // The assembler has relaxed rules for accepting identifiers, in particular we
Hans Wennborgce69d772013-10-18 20:46:28 +00002669 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2670 // separate tokens. At this level, we have already lexed so we cannot (currently)
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002671 // handle this as a context dependent token, instead we detect adjacent tokens
2672 // and return the combined identifier.
Hans Wennborgce69d772013-10-18 20:46:28 +00002673 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2674 SMLoc PrefixLoc = getLexer().getLoc();
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002675
Hans Wennborgce69d772013-10-18 20:46:28 +00002676 // Consume the prefix character, and check for a following identifier.
Nirav Daved0463322016-10-12 13:58:07 +00002677
2678 AsmToken Buf[1];
2679 Lexer.peekTokens(Buf, false);
2680
2681 if (Buf[0].isNot(AsmToken::Identifier))
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002682 return true;
2683
Hans Wennborgce69d772013-10-18 20:46:28 +00002684 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
Nirav Daved0463322016-10-12 13:58:07 +00002685 if (PrefixLoc.getPointer() + 1 != Buf[0].getLoc().getPointer())
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002686 return true;
2687
Nirav Daved0463322016-10-12 13:58:07 +00002688 // eat $ or @
2689 Lexer.Lex(); // Lexer's Lex guarantees consecutive token.
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002690 // Construct the joined identifier and consume the token.
Jim Grosbach4b905842013-09-20 23:08:21 +00002691 Res =
Hans Wennborgce69d772013-10-18 20:46:28 +00002692 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
Nirav Davefd910412016-06-17 16:06:17 +00002693 Lex(); // Parser Lex to maintain invariants.
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002694 return false;
2695 }
2696
Jim Grosbach4b905842013-09-20 23:08:21 +00002697 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002698 return true;
2699
Sean Callanan936b0d32010-01-19 21:44:56 +00002700 Res = getTok().getIdentifier();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002701
Sean Callanan686ed8d2010-01-19 20:22:31 +00002702 Lex(); // Consume the identifier token.
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002703
2704 return false;
2705}
2706
Jim Grosbach4b905842013-09-20 23:08:21 +00002707/// parseDirectiveSet:
Nico Weber4ada0d92011-01-28 03:04:41 +00002708/// ::= .equ identifier ',' expression
2709/// ::= .equiv identifier ',' expression
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002710/// ::= .set identifier ',' expression
Jim Grosbach4b905842013-09-20 23:08:21 +00002711bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002712 StringRef Name;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002713 if (check(parseIdentifier(Name), "expected identifier") ||
2714 parseToken(AsmToken::Comma) || parseAssignment(Name, allow_redef, true))
2715 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
2716 return false;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002717}
2718
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002719bool AsmParser::parseEscapedString(std::string &Data) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00002720 if (check(getTok().isNot(AsmToken::String), "expected string"))
2721 return true;
Daniel Dunbaref668c12009-08-14 18:19:52 +00002722
2723 Data = "";
Sean Callanan936b0d32010-01-19 21:44:56 +00002724 StringRef Str = getTok().getStringContents();
Daniel Dunbaref668c12009-08-14 18:19:52 +00002725 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2726 if (Str[i] != '\\') {
2727 Data += Str[i];
2728 continue;
2729 }
2730
2731 // Recognize escaped characters. Note that this escape semantics currently
2732 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2733 ++i;
2734 if (i == e)
2735 return TokError("unexpected backslash at end of string");
2736
2737 // Recognize octal sequences.
Jim Grosbach4b905842013-09-20 23:08:21 +00002738 if ((unsigned)(Str[i] - '0') <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002739 // Consume up to three octal characters.
2740 unsigned Value = Str[i] - '0';
2741
Jim Grosbach4b905842013-09-20 23:08:21 +00002742 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002743 ++i;
2744 Value = Value * 8 + (Str[i] - '0');
2745
Jim Grosbach4b905842013-09-20 23:08:21 +00002746 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002747 ++i;
2748 Value = Value * 8 + (Str[i] - '0');
2749 }
2750 }
2751
2752 if (Value > 255)
2753 return TokError("invalid octal escape sequence (out of range)");
2754
Jim Grosbach4b905842013-09-20 23:08:21 +00002755 Data += (unsigned char)Value;
Daniel Dunbaref668c12009-08-14 18:19:52 +00002756 continue;
2757 }
2758
2759 // Otherwise recognize individual escapes.
2760 switch (Str[i]) {
2761 default:
2762 // Just reject invalid escape sequences for now.
2763 return TokError("invalid escape sequence (unrecognized character)");
2764
2765 case 'b': Data += '\b'; break;
2766 case 'f': Data += '\f'; break;
2767 case 'n': Data += '\n'; break;
2768 case 'r': Data += '\r'; break;
2769 case 't': Data += '\t'; break;
2770 case '"': Data += '"'; break;
2771 case '\\': Data += '\\'; break;
2772 }
2773 }
2774
Nirav Davea645433c2016-07-18 15:24:03 +00002775 Lex();
Daniel Dunbaref668c12009-08-14 18:19:52 +00002776 return false;
2777}
2778
Jim Grosbach4b905842013-09-20 23:08:21 +00002779/// parseDirectiveAscii:
Rafael Espindola63760ba2010-10-28 20:02:27 +00002780/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002781bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00002782 auto parseOp = [&]() -> bool {
2783 std::string Data;
2784 if (checkForValidSection() || parseEscapedString(Data))
Nirav Davef43cc9f2016-10-10 15:24:54 +00002785 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002786 getStreamer().EmitBytes(Data);
2787 if (ZeroTerminated)
2788 getStreamer().EmitBytes(StringRef("\0", 1));
2789 return false;
2790 };
Daniel Dunbare5444a82010-09-09 22:42:59 +00002791
Nirav Dave1a9044b2016-10-24 14:35:29 +00002792 if (parseMany(parseOp))
2793 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbara10e5192009-06-24 23:30:00 +00002794 return false;
2795}
2796
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002797/// parseDirectiveReloc
2798/// ::= .reloc expression , identifier [ , expression ]
2799bool AsmParser::parseDirectiveReloc(SMLoc DirectiveLoc) {
2800 const MCExpr *Offset;
2801 const MCExpr *Expr = nullptr;
2802
2803 SMLoc OffsetLoc = Lexer.getTok().getLoc();
Nirav Dave1a9044b2016-10-24 14:35:29 +00002804 int64_t OffsetValue;
2805 // We can only deal with constant expressions at the moment.
2806
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002807 if (parseExpression(Offset))
2808 return true;
2809
Nirav Davea645433c2016-07-18 15:24:03 +00002810 if (check(!Offset->evaluateAsAbsolute(OffsetValue), OffsetLoc,
2811 "expression is not a constant value") ||
2812 check(OffsetValue < 0, OffsetLoc, "expression is negative") ||
2813 parseToken(AsmToken::Comma, "expected comma") ||
2814 check(getTok().isNot(AsmToken::Identifier), "expected relocation name"))
2815 return true;
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002816
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002817 SMLoc NameLoc = Lexer.getTok().getLoc();
2818 StringRef Name = Lexer.getTok().getIdentifier();
Nirav Davefd910412016-06-17 16:06:17 +00002819 Lex();
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002820
2821 if (Lexer.is(AsmToken::Comma)) {
Nirav Davefd910412016-06-17 16:06:17 +00002822 Lex();
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002823 SMLoc ExprLoc = Lexer.getLoc();
2824 if (parseExpression(Expr))
2825 return true;
2826
2827 MCValue Value;
2828 if (!Expr->evaluateAsRelocatable(Value, nullptr, nullptr))
2829 return Error(ExprLoc, "expression must be relocatable");
2830 }
2831
Nirav Davea645433c2016-07-18 15:24:03 +00002832 if (parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00002833 "unexpected token in .reloc directive"))
2834 return true;
2835
2836 if (getStreamer().EmitRelocDirective(*Offset, Name, Expr, DirectiveLoc))
2837 return Error(NameLoc, "unknown relocation name");
2838
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002839 return false;
2840}
2841
Jim Grosbach4b905842013-09-20 23:08:21 +00002842/// parseDirectiveValue
Daniel Dunbara10e5192009-06-24 23:30:00 +00002843/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00002844bool AsmParser::parseDirectiveValue(StringRef IDVal, unsigned Size) {
2845 auto parseOp = [&]() -> bool {
2846 const MCExpr *Value;
2847 SMLoc ExprLoc = getLexer().getLoc();
2848 if (checkForValidSection() || parseExpression(Value))
Nirav Davef43cc9f2016-10-10 15:24:54 +00002849 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002850 // Special case constant expressions to match code generator.
2851 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2852 assert(Size <= 8 && "Invalid size");
2853 uint64_t IntValue = MCE->getValue();
2854 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2855 return Error(ExprLoc, "out of range literal value");
2856 getStreamer().EmitIntValue(IntValue, Size);
2857 } else
2858 getStreamer().EmitValue(Value, Size, ExprLoc);
2859 return false;
2860 };
Daniel Dunbare5444a82010-09-09 22:42:59 +00002861
Nirav Dave1a9044b2016-10-24 14:35:29 +00002862 if (parseMany(parseOp))
2863 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbara10e5192009-06-24 23:30:00 +00002864 return false;
2865}
2866
David Woodhoused6de0d92014-02-01 16:20:59 +00002867/// ParseDirectiveOctaValue
2868/// ::= .octa [ hexconstant (, hexconstant)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00002869
2870bool AsmParser::parseDirectiveOctaValue(StringRef IDVal) {
2871 auto parseOp = [&]() -> bool {
Nirav Davef43cc9f2016-10-10 15:24:54 +00002872 if (checkForValidSection())
2873 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002874 if (getTok().isNot(AsmToken::Integer) && getTok().isNot(AsmToken::BigNum))
2875 return TokError("unknown token in expression");
2876 SMLoc ExprLoc = getTok().getLoc();
2877 APInt IntValue = getTok().getAPIntVal();
2878 uint64_t hi, lo;
2879 Lex();
2880 if (!IntValue.isIntN(128))
2881 return Error(ExprLoc, "out of range literal value");
2882 if (!IntValue.isIntN(64)) {
2883 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
2884 lo = IntValue.getLoBits(64).getZExtValue();
2885 } else {
2886 hi = 0;
2887 lo = IntValue.getZExtValue();
David Woodhoused6de0d92014-02-01 16:20:59 +00002888 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00002889 if (MAI.isLittleEndian()) {
2890 getStreamer().EmitIntValue(lo, 8);
2891 getStreamer().EmitIntValue(hi, 8);
2892 } else {
2893 getStreamer().EmitIntValue(hi, 8);
2894 getStreamer().EmitIntValue(lo, 8);
2895 }
2896 return false;
2897 };
David Woodhoused6de0d92014-02-01 16:20:59 +00002898
Nirav Dave1a9044b2016-10-24 14:35:29 +00002899 if (parseMany(parseOp))
2900 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
David Woodhoused6de0d92014-02-01 16:20:59 +00002901 return false;
2902}
2903
Petr Hosek4cb08ce2016-09-23 19:25:15 +00002904bool AsmParser::parseRealValue(const fltSemantics &Semantics, APInt &Res) {
2905 // We don't truly support arithmetic on floating point expressions, so we
2906 // have to manually parse unary prefixes.
2907 bool IsNeg = false;
2908 if (getLexer().is(AsmToken::Minus)) {
2909 Lexer.Lex();
2910 IsNeg = true;
2911 } else if (getLexer().is(AsmToken::Plus))
2912 Lexer.Lex();
2913
2914 if (Lexer.is(AsmToken::Error))
2915 return TokError(Lexer.getErr());
2916 if (Lexer.isNot(AsmToken::Integer) && Lexer.isNot(AsmToken::Real) &&
2917 Lexer.isNot(AsmToken::Identifier))
2918 return TokError("unexpected token in directive");
2919
2920 // Convert to an APFloat.
2921 APFloat Value(Semantics);
2922 StringRef IDVal = getTok().getString();
2923 if (getLexer().is(AsmToken::Identifier)) {
2924 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2925 Value = APFloat::getInf(Semantics);
2926 else if (!IDVal.compare_lower("nan"))
2927 Value = APFloat::getNaN(Semantics, false, ~0);
2928 else
2929 return TokError("invalid floating point literal");
2930 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2931 APFloat::opInvalidOp)
2932 return TokError("invalid floating point literal");
2933 if (IsNeg)
2934 Value.changeSign();
2935
2936 // Consume the numeric token.
2937 Lex();
2938
2939 Res = Value.bitcastToAPInt();
2940
2941 return false;
2942}
2943
Jim Grosbach4b905842013-09-20 23:08:21 +00002944/// parseDirectiveRealValue
Daniel Dunbar2af16532010-09-24 01:59:56 +00002945/// ::= (.single | .double) [ expression (, expression)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00002946bool AsmParser::parseDirectiveRealValue(StringRef IDVal,
2947 const fltSemantics &Semantics) {
2948 auto parseOp = [&]() -> bool {
2949 APInt AsInt;
2950 if (checkForValidSection() || parseRealValue(Semantics, AsInt))
Nirav Davef43cc9f2016-10-10 15:24:54 +00002951 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002952 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2953 AsInt.getBitWidth() / 8);
2954 return false;
2955 };
Daniel Dunbar2af16532010-09-24 01:59:56 +00002956
Nirav Dave1a9044b2016-10-24 14:35:29 +00002957 if (parseMany(parseOp))
2958 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbar2af16532010-09-24 01:59:56 +00002959 return false;
2960}
2961
Jim Grosbach4b905842013-09-20 23:08:21 +00002962/// parseDirectiveZero
Rafael Espindola922e3f42010-09-16 15:03:59 +00002963/// ::= .zero expression
Jim Grosbach4b905842013-09-20 23:08:21 +00002964bool AsmParser::parseDirectiveZero() {
Petr Hosek67a94a72016-05-28 05:57:48 +00002965 SMLoc NumBytesLoc = Lexer.getLoc();
2966 const MCExpr *NumBytes;
Nirav Davef43cc9f2016-10-10 15:24:54 +00002967 if (checkForValidSection() || parseExpression(NumBytes))
Rafael Espindola922e3f42010-09-16 15:03:59 +00002968 return true;
2969
Rafael Espindolab91bac62010-10-05 19:42:57 +00002970 int64_t Val = 0;
2971 if (getLexer().is(AsmToken::Comma)) {
2972 Lex();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002973 if (parseAbsoluteExpression(Val))
Rafael Espindolab91bac62010-10-05 19:42:57 +00002974 return true;
2975 }
2976
Nirav Davea645433c2016-07-18 15:24:03 +00002977 if (parseToken(AsmToken::EndOfStatement,
2978 "unexpected token in '.zero' directive"))
2979 return true;
Petr Hosek67a94a72016-05-28 05:57:48 +00002980 getStreamer().emitFill(*NumBytes, Val, NumBytesLoc);
Rafael Espindola922e3f42010-09-16 15:03:59 +00002981
2982 return false;
2983}
2984
Jim Grosbach4b905842013-09-20 23:08:21 +00002985/// parseDirectiveFill
Roman Divackye33098f2013-09-24 17:44:41 +00002986/// ::= .fill expression [ , expression [ , expression ] ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002987bool AsmParser::parseDirectiveFill() {
Petr Hosek67a94a72016-05-28 05:57:48 +00002988 SMLoc NumValuesLoc = Lexer.getLoc();
2989 const MCExpr *NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00002990 if (checkForValidSection() || parseExpression(NumValues))
Daniel Dunbara10e5192009-06-24 23:30:00 +00002991 return true;
2992
Roman Divackye33098f2013-09-24 17:44:41 +00002993 int64_t FillSize = 1;
2994 int64_t FillExpr = 0;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002995
David Majnemer522d3db2014-02-01 07:19:38 +00002996 SMLoc SizeLoc, ExprLoc;
Daniel Dunbara10e5192009-06-24 23:30:00 +00002997
Nirav Dave1a9044b2016-10-24 14:35:29 +00002998 if (parseOptionalToken(AsmToken::Comma)) {
2999 SizeLoc = getTok().getLoc();
3000 if (parseAbsoluteExpression(FillSize))
Roman Divackye33098f2013-09-24 17:44:41 +00003001 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003002 if (parseOptionalToken(AsmToken::Comma)) {
3003 ExprLoc = getTok().getLoc();
3004 if (parseAbsoluteExpression(FillExpr))
Roman Divackye33098f2013-09-24 17:44:41 +00003005 return true;
Roman Divackye33098f2013-09-24 17:44:41 +00003006 }
3007 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003008 if (parseToken(AsmToken::EndOfStatement,
3009 "unexpected token in '.fill' directive"))
3010 return true;
Daniel Dunbara10e5192009-06-24 23:30:00 +00003011
David Majnemer522d3db2014-02-01 07:19:38 +00003012 if (FillSize < 0) {
3013 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
Petr Hosek6abd38b2016-05-28 08:20:08 +00003014 return false;
David Majnemer522d3db2014-02-01 07:19:38 +00003015 }
3016 if (FillSize > 8) {
3017 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
3018 FillSize = 8;
3019 }
Daniel Dunbara10e5192009-06-24 23:30:00 +00003020
David Majnemer522d3db2014-02-01 07:19:38 +00003021 if (!isUInt<32>(FillExpr) && FillSize > 4)
3022 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
3023
Petr Hosek67a94a72016-05-28 05:57:48 +00003024 getStreamer().emitFill(*NumValues, FillSize, FillExpr, NumValuesLoc);
Daniel Dunbara10e5192009-06-24 23:30:00 +00003025
3026 return false;
3027}
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00003028
Jim Grosbach4b905842013-09-20 23:08:21 +00003029/// parseDirectiveOrg
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00003030/// ::= .org expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00003031bool AsmParser::parseDirectiveOrg() {
Daniel Dunbar897ffad2009-08-31 08:09:28 +00003032 const MCExpr *Offset;
Oliver Stannard268f42f2016-12-14 10:43:58 +00003033 SMLoc OffsetLoc = Lexer.getLoc();
Nirav Davef43cc9f2016-10-10 15:24:54 +00003034 if (checkForValidSection() || parseExpression(Offset))
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00003035 return true;
3036
3037 // Parse optional fill expression.
3038 int64_t FillExpr = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003039 if (parseOptionalToken(AsmToken::Comma))
3040 if (parseAbsoluteExpression(FillExpr))
3041 return addErrorSuffix(" in '.org' directive");
3042 if (parseToken(AsmToken::EndOfStatement))
3043 return addErrorSuffix(" in '.org' directive");
Nirav Davea645433c2016-07-18 15:24:03 +00003044
Oliver Stannard268f42f2016-12-14 10:43:58 +00003045 getStreamer().emitValueToOffset(Offset, FillExpr, OffsetLoc);
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00003046 return false;
3047}
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003048
Jim Grosbach4b905842013-09-20 23:08:21 +00003049/// parseDirectiveAlign
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003050/// ::= {.align, ...} expression [ , expression [ , expression ]]
Jim Grosbach4b905842013-09-20 23:08:21 +00003051bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003052 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003053 int64_t Alignment;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003054 SMLoc MaxBytesLoc;
3055 bool HasFillExpr = false;
3056 int64_t FillExpr = 0;
3057 int64_t MaxBytesToFill = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003058
3059 auto parseAlign = [&]() -> bool {
3060 if (checkForValidSection() || parseAbsoluteExpression(Alignment))
Nirav Davea645433c2016-07-18 15:24:03 +00003061 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003062 if (parseOptionalToken(AsmToken::Comma)) {
3063 // The fill expression can be omitted while specifying a maximum number of
3064 // alignment bytes, e.g:
3065 // .align 3,,4
3066 if (getTok().isNot(AsmToken::Comma)) {
3067 HasFillExpr = true;
3068 if (parseAbsoluteExpression(FillExpr))
3069 return true;
3070 }
3071 if (parseOptionalToken(AsmToken::Comma))
3072 if (parseTokenLoc(MaxBytesLoc) ||
3073 parseAbsoluteExpression(MaxBytesToFill))
3074 return true;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003075 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003076 return parseToken(AsmToken::EndOfStatement);
3077 };
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003078
Nirav Dave1a9044b2016-10-24 14:35:29 +00003079 if (parseAlign())
3080 return addErrorSuffix(" in directive");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003081
Nirav Dave2364748a2016-09-16 18:30:20 +00003082 // Always emit an alignment here even if we thrown an error.
3083 bool ReturnVal = false;
3084
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003085 // Compute alignment in bytes.
3086 if (IsPow2) {
3087 // FIXME: Diagnose overflow.
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003088 if (Alignment >= 32) {
Nirav Dave2364748a2016-09-16 18:30:20 +00003089 ReturnVal |= Error(AlignmentLoc, "invalid alignment value");
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003090 Alignment = 31;
3091 }
3092
Benjamin Kramer63951ad2009-09-06 09:35:10 +00003093 Alignment = 1ULL << Alignment;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00003094 } else {
Davide Italianocb2da712015-09-08 18:59:47 +00003095 // Reject alignments that aren't either a power of two or zero,
3096 // for gas compatibility. Alignment of zero is silently rounded
3097 // up to one.
3098 if (Alignment == 0)
3099 Alignment = 1;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00003100 if (!isPowerOf2_64(Alignment))
Nirav Dave2364748a2016-09-16 18:30:20 +00003101 ReturnVal |= Error(AlignmentLoc, "alignment must be a power of 2");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003102 }
3103
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003104 // Diagnose non-sensical max bytes to align.
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003105 if (MaxBytesLoc.isValid()) {
3106 if (MaxBytesToFill < 1) {
Nirav Dave2364748a2016-09-16 18:30:20 +00003107 ReturnVal |= Error(MaxBytesLoc,
3108 "alignment directive can never be satisfied in this "
Jim Grosbach4b905842013-09-20 23:08:21 +00003109 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar4abcccb2009-08-21 23:01:53 +00003110 MaxBytesToFill = 0;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003111 }
3112
3113 if (MaxBytesToFill >= Alignment) {
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +00003114 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
Jim Grosbach4b905842013-09-20 23:08:21 +00003115 "has no effect");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003116 MaxBytesToFill = 0;
3117 }
3118 }
3119
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003120 // Check whether we should use optimal code alignment for this .align
3121 // directive.
Eric Christopher445c9522016-10-14 05:47:37 +00003122 const MCSection *Section = getStreamer().getCurrentSectionOnly();
Saleem Abdulrasool7f2f9f42014-03-21 05:13:23 +00003123 assert(Section && "must have section to emit alignment");
3124 bool UseCodeAlign = Section->UseCodeAlign();
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003125 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
3126 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003127 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003128 } else {
Kevin Enderby7f993022010-02-25 18:46:04 +00003129 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnerc2b36752010-07-15 21:19:31 +00003130 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
3131 MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003132 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003133
Nirav Dave2364748a2016-09-16 18:30:20 +00003134 return ReturnVal;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003135}
3136
Jim Grosbach4b905842013-09-20 23:08:21 +00003137/// parseDirectiveFile
Eli Bendersky17233942013-01-15 22:59:42 +00003138/// ::= .file [number] filename
3139/// ::= .file number directory filename
Jim Grosbach4b905842013-09-20 23:08:21 +00003140bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003141 // FIXME: I'm not sure what this is.
3142 int64_t FileNumber = -1;
3143 SMLoc FileNumberLoc = getLexer().getLoc();
3144 if (getLexer().is(AsmToken::Integer)) {
3145 FileNumber = getTok().getIntVal();
3146 Lex();
3147
3148 if (FileNumber < 1)
3149 return TokError("file number less than one");
3150 }
3151
Nirav Davea645433c2016-07-18 15:24:03 +00003152 std::string Path = getTok().getString();
Eli Bendersky17233942013-01-15 22:59:42 +00003153
3154 // Usually the directory and filename together, otherwise just the directory.
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003155 // Allow the strings to have escaped octal character sequence.
Nirav Davea645433c2016-07-18 15:24:03 +00003156 if (check(getTok().isNot(AsmToken::String),
3157 "unexpected token in '.file' directive") ||
3158 parseEscapedString(Path))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003159 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003160
3161 StringRef Directory;
3162 StringRef Filename;
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003163 std::string FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00003164 if (getLexer().is(AsmToken::String)) {
Nirav Davea645433c2016-07-18 15:24:03 +00003165 if (check(FileNumber == -1,
3166 "explicit path specified, but no file number") ||
3167 parseEscapedString(FilenameData))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003168 return true;
3169 Filename = FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00003170 Directory = Path;
Eli Bendersky17233942013-01-15 22:59:42 +00003171 } else {
3172 Filename = Path;
3173 }
3174
Nirav Davea645433c2016-07-18 15:24:03 +00003175 if (parseToken(AsmToken::EndOfStatement,
3176 "unexpected token in '.file' directive"))
3177 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003178
3179 if (FileNumber == -1)
3180 getStreamer().EmitFileDirective(Filename);
3181 else {
David Blaikie22748082016-05-26 00:22:26 +00003182 // If there is -g option as well as debug info from directive file,
3183 // we turn off -g option, directly use the existing debug info instead.
David Blaikiedc3f01e2015-03-09 01:57:13 +00003184 if (getContext().getGenDwarfForAssembly())
David Blaikie22748082016-05-26 00:22:26 +00003185 getContext().setGenDwarfForAssembly(false);
3186 else if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename) ==
David Blaikiec714ef42014-03-17 01:52:11 +00003187 0)
Nirav Dave2364748a2016-09-16 18:30:20 +00003188 return Error(FileNumberLoc, "file number already allocated");
Eli Bendersky17233942013-01-15 22:59:42 +00003189 }
3190
3191 return false;
3192}
3193
Jim Grosbach4b905842013-09-20 23:08:21 +00003194/// parseDirectiveLine
Eli Bendersky17233942013-01-15 22:59:42 +00003195/// ::= .line [number]
Jim Grosbach4b905842013-09-20 23:08:21 +00003196bool AsmParser::parseDirectiveLine() {
Nirav Davea645433c2016-07-18 15:24:03 +00003197 int64_t LineNumber;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003198 if (getLexer().is(AsmToken::Integer)) {
Nirav Davea645433c2016-07-18 15:24:03 +00003199 if (parseIntToken(LineNumber, "unexpected token in '.line' directive"))
3200 return true;
Jim Grosbach4b905842013-09-20 23:08:21 +00003201 (void)LineNumber;
Eli Bendersky17233942013-01-15 22:59:42 +00003202 // FIXME: Do something with the .line.
3203 }
Nirav Davea645433c2016-07-18 15:24:03 +00003204 if (parseToken(AsmToken::EndOfStatement,
3205 "unexpected token in '.line' directive"))
3206 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003207
3208 return false;
3209}
3210
Jim Grosbach4b905842013-09-20 23:08:21 +00003211/// parseDirectiveLoc
Eli Bendersky17233942013-01-15 22:59:42 +00003212/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
3213/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
3214/// The first number is a file number, must have been previously assigned with
3215/// a .file directive, the second number is the line number and optionally the
3216/// third number is a column position (zero if not specified). The remaining
3217/// optional items are .loc sub-directives.
Jim Grosbach4b905842013-09-20 23:08:21 +00003218bool AsmParser::parseDirectiveLoc() {
Nirav Davea645433c2016-07-18 15:24:03 +00003219 int64_t FileNumber = 0, LineNumber = 0;
3220 SMLoc Loc = getTok().getLoc();
3221 if (parseIntToken(FileNumber, "unexpected token in '.loc' directive") ||
3222 check(FileNumber < 1, Loc,
3223 "file number less than one in '.loc' directive") ||
3224 check(!getContext().isValidDwarfFileNumber(FileNumber), Loc,
3225 "unassigned file number in '.loc' directive"))
3226 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003227
Nirav Davea645433c2016-07-18 15:24:03 +00003228 // optional
Eli Bendersky17233942013-01-15 22:59:42 +00003229 if (getLexer().is(AsmToken::Integer)) {
3230 LineNumber = getTok().getIntVal();
Adrian Prantl6ac40032013-09-26 23:37:11 +00003231 if (LineNumber < 0)
3232 return TokError("line number less than zero in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003233 Lex();
3234 }
3235
3236 int64_t ColumnPos = 0;
3237 if (getLexer().is(AsmToken::Integer)) {
3238 ColumnPos = getTok().getIntVal();
3239 if (ColumnPos < 0)
3240 return TokError("column position less than zero in '.loc' directive");
3241 Lex();
3242 }
3243
3244 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
3245 unsigned Isa = 0;
3246 int64_t Discriminator = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003247
Nirav Dave1a9044b2016-10-24 14:35:29 +00003248 auto parseLocOp = [&]() -> bool {
3249 StringRef Name;
3250 SMLoc Loc = getTok().getLoc();
3251 if (parseIdentifier(Name))
3252 return TokError("unexpected token in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003253
Nirav Dave1a9044b2016-10-24 14:35:29 +00003254 if (Name == "basic_block")
3255 Flags |= DWARF2_FLAG_BASIC_BLOCK;
3256 else if (Name == "prologue_end")
3257 Flags |= DWARF2_FLAG_PROLOGUE_END;
3258 else if (Name == "epilogue_begin")
3259 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
3260 else if (Name == "is_stmt") {
3261 Loc = getTok().getLoc();
3262 const MCExpr *Value;
3263 if (parseExpression(Value))
3264 return true;
3265 // The expression must be the constant 0 or 1.
3266 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3267 int Value = MCE->getValue();
3268 if (Value == 0)
3269 Flags &= ~DWARF2_FLAG_IS_STMT;
3270 else if (Value == 1)
3271 Flags |= DWARF2_FLAG_IS_STMT;
3272 else
3273 return Error(Loc, "is_stmt value not 0 or 1");
Craig Topperf15655b2013-04-22 04:22:40 +00003274 } else {
Nirav Dave1a9044b2016-10-24 14:35:29 +00003275 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
Eli Bendersky17233942013-01-15 22:59:42 +00003276 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003277 } else if (Name == "isa") {
3278 Loc = getTok().getLoc();
3279 const MCExpr *Value;
3280 if (parseExpression(Value))
3281 return true;
3282 // The expression must be a constant greater or equal to 0.
3283 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3284 int Value = MCE->getValue();
3285 if (Value < 0)
3286 return Error(Loc, "isa number less than zero");
3287 Isa = Value;
3288 } else {
3289 return Error(Loc, "isa number not a constant value");
3290 }
3291 } else if (Name == "discriminator") {
3292 if (parseAbsoluteExpression(Discriminator))
3293 return true;
3294 } else {
3295 return Error(Loc, "unknown sub-directive in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003296 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003297 return false;
3298 };
3299
Nirav Davee2369aa2016-10-26 17:28:58 +00003300 if (parseMany(parseLocOp, false /*hasComma*/))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003301 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003302
3303 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
3304 Isa, Discriminator, StringRef());
3305
3306 return false;
3307}
3308
Jim Grosbach4b905842013-09-20 23:08:21 +00003309/// parseDirectiveStabs
Eli Bendersky17233942013-01-15 22:59:42 +00003310/// ::= .stabs string, number, number, number
Jim Grosbach4b905842013-09-20 23:08:21 +00003311bool AsmParser::parseDirectiveStabs() {
Eli Bendersky17233942013-01-15 22:59:42 +00003312 return TokError("unsupported directive '.stabs'");
3313}
3314
Reid Kleckner2214ed82016-01-29 00:49:42 +00003315/// parseDirectiveCVFile
3316/// ::= .cv_file number filename
3317bool AsmParser::parseDirectiveCVFile() {
Nirav Davea645433c2016-07-18 15:24:03 +00003318 SMLoc FileNumberLoc = getTok().getLoc();
3319 int64_t FileNumber;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003320 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00003321
3322 if (parseIntToken(FileNumber,
3323 "expected file number in '.cv_file' directive") ||
3324 check(FileNumber < 1, FileNumberLoc, "file number less than one") ||
3325 check(getTok().isNot(AsmToken::String),
3326 "unexpected token in '.cv_file' directive") ||
3327 // Usually directory and filename are together, otherwise just
3328 // directory. Allow the strings to have escaped octal character sequence.
3329 parseEscapedString(Filename) ||
3330 parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00003331 "unexpected token in '.cv_file' directive"))
Reid Klecknera5b1eef2016-08-26 17:58:37 +00003332 return true;
Nirav Dave1ab71992016-07-18 19:35:21 +00003333
Reid Klecknera5b1eef2016-08-26 17:58:37 +00003334 if (!getStreamer().EmitCVFileDirective(FileNumber, Filename))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003335 return Error(FileNumberLoc, "file number already allocated");
Reid Kleckner2214ed82016-01-29 00:49:42 +00003336
3337 return false;
3338}
3339
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003340bool AsmParser::parseCVFunctionId(int64_t &FunctionId,
3341 StringRef DirectiveName) {
3342 SMLoc Loc;
3343 return parseTokenLoc(Loc) ||
3344 parseIntToken(FunctionId, "expected function id in '" + DirectiveName +
3345 "' directive") ||
3346 check(FunctionId < 0 || FunctionId >= UINT_MAX, Loc,
3347 "expected function id within range [0, UINT_MAX)");
3348}
3349
3350bool AsmParser::parseCVFileId(int64_t &FileNumber, StringRef DirectiveName) {
3351 SMLoc Loc;
3352 return parseTokenLoc(Loc) ||
3353 parseIntToken(FileNumber, "expected integer in '" + DirectiveName +
3354 "' directive") ||
3355 check(FileNumber < 1, Loc, "file number less than one in '" +
3356 DirectiveName + "' directive") ||
3357 check(!getCVContext().isValidFileNumber(FileNumber), Loc,
3358 "unassigned file number in '" + DirectiveName + "' directive");
3359}
3360
3361/// parseDirectiveCVFuncId
3362/// ::= .cv_func_id FunctionId
3363///
3364/// Introduces a function ID that can be used with .cv_loc.
3365bool AsmParser::parseDirectiveCVFuncId() {
3366 SMLoc FunctionIdLoc = getTok().getLoc();
3367 int64_t FunctionId;
3368
3369 if (parseCVFunctionId(FunctionId, ".cv_func_id") ||
3370 parseToken(AsmToken::EndOfStatement,
3371 "unexpected token in '.cv_func_id' directive"))
3372 return true;
3373
3374 if (!getStreamer().EmitCVFuncIdDirective(FunctionId))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003375 return Error(FunctionIdLoc, "function id already allocated");
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003376
3377 return false;
3378}
3379
3380/// parseDirectiveCVInlineSiteId
3381/// ::= .cv_inline_site_id FunctionId
3382/// "within" IAFunc
3383/// "inlined_at" IAFile IALine [IACol]
3384///
3385/// Introduces a function ID that can be used with .cv_loc. Includes "inlined
3386/// at" source location information for use in the line table of the caller,
3387/// whether the caller is a real function or another inlined call site.
3388bool AsmParser::parseDirectiveCVInlineSiteId() {
3389 SMLoc FunctionIdLoc = getTok().getLoc();
3390 int64_t FunctionId;
3391 int64_t IAFunc;
3392 int64_t IAFile;
3393 int64_t IALine;
3394 int64_t IACol = 0;
3395
3396 // FunctionId
3397 if (parseCVFunctionId(FunctionId, ".cv_inline_site_id"))
3398 return true;
3399
3400 // "within"
3401 if (check((getLexer().isNot(AsmToken::Identifier) ||
3402 getTok().getIdentifier() != "within"),
3403 "expected 'within' identifier in '.cv_inline_site_id' directive"))
3404 return true;
3405 Lex();
3406
3407 // IAFunc
3408 if (parseCVFunctionId(IAFunc, ".cv_inline_site_id"))
3409 return true;
3410
3411 // "inlined_at"
3412 if (check((getLexer().isNot(AsmToken::Identifier) ||
3413 getTok().getIdentifier() != "inlined_at"),
3414 "expected 'inlined_at' identifier in '.cv_inline_site_id' "
3415 "directive") )
3416 return true;
3417 Lex();
3418
3419 // IAFile IALine
3420 if (parseCVFileId(IAFile, ".cv_inline_site_id") ||
3421 parseIntToken(IALine, "expected line number after 'inlined_at'"))
3422 return true;
3423
3424 // [IACol]
3425 if (getLexer().is(AsmToken::Integer)) {
3426 IACol = getTok().getIntVal();
3427 Lex();
3428 }
3429
3430 if (parseToken(AsmToken::EndOfStatement,
3431 "unexpected token in '.cv_inline_site_id' directive"))
3432 return true;
3433
3434 if (!getStreamer().EmitCVInlineSiteIdDirective(FunctionId, IAFunc, IAFile,
3435 IALine, IACol, FunctionIdLoc))
Nirav Dave2364748a2016-09-16 18:30:20 +00003436 return Error(FunctionIdLoc, "function id already allocated");
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003437
3438 return false;
3439}
3440
Reid Kleckner2214ed82016-01-29 00:49:42 +00003441/// parseDirectiveCVLoc
3442/// ::= .cv_loc FunctionId FileNumber [LineNumber] [ColumnPos] [prologue_end]
3443/// [is_stmt VALUE]
3444/// The first number is a file number, must have been previously assigned with
3445/// a .file directive, the second number is the line number and optionally the
3446/// third number is a column position (zero if not specified). The remaining
3447/// optional items are .loc sub-directives.
3448bool AsmParser::parseDirectiveCVLoc() {
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003449 SMLoc DirectiveLoc = getTok().getLoc();
Nirav Davea645433c2016-07-18 15:24:03 +00003450 SMLoc Loc;
3451 int64_t FunctionId, FileNumber;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003452 if (parseCVFunctionId(FunctionId, ".cv_loc") ||
3453 parseCVFileId(FileNumber, ".cv_loc"))
Nirav Davea645433c2016-07-18 15:24:03 +00003454 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003455
3456 int64_t LineNumber = 0;
3457 if (getLexer().is(AsmToken::Integer)) {
3458 LineNumber = getTok().getIntVal();
3459 if (LineNumber < 0)
3460 return TokError("line number less than zero in '.cv_loc' directive");
3461 Lex();
3462 }
3463
3464 int64_t ColumnPos = 0;
3465 if (getLexer().is(AsmToken::Integer)) {
3466 ColumnPos = getTok().getIntVal();
3467 if (ColumnPos < 0)
3468 return TokError("column position less than zero in '.cv_loc' directive");
3469 Lex();
3470 }
3471
3472 bool PrologueEnd = false;
3473 uint64_t IsStmt = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003474
3475 auto parseOp = [&]() -> bool {
Reid Kleckner2214ed82016-01-29 00:49:42 +00003476 StringRef Name;
3477 SMLoc Loc = getTok().getLoc();
3478 if (parseIdentifier(Name))
3479 return TokError("unexpected token in '.cv_loc' directive");
Reid Kleckner2214ed82016-01-29 00:49:42 +00003480 if (Name == "prologue_end")
3481 PrologueEnd = true;
3482 else if (Name == "is_stmt") {
3483 Loc = getTok().getLoc();
3484 const MCExpr *Value;
3485 if (parseExpression(Value))
3486 return true;
3487 // The expression must be the constant 0 or 1.
3488 IsStmt = ~0ULL;
3489 if (const auto *MCE = dyn_cast<MCConstantExpr>(Value))
3490 IsStmt = MCE->getValue();
3491
3492 if (IsStmt > 1)
3493 return Error(Loc, "is_stmt value not 0 or 1");
3494 } else {
3495 return Error(Loc, "unknown sub-directive in '.cv_loc' directive");
3496 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003497 return false;
3498 };
3499
3500 if (parseMany(parseOp, false /*hasComma*/))
3501 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003502
3503 getStreamer().EmitCVLocDirective(FunctionId, FileNumber, LineNumber,
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003504 ColumnPos, PrologueEnd, IsStmt, StringRef(),
3505 DirectiveLoc);
Reid Kleckner2214ed82016-01-29 00:49:42 +00003506 return false;
3507}
3508
3509/// parseDirectiveCVLinetable
3510/// ::= .cv_linetable FunctionId, FnStart, FnEnd
3511bool AsmParser::parseDirectiveCVLinetable() {
Nirav Davea645433c2016-07-18 15:24:03 +00003512 int64_t FunctionId;
3513 StringRef FnStartName, FnEndName;
3514 SMLoc Loc = getTok().getLoc();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003515 if (parseCVFunctionId(FunctionId, ".cv_linetable") ||
Nirav Davea645433c2016-07-18 15:24:03 +00003516 parseToken(AsmToken::Comma,
3517 "unexpected token in '.cv_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003518 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3519 "expected identifier in directive") ||
Nirav Davea645433c2016-07-18 15:24:03 +00003520 parseToken(AsmToken::Comma,
3521 "unexpected token in '.cv_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003522 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3523 "expected identifier in directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00003524 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003525
3526 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3527 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
3528
3529 getStreamer().EmitCVLinetableDirective(FunctionId, FnStartSym, FnEndSym);
3530 return false;
3531}
3532
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003533/// parseDirectiveCVInlineLinetable
David Majnemerc9911f22016-02-02 19:22:34 +00003534/// ::= .cv_inline_linetable PrimaryFunctionId FileId LineNum FnStart FnEnd
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003535bool AsmParser::parseDirectiveCVInlineLinetable() {
Nirav Davea645433c2016-07-18 15:24:03 +00003536 int64_t PrimaryFunctionId, SourceFileId, SourceLineNum;
3537 StringRef FnStartName, FnEndName;
3538 SMLoc Loc = getTok().getLoc();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003539 if (parseCVFunctionId(PrimaryFunctionId, ".cv_inline_linetable") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003540 parseTokenLoc(Loc) ||
Nirav Davea645433c2016-07-18 15:24:03 +00003541 parseIntToken(
3542 SourceFileId,
3543 "expected SourceField in '.cv_inline_linetable' directive") ||
3544 check(SourceFileId <= 0, Loc,
3545 "File id less than zero in '.cv_inline_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003546 parseTokenLoc(Loc) ||
Nirav Davea645433c2016-07-18 15:24:03 +00003547 parseIntToken(
3548 SourceLineNum,
3549 "expected SourceLineNum in '.cv_inline_linetable' directive") ||
3550 check(SourceLineNum < 0, Loc,
3551 "Line number less than zero in '.cv_inline_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003552 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3553 "expected identifier in directive") ||
3554 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3555 "expected identifier in directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00003556 return true;
David Majnemerc9911f22016-02-02 19:22:34 +00003557
Nirav Davea645433c2016-07-18 15:24:03 +00003558 if (parseToken(AsmToken::EndOfStatement, "Expected End of Statement"))
3559 return true;
3560
3561 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3562 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
Reid Kleckner1fcd6102016-02-02 17:41:18 +00003563 getStreamer().EmitCVInlineLinetableDirective(PrimaryFunctionId, SourceFileId,
3564 SourceLineNum, FnStartSym,
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003565 FnEndSym);
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003566 return false;
3567}
3568
David Majnemer408b5e62016-02-05 01:55:49 +00003569/// parseDirectiveCVDefRange
3570/// ::= .cv_def_range RangeStart RangeEnd (GapStart GapEnd)*, bytes*
3571bool AsmParser::parseDirectiveCVDefRange() {
3572 SMLoc Loc;
3573 std::vector<std::pair<const MCSymbol *, const MCSymbol *>> Ranges;
3574 while (getLexer().is(AsmToken::Identifier)) {
3575 Loc = getLexer().getLoc();
3576 StringRef GapStartName;
3577 if (parseIdentifier(GapStartName))
3578 return Error(Loc, "expected identifier in directive");
3579 MCSymbol *GapStartSym = getContext().getOrCreateSymbol(GapStartName);
3580
3581 Loc = getLexer().getLoc();
3582 StringRef GapEndName;
3583 if (parseIdentifier(GapEndName))
3584 return Error(Loc, "expected identifier in directive");
3585 MCSymbol *GapEndSym = getContext().getOrCreateSymbol(GapEndName);
3586
3587 Ranges.push_back({GapStartSym, GapEndSym});
3588 }
3589
David Majnemer408b5e62016-02-05 01:55:49 +00003590 std::string FixedSizePortion;
Nirav Davea645433c2016-07-18 15:24:03 +00003591 if (parseToken(AsmToken::Comma, "unexpected token in directive") ||
3592 parseEscapedString(FixedSizePortion))
David Majnemer408b5e62016-02-05 01:55:49 +00003593 return true;
David Majnemer408b5e62016-02-05 01:55:49 +00003594
3595 getStreamer().EmitCVDefRangeDirective(Ranges, FixedSizePortion);
3596 return false;
3597}
3598
Reid Kleckner2214ed82016-01-29 00:49:42 +00003599/// parseDirectiveCVStringTable
3600/// ::= .cv_stringtable
3601bool AsmParser::parseDirectiveCVStringTable() {
3602 getStreamer().EmitCVStringTableDirective();
3603 return false;
3604}
3605
3606/// parseDirectiveCVFileChecksums
3607/// ::= .cv_filechecksums
3608bool AsmParser::parseDirectiveCVFileChecksums() {
3609 getStreamer().EmitCVFileChecksumsDirective();
3610 return false;
3611}
3612
Jim Grosbach4b905842013-09-20 23:08:21 +00003613/// parseDirectiveCFISections
Eli Bendersky17233942013-01-15 22:59:42 +00003614/// ::= .cfi_sections section [, section]
Jim Grosbach4b905842013-09-20 23:08:21 +00003615bool AsmParser::parseDirectiveCFISections() {
Eli Bendersky17233942013-01-15 22:59:42 +00003616 StringRef Name;
3617 bool EH = false;
3618 bool Debug = false;
3619
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003620 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003621 return TokError("Expected an identifier");
3622
3623 if (Name == ".eh_frame")
3624 EH = true;
3625 else if (Name == ".debug_frame")
3626 Debug = true;
3627
3628 if (getLexer().is(AsmToken::Comma)) {
3629 Lex();
3630
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003631 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003632 return TokError("Expected an identifier");
3633
3634 if (Name == ".eh_frame")
3635 EH = true;
3636 else if (Name == ".debug_frame")
3637 Debug = true;
3638 }
3639
3640 getStreamer().EmitCFISections(EH, Debug);
3641 return false;
3642}
3643
Jim Grosbach4b905842013-09-20 23:08:21 +00003644/// parseDirectiveCFIStartProc
David Majnemere035cf92014-01-27 17:20:25 +00003645/// ::= .cfi_startproc [simple]
Jim Grosbach4b905842013-09-20 23:08:21 +00003646bool AsmParser::parseDirectiveCFIStartProc() {
David Majnemere035cf92014-01-27 17:20:25 +00003647 StringRef Simple;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003648 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
3649 if (check(parseIdentifier(Simple) || Simple != "simple",
3650 "unexpected token") ||
3651 parseToken(AsmToken::EndOfStatement))
3652 return addErrorSuffix(" in '.cfi_startproc' directive");
3653 }
Nirav Davea645433c2016-07-18 15:24:03 +00003654
Oliver Stannardcf6bfb12014-11-03 12:19:03 +00003655 getStreamer().EmitCFIStartProc(!Simple.empty());
Eli Bendersky17233942013-01-15 22:59:42 +00003656 return false;
3657}
3658
Jim Grosbach4b905842013-09-20 23:08:21 +00003659/// parseDirectiveCFIEndProc
Eli Bendersky17233942013-01-15 22:59:42 +00003660/// ::= .cfi_endproc
Jim Grosbach4b905842013-09-20 23:08:21 +00003661bool AsmParser::parseDirectiveCFIEndProc() {
Eli Bendersky17233942013-01-15 22:59:42 +00003662 getStreamer().EmitCFIEndProc();
3663 return false;
3664}
3665
Jim Grosbach4b905842013-09-20 23:08:21 +00003666/// \brief parse register name or number.
3667bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
Eli Bendersky17233942013-01-15 22:59:42 +00003668 SMLoc DirectiveLoc) {
3669 unsigned RegNo;
3670
3671 if (getLexer().isNot(AsmToken::Integer)) {
3672 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
3673 return true;
Bill Wendlingbc07a892013-06-18 07:20:20 +00003674 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
Eli Bendersky17233942013-01-15 22:59:42 +00003675 } else
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003676 return parseAbsoluteExpression(Register);
Eli Bendersky17233942013-01-15 22:59:42 +00003677
3678 return false;
3679}
3680
Jim Grosbach4b905842013-09-20 23:08:21 +00003681/// parseDirectiveCFIDefCfa
Eli Bendersky17233942013-01-15 22:59:42 +00003682/// ::= .cfi_def_cfa register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003683bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003684 int64_t Register = 0, Offset = 0;
3685 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3686 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3687 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003688 return true;
3689
3690 getStreamer().EmitCFIDefCfa(Register, Offset);
3691 return false;
3692}
3693
Jim Grosbach4b905842013-09-20 23:08:21 +00003694/// parseDirectiveCFIDefCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003695/// ::= .cfi_def_cfa_offset offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003696bool AsmParser::parseDirectiveCFIDefCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00003697 int64_t Offset = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003698 if (parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003699 return true;
3700
3701 getStreamer().EmitCFIDefCfaOffset(Offset);
3702 return false;
3703}
3704
Jim Grosbach4b905842013-09-20 23:08:21 +00003705/// parseDirectiveCFIRegister
Eli Bendersky17233942013-01-15 22:59:42 +00003706/// ::= .cfi_register register, register
Jim Grosbach4b905842013-09-20 23:08:21 +00003707bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003708 int64_t Register1 = 0, Register2 = 0;
3709 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc) ||
3710 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3711 parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003712 return true;
3713
3714 getStreamer().EmitCFIRegister(Register1, Register2);
3715 return false;
3716}
3717
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00003718/// parseDirectiveCFIWindowSave
3719/// ::= .cfi_window_save
3720bool AsmParser::parseDirectiveCFIWindowSave() {
3721 getStreamer().EmitCFIWindowSave();
3722 return false;
3723}
3724
Jim Grosbach4b905842013-09-20 23:08:21 +00003725/// parseDirectiveCFIAdjustCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003726/// ::= .cfi_adjust_cfa_offset adjustment
Jim Grosbach4b905842013-09-20 23:08:21 +00003727bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00003728 int64_t Adjustment = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003729 if (parseAbsoluteExpression(Adjustment))
Eli Bendersky17233942013-01-15 22:59:42 +00003730 return true;
3731
3732 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3733 return false;
3734}
3735
Jim Grosbach4b905842013-09-20 23:08:21 +00003736/// parseDirectiveCFIDefCfaRegister
Eli Bendersky17233942013-01-15 22:59:42 +00003737/// ::= .cfi_def_cfa_register register
Jim Grosbach4b905842013-09-20 23:08:21 +00003738bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003739 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003740 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003741 return true;
3742
3743 getStreamer().EmitCFIDefCfaRegister(Register);
3744 return false;
3745}
3746
Jim Grosbach4b905842013-09-20 23:08:21 +00003747/// parseDirectiveCFIOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003748/// ::= .cfi_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003749bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003750 int64_t Register = 0;
3751 int64_t Offset = 0;
3752
Nirav Davea645433c2016-07-18 15:24:03 +00003753 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3754 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3755 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003756 return true;
3757
3758 getStreamer().EmitCFIOffset(Register, Offset);
3759 return false;
3760}
3761
Jim Grosbach4b905842013-09-20 23:08:21 +00003762/// parseDirectiveCFIRelOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003763/// ::= .cfi_rel_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003764bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003765 int64_t Register = 0, Offset = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003766
Nirav Davea645433c2016-07-18 15:24:03 +00003767 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3768 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3769 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003770 return true;
3771
3772 getStreamer().EmitCFIRelOffset(Register, Offset);
3773 return false;
3774}
3775
3776static bool isValidEncoding(int64_t Encoding) {
3777 if (Encoding & ~0xff)
3778 return false;
3779
3780 if (Encoding == dwarf::DW_EH_PE_omit)
3781 return true;
3782
3783 const unsigned Format = Encoding & 0xf;
3784 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3785 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3786 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3787 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3788 return false;
3789
3790 const unsigned Application = Encoding & 0x70;
3791 if (Application != dwarf::DW_EH_PE_absptr &&
3792 Application != dwarf::DW_EH_PE_pcrel)
3793 return false;
3794
3795 return true;
3796}
3797
Jim Grosbach4b905842013-09-20 23:08:21 +00003798/// parseDirectiveCFIPersonalityOrLsda
Eli Bendersky17233942013-01-15 22:59:42 +00003799/// IsPersonality true for cfi_personality, false for cfi_lsda
3800/// ::= .cfi_personality encoding, [symbol_name]
3801/// ::= .cfi_lsda encoding, [symbol_name]
Jim Grosbach4b905842013-09-20 23:08:21 +00003802bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
Eli Bendersky17233942013-01-15 22:59:42 +00003803 int64_t Encoding = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003804 if (parseAbsoluteExpression(Encoding))
Eli Bendersky17233942013-01-15 22:59:42 +00003805 return true;
3806 if (Encoding == dwarf::DW_EH_PE_omit)
3807 return false;
3808
Eli Bendersky17233942013-01-15 22:59:42 +00003809 StringRef Name;
Nirav Davea645433c2016-07-18 15:24:03 +00003810 if (check(!isValidEncoding(Encoding), "unsupported encoding.") ||
3811 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3812 check(parseIdentifier(Name), "expected identifier in directive"))
3813 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003814
Jim Grosbach6f482002015-05-18 18:43:14 +00003815 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Eli Bendersky17233942013-01-15 22:59:42 +00003816
3817 if (IsPersonality)
3818 getStreamer().EmitCFIPersonality(Sym, Encoding);
3819 else
3820 getStreamer().EmitCFILsda(Sym, Encoding);
3821 return false;
3822}
3823
Jim Grosbach4b905842013-09-20 23:08:21 +00003824/// parseDirectiveCFIRememberState
Eli Bendersky17233942013-01-15 22:59:42 +00003825/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00003826bool AsmParser::parseDirectiveCFIRememberState() {
Eli Bendersky17233942013-01-15 22:59:42 +00003827 getStreamer().EmitCFIRememberState();
3828 return false;
3829}
3830
Jim Grosbach4b905842013-09-20 23:08:21 +00003831/// parseDirectiveCFIRestoreState
Eli Bendersky17233942013-01-15 22:59:42 +00003832/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00003833bool AsmParser::parseDirectiveCFIRestoreState() {
Eli Bendersky17233942013-01-15 22:59:42 +00003834 getStreamer().EmitCFIRestoreState();
3835 return false;
3836}
3837
Jim Grosbach4b905842013-09-20 23:08:21 +00003838/// parseDirectiveCFISameValue
Eli Bendersky17233942013-01-15 22:59:42 +00003839/// ::= .cfi_same_value register
Jim Grosbach4b905842013-09-20 23:08:21 +00003840bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003841 int64_t Register = 0;
3842
Jim Grosbach4b905842013-09-20 23:08:21 +00003843 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003844 return true;
3845
3846 getStreamer().EmitCFISameValue(Register);
3847 return false;
3848}
3849
Jim Grosbach4b905842013-09-20 23:08:21 +00003850/// parseDirectiveCFIRestore
Eli Bendersky17233942013-01-15 22:59:42 +00003851/// ::= .cfi_restore register
Jim Grosbach4b905842013-09-20 23:08:21 +00003852bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003853 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003854 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003855 return true;
3856
3857 getStreamer().EmitCFIRestore(Register);
3858 return false;
3859}
3860
Jim Grosbach4b905842013-09-20 23:08:21 +00003861/// parseDirectiveCFIEscape
Eli Bendersky17233942013-01-15 22:59:42 +00003862/// ::= .cfi_escape expression[,...]
Jim Grosbach4b905842013-09-20 23:08:21 +00003863bool AsmParser::parseDirectiveCFIEscape() {
Eli Bendersky17233942013-01-15 22:59:42 +00003864 std::string Values;
3865 int64_t CurrValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003866 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00003867 return true;
3868
3869 Values.push_back((uint8_t)CurrValue);
3870
3871 while (getLexer().is(AsmToken::Comma)) {
3872 Lex();
3873
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003874 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00003875 return true;
3876
3877 Values.push_back((uint8_t)CurrValue);
3878 }
3879
3880 getStreamer().EmitCFIEscape(Values);
3881 return false;
3882}
3883
Jim Grosbach4b905842013-09-20 23:08:21 +00003884/// parseDirectiveCFISignalFrame
Eli Bendersky17233942013-01-15 22:59:42 +00003885/// ::= .cfi_signal_frame
Jim Grosbach4b905842013-09-20 23:08:21 +00003886bool AsmParser::parseDirectiveCFISignalFrame() {
Nirav Davea645433c2016-07-18 15:24:03 +00003887 if (parseToken(AsmToken::EndOfStatement,
3888 "unexpected token in '.cfi_signal_frame'"))
3889 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003890
3891 getStreamer().EmitCFISignalFrame();
3892 return false;
3893}
3894
Jim Grosbach4b905842013-09-20 23:08:21 +00003895/// parseDirectiveCFIUndefined
Eli Bendersky17233942013-01-15 22:59:42 +00003896/// ::= .cfi_undefined register
Jim Grosbach4b905842013-09-20 23:08:21 +00003897bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003898 int64_t Register = 0;
3899
Jim Grosbach4b905842013-09-20 23:08:21 +00003900 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003901 return true;
3902
3903 getStreamer().EmitCFIUndefined(Register);
3904 return false;
3905}
3906
Michael Zuckerman56704612017-05-01 13:20:12 +00003907/// parseDirectiveAltmacro
3908/// ::= .altmacro
3909/// ::= .noaltmacro
3910bool AsmParser::parseDirectiveAltmacro(StringRef Directive) {
3911 if (getLexer().isNot(AsmToken::EndOfStatement))
3912 return TokError("unexpected token in '" + Directive + "' directive");
3913 if (Directive == ".altmacro")
3914 getLexer().SetAltMacroMode(true);
3915 else
3916 getLexer().SetAltMacroMode(false);
3917 return false;
3918}
3919
Jim Grosbach4b905842013-09-20 23:08:21 +00003920/// parseDirectiveMacrosOnOff
Eli Bendersky17233942013-01-15 22:59:42 +00003921/// ::= .macros_on
3922/// ::= .macros_off
Jim Grosbach4b905842013-09-20 23:08:21 +00003923bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
Nirav Davea645433c2016-07-18 15:24:03 +00003924 if (parseToken(AsmToken::EndOfStatement,
3925 "unexpected token in '" + Directive + "' directive"))
3926 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003927
Jim Grosbach4b905842013-09-20 23:08:21 +00003928 setMacrosEnabled(Directive == ".macros_on");
Eli Bendersky17233942013-01-15 22:59:42 +00003929 return false;
3930}
3931
Jim Grosbach4b905842013-09-20 23:08:21 +00003932/// parseDirectiveMacro
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00003933/// ::= .macro name[,] [parameters]
Jim Grosbach4b905842013-09-20 23:08:21 +00003934bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003935 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003936 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003937 return TokError("expected identifier in '.macro' directive");
3938
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00003939 if (getLexer().is(AsmToken::Comma))
3940 Lex();
3941
Eli Bendersky17233942013-01-15 22:59:42 +00003942 MCAsmMacroParameters Parameters;
David Majnemer91fc4c22014-01-29 18:57:46 +00003943 while (getLexer().isNot(AsmToken::EndOfStatement)) {
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003944
Alexander Kornienko8c0809c2015-01-15 11:41:30 +00003945 if (!Parameters.empty() && Parameters.back().Vararg)
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003946 return Error(Lexer.getLoc(),
3947 "Vararg parameter '" + Parameters.back().Name +
3948 "' should be last one in the list of parameters.");
3949
David Majnemer91fc4c22014-01-29 18:57:46 +00003950 MCAsmMacroParameter Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00003951 if (parseIdentifier(Parameter.Name))
David Majnemer91fc4c22014-01-29 18:57:46 +00003952 return TokError("expected identifier in '.macro' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003953
Coby Tayreebedaae02017-04-08 20:29:03 +00003954 // Emit an error if two (or more) named parameters share the same name
3955 for (const MCAsmMacroParameter& CurrParam : Parameters)
3956 if (CurrParam.Name.equals(Parameter.Name))
3957 return TokError("macro '" + Name + "' has multiple parameters"
3958 " named '" + Parameter.Name + "'");
3959
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003960 if (Lexer.is(AsmToken::Colon)) {
3961 Lex(); // consume ':'
3962
3963 SMLoc QualLoc;
3964 StringRef Qualifier;
3965
3966 QualLoc = Lexer.getLoc();
3967 if (parseIdentifier(Qualifier))
3968 return Error(QualLoc, "missing parameter qualifier for "
3969 "'" + Parameter.Name + "' in macro '" + Name + "'");
3970
3971 if (Qualifier == "req")
3972 Parameter.Required = true;
Kevin Enderbye3c13462014-08-04 23:14:37 +00003973 else if (Qualifier == "vararg")
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003974 Parameter.Vararg = true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003975 else
3976 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
3977 "for '" + Parameter.Name + "' in macro '" + Name + "'");
3978 }
3979
David Majnemer91fc4c22014-01-29 18:57:46 +00003980 if (getLexer().is(AsmToken::Equal)) {
3981 Lex();
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003982
3983 SMLoc ParamLoc;
3984
3985 ParamLoc = Lexer.getLoc();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003986 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
David Majnemer91fc4c22014-01-29 18:57:46 +00003987 return true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003988
3989 if (Parameter.Required)
3990 Warning(ParamLoc, "pointless default value for required parameter "
3991 "'" + Parameter.Name + "' in macro '" + Name + "'");
Eli Bendersky17233942013-01-15 22:59:42 +00003992 }
David Majnemer91fc4c22014-01-29 18:57:46 +00003993
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00003994 Parameters.push_back(std::move(Parameter));
David Majnemer91fc4c22014-01-29 18:57:46 +00003995
3996 if (getLexer().is(AsmToken::Comma))
3997 Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00003998 }
3999
Nirav Dave1180e6892016-06-02 17:15:05 +00004000 // Eat just the end of statement.
4001 Lexer.Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00004002
Nirav Dave1180e6892016-06-02 17:15:05 +00004003 // Consuming deferred text, so use Lexer.Lex to ignore Lexing Errors
Eli Bendersky17233942013-01-15 22:59:42 +00004004 AsmToken EndToken, StartToken = getTok();
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00004005 unsigned MacroDepth = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00004006 // Lex the macro definition.
Eugene Zelenko33d7b762016-08-23 17:14:32 +00004007 while (true) {
Nirav Dave1180e6892016-06-02 17:15:05 +00004008 // Ignore Lexing errors in macros.
4009 while (Lexer.is(AsmToken::Error)) {
4010 Lexer.Lex();
4011 }
4012
Eli Bendersky17233942013-01-15 22:59:42 +00004013 // Check whether we have reached the end of the file.
4014 if (getLexer().is(AsmToken::Eof))
4015 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
4016
4017 // Otherwise, check whether we have reach the .endmacro.
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00004018 if (getLexer().is(AsmToken::Identifier)) {
4019 if (getTok().getIdentifier() == ".endm" ||
4020 getTok().getIdentifier() == ".endmacro") {
4021 if (MacroDepth == 0) { // Outermost macro.
4022 EndToken = getTok();
Nirav Dave1180e6892016-06-02 17:15:05 +00004023 Lexer.Lex();
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00004024 if (getLexer().isNot(AsmToken::EndOfStatement))
4025 return TokError("unexpected token in '" + EndToken.getIdentifier() +
4026 "' directive");
4027 break;
4028 } else {
4029 // Otherwise we just found the end of an inner macro.
4030 --MacroDepth;
4031 }
4032 } else if (getTok().getIdentifier() == ".macro") {
4033 // We allow nested macros. Those aren't instantiated until the outermost
4034 // macro is expanded so just ignore them for now.
4035 ++MacroDepth;
4036 }
Eli Bendersky17233942013-01-15 22:59:42 +00004037 }
4038
4039 // Otherwise, scan til the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004040 eatToEndOfStatement();
Eli Bendersky17233942013-01-15 22:59:42 +00004041 }
4042
Jim Grosbach4b905842013-09-20 23:08:21 +00004043 if (lookupMacro(Name)) {
Eli Bendersky17233942013-01-15 22:59:42 +00004044 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
4045 }
4046
4047 const char *BodyStart = StartToken.getLoc().getPointer();
4048 const char *BodyEnd = EndToken.getLoc().getPointer();
4049 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Jim Grosbach4b905842013-09-20 23:08:21 +00004050 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00004051 defineMacro(Name, MCAsmMacro(Name, Body, std::move(Parameters)));
Eli Bendersky17233942013-01-15 22:59:42 +00004052 return false;
4053}
4054
Jim Grosbach4b905842013-09-20 23:08:21 +00004055/// checkForBadMacro
Kevin Enderby81c944c2013-01-22 21:44:53 +00004056///
4057/// With the support added for named parameters there may be code out there that
4058/// is transitioning from positional parameters. In versions of gas that did
Alp Tokercb402912014-01-24 17:20:08 +00004059/// not support named parameters they would be ignored on the macro definition.
Kevin Enderby81c944c2013-01-22 21:44:53 +00004060/// But to support both styles of parameters this is not possible so if a macro
Alp Tokercb402912014-01-24 17:20:08 +00004061/// definition has named parameters but does not use them and has what appears
Kevin Enderby81c944c2013-01-22 21:44:53 +00004062/// to be positional parameters, strings like $1, $2, ... and $n, then issue a
4063/// warning that the positional parameter found in body which have no effect.
4064/// Hoping the developer will either remove the named parameters from the macro
Alp Tokercb402912014-01-24 17:20:08 +00004065/// definition so the positional parameters get used if that was what was
Kevin Enderby81c944c2013-01-22 21:44:53 +00004066/// intended or change the macro to use the named parameters. It is possible
4067/// this warning will trigger when the none of the named parameters are used
4068/// and the strings like $1 are infact to simply to be passed trough unchanged.
Jim Grosbach4b905842013-09-20 23:08:21 +00004069void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
Kevin Enderby81c944c2013-01-22 21:44:53 +00004070 StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00004071 ArrayRef<MCAsmMacroParameter> Parameters) {
Kevin Enderby81c944c2013-01-22 21:44:53 +00004072 // If this macro is not defined with named parameters the warning we are
4073 // checking for here doesn't apply.
4074 unsigned NParameters = Parameters.size();
4075 if (NParameters == 0)
4076 return;
4077
4078 bool NamedParametersFound = false;
4079 bool PositionalParametersFound = false;
4080
4081 // Look at the body of the macro for use of both the named parameters and what
4082 // are likely to be positional parameters. This is what expandMacro() is
4083 // doing when it finds the parameters in the body.
4084 while (!Body.empty()) {
4085 // Scan for the next possible parameter.
4086 std::size_t End = Body.size(), Pos = 0;
4087 for (; Pos != End; ++Pos) {
4088 // Check for a substitution or escape.
4089 // This macro is defined with parameters, look for \foo, \bar, etc.
4090 if (Body[Pos] == '\\' && Pos + 1 != End)
4091 break;
4092
4093 // This macro should have parameters, but look for $0, $1, ..., $n too.
4094 if (Body[Pos] != '$' || Pos + 1 == End)
4095 continue;
4096 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00004097 if (Next == '$' || Next == 'n' ||
4098 isdigit(static_cast<unsigned char>(Next)))
Kevin Enderby81c944c2013-01-22 21:44:53 +00004099 break;
4100 }
4101
4102 // Check if we reached the end.
4103 if (Pos == End)
4104 break;
4105
4106 if (Body[Pos] == '$') {
Jim Grosbach4b905842013-09-20 23:08:21 +00004107 switch (Body[Pos + 1]) {
4108 // $$ => $
Kevin Enderby81c944c2013-01-22 21:44:53 +00004109 case '$':
4110 break;
4111
Jim Grosbach4b905842013-09-20 23:08:21 +00004112 // $n => number of arguments
Kevin Enderby81c944c2013-01-22 21:44:53 +00004113 case 'n':
4114 PositionalParametersFound = true;
4115 break;
4116
Jim Grosbach4b905842013-09-20 23:08:21 +00004117 // $[0-9] => argument
Kevin Enderby81c944c2013-01-22 21:44:53 +00004118 default: {
4119 PositionalParametersFound = true;
4120 break;
Jim Grosbach4b905842013-09-20 23:08:21 +00004121 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00004122 }
4123 Pos += 2;
4124 } else {
4125 unsigned I = Pos + 1;
4126 while (isIdentifierChar(Body[I]) && I + 1 != End)
4127 ++I;
4128
Jim Grosbach4b905842013-09-20 23:08:21 +00004129 const char *Begin = Body.data() + Pos + 1;
4130 StringRef Argument(Begin, I - (Pos + 1));
Kevin Enderby81c944c2013-01-22 21:44:53 +00004131 unsigned Index = 0;
4132 for (; Index < NParameters; ++Index)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00004133 if (Parameters[Index].Name == Argument)
Kevin Enderby81c944c2013-01-22 21:44:53 +00004134 break;
4135
4136 if (Index == NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00004137 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
4138 Pos += 3;
4139 else {
4140 Pos = I;
4141 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00004142 } else {
4143 NamedParametersFound = true;
4144 Pos += 1 + Argument.size();
4145 }
4146 }
4147 // Update the scan point.
4148 Body = Body.substr(Pos);
4149 }
4150
4151 if (!NamedParametersFound && PositionalParametersFound)
4152 Warning(DirectiveLoc, "macro defined with named parameters which are not "
4153 "used in macro body, possible positional parameter "
4154 "found in body which will have no effect");
4155}
4156
Nico Weber155dccd12014-07-24 17:08:39 +00004157/// parseDirectiveExitMacro
4158/// ::= .exitm
4159bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
Nirav Davea645433c2016-07-18 15:24:03 +00004160 if (parseToken(AsmToken::EndOfStatement,
4161 "unexpected token in '" + Directive + "' directive"))
4162 return true;
Nico Weber155dccd12014-07-24 17:08:39 +00004163
4164 if (!isInsideMacroInstantiation())
4165 return TokError("unexpected '" + Directive + "' in file, "
4166 "no current macro definition");
4167
4168 // Exit all conditionals that are active in the current macro.
4169 while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
4170 TheCondState = TheCondStack.back();
4171 TheCondStack.pop_back();
4172 }
4173
4174 handleMacroExit();
4175 return false;
4176}
4177
Jim Grosbach4b905842013-09-20 23:08:21 +00004178/// parseDirectiveEndMacro
Eli Bendersky17233942013-01-15 22:59:42 +00004179/// ::= .endm
4180/// ::= .endmacro
Jim Grosbach4b905842013-09-20 23:08:21 +00004181bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
Eli Bendersky17233942013-01-15 22:59:42 +00004182 if (getLexer().isNot(AsmToken::EndOfStatement))
4183 return TokError("unexpected token in '" + Directive + "' directive");
4184
4185 // If we are inside a macro instantiation, terminate the current
4186 // instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00004187 if (isInsideMacroInstantiation()) {
4188 handleMacroExit();
Eli Bendersky17233942013-01-15 22:59:42 +00004189 return false;
4190 }
4191
4192 // Otherwise, this .endmacro is a stray entry in the file; well formed
4193 // .endmacro directives are handled during the macro definition parsing.
4194 return TokError("unexpected '" + Directive + "' in file, "
Jim Grosbach4b905842013-09-20 23:08:21 +00004195 "no current macro definition");
Eli Bendersky17233942013-01-15 22:59:42 +00004196}
4197
Jim Grosbach4b905842013-09-20 23:08:21 +00004198/// parseDirectivePurgeMacro
Eli Bendersky17233942013-01-15 22:59:42 +00004199/// ::= .purgem
Jim Grosbach4b905842013-09-20 23:08:21 +00004200bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004201 StringRef Name;
Nirav Davea645433c2016-07-18 15:24:03 +00004202 SMLoc Loc;
Nirav Daved8858ca2016-08-30 14:15:43 +00004203 if (parseTokenLoc(Loc) ||
4204 check(parseIdentifier(Name), Loc,
4205 "expected identifier in '.purgem' directive") ||
Nirav Davea645433c2016-07-18 15:24:03 +00004206 parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00004207 "unexpected token in '.purgem' directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00004208 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004209
Nirav Dave1ab71992016-07-18 19:35:21 +00004210 if (!lookupMacro(Name))
4211 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
4212
Jim Grosbach4b905842013-09-20 23:08:21 +00004213 undefineMacro(Name);
Eli Bendersky17233942013-01-15 22:59:42 +00004214 return false;
4215}
Eli Benderskyf483ff92012-12-20 19:05:53 +00004216
Jim Grosbach4b905842013-09-20 23:08:21 +00004217/// parseDirectiveBundleAlignMode
Eli Benderskyf483ff92012-12-20 19:05:53 +00004218/// ::= {.bundle_align_mode} expression
Jim Grosbach4b905842013-09-20 23:08:21 +00004219bool AsmParser::parseDirectiveBundleAlignMode() {
Eli Benderskyf483ff92012-12-20 19:05:53 +00004220 // Expect a single argument: an expression that evaluates to a constant
4221 // in the inclusive range 0-30.
4222 SMLoc ExprLoc = getLexer().getLoc();
4223 int64_t AlignSizePow2;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004224 if (checkForValidSection() || parseAbsoluteExpression(AlignSizePow2) ||
Nirav Davea645433c2016-07-18 15:24:03 +00004225 parseToken(AsmToken::EndOfStatement, "unexpected token after expression "
4226 "in '.bundle_align_mode' "
4227 "directive") ||
4228 check(AlignSizePow2 < 0 || AlignSizePow2 > 30, ExprLoc,
4229 "invalid bundle alignment size (expected between 0 and 30)"))
Eli Benderskyf483ff92012-12-20 19:05:53 +00004230 return true;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004231
4232 // Because of AlignSizePow2's verified range we can safely truncate it to
4233 // unsigned.
4234 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
4235 return false;
4236}
4237
Jim Grosbach4b905842013-09-20 23:08:21 +00004238/// parseDirectiveBundleLock
Eli Bendersky802b6282013-01-07 21:51:08 +00004239/// ::= {.bundle_lock} [align_to_end]
Jim Grosbach4b905842013-09-20 23:08:21 +00004240bool AsmParser::parseDirectiveBundleLock() {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004241 if (checkForValidSection())
4242 return true;
Eli Bendersky802b6282013-01-07 21:51:08 +00004243 bool AlignToEnd = false;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004244
Nirav Dave1a9044b2016-10-24 14:35:29 +00004245 StringRef Option;
4246 SMLoc Loc = getTok().getLoc();
4247 const char *kInvalidOptionError =
4248 "invalid option for '.bundle_lock' directive";
Eli Bendersky802b6282013-01-07 21:51:08 +00004249
Nirav Dave1a9044b2016-10-24 14:35:29 +00004250 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
Nirav Davea645433c2016-07-18 15:24:03 +00004251 if (check(parseIdentifier(Option), Loc, kInvalidOptionError) ||
4252 check(Option != "align_to_end", Loc, kInvalidOptionError) ||
Nirav Dave1a9044b2016-10-24 14:35:29 +00004253 parseToken(AsmToken::EndOfStatement,
4254 "unexpected token after '.bundle_lock' directive option"))
Nirav Davea645433c2016-07-18 15:24:03 +00004255 return true;
Eli Bendersky802b6282013-01-07 21:51:08 +00004256 AlignToEnd = true;
4257 }
4258
Eli Bendersky802b6282013-01-07 21:51:08 +00004259 getStreamer().EmitBundleLock(AlignToEnd);
Eli Benderskyf483ff92012-12-20 19:05:53 +00004260 return false;
4261}
4262
Jim Grosbach4b905842013-09-20 23:08:21 +00004263/// parseDirectiveBundleLock
Eli Benderskyf483ff92012-12-20 19:05:53 +00004264/// ::= {.bundle_lock}
Jim Grosbach4b905842013-09-20 23:08:21 +00004265bool AsmParser::parseDirectiveBundleUnlock() {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004266 if (checkForValidSection() ||
4267 parseToken(AsmToken::EndOfStatement,
Nirav Davea645433c2016-07-18 15:24:03 +00004268 "unexpected token in '.bundle_unlock' directive"))
4269 return true;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004270
4271 getStreamer().EmitBundleUnlock();
4272 return false;
4273}
4274
Jim Grosbach4b905842013-09-20 23:08:21 +00004275/// parseDirectiveSpace
Eli Bendersky17233942013-01-15 22:59:42 +00004276/// ::= (.skip | .space) expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004277bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
Petr Hosek67a94a72016-05-28 05:57:48 +00004278 SMLoc NumBytesLoc = Lexer.getLoc();
4279 const MCExpr *NumBytes;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004280 if (checkForValidSection() || parseExpression(NumBytes))
Eli Bendersky17233942013-01-15 22:59:42 +00004281 return true;
4282
4283 int64_t FillExpr = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00004284 if (parseOptionalToken(AsmToken::Comma))
4285 if (parseAbsoluteExpression(FillExpr))
4286 return addErrorSuffix("in '" + Twine(IDVal) + "' directive");
4287 if (parseToken(AsmToken::EndOfStatement))
4288 return addErrorSuffix("in '" + Twine(IDVal) + "' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00004289
Eli Bendersky17233942013-01-15 22:59:42 +00004290 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
Petr Hosek67a94a72016-05-28 05:57:48 +00004291 getStreamer().emitFill(*NumBytes, FillExpr, NumBytesLoc);
Eli Bendersky17233942013-01-15 22:59:42 +00004292
4293 return false;
4294}
4295
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004296/// parseDirectiveDCB
4297/// ::= .dcb.{b, l, w} expression, expression
4298bool AsmParser::parseDirectiveDCB(StringRef IDVal, unsigned Size) {
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004299 SMLoc NumValuesLoc = Lexer.getLoc();
4300 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004301 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004302 return true;
4303
4304 if (NumValues < 0) {
4305 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4306 return false;
4307 }
4308
4309 if (parseToken(AsmToken::Comma,
4310 "unexpected token in '" + Twine(IDVal) + "' directive"))
4311 return true;
4312
4313 const MCExpr *Value;
4314 SMLoc ExprLoc = getLexer().getLoc();
4315 if (parseExpression(Value))
4316 return true;
4317
4318 // Special case constant expressions to match code generator.
4319 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
4320 assert(Size <= 8 && "Invalid size");
4321 uint64_t IntValue = MCE->getValue();
4322 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
4323 return Error(ExprLoc, "literal value out of range for directive");
4324 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4325 getStreamer().EmitIntValue(IntValue, Size);
4326 } else {
4327 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4328 getStreamer().EmitValue(Value, Size, ExprLoc);
4329 }
4330
4331 if (parseToken(AsmToken::EndOfStatement,
4332 "unexpected token in '" + Twine(IDVal) + "' directive"))
4333 return true;
4334
4335 return false;
4336}
4337
4338/// parseDirectiveRealDCB
4339/// ::= .dcb.{d, s} expression, expression
4340bool AsmParser::parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &Semantics) {
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004341 SMLoc NumValuesLoc = Lexer.getLoc();
4342 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004343 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004344 return true;
4345
4346 if (NumValues < 0) {
4347 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4348 return false;
4349 }
4350
4351 if (parseToken(AsmToken::Comma,
4352 "unexpected token in '" + Twine(IDVal) + "' directive"))
4353 return true;
4354
4355 APInt AsInt;
4356 if (parseRealValue(Semantics, AsInt))
4357 return true;
4358
4359 if (parseToken(AsmToken::EndOfStatement,
4360 "unexpected token in '" + Twine(IDVal) + "' directive"))
4361 return true;
4362
4363 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4364 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
4365 AsInt.getBitWidth() / 8);
4366
4367 return false;
4368}
4369
Petr Hosek85b2f672016-09-23 21:53:36 +00004370/// parseDirectiveDS
4371/// ::= .ds.{b, d, l, p, s, w, x} expression
4372bool AsmParser::parseDirectiveDS(StringRef IDVal, unsigned Size) {
Petr Hosek85b2f672016-09-23 21:53:36 +00004373 SMLoc NumValuesLoc = Lexer.getLoc();
4374 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004375 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek85b2f672016-09-23 21:53:36 +00004376 return true;
4377
4378 if (NumValues < 0) {
4379 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4380 return false;
4381 }
4382
4383 if (parseToken(AsmToken::EndOfStatement,
4384 "unexpected token in '" + Twine(IDVal) + "' directive"))
4385 return true;
4386
4387 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4388 getStreamer().emitFill(Size, 0);
4389
4390 return false;
4391}
4392
Jim Grosbach4b905842013-09-20 23:08:21 +00004393/// parseDirectiveLEB128
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004394/// ::= (.sleb128 | .uleb128) [ expression (, expression)* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004395bool AsmParser::parseDirectiveLEB128(bool Signed) {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004396 if (checkForValidSection())
4397 return true;
4398
Nirav Dave1a9044b2016-10-24 14:35:29 +00004399 auto parseOp = [&]() -> bool {
4400 const MCExpr *Value;
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004401 if (parseExpression(Value))
4402 return true;
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004403 if (Signed)
4404 getStreamer().EmitSLEB128Value(Value);
4405 else
4406 getStreamer().EmitULEB128Value(Value);
Nirav Dave1a9044b2016-10-24 14:35:29 +00004407 return false;
4408 };
Eli Bendersky17233942013-01-15 22:59:42 +00004409
Nirav Dave1a9044b2016-10-24 14:35:29 +00004410 if (parseMany(parseOp))
4411 return addErrorSuffix(" in directive");
Eli Bendersky17233942013-01-15 22:59:42 +00004412
4413 return false;
4414}
4415
Jim Grosbach4b905842013-09-20 23:08:21 +00004416/// parseDirectiveSymbolAttribute
Daniel Dunbara5508c82009-06-30 00:33:19 +00004417/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004418bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00004419 auto parseOp = [&]() -> bool {
4420 StringRef Name;
4421 SMLoc Loc = getTok().getLoc();
4422 if (parseIdentifier(Name))
4423 return Error(Loc, "expected identifier");
4424 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004425
Nirav Dave1a9044b2016-10-24 14:35:29 +00004426 // Assembler local symbols don't make any sense here. Complain loudly.
4427 if (Sym->isTemporary())
4428 return Error(Loc, "non-local symbol required");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004429
Nirav Dave1a9044b2016-10-24 14:35:29 +00004430 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
4431 return Error(Loc, "unable to emit symbol attribute");
4432 return false;
4433 };
Daniel Dunbara5508c82009-06-30 00:33:19 +00004434
Nirav Dave1a9044b2016-10-24 14:35:29 +00004435 if (parseMany(parseOp))
4436 return addErrorSuffix(" in directive");
Jan Wen Voungc7682872010-09-30 01:09:20 +00004437 return false;
Daniel Dunbara5508c82009-06-30 00:33:19 +00004438}
Chris Lattnera1e11f52009-07-07 20:30:46 +00004439
Jim Grosbach4b905842013-09-20 23:08:21 +00004440/// parseDirectiveComm
Chris Lattner28ad7542009-07-09 17:25:12 +00004441/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004442bool AsmParser::parseDirectiveComm(bool IsLocal) {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004443 if (checkForValidSection())
4444 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00004445
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004446 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004447 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004448 if (parseIdentifier(Name))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004449 return TokError("expected identifier in directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004450
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +00004451 // Handle the identifier as the key symbol.
Jim Grosbach6f482002015-05-18 18:43:14 +00004452 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Chris Lattnera1e11f52009-07-07 20:30:46 +00004453
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004454 if (getLexer().isNot(AsmToken::Comma))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004455 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00004456 Lex();
Chris Lattnera1e11f52009-07-07 20:30:46 +00004457
4458 int64_t Size;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004459 SMLoc SizeLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004460 if (parseAbsoluteExpression(Size))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004461 return true;
4462
4463 int64_t Pow2Alignment = 0;
4464 SMLoc Pow2AlignmentLoc;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004465 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan686ed8d2010-01-19 20:22:31 +00004466 Lex();
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004467 Pow2AlignmentLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004468 if (parseAbsoluteExpression(Pow2Alignment))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004469 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00004470
Benjamin Kramer68b9f052012-09-07 21:08:01 +00004471 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
4472 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00004473 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
4474
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00004475 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramer68b9f052012-09-07 21:08:01 +00004476 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
4477 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00004478 if (!isPowerOf2_64(Pow2Alignment))
4479 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
4480 Pow2Alignment = Log2_64(Pow2Alignment);
4481 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00004482 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00004483
Nirav Dave1a9044b2016-10-24 14:35:29 +00004484 if (parseToken(AsmToken::EndOfStatement,
4485 "unexpected token in '.comm' or '.lcomm' directive"))
4486 return true;
Chris Lattnera1e11f52009-07-07 20:30:46 +00004487
Chris Lattner28ad7542009-07-09 17:25:12 +00004488 // NOTE: a size of zero for a .comm should create a undefined symbol
4489 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattnera1e11f52009-07-07 20:30:46 +00004490 if (Size < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00004491 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
Jim Grosbach4b905842013-09-20 23:08:21 +00004492 "be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00004493
Eric Christopherbc818852010-05-14 01:38:54 +00004494 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattnera1e11f52009-07-07 20:30:46 +00004495 // may internally end up wanting an alignment in bytes.
4496 // FIXME: Diagnose overflow.
4497 if (Pow2Alignment < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00004498 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
Jim Grosbach4b905842013-09-20 23:08:21 +00004499 "alignment, can't be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00004500
Rafael Espindola13a79bb2017-02-02 21:26:06 +00004501 Sym->redefineIfPossible();
Daniel Dunbar6860ac72009-08-22 07:22:36 +00004502 if (!Sym->isUndefined())
Chris Lattnera1e11f52009-07-07 20:30:46 +00004503 return Error(IDLoc, "invalid symbol redefinition");
4504
Chris Lattner28ad7542009-07-09 17:25:12 +00004505 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00004506 if (IsLocal) {
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00004507 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00004508 return false;
4509 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00004510
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004511 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattnera1e11f52009-07-07 20:30:46 +00004512 return false;
4513}
Chris Lattner07cadaf2009-07-10 22:20:30 +00004514
Jim Grosbach4b905842013-09-20 23:08:21 +00004515/// parseDirectiveAbort
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004516/// ::= .abort [... message ...]
Jim Grosbach4b905842013-09-20 23:08:21 +00004517bool AsmParser::parseDirectiveAbort() {
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004518 // FIXME: Use loc from directive.
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004519 SMLoc Loc = getLexer().getLoc();
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004520
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004521 StringRef Str = parseStringToEndOfStatement();
Nirav Davea645433c2016-07-18 15:24:03 +00004522 if (parseToken(AsmToken::EndOfStatement,
4523 "unexpected token in '.abort' directive"))
4524 return true;
Kevin Enderby56523ce2009-07-13 23:15:14 +00004525
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004526 if (Str.empty())
Nirav Dave2364748a2016-09-16 18:30:20 +00004527 return Error(Loc, ".abort detected. Assembly stopping.");
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004528 else
Nirav Dave2364748a2016-09-16 18:30:20 +00004529 return Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004530 // FIXME: Actually abort assembly here.
Kevin Enderby56523ce2009-07-13 23:15:14 +00004531
4532 return false;
4533}
Kevin Enderbycbe475d2009-07-14 21:35:03 +00004534
Jim Grosbach4b905842013-09-20 23:08:21 +00004535/// parseDirectiveInclude
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004536/// ::= .include "filename"
Jim Grosbach4b905842013-09-20 23:08:21 +00004537bool AsmParser::parseDirectiveInclude() {
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004538 // Allow the strings to have escaped octal character sequence.
4539 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00004540 SMLoc IncludeLoc = getTok().getLoc();
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004541
Nirav Davea645433c2016-07-18 15:24:03 +00004542 if (check(getTok().isNot(AsmToken::String),
4543 "expected string in '.include' directive") ||
4544 parseEscapedString(Filename) ||
4545 check(getTok().isNot(AsmToken::EndOfStatement),
4546 "unexpected token in '.include' directive") ||
4547 // Attempt to switch the lexer to the included file before consuming the
4548 // end of statement to avoid losing it when we switch.
4549 check(enterIncludeFile(Filename), IncludeLoc,
4550 "Could not find include file '" + Filename + "'"))
Chris Lattner693fbb82009-07-16 06:14:39 +00004551 return true;
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004552
4553 return false;
4554}
Kevin Enderby09ea5702009-07-15 15:30:11 +00004555
Jim Grosbach4b905842013-09-20 23:08:21 +00004556/// parseDirectiveIncbin
Petr Hosek2f4ac442016-09-23 00:41:06 +00004557/// ::= .incbin "filename" [ , skip [ , count ] ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004558bool AsmParser::parseDirectiveIncbin() {
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004559 // Allow the strings to have escaped octal character sequence.
4560 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00004561 SMLoc IncbinLoc = getTok().getLoc();
4562 if (check(getTok().isNot(AsmToken::String),
4563 "expected string in '.incbin' directive") ||
Petr Hosek2f4ac442016-09-23 00:41:06 +00004564 parseEscapedString(Filename))
4565 return true;
4566
4567 int64_t Skip = 0;
4568 const MCExpr *Count = nullptr;
4569 SMLoc SkipLoc, CountLoc;
Nirav Dave1a9044b2016-10-24 14:35:29 +00004570 if (parseOptionalToken(AsmToken::Comma)) {
Petr Hosek2f4ac442016-09-23 00:41:06 +00004571 // The skip expression can be omitted while specifying the count, e.g:
4572 // .incbin "filename",,4
4573 if (getTok().isNot(AsmToken::Comma)) {
4574 if (parseTokenLoc(SkipLoc) || parseAbsoluteExpression(Skip))
4575 return true;
4576 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00004577 if (parseOptionalToken(AsmToken::Comma)) {
4578 CountLoc = getTok().getLoc();
4579 if (parseExpression(Count))
Petr Hosek2f4ac442016-09-23 00:41:06 +00004580 return true;
4581 }
4582 }
4583
4584 if (parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00004585 "unexpected token in '.incbin' directive"))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004586 return true;
Nirav Dave1ab71992016-07-18 19:35:21 +00004587
Petr Hosek2f4ac442016-09-23 00:41:06 +00004588 if (check(Skip < 0, SkipLoc, "skip is negative"))
4589 return true;
4590
Nirav Dave1ab71992016-07-18 19:35:21 +00004591 // Attempt to process the included file.
Petr Hosek2f4ac442016-09-23 00:41:06 +00004592 if (processIncbinFile(Filename, Skip, Count, CountLoc))
Nirav Dave1ab71992016-07-18 19:35:21 +00004593 return Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
Kevin Enderby109f25c2011-12-14 21:47:48 +00004594 return false;
4595}
4596
Jim Grosbach4b905842013-09-20 23:08:21 +00004597/// parseDirectiveIf
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004598/// ::= .if{,eq,ge,gt,le,lt,ne} expression
4599bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004600 TheCondStack.push_back(TheCondState);
4601 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004602 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004603 eatToEndOfStatement();
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004604 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004605 int64_t ExprValue;
Nirav Davea645433c2016-07-18 15:24:03 +00004606 if (parseAbsoluteExpression(ExprValue) ||
4607 parseToken(AsmToken::EndOfStatement,
4608 "unexpected token in '.if' directive"))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004609 return true;
4610
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004611 switch (DirKind) {
4612 default:
4613 llvm_unreachable("unsupported directive");
4614 case DK_IF:
4615 case DK_IFNE:
4616 break;
4617 case DK_IFEQ:
4618 ExprValue = ExprValue == 0;
4619 break;
4620 case DK_IFGE:
4621 ExprValue = ExprValue >= 0;
4622 break;
4623 case DK_IFGT:
4624 ExprValue = ExprValue > 0;
4625 break;
4626 case DK_IFLE:
4627 ExprValue = ExprValue <= 0;
4628 break;
4629 case DK_IFLT:
4630 ExprValue = ExprValue < 0;
4631 break;
4632 }
4633
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004634 TheCondState.CondMet = ExprValue;
4635 TheCondState.Ignore = !TheCondState.CondMet;
4636 }
4637
4638 return false;
4639}
4640
Jim Grosbach4b905842013-09-20 23:08:21 +00004641/// parseDirectiveIfb
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004642/// ::= .ifb string
Jim Grosbach4b905842013-09-20 23:08:21 +00004643bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004644 TheCondStack.push_back(TheCondState);
4645 TheCondState.TheCond = AsmCond::IfCond;
4646
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004647 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004648 eatToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004649 } else {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004650 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004651
Nirav Davea645433c2016-07-18 15:24:03 +00004652 if (parseToken(AsmToken::EndOfStatement,
4653 "unexpected token in '.ifb' directive"))
4654 return true;
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004655
4656 TheCondState.CondMet = ExpectBlank == Str.empty();
4657 TheCondState.Ignore = !TheCondState.CondMet;
4658 }
4659
4660 return false;
4661}
4662
Jim Grosbach4b905842013-09-20 23:08:21 +00004663/// parseDirectiveIfc
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004664/// ::= .ifc string1, string2
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00004665/// ::= .ifnc string1, string2
Jim Grosbach4b905842013-09-20 23:08:21 +00004666bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004667 TheCondStack.push_back(TheCondState);
4668 TheCondState.TheCond = AsmCond::IfCond;
4669
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004670 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004671 eatToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004672 } else {
Jim Grosbach4b905842013-09-20 23:08:21 +00004673 StringRef Str1 = parseStringToComma();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004674
Nirav Davea645433c2016-07-18 15:24:03 +00004675 if (parseToken(AsmToken::Comma, "unexpected token in '.ifc' directive"))
4676 return true;
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004677
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004678 StringRef Str2 = parseStringToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004679
Nirav Davea645433c2016-07-18 15:24:03 +00004680 if (parseToken(AsmToken::EndOfStatement,
4681 "unexpected token in '.ifc' directive"))
4682 return true;
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004683
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00004684 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004685 TheCondState.Ignore = !TheCondState.CondMet;
4686 }
4687
4688 return false;
4689}
4690
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004691/// parseDirectiveIfeqs
4692/// ::= .ifeqs string1, string2
Sid Manning51c35602015-03-18 14:20:54 +00004693bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual) {
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004694 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00004695 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00004696 return TokError("expected string parameter for '.ifeqs' directive");
4697 return TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004698 }
4699
4700 StringRef String1 = getTok().getStringContents();
4701 Lex();
4702
4703 if (Lexer.isNot(AsmToken::Comma)) {
Sid Manning51c35602015-03-18 14:20:54 +00004704 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00004705 return TokError(
4706 "expected comma after first string for '.ifeqs' directive");
4707 return TokError("expected comma after first string for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004708 }
4709
4710 Lex();
4711
4712 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00004713 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00004714 return TokError("expected string parameter for '.ifeqs' directive");
4715 return TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004716 }
4717
4718 StringRef String2 = getTok().getStringContents();
4719 Lex();
4720
4721 TheCondStack.push_back(TheCondState);
4722 TheCondState.TheCond = AsmCond::IfCond;
Sid Manning51c35602015-03-18 14:20:54 +00004723 TheCondState.CondMet = ExpectEqual == (String1 == String2);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004724 TheCondState.Ignore = !TheCondState.CondMet;
4725
4726 return false;
4727}
4728
Jim Grosbach4b905842013-09-20 23:08:21 +00004729/// parseDirectiveIfdef
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004730/// ::= .ifdef symbol
Jim Grosbach4b905842013-09-20 23:08:21 +00004731bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004732 StringRef Name;
4733 TheCondStack.push_back(TheCondState);
4734 TheCondState.TheCond = AsmCond::IfCond;
4735
4736 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004737 eatToEndOfStatement();
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004738 } else {
Nirav Davea645433c2016-07-18 15:24:03 +00004739 if (check(parseIdentifier(Name), "expected identifier after '.ifdef'") ||
4740 parseToken(AsmToken::EndOfStatement, "unexpected token in '.ifdef'"))
4741 return true;
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004742
Jim Grosbach6f482002015-05-18 18:43:14 +00004743 MCSymbol *Sym = getContext().lookupSymbol(Name);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004744
4745 if (expect_defined)
Craig Topper353eda42014-04-24 06:44:33 +00004746 TheCondState.CondMet = (Sym && !Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004747 else
Craig Topper353eda42014-04-24 06:44:33 +00004748 TheCondState.CondMet = (!Sym || Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004749 TheCondState.Ignore = !TheCondState.CondMet;
4750 }
4751
4752 return false;
4753}
4754
Jim Grosbach4b905842013-09-20 23:08:21 +00004755/// parseDirectiveElseIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004756/// ::= .elseif expression
Jim Grosbach4b905842013-09-20 23:08:21 +00004757bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004758 if (TheCondState.TheCond != AsmCond::IfCond &&
4759 TheCondState.TheCond != AsmCond::ElseIfCond)
Nirav Dave2364748a2016-09-16 18:30:20 +00004760 return Error(DirectiveLoc, "Encountered a .elseif that doesn't follow an"
4761 " .if or an .elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004762 TheCondState.TheCond = AsmCond::ElseIfCond;
4763
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004764 bool LastIgnoreState = false;
4765 if (!TheCondStack.empty())
Craig Topper2172ad62013-04-22 04:24:02 +00004766 LastIgnoreState = TheCondStack.back().Ignore;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004767 if (LastIgnoreState || TheCondState.CondMet) {
4768 TheCondState.Ignore = true;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004769 eatToEndOfStatement();
Craig Topperf15655b2013-04-22 04:22:40 +00004770 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004771 int64_t ExprValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004772 if (parseAbsoluteExpression(ExprValue))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004773 return true;
4774
Nirav Dave1a9044b2016-10-24 14:35:29 +00004775 if (parseToken(AsmToken::EndOfStatement,
4776 "unexpected token in '.elseif' directive"))
4777 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00004778
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004779 TheCondState.CondMet = ExprValue;
4780 TheCondState.Ignore = !TheCondState.CondMet;
4781 }
4782
4783 return false;
4784}
4785
Jim Grosbach4b905842013-09-20 23:08:21 +00004786/// parseDirectiveElse
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004787/// ::= .else
Jim Grosbach4b905842013-09-20 23:08:21 +00004788bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00004789 if (parseToken(AsmToken::EndOfStatement,
4790 "unexpected token in '.else' directive"))
4791 return true;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004792
4793 if (TheCondState.TheCond != AsmCond::IfCond &&
4794 TheCondState.TheCond != AsmCond::ElseIfCond)
Nirav Dave2364748a2016-09-16 18:30:20 +00004795 return Error(DirectiveLoc, "Encountered a .else that doesn't follow "
4796 " an .if or an .elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004797 TheCondState.TheCond = AsmCond::ElseCond;
4798 bool LastIgnoreState = false;
4799 if (!TheCondStack.empty())
4800 LastIgnoreState = TheCondStack.back().Ignore;
4801 if (LastIgnoreState || TheCondState.CondMet)
4802 TheCondState.Ignore = true;
4803 else
4804 TheCondState.Ignore = false;
4805
4806 return false;
4807}
4808
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004809/// parseDirectiveEnd
4810/// ::= .end
4811bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00004812 if (parseToken(AsmToken::EndOfStatement,
4813 "unexpected token in '.end' directive"))
4814 return true;
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004815
4816 while (Lexer.isNot(AsmToken::Eof))
Nirav Dave1a9044b2016-10-24 14:35:29 +00004817 Lexer.Lex();
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004818
4819 return false;
4820}
4821
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004822/// parseDirectiveError
4823/// ::= .err
4824/// ::= .error [string]
4825bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
4826 if (!TheCondStack.empty()) {
4827 if (TheCondStack.back().Ignore) {
4828 eatToEndOfStatement();
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004829 return false;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004830 }
4831 }
4832
4833 if (!WithMessage)
4834 return Error(L, ".err encountered");
4835
4836 StringRef Message = ".error directive invoked in source file";
4837 if (Lexer.isNot(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00004838 if (Lexer.isNot(AsmToken::String))
4839 return TokError(".error argument must be a string");
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004840
4841 Message = getTok().getStringContents();
4842 Lex();
4843 }
4844
Nirav Dave2364748a2016-09-16 18:30:20 +00004845 return Error(L, Message);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004846}
4847
Nico Weber404012b2014-07-24 16:26:06 +00004848/// parseDirectiveWarning
4849/// ::= .warning [string]
4850bool AsmParser::parseDirectiveWarning(SMLoc L) {
4851 if (!TheCondStack.empty()) {
4852 if (TheCondStack.back().Ignore) {
4853 eatToEndOfStatement();
4854 return false;
4855 }
4856 }
4857
4858 StringRef Message = ".warning directive invoked in source file";
Nirav Dave1a9044b2016-10-24 14:35:29 +00004859
4860 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00004861 if (Lexer.isNot(AsmToken::String))
4862 return TokError(".warning argument must be a string");
Nico Weber404012b2014-07-24 16:26:06 +00004863
4864 Message = getTok().getStringContents();
4865 Lex();
Nirav Dave1a9044b2016-10-24 14:35:29 +00004866 if (parseToken(AsmToken::EndOfStatement,
4867 "expected end of statement in '.warning' directive"))
4868 return true;
Nico Weber404012b2014-07-24 16:26:06 +00004869 }
4870
Nirav Dave2364748a2016-09-16 18:30:20 +00004871 return Warning(L, Message);
Nico Weber404012b2014-07-24 16:26:06 +00004872}
4873
Jim Grosbach4b905842013-09-20 23:08:21 +00004874/// parseDirectiveEndIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004875/// ::= .endif
Jim Grosbach4b905842013-09-20 23:08:21 +00004876bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00004877 if (parseToken(AsmToken::EndOfStatement,
4878 "unexpected token in '.endif' directive"))
4879 return true;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004880
Jim Grosbach4b905842013-09-20 23:08:21 +00004881 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
Nirav Dave2364748a2016-09-16 18:30:20 +00004882 return Error(DirectiveLoc, "Encountered a .endif that doesn't follow "
4883 "an .if or .else");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004884 if (!TheCondStack.empty()) {
4885 TheCondState = TheCondStack.back();
4886 TheCondStack.pop_back();
4887 }
4888
4889 return false;
4890}
Daniel Dunbara4b069c2009-08-11 04:24:50 +00004891
Eli Bendersky17233942013-01-15 22:59:42 +00004892void AsmParser::initializeDirectiveKindMap() {
4893 DirectiveKindMap[".set"] = DK_SET;
4894 DirectiveKindMap[".equ"] = DK_EQU;
4895 DirectiveKindMap[".equiv"] = DK_EQUIV;
4896 DirectiveKindMap[".ascii"] = DK_ASCII;
4897 DirectiveKindMap[".asciz"] = DK_ASCIZ;
4898 DirectiveKindMap[".string"] = DK_STRING;
4899 DirectiveKindMap[".byte"] = DK_BYTE;
4900 DirectiveKindMap[".short"] = DK_SHORT;
4901 DirectiveKindMap[".value"] = DK_VALUE;
4902 DirectiveKindMap[".2byte"] = DK_2BYTE;
4903 DirectiveKindMap[".long"] = DK_LONG;
4904 DirectiveKindMap[".int"] = DK_INT;
4905 DirectiveKindMap[".4byte"] = DK_4BYTE;
4906 DirectiveKindMap[".quad"] = DK_QUAD;
4907 DirectiveKindMap[".8byte"] = DK_8BYTE;
David Woodhoused6de0d92014-02-01 16:20:59 +00004908 DirectiveKindMap[".octa"] = DK_OCTA;
Eli Bendersky17233942013-01-15 22:59:42 +00004909 DirectiveKindMap[".single"] = DK_SINGLE;
4910 DirectiveKindMap[".float"] = DK_FLOAT;
4911 DirectiveKindMap[".double"] = DK_DOUBLE;
4912 DirectiveKindMap[".align"] = DK_ALIGN;
4913 DirectiveKindMap[".align32"] = DK_ALIGN32;
4914 DirectiveKindMap[".balign"] = DK_BALIGN;
4915 DirectiveKindMap[".balignw"] = DK_BALIGNW;
4916 DirectiveKindMap[".balignl"] = DK_BALIGNL;
4917 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
4918 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
4919 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
4920 DirectiveKindMap[".org"] = DK_ORG;
4921 DirectiveKindMap[".fill"] = DK_FILL;
4922 DirectiveKindMap[".zero"] = DK_ZERO;
4923 DirectiveKindMap[".extern"] = DK_EXTERN;
4924 DirectiveKindMap[".globl"] = DK_GLOBL;
4925 DirectiveKindMap[".global"] = DK_GLOBAL;
Eli Bendersky17233942013-01-15 22:59:42 +00004926 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
4927 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
4928 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
4929 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
4930 DirectiveKindMap[".reference"] = DK_REFERENCE;
4931 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
4932 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
4933 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
4934 DirectiveKindMap[".comm"] = DK_COMM;
4935 DirectiveKindMap[".common"] = DK_COMMON;
4936 DirectiveKindMap[".lcomm"] = DK_LCOMM;
4937 DirectiveKindMap[".abort"] = DK_ABORT;
4938 DirectiveKindMap[".include"] = DK_INCLUDE;
4939 DirectiveKindMap[".incbin"] = DK_INCBIN;
4940 DirectiveKindMap[".code16"] = DK_CODE16;
4941 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
4942 DirectiveKindMap[".rept"] = DK_REPT;
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00004943 DirectiveKindMap[".rep"] = DK_REPT;
Eli Bendersky17233942013-01-15 22:59:42 +00004944 DirectiveKindMap[".irp"] = DK_IRP;
4945 DirectiveKindMap[".irpc"] = DK_IRPC;
4946 DirectiveKindMap[".endr"] = DK_ENDR;
4947 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
4948 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
4949 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
4950 DirectiveKindMap[".if"] = DK_IF;
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004951 DirectiveKindMap[".ifeq"] = DK_IFEQ;
4952 DirectiveKindMap[".ifge"] = DK_IFGE;
4953 DirectiveKindMap[".ifgt"] = DK_IFGT;
4954 DirectiveKindMap[".ifle"] = DK_IFLE;
4955 DirectiveKindMap[".iflt"] = DK_IFLT;
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00004956 DirectiveKindMap[".ifne"] = DK_IFNE;
Eli Bendersky17233942013-01-15 22:59:42 +00004957 DirectiveKindMap[".ifb"] = DK_IFB;
4958 DirectiveKindMap[".ifnb"] = DK_IFNB;
4959 DirectiveKindMap[".ifc"] = DK_IFC;
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004960 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
Eli Bendersky17233942013-01-15 22:59:42 +00004961 DirectiveKindMap[".ifnc"] = DK_IFNC;
Sid Manning51c35602015-03-18 14:20:54 +00004962 DirectiveKindMap[".ifnes"] = DK_IFNES;
Eli Bendersky17233942013-01-15 22:59:42 +00004963 DirectiveKindMap[".ifdef"] = DK_IFDEF;
4964 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
4965 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
4966 DirectiveKindMap[".elseif"] = DK_ELSEIF;
4967 DirectiveKindMap[".else"] = DK_ELSE;
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004968 DirectiveKindMap[".end"] = DK_END;
Eli Bendersky17233942013-01-15 22:59:42 +00004969 DirectiveKindMap[".endif"] = DK_ENDIF;
4970 DirectiveKindMap[".skip"] = DK_SKIP;
4971 DirectiveKindMap[".space"] = DK_SPACE;
4972 DirectiveKindMap[".file"] = DK_FILE;
4973 DirectiveKindMap[".line"] = DK_LINE;
4974 DirectiveKindMap[".loc"] = DK_LOC;
4975 DirectiveKindMap[".stabs"] = DK_STABS;
Reid Kleckner2214ed82016-01-29 00:49:42 +00004976 DirectiveKindMap[".cv_file"] = DK_CV_FILE;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00004977 DirectiveKindMap[".cv_func_id"] = DK_CV_FUNC_ID;
Reid Kleckner2214ed82016-01-29 00:49:42 +00004978 DirectiveKindMap[".cv_loc"] = DK_CV_LOC;
4979 DirectiveKindMap[".cv_linetable"] = DK_CV_LINETABLE;
David Majnemer6fcbd7e2016-01-29 19:24:12 +00004980 DirectiveKindMap[".cv_inline_linetable"] = DK_CV_INLINE_LINETABLE;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00004981 DirectiveKindMap[".cv_inline_site_id"] = DK_CV_INLINE_SITE_ID;
David Majnemer408b5e62016-02-05 01:55:49 +00004982 DirectiveKindMap[".cv_def_range"] = DK_CV_DEF_RANGE;
Reid Kleckner2214ed82016-01-29 00:49:42 +00004983 DirectiveKindMap[".cv_stringtable"] = DK_CV_STRINGTABLE;
4984 DirectiveKindMap[".cv_filechecksums"] = DK_CV_FILECHECKSUMS;
Eli Bendersky17233942013-01-15 22:59:42 +00004985 DirectiveKindMap[".sleb128"] = DK_SLEB128;
4986 DirectiveKindMap[".uleb128"] = DK_ULEB128;
4987 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
4988 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
4989 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
4990 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
4991 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
4992 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
4993 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
4994 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
4995 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
4996 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
4997 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
4998 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
4999 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
5000 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
5001 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
5002 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
5003 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
5004 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
5005 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00005006 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
Eli Bendersky17233942013-01-15 22:59:42 +00005007 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
5008 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
5009 DirectiveKindMap[".macro"] = DK_MACRO;
Nico Weber155dccd12014-07-24 17:08:39 +00005010 DirectiveKindMap[".exitm"] = DK_EXITM;
Eli Bendersky17233942013-01-15 22:59:42 +00005011 DirectiveKindMap[".endm"] = DK_ENDM;
5012 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
5013 DirectiveKindMap[".purgem"] = DK_PURGEM;
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00005014 DirectiveKindMap[".err"] = DK_ERR;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00005015 DirectiveKindMap[".error"] = DK_ERROR;
Nico Weber404012b2014-07-24 16:26:06 +00005016 DirectiveKindMap[".warning"] = DK_WARNING;
Michael Zuckerman56704612017-05-01 13:20:12 +00005017 DirectiveKindMap[".altmacro"] = DK_ALTMACRO;
5018 DirectiveKindMap[".noaltmacro"] = DK_NOALTMACRO;
Daniel Sanders9f6ad492015-11-12 13:33:00 +00005019 DirectiveKindMap[".reloc"] = DK_RELOC;
Petr Hosek731bb9c2016-08-23 21:34:53 +00005020 DirectiveKindMap[".dc"] = DK_DC;
5021 DirectiveKindMap[".dc.a"] = DK_DC_A;
5022 DirectiveKindMap[".dc.b"] = DK_DC_B;
5023 DirectiveKindMap[".dc.d"] = DK_DC_D;
5024 DirectiveKindMap[".dc.l"] = DK_DC_L;
5025 DirectiveKindMap[".dc.s"] = DK_DC_S;
5026 DirectiveKindMap[".dc.w"] = DK_DC_W;
5027 DirectiveKindMap[".dc.x"] = DK_DC_X;
Petr Hosek4cb08ce2016-09-23 19:25:15 +00005028 DirectiveKindMap[".dcb"] = DK_DCB;
5029 DirectiveKindMap[".dcb.b"] = DK_DCB_B;
5030 DirectiveKindMap[".dcb.d"] = DK_DCB_D;
5031 DirectiveKindMap[".dcb.l"] = DK_DCB_L;
5032 DirectiveKindMap[".dcb.s"] = DK_DCB_S;
5033 DirectiveKindMap[".dcb.w"] = DK_DCB_W;
5034 DirectiveKindMap[".dcb.x"] = DK_DCB_X;
Petr Hosek85b2f672016-09-23 21:53:36 +00005035 DirectiveKindMap[".ds"] = DK_DS;
5036 DirectiveKindMap[".ds.b"] = DK_DS_B;
5037 DirectiveKindMap[".ds.d"] = DK_DS_D;
5038 DirectiveKindMap[".ds.l"] = DK_DS_L;
5039 DirectiveKindMap[".ds.p"] = DK_DS_P;
5040 DirectiveKindMap[".ds.s"] = DK_DS_S;
5041 DirectiveKindMap[".ds.w"] = DK_DS_W;
5042 DirectiveKindMap[".ds.x"] = DK_DS_X;
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00005043}
5044
Jim Grosbach4b905842013-09-20 23:08:21 +00005045MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005046 AsmToken EndToken, StartToken = getTok();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005047
Rafael Espindola34b9c512012-06-03 23:57:14 +00005048 unsigned NestLevel = 0;
Eugene Zelenko33d7b762016-08-23 17:14:32 +00005049 while (true) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005050 // Check whether we have reached the end of the file.
Rafael Espindola34b9c512012-06-03 23:57:14 +00005051 if (getLexer().is(AsmToken::Eof)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00005052 printError(DirectiveLoc, "no matching '.endr' in definition");
Craig Topper353eda42014-04-24 06:44:33 +00005053 return nullptr;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005054 }
5055
Rafael Espindola34b9c512012-06-03 23:57:14 +00005056 if (Lexer.is(AsmToken::Identifier) &&
Nikolay Haustov95b4fcd2016-03-01 08:18:28 +00005057 (getTok().getIdentifier() == ".rept" ||
5058 getTok().getIdentifier() == ".irp" ||
5059 getTok().getIdentifier() == ".irpc")) {
Rafael Espindola34b9c512012-06-03 23:57:14 +00005060 ++NestLevel;
5061 }
5062
5063 // Otherwise, check whether we have reached the .endr.
Jim Grosbach4b905842013-09-20 23:08:21 +00005064 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
Rafael Espindola34b9c512012-06-03 23:57:14 +00005065 if (NestLevel == 0) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005066 EndToken = getTok();
5067 Lex();
Rafael Espindola34b9c512012-06-03 23:57:14 +00005068 if (Lexer.isNot(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00005069 printError(getTok().getLoc(),
5070 "unexpected token in '.endr' directive");
Craig Topper353eda42014-04-24 06:44:33 +00005071 return nullptr;
Rafael Espindola34b9c512012-06-03 23:57:14 +00005072 }
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005073 break;
5074 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00005075 --NestLevel;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005076 }
5077
Rafael Espindola34b9c512012-06-03 23:57:14 +00005078 // Otherwise, scan till the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005079 eatToEndOfStatement();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005080 }
5081
5082 const char *BodyStart = StartToken.getLoc().getPointer();
5083 const char *BodyEnd = EndToken.getLoc().getPointer();
5084 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
5085
Rafael Espindola34b9c512012-06-03 23:57:14 +00005086 // We Are Anonymous.
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00005087 MacroLikeBodies.emplace_back(StringRef(), Body, MCAsmMacroParameters());
Benjamin Kramer1df3a1f2013-08-04 09:06:29 +00005088 return &MacroLikeBodies.back();
Rafael Espindola34b9c512012-06-03 23:57:14 +00005089}
5090
Jim Grosbach4b905842013-09-20 23:08:21 +00005091void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +00005092 raw_svector_ostream &OS) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005093 OS << ".endr\n";
5094
Rafael Espindola3560ff22014-08-27 20:03:13 +00005095 std::unique_ptr<MemoryBuffer> Instantiation =
5096 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005097
Rafael Espindola34b9c512012-06-03 23:57:14 +00005098 // Create the macro instantiation object and add to the current macro
5099 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00005100 MacroInstantiation *MI = new MacroInstantiation(
5101 DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Rafael Espindola34b9c512012-06-03 23:57:14 +00005102 ActiveMacros.push_back(MI);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005103
Rafael Espindola34b9c512012-06-03 23:57:14 +00005104 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00005105 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00005106 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Rafael Espindola34b9c512012-06-03 23:57:14 +00005107 Lex();
5108}
5109
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00005110/// parseDirectiveRept
5111/// ::= .rep | .rept count
5112bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00005113 const MCExpr *CountExpr;
5114 SMLoc CountLoc = getTok().getLoc();
5115 if (parseExpression(CountExpr))
5116 return true;
5117
Rafael Espindola34b9c512012-06-03 23:57:14 +00005118 int64_t Count;
Jim Grosbach13760bd2015-05-30 01:25:56 +00005119 if (!CountExpr->evaluateAsAbsolute(Count)) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00005120 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
5121 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00005122
Nirav Davea645433c2016-07-18 15:24:03 +00005123 if (check(Count < 0, CountLoc, "Count is negative") ||
5124 parseToken(AsmToken::EndOfStatement,
5125 "unexpected token in '" + Dir + "' directive"))
5126 return true;
Rafael Espindola34b9c512012-06-03 23:57:14 +00005127
5128 // Lex the rept definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005129 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola34b9c512012-06-03 23:57:14 +00005130 if (!M)
5131 return true;
5132
5133 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5134 // to hold the macro body with substitutions.
5135 SmallString<256> Buf;
Rafael Espindola34b9c512012-06-03 23:57:14 +00005136 raw_svector_ostream OS(Buf);
5137 while (Count--) {
Toma Tabacu217116e2015-04-27 10:50:29 +00005138 // Note that the AtPseudoVariable is disabled for instantiations of .rep(t).
5139 if (expandMacro(OS, M->Body, None, None, false, getTok().getLoc()))
Rafael Espindola34b9c512012-06-03 23:57:14 +00005140 return true;
5141 }
Jim Grosbach4b905842013-09-20 23:08:21 +00005142 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005143
5144 return false;
5145}
5146
Jim Grosbach4b905842013-09-20 23:08:21 +00005147/// parseDirectiveIrp
Rafael Espindola768b41c2012-06-15 14:02:34 +00005148/// ::= .irp symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00005149bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00005150 MCAsmMacroParameter Parameter;
Eli Bendersky38274122013-01-14 23:22:36 +00005151 MCAsmMacroArguments A;
Nirav Davea645433c2016-07-18 15:24:03 +00005152 if (check(parseIdentifier(Parameter.Name),
5153 "expected identifier in '.irp' directive") ||
5154 parseToken(AsmToken::Comma, "expected comma in '.irp' directive") ||
5155 parseMacroArguments(nullptr, A) ||
5156 parseToken(AsmToken::EndOfStatement, "expected End of Statement"))
Rafael Espindola768b41c2012-06-15 14:02:34 +00005157 return true;
5158
Rafael Espindola768b41c2012-06-15 14:02:34 +00005159 // Lex the irp definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005160 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola768b41c2012-06-15 14:02:34 +00005161 if (!M)
5162 return true;
5163
5164 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5165 // to hold the macro body with substitutions.
5166 SmallString<256> Buf;
5167 raw_svector_ostream OS(Buf);
5168
Craig Topper84008482015-10-10 05:38:14 +00005169 for (const MCAsmMacroArgument &Arg : A) {
Toma Tabacu217116e2015-04-27 10:50:29 +00005170 // Note that the AtPseudoVariable is enabled for instantiations of .irp.
5171 // This is undocumented, but GAS seems to support it.
Craig Topper84008482015-10-10 05:38:14 +00005172 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindola768b41c2012-06-15 14:02:34 +00005173 return true;
5174 }
5175
Jim Grosbach4b905842013-09-20 23:08:21 +00005176 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola768b41c2012-06-15 14:02:34 +00005177
5178 return false;
5179}
5180
Jim Grosbach4b905842013-09-20 23:08:21 +00005181/// parseDirectiveIrpc
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005182/// ::= .irpc symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00005183bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00005184 MCAsmMacroParameter Parameter;
Eli Bendersky38274122013-01-14 23:22:36 +00005185 MCAsmMacroArguments A;
Nirav Davea645433c2016-07-18 15:24:03 +00005186
5187 if (check(parseIdentifier(Parameter.Name),
5188 "expected identifier in '.irpc' directive") ||
5189 parseToken(AsmToken::Comma, "expected comma in '.irpc' directive") ||
5190 parseMacroArguments(nullptr, A))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005191 return true;
5192
5193 if (A.size() != 1 || A.front().size() != 1)
5194 return TokError("unexpected token in '.irpc' directive");
5195
5196 // Eat the end of statement.
Nirav Davea645433c2016-07-18 15:24:03 +00005197 if (parseToken(AsmToken::EndOfStatement, "expected end of statement"))
5198 return true;
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005199
5200 // Lex the irpc definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005201 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005202 if (!M)
5203 return true;
5204
5205 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5206 // to hold the macro body with substitutions.
5207 SmallString<256> Buf;
5208 raw_svector_ostream OS(Buf);
5209
5210 StringRef Values = A.front().front().getString();
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00005211 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
Eli Benderskya7b905e2013-01-14 19:00:26 +00005212 MCAsmMacroArgument Arg;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00005213 Arg.emplace_back(AsmToken::Identifier, Values.slice(I, I + 1));
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005214
Toma Tabacu217116e2015-04-27 10:50:29 +00005215 // Note that the AtPseudoVariable is enabled for instantiations of .irpc.
5216 // This is undocumented, but GAS seems to support it.
5217 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005218 return true;
5219 }
5220
Jim Grosbach4b905842013-09-20 23:08:21 +00005221 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005222
5223 return false;
5224}
5225
Jim Grosbach4b905842013-09-20 23:08:21 +00005226bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
Rafael Espindola34b9c512012-06-03 23:57:14 +00005227 if (ActiveMacros.empty())
Preston Gurdeb3ebf12012-09-19 20:23:43 +00005228 return TokError("unmatched '.endr' directive");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005229
5230 // The only .repl that should get here are the ones created by
Jim Grosbach4b905842013-09-20 23:08:21 +00005231 // instantiateMacroLikeBody.
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005232 assert(getLexer().is(AsmToken::EndOfStatement));
5233
Jim Grosbach4b905842013-09-20 23:08:21 +00005234 handleMacroExit();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005235 return false;
5236}
Rafael Espindola12d73d12010-09-11 16:45:15 +00005237
Jim Grosbach4b905842013-09-20 23:08:21 +00005238bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
Benjamin Kramer1a136112013-02-15 20:37:21 +00005239 size_t Len) {
Eli Friedman0f4871d2012-10-22 23:58:19 +00005240 const MCExpr *Value;
5241 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005242 if (parseExpression(Value))
Eli Friedman0f4871d2012-10-22 23:58:19 +00005243 return true;
5244 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5245 if (!MCE)
5246 return Error(ExprLoc, "unexpected expression in _emit");
5247 uint64_t IntValue = MCE->getValue();
Craig Topper55b1f292015-10-10 20:17:07 +00005248 if (!isUInt<8>(IntValue) && !isInt<8>(IntValue))
Eli Friedman0f4871d2012-10-22 23:58:19 +00005249 return Error(ExprLoc, "literal value out of range for directive");
5250
Craig Topper7d5b2312015-10-10 05:25:02 +00005251 Info.AsmRewrites->emplace_back(AOK_Emit, IDLoc, Len);
Chad Rosierc7f552c2013-02-12 21:33:51 +00005252 return false;
5253}
5254
Jim Grosbach4b905842013-09-20 23:08:21 +00005255bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
Chad Rosierc7f552c2013-02-12 21:33:51 +00005256 const MCExpr *Value;
5257 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005258 if (parseExpression(Value))
Chad Rosierc7f552c2013-02-12 21:33:51 +00005259 return true;
5260 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5261 if (!MCE)
5262 return Error(ExprLoc, "unexpected expression in align");
5263 uint64_t IntValue = MCE->getValue();
5264 if (!isPowerOf2_64(IntValue))
5265 return Error(ExprLoc, "literal value not a power of two greater then zero");
5266
Craig Topper7d5b2312015-10-10 05:25:02 +00005267 Info.AsmRewrites->emplace_back(AOK_Align, IDLoc, 5, Log2_64(IntValue));
Eli Friedman0f4871d2012-10-22 23:58:19 +00005268 return false;
5269}
5270
Chad Rosierf43fcf52013-02-13 21:27:17 +00005271// We are comparing pointers, but the pointers are relative to a single string.
5272// Thus, this should always be deterministic.
Benjamin Kramer8817cca2013-09-22 14:09:50 +00005273static int rewritesSort(const AsmRewrite *AsmRewriteA,
5274 const AsmRewrite *AsmRewriteB) {
Chad Rosiereb5c1682013-02-13 18:38:58 +00005275 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
5276 return -1;
5277 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
5278 return 1;
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005279
Chad Rosierfce4fab2013-04-08 17:43:47 +00005280 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
5281 // rewrite to the same location. Make sure the SizeDirective rewrite is
5282 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
5283 // ensures the sort algorithm is stable.
Jim Grosbach4b905842013-09-20 23:08:21 +00005284 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
5285 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005286 return -1;
Chad Rosierfce4fab2013-04-08 17:43:47 +00005287
Jim Grosbach4b905842013-09-20 23:08:21 +00005288 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
5289 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005290 return 1;
Jim Grosbach4b905842013-09-20 23:08:21 +00005291 llvm_unreachable("Unstable rewrite sort.");
Chad Rosierb2144ce2013-02-13 01:03:13 +00005292}
5293
Jim Grosbach4b905842013-09-20 23:08:21 +00005294bool AsmParser::parseMSInlineAsm(
5295 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00005296 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool>> &OpDecls,
Jim Grosbach4b905842013-09-20 23:08:21 +00005297 SmallVectorImpl<std::string> &Constraints,
5298 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
5299 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
Chad Rosier37e755c2012-10-23 17:43:43 +00005300 SmallVector<void *, 4> InputDecls;
5301 SmallVector<void *, 4> OutputDecls;
Chad Rosiera4bc9432013-01-10 22:10:27 +00005302 SmallVector<bool, 4> InputDeclsAddressOf;
5303 SmallVector<bool, 4> OutputDeclsAddressOf;
Chad Rosier8bce6642012-10-18 15:49:34 +00005304 SmallVector<std::string, 4> InputConstraints;
5305 SmallVector<std::string, 4> OutputConstraints;
Benjamin Kramer1a136112013-02-15 20:37:21 +00005306 SmallVector<unsigned, 4> ClobberRegs;
Chad Rosier8bce6642012-10-18 15:49:34 +00005307
Benjamin Kramer1a136112013-02-15 20:37:21 +00005308 SmallVector<AsmRewrite, 4> AsmStrRewrites;
Chad Rosier8bce6642012-10-18 15:49:34 +00005309
5310 // Prime the lexer.
5311 Lex();
5312
5313 // While we have input, parse each statement.
5314 unsigned InputIdx = 0;
5315 unsigned OutputIdx = 0;
5316 while (getLexer().isNot(AsmToken::Eof)) {
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00005317 // Parse curly braces marking block start/end
5318 if (parseCurlyBlockScope(AsmStrRewrites))
5319 continue;
5320
Eli Friedman0f4871d2012-10-22 23:58:19 +00005321 ParseStatementInfo Info(&AsmStrRewrites);
Nirav Dave2364748a2016-09-16 18:30:20 +00005322 bool StatementErr = parseStatement(Info, &SI);
Nirav Dave9fa8af22016-09-13 13:55:06 +00005323
Nirav Dave2364748a2016-09-16 18:30:20 +00005324 if (StatementErr || Info.ParseError) {
5325 // Emit pending errors if any exist.
5326 printPendingErrors();
Nico Webere204c482016-09-13 18:17:00 +00005327 return true;
Nirav Dave2364748a2016-09-16 18:30:20 +00005328 }
5329
5330 // No pending error should exist here.
5331 assert(!hasPendingError() && "unexpected error from parseStatement");
Chad Rosier149e8e02012-12-12 22:45:52 +00005332
Benjamin Kramer1a136112013-02-15 20:37:21 +00005333 if (Info.Opcode == ~0U)
5334 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00005335
Benjamin Kramer1a136112013-02-15 20:37:21 +00005336 const MCInstrDesc &Desc = MII->get(Info.Opcode);
Chad Rosier8bce6642012-10-18 15:49:34 +00005337
Benjamin Kramer1a136112013-02-15 20:37:21 +00005338 // Build the list of clobbers, outputs and inputs.
5339 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
David Blaikie960ea3f2014-06-08 16:18:35 +00005340 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005341
Benjamin Kramer1a136112013-02-15 20:37:21 +00005342 // Immediate.
David Blaikie960ea3f2014-06-08 16:18:35 +00005343 if (Operand.isImm())
Benjamin Kramer1a136112013-02-15 20:37:21 +00005344 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00005345
Benjamin Kramer1a136112013-02-15 20:37:21 +00005346 // Register operand.
Nico Weber42f79db2014-07-17 20:24:55 +00005347 if (Operand.isReg() && !Operand.needAddressOf() &&
5348 !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
Benjamin Kramer1a136112013-02-15 20:37:21 +00005349 unsigned NumDefs = Desc.getNumDefs();
5350 // Clobber.
David Blaikie960ea3f2014-06-08 16:18:35 +00005351 if (NumDefs && Operand.getMCOperandNum() < NumDefs)
5352 ClobberRegs.push_back(Operand.getReg());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005353 continue;
5354 }
5355
5356 // Expr/Input or Output.
David Blaikie960ea3f2014-06-08 16:18:35 +00005357 StringRef SymName = Operand.getSymName();
Chad Rosiere81309b2013-04-09 17:53:49 +00005358 if (SymName.empty())
5359 continue;
5360
David Blaikie960ea3f2014-06-08 16:18:35 +00005361 void *OpDecl = Operand.getOpDecl();
Benjamin Kramer1a136112013-02-15 20:37:21 +00005362 if (!OpDecl)
5363 continue;
5364
5365 bool isOutput = (i == 1) && Desc.mayStore();
Chad Rosiere81309b2013-04-09 17:53:49 +00005366 SMLoc Start = SMLoc::getFromPointer(SymName.data());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005367 if (isOutput) {
5368 ++InputIdx;
5369 OutputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00005370 OutputDeclsAddressOf.push_back(Operand.needAddressOf());
Yaron Keren075759a2015-03-30 15:42:36 +00005371 OutputConstraints.push_back(("=" + Operand.getConstraint()).str());
Craig Topper7d5b2312015-10-10 05:25:02 +00005372 AsmStrRewrites.emplace_back(AOK_Output, Start, SymName.size());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005373 } else {
5374 InputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00005375 InputDeclsAddressOf.push_back(Operand.needAddressOf());
5376 InputConstraints.push_back(Operand.getConstraint().str());
Craig Topper7d5b2312015-10-10 05:25:02 +00005377 AsmStrRewrites.emplace_back(AOK_Input, Start, SymName.size());
Chad Rosier8bce6642012-10-18 15:49:34 +00005378 }
Chad Rosier8bce6642012-10-18 15:49:34 +00005379 }
Reid Kleckneree088972013-12-10 18:27:32 +00005380
5381 // Consider implicit defs to be clobbers. Think of cpuid and push.
Craig Toppere5e035a32015-12-05 07:13:35 +00005382 ArrayRef<MCPhysReg> ImpDefs(Desc.getImplicitDefs(),
5383 Desc.getNumImplicitDefs());
David Majnemer8114c1a2014-06-23 02:17:16 +00005384 ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end());
Chad Rosier8bce6642012-10-18 15:49:34 +00005385 }
5386
5387 // Set the number of Outputs and Inputs.
Chad Rosierf641baa2012-10-18 19:39:30 +00005388 NumOutputs = OutputDecls.size();
5389 NumInputs = InputDecls.size();
Chad Rosier8bce6642012-10-18 15:49:34 +00005390
5391 // Set the unique clobbers.
Benjamin Kramer1a136112013-02-15 20:37:21 +00005392 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
5393 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
5394 ClobberRegs.end());
5395 Clobbers.assign(ClobberRegs.size(), std::string());
5396 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
5397 raw_string_ostream OS(Clobbers[I]);
5398 IP->printRegName(OS, ClobberRegs[I]);
5399 }
Chad Rosier8bce6642012-10-18 15:49:34 +00005400
5401 // Merge the various outputs and inputs. Output are expected first.
5402 if (NumOutputs || NumInputs) {
5403 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierf641baa2012-10-18 19:39:30 +00005404 OpDecls.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00005405 Constraints.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00005406 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00005407 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00005408 Constraints[i] = OutputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005409 }
5410 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00005411 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00005412 Constraints[j] = InputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005413 }
5414 }
5415
5416 // Build the IR assembly string.
Alp Tokere69170a2014-06-26 22:52:05 +00005417 std::string AsmStringIR;
5418 raw_string_ostream OS(AsmStringIR);
Alp Tokera55b95b2014-07-06 10:33:31 +00005419 StringRef ASMString =
5420 SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
5421 const char *AsmStart = ASMString.begin();
5422 const char *AsmEnd = ASMString.end();
Jim Grosbach4b905842013-09-20 23:08:21 +00005423 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
David Majnemer8114c1a2014-06-23 02:17:16 +00005424 for (const AsmRewrite &AR : AsmStrRewrites) {
5425 AsmRewriteKind Kind = AR.Kind;
Chad Rosierff10ed12013-04-12 16:26:42 +00005426 if (Kind == AOK_Delete)
5427 continue;
5428
David Majnemer8114c1a2014-06-23 02:17:16 +00005429 const char *Loc = AR.Loc.getPointer();
Chad Rosier17d37992013-03-19 21:12:14 +00005430 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
Chad Rosier0f48c552012-10-19 20:57:14 +00005431
Chad Rosier120eefd2013-03-19 17:32:17 +00005432 // Emit everything up to the immediate/expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00005433 if (unsigned Len = Loc - AsmStart)
Chad Rosier17d37992013-03-19 21:12:14 +00005434 OS << StringRef(AsmStart, Len);
Chad Rosier0f48c552012-10-19 20:57:14 +00005435
Chad Rosier37e755c2012-10-23 17:43:43 +00005436 // Skip the original expression.
5437 if (Kind == AOK_Skip) {
David Majnemer8114c1a2014-06-23 02:17:16 +00005438 AsmStart = Loc + AR.Len;
Chad Rosier37e755c2012-10-23 17:43:43 +00005439 continue;
5440 }
5441
Chad Rosierff10ed12013-04-12 16:26:42 +00005442 unsigned AdditionalSkip = 0;
Chad Rosier8bce6642012-10-18 15:49:34 +00005443 // Rewrite expressions in $N notation.
Chad Rosier0f48c552012-10-19 20:57:14 +00005444 switch (Kind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00005445 default:
5446 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005447 case AOK_Imm:
David Majnemer8114c1a2014-06-23 02:17:16 +00005448 OS << "$$" << AR.Val;
Chad Rosier11c42f22012-10-26 18:04:20 +00005449 break;
5450 case AOK_ImmPrefix:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005451 OS << "$$";
Chad Rosier8bce6642012-10-18 15:49:34 +00005452 break;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005453 case AOK_Label:
Matt Arsenault4e273432014-12-04 00:06:57 +00005454 OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005455 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005456 case AOK_Input:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005457 OS << '$' << InputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00005458 break;
5459 case AOK_Output:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005460 OS << '$' << OutputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00005461 break;
Chad Rosier0f48c552012-10-19 20:57:14 +00005462 case AOK_SizeDirective:
David Majnemer8114c1a2014-06-23 02:17:16 +00005463 switch (AR.Val) {
Chad Rosier0f48c552012-10-19 20:57:14 +00005464 default: break;
5465 case 8: OS << "byte ptr "; break;
5466 case 16: OS << "word ptr "; break;
5467 case 32: OS << "dword ptr "; break;
5468 case 64: OS << "qword ptr "; break;
5469 case 80: OS << "xword ptr "; break;
5470 case 128: OS << "xmmword ptr "; break;
5471 case 256: OS << "ymmword ptr "; break;
5472 }
Eli Friedman0f4871d2012-10-22 23:58:19 +00005473 break;
5474 case AOK_Emit:
5475 OS << ".byte";
5476 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00005477 case AOK_Align: {
Reid Klecknerfb1c1c72015-10-27 17:32:48 +00005478 // MS alignment directives are measured in bytes. If the native assembler
5479 // measures alignment in bytes, we can pass it straight through.
5480 OS << ".align";
5481 if (getContext().getAsmInfo()->getAlignmentIsInBytes())
5482 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00005483
Reid Klecknerfb1c1c72015-10-27 17:32:48 +00005484 // Alignment is in log2 form, so print that instead and skip the original
5485 // immediate.
5486 unsigned Val = AR.Val;
5487 OS << ' ' << Val;
Benjamin Kramer1a136112013-02-15 20:37:21 +00005488 assert(Val < 10 && "Expected alignment less then 2^10.");
Chad Rosierc7f552c2013-02-12 21:33:51 +00005489 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
5490 break;
5491 }
Michael Zuckerman02ecd432015-12-13 17:07:23 +00005492 case AOK_EVEN:
5493 OS << ".even";
5494 break;
Chad Rosierf0e87202012-10-25 20:41:34 +00005495 case AOK_DotOperator:
Reid Kleckner94a1c4d2014-03-06 19:19:12 +00005496 // Insert the dot if the user omitted it.
Alp Tokere69170a2014-06-26 22:52:05 +00005497 OS.flush();
5498 if (AsmStringIR.back() != '.')
Reid Kleckner94a1c4d2014-03-06 19:19:12 +00005499 OS << '.';
David Majnemer8114c1a2014-06-23 02:17:16 +00005500 OS << AR.Val;
Chad Rosierf0e87202012-10-25 20:41:34 +00005501 break;
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00005502 case AOK_EndOfStatement:
5503 OS << "\n\t";
5504 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005505 }
Chad Rosier0f48c552012-10-19 20:57:14 +00005506
Chad Rosier8bce6642012-10-18 15:49:34 +00005507 // Skip the original expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00005508 AsmStart = Loc + AR.Len + AdditionalSkip;
Chad Rosier8bce6642012-10-18 15:49:34 +00005509 }
5510
5511 // Emit the remainder of the asm string.
Chad Rosier17d37992013-03-19 21:12:14 +00005512 if (AsmStart != AsmEnd)
5513 OS << StringRef(AsmStart, AsmEnd - AsmStart);
Chad Rosier8bce6642012-10-18 15:49:34 +00005514
5515 AsmString = OS.str();
5516 return false;
5517}
5518
Pete Cooper80d21cb2015-06-22 19:35:57 +00005519namespace llvm {
5520namespace MCParserUtils {
5521
5522/// Returns whether the given symbol is used anywhere in the given expression,
5523/// or subexpressions.
5524static bool isSymbolUsedInExpression(const MCSymbol *Sym, const MCExpr *Value) {
5525 switch (Value->getKind()) {
5526 case MCExpr::Binary: {
5527 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
5528 return isSymbolUsedInExpression(Sym, BE->getLHS()) ||
5529 isSymbolUsedInExpression(Sym, BE->getRHS());
5530 }
5531 case MCExpr::Target:
5532 case MCExpr::Constant:
5533 return false;
5534 case MCExpr::SymbolRef: {
5535 const MCSymbol &S =
5536 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
5537 if (S.isVariable())
5538 return isSymbolUsedInExpression(Sym, S.getVariableValue());
5539 return &S == Sym;
5540 }
5541 case MCExpr::Unary:
5542 return isSymbolUsedInExpression(
5543 Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
5544 }
5545
5546 llvm_unreachable("Unknown expr kind!");
5547}
5548
5549bool parseAssignmentExpression(StringRef Name, bool allow_redef,
5550 MCAsmParser &Parser, MCSymbol *&Sym,
5551 const MCExpr *&Value) {
Pete Cooper80d21cb2015-06-22 19:35:57 +00005552
5553 // FIXME: Use better location, we should use proper tokens.
Nirav Davefd910412016-06-17 16:06:17 +00005554 SMLoc EqualLoc = Parser.getTok().getLoc();
Pete Cooper80d21cb2015-06-22 19:35:57 +00005555
5556 if (Parser.parseExpression(Value)) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00005557 return Parser.TokError("missing expression");
Pete Cooper80d21cb2015-06-22 19:35:57 +00005558 }
5559
5560 // Note: we don't count b as used in "a = b". This is to allow
5561 // a = b
5562 // b = c
5563
Nirav Dave1a9044b2016-10-24 14:35:29 +00005564 if (Parser.parseToken(AsmToken::EndOfStatement))
5565 return true;
Pete Cooper80d21cb2015-06-22 19:35:57 +00005566
5567 // Validate that the LHS is allowed to be a variable (either it has not been
5568 // used as a symbol, or it is an absolute symbol).
5569 Sym = Parser.getContext().lookupSymbol(Name);
5570 if (Sym) {
5571 // Diagnose assignment to a label.
5572 //
5573 // FIXME: Diagnostics. Note the location of the definition as a label.
5574 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
5575 if (isSymbolUsedInExpression(Sym, Value))
5576 return Parser.Error(EqualLoc, "Recursive use of '" + Name + "'");
Vedant Kumar86dbd922015-08-31 17:44:53 +00005577 else if (Sym->isUndefined(/*SetUsed*/ false) && !Sym->isUsed() &&
5578 !Sym->isVariable())
Pete Cooper80d21cb2015-06-22 19:35:57 +00005579 ; // Allow redefinitions of undefined symbols only used in directives.
5580 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
5581 ; // Allow redefinitions of variables that haven't yet been used.
5582 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
5583 return Parser.Error(EqualLoc, "redefinition of '" + Name + "'");
5584 else if (!Sym->isVariable())
5585 return Parser.Error(EqualLoc, "invalid assignment to '" + Name + "'");
5586 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
5587 return Parser.Error(EqualLoc,
5588 "invalid reassignment of non-absolute variable '" +
5589 Name + "'");
Pete Cooper80d21cb2015-06-22 19:35:57 +00005590 } else if (Name == ".") {
Oliver Stannard268f42f2016-12-14 10:43:58 +00005591 Parser.getStreamer().emitValueToOffset(Value, 0, EqualLoc);
Pete Cooper80d21cb2015-06-22 19:35:57 +00005592 return false;
5593 } else
5594 Sym = Parser.getContext().getOrCreateSymbol(Name);
5595
5596 Sym->setRedefinable(allow_redef);
5597
5598 return false;
5599}
5600
Eugene Zelenko33d7b762016-08-23 17:14:32 +00005601} // end namespace MCParserUtils
5602} // end namespace llvm
Pete Cooper80d21cb2015-06-22 19:35:57 +00005603
Daniel Dunbar01e36072010-07-17 02:26:10 +00005604/// \brief Create an MCAsmParser instance.
Jim Grosbach4b905842013-09-20 23:08:21 +00005605MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
Sanne Wouda29338752017-02-08 14:48:05 +00005606 MCStreamer &Out, const MCAsmInfo &MAI,
5607 unsigned CB) {
5608 return new AsmParser(SM, C, Out, MAI, CB);
Daniel Dunbar01e36072010-07-17 02:26:10 +00005609}