blob: a8497092448c28e57a8fde354234861663cc511d [file] [log] [blame]
Chris Lattnerb0133452009-06-21 20:16:42 +00001//===- AsmParser.cpp - Parser for Assembly Files --------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This class implements the parser for assembly files.
11//
12//===----------------------------------------------------------------------===//
13
Daniel Dunbar2af16532010-09-24 01:59:56 +000014#include "llvm/ADT/APFloat.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000015#include "llvm/ADT/APInt.h"
16#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/None.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000018#include "llvm/ADT/SmallString.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000019#include "llvm/ADT/SmallVector.h"
20#include "llvm/ADT/STLExtras.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000021#include "llvm/ADT/StringMap.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000022#include "llvm/ADT/StringRef.h"
Daniel Dunbareb6bb322009-07-27 23:20:52 +000023#include "llvm/ADT/Twine.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000024#include "llvm/MC/MCAsmInfo.h"
Reid Klecknera5b1eef2016-08-26 17:58:37 +000025#include "llvm/MC/MCCodeView.h"
Daniel Dunbarca29e4d2009-06-23 22:01:43 +000026#include "llvm/MC/MCContext.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000027#include "llvm/MC/MCDirectives.h"
Evan Cheng11424442011-07-26 00:24:13 +000028#include "llvm/MC/MCDwarf.h"
Daniel Dunbar115e4d62009-08-31 08:06:59 +000029#include "llvm/MC/MCExpr.h"
Chad Rosier8bce6642012-10-18 15:49:34 +000030#include "llvm/MC/MCInstPrinter.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000031#include "llvm/MC/MCInstrDesc.h"
Chad Rosier8bce6642012-10-18 15:49:34 +000032#include "llvm/MC/MCInstrInfo.h"
Rafael Espindolae28610d2013-12-09 20:26:40 +000033#include "llvm/MC/MCObjectFileInfo.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000034#include "llvm/MC/MCParser/AsmCond.h"
35#include "llvm/MC/MCParser/AsmLexer.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000036#include "llvm/MC/MCParser/MCAsmLexer.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000037#include "llvm/MC/MCParser/MCAsmParser.h"
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +000038#include "llvm/MC/MCParser/MCAsmParserExtension.h"
Pete Cooper80d21cb2015-06-22 19:35:57 +000039#include "llvm/MC/MCParser/MCAsmParserUtils.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000040#include "llvm/MC/MCParser/MCParsedAsmOperand.h"
Benjamin Kramerb3e8a6d2016-01-27 10:01:28 +000041#include "llvm/MC/MCParser/MCTargetAsmParser.h"
Evan Cheng76792992011-07-20 05:58:47 +000042#include "llvm/MC/MCRegisterInfo.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000043#include "llvm/MC/MCSection.h"
Daniel Dunbarca29e4d2009-06-23 22:01:43 +000044#include "llvm/MC/MCStreamer.h"
Daniel Dunbarae7ac012009-06-29 23:43:14 +000045#include "llvm/MC/MCSymbol.h"
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +000046#include "llvm/MC/MCTargetOptions.h"
Daniel Sanders9f6ad492015-11-12 13:33:00 +000047#include "llvm/MC/MCValue.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000048#include "llvm/Support/Casting.h"
Davide Italiano7c9fc732016-07-27 05:51:56 +000049#include "llvm/Support/CommandLine.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000050#include "llvm/Support/Dwarf.h"
Benjamin Kramer4efe5062012-01-28 15:28:41 +000051#include "llvm/Support/ErrorHandling.h"
Jim Grosbach76346c32011-06-29 16:05:14 +000052#include "llvm/Support/MathExtras.h"
Kevin Enderbye233dda2010-06-28 21:45:58 +000053#include "llvm/Support/MemoryBuffer.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000054#include "llvm/Support/SMLoc.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000055#include "llvm/Support/SourceMgr.h"
Chris Lattner36e02122009-06-21 20:54:55 +000056#include "llvm/Support/raw_ostream.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000057#include <algorithm>
58#include <cassert>
Nick Lewycky0de20af2010-12-19 20:43:38 +000059#include <cctype>
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +000060#include <climits>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000061#include <cstddef>
62#include <cstdint>
Benjamin Kramerd59664f2014-04-29 23:26:49 +000063#include <deque>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000064#include <memory>
Davide Italiano7c9fc732016-07-27 05:51:56 +000065#include <sstream>
Chad Rosier8bce6642012-10-18 15:49:34 +000066#include <string>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000067#include <tuple>
68#include <utility>
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000069#include <vector>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000070
Chris Lattnerb0133452009-06-21 20:16:42 +000071using namespace llvm;
72
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +000073MCAsmParserSemaCallback::~MCAsmParserSemaCallback() = default;
Nick Lewyckyac612272012-10-19 07:00:09 +000074
Davide Italiano7c9fc732016-07-27 05:51:56 +000075static cl::opt<unsigned> AsmMacroMaxNestingDepth(
76 "asm-macro-max-nesting-depth", cl::init(20), cl::Hidden,
77 cl::desc("The maximum nesting depth allowed for assembly macros."));
78
Daniel Dunbar86033402010-07-12 17:54:38 +000079namespace {
Eugene Zelenko33d7b762016-08-23 17:14:32 +000080
Eli Benderskya313ae62013-01-16 18:56:50 +000081/// \brief Helper types for tracking macro definitions.
82typedef std::vector<AsmToken> MCAsmMacroArgument;
83typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +000084
85struct MCAsmMacroParameter {
86 StringRef Name;
87 MCAsmMacroArgument Value;
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +000088 bool Required = false;
89 bool Vararg = false;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +000090
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +000091 MCAsmMacroParameter() = default;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +000092};
93
Eli Benderskya313ae62013-01-16 18:56:50 +000094typedef std::vector<MCAsmMacroParameter> MCAsmMacroParameters;
95
96struct MCAsmMacro {
97 StringRef Name;
98 StringRef Body;
99 MCAsmMacroParameters Parameters;
100
101public:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000102 MCAsmMacro(StringRef N, StringRef B, MCAsmMacroParameters P)
103 : Name(N), Body(B), Parameters(std::move(P)) {}
Eli Benderskya313ae62013-01-16 18:56:50 +0000104};
105
Daniel Dunbar43235712010-07-18 18:54:11 +0000106/// \brief Helper class for storing information about an active macro
107/// instantiation.
108struct MacroInstantiation {
Daniel Dunbar43235712010-07-18 18:54:11 +0000109 /// The location of the instantiation.
110 SMLoc InstantiationLoc;
111
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000112 /// The buffer where parsing should resume upon instantiation completion.
113 int ExitBuffer;
114
Daniel Dunbar43235712010-07-18 18:54:11 +0000115 /// The location where parsing should resume upon instantiation completion.
116 SMLoc ExitLoc;
117
Nico Weber155dccd12014-07-24 17:08:39 +0000118 /// The depth of TheCondStack at the start of the instantiation.
119 size_t CondStackDepth;
120
Daniel Dunbar43235712010-07-18 18:54:11 +0000121public:
Rafael Espindola9eef18c2014-08-27 19:49:03 +0000122 MacroInstantiation(SMLoc IL, int EB, SMLoc EL, size_t CondStackDepth);
Daniel Dunbar43235712010-07-18 18:54:11 +0000123};
124
Eli Friedman0f4871d2012-10-22 23:58:19 +0000125struct ParseStatementInfo {
Jim Grosbach4b905842013-09-20 23:08:21 +0000126 /// \brief The parsed operands from the last parsed statement.
David Blaikie960ea3f2014-06-08 16:18:35 +0000127 SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> ParsedOperands;
Eli Friedman0f4871d2012-10-22 23:58:19 +0000128
Jim Grosbach4b905842013-09-20 23:08:21 +0000129 /// \brief The opcode from the last parsed instruction.
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000130 unsigned Opcode = ~0U;
Eli Friedman0f4871d2012-10-22 23:58:19 +0000131
Jim Grosbach4b905842013-09-20 23:08:21 +0000132 /// \brief Was there an error parsing the inline assembly?
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000133 bool ParseError = false;
Chad Rosier149e8e02012-12-12 22:45:52 +0000134
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000135 SmallVectorImpl<AsmRewrite> *AsmRewrites = nullptr;
Eli Friedman0f4871d2012-10-22 23:58:19 +0000136
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000137 ParseStatementInfo() = default;
Eli Friedman0f4871d2012-10-22 23:58:19 +0000138 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000139 : AsmRewrites(rewrites) {}
Eli Friedman0f4871d2012-10-22 23:58:19 +0000140};
141
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000142/// \brief The concrete assembly parser instance.
143class AsmParser : public MCAsmParser {
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000144private:
145 AsmLexer Lexer;
146 MCContext &Ctx;
147 MCStreamer &Out;
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000148 const MCAsmInfo &MAI;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000149 SourceMgr &SrcMgr;
Benjamin Kramer47f5e302011-10-16 10:48:29 +0000150 SourceMgr::DiagHandlerTy SavedDiagHandler;
151 void *SavedDiagContext;
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000152 std::unique_ptr<MCAsmParserExtension> PlatformParser;
Rafael Espindola82065cb2011-04-11 21:49:50 +0000153
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000154 /// This is the current buffer index we're lexing from as managed by the
155 /// SourceMgr object.
Alp Tokera55b95b2014-07-06 10:33:31 +0000156 unsigned CurBuffer;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000157
158 AsmCond TheCondState;
159 std::vector<AsmCond> TheCondStack;
160
Jim Grosbach4b905842013-09-20 23:08:21 +0000161 /// \brief maps directive names to handler methods in parser
Eli Bendersky17233942013-01-15 22:59:42 +0000162 /// extensions. Extensions register themselves in this map by calling
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000163 /// addDirectiveHandler.
Eli Bendersky17233942013-01-15 22:59:42 +0000164 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
Daniel Dunbar828984f2010-07-18 18:38:02 +0000165
Jim Grosbach4b905842013-09-20 23:08:21 +0000166 /// \brief Map of currently defined macros.
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000167 StringMap<MCAsmMacro> MacroMap;
Daniel Dunbarc1f58ec2010-07-18 18:47:21 +0000168
Jim Grosbach4b905842013-09-20 23:08:21 +0000169 /// \brief Stack of active macro instantiations.
Daniel Dunbar43235712010-07-18 18:54:11 +0000170 std::vector<MacroInstantiation*> ActiveMacros;
171
Jim Grosbach4b905842013-09-20 23:08:21 +0000172 /// \brief List of bodies of anonymous macros.
Benjamin Kramer1df3a1f2013-08-04 09:06:29 +0000173 std::deque<MCAsmMacro> MacroLikeBodies;
174
Daniel Dunbar828984f2010-07-18 18:38:02 +0000175 /// Boolean tracking whether macro substitution is enabled.
Eli Benderskyc2f6f922013-01-14 18:08:41 +0000176 unsigned MacrosEnabledFlag : 1;
Daniel Dunbar828984f2010-07-18 18:38:02 +0000177
Toma Tabacu217116e2015-04-27 10:50:29 +0000178 /// \brief Keeps track of how many .macro's have been instantiated.
179 unsigned NumOfMacroInstantiations;
180
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000181 /// The values from the last parsed cpp hash file line comment if any.
Tim Northoverc0bef992016-04-13 19:46:54 +0000182 struct CppHashInfoTy {
183 StringRef Filename;
Andrew Kaylorca196472016-04-21 20:09:35 +0000184 int64_t LineNumber = 0;
Tim Northoverc0bef992016-04-13 19:46:54 +0000185 SMLoc Loc;
Andrew Kaylorca196472016-04-21 20:09:35 +0000186 unsigned Buf = 0;
Tim Northoverc0bef992016-04-13 19:46:54 +0000187 };
188 CppHashInfoTy CppHashInfo;
189
190 /// \brief List of forward directional labels for diagnosis at the end.
191 SmallVector<std::tuple<SMLoc, CppHashInfoTy, MCSymbol *>, 4> DirLabels;
192
Kevin Enderby0fd064c2013-06-21 20:51:39 +0000193 /// When generating dwarf for assembly source files we need to calculate the
194 /// logical line number based on the last parsed cpp hash file line comment
Vladimir Medic9bad0d332013-08-20 13:33:18 +0000195 /// and current line. Since this is slow and messes up the SourceMgr's
Kevin Enderby0fd064c2013-06-21 20:51:39 +0000196 /// cache we save the last info we queried with SrcMgr.FindLineNumber().
197 SMLoc LastQueryIDLoc;
Alp Tokera55b95b2014-07-06 10:33:31 +0000198 unsigned LastQueryBuffer;
Kevin Enderby0fd064c2013-06-21 20:51:39 +0000199 unsigned LastQueryLine;
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000200
Devang Patela173ee52012-01-31 18:14:05 +0000201 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000202 unsigned AssemblerDialect = ~0U;
Devang Patela173ee52012-01-31 18:14:05 +0000203
Jim Grosbach4b905842013-09-20 23:08:21 +0000204 /// \brief is Darwin compatibility enabled?
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000205 bool IsDarwin = false;
Preston Gurd05500642012-09-19 20:36:12 +0000206
Jim Grosbach4b905842013-09-20 23:08:21 +0000207 /// \brief Are we parsing ms-style inline assembly?
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000208 bool ParsingInlineAsm = false;
Chad Rosier49963552012-10-13 00:26:04 +0000209
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000210public:
Jim Grosbach345768c2011-08-16 18:33:49 +0000211 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Sanne Wouda29338752017-02-08 14:48:05 +0000212 const MCAsmInfo &MAI, unsigned CB);
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000213 AsmParser(const AsmParser &) = delete;
214 AsmParser &operator=(const AsmParser &) = delete;
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000215 ~AsmParser() override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000216
Craig Topper59be68f2014-03-08 07:14:16 +0000217 bool Run(bool NoInitialTextSection, bool NoFinalize = false) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000218
Craig Topper59be68f2014-03-08 07:14:16 +0000219 void addDirectiveHandler(StringRef Directive,
220 ExtensionDirectiveHandler Handler) override {
Eli Bendersky29b9f472013-01-16 00:50:52 +0000221 ExtensionDirectiveMap[Directive] = Handler;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000222 }
223
Toma Tabacu11e14a92015-04-21 11:50:52 +0000224 void addAliasForDirective(StringRef Directive, StringRef Alias) override {
225 DirectiveKindMap[Directive] = DirectiveKindMap[Alias];
226 }
227
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000228 /// @name MCAsmParser Interface
229 /// {
230
Craig Topper59be68f2014-03-08 07:14:16 +0000231 SourceMgr &getSourceManager() override { return SrcMgr; }
232 MCAsmLexer &getLexer() override { return Lexer; }
233 MCContext &getContext() override { return Ctx; }
234 MCStreamer &getStreamer() override { return Out; }
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000235
Reid Klecknera5b1eef2016-08-26 17:58:37 +0000236 CodeViewContext &getCVContext() { return Ctx.getCVContext(); }
237
Craig Topper59be68f2014-03-08 07:14:16 +0000238 unsigned getAssemblerDialect() override {
Devang Patela173ee52012-01-31 18:14:05 +0000239 if (AssemblerDialect == ~0U)
Eric Christophera7c32732012-12-18 00:30:54 +0000240 return MAI.getAssemblerDialect();
Devang Patela173ee52012-01-31 18:14:05 +0000241 else
242 return AssemblerDialect;
243 }
Craig Topper59be68f2014-03-08 07:14:16 +0000244 void setAssemblerDialect(unsigned i) override {
Devang Patela173ee52012-01-31 18:14:05 +0000245 AssemblerDialect = i;
246 }
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000247
Nirav Dave2364748a2016-09-16 18:30:20 +0000248 void Note(SMLoc L, const Twine &Msg, SMRange Range = None) override;
249 bool Warning(SMLoc L, const Twine &Msg, SMRange Range = None) override;
250 bool printError(SMLoc L, const Twine &Msg, SMRange Range = None) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000251
Craig Topper59be68f2014-03-08 07:14:16 +0000252 const AsmToken &Lex() override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000253
Yunzhong Gao27ea29b2016-09-02 23:15:29 +0000254 void setParsingInlineAsm(bool V) override {
255 ParsingInlineAsm = V;
256 Lexer.setParsingMSInlineAsm(V);
257 }
Craig Topper59be68f2014-03-08 07:14:16 +0000258 bool isParsingInlineAsm() override { return ParsingInlineAsm; }
Chad Rosier8bce6642012-10-18 15:49:34 +0000259
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000260 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
Chad Rosier8bce6642012-10-18 15:49:34 +0000261 unsigned &NumOutputs, unsigned &NumInputs,
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000262 SmallVectorImpl<std::pair<void *,bool>> &OpDecls,
Chad Rosier8bce6642012-10-18 15:49:34 +0000263 SmallVectorImpl<std::string> &Constraints,
Chad Rosier8bce6642012-10-18 15:49:34 +0000264 SmallVectorImpl<std::string> &Clobbers,
Craig Topper59be68f2014-03-08 07:14:16 +0000265 const MCInstrInfo *MII, const MCInstPrinter *IP,
266 MCAsmParserSemaCallback &SI) override;
Chad Rosier49963552012-10-13 00:26:04 +0000267
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000268 bool parseExpression(const MCExpr *&Res);
Craig Topper59be68f2014-03-08 07:14:16 +0000269 bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
270 bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) override;
271 bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
Toma Tabacu7bc44dc2015-06-25 09:52:02 +0000272 bool parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
273 SMLoc &EndLoc) override;
Craig Topper59be68f2014-03-08 07:14:16 +0000274 bool parseAbsoluteExpression(int64_t &Res) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000275
Petr Hosek4cb08ce2016-09-23 19:25:15 +0000276 /// \brief Parse a floating point expression using the float \p Semantics
277 /// and set \p Res to the value.
278 bool parseRealValue(const fltSemantics &Semantics, APInt &Res);
279
Jim Grosbach4b905842013-09-20 23:08:21 +0000280 /// \brief Parse an identifier or string (as a quoted identifier)
Eli Bendersky0cf0cb92013-01-12 00:05:00 +0000281 /// and set \p Res to the identifier contents.
Craig Topper59be68f2014-03-08 07:14:16 +0000282 bool parseIdentifier(StringRef &Res) override;
283 void eatToEndOfStatement() override;
Eli Bendersky0cf0cb92013-01-12 00:05:00 +0000284
Nirav Davef43cc9f2016-10-10 15:24:54 +0000285 bool checkForValidSection() override;
Nirav Davea645433c2016-07-18 15:24:03 +0000286
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000287 /// }
288
289private:
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +0000290 bool parseStatement(ParseStatementInfo &Info,
291 MCAsmParserSemaCallback *SI);
Marina Yatsina5f5de9f2016-03-07 18:11:16 +0000292 bool parseCurlyBlockScope(SmallVectorImpl<AsmRewrite>& AsmStrRewrites);
Craig Topper3c76c522015-09-20 23:35:59 +0000293 bool parseCppHashLineFilenameComment(SMLoc L);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000294
Jim Grosbach4b905842013-09-20 23:08:21 +0000295 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +0000296 ArrayRef<MCAsmMacroParameter> Parameters);
Rafael Espindola34b9c512012-06-03 23:57:14 +0000297 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +0000298 ArrayRef<MCAsmMacroParameter> Parameters,
Toma Tabacu217116e2015-04-27 10:50:29 +0000299 ArrayRef<MCAsmMacroArgument> A, bool EnableAtPseudoVariable,
Craig Topper3c76c522015-09-20 23:35:59 +0000300 SMLoc L);
Daniel Dunbar43235712010-07-18 18:54:11 +0000301
Eli Benderskya313ae62013-01-16 18:56:50 +0000302 /// \brief Are macros enabled in the parser?
Jim Grosbach4b905842013-09-20 23:08:21 +0000303 bool areMacrosEnabled() {return MacrosEnabledFlag;}
Eli Benderskya313ae62013-01-16 18:56:50 +0000304
305 /// \brief Control a flag in the parser that enables or disables macros.
Jim Grosbach4b905842013-09-20 23:08:21 +0000306 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
Eli Benderskya313ae62013-01-16 18:56:50 +0000307
308 /// \brief Lookup a previously defined macro.
309 /// \param Name Macro name.
310 /// \returns Pointer to macro. NULL if no such macro was defined.
Jim Grosbach4b905842013-09-20 23:08:21 +0000311 const MCAsmMacro* lookupMacro(StringRef Name);
Eli Benderskya313ae62013-01-16 18:56:50 +0000312
313 /// \brief Define a new macro with the given name and information.
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000314 void defineMacro(StringRef Name, MCAsmMacro Macro);
Eli Benderskya313ae62013-01-16 18:56:50 +0000315
316 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
Jim Grosbach4b905842013-09-20 23:08:21 +0000317 void undefineMacro(StringRef Name);
Eli Benderskya313ae62013-01-16 18:56:50 +0000318
319 /// \brief Are we inside a macro instantiation?
Jim Grosbach4b905842013-09-20 23:08:21 +0000320 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
Eli Benderskya313ae62013-01-16 18:56:50 +0000321
Vladimir Medic9bad0d332013-08-20 13:33:18 +0000322 /// \brief Handle entry to macro instantiation.
Eli Benderskya313ae62013-01-16 18:56:50 +0000323 ///
324 /// \param M The macro.
325 /// \param NameLoc Instantiation location.
Jim Grosbach4b905842013-09-20 23:08:21 +0000326 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
Eli Benderskya313ae62013-01-16 18:56:50 +0000327
328 /// \brief Handle exit from macro instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +0000329 void handleMacroExit();
Eli Benderskya313ae62013-01-16 18:56:50 +0000330
David Majnemer91fc4c22014-01-29 18:57:46 +0000331 /// \brief Extract AsmTokens for a macro argument.
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +0000332 bool parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg);
Eli Benderskya313ae62013-01-16 18:56:50 +0000333
334 /// \brief Parse all macro arguments for a given macro.
Jim Grosbach4b905842013-09-20 23:08:21 +0000335 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
Eli Benderskya313ae62013-01-16 18:56:50 +0000336
Jim Grosbach4b905842013-09-20 23:08:21 +0000337 void printMacroInstantiations();
338 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
Nirav Dave2364748a2016-09-16 18:30:20 +0000339 SMRange Range = None) const {
340 ArrayRef<SMRange> Ranges(Range);
Chris Lattner72845262011-10-16 05:47:55 +0000341 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
Benjamin Kramerc7583112010-09-27 17:42:11 +0000342 }
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000343 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
Benjamin Kramerc7583112010-09-27 17:42:11 +0000344
Jim Grosbach4b905842013-09-20 23:08:21 +0000345 /// \brief Enter the specified file. This returns true on failure.
346 bool enterIncludeFile(const std::string &Filename);
347
348 /// \brief Process the specified file for the .incbin directive.
Kevin Enderby109f25c2011-12-14 21:47:48 +0000349 /// This returns true on failure.
Petr Hosek2f4ac442016-09-23 00:41:06 +0000350 bool processIncbinFile(const std::string &Filename, int64_t Skip = 0,
351 const MCExpr *Count = nullptr, SMLoc Loc = SMLoc());
Daniel Dunbar43235712010-07-18 18:54:11 +0000352
Dmitri Gribenko5485acd2012-09-14 14:57:36 +0000353 /// \brief Reset the current lexer position to that given by \p Loc. The
Daniel Dunbar43235712010-07-18 18:54:11 +0000354 /// current token is not set; clients should ensure Lex() is called
355 /// subsequently.
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000356 ///
Alp Tokera55b95b2014-07-06 10:33:31 +0000357 /// \param InBuffer If not 0, should be the known buffer id that contains the
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000358 /// location.
Alp Tokera55b95b2014-07-06 10:33:31 +0000359 void jumpToLoc(SMLoc Loc, unsigned InBuffer = 0);
Daniel Dunbar43235712010-07-18 18:54:11 +0000360
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000361 /// \brief Parse up to the end of statement and a return the contents from the
362 /// current token until the end of the statement; the current token on exit
363 /// will be either the EndOfStatement or EOF.
Craig Topper59be68f2014-03-08 07:14:16 +0000364 StringRef parseStringToEndOfStatement() override;
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000365
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000366 /// \brief Parse until the end of a statement or a comma is encountered,
367 /// return the contents from the current token up to the end or comma.
Jim Grosbach4b905842013-09-20 23:08:21 +0000368 StringRef parseStringToComma();
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000369
Jim Grosbach4b905842013-09-20 23:08:21 +0000370 bool parseAssignment(StringRef Name, bool allow_redef,
Jim Grosbachb7b750d2012-09-13 23:11:31 +0000371 bool NoDeadStrip = false);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000372
Ahmed Bougacha457852f2015-04-28 00:17:39 +0000373 unsigned getBinOpPrecedence(AsmToken::TokenKind K,
374 MCBinaryExpr::Opcode &Kind);
375
Jim Grosbach4b905842013-09-20 23:08:21 +0000376 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
377 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
378 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000379
Jim Grosbach4b905842013-09-20 23:08:21 +0000380 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
Rafael Espindola63760ba2010-10-28 20:02:27 +0000381
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000382 bool parseCVFunctionId(int64_t &FunctionId, StringRef DirectiveName);
383 bool parseCVFileId(int64_t &FileId, StringRef DirectiveName);
384
Eli Bendersky17233942013-01-15 22:59:42 +0000385 // Generic (target and platform independent) directive parsing.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000386 enum DirectiveKind {
Eli Bendersky4d21fa02013-01-10 23:40:56 +0000387 DK_NO_DIRECTIVE, // Placeholder
388 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
Daniel Sanders9f6ad492015-11-12 13:33:00 +0000389 DK_RELOC,
David Woodhoused6de0d92014-02-01 16:20:59 +0000390 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_OCTA,
Petr Hosek731bb9c2016-08-23 21:34:53 +0000391 DK_DC, DK_DC_A, DK_DC_B, DK_DC_D, DK_DC_L, DK_DC_S, DK_DC_W, DK_DC_X,
Petr Hosek4cb08ce2016-09-23 19:25:15 +0000392 DK_DCB, DK_DCB_B, DK_DCB_D, DK_DCB_L, DK_DCB_S, DK_DCB_W, DK_DCB_X,
Petr Hosek85b2f672016-09-23 21:53:36 +0000393 DK_DS, DK_DS_B, DK_DS_D, DK_DS_L, DK_DS_P, DK_DS_S, DK_DS_W, DK_DS_X,
David Woodhoused6de0d92014-02-01 16:20:59 +0000394 DK_SINGLE, DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
Eli Bendersky96522722013-01-11 22:55:28 +0000395 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
Eli Bendersky4d21fa02013-01-10 23:40:56 +0000396 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
Kevin Enderby3aeada22013-08-28 17:50:59 +0000397 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL,
Lang Hamesf9033bb2016-04-11 18:33:45 +0000398 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER,
Lang Hames1b640e02016-03-15 01:43:05 +0000399 DK_PRIVATE_EXTERN, DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
Eli Bendersky4d21fa02013-01-10 23:40:56 +0000400 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
401 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +0000402 DK_IF, DK_IFEQ, DK_IFGE, DK_IFGT, DK_IFLE, DK_IFLT, DK_IFNE, DK_IFB,
Sid Manning51c35602015-03-18 14:20:54 +0000403 DK_IFNB, DK_IFC, DK_IFEQS, DK_IFNC, DK_IFNES, DK_IFDEF, DK_IFNDEF,
404 DK_IFNOTDEF, DK_ELSEIF, DK_ELSE, DK_ENDIF,
Eli Bendersky17233942013-01-15 22:59:42 +0000405 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000406 DK_CV_FILE, DK_CV_FUNC_ID, DK_CV_INLINE_SITE_ID, DK_CV_LOC, DK_CV_LINETABLE,
407 DK_CV_INLINE_LINETABLE, DK_CV_DEF_RANGE, DK_CV_STRINGTABLE,
408 DK_CV_FILECHECKSUMS,
Eli Bendersky17233942013-01-15 22:59:42 +0000409 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
410 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
411 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
412 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
413 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +0000414 DK_CFI_REGISTER, DK_CFI_WINDOW_SAVE,
Nico Weber155dccd12014-07-24 17:08:39 +0000415 DK_MACROS_ON, DK_MACROS_OFF,
416 DK_MACRO, DK_EXITM, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000417 DK_SLEB128, DK_ULEB128,
Nico Weber404012b2014-07-24 16:26:06 +0000418 DK_ERR, DK_ERROR, DK_WARNING,
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000419 DK_END
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000420 };
421
Jim Grosbach4b905842013-09-20 23:08:21 +0000422 /// \brief Maps directive name --> DirectiveKind enum, for
Eli Bendersky17233942013-01-15 22:59:42 +0000423 /// directives parsed by this class.
424 StringMap<DirectiveKind> DirectiveKindMap;
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000425
426 // ".ascii", ".asciz", ".string"
Jim Grosbach4b905842013-09-20 23:08:21 +0000427 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
Daniel Sanders9f6ad492015-11-12 13:33:00 +0000428 bool parseDirectiveReloc(SMLoc DirectiveLoc); // ".reloc"
Nirav Dave1a9044b2016-10-24 14:35:29 +0000429 bool parseDirectiveValue(StringRef IDVal,
430 unsigned Size); // ".byte", ".long", ...
431 bool parseDirectiveOctaValue(StringRef IDVal); // ".octa", ...
432 bool parseDirectiveRealValue(StringRef IDVal,
433 const fltSemantics &); // ".single", ...
Jim Grosbach4b905842013-09-20 23:08:21 +0000434 bool parseDirectiveFill(); // ".fill"
435 bool parseDirectiveZero(); // ".zero"
Eric Christophera7c32732012-12-18 00:30:54 +0000436 // ".set", ".equ", ".equiv"
Jim Grosbach4b905842013-09-20 23:08:21 +0000437 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
438 bool parseDirectiveOrg(); // ".org"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000439 // ".align{,32}", ".p2align{,w,l}"
Jim Grosbach4b905842013-09-20 23:08:21 +0000440 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000441
Eli Bendersky17233942013-01-15 22:59:42 +0000442 // ".file", ".line", ".loc", ".stabs"
Jim Grosbach4b905842013-09-20 23:08:21 +0000443 bool parseDirectiveFile(SMLoc DirectiveLoc);
444 bool parseDirectiveLine();
445 bool parseDirectiveLoc();
446 bool parseDirectiveStabs();
Eli Bendersky17233942013-01-15 22:59:42 +0000447
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000448 // ".cv_file", ".cv_func_id", ".cv_inline_site_id", ".cv_loc", ".cv_linetable",
449 // ".cv_inline_linetable", ".cv_def_range"
Reid Kleckner2214ed82016-01-29 00:49:42 +0000450 bool parseDirectiveCVFile();
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000451 bool parseDirectiveCVFuncId();
452 bool parseDirectiveCVInlineSiteId();
Reid Kleckner2214ed82016-01-29 00:49:42 +0000453 bool parseDirectiveCVLoc();
454 bool parseDirectiveCVLinetable();
David Majnemer6fcbd7e2016-01-29 19:24:12 +0000455 bool parseDirectiveCVInlineLinetable();
David Majnemer408b5e62016-02-05 01:55:49 +0000456 bool parseDirectiveCVDefRange();
Reid Kleckner2214ed82016-01-29 00:49:42 +0000457 bool parseDirectiveCVStringTable();
458 bool parseDirectiveCVFileChecksums();
459
Eli Bendersky17233942013-01-15 22:59:42 +0000460 // .cfi directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000461 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +0000462 bool parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +0000463 bool parseDirectiveCFISections();
464 bool parseDirectiveCFIStartProc();
465 bool parseDirectiveCFIEndProc();
466 bool parseDirectiveCFIDefCfaOffset();
467 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
468 bool parseDirectiveCFIAdjustCfaOffset();
469 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
470 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
471 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
472 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
473 bool parseDirectiveCFIRememberState();
474 bool parseDirectiveCFIRestoreState();
475 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
476 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
477 bool parseDirectiveCFIEscape();
478 bool parseDirectiveCFISignalFrame();
479 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
Eli Bendersky17233942013-01-15 22:59:42 +0000480
481 // macro directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000482 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
Nico Weber155dccd12014-07-24 17:08:39 +0000483 bool parseDirectiveExitMacro(StringRef Directive);
Jim Grosbach4b905842013-09-20 23:08:21 +0000484 bool parseDirectiveEndMacro(StringRef Directive);
485 bool parseDirectiveMacro(SMLoc DirectiveLoc);
486 bool parseDirectiveMacrosOnOff(StringRef Directive);
Eli Bendersky17233942013-01-15 22:59:42 +0000487
Eli Benderskyf483ff92012-12-20 19:05:53 +0000488 // ".bundle_align_mode"
Jim Grosbach4b905842013-09-20 23:08:21 +0000489 bool parseDirectiveBundleAlignMode();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000490 // ".bundle_lock"
Jim Grosbach4b905842013-09-20 23:08:21 +0000491 bool parseDirectiveBundleLock();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000492 // ".bundle_unlock"
Jim Grosbach4b905842013-09-20 23:08:21 +0000493 bool parseDirectiveBundleUnlock();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000494
Eli Bendersky17233942013-01-15 22:59:42 +0000495 // ".space", ".skip"
Jim Grosbach4b905842013-09-20 23:08:21 +0000496 bool parseDirectiveSpace(StringRef IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +0000497
Petr Hosek4cb08ce2016-09-23 19:25:15 +0000498 // ".dcb"
499 bool parseDirectiveDCB(StringRef IDVal, unsigned Size);
500 bool parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &);
Petr Hosek85b2f672016-09-23 21:53:36 +0000501 // ".ds"
502 bool parseDirectiveDS(StringRef IDVal, unsigned Size);
Petr Hosek4cb08ce2016-09-23 19:25:15 +0000503
Eli Bendersky17233942013-01-15 22:59:42 +0000504 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
Jim Grosbach4b905842013-09-20 23:08:21 +0000505 bool parseDirectiveLEB128(bool Signed);
Eli Bendersky17233942013-01-15 22:59:42 +0000506
Jim Grosbach4b905842013-09-20 23:08:21 +0000507 /// \brief Parse a directive like ".globl" which
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000508 /// accepts a single symbol (which should be a label or an external).
Jim Grosbach4b905842013-09-20 23:08:21 +0000509 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000510
Jim Grosbach4b905842013-09-20 23:08:21 +0000511 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000512
Jim Grosbach4b905842013-09-20 23:08:21 +0000513 bool parseDirectiveAbort(); // ".abort"
514 bool parseDirectiveInclude(); // ".include"
515 bool parseDirectiveIncbin(); // ".incbin"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000516
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +0000517 // ".if", ".ifeq", ".ifge", ".ifgt" , ".ifle", ".iflt" or ".ifne"
518 bool parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind);
Benjamin Kramer62c18b02012-05-12 11:18:42 +0000519 // ".ifb" or ".ifnb", depending on ExpectBlank.
Jim Grosbach4b905842013-09-20 23:08:21 +0000520 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000521 // ".ifc" or ".ifnc", depending on ExpectEqual.
Jim Grosbach4b905842013-09-20 23:08:21 +0000522 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
Sid Manning51c35602015-03-18 14:20:54 +0000523 // ".ifeqs" or ".ifnes", depending on ExpectEqual.
524 bool parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +0000525 // ".ifdef" or ".ifndef", depending on expect_defined
Jim Grosbach4b905842013-09-20 23:08:21 +0000526 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
527 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
528 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
529 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
Craig Topper59be68f2014-03-08 07:14:16 +0000530 bool parseEscapedString(std::string &Data) override;
Daniel Dunbar55f16672010-09-17 02:47:07 +0000531
Jim Grosbach4b905842013-09-20 23:08:21 +0000532 const MCExpr *applyModifierToExpr(const MCExpr *E,
Daniel Dunbar55f16672010-09-17 02:47:07 +0000533 MCSymbolRefExpr::VariantKind Variant);
Rafael Espindola47b7dac2012-05-12 16:31:10 +0000534
Rafael Espindola34b9c512012-06-03 23:57:14 +0000535 // Macro-like directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000536 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
537 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +0000538 raw_svector_ostream &OS);
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +0000539 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
Jim Grosbach4b905842013-09-20 23:08:21 +0000540 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
541 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
542 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
Chad Rosier8bce6642012-10-18 15:49:34 +0000543
Chad Rosierc7f552c2013-02-12 21:33:51 +0000544 // "_emit" or "__emit"
Jim Grosbach4b905842013-09-20 23:08:21 +0000545 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
Chad Rosierc7f552c2013-02-12 21:33:51 +0000546 size_t Len);
547
548 // "align"
Jim Grosbach4b905842013-09-20 23:08:21 +0000549 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000550
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000551 // "end"
552 bool parseDirectiveEnd(SMLoc DirectiveLoc);
553
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +0000554 // ".err" or ".error"
555 bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +0000556
Nico Weber404012b2014-07-24 16:26:06 +0000557 // ".warning"
558 bool parseDirectiveWarning(SMLoc DirectiveLoc);
559
Eli Bendersky17233942013-01-15 22:59:42 +0000560 void initializeDirectiveKindMap();
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000561};
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000562
563} // end anonymous namespace
Daniel Dunbar86033402010-07-12 17:54:38 +0000564
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000565namespace llvm {
566
567extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbarab058b82010-07-12 21:23:32 +0000568extern MCAsmParserExtension *createELFAsmParser();
Michael J. Spencerc8dbdfd2010-10-09 11:01:07 +0000569extern MCAsmParserExtension *createCOFFAsmParser();
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000570
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000571} // end namespace llvm
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000572
Chris Lattnerc35681b2010-01-19 19:46:13 +0000573enum { DEFAULT_ADDRSPACE = 0 };
574
David Blaikie9f380a32015-03-16 18:06:57 +0000575AsmParser::AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Sanne Wouda29338752017-02-08 14:48:05 +0000576 const MCAsmInfo &MAI, unsigned CB = 0)
David Blaikie9f380a32015-03-16 18:06:57 +0000577 : Lexer(MAI), Ctx(Ctx), Out(Out), MAI(MAI), SrcMgr(SM),
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000578 CurBuffer(CB ? CB : SM.getMainFileID()), MacrosEnabledFlag(true) {
Nirav Dave2364748a2016-09-16 18:30:20 +0000579 HadError = false;
Benjamin Kramer47f5e302011-10-16 10:48:29 +0000580 // Save the old handler.
581 SavedDiagHandler = SrcMgr.getDiagHandler();
582 SavedDiagContext = SrcMgr.getDiagContext();
583 // Set our own handler which calls the saved handler.
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000584 SrcMgr.setDiagHandler(DiagHandler, this);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000585 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar86033402010-07-12 17:54:38 +0000586
Daniel Dunbarc5011082010-07-12 18:12:02 +0000587 // Initialize the platform / file format parser.
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000588 switch (Ctx.getObjectFileInfo()->getObjectFileType()) {
589 case MCObjectFileInfo::IsCOFF:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000590 PlatformParser.reset(createCOFFAsmParser());
591 break;
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000592 case MCObjectFileInfo::IsMachO:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000593 PlatformParser.reset(createDarwinAsmParser());
594 IsDarwin = true;
595 break;
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000596 case MCObjectFileInfo::IsELF:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000597 PlatformParser.reset(createELFAsmParser());
598 break;
Daniel Dunbarc5011082010-07-12 18:12:02 +0000599 }
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000600
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000601 PlatformParser->Initialize(*this);
Eli Bendersky17233942013-01-15 22:59:42 +0000602 initializeDirectiveKindMap();
Toma Tabacu217116e2015-04-27 10:50:29 +0000603
604 NumOfMacroInstantiations = 0;
Chris Lattner351a7ef2009-09-27 21:16:52 +0000605}
606
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000607AsmParser::~AsmParser() {
Saleem Abdulrasool6eae1e62014-05-21 17:53:18 +0000608 assert((HadError || ActiveMacros.empty()) &&
609 "Unexpected active macro instantiation!");
Sanne Wouda29338752017-02-08 14:48:05 +0000610
611 // Restore the saved diagnostics handler and context for use during
612 // finalization.
613 SrcMgr.setDiagHandler(SavedDiagHandler, SavedDiagContext);
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000614}
615
Jim Grosbach4b905842013-09-20 23:08:21 +0000616void AsmParser::printMacroInstantiations() {
Daniel Dunbar43235712010-07-18 18:54:11 +0000617 // Print the active macro instantiation stack.
Jim Grosbach4b905842013-09-20 23:08:21 +0000618 for (std::vector<MacroInstantiation *>::const_reverse_iterator
619 it = ActiveMacros.rbegin(),
620 ie = ActiveMacros.rend();
621 it != ie; ++it)
622 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
Chris Lattner03b80a42011-10-16 05:43:57 +0000623 "while in macro instantiation");
Daniel Dunbar43235712010-07-18 18:54:11 +0000624}
625
Nirav Dave2364748a2016-09-16 18:30:20 +0000626void AsmParser::Note(SMLoc L, const Twine &Msg, SMRange Range) {
627 printPendingErrors();
628 printMessage(L, SourceMgr::DK_Note, Msg, Range);
Saleem Abdulrasool69c7caf2014-01-07 02:28:31 +0000629 printMacroInstantiations();
630}
631
Nirav Dave2364748a2016-09-16 18:30:20 +0000632bool AsmParser::Warning(SMLoc L, const Twine &Msg, SMRange Range) {
Colin LeMahieufe36f832015-07-27 22:39:14 +0000633 if(getTargetParser().getTargetOptions().MCNoWarn)
634 return false;
Joerg Sonnenberger29815912014-08-26 18:39:50 +0000635 if (getTargetParser().getTargetOptions().MCFatalWarnings)
Nirav Dave2364748a2016-09-16 18:30:20 +0000636 return Error(L, Msg, Range);
637 printMessage(L, SourceMgr::DK_Warning, Msg, Range);
Jim Grosbach4b905842013-09-20 23:08:21 +0000638 printMacroInstantiations();
Joerg Sonnenberger74ba2622011-05-19 18:00:13 +0000639 return false;
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +0000640}
641
Nirav Dave2364748a2016-09-16 18:30:20 +0000642bool AsmParser::printError(SMLoc L, const Twine &Msg, SMRange Range) {
Daniel Dunbar43325c42010-09-09 22:42:56 +0000643 HadError = true;
Nirav Dave2364748a2016-09-16 18:30:20 +0000644 printMessage(L, SourceMgr::DK_Error, Msg, Range);
Jim Grosbach4b905842013-09-20 23:08:21 +0000645 printMacroInstantiations();
Chris Lattner2adc9e72009-06-21 21:22:11 +0000646 return true;
647}
648
Jim Grosbach4b905842013-09-20 23:08:21 +0000649bool AsmParser::enterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergeraf5f23e2011-06-01 13:10:15 +0000650 std::string IncludedFile;
Alp Tokera55b95b2014-07-06 10:33:31 +0000651 unsigned NewBuf =
652 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
653 if (!NewBuf)
Sean Callanan7a77eae2010-01-21 00:19:58 +0000654 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +0000655
Sean Callanan7a77eae2010-01-21 00:19:58 +0000656 CurBuffer = NewBuf;
Rafael Espindola8026bd02014-07-06 14:17:29 +0000657 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Sean Callanan7a77eae2010-01-21 00:19:58 +0000658 return false;
659}
Daniel Dunbar43235712010-07-18 18:54:11 +0000660
Sylvestre Ledru149e2812013-05-14 23:36:24 +0000661/// Process the specified .incbin file by searching for it in the include paths
Benjamin Kramerbde91762012-06-02 10:20:22 +0000662/// then just emitting the byte contents of the file to the streamer. This
Kevin Enderby109f25c2011-12-14 21:47:48 +0000663/// returns true on failure.
Petr Hosek2f4ac442016-09-23 00:41:06 +0000664bool AsmParser::processIncbinFile(const std::string &Filename, int64_t Skip,
665 const MCExpr *Count, SMLoc Loc) {
Kevin Enderby109f25c2011-12-14 21:47:48 +0000666 std::string IncludedFile;
Alp Tokera55b95b2014-07-06 10:33:31 +0000667 unsigned NewBuf =
668 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
669 if (!NewBuf)
Kevin Enderby109f25c2011-12-14 21:47:48 +0000670 return true;
671
Kevin Enderbyad41ab52011-12-14 22:34:45 +0000672 // Pick up the bytes from the file and emit them.
Petr Hosek2f4ac442016-09-23 00:41:06 +0000673 StringRef Bytes = SrcMgr.getMemoryBuffer(NewBuf)->getBuffer();
674 Bytes = Bytes.drop_front(Skip);
675 if (Count) {
676 int64_t Res;
677 if (!Count->evaluateAsAbsolute(Res))
678 return Error(Loc, "expected absolute expression");
679 if (Res < 0)
680 return Warning(Loc, "negative count has no effect");
681 Bytes = Bytes.take_front(Res);
682 }
683 getStreamer().EmitBytes(Bytes);
Kevin Enderby109f25c2011-12-14 21:47:48 +0000684 return false;
685}
686
Alp Tokera55b95b2014-07-06 10:33:31 +0000687void AsmParser::jumpToLoc(SMLoc Loc, unsigned InBuffer) {
688 CurBuffer = InBuffer ? InBuffer : SrcMgr.FindBufferContainingLoc(Loc);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000689 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(),
690 Loc.getPointer());
Daniel Dunbar43235712010-07-18 18:54:11 +0000691}
692
Sean Callanan7a77eae2010-01-21 00:19:58 +0000693const AsmToken &AsmParser::Lex() {
Nirav Dave1180e6892016-06-02 17:15:05 +0000694 if (Lexer.getTok().is(AsmToken::Error))
695 Error(Lexer.getErrLoc(), Lexer.getErr());
696
Nirav Dave53a72f42016-07-11 12:42:14 +0000697 // if it's a end of statement with a comment in it
698 if (getTok().is(AsmToken::EndOfStatement)) {
699 // if this is a line comment output it.
700 if (getTok().getString().front() != '\n' &&
701 getTok().getString().front() != '\r' && MAI.preserveAsmComments())
702 Out.addExplicitComment(Twine(getTok().getString()));
703 }
704
Sean Callanan7a77eae2010-01-21 00:19:58 +0000705 const AsmToken *tok = &Lexer.Lex();
Nirav Dave53a72f42016-07-11 12:42:14 +0000706
707 // Parse comments here to be deferred until end of next statement.
Nirav Davefd910412016-06-17 16:06:17 +0000708 while (tok->is(AsmToken::Comment)) {
Nirav Dave53a72f42016-07-11 12:42:14 +0000709 if (MAI.preserveAsmComments())
710 Out.addExplicitComment(Twine(tok->getString()));
Nirav Davefd910412016-06-17 16:06:17 +0000711 tok = &Lexer.Lex();
712 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000713
Sean Callanan7a77eae2010-01-21 00:19:58 +0000714 if (tok->is(AsmToken::Eof)) {
715 // If this is the end of an included file, pop the parent file off the
716 // include stack.
717 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
718 if (ParentIncludeLoc != SMLoc()) {
Jim Grosbach4b905842013-09-20 23:08:21 +0000719 jumpToLoc(ParentIncludeLoc);
Nirav Davefd910412016-06-17 16:06:17 +0000720 return Lex();
Sean Callanan7a77eae2010-01-21 00:19:58 +0000721 }
722 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000723
Sean Callanan7a77eae2010-01-21 00:19:58 +0000724 return *tok;
Sean Callanan686ed8d2010-01-19 20:22:31 +0000725}
726
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000727bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar322fec62010-03-13 02:20:57 +0000728 // Create the initial section, if requested.
Daniel Dunbar322fec62010-03-13 02:20:57 +0000729 if (!NoInitialTextSection)
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000730 Out.InitSections(false);
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000731
Chris Lattner36e02122009-06-21 20:54:55 +0000732 // Prime the lexer.
Sean Callanan686ed8d2010-01-19 20:22:31 +0000733 Lex();
Daniel Dunbar43325c42010-09-09 22:42:56 +0000734
735 HadError = false;
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000736 AsmCond StartingCondState = TheCondState;
737
Kevin Enderby6469fc22011-11-01 22:27:22 +0000738 // If we are generating dwarf for assembly source files save the initial text
739 // section and generate a .file directive.
740 if (getContext().getGenDwarfForAssembly()) {
Eric Christopher445c9522016-10-14 05:47:37 +0000741 MCSection *Sec = getStreamer().getCurrentSectionOnly();
Rafael Espindola2f9bdd82015-05-27 20:52:32 +0000742 if (!Sec->getBeginSymbol()) {
743 MCSymbol *SectionStartSym = getContext().createTempSymbol();
744 getStreamer().EmitLabel(SectionStartSym);
745 Sec->setBeginSymbol(SectionStartSym);
746 }
Rafael Espindolae0746792015-05-21 16:52:32 +0000747 bool InsertResult = getContext().addGenDwarfSection(Sec);
748 assert(InsertResult && ".text section should not have debug info yet");
Rafael Espindolafa160c72015-05-21 17:09:22 +0000749 (void)InsertResult;
David Blaikiec714ef42014-03-17 01:52:11 +0000750 getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective(
751 0, StringRef(), getContext().getMainFileName()));
Kevin Enderby6469fc22011-11-01 22:27:22 +0000752 }
753
Chris Lattner73f36112009-07-02 21:53:43 +0000754 // While we have input, parse each statement.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000755 while (Lexer.isNot(AsmToken::Eof)) {
Eli Friedman0f4871d2012-10-22 23:58:19 +0000756 ParseStatementInfo Info;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +0000757 if (!parseStatement(Info, nullptr))
Jim Grosbach4b905842013-09-20 23:08:21 +0000758 continue;
Michael J. Spencer530ce852010-10-09 11:00:50 +0000759
Nirav Dave2364748a2016-09-16 18:30:20 +0000760 // If we have a Lexer Error we are on an Error Token. Load in Lexer Error
761 // for printing ErrMsg via Lex() only if no (presumably better) parser error
762 // exists.
763 if (!hasPendingError() && Lexer.getTok().is(AsmToken::Error)) {
Nirav Dave1180e6892016-06-02 17:15:05 +0000764 Lex();
765 }
766
Nirav Dave2364748a2016-09-16 18:30:20 +0000767 // parseStatement returned true so may need to emit an error.
768 printPendingErrors();
769
770 // Skipping to the next line if needed.
771 if (!getLexer().isAtStartOfStatement())
772 eatToEndOfStatement();
Chris Lattner73f36112009-07-02 21:53:43 +0000773 }
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000774
Nirav Dave2364748a2016-09-16 18:30:20 +0000775 // All errors should have been emitted.
776 assert(!hasPendingError() && "unexpected error from parseStatement");
777
Oliver Stannard21718282016-07-26 14:19:47 +0000778 getTargetParser().flushPendingInstructions(getStreamer());
779
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000780 if (TheCondState.TheCond != StartingCondState.TheCond ||
781 TheCondState.Ignore != StartingCondState.Ignore)
Nirav Dave2364748a2016-09-16 18:30:20 +0000782 printError(getTok().getLoc(), "unmatched .ifs or .elses");
Kevin Enderbye5930f12010-07-28 20:55:35 +0000783 // Check to see there are no empty DwarfFile slots.
David Blaikie8bf66c42014-04-01 07:35:52 +0000784 const auto &LineTables = getContext().getMCDwarfLineTables();
785 if (!LineTables.empty()) {
786 unsigned Index = 0;
787 for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) {
788 if (File.Name.empty() && Index != 0)
Nirav Dave2364748a2016-09-16 18:30:20 +0000789 printError(getTok().getLoc(), "unassigned file number: " +
790 Twine(Index) +
791 " for .file directives");
David Blaikie8bf66c42014-04-01 07:35:52 +0000792 ++Index;
793 }
Kevin Enderbye5930f12010-07-28 20:55:35 +0000794 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000795
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000796 // Check to see that all assembler local symbols were actually defined.
797 // Targets that don't do subsections via symbols may not want this, though,
798 // so conservatively exclude them. Only do this if we're finalizing, though,
799 // as otherwise we won't necessarilly have seen everything yet.
Tim Northover6b3169b2016-04-11 19:50:46 +0000800 if (!NoFinalize) {
801 if (MAI.hasSubsectionsViaSymbols()) {
802 for (const auto &TableEntry : getContext().getSymbols()) {
803 MCSymbol *Sym = TableEntry.getValue();
804 // Variable symbols may not be marked as defined, so check those
805 // explicitly. If we know it's a variable, we have a definition for
806 // the purposes of this check.
807 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
808 // FIXME: We would really like to refer back to where the symbol was
809 // first referenced for a source location. We need to add something
810 // to track that. Currently, we just point to the end of the file.
Nirav Dave2364748a2016-09-16 18:30:20 +0000811 printError(getTok().getLoc(), "assembler local symbol '" +
812 Sym->getName() + "' not defined");
Tim Northover6b3169b2016-04-11 19:50:46 +0000813 }
814 }
815
816 // Temporary symbols like the ones for directional jumps don't go in the
817 // symbol table. They also need to be diagnosed in all (final) cases.
Tim Northoverc0bef992016-04-13 19:46:54 +0000818 for (std::tuple<SMLoc, CppHashInfoTy, MCSymbol *> &LocSym : DirLabels) {
819 if (std::get<2>(LocSym)->isUndefined()) {
820 // Reset the state of any "# line file" directives we've seen to the
821 // context as it was at the diagnostic site.
822 CppHashInfo = std::get<1>(LocSym);
Nirav Dave2364748a2016-09-16 18:30:20 +0000823 printError(std::get<0>(LocSym), "directional label undefined");
Tim Northoverc0bef992016-04-13 19:46:54 +0000824 }
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000825 }
826 }
827
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000828 // Finalize the output stream if there are no errors and if the client wants
829 // us to.
Jack Carter13d5f752013-10-04 22:52:31 +0000830 if (!HadError && !NoFinalize)
Daniel Dunbar9df5f332009-08-21 08:34:18 +0000831 Out.Finish();
832
Oliver Stannard07b43d32015-11-17 09:58:07 +0000833 return HadError || getContext().hadError();
Chris Lattner36e02122009-06-21 20:54:55 +0000834}
835
Nirav Davef43cc9f2016-10-10 15:24:54 +0000836bool AsmParser::checkForValidSection() {
Eric Christopher445c9522016-10-14 05:47:37 +0000837 if (!ParsingInlineAsm && !getStreamer().getCurrentSectionOnly()) {
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000838 Out.InitSections(false);
Nirav Davef43cc9f2016-10-10 15:24:54 +0000839 return Error(getTok().getLoc(),
840 "expected section directive before assembly directive");
Daniel Dunbare5444a82010-09-09 22:42:59 +0000841 }
Nirav Davef43cc9f2016-10-10 15:24:54 +0000842 return false;
Daniel Dunbare5444a82010-09-09 22:42:59 +0000843}
844
Jim Grosbach4b905842013-09-20 23:08:21 +0000845/// \brief Throw away the rest of the line for testing purposes.
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000846void AsmParser::eatToEndOfStatement() {
Jim Grosbach4b905842013-09-20 23:08:21 +0000847 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Nirav Dave1180e6892016-06-02 17:15:05 +0000848 Lexer.Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +0000849
Chris Lattnere5074c42009-06-22 01:29:09 +0000850 // Eat EOL.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000851 if (Lexer.is(AsmToken::EndOfStatement))
Nirav Dave1180e6892016-06-02 17:15:05 +0000852 Lexer.Lex();
Chris Lattnere5074c42009-06-22 01:29:09 +0000853}
854
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000855StringRef AsmParser::parseStringToEndOfStatement() {
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000856 const char *Start = getTok().getLoc().getPointer();
857
Jim Grosbach4b905842013-09-20 23:08:21 +0000858 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Nirav Davefd910412016-06-17 16:06:17 +0000859 Lexer.Lex();
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000860
861 const char *End = getTok().getLoc().getPointer();
862 return StringRef(Start, End - Start);
863}
Chris Lattner78db3622009-06-22 05:51:26 +0000864
Jim Grosbach4b905842013-09-20 23:08:21 +0000865StringRef AsmParser::parseStringToComma() {
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000866 const char *Start = getTok().getLoc().getPointer();
867
868 while (Lexer.isNot(AsmToken::EndOfStatement) &&
Jim Grosbach4b905842013-09-20 23:08:21 +0000869 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
Nirav Davefd910412016-06-17 16:06:17 +0000870 Lexer.Lex();
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000871
872 const char *End = getTok().getLoc().getPointer();
873 return StringRef(Start, End - Start);
874}
875
Jim Grosbach4b905842013-09-20 23:08:21 +0000876/// \brief Parse a paren expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +0000877/// NOTE: This assumes the leading '(' has already been consumed.
878///
879/// parenexpr ::= expr)
880///
Jim Grosbach4b905842013-09-20 23:08:21 +0000881bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
882 if (parseExpression(Res))
883 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000884 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner7fdbce72009-06-22 06:32:03 +0000885 return TokError("expected ')' in parentheses expression");
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000886 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +0000887 Lex();
Chris Lattner7fdbce72009-06-22 06:32:03 +0000888 return false;
889}
Chris Lattner78db3622009-06-22 05:51:26 +0000890
Jim Grosbach4b905842013-09-20 23:08:21 +0000891/// \brief Parse a bracket expression and return it.
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +0000892/// NOTE: This assumes the leading '[' has already been consumed.
893///
894/// bracketexpr ::= expr]
895///
Jim Grosbach4b905842013-09-20 23:08:21 +0000896bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
897 if (parseExpression(Res))
898 return true;
Nirav Davea645433c2016-07-18 15:24:03 +0000899 EndLoc = getTok().getEndLoc();
900 if (parseToken(AsmToken::RBrac, "expected ']' in brackets expression"))
901 return true;
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +0000902 return false;
903}
904
Jim Grosbach4b905842013-09-20 23:08:21 +0000905/// \brief Parse a primary expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +0000906/// primaryexpr ::= (parenexpr
907/// primaryexpr ::= symbol
908/// primaryexpr ::= number
Chris Lattner6b55cb92010-04-14 04:40:28 +0000909/// primaryexpr ::= '.'
Chris Lattner7fdbce72009-06-22 06:32:03 +0000910/// primaryexpr ::= ~,+,- primaryexpr
Jim Grosbach4b905842013-09-20 23:08:21 +0000911bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Kevin Enderby0017d8a2013-01-22 21:09:20 +0000912 SMLoc FirstTokenLoc = getLexer().getLoc();
913 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
914 switch (FirstTokenKind) {
Chris Lattner78db3622009-06-22 05:51:26 +0000915 default:
916 return TokError("unknown token in expression");
Eric Christopher104af062011-04-12 00:03:13 +0000917 // If we have an error assume that we've already handled it.
918 case AsmToken::Error:
919 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000920 case AsmToken::Exclaim:
Sean Callanan686ed8d2010-01-19 20:22:31 +0000921 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +0000922 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000923 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +0000924 Res = MCUnaryExpr::createLNot(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000925 return false;
Daniel Dunbar24764322010-08-24 19:13:42 +0000926 case AsmToken::Dollar:
Hans Wennborgce69d772013-10-18 20:46:28 +0000927 case AsmToken::At:
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +0000928 case AsmToken::String:
Daniel Dunbard20cda02009-10-16 01:34:54 +0000929 case AsmToken::Identifier: {
Daniel Dunbar24764322010-08-24 19:13:42 +0000930 StringRef Identifier;
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000931 if (parseIdentifier(Identifier)) {
Nirav Daved0463322016-10-12 13:58:07 +0000932 // We may have failed but $ may be a valid token.
933 if (getTok().is(AsmToken::Dollar)) {
David Majnemer0c58bc62013-09-25 10:47:21 +0000934 if (Lexer.getMAI().getDollarIsPC()) {
Nirav Daved0463322016-10-12 13:58:07 +0000935 Lex();
David Majnemer0c58bc62013-09-25 10:47:21 +0000936 // This is a '$' reference, which references the current PC. Emit a
937 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +0000938 MCSymbol *Sym = Ctx.createTempSymbol();
David Majnemer0c58bc62013-09-25 10:47:21 +0000939 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +0000940 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None,
Jack Carter721726a2013-10-04 21:26:15 +0000941 getContext());
David Majnemer0c58bc62013-09-25 10:47:21 +0000942 EndLoc = FirstTokenLoc;
943 return false;
Ted Kremenek297febe2014-03-06 22:13:17 +0000944 }
945 return Error(FirstTokenLoc, "invalid token in expression");
David Majnemer0c58bc62013-09-25 10:47:21 +0000946 }
Kevin Enderby0017d8a2013-01-22 21:09:20 +0000947 }
David Peixotto8ad70b32013-12-04 22:43:20 +0000948 // Parse symbol variant
949 std::pair<StringRef, StringRef> Split;
950 if (!MAI.useParensForSymbolVariant()) {
David Majnemer6a5b8122014-06-19 01:25:43 +0000951 if (FirstTokenKind == AsmToken::String) {
952 if (Lexer.is(AsmToken::At)) {
Nirav Davefd910412016-06-17 16:06:17 +0000953 Lex(); // eat @
David Majnemer6a5b8122014-06-19 01:25:43 +0000954 SMLoc AtLoc = getLexer().getLoc();
955 StringRef VName;
956 if (parseIdentifier(VName))
957 return Error(AtLoc, "expected symbol variant after '@'");
958
959 Split = std::make_pair(Identifier, VName);
960 }
961 } else {
962 Split = Identifier.split('@');
963 }
David Peixotto8ad70b32013-12-04 22:43:20 +0000964 } else if (Lexer.is(AsmToken::LParen)) {
Nirav Davefd910412016-06-17 16:06:17 +0000965 Lex(); // eat '('.
David Peixotto8ad70b32013-12-04 22:43:20 +0000966 StringRef VName;
967 parseIdentifier(VName);
Nirav Davea645433c2016-07-18 15:24:03 +0000968 // eat ')'.
969 if (parseToken(AsmToken::RParen,
970 "unexpected token in variant, expected ')'"))
971 return true;
David Peixotto8ad70b32013-12-04 22:43:20 +0000972 Split = std::make_pair(Identifier, VName);
973 }
Daniel Dunbar24764322010-08-24 19:13:42 +0000974
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000975 EndLoc = SMLoc::getFromPointer(Identifier.end());
976
Daniel Dunbard20cda02009-10-16 01:34:54 +0000977 // This is a symbol reference.
Hans Wennborgce69d772013-10-18 20:46:28 +0000978 StringRef SymbolName = Identifier;
Weiming Zhaocf26d562016-12-01 18:00:36 +0000979 if (SymbolName.empty())
980 return true;
981
Hans Wennborgce69d772013-10-18 20:46:28 +0000982 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Hans Wennborg69918bc2013-10-17 01:13:02 +0000983
Hans Wennborg7ddcdc82013-10-18 02:14:40 +0000984 // Lookup the symbol variant if used.
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000985 if (!Split.second.empty()) {
Hans Wennborg7ddcdc82013-10-18 02:14:40 +0000986 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Hans Wennborgce69d772013-10-18 20:46:28 +0000987 if (Variant != MCSymbolRefExpr::VK_Invalid) {
988 SymbolName = Split.first;
David Peixotto8ad70b32013-12-04 22:43:20 +0000989 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
Hans Wennborgce69d772013-10-18 20:46:28 +0000990 Variant = MCSymbolRefExpr::VK_None;
991 } else {
Saleem Abdulrasoola25e1e42014-01-26 22:29:43 +0000992 return Error(SMLoc::getFromPointer(Split.second.begin()),
993 "invalid variant '" + Split.second + "'");
Daniel Dunbar55f16672010-09-17 02:47:07 +0000994 }
995 }
Daniel Dunbar55992562010-03-15 23:51:06 +0000996
Jim Grosbach6f482002015-05-18 18:43:14 +0000997 MCSymbol *Sym = getContext().getOrCreateSymbol(SymbolName);
Hans Wennborgce69d772013-10-18 20:46:28 +0000998
Daniel Dunbard20cda02009-10-16 01:34:54 +0000999 // If this is an absolute variable reference, substitute it now to preserve
1000 // semantics in the face of reassignment.
Vedant Kumar86dbd922015-08-31 17:44:53 +00001001 if (Sym->isVariable() &&
1002 isa<MCConstantExpr>(Sym->getVariableValue(/*SetUsed*/ false))) {
Daniel Dunbar55992562010-03-15 23:51:06 +00001003 if (Variant)
Daniel Dunbar8a3c3f22010-11-08 17:53:02 +00001004 return Error(EndLoc, "unexpected modifier on variable reference");
Daniel Dunbar55992562010-03-15 23:51:06 +00001005
Vedant Kumar86dbd922015-08-31 17:44:53 +00001006 Res = Sym->getVariableValue(/*SetUsed*/ false);
Daniel Dunbard20cda02009-10-16 01:34:54 +00001007 return false;
1008 }
1009
1010 // Otherwise create a symbol ref.
Chad Rosier9245e122017-01-19 20:06:32 +00001011 Res = MCSymbolRefExpr::create(Sym, Variant, getContext(), FirstTokenLoc);
Chris Lattner78db3622009-06-22 05:51:26 +00001012 return false;
Daniel Dunbard20cda02009-10-16 01:34:54 +00001013 }
David Woodhousef42a6662014-02-01 16:20:54 +00001014 case AsmToken::BigNum:
1015 return TokError("literal value out of range for directive");
Kevin Enderby0510b482010-05-17 23:08:19 +00001016 case AsmToken::Integer: {
1017 SMLoc Loc = getTok().getLoc();
1018 int64_t IntVal = getTok().getIntVal();
Jim Grosbach13760bd2015-05-30 01:25:56 +00001019 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001020 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001021 Lex(); // Eat token.
Kevin Enderby0510b482010-05-17 23:08:19 +00001022 // Look for 'b' or 'f' following an Integer as a directional label
1023 if (Lexer.getKind() == AsmToken::Identifier) {
1024 StringRef IDVal = getTok().getString();
Ulrich Weigandd4120982013-06-20 16:24:17 +00001025 // Lookup the symbol variant if used.
1026 std::pair<StringRef, StringRef> Split = IDVal.split('@');
1027 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
1028 if (Split.first.size() != IDVal.size()) {
1029 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Arnaud A. de Grandmaisonc97727a2014-03-21 21:54:46 +00001030 if (Variant == MCSymbolRefExpr::VK_Invalid)
Ulrich Weigandd4120982013-06-20 16:24:17 +00001031 return TokError("invalid variant '" + Split.second + "'");
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001032 IDVal = Split.first;
Ulrich Weigandd4120982013-06-20 16:24:17 +00001033 }
Jim Grosbach4b905842013-09-20 23:08:21 +00001034 if (IDVal == "f" || IDVal == "b") {
1035 MCSymbol *Sym =
Jim Grosbach6f482002015-05-18 18:43:14 +00001036 Ctx.getDirectionalLocalSymbol(IntVal, IDVal == "b");
Jim Grosbach13760bd2015-05-30 01:25:56 +00001037 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00001038 if (IDVal == "b" && Sym->isUndefined())
Tim Northover6b3169b2016-04-11 19:50:46 +00001039 return Error(Loc, "directional label undefined");
Tim Northoverc0bef992016-04-13 19:46:54 +00001040 DirLabels.push_back(std::make_tuple(Loc, CppHashInfo, Sym));
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001041 EndLoc = Lexer.getTok().getEndLoc();
Kevin Enderby0510b482010-05-17 23:08:19 +00001042 Lex(); // Eat identifier.
1043 }
1044 }
Chris Lattner78db3622009-06-22 05:51:26 +00001045 return false;
Kevin Enderby0510b482010-05-17 23:08:19 +00001046 }
Bill Wendlingcdbf17b2011-01-25 21:26:41 +00001047 case AsmToken::Real: {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001048 APFloat RealVal(APFloat::IEEEdouble(), getTok().getString());
Bob Wilson813bdf62011-02-03 23:17:47 +00001049 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Jim Grosbach13760bd2015-05-30 01:25:56 +00001050 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001051 EndLoc = Lexer.getTok().getEndLoc();
Bill Wendlingcdbf17b2011-01-25 21:26:41 +00001052 Lex(); // Eat token.
1053 return false;
1054 }
Chris Lattner6b55cb92010-04-14 04:40:28 +00001055 case AsmToken::Dot: {
1056 // This is a '.' reference, which references the current PC. Emit a
1057 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +00001058 MCSymbol *Sym = Ctx.createTempSymbol();
Chris Lattner6b55cb92010-04-14 04:40:28 +00001059 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +00001060 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001061 EndLoc = Lexer.getTok().getEndLoc();
Chris Lattner6b55cb92010-04-14 04:40:28 +00001062 Lex(); // Eat identifier.
1063 return false;
1064 }
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001065 case AsmToken::LParen:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001066 Lex(); // Eat the '('.
Jim Grosbach4b905842013-09-20 23:08:21 +00001067 return parseParenExpr(Res, EndLoc);
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +00001068 case AsmToken::LBrac:
1069 if (!PlatformParser->HasBracketExpressions())
1070 return TokError("brackets expression not supported on this target");
1071 Lex(); // Eat the '['.
Jim Grosbach4b905842013-09-20 23:08:21 +00001072 return parseBracketExpr(Res, EndLoc);
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001073 case AsmToken::Minus:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001074 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001075 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001076 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001077 Res = MCUnaryExpr::createMinus(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001078 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001079 case AsmToken::Plus:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001080 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001081 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001082 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001083 Res = MCUnaryExpr::createPlus(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001084 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001085 case AsmToken::Tilde:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001086 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001087 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001088 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001089 Res = MCUnaryExpr::createNot(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001090 return false;
Daniel Sanders3feeb9c2016-08-08 11:50:25 +00001091 // MIPS unary expression operators. The lexer won't generate these tokens if
1092 // MCAsmInfo::HasMipsExpressions is false for the target.
1093 case AsmToken::PercentCall16:
1094 case AsmToken::PercentCall_Hi:
1095 case AsmToken::PercentCall_Lo:
1096 case AsmToken::PercentDtprel_Hi:
1097 case AsmToken::PercentDtprel_Lo:
1098 case AsmToken::PercentGot:
1099 case AsmToken::PercentGot_Disp:
1100 case AsmToken::PercentGot_Hi:
1101 case AsmToken::PercentGot_Lo:
1102 case AsmToken::PercentGot_Ofst:
1103 case AsmToken::PercentGot_Page:
1104 case AsmToken::PercentGottprel:
1105 case AsmToken::PercentGp_Rel:
1106 case AsmToken::PercentHi:
1107 case AsmToken::PercentHigher:
1108 case AsmToken::PercentHighest:
1109 case AsmToken::PercentLo:
1110 case AsmToken::PercentNeg:
1111 case AsmToken::PercentPcrel_Hi:
1112 case AsmToken::PercentPcrel_Lo:
1113 case AsmToken::PercentTlsgd:
1114 case AsmToken::PercentTlsldm:
1115 case AsmToken::PercentTprel_Hi:
1116 case AsmToken::PercentTprel_Lo:
1117 Lex(); // Eat the operator.
1118 if (Lexer.isNot(AsmToken::LParen))
1119 return TokError("expected '(' after operator");
1120 Lex(); // Eat the operator.
1121 if (parseExpression(Res, EndLoc))
1122 return true;
1123 if (Lexer.isNot(AsmToken::RParen))
1124 return TokError("expected ')'");
1125 Lex(); // Eat the operator.
1126 Res = getTargetParser().createTargetUnaryExpr(Res, FirstTokenKind, Ctx);
1127 return !Res;
Chris Lattner78db3622009-06-22 05:51:26 +00001128 }
1129}
Chris Lattner7fdbce72009-06-22 06:32:03 +00001130
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001131bool AsmParser::parseExpression(const MCExpr *&Res) {
Chris Lattnere17df0b2010-01-15 19:39:23 +00001132 SMLoc EndLoc;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001133 return parseExpression(Res, EndLoc);
Chris Lattner528d00b2010-01-15 19:28:38 +00001134}
1135
Daniel Dunbar55f16672010-09-17 02:47:07 +00001136const MCExpr *
Jim Grosbach4b905842013-09-20 23:08:21 +00001137AsmParser::applyModifierToExpr(const MCExpr *E,
Daniel Dunbar55f16672010-09-17 02:47:07 +00001138 MCSymbolRefExpr::VariantKind Variant) {
Joerg Sonnenbergerb822af42013-08-27 20:23:19 +00001139 // Ask the target implementation about this expression first.
1140 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
1141 if (NewE)
1142 return NewE;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001143 // Recurse over the given expression, rebuilding it to apply the given variant
1144 // if there is exactly one symbol.
1145 switch (E->getKind()) {
1146 case MCExpr::Target:
1147 case MCExpr::Constant:
Craig Topper353eda42014-04-24 06:44:33 +00001148 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001149
1150 case MCExpr::SymbolRef: {
1151 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
1152
1153 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001154 TokError("invalid variant on expression '" + getTok().getIdentifier() +
1155 "' (already modified)");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001156 return E;
1157 }
1158
Jim Grosbach13760bd2015-05-30 01:25:56 +00001159 return MCSymbolRefExpr::create(&SRE->getSymbol(), Variant, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001160 }
1161
1162 case MCExpr::Unary: {
1163 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +00001164 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001165 if (!Sub)
Craig Topper353eda42014-04-24 06:44:33 +00001166 return nullptr;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001167 return MCUnaryExpr::create(UE->getOpcode(), Sub, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001168 }
1169
1170 case MCExpr::Binary: {
1171 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +00001172 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
1173 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001174
1175 if (!LHS && !RHS)
Craig Topper353eda42014-04-24 06:44:33 +00001176 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001177
Jim Grosbach4b905842013-09-20 23:08:21 +00001178 if (!LHS)
1179 LHS = BE->getLHS();
1180 if (!RHS)
1181 RHS = BE->getRHS();
Daniel Dunbar55f16672010-09-17 02:47:07 +00001182
Jim Grosbach13760bd2015-05-30 01:25:56 +00001183 return MCBinaryExpr::create(BE->getOpcode(), LHS, RHS, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001184 }
1185 }
Daniel Dunbarbaad46c2010-09-17 16:34:24 +00001186
Craig Toppera2886c22012-02-07 05:05:23 +00001187 llvm_unreachable("Invalid expression kind!");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001188}
1189
Jim Grosbach4b905842013-09-20 23:08:21 +00001190/// \brief Parse an expression and return it.
Michael J. Spencer530ce852010-10-09 11:00:50 +00001191///
Jim Grosbachbd164242011-08-20 16:24:13 +00001192/// expr ::= expr &&,|| expr -> lowest.
1193/// expr ::= expr |,^,&,! expr
1194/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1195/// expr ::= expr <<,>> expr
1196/// expr ::= expr +,- expr
1197/// expr ::= expr *,/,% expr -> highest.
Chris Lattner7fdbce72009-06-22 06:32:03 +00001198/// expr ::= primaryexpr
1199///
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001200bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001201 // Parse the expression.
Craig Topper353eda42014-04-24 06:44:33 +00001202 Res = nullptr;
Jim Grosbach4b905842013-09-20 23:08:21 +00001203 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001204 return true;
1205
Daniel Dunbar55f16672010-09-17 02:47:07 +00001206 // As a special case, we support 'a op b @ modifier' by rewriting the
1207 // expression to include the modifier. This is inefficient, but in general we
1208 // expect users to use 'a@modifier op b'.
1209 if (Lexer.getKind() == AsmToken::At) {
1210 Lex();
1211
1212 if (Lexer.isNot(AsmToken::Identifier))
1213 return TokError("unexpected symbol modifier following '@'");
1214
1215 MCSymbolRefExpr::VariantKind Variant =
Jim Grosbach4b905842013-09-20 23:08:21 +00001216 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001217 if (Variant == MCSymbolRefExpr::VK_Invalid)
1218 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1219
Jim Grosbach4b905842013-09-20 23:08:21 +00001220 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001221 if (!ModifiedRes) {
1222 return TokError("invalid modifier '" + getTok().getIdentifier() +
1223 "' (no symbols present)");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001224 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001225
Daniel Dunbar55f16672010-09-17 02:47:07 +00001226 Res = ModifiedRes;
1227 Lex();
1228 }
1229
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001230 // Try to constant fold it up front, if possible.
1231 int64_t Value;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001232 if (Res->evaluateAsAbsolute(Value))
1233 Res = MCConstantExpr::create(Value, getContext());
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001234
1235 return false;
Chris Lattner7fdbce72009-06-22 06:32:03 +00001236}
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001237
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001238bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Craig Topper353eda42014-04-24 06:44:33 +00001239 Res = nullptr;
Jim Grosbach4b905842013-09-20 23:08:21 +00001240 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
Daniel Dunbar7c82d562009-08-31 08:08:17 +00001241}
1242
Toma Tabacu7bc44dc2015-06-25 09:52:02 +00001243bool AsmParser::parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
1244 SMLoc &EndLoc) {
1245 if (parseParenExpr(Res, EndLoc))
1246 return true;
1247
1248 for (; ParenDepth > 0; --ParenDepth) {
1249 if (parseBinOpRHS(1, Res, EndLoc))
1250 return true;
1251
1252 // We don't Lex() the last RParen.
1253 // This is the same behavior as parseParenExpression().
1254 if (ParenDepth - 1 > 0) {
Nirav Davea645433c2016-07-18 15:24:03 +00001255 EndLoc = getTok().getEndLoc();
1256 if (parseToken(AsmToken::RParen,
1257 "expected ')' in parentheses expression"))
1258 return true;
Toma Tabacu7bc44dc2015-06-25 09:52:02 +00001259 }
1260 }
1261 return false;
1262}
1263
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001264bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
Daniel Dunbarf3636452009-08-31 08:07:22 +00001265 const MCExpr *Expr;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001266
Daniel Dunbar75630b32009-06-30 02:10:03 +00001267 SMLoc StartLoc = Lexer.getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001268 if (parseExpression(Expr))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001269 return true;
1270
Jim Grosbach13760bd2015-05-30 01:25:56 +00001271 if (!Expr->evaluateAsAbsolute(Res))
Daniel Dunbar75630b32009-06-30 02:10:03 +00001272 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001273
1274 return false;
1275}
1276
David Majnemer0993e0b2015-10-26 03:15:34 +00001277static unsigned getDarwinBinOpPrecedence(AsmToken::TokenKind K,
1278 MCBinaryExpr::Opcode &Kind,
1279 bool ShouldUseLogicalShr) {
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001280 switch (K) {
Daniel Dunbar940cda22009-08-31 08:07:44 +00001281 default:
Jim Grosbach4b905842013-09-20 23:08:21 +00001282 return 0; // not a binop.
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001283
Jim Grosbach4b905842013-09-20 23:08:21 +00001284 // Lowest Precedence: &&, ||
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001285 case AsmToken::AmpAmp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001286 Kind = MCBinaryExpr::LAnd;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001287 return 1;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001288 case AsmToken::PipePipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001289 Kind = MCBinaryExpr::LOr;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001290 return 1;
1291
Jim Grosbach4b905842013-09-20 23:08:21 +00001292 // Low Precedence: |, &, ^
1293 //
1294 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001295 case AsmToken::Pipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001296 Kind = MCBinaryExpr::Or;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001297 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001298 case AsmToken::Caret:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001299 Kind = MCBinaryExpr::Xor;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001300 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001301 case AsmToken::Amp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001302 Kind = MCBinaryExpr::And;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001303 return 2;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001304
Jim Grosbach4b905842013-09-20 23:08:21 +00001305 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001306 case AsmToken::EqualEqual:
1307 Kind = MCBinaryExpr::EQ;
1308 return 3;
1309 case AsmToken::ExclaimEqual:
1310 case AsmToken::LessGreater:
1311 Kind = MCBinaryExpr::NE;
1312 return 3;
1313 case AsmToken::Less:
1314 Kind = MCBinaryExpr::LT;
1315 return 3;
1316 case AsmToken::LessEqual:
1317 Kind = MCBinaryExpr::LTE;
1318 return 3;
1319 case AsmToken::Greater:
1320 Kind = MCBinaryExpr::GT;
1321 return 3;
1322 case AsmToken::GreaterEqual:
1323 Kind = MCBinaryExpr::GTE;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001324 return 3;
1325
Jim Grosbach4b905842013-09-20 23:08:21 +00001326 // Intermediate Precedence: <<, >>
Jim Grosbachbd164242011-08-20 16:24:13 +00001327 case AsmToken::LessLess:
1328 Kind = MCBinaryExpr::Shl;
1329 return 4;
1330 case AsmToken::GreaterGreater:
David Majnemer0993e0b2015-10-26 03:15:34 +00001331 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
Jim Grosbachbd164242011-08-20 16:24:13 +00001332 return 4;
1333
Jim Grosbach4b905842013-09-20 23:08:21 +00001334 // High Intermediate Precedence: +, -
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001335 case AsmToken::Plus:
1336 Kind = MCBinaryExpr::Add;
Jim Grosbachbd164242011-08-20 16:24:13 +00001337 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001338 case AsmToken::Minus:
1339 Kind = MCBinaryExpr::Sub;
Jim Grosbachbd164242011-08-20 16:24:13 +00001340 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001341
Jim Grosbach4b905842013-09-20 23:08:21 +00001342 // Highest Precedence: *, /, %
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001343 case AsmToken::Star:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001344 Kind = MCBinaryExpr::Mul;
Jim Grosbachbd164242011-08-20 16:24:13 +00001345 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001346 case AsmToken::Slash:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001347 Kind = MCBinaryExpr::Div;
Jim Grosbachbd164242011-08-20 16:24:13 +00001348 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001349 case AsmToken::Percent:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001350 Kind = MCBinaryExpr::Mod;
Jim Grosbachbd164242011-08-20 16:24:13 +00001351 return 6;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001352 }
1353}
1354
David Majnemer0993e0b2015-10-26 03:15:34 +00001355static unsigned getGNUBinOpPrecedence(AsmToken::TokenKind K,
1356 MCBinaryExpr::Opcode &Kind,
1357 bool ShouldUseLogicalShr) {
1358 switch (K) {
1359 default:
1360 return 0; // not a binop.
1361
1362 // Lowest Precedence: &&, ||
1363 case AsmToken::AmpAmp:
1364 Kind = MCBinaryExpr::LAnd;
1365 return 2;
1366 case AsmToken::PipePipe:
1367 Kind = MCBinaryExpr::LOr;
1368 return 1;
1369
1370 // Low Precedence: ==, !=, <>, <, <=, >, >=
1371 case AsmToken::EqualEqual:
1372 Kind = MCBinaryExpr::EQ;
1373 return 3;
1374 case AsmToken::ExclaimEqual:
1375 case AsmToken::LessGreater:
1376 Kind = MCBinaryExpr::NE;
1377 return 3;
1378 case AsmToken::Less:
1379 Kind = MCBinaryExpr::LT;
1380 return 3;
1381 case AsmToken::LessEqual:
1382 Kind = MCBinaryExpr::LTE;
1383 return 3;
1384 case AsmToken::Greater:
1385 Kind = MCBinaryExpr::GT;
1386 return 3;
1387 case AsmToken::GreaterEqual:
1388 Kind = MCBinaryExpr::GTE;
1389 return 3;
1390
1391 // Low Intermediate Precedence: +, -
1392 case AsmToken::Plus:
1393 Kind = MCBinaryExpr::Add;
1394 return 4;
1395 case AsmToken::Minus:
1396 Kind = MCBinaryExpr::Sub;
1397 return 4;
1398
1399 // High Intermediate Precedence: |, &, ^
1400 //
1401 // FIXME: gas seems to support '!' as an infix operator?
1402 case AsmToken::Pipe:
1403 Kind = MCBinaryExpr::Or;
1404 return 5;
1405 case AsmToken::Caret:
1406 Kind = MCBinaryExpr::Xor;
1407 return 5;
1408 case AsmToken::Amp:
1409 Kind = MCBinaryExpr::And;
1410 return 5;
1411
1412 // Highest Precedence: *, /, %, <<, >>
1413 case AsmToken::Star:
1414 Kind = MCBinaryExpr::Mul;
1415 return 6;
1416 case AsmToken::Slash:
1417 Kind = MCBinaryExpr::Div;
1418 return 6;
1419 case AsmToken::Percent:
1420 Kind = MCBinaryExpr::Mod;
1421 return 6;
1422 case AsmToken::LessLess:
1423 Kind = MCBinaryExpr::Shl;
1424 return 6;
1425 case AsmToken::GreaterGreater:
1426 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1427 return 6;
1428 }
1429}
1430
1431unsigned AsmParser::getBinOpPrecedence(AsmToken::TokenKind K,
1432 MCBinaryExpr::Opcode &Kind) {
1433 bool ShouldUseLogicalShr = MAI.shouldUseLogicalShr();
1434 return IsDarwin ? getDarwinBinOpPrecedence(K, Kind, ShouldUseLogicalShr)
1435 : getGNUBinOpPrecedence(K, Kind, ShouldUseLogicalShr);
1436}
1437
Jim Grosbach4b905842013-09-20 23:08:21 +00001438/// \brief Parse all binary operators with precedence >= 'Precedence'.
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001439/// Res contains the LHS of the expression on input.
Jim Grosbach4b905842013-09-20 23:08:21 +00001440bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
Chris Lattner528d00b2010-01-15 19:28:38 +00001441 SMLoc &EndLoc) {
Chad Rosier9245e122017-01-19 20:06:32 +00001442 SMLoc StartLoc = Lexer.getLoc();
Eugene Zelenko33d7b762016-08-23 17:14:32 +00001443 while (true) {
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001444 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001445 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001446
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001447 // If the next token is lower precedence than we are allowed to eat, return
1448 // successfully with what we ate already.
1449 if (TokPrec < Precedence)
1450 return false;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001451
Sean Callanan686ed8d2010-01-19 20:22:31 +00001452 Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +00001453
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001454 // Eat the next primary expression.
Daniel Dunbarf3636452009-08-31 08:07:22 +00001455 const MCExpr *RHS;
Jim Grosbach4b905842013-09-20 23:08:21 +00001456 if (parsePrimaryExpr(RHS, EndLoc))
1457 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001458
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001459 // If BinOp binds less tightly with RHS than the operator after RHS, let
1460 // the pending operator take RHS as its LHS.
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001461 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001462 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Jim Grosbach4b905842013-09-20 23:08:21 +00001463 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1464 return true;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001465
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001466 // Merge LHS and RHS according to operator.
Chad Rosier9245e122017-01-19 20:06:32 +00001467 Res = MCBinaryExpr::create(Kind, Res, RHS, getContext(), StartLoc);
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001468 }
1469}
1470
Chris Lattner36e02122009-06-21 20:54:55 +00001471/// ParseStatement:
1472/// ::= EndOfStatement
Chris Lattnere5074c42009-06-22 01:29:09 +00001473/// ::= Label* Directive ...Operands... EndOfStatement
1474/// ::= Label* Identifier OperandList* EndOfStatement
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001475bool AsmParser::parseStatement(ParseStatementInfo &Info,
1476 MCAsmParserSemaCallback *SI) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001477 assert(!hasPendingError() && "parseStatement started with pending error");
Nirav Davefd910412016-06-17 16:06:17 +00001478 // Eat initial spaces and comments
1479 while (Lexer.is(AsmToken::Space))
1480 Lex();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001481 if (Lexer.is(AsmToken::EndOfStatement)) {
Nirav Davefd910412016-06-17 16:06:17 +00001482 // if this is a line comment we can drop it safely
1483 if (getTok().getString().front() == '\r' ||
1484 getTok().getString().front() == '\n')
1485 Out.AddBlankLine();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001486 Lex();
Chris Lattner36e02122009-06-21 20:54:55 +00001487 return false;
Chris Lattner36e02122009-06-21 20:54:55 +00001488 }
Nirav Dave9263ae32016-08-02 19:17:54 +00001489 if (Lexer.is(AsmToken::Hash)) {
1490 // Seeing a hash here means that it was an end-of-line comment in
1491 // an asm syntax where hash's are not comment and the previous
1492 // statement parser did not check the end of statement. Relex as
1493 // EndOfStatement.
1494 StringRef CommentStr = parseStringToEndOfStatement();
1495 Lexer.Lex();
1496 Lexer.UnLex(AsmToken(AsmToken::EndOfStatement, CommentStr));
1497 return false;
1498 }
Nirav Davefd910412016-06-17 16:06:17 +00001499 // Statements always start with an identifier.
Sean Callanan936b0d32010-01-19 21:44:56 +00001500 AsmToken ID = getTok();
Daniel Dunbaree4465c2009-07-28 16:38:40 +00001501 SMLoc IDLoc = ID.getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001502 StringRef IDVal;
Kevin Enderby0510b482010-05-17 23:08:19 +00001503 int64_t LocalLabelVal = -1;
Nirav Davefd910412016-06-17 16:06:17 +00001504 if (Lexer.is(AsmToken::HashDirective))
Jim Grosbach4b905842013-09-20 23:08:21 +00001505 return parseCppHashLineFilenameComment(IDLoc);
Kevin Enderbyfa3c6f12010-12-24 00:12:02 +00001506 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderby0510b482010-05-17 23:08:19 +00001507 if (Lexer.is(AsmToken::Integer)) {
1508 LocalLabelVal = getTok().getIntVal();
1509 if (LocalLabelVal < 0) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001510 if (!TheCondState.Ignore) {
1511 Lex(); // always eat a token
1512 return Error(IDLoc, "unexpected token at start of statement");
1513 }
Kevin Enderby0510b482010-05-17 23:08:19 +00001514 IDVal = "";
Eli Bendersky88024712013-01-16 19:32:36 +00001515 } else {
Kevin Enderby0510b482010-05-17 23:08:19 +00001516 IDVal = getTok().getString();
1517 Lex(); // Consume the integer token to be used as an identifier token.
1518 if (Lexer.getKind() != AsmToken::Colon) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001519 if (!TheCondState.Ignore) {
1520 Lex(); // always eat a token
1521 return Error(IDLoc, "unexpected token at start of statement");
1522 }
Kevin Enderby0510b482010-05-17 23:08:19 +00001523 }
1524 }
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001525 } else if (Lexer.is(AsmToken::Dot)) {
1526 // Treat '.' as a valid identifier in this context.
1527 Lex();
1528 IDVal = ".";
Colin LeMahieu8a0453e2015-11-09 00:31:07 +00001529 } else if (Lexer.is(AsmToken::LCurly)) {
1530 // Treat '{' as a valid identifier in this context.
1531 Lex();
1532 IDVal = "{";
1533
1534 } else if (Lexer.is(AsmToken::RCurly)) {
1535 // Treat '}' as a valid identifier in this context.
1536 Lex();
1537 IDVal = "}";
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001538 } else if (parseIdentifier(IDVal)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001539 if (!TheCondState.Ignore) {
1540 Lex(); // always eat a token
1541 return Error(IDLoc, "unexpected token at start of statement");
1542 }
Chris Lattner926885c2010-04-17 18:14:27 +00001543 IDVal = "";
1544 }
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001545
Chris Lattner926885c2010-04-17 18:14:27 +00001546 // Handle conditional assembly here before checking for skipping. We
1547 // have to do this so that .endif isn't skipped in a ".if 0" block for
1548 // example.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001549 StringMap<DirectiveKind>::const_iterator DirKindIt =
Jim Grosbach4b905842013-09-20 23:08:21 +00001550 DirectiveKindMap.find(IDVal);
1551 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1552 ? DK_NO_DIRECTIVE
1553 : DirKindIt->getValue();
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001554 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001555 default:
1556 break;
1557 case DK_IF:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001558 case DK_IFEQ:
1559 case DK_IFGE:
1560 case DK_IFGT:
1561 case DK_IFLE:
1562 case DK_IFLT:
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00001563 case DK_IFNE:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001564 return parseDirectiveIf(IDLoc, DirKind);
Jim Grosbach4b905842013-09-20 23:08:21 +00001565 case DK_IFB:
1566 return parseDirectiveIfb(IDLoc, true);
1567 case DK_IFNB:
1568 return parseDirectiveIfb(IDLoc, false);
1569 case DK_IFC:
1570 return parseDirectiveIfc(IDLoc, true);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00001571 case DK_IFEQS:
Sid Manning51c35602015-03-18 14:20:54 +00001572 return parseDirectiveIfeqs(IDLoc, true);
Jim Grosbach4b905842013-09-20 23:08:21 +00001573 case DK_IFNC:
1574 return parseDirectiveIfc(IDLoc, false);
Sid Manning51c35602015-03-18 14:20:54 +00001575 case DK_IFNES:
1576 return parseDirectiveIfeqs(IDLoc, false);
Jim Grosbach4b905842013-09-20 23:08:21 +00001577 case DK_IFDEF:
1578 return parseDirectiveIfdef(IDLoc, true);
1579 case DK_IFNDEF:
1580 case DK_IFNOTDEF:
1581 return parseDirectiveIfdef(IDLoc, false);
1582 case DK_ELSEIF:
1583 return parseDirectiveElseIf(IDLoc);
1584 case DK_ELSE:
1585 return parseDirectiveElse(IDLoc);
1586 case DK_ENDIF:
1587 return parseDirectiveEndIf(IDLoc);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001588 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001589
Eli Bendersky88024712013-01-16 19:32:36 +00001590 // Ignore the statement if in the middle of inactive conditional
1591 // (e.g. ".if 0").
Chad Rosiereda70b32012-10-20 00:47:08 +00001592 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001593 eatToEndOfStatement();
Chris Lattner926885c2010-04-17 18:14:27 +00001594 return false;
1595 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001596
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001597 // FIXME: Recurse on local labels?
1598
1599 // See what kind of statement we have.
1600 switch (Lexer.getKind()) {
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001601 case AsmToken::Colon: {
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001602 if (!getTargetParser().isLabel(ID))
1603 break;
Nirav Davef43cc9f2016-10-10 15:24:54 +00001604 if (checkForValidSection())
1605 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00001606
Chris Lattner36e02122009-06-21 20:54:55 +00001607 // identifier ':' -> Label.
Sean Callanan686ed8d2010-01-19 20:22:31 +00001608 Lex();
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001609
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001610 // Diagnose attempt to use '.' as a label.
1611 if (IDVal == ".")
1612 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1613
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001614 // Diagnose attempt to use a variable as a label.
1615 //
1616 // FIXME: Diagnostics. Note the location of the definition as a label.
1617 // FIXME: This doesn't diagnose assignment to a symbol which has been
1618 // implicitly marked as external.
Kevin Enderby0510b482010-05-17 23:08:19 +00001619 MCSymbol *Sym;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001620 if (LocalLabelVal == -1) {
1621 if (ParsingInlineAsm && SI) {
Nico Weber67e715f2015-06-19 23:43:47 +00001622 StringRef RewrittenLabel =
1623 SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true);
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00001624 assert(!RewrittenLabel.empty() &&
Nico Weber67e715f2015-06-19 23:43:47 +00001625 "We should have an internal name here.");
Craig Topper7d5b2312015-10-10 05:25:02 +00001626 Info.AsmRewrites->emplace_back(AOK_Label, IDLoc, IDVal.size(),
1627 RewrittenLabel);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001628 IDVal = RewrittenLabel;
1629 }
Jim Grosbach6f482002015-05-18 18:43:14 +00001630 Sym = getContext().getOrCreateSymbol(IDVal);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001631 } else
Jim Grosbach6f482002015-05-18 18:43:14 +00001632 Sym = Ctx.createDirectionalLocalSymbol(LocalLabelVal);
David Majnemer58cb80c2014-12-24 10:27:50 +00001633
1634 Sym->redefineIfPossible();
1635
Daniel Dunbardeb7ba92010-05-05 19:01:00 +00001636 if (!Sym->isUndefined() || Sym->isVariable())
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001637 return Error(IDLoc, "invalid symbol redefinition");
Michael J. Spencer530ce852010-10-09 11:00:50 +00001638
Nirav Dave9263ae32016-08-02 19:17:54 +00001639 // End of Labels should be treated as end of line for lexing
1640 // purposes but that information is not available to the Lexer who
1641 // does not understand Labels. This may cause us to see a Hash
1642 // here instead of a preprocessor line comment.
1643 if (getTok().is(AsmToken::Hash)) {
1644 StringRef CommentStr = parseStringToEndOfStatement();
1645 Lexer.Lex();
1646 Lexer.UnLex(AsmToken(AsmToken::EndOfStatement, CommentStr));
1647 }
1648
Nirav Dave8ea792d2016-07-13 14:03:12 +00001649 // Consume any end of statement token, if present, to avoid spurious
1650 // AddBlankLine calls().
1651 if (getTok().is(AsmToken::EndOfStatement)) {
1652 Lex();
1653 }
1654
Daniel Dunbare73b2672009-08-26 22:13:22 +00001655 // Emit the label.
Chad Rosierf3feab32013-01-07 20:34:12 +00001656 if (!ParsingInlineAsm)
1657 Out.EmitLabel(Sym);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001658
Kevin Enderbye7739d42011-12-09 18:09:40 +00001659 // If we are generating dwarf for assembly source files then gather the
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001660 // info to make a dwarf label entry for this label if needed.
Kevin Enderbye7739d42011-12-09 18:09:40 +00001661 if (getContext().getGenDwarfForAssembly())
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001662 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1663 IDLoc);
Kevin Enderbye7739d42011-12-09 18:09:40 +00001664
Tim Northover1744d0a2013-10-25 12:49:50 +00001665 getTargetParser().onLabelParsed(Sym);
1666
Eli Friedman0f4871d2012-10-22 23:58:19 +00001667 return false;
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001668 }
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001669
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001670 case AsmToken::Equal:
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001671 if (!getTargetParser().equalIsAsmAssignment())
1672 break;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001673 // identifier '=' ... -> assignment statement
Sean Callanan686ed8d2010-01-19 20:22:31 +00001674 Lex();
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001675
Jim Grosbach4b905842013-09-20 23:08:21 +00001676 return parseAssignment(IDVal, true);
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001677
1678 default: // Normal instruction or directive.
1679 break;
Chris Lattner36e02122009-06-21 20:54:55 +00001680 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001681
1682 // If macros are enabled, check to see if this is a macro instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00001683 if (areMacrosEnabled())
1684 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1685 return handleMacroEntry(M, IDLoc);
Eli Bendersky38274122013-01-14 23:22:36 +00001686 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001687
Michael J. Spencer530ce852010-10-09 11:00:50 +00001688 // Otherwise, we have a normal instruction or directive.
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001689
Eli Bendersky17233942013-01-15 22:59:42 +00001690 // Directives start with "."
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001691 if (IDVal[0] == '.' && IDVal != ".") {
Eli Bendersky17233942013-01-15 22:59:42 +00001692 // There are several entities interested in parsing directives:
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001693 //
Eli Bendersky17233942013-01-15 22:59:42 +00001694 // 1. The target-specific assembly parser. Some directives are target
1695 // specific or may potentially behave differently on certain targets.
1696 // 2. Asm parser extensions. For example, platform-specific parsers
1697 // (like the ELF parser) register themselves as extensions.
1698 // 3. The generic directive parser implemented by this class. These are
1699 // all the directives that behave in a target and platform independent
1700 // manner, or at least have a default behavior that's shared between
1701 // all targets and platforms.
Akira Hatanakad3590752012-07-05 19:09:33 +00001702
Oliver Stannard21718282016-07-26 14:19:47 +00001703 getTargetParser().flushPendingInstructions(getStreamer());
1704
Nirav Dave2364748a2016-09-16 18:30:20 +00001705 SMLoc StartTokLoc = getTok().getLoc();
1706 bool TPDirectiveReturn = getTargetParser().ParseDirective(ID);
1707
1708 if (hasPendingError())
1709 return true;
1710 // Currently the return value should be true if we are
1711 // uninterested but as this is at odds with the standard parsing
1712 // convention (return true = error) we have instances of a parsed
1713 // directive that fails returning true as an error. Catch these
1714 // cases as best as possible errors here.
1715 if (TPDirectiveReturn && StartTokLoc != getTok().getLoc())
1716 return true;
1717 // Return if we did some parsing or believe we succeeded.
1718 if (!TPDirectiveReturn || StartTokLoc != getTok().getLoc())
Akira Hatanakad3590752012-07-05 19:09:33 +00001719 return false;
1720
Alp Tokercb402912014-01-24 17:20:08 +00001721 // Next, check the extension directive map to see if any extension has
Eli Bendersky17233942013-01-15 22:59:42 +00001722 // registered itself to parse this directive.
Jim Grosbach4b905842013-09-20 23:08:21 +00001723 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1724 ExtensionDirectiveMap.lookup(IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +00001725 if (Handler.first)
1726 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1727
1728 // Finally, if no one else is interested in this directive, it must be
1729 // generic and familiar to this class.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001730 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001731 default:
1732 break;
1733 case DK_SET:
1734 case DK_EQU:
1735 return parseDirectiveSet(IDVal, true);
1736 case DK_EQUIV:
1737 return parseDirectiveSet(IDVal, false);
1738 case DK_ASCII:
1739 return parseDirectiveAscii(IDVal, false);
1740 case DK_ASCIZ:
1741 case DK_STRING:
1742 return parseDirectiveAscii(IDVal, true);
1743 case DK_BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001744 case DK_DC_B:
1745 return parseDirectiveValue(IDVal, 1);
1746 case DK_DC:
1747 case DK_DC_W:
Jim Grosbach4b905842013-09-20 23:08:21 +00001748 case DK_SHORT:
1749 case DK_VALUE:
1750 case DK_2BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001751 return parseDirectiveValue(IDVal, 2);
Jim Grosbach4b905842013-09-20 23:08:21 +00001752 case DK_LONG:
1753 case DK_INT:
1754 case DK_4BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001755 case DK_DC_L:
1756 return parseDirectiveValue(IDVal, 4);
Jim Grosbach4b905842013-09-20 23:08:21 +00001757 case DK_QUAD:
1758 case DK_8BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001759 return parseDirectiveValue(IDVal, 8);
1760 case DK_DC_A:
1761 return parseDirectiveValue(IDVal,
1762 getContext().getAsmInfo()->getPointerSize());
David Woodhoused6de0d92014-02-01 16:20:59 +00001763 case DK_OCTA:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001764 return parseDirectiveOctaValue(IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001765 case DK_SINGLE:
1766 case DK_FLOAT:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001767 case DK_DC_S:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001768 return parseDirectiveRealValue(IDVal, APFloat::IEEEsingle());
Jim Grosbach4b905842013-09-20 23:08:21 +00001769 case DK_DOUBLE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001770 case DK_DC_D:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001771 return parseDirectiveRealValue(IDVal, APFloat::IEEEdouble());
Jim Grosbach4b905842013-09-20 23:08:21 +00001772 case DK_ALIGN: {
1773 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1774 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1775 }
1776 case DK_ALIGN32: {
1777 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1778 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1779 }
1780 case DK_BALIGN:
1781 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1782 case DK_BALIGNW:
1783 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1784 case DK_BALIGNL:
1785 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1786 case DK_P2ALIGN:
1787 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1788 case DK_P2ALIGNW:
1789 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1790 case DK_P2ALIGNL:
1791 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1792 case DK_ORG:
1793 return parseDirectiveOrg();
1794 case DK_FILL:
1795 return parseDirectiveFill();
1796 case DK_ZERO:
1797 return parseDirectiveZero();
1798 case DK_EXTERN:
1799 eatToEndOfStatement(); // .extern is the default, ignore it.
1800 return false;
1801 case DK_GLOBL:
1802 case DK_GLOBAL:
1803 return parseDirectiveSymbolAttribute(MCSA_Global);
1804 case DK_LAZY_REFERENCE:
1805 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1806 case DK_NO_DEAD_STRIP:
1807 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1808 case DK_SYMBOL_RESOLVER:
1809 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1810 case DK_PRIVATE_EXTERN:
1811 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1812 case DK_REFERENCE:
1813 return parseDirectiveSymbolAttribute(MCSA_Reference);
1814 case DK_WEAK_DEFINITION:
1815 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1816 case DK_WEAK_REFERENCE:
1817 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1818 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1819 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1820 case DK_COMM:
1821 case DK_COMMON:
1822 return parseDirectiveComm(/*IsLocal=*/false);
1823 case DK_LCOMM:
1824 return parseDirectiveComm(/*IsLocal=*/true);
1825 case DK_ABORT:
1826 return parseDirectiveAbort();
1827 case DK_INCLUDE:
1828 return parseDirectiveInclude();
1829 case DK_INCBIN:
1830 return parseDirectiveIncbin();
1831 case DK_CODE16:
1832 case DK_CODE16GCC:
Nirav Davefd910412016-06-17 16:06:17 +00001833 return TokError(Twine(IDVal) +
1834 " not currently supported for this target");
Jim Grosbach4b905842013-09-20 23:08:21 +00001835 case DK_REPT:
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00001836 return parseDirectiveRept(IDLoc, IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001837 case DK_IRP:
1838 return parseDirectiveIrp(IDLoc);
1839 case DK_IRPC:
1840 return parseDirectiveIrpc(IDLoc);
1841 case DK_ENDR:
1842 return parseDirectiveEndr(IDLoc);
1843 case DK_BUNDLE_ALIGN_MODE:
1844 return parseDirectiveBundleAlignMode();
1845 case DK_BUNDLE_LOCK:
1846 return parseDirectiveBundleLock();
1847 case DK_BUNDLE_UNLOCK:
1848 return parseDirectiveBundleUnlock();
1849 case DK_SLEB128:
1850 return parseDirectiveLEB128(true);
1851 case DK_ULEB128:
1852 return parseDirectiveLEB128(false);
1853 case DK_SPACE:
1854 case DK_SKIP:
1855 return parseDirectiveSpace(IDVal);
1856 case DK_FILE:
1857 return parseDirectiveFile(IDLoc);
1858 case DK_LINE:
1859 return parseDirectiveLine();
1860 case DK_LOC:
1861 return parseDirectiveLoc();
1862 case DK_STABS:
1863 return parseDirectiveStabs();
Reid Kleckner2214ed82016-01-29 00:49:42 +00001864 case DK_CV_FILE:
1865 return parseDirectiveCVFile();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00001866 case DK_CV_FUNC_ID:
1867 return parseDirectiveCVFuncId();
1868 case DK_CV_INLINE_SITE_ID:
1869 return parseDirectiveCVInlineSiteId();
Reid Kleckner2214ed82016-01-29 00:49:42 +00001870 case DK_CV_LOC:
1871 return parseDirectiveCVLoc();
1872 case DK_CV_LINETABLE:
1873 return parseDirectiveCVLinetable();
David Majnemer6fcbd7e2016-01-29 19:24:12 +00001874 case DK_CV_INLINE_LINETABLE:
1875 return parseDirectiveCVInlineLinetable();
David Majnemer408b5e62016-02-05 01:55:49 +00001876 case DK_CV_DEF_RANGE:
1877 return parseDirectiveCVDefRange();
Reid Kleckner2214ed82016-01-29 00:49:42 +00001878 case DK_CV_STRINGTABLE:
1879 return parseDirectiveCVStringTable();
1880 case DK_CV_FILECHECKSUMS:
1881 return parseDirectiveCVFileChecksums();
Jim Grosbach4b905842013-09-20 23:08:21 +00001882 case DK_CFI_SECTIONS:
1883 return parseDirectiveCFISections();
1884 case DK_CFI_STARTPROC:
1885 return parseDirectiveCFIStartProc();
1886 case DK_CFI_ENDPROC:
1887 return parseDirectiveCFIEndProc();
1888 case DK_CFI_DEF_CFA:
1889 return parseDirectiveCFIDefCfa(IDLoc);
1890 case DK_CFI_DEF_CFA_OFFSET:
1891 return parseDirectiveCFIDefCfaOffset();
1892 case DK_CFI_ADJUST_CFA_OFFSET:
1893 return parseDirectiveCFIAdjustCfaOffset();
1894 case DK_CFI_DEF_CFA_REGISTER:
1895 return parseDirectiveCFIDefCfaRegister(IDLoc);
1896 case DK_CFI_OFFSET:
1897 return parseDirectiveCFIOffset(IDLoc);
1898 case DK_CFI_REL_OFFSET:
1899 return parseDirectiveCFIRelOffset(IDLoc);
1900 case DK_CFI_PERSONALITY:
1901 return parseDirectiveCFIPersonalityOrLsda(true);
1902 case DK_CFI_LSDA:
1903 return parseDirectiveCFIPersonalityOrLsda(false);
1904 case DK_CFI_REMEMBER_STATE:
1905 return parseDirectiveCFIRememberState();
1906 case DK_CFI_RESTORE_STATE:
1907 return parseDirectiveCFIRestoreState();
1908 case DK_CFI_SAME_VALUE:
1909 return parseDirectiveCFISameValue(IDLoc);
1910 case DK_CFI_RESTORE:
1911 return parseDirectiveCFIRestore(IDLoc);
1912 case DK_CFI_ESCAPE:
1913 return parseDirectiveCFIEscape();
1914 case DK_CFI_SIGNAL_FRAME:
1915 return parseDirectiveCFISignalFrame();
1916 case DK_CFI_UNDEFINED:
1917 return parseDirectiveCFIUndefined(IDLoc);
1918 case DK_CFI_REGISTER:
1919 return parseDirectiveCFIRegister(IDLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00001920 case DK_CFI_WINDOW_SAVE:
1921 return parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +00001922 case DK_MACROS_ON:
1923 case DK_MACROS_OFF:
1924 return parseDirectiveMacrosOnOff(IDVal);
1925 case DK_MACRO:
1926 return parseDirectiveMacro(IDLoc);
Nico Weber155dccd12014-07-24 17:08:39 +00001927 case DK_EXITM:
1928 return parseDirectiveExitMacro(IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001929 case DK_ENDM:
1930 case DK_ENDMACRO:
1931 return parseDirectiveEndMacro(IDVal);
1932 case DK_PURGEM:
1933 return parseDirectivePurgeMacro(IDLoc);
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00001934 case DK_END:
1935 return parseDirectiveEnd(IDLoc);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00001936 case DK_ERR:
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00001937 return parseDirectiveError(IDLoc, false);
1938 case DK_ERROR:
1939 return parseDirectiveError(IDLoc, true);
Nico Weber404012b2014-07-24 16:26:06 +00001940 case DK_WARNING:
1941 return parseDirectiveWarning(IDLoc);
Daniel Sanders9f6ad492015-11-12 13:33:00 +00001942 case DK_RELOC:
1943 return parseDirectiveReloc(IDLoc);
Petr Hosek4cb08ce2016-09-23 19:25:15 +00001944 case DK_DCB:
1945 case DK_DCB_W:
1946 return parseDirectiveDCB(IDVal, 2);
1947 case DK_DCB_B:
1948 return parseDirectiveDCB(IDVal, 1);
1949 case DK_DCB_D:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001950 return parseDirectiveRealDCB(IDVal, APFloat::IEEEdouble());
Petr Hosek4cb08ce2016-09-23 19:25:15 +00001951 case DK_DCB_L:
1952 return parseDirectiveDCB(IDVal, 4);
1953 case DK_DCB_S:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001954 return parseDirectiveRealDCB(IDVal, APFloat::IEEEsingle());
Petr Hosek731bb9c2016-08-23 21:34:53 +00001955 case DK_DC_X:
Petr Hosek4cb08ce2016-09-23 19:25:15 +00001956 case DK_DCB_X:
Petr Hosek731bb9c2016-08-23 21:34:53 +00001957 return TokError(Twine(IDVal) +
1958 " not currently supported for this target");
Petr Hosek85b2f672016-09-23 21:53:36 +00001959 case DK_DS:
1960 case DK_DS_W:
1961 return parseDirectiveDS(IDVal, 2);
1962 case DK_DS_B:
1963 return parseDirectiveDS(IDVal, 1);
1964 case DK_DS_D:
1965 return parseDirectiveDS(IDVal, 8);
1966 case DK_DS_L:
1967 case DK_DS_S:
1968 return parseDirectiveDS(IDVal, 4);
1969 case DK_DS_P:
1970 case DK_DS_X:
1971 return parseDirectiveDS(IDVal, 12);
Eli Friedman20b02642010-07-19 04:17:25 +00001972 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00001973
Jim Grosbach758e0cc2012-05-01 18:38:27 +00001974 return Error(IDLoc, "unknown directive");
Chris Lattnere5074c42009-06-22 01:29:09 +00001975 }
Chris Lattner36e02122009-06-21 20:54:55 +00001976
Chad Rosierc7f552c2013-02-12 21:33:51 +00001977 // __asm _emit or __asm __emit
1978 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1979 IDVal == "_EMIT" || IDVal == "__EMIT"))
Jim Grosbach4b905842013-09-20 23:08:21 +00001980 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
Chad Rosierc7f552c2013-02-12 21:33:51 +00001981
1982 // __asm align
1983 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
Jim Grosbach4b905842013-09-20 23:08:21 +00001984 return parseDirectiveMSAlign(IDLoc, Info);
Eli Friedman0f4871d2012-10-22 23:58:19 +00001985
Michael Zuckerman02ecd432015-12-13 17:07:23 +00001986 if (ParsingInlineAsm && (IDVal == "even"))
1987 Info.AsmRewrites->emplace_back(AOK_EVEN, IDLoc, 4);
Nirav Davef43cc9f2016-10-10 15:24:54 +00001988 if (checkForValidSection())
1989 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00001990
Chris Lattner7cbfa442010-05-19 23:34:33 +00001991 // Canonicalize the opcode to lower case.
Eli Bendersky88024712013-01-16 19:32:36 +00001992 std::string OpcodeStr = IDVal.lower();
Chad Rosierf0e87202012-10-25 20:41:34 +00001993 ParseInstructionInfo IInfo(Info.AsmRewrites);
Nirav Dave2364748a2016-09-16 18:30:20 +00001994 bool ParseHadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, ID,
1995 Info.ParsedOperands);
1996 Info.ParseError = ParseHadError;
Chris Lattnere5074c42009-06-22 01:29:09 +00001997
Daniel Dunbar2eca0252010-08-11 06:37:09 +00001998 // Dump the parsed representation, if requested.
1999 if (getShowParsedOperands()) {
2000 SmallString<256> Str;
2001 raw_svector_ostream OS(Str);
2002 OS << "parsed instruction: [";
Eli Friedman0f4871d2012-10-22 23:58:19 +00002003 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002004 if (i != 0)
2005 OS << ", ";
Eli Friedman0f4871d2012-10-22 23:58:19 +00002006 Info.ParsedOperands[i]->print(OS);
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002007 }
2008 OS << "]";
2009
Jim Grosbach4b905842013-09-20 23:08:21 +00002010 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002011 }
2012
Nirav Dave2364748a2016-09-16 18:30:20 +00002013 // Fail even if ParseInstruction erroneously returns false.
2014 if (hasPendingError() || ParseHadError)
2015 return true;
2016
Oliver Stannard8b273082014-06-19 15:52:37 +00002017 // If we are generating dwarf for the current section then generate a .loc
2018 // directive for the instruction.
Nirav Dave2364748a2016-09-16 18:30:20 +00002019 if (!ParseHadError && getContext().getGenDwarfForAssembly() &&
Oliver Stannard8b273082014-06-19 15:52:37 +00002020 getContext().getGenDwarfSectionSyms().count(
Eric Christopher445c9522016-10-14 05:47:37 +00002021 getStreamer().getCurrentSectionOnly())) {
Saleem Abdulrasool4d6ed7c2014-12-24 06:32:43 +00002022 unsigned Line;
2023 if (ActiveMacros.empty())
2024 Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
2025 else
Frederic Riss16238d92015-06-25 21:57:33 +00002026 Line = SrcMgr.FindLineNumber(ActiveMacros.front()->InstantiationLoc,
2027 ActiveMacros.front()->ExitBuffer);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002028
Eli Bendersky88024712013-01-16 19:32:36 +00002029 // If we previously parsed a cpp hash file line comment then make sure the
2030 // current Dwarf File is for the CppHashFilename if not then emit the
2031 // Dwarf File table for it and adjust the line number for the .loc.
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00002032 if (!CppHashInfo.Filename.empty()) {
David Blaikiec714ef42014-03-17 01:52:11 +00002033 unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
Tim Northoverc0bef992016-04-13 19:46:54 +00002034 0, StringRef(), CppHashInfo.Filename);
David Blaikiec714ef42014-03-17 01:52:11 +00002035 getContext().setGenDwarfFileNumber(FileNumber);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002036
Jim Grosbach4b905842013-09-20 23:08:21 +00002037 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
2038 // cache with the different Loc from the call above we save the last
2039 // info we queried here with SrcMgr.FindLineNumber().
2040 unsigned CppHashLocLineNo;
Tim Northoverc0bef992016-04-13 19:46:54 +00002041 if (LastQueryIDLoc == CppHashInfo.Loc &&
2042 LastQueryBuffer == CppHashInfo.Buf)
Jim Grosbach4b905842013-09-20 23:08:21 +00002043 CppHashLocLineNo = LastQueryLine;
2044 else {
Tim Northoverc0bef992016-04-13 19:46:54 +00002045 CppHashLocLineNo =
2046 SrcMgr.FindLineNumber(CppHashInfo.Loc, CppHashInfo.Buf);
Jim Grosbach4b905842013-09-20 23:08:21 +00002047 LastQueryLine = CppHashLocLineNo;
Tim Northoverc0bef992016-04-13 19:46:54 +00002048 LastQueryIDLoc = CppHashInfo.Loc;
2049 LastQueryBuffer = CppHashInfo.Buf;
Jim Grosbach4b905842013-09-20 23:08:21 +00002050 }
Tim Northoverc0bef992016-04-13 19:46:54 +00002051 Line = CppHashInfo.LineNumber - 1 + (Line - CppHashLocLineNo);
Eli Bendersky88024712013-01-16 19:32:36 +00002052 }
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002053
Jim Grosbach4b905842013-09-20 23:08:21 +00002054 getStreamer().EmitDwarfLocDirective(
2055 getContext().getGenDwarfFileNumber(), Line, 0,
2056 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
2057 StringRef());
Kevin Enderby6469fc22011-11-01 22:27:22 +00002058 }
2059
Daniel Dunbarce0c1e12010-05-04 00:33:07 +00002060 // If parsing succeeded, match the instruction.
Nirav Dave2364748a2016-09-16 18:30:20 +00002061 if (!ParseHadError) {
Tim Northover26bb14e2014-08-18 11:49:42 +00002062 uint64_t ErrorInfo;
Nirav Dave2364748a2016-09-16 18:30:20 +00002063 if (getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
2064 Info.ParsedOperands, Out,
2065 ErrorInfo, ParsingInlineAsm))
2066 return true;
Chad Rosier49963552012-10-13 00:26:04 +00002067 }
Chris Lattnera2a9d162010-09-11 16:18:25 +00002068 return false;
Chris Lattnerb0133452009-06-21 20:16:42 +00002069}
Chris Lattnerbedf6c22009-06-24 04:43:34 +00002070
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00002071// Parse and erase curly braces marking block start/end
2072bool
2073AsmParser::parseCurlyBlockScope(SmallVectorImpl<AsmRewrite> &AsmStrRewrites) {
2074 // Identify curly brace marking block start/end
2075 if (Lexer.isNot(AsmToken::LCurly) && Lexer.isNot(AsmToken::RCurly))
2076 return false;
2077
2078 SMLoc StartLoc = Lexer.getLoc();
2079 Lex(); // Eat the brace
2080 if (Lexer.is(AsmToken::EndOfStatement))
2081 Lex(); // Eat EndOfStatement following the brace
2082
2083 // Erase the block start/end brace from the output asm string
2084 AsmStrRewrites.emplace_back(AOK_Skip, StartLoc, Lexer.getLoc().getPointer() -
2085 StartLoc.getPointer());
2086 return true;
2087}
2088
Jim Grosbach4b905842013-09-20 23:08:21 +00002089/// parseCppHashLineFilenameComment as this:
Kevin Enderby72553612011-09-13 23:45:18 +00002090/// ::= # number "filename"
Craig Topper3c76c522015-09-20 23:35:59 +00002091bool AsmParser::parseCppHashLineFilenameComment(SMLoc L) {
Kevin Enderby72553612011-09-13 23:45:18 +00002092 Lex(); // Eat the hash token.
Nirav Davefd910412016-06-17 16:06:17 +00002093 // Lexer only ever emits HashDirective if it fully formed if it's
2094 // done the checking already so this is an internal error.
2095 assert(getTok().is(AsmToken::Integer) &&
2096 "Lexing Cpp line comment: Expected Integer");
Kevin Enderby72553612011-09-13 23:45:18 +00002097 int64_t LineNumber = getTok().getIntVal();
Kevin Enderby72553612011-09-13 23:45:18 +00002098 Lex();
Nirav Davefd910412016-06-17 16:06:17 +00002099 assert(getTok().is(AsmToken::String) &&
2100 "Lexing Cpp line comment: Expected String");
Kevin Enderby72553612011-09-13 23:45:18 +00002101 StringRef Filename = getTok().getString();
Nirav Davefd910412016-06-17 16:06:17 +00002102 Lex();
Nirav Dave2364748a2016-09-16 18:30:20 +00002103
Kevin Enderby72553612011-09-13 23:45:18 +00002104 // Get rid of the enclosing quotes.
Jim Grosbach4b905842013-09-20 23:08:21 +00002105 Filename = Filename.substr(1, Filename.size() - 2);
Kevin Enderby72553612011-09-13 23:45:18 +00002106
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002107 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
Tim Northoverc0bef992016-04-13 19:46:54 +00002108 CppHashInfo.Loc = L;
2109 CppHashInfo.Filename = Filename;
2110 CppHashInfo.LineNumber = LineNumber;
2111 CppHashInfo.Buf = CurBuffer;
Kevin Enderby72553612011-09-13 23:45:18 +00002112 return false;
2113}
2114
Jim Grosbach4b905842013-09-20 23:08:21 +00002115/// \brief will use the last parsed cpp hash line filename comment
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002116/// for the Filename and LineNo if any in the diagnostic.
2117void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002118 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002119 raw_ostream &OS = errs();
2120
2121 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
Craig Topper3c76c522015-09-20 23:35:59 +00002122 SMLoc DiagLoc = Diag.getLoc();
Alp Tokera55b95b2014-07-06 10:33:31 +00002123 unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2124 unsigned CppHashBuf =
Tim Northoverc0bef992016-04-13 19:46:54 +00002125 Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashInfo.Loc);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002126
Jim Grosbach4b905842013-09-20 23:08:21 +00002127 // Like SourceMgr::printMessage() we need to print the include stack if any
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002128 // before printing the message.
Alp Tokera55b95b2014-07-06 10:33:31 +00002129 unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2130 if (!Parser->SavedDiagHandler && DiagCurBuffer &&
2131 DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002132 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
2133 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002134 }
2135
Eric Christophera7c32732012-12-18 00:30:54 +00002136 // If we have not parsed a cpp hash line filename comment or the source
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002137 // manager changed or buffer changed (like in a nested include) then just
2138 // print the normal diagnostic using its Filename and LineNo.
Tim Northoverc0bef992016-04-13 19:46:54 +00002139 if (!Parser->CppHashInfo.LineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002140 DiagBuf != CppHashBuf) {
Benjamin Kramer47f5e302011-10-16 10:48:29 +00002141 if (Parser->SavedDiagHandler)
2142 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
2143 else
Craig Topper353eda42014-04-24 06:44:33 +00002144 Diag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002145 return;
2146 }
2147
Eric Christophera7c32732012-12-18 00:30:54 +00002148 // Use the CppHashFilename and calculate a line number based on the
Tim Northoverc0bef992016-04-13 19:46:54 +00002149 // CppHashInfo.Loc and CppHashInfo.LineNumber relative to this Diag's SMLoc
2150 // for the diagnostic.
2151 const std::string &Filename = Parser->CppHashInfo.Filename;
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002152
2153 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
2154 int CppHashLocLineNo =
Tim Northoverc0bef992016-04-13 19:46:54 +00002155 Parser->SrcMgr.FindLineNumber(Parser->CppHashInfo.Loc, CppHashBuf);
Jim Grosbach4b905842013-09-20 23:08:21 +00002156 int LineNo =
Tim Northoverc0bef992016-04-13 19:46:54 +00002157 Parser->CppHashInfo.LineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002158
Jim Grosbach4b905842013-09-20 23:08:21 +00002159 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
2160 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
Chris Lattner72845262011-10-16 05:47:55 +00002161 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002162
Benjamin Kramer47f5e302011-10-16 10:48:29 +00002163 if (Parser->SavedDiagHandler)
2164 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
2165 else
Craig Topper353eda42014-04-24 06:44:33 +00002166 NewDiag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002167}
2168
Rafael Espindola2c064482012-08-21 18:29:30 +00002169// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
2170// difference being that that function accepts '@' as part of identifiers and
2171// we can't do that. AsmLexer.cpp should probably be changed to handle
2172// '@' as a special case when needed.
2173static bool isIdentifierChar(char c) {
Guy Benyei83c74e92013-02-12 21:21:59 +00002174 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
2175 c == '.';
Rafael Espindola2c064482012-08-21 18:29:30 +00002176}
2177
Rafael Espindola34b9c512012-06-03 23:57:14 +00002178bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00002179 ArrayRef<MCAsmMacroParameter> Parameters,
Toma Tabacu217116e2015-04-27 10:50:29 +00002180 ArrayRef<MCAsmMacroArgument> A,
Craig Topper3c76c522015-09-20 23:35:59 +00002181 bool EnableAtPseudoVariable, SMLoc L) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00002182 unsigned NParameters = Parameters.size();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002183 bool HasVararg = NParameters ? Parameters.back().Vararg : false;
Benjamin Kramer513e7442014-02-20 13:36:32 +00002184 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
Rafael Espindola1134ab232011-06-05 02:43:45 +00002185 return Error(L, "Wrong number of arguments");
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002186
Preston Gurd05500642012-09-19 20:36:12 +00002187 // A macro without parameters is handled differently on Darwin:
2188 // gas accepts no arguments and does no substitutions
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002189 while (!Body.empty()) {
2190 // Scan for the next substitution.
2191 std::size_t End = Body.size(), Pos = 0;
2192 for (; Pos != End; ++Pos) {
2193 // Check for a substitution or escape.
Benjamin Kramer513e7442014-02-20 13:36:32 +00002194 if (IsDarwin && !NParameters) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00002195 // This macro has no parameters, look for $0, $1, etc.
2196 if (Body[Pos] != '$' || Pos + 1 == End)
2197 continue;
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002198
Rafael Espindola1134ab232011-06-05 02:43:45 +00002199 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00002200 if (Next == '$' || Next == 'n' ||
2201 isdigit(static_cast<unsigned char>(Next)))
Rafael Espindola1134ab232011-06-05 02:43:45 +00002202 break;
2203 } else {
2204 // This macro has parameters, look for \foo, \bar, etc.
2205 if (Body[Pos] == '\\' && Pos + 1 != End)
2206 break;
2207 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002208 }
2209
2210 // Add the prefix.
2211 OS << Body.slice(0, Pos);
2212
2213 // Check if we reached the end.
2214 if (Pos == End)
2215 break;
2216
Benjamin Kramer513e7442014-02-20 13:36:32 +00002217 if (IsDarwin && !NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002218 switch (Body[Pos + 1]) {
2219 // $$ => $
Rafael Espindola1134ab232011-06-05 02:43:45 +00002220 case '$':
2221 OS << '$';
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002222 break;
2223
Jim Grosbach4b905842013-09-20 23:08:21 +00002224 // $n => number of arguments
Rafael Espindola1134ab232011-06-05 02:43:45 +00002225 case 'n':
2226 OS << A.size();
2227 break;
2228
Jim Grosbach4b905842013-09-20 23:08:21 +00002229 // $[0-9] => argument
Rafael Espindola1134ab232011-06-05 02:43:45 +00002230 default: {
2231 // Missing arguments are ignored.
Jim Grosbach4b905842013-09-20 23:08:21 +00002232 unsigned Index = Body[Pos + 1] - '0';
Rafael Espindola1134ab232011-06-05 02:43:45 +00002233 if (Index >= A.size())
2234 break;
2235
2236 // Otherwise substitute with the token values, with spaces eliminated.
Craig Topper84008482015-10-10 05:38:14 +00002237 for (const AsmToken &Token : A[Index])
2238 OS << Token.getString();
Rafael Espindola1134ab232011-06-05 02:43:45 +00002239 break;
2240 }
2241 }
2242 Pos += 2;
2243 } else {
2244 unsigned I = Pos + 1;
Toma Tabacu217116e2015-04-27 10:50:29 +00002245
2246 // Check for the \@ pseudo-variable.
2247 if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End)
Rafael Espindola1134ab232011-06-05 02:43:45 +00002248 ++I;
Toma Tabacu217116e2015-04-27 10:50:29 +00002249 else
2250 while (isIdentifierChar(Body[I]) && I + 1 != End)
2251 ++I;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002252
Jim Grosbach4b905842013-09-20 23:08:21 +00002253 const char *Begin = Body.data() + Pos + 1;
2254 StringRef Argument(Begin, I - (Pos + 1));
Rafael Espindola1134ab232011-06-05 02:43:45 +00002255 unsigned Index = 0;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002256
Toma Tabacu217116e2015-04-27 10:50:29 +00002257 if (Argument == "@") {
2258 OS << NumOfMacroInstantiations;
2259 Pos += 2;
Preston Gurd05500642012-09-19 20:36:12 +00002260 } else {
Toma Tabacu217116e2015-04-27 10:50:29 +00002261 for (; Index < NParameters; ++Index)
2262 if (Parameters[Index].Name == Argument)
2263 break;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002264
Toma Tabacu217116e2015-04-27 10:50:29 +00002265 if (Index == NParameters) {
2266 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
2267 Pos += 3;
2268 else {
2269 OS << '\\' << Argument;
2270 Pos = I;
2271 }
2272 } else {
2273 bool VarargParameter = HasVararg && Index == (NParameters - 1);
Craig Topper84008482015-10-10 05:38:14 +00002274 for (const AsmToken &Token : A[Index])
Toma Tabacu217116e2015-04-27 10:50:29 +00002275 // We expect no quotes around the string's contents when
2276 // parsing for varargs.
Craig Topper84008482015-10-10 05:38:14 +00002277 if (Token.getKind() != AsmToken::String || VarargParameter)
2278 OS << Token.getString();
Toma Tabacu217116e2015-04-27 10:50:29 +00002279 else
Craig Topper84008482015-10-10 05:38:14 +00002280 OS << Token.getStringContents();
Toma Tabacu217116e2015-04-27 10:50:29 +00002281
2282 Pos += 1 + Argument.size();
2283 }
Preston Gurd05500642012-09-19 20:36:12 +00002284 }
Rafael Espindola1134ab232011-06-05 02:43:45 +00002285 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002286 // Update the scan point.
Rafael Espindola1134ab232011-06-05 02:43:45 +00002287 Body = Body.substr(Pos);
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002288 }
Daniel Dunbar43235712010-07-18 18:54:11 +00002289
Rafael Espindola1134ab232011-06-05 02:43:45 +00002290 return false;
2291}
Daniel Dunbar43235712010-07-18 18:54:11 +00002292
Nico Weber2a8f9222014-07-24 16:29:04 +00002293MacroInstantiation::MacroInstantiation(SMLoc IL, int EB, SMLoc EL,
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002294 size_t CondStackDepth)
Rafael Espindolaf43a94e2014-08-17 22:48:55 +00002295 : InstantiationLoc(IL), ExitBuffer(EB), ExitLoc(EL),
Nico Weber155dccd12014-07-24 17:08:39 +00002296 CondStackDepth(CondStackDepth) {}
Daniel Dunbar43235712010-07-18 18:54:11 +00002297
Jim Grosbach4b905842013-09-20 23:08:21 +00002298static bool isOperator(AsmToken::TokenKind kind) {
2299 switch (kind) {
2300 default:
2301 return false;
2302 case AsmToken::Plus:
2303 case AsmToken::Minus:
2304 case AsmToken::Tilde:
2305 case AsmToken::Slash:
2306 case AsmToken::Star:
2307 case AsmToken::Dot:
2308 case AsmToken::Equal:
2309 case AsmToken::EqualEqual:
2310 case AsmToken::Pipe:
2311 case AsmToken::PipePipe:
2312 case AsmToken::Caret:
2313 case AsmToken::Amp:
2314 case AsmToken::AmpAmp:
2315 case AsmToken::Exclaim:
2316 case AsmToken::ExclaimEqual:
Jim Grosbach4b905842013-09-20 23:08:21 +00002317 case AsmToken::Less:
2318 case AsmToken::LessEqual:
2319 case AsmToken::LessLess:
2320 case AsmToken::LessGreater:
2321 case AsmToken::Greater:
2322 case AsmToken::GreaterEqual:
2323 case AsmToken::GreaterGreater:
2324 return true;
Preston Gurd05500642012-09-19 20:36:12 +00002325 }
2326}
2327
David Majnemer16252452014-01-29 00:07:39 +00002328namespace {
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002329
David Majnemer16252452014-01-29 00:07:39 +00002330class AsmLexerSkipSpaceRAII {
2331public:
2332 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
2333 Lexer.setSkipSpace(SkipSpace);
2334 }
2335
2336 ~AsmLexerSkipSpaceRAII() {
2337 Lexer.setSkipSpace(true);
2338 }
2339
2340private:
2341 AsmLexer &Lexer;
2342};
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002343
2344} // end anonymous namespace
David Majnemer16252452014-01-29 00:07:39 +00002345
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002346bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
2347
2348 if (Vararg) {
2349 if (Lexer.isNot(AsmToken::EndOfStatement)) {
2350 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002351 MA.emplace_back(AsmToken::String, Str);
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002352 }
2353 return false;
2354 }
2355
Rafael Espindola768b41c2012-06-15 14:02:34 +00002356 unsigned ParenLevel = 0;
Preston Gurd05500642012-09-19 20:36:12 +00002357
David Majnemer16252452014-01-29 00:07:39 +00002358 // Darwin doesn't use spaces to delmit arguments.
2359 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
Rafael Espindola768b41c2012-06-15 14:02:34 +00002360
Scott Egertona1fa68a2016-02-11 13:48:49 +00002361 bool SpaceEaten;
2362
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002363 while (true) {
Scott Egertona1fa68a2016-02-11 13:48:49 +00002364 SpaceEaten = false;
David Majnemer16252452014-01-29 00:07:39 +00002365 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002366 return TokError("unexpected token in macro instantiation");
Preston Gurd05500642012-09-19 20:36:12 +00002367
Scott Egertona1fa68a2016-02-11 13:48:49 +00002368 if (ParenLevel == 0) {
Preston Gurd05500642012-09-19 20:36:12 +00002369
Scott Egertona1fa68a2016-02-11 13:48:49 +00002370 if (Lexer.is(AsmToken::Comma))
2371 break;
2372
2373 if (Lexer.is(AsmToken::Space)) {
2374 SpaceEaten = true;
Nirav Dave1180e6892016-06-02 17:15:05 +00002375 Lexer.Lex(); // Eat spaces
Scott Egertona1fa68a2016-02-11 13:48:49 +00002376 }
Preston Gurd05500642012-09-19 20:36:12 +00002377
2378 // Spaces can delimit parameters, but could also be part an expression.
2379 // If the token after a space is an operator, add the token and the next
2380 // one into this argument
David Majnemer91fc4c22014-01-29 18:57:46 +00002381 if (!IsDarwin) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002382 if (isOperator(Lexer.getKind())) {
Scott Egertona1fa68a2016-02-11 13:48:49 +00002383 MA.push_back(getTok());
Nirav Dave1180e6892016-06-02 17:15:05 +00002384 Lexer.Lex();
Preston Gurd05500642012-09-19 20:36:12 +00002385
Scott Egertona1fa68a2016-02-11 13:48:49 +00002386 // Whitespace after an operator can be ignored.
2387 if (Lexer.is(AsmToken::Space))
Nirav Dave1180e6892016-06-02 17:15:05 +00002388 Lexer.Lex();
Scott Egertona1fa68a2016-02-11 13:48:49 +00002389
2390 continue;
Preston Gurd05500642012-09-19 20:36:12 +00002391 }
2392 }
Scott Egertona1fa68a2016-02-11 13:48:49 +00002393 if (SpaceEaten)
2394 break;
Preston Gurd05500642012-09-19 20:36:12 +00002395 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002396
Jim Grosbach4b905842013-09-20 23:08:21 +00002397 // handleMacroEntry relies on not advancing the lexer here
Rafael Espindola768b41c2012-06-15 14:02:34 +00002398 // to be able to fill in the remaining default parameter values
2399 if (Lexer.is(AsmToken::EndOfStatement))
2400 break;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002401
2402 // Adjust the current parentheses level.
2403 if (Lexer.is(AsmToken::LParen))
2404 ++ParenLevel;
2405 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
2406 --ParenLevel;
2407
2408 // Append the token to the current argument list.
2409 MA.push_back(getTok());
Nirav Dave1180e6892016-06-02 17:15:05 +00002410 Lexer.Lex();
Rafael Espindola768b41c2012-06-15 14:02:34 +00002411 }
Preston Gurd05500642012-09-19 20:36:12 +00002412
Rafael Espindola768b41c2012-06-15 14:02:34 +00002413 if (ParenLevel != 0)
Rafael Espindola3e5eb422012-08-21 15:55:04 +00002414 return TokError("unbalanced parentheses in macro argument");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002415 return false;
2416}
2417
2418// Parse the macro instantiation arguments.
Jim Grosbach4b905842013-09-20 23:08:21 +00002419bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
Vladimir Medic9bad0d332013-08-20 13:33:18 +00002420 MCAsmMacroArguments &A) {
Rafael Espindola768b41c2012-06-15 14:02:34 +00002421 const unsigned NParameters = M ? M->Parameters.size() : 0;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002422 bool NamedParametersFound = false;
2423 SmallVector<SMLoc, 4> FALocs;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002424
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002425 A.resize(NParameters);
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002426 FALocs.resize(NParameters);
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002427
Rafael Espindola768b41c2012-06-15 14:02:34 +00002428 // Parse two kinds of macro invocations:
2429 // - macros defined without any parameters accept an arbitrary number of them
2430 // - macros defined with parameters accept at most that many of them
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002431 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002432 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
2433 ++Parameter) {
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002434 SMLoc IDLoc = Lexer.getLoc();
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002435 MCAsmMacroParameter FA;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002436
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002437 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00002438 if (parseIdentifier(FA.Name))
2439 return Error(IDLoc, "invalid argument identifier for formal argument");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002440
Nirav Dave2364748a2016-09-16 18:30:20 +00002441 if (Lexer.isNot(AsmToken::Equal))
2442 return TokError("expected '=' after formal parameter identifier");
2443
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002444 Lex();
2445
2446 NamedParametersFound = true;
2447 }
2448
Nirav Dave2364748a2016-09-16 18:30:20 +00002449 if (NamedParametersFound && FA.Name.empty())
2450 return Error(IDLoc, "cannot mix positional and keyword arguments");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002451
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002452 bool Vararg = HasVararg && Parameter == (NParameters - 1);
2453 if (parseMacroArgument(FA.Value, Vararg))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002454 return true;
2455
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002456 unsigned PI = Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002457 if (!FA.Name.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002458 unsigned FAI = 0;
2459 for (FAI = 0; FAI < NParameters; ++FAI)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002460 if (M->Parameters[FAI].Name == FA.Name)
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002461 break;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002462
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002463 if (FAI >= NParameters) {
Nirav Davefd910412016-06-17 16:06:17 +00002464 assert(M && "expected macro to be defined");
Nirav Dave2364748a2016-09-16 18:30:20 +00002465 return Error(IDLoc, "parameter named '" + FA.Name +
2466 "' does not exist for macro '" + M->Name + "'");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002467 }
2468 PI = FAI;
2469 }
2470
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002471 if (!FA.Value.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002472 if (A.size() <= PI)
2473 A.resize(PI + 1);
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002474 A[PI] = FA.Value;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002475
2476 if (FALocs.size() <= PI)
2477 FALocs.resize(PI + 1);
2478
2479 FALocs[PI] = Lexer.getLoc();
Preston Gurd242ed3152012-09-19 20:29:04 +00002480 }
Jim Grosbach206661622012-07-30 22:44:17 +00002481
Preston Gurd242ed3152012-09-19 20:29:04 +00002482 // At the end of the statement, fill in remaining arguments that have
2483 // default values. If there aren't any, then the next argument is
2484 // required but missing
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002485 if (Lexer.is(AsmToken::EndOfStatement)) {
2486 bool Failure = false;
2487 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2488 if (A[FAI].empty()) {
2489 if (M->Parameters[FAI].Required) {
2490 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2491 "missing value for required parameter "
2492 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2493 Failure = true;
2494 }
2495
2496 if (!M->Parameters[FAI].Value.empty())
2497 A[FAI] = M->Parameters[FAI].Value;
2498 }
2499 }
2500 return Failure;
2501 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002502
2503 if (Lexer.is(AsmToken::Comma))
2504 Lex();
2505 }
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002506
2507 return TokError("too many positional arguments");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002508}
2509
Jim Grosbach4b905842013-09-20 23:08:21 +00002510const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002511 StringMap<MCAsmMacro>::iterator I = MacroMap.find(Name);
2512 return (I == MacroMap.end()) ? nullptr : &I->getValue();
Eli Bendersky38274122013-01-14 23:22:36 +00002513}
2514
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002515void AsmParser::defineMacro(StringRef Name, MCAsmMacro Macro) {
2516 MacroMap.insert(std::make_pair(Name, std::move(Macro)));
Eli Bendersky38274122013-01-14 23:22:36 +00002517}
2518
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002519void AsmParser::undefineMacro(StringRef Name) { MacroMap.erase(Name); }
Eli Bendersky38274122013-01-14 23:22:36 +00002520
Jim Grosbach4b905842013-09-20 23:08:21 +00002521bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
Davide Italiano7c9fc732016-07-27 05:51:56 +00002522 // Arbitrarily limit macro nesting depth (default matches 'as'). We can
2523 // eliminate this, although we should protect against infinite loops.
2524 unsigned MaxNestingDepth = AsmMacroMaxNestingDepth;
2525 if (ActiveMacros.size() == MaxNestingDepth) {
2526 std::ostringstream MaxNestingDepthError;
2527 MaxNestingDepthError << "macros cannot be nested more than "
2528 << MaxNestingDepth << " levels deep."
2529 << " Use -asm-macro-max-nesting-depth to increase "
2530 "this limit.";
2531 return TokError(MaxNestingDepthError.str());
2532 }
Daniel Dunbar43235712010-07-18 18:54:11 +00002533
Eli Bendersky38274122013-01-14 23:22:36 +00002534 MCAsmMacroArguments A;
Jim Grosbach4b905842013-09-20 23:08:21 +00002535 if (parseMacroArguments(M, A))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002536 return true;
Daniel Dunbar43235712010-07-18 18:54:11 +00002537
Rafael Espindola1134ab232011-06-05 02:43:45 +00002538 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2539 // to hold the macro body with substitutions.
2540 SmallString<256> Buf;
2541 StringRef Body = M->Body;
Rafael Espindola34b9c512012-06-03 23:57:14 +00002542 raw_svector_ostream OS(Buf);
Rafael Espindola1134ab232011-06-05 02:43:45 +00002543
Toma Tabacu217116e2015-04-27 10:50:29 +00002544 if (expandMacro(OS, Body, M->Parameters, A, true, getTok().getLoc()))
Rafael Espindola1134ab232011-06-05 02:43:45 +00002545 return true;
2546
Eli Bendersky38274122013-01-14 23:22:36 +00002547 // We include the .endmacro in the buffer as our cue to exit the macro
Rafael Espindola34b9c512012-06-03 23:57:14 +00002548 // instantiation.
2549 OS << ".endmacro\n";
2550
Rafael Espindola3560ff22014-08-27 20:03:13 +00002551 std::unique_ptr<MemoryBuffer> Instantiation =
2552 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola1134ab232011-06-05 02:43:45 +00002553
Daniel Dunbar43235712010-07-18 18:54:11 +00002554 // Create the macro instantiation object and add to the current macro
2555 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002556 MacroInstantiation *MI = new MacroInstantiation(
2557 NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Daniel Dunbar43235712010-07-18 18:54:11 +00002558 ActiveMacros.push_back(MI);
2559
Toma Tabacu217116e2015-04-27 10:50:29 +00002560 ++NumOfMacroInstantiations;
2561
Daniel Dunbar43235712010-07-18 18:54:11 +00002562 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00002563 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00002564 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar43235712010-07-18 18:54:11 +00002565 Lex();
2566
2567 return false;
2568}
2569
Jim Grosbach4b905842013-09-20 23:08:21 +00002570void AsmParser::handleMacroExit() {
Daniel Dunbar43235712010-07-18 18:54:11 +00002571 // Jump to the EndOfStatement we should return to, and consume it.
Jim Grosbach4b905842013-09-20 23:08:21 +00002572 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
Daniel Dunbar43235712010-07-18 18:54:11 +00002573 Lex();
2574
2575 // Pop the instantiation entry.
2576 delete ActiveMacros.back();
2577 ActiveMacros.pop_back();
2578}
2579
Jim Grosbach4b905842013-09-20 23:08:21 +00002580bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
Jim Grosbachb7b750d2012-09-13 23:11:31 +00002581 bool NoDeadStrip) {
Pete Cooper80d21cb2015-06-22 19:35:57 +00002582 MCSymbol *Sym;
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002583 const MCExpr *Value;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002584 if (MCParserUtils::parseAssignmentExpression(Name, allow_redef, *this, Sym,
2585 Value))
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002586 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002587
Pete Cooper80d21cb2015-06-22 19:35:57 +00002588 if (!Sym) {
2589 // In the case where we parse an expression starting with a '.', we will
2590 // not generate an error, nor will we create a symbol. In this case we
2591 // should just return out.
Anders Waldenborg84809572014-02-17 20:48:32 +00002592 return false;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002593 }
David Majnemer58cb80c2014-12-24 10:27:50 +00002594
Daniel Dunbarae7ac012009-06-29 23:43:14 +00002595 // Do the assignment.
Daniel Dunbarb7b20972009-08-31 08:09:09 +00002596 Out.EmitAssignment(Sym, Value);
Jim Grosbachb7b750d2012-09-13 23:11:31 +00002597 if (NoDeadStrip)
2598 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2599
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002600 return false;
2601}
2602
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002603/// parseIdentifier:
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002604/// ::= identifier
2605/// ::= string
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002606bool AsmParser::parseIdentifier(StringRef &Res) {
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002607 // The assembler has relaxed rules for accepting identifiers, in particular we
Hans Wennborgce69d772013-10-18 20:46:28 +00002608 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2609 // separate tokens. At this level, we have already lexed so we cannot (currently)
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002610 // handle this as a context dependent token, instead we detect adjacent tokens
2611 // and return the combined identifier.
Hans Wennborgce69d772013-10-18 20:46:28 +00002612 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2613 SMLoc PrefixLoc = getLexer().getLoc();
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002614
Hans Wennborgce69d772013-10-18 20:46:28 +00002615 // Consume the prefix character, and check for a following identifier.
Nirav Daved0463322016-10-12 13:58:07 +00002616
2617 AsmToken Buf[1];
2618 Lexer.peekTokens(Buf, false);
2619
2620 if (Buf[0].isNot(AsmToken::Identifier))
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002621 return true;
2622
Hans Wennborgce69d772013-10-18 20:46:28 +00002623 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
Nirav Daved0463322016-10-12 13:58:07 +00002624 if (PrefixLoc.getPointer() + 1 != Buf[0].getLoc().getPointer())
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002625 return true;
2626
Nirav Daved0463322016-10-12 13:58:07 +00002627 // eat $ or @
2628 Lexer.Lex(); // Lexer's Lex guarantees consecutive token.
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002629 // Construct the joined identifier and consume the token.
Jim Grosbach4b905842013-09-20 23:08:21 +00002630 Res =
Hans Wennborgce69d772013-10-18 20:46:28 +00002631 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
Nirav Davefd910412016-06-17 16:06:17 +00002632 Lex(); // Parser Lex to maintain invariants.
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002633 return false;
2634 }
2635
Jim Grosbach4b905842013-09-20 23:08:21 +00002636 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002637 return true;
2638
Sean Callanan936b0d32010-01-19 21:44:56 +00002639 Res = getTok().getIdentifier();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002640
Sean Callanan686ed8d2010-01-19 20:22:31 +00002641 Lex(); // Consume the identifier token.
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002642
2643 return false;
2644}
2645
Jim Grosbach4b905842013-09-20 23:08:21 +00002646/// parseDirectiveSet:
Nico Weber4ada0d92011-01-28 03:04:41 +00002647/// ::= .equ identifier ',' expression
2648/// ::= .equiv identifier ',' expression
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002649/// ::= .set identifier ',' expression
Jim Grosbach4b905842013-09-20 23:08:21 +00002650bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002651 StringRef Name;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002652 if (check(parseIdentifier(Name), "expected identifier") ||
2653 parseToken(AsmToken::Comma) || parseAssignment(Name, allow_redef, true))
2654 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
2655 return false;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002656}
2657
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002658bool AsmParser::parseEscapedString(std::string &Data) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00002659 if (check(getTok().isNot(AsmToken::String), "expected string"))
2660 return true;
Daniel Dunbaref668c12009-08-14 18:19:52 +00002661
2662 Data = "";
Sean Callanan936b0d32010-01-19 21:44:56 +00002663 StringRef Str = getTok().getStringContents();
Daniel Dunbaref668c12009-08-14 18:19:52 +00002664 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2665 if (Str[i] != '\\') {
2666 Data += Str[i];
2667 continue;
2668 }
2669
2670 // Recognize escaped characters. Note that this escape semantics currently
2671 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2672 ++i;
2673 if (i == e)
2674 return TokError("unexpected backslash at end of string");
2675
2676 // Recognize octal sequences.
Jim Grosbach4b905842013-09-20 23:08:21 +00002677 if ((unsigned)(Str[i] - '0') <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002678 // Consume up to three octal characters.
2679 unsigned Value = Str[i] - '0';
2680
Jim Grosbach4b905842013-09-20 23:08:21 +00002681 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002682 ++i;
2683 Value = Value * 8 + (Str[i] - '0');
2684
Jim Grosbach4b905842013-09-20 23:08:21 +00002685 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002686 ++i;
2687 Value = Value * 8 + (Str[i] - '0');
2688 }
2689 }
2690
2691 if (Value > 255)
2692 return TokError("invalid octal escape sequence (out of range)");
2693
Jim Grosbach4b905842013-09-20 23:08:21 +00002694 Data += (unsigned char)Value;
Daniel Dunbaref668c12009-08-14 18:19:52 +00002695 continue;
2696 }
2697
2698 // Otherwise recognize individual escapes.
2699 switch (Str[i]) {
2700 default:
2701 // Just reject invalid escape sequences for now.
2702 return TokError("invalid escape sequence (unrecognized character)");
2703
2704 case 'b': Data += '\b'; break;
2705 case 'f': Data += '\f'; break;
2706 case 'n': Data += '\n'; break;
2707 case 'r': Data += '\r'; break;
2708 case 't': Data += '\t'; break;
2709 case '"': Data += '"'; break;
2710 case '\\': Data += '\\'; break;
2711 }
2712 }
2713
Nirav Davea645433c2016-07-18 15:24:03 +00002714 Lex();
Daniel Dunbaref668c12009-08-14 18:19:52 +00002715 return false;
2716}
2717
Jim Grosbach4b905842013-09-20 23:08:21 +00002718/// parseDirectiveAscii:
Rafael Espindola63760ba2010-10-28 20:02:27 +00002719/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002720bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00002721 auto parseOp = [&]() -> bool {
2722 std::string Data;
2723 if (checkForValidSection() || parseEscapedString(Data))
Nirav Davef43cc9f2016-10-10 15:24:54 +00002724 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002725 getStreamer().EmitBytes(Data);
2726 if (ZeroTerminated)
2727 getStreamer().EmitBytes(StringRef("\0", 1));
2728 return false;
2729 };
Daniel Dunbare5444a82010-09-09 22:42:59 +00002730
Nirav Dave1a9044b2016-10-24 14:35:29 +00002731 if (parseMany(parseOp))
2732 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbara10e5192009-06-24 23:30:00 +00002733 return false;
2734}
2735
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002736/// parseDirectiveReloc
2737/// ::= .reloc expression , identifier [ , expression ]
2738bool AsmParser::parseDirectiveReloc(SMLoc DirectiveLoc) {
2739 const MCExpr *Offset;
2740 const MCExpr *Expr = nullptr;
2741
2742 SMLoc OffsetLoc = Lexer.getTok().getLoc();
Nirav Dave1a9044b2016-10-24 14:35:29 +00002743 int64_t OffsetValue;
2744 // We can only deal with constant expressions at the moment.
2745
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002746 if (parseExpression(Offset))
2747 return true;
2748
Nirav Davea645433c2016-07-18 15:24:03 +00002749 if (check(!Offset->evaluateAsAbsolute(OffsetValue), OffsetLoc,
2750 "expression is not a constant value") ||
2751 check(OffsetValue < 0, OffsetLoc, "expression is negative") ||
2752 parseToken(AsmToken::Comma, "expected comma") ||
2753 check(getTok().isNot(AsmToken::Identifier), "expected relocation name"))
2754 return true;
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002755
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002756 SMLoc NameLoc = Lexer.getTok().getLoc();
2757 StringRef Name = Lexer.getTok().getIdentifier();
Nirav Davefd910412016-06-17 16:06:17 +00002758 Lex();
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002759
2760 if (Lexer.is(AsmToken::Comma)) {
Nirav Davefd910412016-06-17 16:06:17 +00002761 Lex();
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002762 SMLoc ExprLoc = Lexer.getLoc();
2763 if (parseExpression(Expr))
2764 return true;
2765
2766 MCValue Value;
2767 if (!Expr->evaluateAsRelocatable(Value, nullptr, nullptr))
2768 return Error(ExprLoc, "expression must be relocatable");
2769 }
2770
Nirav Davea645433c2016-07-18 15:24:03 +00002771 if (parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00002772 "unexpected token in .reloc directive"))
2773 return true;
2774
2775 if (getStreamer().EmitRelocDirective(*Offset, Name, Expr, DirectiveLoc))
2776 return Error(NameLoc, "unknown relocation name");
2777
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002778 return false;
2779}
2780
Jim Grosbach4b905842013-09-20 23:08:21 +00002781/// parseDirectiveValue
Daniel Dunbara10e5192009-06-24 23:30:00 +00002782/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00002783bool AsmParser::parseDirectiveValue(StringRef IDVal, unsigned Size) {
2784 auto parseOp = [&]() -> bool {
2785 const MCExpr *Value;
2786 SMLoc ExprLoc = getLexer().getLoc();
2787 if (checkForValidSection() || parseExpression(Value))
Nirav Davef43cc9f2016-10-10 15:24:54 +00002788 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002789 // Special case constant expressions to match code generator.
2790 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2791 assert(Size <= 8 && "Invalid size");
2792 uint64_t IntValue = MCE->getValue();
2793 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2794 return Error(ExprLoc, "out of range literal value");
2795 getStreamer().EmitIntValue(IntValue, Size);
2796 } else
2797 getStreamer().EmitValue(Value, Size, ExprLoc);
2798 return false;
2799 };
Daniel Dunbare5444a82010-09-09 22:42:59 +00002800
Nirav Dave1a9044b2016-10-24 14:35:29 +00002801 if (parseMany(parseOp))
2802 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbara10e5192009-06-24 23:30:00 +00002803 return false;
2804}
2805
David Woodhoused6de0d92014-02-01 16:20:59 +00002806/// ParseDirectiveOctaValue
2807/// ::= .octa [ hexconstant (, hexconstant)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00002808
2809bool AsmParser::parseDirectiveOctaValue(StringRef IDVal) {
2810 auto parseOp = [&]() -> bool {
Nirav Davef43cc9f2016-10-10 15:24:54 +00002811 if (checkForValidSection())
2812 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002813 if (getTok().isNot(AsmToken::Integer) && getTok().isNot(AsmToken::BigNum))
2814 return TokError("unknown token in expression");
2815 SMLoc ExprLoc = getTok().getLoc();
2816 APInt IntValue = getTok().getAPIntVal();
2817 uint64_t hi, lo;
2818 Lex();
2819 if (!IntValue.isIntN(128))
2820 return Error(ExprLoc, "out of range literal value");
2821 if (!IntValue.isIntN(64)) {
2822 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
2823 lo = IntValue.getLoBits(64).getZExtValue();
2824 } else {
2825 hi = 0;
2826 lo = IntValue.getZExtValue();
David Woodhoused6de0d92014-02-01 16:20:59 +00002827 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00002828 if (MAI.isLittleEndian()) {
2829 getStreamer().EmitIntValue(lo, 8);
2830 getStreamer().EmitIntValue(hi, 8);
2831 } else {
2832 getStreamer().EmitIntValue(hi, 8);
2833 getStreamer().EmitIntValue(lo, 8);
2834 }
2835 return false;
2836 };
David Woodhoused6de0d92014-02-01 16:20:59 +00002837
Nirav Dave1a9044b2016-10-24 14:35:29 +00002838 if (parseMany(parseOp))
2839 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
David Woodhoused6de0d92014-02-01 16:20:59 +00002840 return false;
2841}
2842
Petr Hosek4cb08ce2016-09-23 19:25:15 +00002843bool AsmParser::parseRealValue(const fltSemantics &Semantics, APInt &Res) {
2844 // We don't truly support arithmetic on floating point expressions, so we
2845 // have to manually parse unary prefixes.
2846 bool IsNeg = false;
2847 if (getLexer().is(AsmToken::Minus)) {
2848 Lexer.Lex();
2849 IsNeg = true;
2850 } else if (getLexer().is(AsmToken::Plus))
2851 Lexer.Lex();
2852
2853 if (Lexer.is(AsmToken::Error))
2854 return TokError(Lexer.getErr());
2855 if (Lexer.isNot(AsmToken::Integer) && Lexer.isNot(AsmToken::Real) &&
2856 Lexer.isNot(AsmToken::Identifier))
2857 return TokError("unexpected token in directive");
2858
2859 // Convert to an APFloat.
2860 APFloat Value(Semantics);
2861 StringRef IDVal = getTok().getString();
2862 if (getLexer().is(AsmToken::Identifier)) {
2863 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2864 Value = APFloat::getInf(Semantics);
2865 else if (!IDVal.compare_lower("nan"))
2866 Value = APFloat::getNaN(Semantics, false, ~0);
2867 else
2868 return TokError("invalid floating point literal");
2869 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2870 APFloat::opInvalidOp)
2871 return TokError("invalid floating point literal");
2872 if (IsNeg)
2873 Value.changeSign();
2874
2875 // Consume the numeric token.
2876 Lex();
2877
2878 Res = Value.bitcastToAPInt();
2879
2880 return false;
2881}
2882
Jim Grosbach4b905842013-09-20 23:08:21 +00002883/// parseDirectiveRealValue
Daniel Dunbar2af16532010-09-24 01:59:56 +00002884/// ::= (.single | .double) [ expression (, expression)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00002885bool AsmParser::parseDirectiveRealValue(StringRef IDVal,
2886 const fltSemantics &Semantics) {
2887 auto parseOp = [&]() -> bool {
2888 APInt AsInt;
2889 if (checkForValidSection() || parseRealValue(Semantics, AsInt))
Nirav Davef43cc9f2016-10-10 15:24:54 +00002890 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002891 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2892 AsInt.getBitWidth() / 8);
2893 return false;
2894 };
Daniel Dunbar2af16532010-09-24 01:59:56 +00002895
Nirav Dave1a9044b2016-10-24 14:35:29 +00002896 if (parseMany(parseOp))
2897 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbar2af16532010-09-24 01:59:56 +00002898 return false;
2899}
2900
Jim Grosbach4b905842013-09-20 23:08:21 +00002901/// parseDirectiveZero
Rafael Espindola922e3f42010-09-16 15:03:59 +00002902/// ::= .zero expression
Jim Grosbach4b905842013-09-20 23:08:21 +00002903bool AsmParser::parseDirectiveZero() {
Petr Hosek67a94a72016-05-28 05:57:48 +00002904 SMLoc NumBytesLoc = Lexer.getLoc();
2905 const MCExpr *NumBytes;
Nirav Davef43cc9f2016-10-10 15:24:54 +00002906 if (checkForValidSection() || parseExpression(NumBytes))
Rafael Espindola922e3f42010-09-16 15:03:59 +00002907 return true;
2908
Rafael Espindolab91bac62010-10-05 19:42:57 +00002909 int64_t Val = 0;
2910 if (getLexer().is(AsmToken::Comma)) {
2911 Lex();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002912 if (parseAbsoluteExpression(Val))
Rafael Espindolab91bac62010-10-05 19:42:57 +00002913 return true;
2914 }
2915
Nirav Davea645433c2016-07-18 15:24:03 +00002916 if (parseToken(AsmToken::EndOfStatement,
2917 "unexpected token in '.zero' directive"))
2918 return true;
Petr Hosek67a94a72016-05-28 05:57:48 +00002919 getStreamer().emitFill(*NumBytes, Val, NumBytesLoc);
Rafael Espindola922e3f42010-09-16 15:03:59 +00002920
2921 return false;
2922}
2923
Jim Grosbach4b905842013-09-20 23:08:21 +00002924/// parseDirectiveFill
Roman Divackye33098f2013-09-24 17:44:41 +00002925/// ::= .fill expression [ , expression [ , expression ] ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002926bool AsmParser::parseDirectiveFill() {
Petr Hosek67a94a72016-05-28 05:57:48 +00002927 SMLoc NumValuesLoc = Lexer.getLoc();
2928 const MCExpr *NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00002929 if (checkForValidSection() || parseExpression(NumValues))
Daniel Dunbara10e5192009-06-24 23:30:00 +00002930 return true;
2931
Roman Divackye33098f2013-09-24 17:44:41 +00002932 int64_t FillSize = 1;
2933 int64_t FillExpr = 0;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002934
David Majnemer522d3db2014-02-01 07:19:38 +00002935 SMLoc SizeLoc, ExprLoc;
Daniel Dunbara10e5192009-06-24 23:30:00 +00002936
Nirav Dave1a9044b2016-10-24 14:35:29 +00002937 if (parseOptionalToken(AsmToken::Comma)) {
2938 SizeLoc = getTok().getLoc();
2939 if (parseAbsoluteExpression(FillSize))
Roman Divackye33098f2013-09-24 17:44:41 +00002940 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002941 if (parseOptionalToken(AsmToken::Comma)) {
2942 ExprLoc = getTok().getLoc();
2943 if (parseAbsoluteExpression(FillExpr))
Roman Divackye33098f2013-09-24 17:44:41 +00002944 return true;
Roman Divackye33098f2013-09-24 17:44:41 +00002945 }
2946 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00002947 if (parseToken(AsmToken::EndOfStatement,
2948 "unexpected token in '.fill' directive"))
2949 return true;
Daniel Dunbara10e5192009-06-24 23:30:00 +00002950
David Majnemer522d3db2014-02-01 07:19:38 +00002951 if (FillSize < 0) {
2952 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
Petr Hosek6abd38b2016-05-28 08:20:08 +00002953 return false;
David Majnemer522d3db2014-02-01 07:19:38 +00002954 }
2955 if (FillSize > 8) {
2956 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
2957 FillSize = 8;
2958 }
Daniel Dunbara10e5192009-06-24 23:30:00 +00002959
David Majnemer522d3db2014-02-01 07:19:38 +00002960 if (!isUInt<32>(FillExpr) && FillSize > 4)
2961 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
2962
Petr Hosek67a94a72016-05-28 05:57:48 +00002963 getStreamer().emitFill(*NumValues, FillSize, FillExpr, NumValuesLoc);
Daniel Dunbara10e5192009-06-24 23:30:00 +00002964
2965 return false;
2966}
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002967
Jim Grosbach4b905842013-09-20 23:08:21 +00002968/// parseDirectiveOrg
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002969/// ::= .org expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002970bool AsmParser::parseDirectiveOrg() {
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002971 const MCExpr *Offset;
Oliver Stannard268f42f2016-12-14 10:43:58 +00002972 SMLoc OffsetLoc = Lexer.getLoc();
Nirav Davef43cc9f2016-10-10 15:24:54 +00002973 if (checkForValidSection() || parseExpression(Offset))
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002974 return true;
2975
2976 // Parse optional fill expression.
2977 int64_t FillExpr = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002978 if (parseOptionalToken(AsmToken::Comma))
2979 if (parseAbsoluteExpression(FillExpr))
2980 return addErrorSuffix(" in '.org' directive");
2981 if (parseToken(AsmToken::EndOfStatement))
2982 return addErrorSuffix(" in '.org' directive");
Nirav Davea645433c2016-07-18 15:24:03 +00002983
Oliver Stannard268f42f2016-12-14 10:43:58 +00002984 getStreamer().emitValueToOffset(Offset, FillExpr, OffsetLoc);
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002985 return false;
2986}
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002987
Jim Grosbach4b905842013-09-20 23:08:21 +00002988/// parseDirectiveAlign
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002989/// ::= {.align, ...} expression [ , expression [ , expression ]]
Jim Grosbach4b905842013-09-20 23:08:21 +00002990bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002991 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002992 int64_t Alignment;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002993 SMLoc MaxBytesLoc;
2994 bool HasFillExpr = false;
2995 int64_t FillExpr = 0;
2996 int64_t MaxBytesToFill = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002997
2998 auto parseAlign = [&]() -> bool {
2999 if (checkForValidSection() || parseAbsoluteExpression(Alignment))
Nirav Davea645433c2016-07-18 15:24:03 +00003000 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003001 if (parseOptionalToken(AsmToken::Comma)) {
3002 // The fill expression can be omitted while specifying a maximum number of
3003 // alignment bytes, e.g:
3004 // .align 3,,4
3005 if (getTok().isNot(AsmToken::Comma)) {
3006 HasFillExpr = true;
3007 if (parseAbsoluteExpression(FillExpr))
3008 return true;
3009 }
3010 if (parseOptionalToken(AsmToken::Comma))
3011 if (parseTokenLoc(MaxBytesLoc) ||
3012 parseAbsoluteExpression(MaxBytesToFill))
3013 return true;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003014 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003015 return parseToken(AsmToken::EndOfStatement);
3016 };
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003017
Nirav Dave1a9044b2016-10-24 14:35:29 +00003018 if (parseAlign())
3019 return addErrorSuffix(" in directive");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003020
Nirav Dave2364748a2016-09-16 18:30:20 +00003021 // Always emit an alignment here even if we thrown an error.
3022 bool ReturnVal = false;
3023
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003024 // Compute alignment in bytes.
3025 if (IsPow2) {
3026 // FIXME: Diagnose overflow.
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003027 if (Alignment >= 32) {
Nirav Dave2364748a2016-09-16 18:30:20 +00003028 ReturnVal |= Error(AlignmentLoc, "invalid alignment value");
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003029 Alignment = 31;
3030 }
3031
Benjamin Kramer63951ad2009-09-06 09:35:10 +00003032 Alignment = 1ULL << Alignment;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00003033 } else {
Davide Italianocb2da712015-09-08 18:59:47 +00003034 // Reject alignments that aren't either a power of two or zero,
3035 // for gas compatibility. Alignment of zero is silently rounded
3036 // up to one.
3037 if (Alignment == 0)
3038 Alignment = 1;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00003039 if (!isPowerOf2_64(Alignment))
Nirav Dave2364748a2016-09-16 18:30:20 +00003040 ReturnVal |= Error(AlignmentLoc, "alignment must be a power of 2");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003041 }
3042
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003043 // Diagnose non-sensical max bytes to align.
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003044 if (MaxBytesLoc.isValid()) {
3045 if (MaxBytesToFill < 1) {
Nirav Dave2364748a2016-09-16 18:30:20 +00003046 ReturnVal |= Error(MaxBytesLoc,
3047 "alignment directive can never be satisfied in this "
Jim Grosbach4b905842013-09-20 23:08:21 +00003048 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar4abcccb2009-08-21 23:01:53 +00003049 MaxBytesToFill = 0;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003050 }
3051
3052 if (MaxBytesToFill >= Alignment) {
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +00003053 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
Jim Grosbach4b905842013-09-20 23:08:21 +00003054 "has no effect");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003055 MaxBytesToFill = 0;
3056 }
3057 }
3058
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003059 // Check whether we should use optimal code alignment for this .align
3060 // directive.
Eric Christopher445c9522016-10-14 05:47:37 +00003061 const MCSection *Section = getStreamer().getCurrentSectionOnly();
Saleem Abdulrasool7f2f9f42014-03-21 05:13:23 +00003062 assert(Section && "must have section to emit alignment");
3063 bool UseCodeAlign = Section->UseCodeAlign();
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003064 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
3065 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003066 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003067 } else {
Kevin Enderby7f993022010-02-25 18:46:04 +00003068 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnerc2b36752010-07-15 21:19:31 +00003069 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
3070 MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003071 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003072
Nirav Dave2364748a2016-09-16 18:30:20 +00003073 return ReturnVal;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003074}
3075
Jim Grosbach4b905842013-09-20 23:08:21 +00003076/// parseDirectiveFile
Eli Bendersky17233942013-01-15 22:59:42 +00003077/// ::= .file [number] filename
3078/// ::= .file number directory filename
Jim Grosbach4b905842013-09-20 23:08:21 +00003079bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003080 // FIXME: I'm not sure what this is.
3081 int64_t FileNumber = -1;
3082 SMLoc FileNumberLoc = getLexer().getLoc();
3083 if (getLexer().is(AsmToken::Integer)) {
3084 FileNumber = getTok().getIntVal();
3085 Lex();
3086
3087 if (FileNumber < 1)
3088 return TokError("file number less than one");
3089 }
3090
Nirav Davea645433c2016-07-18 15:24:03 +00003091 std::string Path = getTok().getString();
Eli Bendersky17233942013-01-15 22:59:42 +00003092
3093 // Usually the directory and filename together, otherwise just the directory.
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003094 // Allow the strings to have escaped octal character sequence.
Nirav Davea645433c2016-07-18 15:24:03 +00003095 if (check(getTok().isNot(AsmToken::String),
3096 "unexpected token in '.file' directive") ||
3097 parseEscapedString(Path))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003098 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003099
3100 StringRef Directory;
3101 StringRef Filename;
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003102 std::string FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00003103 if (getLexer().is(AsmToken::String)) {
Nirav Davea645433c2016-07-18 15:24:03 +00003104 if (check(FileNumber == -1,
3105 "explicit path specified, but no file number") ||
3106 parseEscapedString(FilenameData))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003107 return true;
3108 Filename = FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00003109 Directory = Path;
Eli Bendersky17233942013-01-15 22:59:42 +00003110 } else {
3111 Filename = Path;
3112 }
3113
Nirav Davea645433c2016-07-18 15:24:03 +00003114 if (parseToken(AsmToken::EndOfStatement,
3115 "unexpected token in '.file' directive"))
3116 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003117
3118 if (FileNumber == -1)
3119 getStreamer().EmitFileDirective(Filename);
3120 else {
David Blaikie22748082016-05-26 00:22:26 +00003121 // If there is -g option as well as debug info from directive file,
3122 // we turn off -g option, directly use the existing debug info instead.
David Blaikiedc3f01e2015-03-09 01:57:13 +00003123 if (getContext().getGenDwarfForAssembly())
David Blaikie22748082016-05-26 00:22:26 +00003124 getContext().setGenDwarfForAssembly(false);
3125 else if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename) ==
David Blaikiec714ef42014-03-17 01:52:11 +00003126 0)
Nirav Dave2364748a2016-09-16 18:30:20 +00003127 return Error(FileNumberLoc, "file number already allocated");
Eli Bendersky17233942013-01-15 22:59:42 +00003128 }
3129
3130 return false;
3131}
3132
Jim Grosbach4b905842013-09-20 23:08:21 +00003133/// parseDirectiveLine
Eli Bendersky17233942013-01-15 22:59:42 +00003134/// ::= .line [number]
Jim Grosbach4b905842013-09-20 23:08:21 +00003135bool AsmParser::parseDirectiveLine() {
Nirav Davea645433c2016-07-18 15:24:03 +00003136 int64_t LineNumber;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003137 if (getLexer().is(AsmToken::Integer)) {
Nirav Davea645433c2016-07-18 15:24:03 +00003138 if (parseIntToken(LineNumber, "unexpected token in '.line' directive"))
3139 return true;
Jim Grosbach4b905842013-09-20 23:08:21 +00003140 (void)LineNumber;
Eli Bendersky17233942013-01-15 22:59:42 +00003141 // FIXME: Do something with the .line.
3142 }
Nirav Davea645433c2016-07-18 15:24:03 +00003143 if (parseToken(AsmToken::EndOfStatement,
3144 "unexpected token in '.line' directive"))
3145 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003146
3147 return false;
3148}
3149
Jim Grosbach4b905842013-09-20 23:08:21 +00003150/// parseDirectiveLoc
Eli Bendersky17233942013-01-15 22:59:42 +00003151/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
3152/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
3153/// The first number is a file number, must have been previously assigned with
3154/// a .file directive, the second number is the line number and optionally the
3155/// third number is a column position (zero if not specified). The remaining
3156/// optional items are .loc sub-directives.
Jim Grosbach4b905842013-09-20 23:08:21 +00003157bool AsmParser::parseDirectiveLoc() {
Nirav Davea645433c2016-07-18 15:24:03 +00003158 int64_t FileNumber = 0, LineNumber = 0;
3159 SMLoc Loc = getTok().getLoc();
3160 if (parseIntToken(FileNumber, "unexpected token in '.loc' directive") ||
3161 check(FileNumber < 1, Loc,
3162 "file number less than one in '.loc' directive") ||
3163 check(!getContext().isValidDwarfFileNumber(FileNumber), Loc,
3164 "unassigned file number in '.loc' directive"))
3165 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003166
Nirav Davea645433c2016-07-18 15:24:03 +00003167 // optional
Eli Bendersky17233942013-01-15 22:59:42 +00003168 if (getLexer().is(AsmToken::Integer)) {
3169 LineNumber = getTok().getIntVal();
Adrian Prantl6ac40032013-09-26 23:37:11 +00003170 if (LineNumber < 0)
3171 return TokError("line number less than zero in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003172 Lex();
3173 }
3174
3175 int64_t ColumnPos = 0;
3176 if (getLexer().is(AsmToken::Integer)) {
3177 ColumnPos = getTok().getIntVal();
3178 if (ColumnPos < 0)
3179 return TokError("column position less than zero in '.loc' directive");
3180 Lex();
3181 }
3182
3183 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
3184 unsigned Isa = 0;
3185 int64_t Discriminator = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003186
Nirav Dave1a9044b2016-10-24 14:35:29 +00003187 auto parseLocOp = [&]() -> bool {
3188 StringRef Name;
3189 SMLoc Loc = getTok().getLoc();
3190 if (parseIdentifier(Name))
3191 return TokError("unexpected token in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003192
Nirav Dave1a9044b2016-10-24 14:35:29 +00003193 if (Name == "basic_block")
3194 Flags |= DWARF2_FLAG_BASIC_BLOCK;
3195 else if (Name == "prologue_end")
3196 Flags |= DWARF2_FLAG_PROLOGUE_END;
3197 else if (Name == "epilogue_begin")
3198 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
3199 else if (Name == "is_stmt") {
3200 Loc = getTok().getLoc();
3201 const MCExpr *Value;
3202 if (parseExpression(Value))
3203 return true;
3204 // The expression must be the constant 0 or 1.
3205 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3206 int Value = MCE->getValue();
3207 if (Value == 0)
3208 Flags &= ~DWARF2_FLAG_IS_STMT;
3209 else if (Value == 1)
3210 Flags |= DWARF2_FLAG_IS_STMT;
3211 else
3212 return Error(Loc, "is_stmt value not 0 or 1");
Craig Topperf15655b2013-04-22 04:22:40 +00003213 } else {
Nirav Dave1a9044b2016-10-24 14:35:29 +00003214 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
Eli Bendersky17233942013-01-15 22:59:42 +00003215 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003216 } else if (Name == "isa") {
3217 Loc = getTok().getLoc();
3218 const MCExpr *Value;
3219 if (parseExpression(Value))
3220 return true;
3221 // The expression must be a constant greater or equal to 0.
3222 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3223 int Value = MCE->getValue();
3224 if (Value < 0)
3225 return Error(Loc, "isa number less than zero");
3226 Isa = Value;
3227 } else {
3228 return Error(Loc, "isa number not a constant value");
3229 }
3230 } else if (Name == "discriminator") {
3231 if (parseAbsoluteExpression(Discriminator))
3232 return true;
3233 } else {
3234 return Error(Loc, "unknown sub-directive in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003235 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003236 return false;
3237 };
3238
Nirav Davee2369aa2016-10-26 17:28:58 +00003239 if (parseMany(parseLocOp, false /*hasComma*/))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003240 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003241
3242 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
3243 Isa, Discriminator, StringRef());
3244
3245 return false;
3246}
3247
Jim Grosbach4b905842013-09-20 23:08:21 +00003248/// parseDirectiveStabs
Eli Bendersky17233942013-01-15 22:59:42 +00003249/// ::= .stabs string, number, number, number
Jim Grosbach4b905842013-09-20 23:08:21 +00003250bool AsmParser::parseDirectiveStabs() {
Eli Bendersky17233942013-01-15 22:59:42 +00003251 return TokError("unsupported directive '.stabs'");
3252}
3253
Reid Kleckner2214ed82016-01-29 00:49:42 +00003254/// parseDirectiveCVFile
3255/// ::= .cv_file number filename
3256bool AsmParser::parseDirectiveCVFile() {
Nirav Davea645433c2016-07-18 15:24:03 +00003257 SMLoc FileNumberLoc = getTok().getLoc();
3258 int64_t FileNumber;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003259 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00003260
3261 if (parseIntToken(FileNumber,
3262 "expected file number in '.cv_file' directive") ||
3263 check(FileNumber < 1, FileNumberLoc, "file number less than one") ||
3264 check(getTok().isNot(AsmToken::String),
3265 "unexpected token in '.cv_file' directive") ||
3266 // Usually directory and filename are together, otherwise just
3267 // directory. Allow the strings to have escaped octal character sequence.
3268 parseEscapedString(Filename) ||
3269 parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00003270 "unexpected token in '.cv_file' directive"))
Reid Klecknera5b1eef2016-08-26 17:58:37 +00003271 return true;
Nirav Dave1ab71992016-07-18 19:35:21 +00003272
Reid Klecknera5b1eef2016-08-26 17:58:37 +00003273 if (!getStreamer().EmitCVFileDirective(FileNumber, Filename))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003274 return Error(FileNumberLoc, "file number already allocated");
Reid Kleckner2214ed82016-01-29 00:49:42 +00003275
3276 return false;
3277}
3278
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003279bool AsmParser::parseCVFunctionId(int64_t &FunctionId,
3280 StringRef DirectiveName) {
3281 SMLoc Loc;
3282 return parseTokenLoc(Loc) ||
3283 parseIntToken(FunctionId, "expected function id in '" + DirectiveName +
3284 "' directive") ||
3285 check(FunctionId < 0 || FunctionId >= UINT_MAX, Loc,
3286 "expected function id within range [0, UINT_MAX)");
3287}
3288
3289bool AsmParser::parseCVFileId(int64_t &FileNumber, StringRef DirectiveName) {
3290 SMLoc Loc;
3291 return parseTokenLoc(Loc) ||
3292 parseIntToken(FileNumber, "expected integer in '" + DirectiveName +
3293 "' directive") ||
3294 check(FileNumber < 1, Loc, "file number less than one in '" +
3295 DirectiveName + "' directive") ||
3296 check(!getCVContext().isValidFileNumber(FileNumber), Loc,
3297 "unassigned file number in '" + DirectiveName + "' directive");
3298}
3299
3300/// parseDirectiveCVFuncId
3301/// ::= .cv_func_id FunctionId
3302///
3303/// Introduces a function ID that can be used with .cv_loc.
3304bool AsmParser::parseDirectiveCVFuncId() {
3305 SMLoc FunctionIdLoc = getTok().getLoc();
3306 int64_t FunctionId;
3307
3308 if (parseCVFunctionId(FunctionId, ".cv_func_id") ||
3309 parseToken(AsmToken::EndOfStatement,
3310 "unexpected token in '.cv_func_id' directive"))
3311 return true;
3312
3313 if (!getStreamer().EmitCVFuncIdDirective(FunctionId))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003314 return Error(FunctionIdLoc, "function id already allocated");
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003315
3316 return false;
3317}
3318
3319/// parseDirectiveCVInlineSiteId
3320/// ::= .cv_inline_site_id FunctionId
3321/// "within" IAFunc
3322/// "inlined_at" IAFile IALine [IACol]
3323///
3324/// Introduces a function ID that can be used with .cv_loc. Includes "inlined
3325/// at" source location information for use in the line table of the caller,
3326/// whether the caller is a real function or another inlined call site.
3327bool AsmParser::parseDirectiveCVInlineSiteId() {
3328 SMLoc FunctionIdLoc = getTok().getLoc();
3329 int64_t FunctionId;
3330 int64_t IAFunc;
3331 int64_t IAFile;
3332 int64_t IALine;
3333 int64_t IACol = 0;
3334
3335 // FunctionId
3336 if (parseCVFunctionId(FunctionId, ".cv_inline_site_id"))
3337 return true;
3338
3339 // "within"
3340 if (check((getLexer().isNot(AsmToken::Identifier) ||
3341 getTok().getIdentifier() != "within"),
3342 "expected 'within' identifier in '.cv_inline_site_id' directive"))
3343 return true;
3344 Lex();
3345
3346 // IAFunc
3347 if (parseCVFunctionId(IAFunc, ".cv_inline_site_id"))
3348 return true;
3349
3350 // "inlined_at"
3351 if (check((getLexer().isNot(AsmToken::Identifier) ||
3352 getTok().getIdentifier() != "inlined_at"),
3353 "expected 'inlined_at' identifier in '.cv_inline_site_id' "
3354 "directive") )
3355 return true;
3356 Lex();
3357
3358 // IAFile IALine
3359 if (parseCVFileId(IAFile, ".cv_inline_site_id") ||
3360 parseIntToken(IALine, "expected line number after 'inlined_at'"))
3361 return true;
3362
3363 // [IACol]
3364 if (getLexer().is(AsmToken::Integer)) {
3365 IACol = getTok().getIntVal();
3366 Lex();
3367 }
3368
3369 if (parseToken(AsmToken::EndOfStatement,
3370 "unexpected token in '.cv_inline_site_id' directive"))
3371 return true;
3372
3373 if (!getStreamer().EmitCVInlineSiteIdDirective(FunctionId, IAFunc, IAFile,
3374 IALine, IACol, FunctionIdLoc))
Nirav Dave2364748a2016-09-16 18:30:20 +00003375 return Error(FunctionIdLoc, "function id already allocated");
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003376
3377 return false;
3378}
3379
Reid Kleckner2214ed82016-01-29 00:49:42 +00003380/// parseDirectiveCVLoc
3381/// ::= .cv_loc FunctionId FileNumber [LineNumber] [ColumnPos] [prologue_end]
3382/// [is_stmt VALUE]
3383/// The first number is a file number, must have been previously assigned with
3384/// a .file directive, the second number is the line number and optionally the
3385/// third number is a column position (zero if not specified). The remaining
3386/// optional items are .loc sub-directives.
3387bool AsmParser::parseDirectiveCVLoc() {
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003388 SMLoc DirectiveLoc = getTok().getLoc();
Nirav Davea645433c2016-07-18 15:24:03 +00003389 SMLoc Loc;
3390 int64_t FunctionId, FileNumber;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003391 if (parseCVFunctionId(FunctionId, ".cv_loc") ||
3392 parseCVFileId(FileNumber, ".cv_loc"))
Nirav Davea645433c2016-07-18 15:24:03 +00003393 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003394
3395 int64_t LineNumber = 0;
3396 if (getLexer().is(AsmToken::Integer)) {
3397 LineNumber = getTok().getIntVal();
3398 if (LineNumber < 0)
3399 return TokError("line number less than zero in '.cv_loc' directive");
3400 Lex();
3401 }
3402
3403 int64_t ColumnPos = 0;
3404 if (getLexer().is(AsmToken::Integer)) {
3405 ColumnPos = getTok().getIntVal();
3406 if (ColumnPos < 0)
3407 return TokError("column position less than zero in '.cv_loc' directive");
3408 Lex();
3409 }
3410
3411 bool PrologueEnd = false;
3412 uint64_t IsStmt = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003413
3414 auto parseOp = [&]() -> bool {
Reid Kleckner2214ed82016-01-29 00:49:42 +00003415 StringRef Name;
3416 SMLoc Loc = getTok().getLoc();
3417 if (parseIdentifier(Name))
3418 return TokError("unexpected token in '.cv_loc' directive");
Reid Kleckner2214ed82016-01-29 00:49:42 +00003419 if (Name == "prologue_end")
3420 PrologueEnd = true;
3421 else if (Name == "is_stmt") {
3422 Loc = getTok().getLoc();
3423 const MCExpr *Value;
3424 if (parseExpression(Value))
3425 return true;
3426 // The expression must be the constant 0 or 1.
3427 IsStmt = ~0ULL;
3428 if (const auto *MCE = dyn_cast<MCConstantExpr>(Value))
3429 IsStmt = MCE->getValue();
3430
3431 if (IsStmt > 1)
3432 return Error(Loc, "is_stmt value not 0 or 1");
3433 } else {
3434 return Error(Loc, "unknown sub-directive in '.cv_loc' directive");
3435 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003436 return false;
3437 };
3438
3439 if (parseMany(parseOp, false /*hasComma*/))
3440 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003441
3442 getStreamer().EmitCVLocDirective(FunctionId, FileNumber, LineNumber,
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003443 ColumnPos, PrologueEnd, IsStmt, StringRef(),
3444 DirectiveLoc);
Reid Kleckner2214ed82016-01-29 00:49:42 +00003445 return false;
3446}
3447
3448/// parseDirectiveCVLinetable
3449/// ::= .cv_linetable FunctionId, FnStart, FnEnd
3450bool AsmParser::parseDirectiveCVLinetable() {
Nirav Davea645433c2016-07-18 15:24:03 +00003451 int64_t FunctionId;
3452 StringRef FnStartName, FnEndName;
3453 SMLoc Loc = getTok().getLoc();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003454 if (parseCVFunctionId(FunctionId, ".cv_linetable") ||
Nirav Davea645433c2016-07-18 15:24:03 +00003455 parseToken(AsmToken::Comma,
3456 "unexpected token in '.cv_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003457 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3458 "expected identifier in directive") ||
Nirav Davea645433c2016-07-18 15:24:03 +00003459 parseToken(AsmToken::Comma,
3460 "unexpected token in '.cv_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003461 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3462 "expected identifier in directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00003463 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003464
3465 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3466 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
3467
3468 getStreamer().EmitCVLinetableDirective(FunctionId, FnStartSym, FnEndSym);
3469 return false;
3470}
3471
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003472/// parseDirectiveCVInlineLinetable
David Majnemerc9911f22016-02-02 19:22:34 +00003473/// ::= .cv_inline_linetable PrimaryFunctionId FileId LineNum FnStart FnEnd
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003474bool AsmParser::parseDirectiveCVInlineLinetable() {
Nirav Davea645433c2016-07-18 15:24:03 +00003475 int64_t PrimaryFunctionId, SourceFileId, SourceLineNum;
3476 StringRef FnStartName, FnEndName;
3477 SMLoc Loc = getTok().getLoc();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003478 if (parseCVFunctionId(PrimaryFunctionId, ".cv_inline_linetable") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003479 parseTokenLoc(Loc) ||
Nirav Davea645433c2016-07-18 15:24:03 +00003480 parseIntToken(
3481 SourceFileId,
3482 "expected SourceField in '.cv_inline_linetable' directive") ||
3483 check(SourceFileId <= 0, Loc,
3484 "File id less than zero in '.cv_inline_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003485 parseTokenLoc(Loc) ||
Nirav Davea645433c2016-07-18 15:24:03 +00003486 parseIntToken(
3487 SourceLineNum,
3488 "expected SourceLineNum in '.cv_inline_linetable' directive") ||
3489 check(SourceLineNum < 0, Loc,
3490 "Line number less than zero in '.cv_inline_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003491 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3492 "expected identifier in directive") ||
3493 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3494 "expected identifier in directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00003495 return true;
David Majnemerc9911f22016-02-02 19:22:34 +00003496
Nirav Davea645433c2016-07-18 15:24:03 +00003497 if (parseToken(AsmToken::EndOfStatement, "Expected End of Statement"))
3498 return true;
3499
3500 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3501 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
Reid Kleckner1fcd6102016-02-02 17:41:18 +00003502 getStreamer().EmitCVInlineLinetableDirective(PrimaryFunctionId, SourceFileId,
3503 SourceLineNum, FnStartSym,
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003504 FnEndSym);
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003505 return false;
3506}
3507
David Majnemer408b5e62016-02-05 01:55:49 +00003508/// parseDirectiveCVDefRange
3509/// ::= .cv_def_range RangeStart RangeEnd (GapStart GapEnd)*, bytes*
3510bool AsmParser::parseDirectiveCVDefRange() {
3511 SMLoc Loc;
3512 std::vector<std::pair<const MCSymbol *, const MCSymbol *>> Ranges;
3513 while (getLexer().is(AsmToken::Identifier)) {
3514 Loc = getLexer().getLoc();
3515 StringRef GapStartName;
3516 if (parseIdentifier(GapStartName))
3517 return Error(Loc, "expected identifier in directive");
3518 MCSymbol *GapStartSym = getContext().getOrCreateSymbol(GapStartName);
3519
3520 Loc = getLexer().getLoc();
3521 StringRef GapEndName;
3522 if (parseIdentifier(GapEndName))
3523 return Error(Loc, "expected identifier in directive");
3524 MCSymbol *GapEndSym = getContext().getOrCreateSymbol(GapEndName);
3525
3526 Ranges.push_back({GapStartSym, GapEndSym});
3527 }
3528
David Majnemer408b5e62016-02-05 01:55:49 +00003529 std::string FixedSizePortion;
Nirav Davea645433c2016-07-18 15:24:03 +00003530 if (parseToken(AsmToken::Comma, "unexpected token in directive") ||
3531 parseEscapedString(FixedSizePortion))
David Majnemer408b5e62016-02-05 01:55:49 +00003532 return true;
David Majnemer408b5e62016-02-05 01:55:49 +00003533
3534 getStreamer().EmitCVDefRangeDirective(Ranges, FixedSizePortion);
3535 return false;
3536}
3537
Reid Kleckner2214ed82016-01-29 00:49:42 +00003538/// parseDirectiveCVStringTable
3539/// ::= .cv_stringtable
3540bool AsmParser::parseDirectiveCVStringTable() {
3541 getStreamer().EmitCVStringTableDirective();
3542 return false;
3543}
3544
3545/// parseDirectiveCVFileChecksums
3546/// ::= .cv_filechecksums
3547bool AsmParser::parseDirectiveCVFileChecksums() {
3548 getStreamer().EmitCVFileChecksumsDirective();
3549 return false;
3550}
3551
Jim Grosbach4b905842013-09-20 23:08:21 +00003552/// parseDirectiveCFISections
Eli Bendersky17233942013-01-15 22:59:42 +00003553/// ::= .cfi_sections section [, section]
Jim Grosbach4b905842013-09-20 23:08:21 +00003554bool AsmParser::parseDirectiveCFISections() {
Eli Bendersky17233942013-01-15 22:59:42 +00003555 StringRef Name;
3556 bool EH = false;
3557 bool Debug = false;
3558
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003559 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003560 return TokError("Expected an identifier");
3561
3562 if (Name == ".eh_frame")
3563 EH = true;
3564 else if (Name == ".debug_frame")
3565 Debug = true;
3566
3567 if (getLexer().is(AsmToken::Comma)) {
3568 Lex();
3569
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003570 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003571 return TokError("Expected an identifier");
3572
3573 if (Name == ".eh_frame")
3574 EH = true;
3575 else if (Name == ".debug_frame")
3576 Debug = true;
3577 }
3578
3579 getStreamer().EmitCFISections(EH, Debug);
3580 return false;
3581}
3582
Jim Grosbach4b905842013-09-20 23:08:21 +00003583/// parseDirectiveCFIStartProc
David Majnemere035cf92014-01-27 17:20:25 +00003584/// ::= .cfi_startproc [simple]
Jim Grosbach4b905842013-09-20 23:08:21 +00003585bool AsmParser::parseDirectiveCFIStartProc() {
David Majnemere035cf92014-01-27 17:20:25 +00003586 StringRef Simple;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003587 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
3588 if (check(parseIdentifier(Simple) || Simple != "simple",
3589 "unexpected token") ||
3590 parseToken(AsmToken::EndOfStatement))
3591 return addErrorSuffix(" in '.cfi_startproc' directive");
3592 }
Nirav Davea645433c2016-07-18 15:24:03 +00003593
Oliver Stannardcf6bfb12014-11-03 12:19:03 +00003594 getStreamer().EmitCFIStartProc(!Simple.empty());
Eli Bendersky17233942013-01-15 22:59:42 +00003595 return false;
3596}
3597
Jim Grosbach4b905842013-09-20 23:08:21 +00003598/// parseDirectiveCFIEndProc
Eli Bendersky17233942013-01-15 22:59:42 +00003599/// ::= .cfi_endproc
Jim Grosbach4b905842013-09-20 23:08:21 +00003600bool AsmParser::parseDirectiveCFIEndProc() {
Eli Bendersky17233942013-01-15 22:59:42 +00003601 getStreamer().EmitCFIEndProc();
3602 return false;
3603}
3604
Jim Grosbach4b905842013-09-20 23:08:21 +00003605/// \brief parse register name or number.
3606bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
Eli Bendersky17233942013-01-15 22:59:42 +00003607 SMLoc DirectiveLoc) {
3608 unsigned RegNo;
3609
3610 if (getLexer().isNot(AsmToken::Integer)) {
3611 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
3612 return true;
Bill Wendlingbc07a892013-06-18 07:20:20 +00003613 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
Eli Bendersky17233942013-01-15 22:59:42 +00003614 } else
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003615 return parseAbsoluteExpression(Register);
Eli Bendersky17233942013-01-15 22:59:42 +00003616
3617 return false;
3618}
3619
Jim Grosbach4b905842013-09-20 23:08:21 +00003620/// parseDirectiveCFIDefCfa
Eli Bendersky17233942013-01-15 22:59:42 +00003621/// ::= .cfi_def_cfa register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003622bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003623 int64_t Register = 0, Offset = 0;
3624 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3625 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3626 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003627 return true;
3628
3629 getStreamer().EmitCFIDefCfa(Register, Offset);
3630 return false;
3631}
3632
Jim Grosbach4b905842013-09-20 23:08:21 +00003633/// parseDirectiveCFIDefCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003634/// ::= .cfi_def_cfa_offset offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003635bool AsmParser::parseDirectiveCFIDefCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00003636 int64_t Offset = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003637 if (parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003638 return true;
3639
3640 getStreamer().EmitCFIDefCfaOffset(Offset);
3641 return false;
3642}
3643
Jim Grosbach4b905842013-09-20 23:08:21 +00003644/// parseDirectiveCFIRegister
Eli Bendersky17233942013-01-15 22:59:42 +00003645/// ::= .cfi_register register, register
Jim Grosbach4b905842013-09-20 23:08:21 +00003646bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003647 int64_t Register1 = 0, Register2 = 0;
3648 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc) ||
3649 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3650 parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003651 return true;
3652
3653 getStreamer().EmitCFIRegister(Register1, Register2);
3654 return false;
3655}
3656
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00003657/// parseDirectiveCFIWindowSave
3658/// ::= .cfi_window_save
3659bool AsmParser::parseDirectiveCFIWindowSave() {
3660 getStreamer().EmitCFIWindowSave();
3661 return false;
3662}
3663
Jim Grosbach4b905842013-09-20 23:08:21 +00003664/// parseDirectiveCFIAdjustCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003665/// ::= .cfi_adjust_cfa_offset adjustment
Jim Grosbach4b905842013-09-20 23:08:21 +00003666bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00003667 int64_t Adjustment = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003668 if (parseAbsoluteExpression(Adjustment))
Eli Bendersky17233942013-01-15 22:59:42 +00003669 return true;
3670
3671 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3672 return false;
3673}
3674
Jim Grosbach4b905842013-09-20 23:08:21 +00003675/// parseDirectiveCFIDefCfaRegister
Eli Bendersky17233942013-01-15 22:59:42 +00003676/// ::= .cfi_def_cfa_register register
Jim Grosbach4b905842013-09-20 23:08:21 +00003677bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003678 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003679 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003680 return true;
3681
3682 getStreamer().EmitCFIDefCfaRegister(Register);
3683 return false;
3684}
3685
Jim Grosbach4b905842013-09-20 23:08:21 +00003686/// parseDirectiveCFIOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003687/// ::= .cfi_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003688bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003689 int64_t Register = 0;
3690 int64_t Offset = 0;
3691
Nirav Davea645433c2016-07-18 15:24:03 +00003692 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3693 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3694 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003695 return true;
3696
3697 getStreamer().EmitCFIOffset(Register, Offset);
3698 return false;
3699}
3700
Jim Grosbach4b905842013-09-20 23:08:21 +00003701/// parseDirectiveCFIRelOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003702/// ::= .cfi_rel_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003703bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003704 int64_t Register = 0, Offset = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003705
Nirav Davea645433c2016-07-18 15:24:03 +00003706 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3707 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3708 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003709 return true;
3710
3711 getStreamer().EmitCFIRelOffset(Register, Offset);
3712 return false;
3713}
3714
3715static bool isValidEncoding(int64_t Encoding) {
3716 if (Encoding & ~0xff)
3717 return false;
3718
3719 if (Encoding == dwarf::DW_EH_PE_omit)
3720 return true;
3721
3722 const unsigned Format = Encoding & 0xf;
3723 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3724 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3725 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3726 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3727 return false;
3728
3729 const unsigned Application = Encoding & 0x70;
3730 if (Application != dwarf::DW_EH_PE_absptr &&
3731 Application != dwarf::DW_EH_PE_pcrel)
3732 return false;
3733
3734 return true;
3735}
3736
Jim Grosbach4b905842013-09-20 23:08:21 +00003737/// parseDirectiveCFIPersonalityOrLsda
Eli Bendersky17233942013-01-15 22:59:42 +00003738/// IsPersonality true for cfi_personality, false for cfi_lsda
3739/// ::= .cfi_personality encoding, [symbol_name]
3740/// ::= .cfi_lsda encoding, [symbol_name]
Jim Grosbach4b905842013-09-20 23:08:21 +00003741bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
Eli Bendersky17233942013-01-15 22:59:42 +00003742 int64_t Encoding = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003743 if (parseAbsoluteExpression(Encoding))
Eli Bendersky17233942013-01-15 22:59:42 +00003744 return true;
3745 if (Encoding == dwarf::DW_EH_PE_omit)
3746 return false;
3747
Eli Bendersky17233942013-01-15 22:59:42 +00003748 StringRef Name;
Nirav Davea645433c2016-07-18 15:24:03 +00003749 if (check(!isValidEncoding(Encoding), "unsupported encoding.") ||
3750 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3751 check(parseIdentifier(Name), "expected identifier in directive"))
3752 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003753
Jim Grosbach6f482002015-05-18 18:43:14 +00003754 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Eli Bendersky17233942013-01-15 22:59:42 +00003755
3756 if (IsPersonality)
3757 getStreamer().EmitCFIPersonality(Sym, Encoding);
3758 else
3759 getStreamer().EmitCFILsda(Sym, Encoding);
3760 return false;
3761}
3762
Jim Grosbach4b905842013-09-20 23:08:21 +00003763/// parseDirectiveCFIRememberState
Eli Bendersky17233942013-01-15 22:59:42 +00003764/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00003765bool AsmParser::parseDirectiveCFIRememberState() {
Eli Bendersky17233942013-01-15 22:59:42 +00003766 getStreamer().EmitCFIRememberState();
3767 return false;
3768}
3769
Jim Grosbach4b905842013-09-20 23:08:21 +00003770/// parseDirectiveCFIRestoreState
Eli Bendersky17233942013-01-15 22:59:42 +00003771/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00003772bool AsmParser::parseDirectiveCFIRestoreState() {
Eli Bendersky17233942013-01-15 22:59:42 +00003773 getStreamer().EmitCFIRestoreState();
3774 return false;
3775}
3776
Jim Grosbach4b905842013-09-20 23:08:21 +00003777/// parseDirectiveCFISameValue
Eli Bendersky17233942013-01-15 22:59:42 +00003778/// ::= .cfi_same_value register
Jim Grosbach4b905842013-09-20 23:08:21 +00003779bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003780 int64_t Register = 0;
3781
Jim Grosbach4b905842013-09-20 23:08:21 +00003782 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003783 return true;
3784
3785 getStreamer().EmitCFISameValue(Register);
3786 return false;
3787}
3788
Jim Grosbach4b905842013-09-20 23:08:21 +00003789/// parseDirectiveCFIRestore
Eli Bendersky17233942013-01-15 22:59:42 +00003790/// ::= .cfi_restore register
Jim Grosbach4b905842013-09-20 23:08:21 +00003791bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003792 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003793 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003794 return true;
3795
3796 getStreamer().EmitCFIRestore(Register);
3797 return false;
3798}
3799
Jim Grosbach4b905842013-09-20 23:08:21 +00003800/// parseDirectiveCFIEscape
Eli Bendersky17233942013-01-15 22:59:42 +00003801/// ::= .cfi_escape expression[,...]
Jim Grosbach4b905842013-09-20 23:08:21 +00003802bool AsmParser::parseDirectiveCFIEscape() {
Eli Bendersky17233942013-01-15 22:59:42 +00003803 std::string Values;
3804 int64_t CurrValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003805 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00003806 return true;
3807
3808 Values.push_back((uint8_t)CurrValue);
3809
3810 while (getLexer().is(AsmToken::Comma)) {
3811 Lex();
3812
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003813 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00003814 return true;
3815
3816 Values.push_back((uint8_t)CurrValue);
3817 }
3818
3819 getStreamer().EmitCFIEscape(Values);
3820 return false;
3821}
3822
Jim Grosbach4b905842013-09-20 23:08:21 +00003823/// parseDirectiveCFISignalFrame
Eli Bendersky17233942013-01-15 22:59:42 +00003824/// ::= .cfi_signal_frame
Jim Grosbach4b905842013-09-20 23:08:21 +00003825bool AsmParser::parseDirectiveCFISignalFrame() {
Nirav Davea645433c2016-07-18 15:24:03 +00003826 if (parseToken(AsmToken::EndOfStatement,
3827 "unexpected token in '.cfi_signal_frame'"))
3828 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003829
3830 getStreamer().EmitCFISignalFrame();
3831 return false;
3832}
3833
Jim Grosbach4b905842013-09-20 23:08:21 +00003834/// parseDirectiveCFIUndefined
Eli Bendersky17233942013-01-15 22:59:42 +00003835/// ::= .cfi_undefined register
Jim Grosbach4b905842013-09-20 23:08:21 +00003836bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003837 int64_t Register = 0;
3838
Jim Grosbach4b905842013-09-20 23:08:21 +00003839 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003840 return true;
3841
3842 getStreamer().EmitCFIUndefined(Register);
3843 return false;
3844}
3845
Jim Grosbach4b905842013-09-20 23:08:21 +00003846/// parseDirectiveMacrosOnOff
Eli Bendersky17233942013-01-15 22:59:42 +00003847/// ::= .macros_on
3848/// ::= .macros_off
Jim Grosbach4b905842013-09-20 23:08:21 +00003849bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
Nirav Davea645433c2016-07-18 15:24:03 +00003850 if (parseToken(AsmToken::EndOfStatement,
3851 "unexpected token in '" + Directive + "' directive"))
3852 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003853
Jim Grosbach4b905842013-09-20 23:08:21 +00003854 setMacrosEnabled(Directive == ".macros_on");
Eli Bendersky17233942013-01-15 22:59:42 +00003855 return false;
3856}
3857
Jim Grosbach4b905842013-09-20 23:08:21 +00003858/// parseDirectiveMacro
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00003859/// ::= .macro name[,] [parameters]
Jim Grosbach4b905842013-09-20 23:08:21 +00003860bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003861 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003862 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003863 return TokError("expected identifier in '.macro' directive");
3864
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00003865 if (getLexer().is(AsmToken::Comma))
3866 Lex();
3867
Eli Bendersky17233942013-01-15 22:59:42 +00003868 MCAsmMacroParameters Parameters;
David Majnemer91fc4c22014-01-29 18:57:46 +00003869 while (getLexer().isNot(AsmToken::EndOfStatement)) {
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003870
Alexander Kornienko8c0809c2015-01-15 11:41:30 +00003871 if (!Parameters.empty() && Parameters.back().Vararg)
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003872 return Error(Lexer.getLoc(),
3873 "Vararg parameter '" + Parameters.back().Name +
3874 "' should be last one in the list of parameters.");
3875
David Majnemer91fc4c22014-01-29 18:57:46 +00003876 MCAsmMacroParameter Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00003877 if (parseIdentifier(Parameter.Name))
David Majnemer91fc4c22014-01-29 18:57:46 +00003878 return TokError("expected identifier in '.macro' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003879
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003880 if (Lexer.is(AsmToken::Colon)) {
3881 Lex(); // consume ':'
3882
3883 SMLoc QualLoc;
3884 StringRef Qualifier;
3885
3886 QualLoc = Lexer.getLoc();
3887 if (parseIdentifier(Qualifier))
3888 return Error(QualLoc, "missing parameter qualifier for "
3889 "'" + Parameter.Name + "' in macro '" + Name + "'");
3890
3891 if (Qualifier == "req")
3892 Parameter.Required = true;
Kevin Enderbye3c13462014-08-04 23:14:37 +00003893 else if (Qualifier == "vararg")
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003894 Parameter.Vararg = true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003895 else
3896 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
3897 "for '" + Parameter.Name + "' in macro '" + Name + "'");
3898 }
3899
David Majnemer91fc4c22014-01-29 18:57:46 +00003900 if (getLexer().is(AsmToken::Equal)) {
3901 Lex();
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003902
3903 SMLoc ParamLoc;
3904
3905 ParamLoc = Lexer.getLoc();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003906 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
David Majnemer91fc4c22014-01-29 18:57:46 +00003907 return true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003908
3909 if (Parameter.Required)
3910 Warning(ParamLoc, "pointless default value for required parameter "
3911 "'" + Parameter.Name + "' in macro '" + Name + "'");
Eli Bendersky17233942013-01-15 22:59:42 +00003912 }
David Majnemer91fc4c22014-01-29 18:57:46 +00003913
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00003914 Parameters.push_back(std::move(Parameter));
David Majnemer91fc4c22014-01-29 18:57:46 +00003915
3916 if (getLexer().is(AsmToken::Comma))
3917 Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00003918 }
3919
Nirav Dave1180e6892016-06-02 17:15:05 +00003920 // Eat just the end of statement.
3921 Lexer.Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00003922
Nirav Dave1180e6892016-06-02 17:15:05 +00003923 // Consuming deferred text, so use Lexer.Lex to ignore Lexing Errors
Eli Bendersky17233942013-01-15 22:59:42 +00003924 AsmToken EndToken, StartToken = getTok();
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00003925 unsigned MacroDepth = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003926 // Lex the macro definition.
Eugene Zelenko33d7b762016-08-23 17:14:32 +00003927 while (true) {
Nirav Dave1180e6892016-06-02 17:15:05 +00003928 // Ignore Lexing errors in macros.
3929 while (Lexer.is(AsmToken::Error)) {
3930 Lexer.Lex();
3931 }
3932
Eli Bendersky17233942013-01-15 22:59:42 +00003933 // Check whether we have reached the end of the file.
3934 if (getLexer().is(AsmToken::Eof))
3935 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3936
3937 // Otherwise, check whether we have reach the .endmacro.
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00003938 if (getLexer().is(AsmToken::Identifier)) {
3939 if (getTok().getIdentifier() == ".endm" ||
3940 getTok().getIdentifier() == ".endmacro") {
3941 if (MacroDepth == 0) { // Outermost macro.
3942 EndToken = getTok();
Nirav Dave1180e6892016-06-02 17:15:05 +00003943 Lexer.Lex();
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00003944 if (getLexer().isNot(AsmToken::EndOfStatement))
3945 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3946 "' directive");
3947 break;
3948 } else {
3949 // Otherwise we just found the end of an inner macro.
3950 --MacroDepth;
3951 }
3952 } else if (getTok().getIdentifier() == ".macro") {
3953 // We allow nested macros. Those aren't instantiated until the outermost
3954 // macro is expanded so just ignore them for now.
3955 ++MacroDepth;
3956 }
Eli Bendersky17233942013-01-15 22:59:42 +00003957 }
3958
3959 // Otherwise, scan til the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003960 eatToEndOfStatement();
Eli Bendersky17233942013-01-15 22:59:42 +00003961 }
3962
Jim Grosbach4b905842013-09-20 23:08:21 +00003963 if (lookupMacro(Name)) {
Eli Bendersky17233942013-01-15 22:59:42 +00003964 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3965 }
3966
3967 const char *BodyStart = StartToken.getLoc().getPointer();
3968 const char *BodyEnd = EndToken.getLoc().getPointer();
3969 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Jim Grosbach4b905842013-09-20 23:08:21 +00003970 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00003971 defineMacro(Name, MCAsmMacro(Name, Body, std::move(Parameters)));
Eli Bendersky17233942013-01-15 22:59:42 +00003972 return false;
3973}
3974
Jim Grosbach4b905842013-09-20 23:08:21 +00003975/// checkForBadMacro
Kevin Enderby81c944c2013-01-22 21:44:53 +00003976///
3977/// With the support added for named parameters there may be code out there that
3978/// is transitioning from positional parameters. In versions of gas that did
Alp Tokercb402912014-01-24 17:20:08 +00003979/// not support named parameters they would be ignored on the macro definition.
Kevin Enderby81c944c2013-01-22 21:44:53 +00003980/// But to support both styles of parameters this is not possible so if a macro
Alp Tokercb402912014-01-24 17:20:08 +00003981/// definition has named parameters but does not use them and has what appears
Kevin Enderby81c944c2013-01-22 21:44:53 +00003982/// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3983/// warning that the positional parameter found in body which have no effect.
3984/// Hoping the developer will either remove the named parameters from the macro
Alp Tokercb402912014-01-24 17:20:08 +00003985/// definition so the positional parameters get used if that was what was
Kevin Enderby81c944c2013-01-22 21:44:53 +00003986/// intended or change the macro to use the named parameters. It is possible
3987/// this warning will trigger when the none of the named parameters are used
3988/// and the strings like $1 are infact to simply to be passed trough unchanged.
Jim Grosbach4b905842013-09-20 23:08:21 +00003989void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
Kevin Enderby81c944c2013-01-22 21:44:53 +00003990 StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00003991 ArrayRef<MCAsmMacroParameter> Parameters) {
Kevin Enderby81c944c2013-01-22 21:44:53 +00003992 // If this macro is not defined with named parameters the warning we are
3993 // checking for here doesn't apply.
3994 unsigned NParameters = Parameters.size();
3995 if (NParameters == 0)
3996 return;
3997
3998 bool NamedParametersFound = false;
3999 bool PositionalParametersFound = false;
4000
4001 // Look at the body of the macro for use of both the named parameters and what
4002 // are likely to be positional parameters. This is what expandMacro() is
4003 // doing when it finds the parameters in the body.
4004 while (!Body.empty()) {
4005 // Scan for the next possible parameter.
4006 std::size_t End = Body.size(), Pos = 0;
4007 for (; Pos != End; ++Pos) {
4008 // Check for a substitution or escape.
4009 // This macro is defined with parameters, look for \foo, \bar, etc.
4010 if (Body[Pos] == '\\' && Pos + 1 != End)
4011 break;
4012
4013 // This macro should have parameters, but look for $0, $1, ..., $n too.
4014 if (Body[Pos] != '$' || Pos + 1 == End)
4015 continue;
4016 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00004017 if (Next == '$' || Next == 'n' ||
4018 isdigit(static_cast<unsigned char>(Next)))
Kevin Enderby81c944c2013-01-22 21:44:53 +00004019 break;
4020 }
4021
4022 // Check if we reached the end.
4023 if (Pos == End)
4024 break;
4025
4026 if (Body[Pos] == '$') {
Jim Grosbach4b905842013-09-20 23:08:21 +00004027 switch (Body[Pos + 1]) {
4028 // $$ => $
Kevin Enderby81c944c2013-01-22 21:44:53 +00004029 case '$':
4030 break;
4031
Jim Grosbach4b905842013-09-20 23:08:21 +00004032 // $n => number of arguments
Kevin Enderby81c944c2013-01-22 21:44:53 +00004033 case 'n':
4034 PositionalParametersFound = true;
4035 break;
4036
Jim Grosbach4b905842013-09-20 23:08:21 +00004037 // $[0-9] => argument
Kevin Enderby81c944c2013-01-22 21:44:53 +00004038 default: {
4039 PositionalParametersFound = true;
4040 break;
Jim Grosbach4b905842013-09-20 23:08:21 +00004041 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00004042 }
4043 Pos += 2;
4044 } else {
4045 unsigned I = Pos + 1;
4046 while (isIdentifierChar(Body[I]) && I + 1 != End)
4047 ++I;
4048
Jim Grosbach4b905842013-09-20 23:08:21 +00004049 const char *Begin = Body.data() + Pos + 1;
4050 StringRef Argument(Begin, I - (Pos + 1));
Kevin Enderby81c944c2013-01-22 21:44:53 +00004051 unsigned Index = 0;
4052 for (; Index < NParameters; ++Index)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00004053 if (Parameters[Index].Name == Argument)
Kevin Enderby81c944c2013-01-22 21:44:53 +00004054 break;
4055
4056 if (Index == NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00004057 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
4058 Pos += 3;
4059 else {
4060 Pos = I;
4061 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00004062 } else {
4063 NamedParametersFound = true;
4064 Pos += 1 + Argument.size();
4065 }
4066 }
4067 // Update the scan point.
4068 Body = Body.substr(Pos);
4069 }
4070
4071 if (!NamedParametersFound && PositionalParametersFound)
4072 Warning(DirectiveLoc, "macro defined with named parameters which are not "
4073 "used in macro body, possible positional parameter "
4074 "found in body which will have no effect");
4075}
4076
Nico Weber155dccd12014-07-24 17:08:39 +00004077/// parseDirectiveExitMacro
4078/// ::= .exitm
4079bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
Nirav Davea645433c2016-07-18 15:24:03 +00004080 if (parseToken(AsmToken::EndOfStatement,
4081 "unexpected token in '" + Directive + "' directive"))
4082 return true;
Nico Weber155dccd12014-07-24 17:08:39 +00004083
4084 if (!isInsideMacroInstantiation())
4085 return TokError("unexpected '" + Directive + "' in file, "
4086 "no current macro definition");
4087
4088 // Exit all conditionals that are active in the current macro.
4089 while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
4090 TheCondState = TheCondStack.back();
4091 TheCondStack.pop_back();
4092 }
4093
4094 handleMacroExit();
4095 return false;
4096}
4097
Jim Grosbach4b905842013-09-20 23:08:21 +00004098/// parseDirectiveEndMacro
Eli Bendersky17233942013-01-15 22:59:42 +00004099/// ::= .endm
4100/// ::= .endmacro
Jim Grosbach4b905842013-09-20 23:08:21 +00004101bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
Eli Bendersky17233942013-01-15 22:59:42 +00004102 if (getLexer().isNot(AsmToken::EndOfStatement))
4103 return TokError("unexpected token in '" + Directive + "' directive");
4104
4105 // If we are inside a macro instantiation, terminate the current
4106 // instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00004107 if (isInsideMacroInstantiation()) {
4108 handleMacroExit();
Eli Bendersky17233942013-01-15 22:59:42 +00004109 return false;
4110 }
4111
4112 // Otherwise, this .endmacro is a stray entry in the file; well formed
4113 // .endmacro directives are handled during the macro definition parsing.
4114 return TokError("unexpected '" + Directive + "' in file, "
Jim Grosbach4b905842013-09-20 23:08:21 +00004115 "no current macro definition");
Eli Bendersky17233942013-01-15 22:59:42 +00004116}
4117
Jim Grosbach4b905842013-09-20 23:08:21 +00004118/// parseDirectivePurgeMacro
Eli Bendersky17233942013-01-15 22:59:42 +00004119/// ::= .purgem
Jim Grosbach4b905842013-09-20 23:08:21 +00004120bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004121 StringRef Name;
Nirav Davea645433c2016-07-18 15:24:03 +00004122 SMLoc Loc;
Nirav Daved8858ca2016-08-30 14:15:43 +00004123 if (parseTokenLoc(Loc) ||
4124 check(parseIdentifier(Name), Loc,
4125 "expected identifier in '.purgem' directive") ||
Nirav Davea645433c2016-07-18 15:24:03 +00004126 parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00004127 "unexpected token in '.purgem' directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00004128 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004129
Nirav Dave1ab71992016-07-18 19:35:21 +00004130 if (!lookupMacro(Name))
4131 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
4132
Jim Grosbach4b905842013-09-20 23:08:21 +00004133 undefineMacro(Name);
Eli Bendersky17233942013-01-15 22:59:42 +00004134 return false;
4135}
Eli Benderskyf483ff92012-12-20 19:05:53 +00004136
Jim Grosbach4b905842013-09-20 23:08:21 +00004137/// parseDirectiveBundleAlignMode
Eli Benderskyf483ff92012-12-20 19:05:53 +00004138/// ::= {.bundle_align_mode} expression
Jim Grosbach4b905842013-09-20 23:08:21 +00004139bool AsmParser::parseDirectiveBundleAlignMode() {
Eli Benderskyf483ff92012-12-20 19:05:53 +00004140 // Expect a single argument: an expression that evaluates to a constant
4141 // in the inclusive range 0-30.
4142 SMLoc ExprLoc = getLexer().getLoc();
4143 int64_t AlignSizePow2;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004144 if (checkForValidSection() || parseAbsoluteExpression(AlignSizePow2) ||
Nirav Davea645433c2016-07-18 15:24:03 +00004145 parseToken(AsmToken::EndOfStatement, "unexpected token after expression "
4146 "in '.bundle_align_mode' "
4147 "directive") ||
4148 check(AlignSizePow2 < 0 || AlignSizePow2 > 30, ExprLoc,
4149 "invalid bundle alignment size (expected between 0 and 30)"))
Eli Benderskyf483ff92012-12-20 19:05:53 +00004150 return true;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004151
4152 // Because of AlignSizePow2's verified range we can safely truncate it to
4153 // unsigned.
4154 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
4155 return false;
4156}
4157
Jim Grosbach4b905842013-09-20 23:08:21 +00004158/// parseDirectiveBundleLock
Eli Bendersky802b6282013-01-07 21:51:08 +00004159/// ::= {.bundle_lock} [align_to_end]
Jim Grosbach4b905842013-09-20 23:08:21 +00004160bool AsmParser::parseDirectiveBundleLock() {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004161 if (checkForValidSection())
4162 return true;
Eli Bendersky802b6282013-01-07 21:51:08 +00004163 bool AlignToEnd = false;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004164
Nirav Dave1a9044b2016-10-24 14:35:29 +00004165 StringRef Option;
4166 SMLoc Loc = getTok().getLoc();
4167 const char *kInvalidOptionError =
4168 "invalid option for '.bundle_lock' directive";
Eli Bendersky802b6282013-01-07 21:51:08 +00004169
Nirav Dave1a9044b2016-10-24 14:35:29 +00004170 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
Nirav Davea645433c2016-07-18 15:24:03 +00004171 if (check(parseIdentifier(Option), Loc, kInvalidOptionError) ||
4172 check(Option != "align_to_end", Loc, kInvalidOptionError) ||
Nirav Dave1a9044b2016-10-24 14:35:29 +00004173 parseToken(AsmToken::EndOfStatement,
4174 "unexpected token after '.bundle_lock' directive option"))
Nirav Davea645433c2016-07-18 15:24:03 +00004175 return true;
Eli Bendersky802b6282013-01-07 21:51:08 +00004176 AlignToEnd = true;
4177 }
4178
Eli Bendersky802b6282013-01-07 21:51:08 +00004179 getStreamer().EmitBundleLock(AlignToEnd);
Eli Benderskyf483ff92012-12-20 19:05:53 +00004180 return false;
4181}
4182
Jim Grosbach4b905842013-09-20 23:08:21 +00004183/// parseDirectiveBundleLock
Eli Benderskyf483ff92012-12-20 19:05:53 +00004184/// ::= {.bundle_lock}
Jim Grosbach4b905842013-09-20 23:08:21 +00004185bool AsmParser::parseDirectiveBundleUnlock() {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004186 if (checkForValidSection() ||
4187 parseToken(AsmToken::EndOfStatement,
Nirav Davea645433c2016-07-18 15:24:03 +00004188 "unexpected token in '.bundle_unlock' directive"))
4189 return true;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004190
4191 getStreamer().EmitBundleUnlock();
4192 return false;
4193}
4194
Jim Grosbach4b905842013-09-20 23:08:21 +00004195/// parseDirectiveSpace
Eli Bendersky17233942013-01-15 22:59:42 +00004196/// ::= (.skip | .space) expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004197bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
Petr Hosek67a94a72016-05-28 05:57:48 +00004198 SMLoc NumBytesLoc = Lexer.getLoc();
4199 const MCExpr *NumBytes;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004200 if (checkForValidSection() || parseExpression(NumBytes))
Eli Bendersky17233942013-01-15 22:59:42 +00004201 return true;
4202
4203 int64_t FillExpr = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00004204 if (parseOptionalToken(AsmToken::Comma))
4205 if (parseAbsoluteExpression(FillExpr))
4206 return addErrorSuffix("in '" + Twine(IDVal) + "' directive");
4207 if (parseToken(AsmToken::EndOfStatement))
4208 return addErrorSuffix("in '" + Twine(IDVal) + "' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00004209
Eli Bendersky17233942013-01-15 22:59:42 +00004210 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
Petr Hosek67a94a72016-05-28 05:57:48 +00004211 getStreamer().emitFill(*NumBytes, FillExpr, NumBytesLoc);
Eli Bendersky17233942013-01-15 22:59:42 +00004212
4213 return false;
4214}
4215
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004216/// parseDirectiveDCB
4217/// ::= .dcb.{b, l, w} expression, expression
4218bool AsmParser::parseDirectiveDCB(StringRef IDVal, unsigned Size) {
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004219 SMLoc NumValuesLoc = Lexer.getLoc();
4220 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004221 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004222 return true;
4223
4224 if (NumValues < 0) {
4225 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4226 return false;
4227 }
4228
4229 if (parseToken(AsmToken::Comma,
4230 "unexpected token in '" + Twine(IDVal) + "' directive"))
4231 return true;
4232
4233 const MCExpr *Value;
4234 SMLoc ExprLoc = getLexer().getLoc();
4235 if (parseExpression(Value))
4236 return true;
4237
4238 // Special case constant expressions to match code generator.
4239 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
4240 assert(Size <= 8 && "Invalid size");
4241 uint64_t IntValue = MCE->getValue();
4242 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
4243 return Error(ExprLoc, "literal value out of range for directive");
4244 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4245 getStreamer().EmitIntValue(IntValue, Size);
4246 } else {
4247 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4248 getStreamer().EmitValue(Value, Size, ExprLoc);
4249 }
4250
4251 if (parseToken(AsmToken::EndOfStatement,
4252 "unexpected token in '" + Twine(IDVal) + "' directive"))
4253 return true;
4254
4255 return false;
4256}
4257
4258/// parseDirectiveRealDCB
4259/// ::= .dcb.{d, s} expression, expression
4260bool AsmParser::parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &Semantics) {
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004261 SMLoc NumValuesLoc = Lexer.getLoc();
4262 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004263 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004264 return true;
4265
4266 if (NumValues < 0) {
4267 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4268 return false;
4269 }
4270
4271 if (parseToken(AsmToken::Comma,
4272 "unexpected token in '" + Twine(IDVal) + "' directive"))
4273 return true;
4274
4275 APInt AsInt;
4276 if (parseRealValue(Semantics, AsInt))
4277 return true;
4278
4279 if (parseToken(AsmToken::EndOfStatement,
4280 "unexpected token in '" + Twine(IDVal) + "' directive"))
4281 return true;
4282
4283 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4284 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
4285 AsInt.getBitWidth() / 8);
4286
4287 return false;
4288}
4289
Petr Hosek85b2f672016-09-23 21:53:36 +00004290/// parseDirectiveDS
4291/// ::= .ds.{b, d, l, p, s, w, x} expression
4292bool AsmParser::parseDirectiveDS(StringRef IDVal, unsigned Size) {
Petr Hosek85b2f672016-09-23 21:53:36 +00004293 SMLoc NumValuesLoc = Lexer.getLoc();
4294 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004295 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek85b2f672016-09-23 21:53:36 +00004296 return true;
4297
4298 if (NumValues < 0) {
4299 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4300 return false;
4301 }
4302
4303 if (parseToken(AsmToken::EndOfStatement,
4304 "unexpected token in '" + Twine(IDVal) + "' directive"))
4305 return true;
4306
4307 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4308 getStreamer().emitFill(Size, 0);
4309
4310 return false;
4311}
4312
Jim Grosbach4b905842013-09-20 23:08:21 +00004313/// parseDirectiveLEB128
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004314/// ::= (.sleb128 | .uleb128) [ expression (, expression)* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004315bool AsmParser::parseDirectiveLEB128(bool Signed) {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004316 if (checkForValidSection())
4317 return true;
4318
Nirav Dave1a9044b2016-10-24 14:35:29 +00004319 auto parseOp = [&]() -> bool {
4320 const MCExpr *Value;
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004321 if (parseExpression(Value))
4322 return true;
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004323 if (Signed)
4324 getStreamer().EmitSLEB128Value(Value);
4325 else
4326 getStreamer().EmitULEB128Value(Value);
Nirav Dave1a9044b2016-10-24 14:35:29 +00004327 return false;
4328 };
Eli Bendersky17233942013-01-15 22:59:42 +00004329
Nirav Dave1a9044b2016-10-24 14:35:29 +00004330 if (parseMany(parseOp))
4331 return addErrorSuffix(" in directive");
Eli Bendersky17233942013-01-15 22:59:42 +00004332
4333 return false;
4334}
4335
Jim Grosbach4b905842013-09-20 23:08:21 +00004336/// parseDirectiveSymbolAttribute
Daniel Dunbara5508c82009-06-30 00:33:19 +00004337/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004338bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00004339 auto parseOp = [&]() -> bool {
4340 StringRef Name;
4341 SMLoc Loc = getTok().getLoc();
4342 if (parseIdentifier(Name))
4343 return Error(Loc, "expected identifier");
4344 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004345
Nirav Dave1a9044b2016-10-24 14:35:29 +00004346 // Assembler local symbols don't make any sense here. Complain loudly.
4347 if (Sym->isTemporary())
4348 return Error(Loc, "non-local symbol required");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004349
Nirav Dave1a9044b2016-10-24 14:35:29 +00004350 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
4351 return Error(Loc, "unable to emit symbol attribute");
4352 return false;
4353 };
Daniel Dunbara5508c82009-06-30 00:33:19 +00004354
Nirav Dave1a9044b2016-10-24 14:35:29 +00004355 if (parseMany(parseOp))
4356 return addErrorSuffix(" in directive");
Jan Wen Voungc7682872010-09-30 01:09:20 +00004357 return false;
Daniel Dunbara5508c82009-06-30 00:33:19 +00004358}
Chris Lattnera1e11f52009-07-07 20:30:46 +00004359
Jim Grosbach4b905842013-09-20 23:08:21 +00004360/// parseDirectiveComm
Chris Lattner28ad7542009-07-09 17:25:12 +00004361/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004362bool AsmParser::parseDirectiveComm(bool IsLocal) {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004363 if (checkForValidSection())
4364 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00004365
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004366 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004367 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004368 if (parseIdentifier(Name))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004369 return TokError("expected identifier in directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004370
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +00004371 // Handle the identifier as the key symbol.
Jim Grosbach6f482002015-05-18 18:43:14 +00004372 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Chris Lattnera1e11f52009-07-07 20:30:46 +00004373
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004374 if (getLexer().isNot(AsmToken::Comma))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004375 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00004376 Lex();
Chris Lattnera1e11f52009-07-07 20:30:46 +00004377
4378 int64_t Size;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004379 SMLoc SizeLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004380 if (parseAbsoluteExpression(Size))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004381 return true;
4382
4383 int64_t Pow2Alignment = 0;
4384 SMLoc Pow2AlignmentLoc;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004385 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan686ed8d2010-01-19 20:22:31 +00004386 Lex();
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004387 Pow2AlignmentLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004388 if (parseAbsoluteExpression(Pow2Alignment))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004389 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00004390
Benjamin Kramer68b9f052012-09-07 21:08:01 +00004391 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
4392 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00004393 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
4394
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00004395 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramer68b9f052012-09-07 21:08:01 +00004396 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
4397 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00004398 if (!isPowerOf2_64(Pow2Alignment))
4399 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
4400 Pow2Alignment = Log2_64(Pow2Alignment);
4401 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00004402 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00004403
Nirav Dave1a9044b2016-10-24 14:35:29 +00004404 if (parseToken(AsmToken::EndOfStatement,
4405 "unexpected token in '.comm' or '.lcomm' directive"))
4406 return true;
Chris Lattnera1e11f52009-07-07 20:30:46 +00004407
Chris Lattner28ad7542009-07-09 17:25:12 +00004408 // NOTE: a size of zero for a .comm should create a undefined symbol
4409 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattnera1e11f52009-07-07 20:30:46 +00004410 if (Size < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00004411 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
Jim Grosbach4b905842013-09-20 23:08:21 +00004412 "be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00004413
Eric Christopherbc818852010-05-14 01:38:54 +00004414 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattnera1e11f52009-07-07 20:30:46 +00004415 // may internally end up wanting an alignment in bytes.
4416 // FIXME: Diagnose overflow.
4417 if (Pow2Alignment < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00004418 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
Jim Grosbach4b905842013-09-20 23:08:21 +00004419 "alignment, can't be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00004420
Rafael Espindola13a79bb2017-02-02 21:26:06 +00004421 Sym->redefineIfPossible();
Daniel Dunbar6860ac72009-08-22 07:22:36 +00004422 if (!Sym->isUndefined())
Chris Lattnera1e11f52009-07-07 20:30:46 +00004423 return Error(IDLoc, "invalid symbol redefinition");
4424
Chris Lattner28ad7542009-07-09 17:25:12 +00004425 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00004426 if (IsLocal) {
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00004427 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00004428 return false;
4429 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00004430
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004431 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattnera1e11f52009-07-07 20:30:46 +00004432 return false;
4433}
Chris Lattner07cadaf2009-07-10 22:20:30 +00004434
Jim Grosbach4b905842013-09-20 23:08:21 +00004435/// parseDirectiveAbort
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004436/// ::= .abort [... message ...]
Jim Grosbach4b905842013-09-20 23:08:21 +00004437bool AsmParser::parseDirectiveAbort() {
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004438 // FIXME: Use loc from directive.
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004439 SMLoc Loc = getLexer().getLoc();
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004440
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004441 StringRef Str = parseStringToEndOfStatement();
Nirav Davea645433c2016-07-18 15:24:03 +00004442 if (parseToken(AsmToken::EndOfStatement,
4443 "unexpected token in '.abort' directive"))
4444 return true;
Kevin Enderby56523ce2009-07-13 23:15:14 +00004445
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004446 if (Str.empty())
Nirav Dave2364748a2016-09-16 18:30:20 +00004447 return Error(Loc, ".abort detected. Assembly stopping.");
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004448 else
Nirav Dave2364748a2016-09-16 18:30:20 +00004449 return Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004450 // FIXME: Actually abort assembly here.
Kevin Enderby56523ce2009-07-13 23:15:14 +00004451
4452 return false;
4453}
Kevin Enderbycbe475d2009-07-14 21:35:03 +00004454
Jim Grosbach4b905842013-09-20 23:08:21 +00004455/// parseDirectiveInclude
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004456/// ::= .include "filename"
Jim Grosbach4b905842013-09-20 23:08:21 +00004457bool AsmParser::parseDirectiveInclude() {
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004458 // Allow the strings to have escaped octal character sequence.
4459 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00004460 SMLoc IncludeLoc = getTok().getLoc();
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004461
Nirav Davea645433c2016-07-18 15:24:03 +00004462 if (check(getTok().isNot(AsmToken::String),
4463 "expected string in '.include' directive") ||
4464 parseEscapedString(Filename) ||
4465 check(getTok().isNot(AsmToken::EndOfStatement),
4466 "unexpected token in '.include' directive") ||
4467 // Attempt to switch the lexer to the included file before consuming the
4468 // end of statement to avoid losing it when we switch.
4469 check(enterIncludeFile(Filename), IncludeLoc,
4470 "Could not find include file '" + Filename + "'"))
Chris Lattner693fbb82009-07-16 06:14:39 +00004471 return true;
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004472
4473 return false;
4474}
Kevin Enderby09ea5702009-07-15 15:30:11 +00004475
Jim Grosbach4b905842013-09-20 23:08:21 +00004476/// parseDirectiveIncbin
Petr Hosek2f4ac442016-09-23 00:41:06 +00004477/// ::= .incbin "filename" [ , skip [ , count ] ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004478bool AsmParser::parseDirectiveIncbin() {
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004479 // Allow the strings to have escaped octal character sequence.
4480 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00004481 SMLoc IncbinLoc = getTok().getLoc();
4482 if (check(getTok().isNot(AsmToken::String),
4483 "expected string in '.incbin' directive") ||
Petr Hosek2f4ac442016-09-23 00:41:06 +00004484 parseEscapedString(Filename))
4485 return true;
4486
4487 int64_t Skip = 0;
4488 const MCExpr *Count = nullptr;
4489 SMLoc SkipLoc, CountLoc;
Nirav Dave1a9044b2016-10-24 14:35:29 +00004490 if (parseOptionalToken(AsmToken::Comma)) {
Petr Hosek2f4ac442016-09-23 00:41:06 +00004491 // The skip expression can be omitted while specifying the count, e.g:
4492 // .incbin "filename",,4
4493 if (getTok().isNot(AsmToken::Comma)) {
4494 if (parseTokenLoc(SkipLoc) || parseAbsoluteExpression(Skip))
4495 return true;
4496 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00004497 if (parseOptionalToken(AsmToken::Comma)) {
4498 CountLoc = getTok().getLoc();
4499 if (parseExpression(Count))
Petr Hosek2f4ac442016-09-23 00:41:06 +00004500 return true;
4501 }
4502 }
4503
4504 if (parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00004505 "unexpected token in '.incbin' directive"))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004506 return true;
Nirav Dave1ab71992016-07-18 19:35:21 +00004507
Petr Hosek2f4ac442016-09-23 00:41:06 +00004508 if (check(Skip < 0, SkipLoc, "skip is negative"))
4509 return true;
4510
Nirav Dave1ab71992016-07-18 19:35:21 +00004511 // Attempt to process the included file.
Petr Hosek2f4ac442016-09-23 00:41:06 +00004512 if (processIncbinFile(Filename, Skip, Count, CountLoc))
Nirav Dave1ab71992016-07-18 19:35:21 +00004513 return Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
Kevin Enderby109f25c2011-12-14 21:47:48 +00004514 return false;
4515}
4516
Jim Grosbach4b905842013-09-20 23:08:21 +00004517/// parseDirectiveIf
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004518/// ::= .if{,eq,ge,gt,le,lt,ne} expression
4519bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004520 TheCondStack.push_back(TheCondState);
4521 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004522 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004523 eatToEndOfStatement();
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004524 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004525 int64_t ExprValue;
Nirav Davea645433c2016-07-18 15:24:03 +00004526 if (parseAbsoluteExpression(ExprValue) ||
4527 parseToken(AsmToken::EndOfStatement,
4528 "unexpected token in '.if' directive"))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004529 return true;
4530
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004531 switch (DirKind) {
4532 default:
4533 llvm_unreachable("unsupported directive");
4534 case DK_IF:
4535 case DK_IFNE:
4536 break;
4537 case DK_IFEQ:
4538 ExprValue = ExprValue == 0;
4539 break;
4540 case DK_IFGE:
4541 ExprValue = ExprValue >= 0;
4542 break;
4543 case DK_IFGT:
4544 ExprValue = ExprValue > 0;
4545 break;
4546 case DK_IFLE:
4547 ExprValue = ExprValue <= 0;
4548 break;
4549 case DK_IFLT:
4550 ExprValue = ExprValue < 0;
4551 break;
4552 }
4553
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004554 TheCondState.CondMet = ExprValue;
4555 TheCondState.Ignore = !TheCondState.CondMet;
4556 }
4557
4558 return false;
4559}
4560
Jim Grosbach4b905842013-09-20 23:08:21 +00004561/// parseDirectiveIfb
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004562/// ::= .ifb string
Jim Grosbach4b905842013-09-20 23:08:21 +00004563bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004564 TheCondStack.push_back(TheCondState);
4565 TheCondState.TheCond = AsmCond::IfCond;
4566
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004567 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004568 eatToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004569 } else {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004570 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004571
Nirav Davea645433c2016-07-18 15:24:03 +00004572 if (parseToken(AsmToken::EndOfStatement,
4573 "unexpected token in '.ifb' directive"))
4574 return true;
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004575
4576 TheCondState.CondMet = ExpectBlank == Str.empty();
4577 TheCondState.Ignore = !TheCondState.CondMet;
4578 }
4579
4580 return false;
4581}
4582
Jim Grosbach4b905842013-09-20 23:08:21 +00004583/// parseDirectiveIfc
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004584/// ::= .ifc string1, string2
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00004585/// ::= .ifnc string1, string2
Jim Grosbach4b905842013-09-20 23:08:21 +00004586bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004587 TheCondStack.push_back(TheCondState);
4588 TheCondState.TheCond = AsmCond::IfCond;
4589
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004590 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004591 eatToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004592 } else {
Jim Grosbach4b905842013-09-20 23:08:21 +00004593 StringRef Str1 = parseStringToComma();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004594
Nirav Davea645433c2016-07-18 15:24:03 +00004595 if (parseToken(AsmToken::Comma, "unexpected token in '.ifc' directive"))
4596 return true;
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004597
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004598 StringRef Str2 = parseStringToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004599
Nirav Davea645433c2016-07-18 15:24:03 +00004600 if (parseToken(AsmToken::EndOfStatement,
4601 "unexpected token in '.ifc' directive"))
4602 return true;
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004603
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00004604 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004605 TheCondState.Ignore = !TheCondState.CondMet;
4606 }
4607
4608 return false;
4609}
4610
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004611/// parseDirectiveIfeqs
4612/// ::= .ifeqs string1, string2
Sid Manning51c35602015-03-18 14:20:54 +00004613bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual) {
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004614 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00004615 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00004616 return TokError("expected string parameter for '.ifeqs' directive");
4617 return TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004618 }
4619
4620 StringRef String1 = getTok().getStringContents();
4621 Lex();
4622
4623 if (Lexer.isNot(AsmToken::Comma)) {
Sid Manning51c35602015-03-18 14:20:54 +00004624 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00004625 return TokError(
4626 "expected comma after first string for '.ifeqs' directive");
4627 return TokError("expected comma after first string for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004628 }
4629
4630 Lex();
4631
4632 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00004633 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00004634 return TokError("expected string parameter for '.ifeqs' directive");
4635 return TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004636 }
4637
4638 StringRef String2 = getTok().getStringContents();
4639 Lex();
4640
4641 TheCondStack.push_back(TheCondState);
4642 TheCondState.TheCond = AsmCond::IfCond;
Sid Manning51c35602015-03-18 14:20:54 +00004643 TheCondState.CondMet = ExpectEqual == (String1 == String2);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004644 TheCondState.Ignore = !TheCondState.CondMet;
4645
4646 return false;
4647}
4648
Jim Grosbach4b905842013-09-20 23:08:21 +00004649/// parseDirectiveIfdef
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004650/// ::= .ifdef symbol
Jim Grosbach4b905842013-09-20 23:08:21 +00004651bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004652 StringRef Name;
4653 TheCondStack.push_back(TheCondState);
4654 TheCondState.TheCond = AsmCond::IfCond;
4655
4656 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004657 eatToEndOfStatement();
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004658 } else {
Nirav Davea645433c2016-07-18 15:24:03 +00004659 if (check(parseIdentifier(Name), "expected identifier after '.ifdef'") ||
4660 parseToken(AsmToken::EndOfStatement, "unexpected token in '.ifdef'"))
4661 return true;
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004662
Jim Grosbach6f482002015-05-18 18:43:14 +00004663 MCSymbol *Sym = getContext().lookupSymbol(Name);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004664
4665 if (expect_defined)
Craig Topper353eda42014-04-24 06:44:33 +00004666 TheCondState.CondMet = (Sym && !Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004667 else
Craig Topper353eda42014-04-24 06:44:33 +00004668 TheCondState.CondMet = (!Sym || Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004669 TheCondState.Ignore = !TheCondState.CondMet;
4670 }
4671
4672 return false;
4673}
4674
Jim Grosbach4b905842013-09-20 23:08:21 +00004675/// parseDirectiveElseIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004676/// ::= .elseif expression
Jim Grosbach4b905842013-09-20 23:08:21 +00004677bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004678 if (TheCondState.TheCond != AsmCond::IfCond &&
4679 TheCondState.TheCond != AsmCond::ElseIfCond)
Nirav Dave2364748a2016-09-16 18:30:20 +00004680 return Error(DirectiveLoc, "Encountered a .elseif that doesn't follow an"
4681 " .if or an .elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004682 TheCondState.TheCond = AsmCond::ElseIfCond;
4683
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004684 bool LastIgnoreState = false;
4685 if (!TheCondStack.empty())
Craig Topper2172ad62013-04-22 04:24:02 +00004686 LastIgnoreState = TheCondStack.back().Ignore;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004687 if (LastIgnoreState || TheCondState.CondMet) {
4688 TheCondState.Ignore = true;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004689 eatToEndOfStatement();
Craig Topperf15655b2013-04-22 04:22:40 +00004690 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004691 int64_t ExprValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004692 if (parseAbsoluteExpression(ExprValue))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004693 return true;
4694
Nirav Dave1a9044b2016-10-24 14:35:29 +00004695 if (parseToken(AsmToken::EndOfStatement,
4696 "unexpected token in '.elseif' directive"))
4697 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00004698
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004699 TheCondState.CondMet = ExprValue;
4700 TheCondState.Ignore = !TheCondState.CondMet;
4701 }
4702
4703 return false;
4704}
4705
Jim Grosbach4b905842013-09-20 23:08:21 +00004706/// parseDirectiveElse
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004707/// ::= .else
Jim Grosbach4b905842013-09-20 23:08:21 +00004708bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00004709 if (parseToken(AsmToken::EndOfStatement,
4710 "unexpected token in '.else' directive"))
4711 return true;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004712
4713 if (TheCondState.TheCond != AsmCond::IfCond &&
4714 TheCondState.TheCond != AsmCond::ElseIfCond)
Nirav Dave2364748a2016-09-16 18:30:20 +00004715 return Error(DirectiveLoc, "Encountered a .else that doesn't follow "
4716 " an .if or an .elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004717 TheCondState.TheCond = AsmCond::ElseCond;
4718 bool LastIgnoreState = false;
4719 if (!TheCondStack.empty())
4720 LastIgnoreState = TheCondStack.back().Ignore;
4721 if (LastIgnoreState || TheCondState.CondMet)
4722 TheCondState.Ignore = true;
4723 else
4724 TheCondState.Ignore = false;
4725
4726 return false;
4727}
4728
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004729/// parseDirectiveEnd
4730/// ::= .end
4731bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00004732 if (parseToken(AsmToken::EndOfStatement,
4733 "unexpected token in '.end' directive"))
4734 return true;
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004735
4736 while (Lexer.isNot(AsmToken::Eof))
Nirav Dave1a9044b2016-10-24 14:35:29 +00004737 Lexer.Lex();
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004738
4739 return false;
4740}
4741
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004742/// parseDirectiveError
4743/// ::= .err
4744/// ::= .error [string]
4745bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
4746 if (!TheCondStack.empty()) {
4747 if (TheCondStack.back().Ignore) {
4748 eatToEndOfStatement();
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004749 return false;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004750 }
4751 }
4752
4753 if (!WithMessage)
4754 return Error(L, ".err encountered");
4755
4756 StringRef Message = ".error directive invoked in source file";
4757 if (Lexer.isNot(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00004758 if (Lexer.isNot(AsmToken::String))
4759 return TokError(".error argument must be a string");
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004760
4761 Message = getTok().getStringContents();
4762 Lex();
4763 }
4764
Nirav Dave2364748a2016-09-16 18:30:20 +00004765 return Error(L, Message);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004766}
4767
Nico Weber404012b2014-07-24 16:26:06 +00004768/// parseDirectiveWarning
4769/// ::= .warning [string]
4770bool AsmParser::parseDirectiveWarning(SMLoc L) {
4771 if (!TheCondStack.empty()) {
4772 if (TheCondStack.back().Ignore) {
4773 eatToEndOfStatement();
4774 return false;
4775 }
4776 }
4777
4778 StringRef Message = ".warning directive invoked in source file";
Nirav Dave1a9044b2016-10-24 14:35:29 +00004779
4780 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00004781 if (Lexer.isNot(AsmToken::String))
4782 return TokError(".warning argument must be a string");
Nico Weber404012b2014-07-24 16:26:06 +00004783
4784 Message = getTok().getStringContents();
4785 Lex();
Nirav Dave1a9044b2016-10-24 14:35:29 +00004786 if (parseToken(AsmToken::EndOfStatement,
4787 "expected end of statement in '.warning' directive"))
4788 return true;
Nico Weber404012b2014-07-24 16:26:06 +00004789 }
4790
Nirav Dave2364748a2016-09-16 18:30:20 +00004791 return Warning(L, Message);
Nico Weber404012b2014-07-24 16:26:06 +00004792}
4793
Jim Grosbach4b905842013-09-20 23:08:21 +00004794/// parseDirectiveEndIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004795/// ::= .endif
Jim Grosbach4b905842013-09-20 23:08:21 +00004796bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00004797 if (parseToken(AsmToken::EndOfStatement,
4798 "unexpected token in '.endif' directive"))
4799 return true;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004800
Jim Grosbach4b905842013-09-20 23:08:21 +00004801 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
Nirav Dave2364748a2016-09-16 18:30:20 +00004802 return Error(DirectiveLoc, "Encountered a .endif that doesn't follow "
4803 "an .if or .else");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004804 if (!TheCondStack.empty()) {
4805 TheCondState = TheCondStack.back();
4806 TheCondStack.pop_back();
4807 }
4808
4809 return false;
4810}
Daniel Dunbara4b069c2009-08-11 04:24:50 +00004811
Eli Bendersky17233942013-01-15 22:59:42 +00004812void AsmParser::initializeDirectiveKindMap() {
4813 DirectiveKindMap[".set"] = DK_SET;
4814 DirectiveKindMap[".equ"] = DK_EQU;
4815 DirectiveKindMap[".equiv"] = DK_EQUIV;
4816 DirectiveKindMap[".ascii"] = DK_ASCII;
4817 DirectiveKindMap[".asciz"] = DK_ASCIZ;
4818 DirectiveKindMap[".string"] = DK_STRING;
4819 DirectiveKindMap[".byte"] = DK_BYTE;
4820 DirectiveKindMap[".short"] = DK_SHORT;
4821 DirectiveKindMap[".value"] = DK_VALUE;
4822 DirectiveKindMap[".2byte"] = DK_2BYTE;
4823 DirectiveKindMap[".long"] = DK_LONG;
4824 DirectiveKindMap[".int"] = DK_INT;
4825 DirectiveKindMap[".4byte"] = DK_4BYTE;
4826 DirectiveKindMap[".quad"] = DK_QUAD;
4827 DirectiveKindMap[".8byte"] = DK_8BYTE;
David Woodhoused6de0d92014-02-01 16:20:59 +00004828 DirectiveKindMap[".octa"] = DK_OCTA;
Eli Bendersky17233942013-01-15 22:59:42 +00004829 DirectiveKindMap[".single"] = DK_SINGLE;
4830 DirectiveKindMap[".float"] = DK_FLOAT;
4831 DirectiveKindMap[".double"] = DK_DOUBLE;
4832 DirectiveKindMap[".align"] = DK_ALIGN;
4833 DirectiveKindMap[".align32"] = DK_ALIGN32;
4834 DirectiveKindMap[".balign"] = DK_BALIGN;
4835 DirectiveKindMap[".balignw"] = DK_BALIGNW;
4836 DirectiveKindMap[".balignl"] = DK_BALIGNL;
4837 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
4838 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
4839 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
4840 DirectiveKindMap[".org"] = DK_ORG;
4841 DirectiveKindMap[".fill"] = DK_FILL;
4842 DirectiveKindMap[".zero"] = DK_ZERO;
4843 DirectiveKindMap[".extern"] = DK_EXTERN;
4844 DirectiveKindMap[".globl"] = DK_GLOBL;
4845 DirectiveKindMap[".global"] = DK_GLOBAL;
Eli Bendersky17233942013-01-15 22:59:42 +00004846 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
4847 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
4848 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
4849 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
4850 DirectiveKindMap[".reference"] = DK_REFERENCE;
4851 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
4852 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
4853 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
4854 DirectiveKindMap[".comm"] = DK_COMM;
4855 DirectiveKindMap[".common"] = DK_COMMON;
4856 DirectiveKindMap[".lcomm"] = DK_LCOMM;
4857 DirectiveKindMap[".abort"] = DK_ABORT;
4858 DirectiveKindMap[".include"] = DK_INCLUDE;
4859 DirectiveKindMap[".incbin"] = DK_INCBIN;
4860 DirectiveKindMap[".code16"] = DK_CODE16;
4861 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
4862 DirectiveKindMap[".rept"] = DK_REPT;
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00004863 DirectiveKindMap[".rep"] = DK_REPT;
Eli Bendersky17233942013-01-15 22:59:42 +00004864 DirectiveKindMap[".irp"] = DK_IRP;
4865 DirectiveKindMap[".irpc"] = DK_IRPC;
4866 DirectiveKindMap[".endr"] = DK_ENDR;
4867 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
4868 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
4869 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
4870 DirectiveKindMap[".if"] = DK_IF;
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004871 DirectiveKindMap[".ifeq"] = DK_IFEQ;
4872 DirectiveKindMap[".ifge"] = DK_IFGE;
4873 DirectiveKindMap[".ifgt"] = DK_IFGT;
4874 DirectiveKindMap[".ifle"] = DK_IFLE;
4875 DirectiveKindMap[".iflt"] = DK_IFLT;
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00004876 DirectiveKindMap[".ifne"] = DK_IFNE;
Eli Bendersky17233942013-01-15 22:59:42 +00004877 DirectiveKindMap[".ifb"] = DK_IFB;
4878 DirectiveKindMap[".ifnb"] = DK_IFNB;
4879 DirectiveKindMap[".ifc"] = DK_IFC;
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004880 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
Eli Bendersky17233942013-01-15 22:59:42 +00004881 DirectiveKindMap[".ifnc"] = DK_IFNC;
Sid Manning51c35602015-03-18 14:20:54 +00004882 DirectiveKindMap[".ifnes"] = DK_IFNES;
Eli Bendersky17233942013-01-15 22:59:42 +00004883 DirectiveKindMap[".ifdef"] = DK_IFDEF;
4884 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
4885 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
4886 DirectiveKindMap[".elseif"] = DK_ELSEIF;
4887 DirectiveKindMap[".else"] = DK_ELSE;
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004888 DirectiveKindMap[".end"] = DK_END;
Eli Bendersky17233942013-01-15 22:59:42 +00004889 DirectiveKindMap[".endif"] = DK_ENDIF;
4890 DirectiveKindMap[".skip"] = DK_SKIP;
4891 DirectiveKindMap[".space"] = DK_SPACE;
4892 DirectiveKindMap[".file"] = DK_FILE;
4893 DirectiveKindMap[".line"] = DK_LINE;
4894 DirectiveKindMap[".loc"] = DK_LOC;
4895 DirectiveKindMap[".stabs"] = DK_STABS;
Reid Kleckner2214ed82016-01-29 00:49:42 +00004896 DirectiveKindMap[".cv_file"] = DK_CV_FILE;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00004897 DirectiveKindMap[".cv_func_id"] = DK_CV_FUNC_ID;
Reid Kleckner2214ed82016-01-29 00:49:42 +00004898 DirectiveKindMap[".cv_loc"] = DK_CV_LOC;
4899 DirectiveKindMap[".cv_linetable"] = DK_CV_LINETABLE;
David Majnemer6fcbd7e2016-01-29 19:24:12 +00004900 DirectiveKindMap[".cv_inline_linetable"] = DK_CV_INLINE_LINETABLE;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00004901 DirectiveKindMap[".cv_inline_site_id"] = DK_CV_INLINE_SITE_ID;
David Majnemer408b5e62016-02-05 01:55:49 +00004902 DirectiveKindMap[".cv_def_range"] = DK_CV_DEF_RANGE;
Reid Kleckner2214ed82016-01-29 00:49:42 +00004903 DirectiveKindMap[".cv_stringtable"] = DK_CV_STRINGTABLE;
4904 DirectiveKindMap[".cv_filechecksums"] = DK_CV_FILECHECKSUMS;
Eli Bendersky17233942013-01-15 22:59:42 +00004905 DirectiveKindMap[".sleb128"] = DK_SLEB128;
4906 DirectiveKindMap[".uleb128"] = DK_ULEB128;
4907 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
4908 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
4909 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
4910 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
4911 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
4912 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
4913 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
4914 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
4915 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
4916 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
4917 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
4918 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
4919 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
4920 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
4921 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
4922 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
4923 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
4924 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
4925 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00004926 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
Eli Bendersky17233942013-01-15 22:59:42 +00004927 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
4928 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
4929 DirectiveKindMap[".macro"] = DK_MACRO;
Nico Weber155dccd12014-07-24 17:08:39 +00004930 DirectiveKindMap[".exitm"] = DK_EXITM;
Eli Bendersky17233942013-01-15 22:59:42 +00004931 DirectiveKindMap[".endm"] = DK_ENDM;
4932 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
4933 DirectiveKindMap[".purgem"] = DK_PURGEM;
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004934 DirectiveKindMap[".err"] = DK_ERR;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004935 DirectiveKindMap[".error"] = DK_ERROR;
Nico Weber404012b2014-07-24 16:26:06 +00004936 DirectiveKindMap[".warning"] = DK_WARNING;
Daniel Sanders9f6ad492015-11-12 13:33:00 +00004937 DirectiveKindMap[".reloc"] = DK_RELOC;
Petr Hosek731bb9c2016-08-23 21:34:53 +00004938 DirectiveKindMap[".dc"] = DK_DC;
4939 DirectiveKindMap[".dc.a"] = DK_DC_A;
4940 DirectiveKindMap[".dc.b"] = DK_DC_B;
4941 DirectiveKindMap[".dc.d"] = DK_DC_D;
4942 DirectiveKindMap[".dc.l"] = DK_DC_L;
4943 DirectiveKindMap[".dc.s"] = DK_DC_S;
4944 DirectiveKindMap[".dc.w"] = DK_DC_W;
4945 DirectiveKindMap[".dc.x"] = DK_DC_X;
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004946 DirectiveKindMap[".dcb"] = DK_DCB;
4947 DirectiveKindMap[".dcb.b"] = DK_DCB_B;
4948 DirectiveKindMap[".dcb.d"] = DK_DCB_D;
4949 DirectiveKindMap[".dcb.l"] = DK_DCB_L;
4950 DirectiveKindMap[".dcb.s"] = DK_DCB_S;
4951 DirectiveKindMap[".dcb.w"] = DK_DCB_W;
4952 DirectiveKindMap[".dcb.x"] = DK_DCB_X;
Petr Hosek85b2f672016-09-23 21:53:36 +00004953 DirectiveKindMap[".ds"] = DK_DS;
4954 DirectiveKindMap[".ds.b"] = DK_DS_B;
4955 DirectiveKindMap[".ds.d"] = DK_DS_D;
4956 DirectiveKindMap[".ds.l"] = DK_DS_L;
4957 DirectiveKindMap[".ds.p"] = DK_DS_P;
4958 DirectiveKindMap[".ds.s"] = DK_DS_S;
4959 DirectiveKindMap[".ds.w"] = DK_DS_W;
4960 DirectiveKindMap[".ds.x"] = DK_DS_X;
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00004961}
4962
Jim Grosbach4b905842013-09-20 23:08:21 +00004963MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004964 AsmToken EndToken, StartToken = getTok();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004965
Rafael Espindola34b9c512012-06-03 23:57:14 +00004966 unsigned NestLevel = 0;
Eugene Zelenko33d7b762016-08-23 17:14:32 +00004967 while (true) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004968 // Check whether we have reached the end of the file.
Rafael Espindola34b9c512012-06-03 23:57:14 +00004969 if (getLexer().is(AsmToken::Eof)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00004970 printError(DirectiveLoc, "no matching '.endr' in definition");
Craig Topper353eda42014-04-24 06:44:33 +00004971 return nullptr;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004972 }
4973
Rafael Espindola34b9c512012-06-03 23:57:14 +00004974 if (Lexer.is(AsmToken::Identifier) &&
Nikolay Haustov95b4fcd2016-03-01 08:18:28 +00004975 (getTok().getIdentifier() == ".rept" ||
4976 getTok().getIdentifier() == ".irp" ||
4977 getTok().getIdentifier() == ".irpc")) {
Rafael Espindola34b9c512012-06-03 23:57:14 +00004978 ++NestLevel;
4979 }
4980
4981 // Otherwise, check whether we have reached the .endr.
Jim Grosbach4b905842013-09-20 23:08:21 +00004982 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
Rafael Espindola34b9c512012-06-03 23:57:14 +00004983 if (NestLevel == 0) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004984 EndToken = getTok();
4985 Lex();
Rafael Espindola34b9c512012-06-03 23:57:14 +00004986 if (Lexer.isNot(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00004987 printError(getTok().getLoc(),
4988 "unexpected token in '.endr' directive");
Craig Topper353eda42014-04-24 06:44:33 +00004989 return nullptr;
Rafael Espindola34b9c512012-06-03 23:57:14 +00004990 }
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004991 break;
4992 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00004993 --NestLevel;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004994 }
4995
Rafael Espindola34b9c512012-06-03 23:57:14 +00004996 // Otherwise, scan till the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004997 eatToEndOfStatement();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004998 }
4999
5000 const char *BodyStart = StartToken.getLoc().getPointer();
5001 const char *BodyEnd = EndToken.getLoc().getPointer();
5002 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
5003
Rafael Espindola34b9c512012-06-03 23:57:14 +00005004 // We Are Anonymous.
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00005005 MacroLikeBodies.emplace_back(StringRef(), Body, MCAsmMacroParameters());
Benjamin Kramer1df3a1f2013-08-04 09:06:29 +00005006 return &MacroLikeBodies.back();
Rafael Espindola34b9c512012-06-03 23:57:14 +00005007}
5008
Jim Grosbach4b905842013-09-20 23:08:21 +00005009void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +00005010 raw_svector_ostream &OS) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005011 OS << ".endr\n";
5012
Rafael Espindola3560ff22014-08-27 20:03:13 +00005013 std::unique_ptr<MemoryBuffer> Instantiation =
5014 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005015
Rafael Espindola34b9c512012-06-03 23:57:14 +00005016 // Create the macro instantiation object and add to the current macro
5017 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00005018 MacroInstantiation *MI = new MacroInstantiation(
5019 DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Rafael Espindola34b9c512012-06-03 23:57:14 +00005020 ActiveMacros.push_back(MI);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005021
Rafael Espindola34b9c512012-06-03 23:57:14 +00005022 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00005023 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00005024 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Rafael Espindola34b9c512012-06-03 23:57:14 +00005025 Lex();
5026}
5027
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00005028/// parseDirectiveRept
5029/// ::= .rep | .rept count
5030bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00005031 const MCExpr *CountExpr;
5032 SMLoc CountLoc = getTok().getLoc();
5033 if (parseExpression(CountExpr))
5034 return true;
5035
Rafael Espindola34b9c512012-06-03 23:57:14 +00005036 int64_t Count;
Jim Grosbach13760bd2015-05-30 01:25:56 +00005037 if (!CountExpr->evaluateAsAbsolute(Count)) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00005038 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
5039 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00005040
Nirav Davea645433c2016-07-18 15:24:03 +00005041 if (check(Count < 0, CountLoc, "Count is negative") ||
5042 parseToken(AsmToken::EndOfStatement,
5043 "unexpected token in '" + Dir + "' directive"))
5044 return true;
Rafael Espindola34b9c512012-06-03 23:57:14 +00005045
5046 // Lex the rept definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005047 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola34b9c512012-06-03 23:57:14 +00005048 if (!M)
5049 return true;
5050
5051 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5052 // to hold the macro body with substitutions.
5053 SmallString<256> Buf;
Rafael Espindola34b9c512012-06-03 23:57:14 +00005054 raw_svector_ostream OS(Buf);
5055 while (Count--) {
Toma Tabacu217116e2015-04-27 10:50:29 +00005056 // Note that the AtPseudoVariable is disabled for instantiations of .rep(t).
5057 if (expandMacro(OS, M->Body, None, None, false, getTok().getLoc()))
Rafael Espindola34b9c512012-06-03 23:57:14 +00005058 return true;
5059 }
Jim Grosbach4b905842013-09-20 23:08:21 +00005060 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005061
5062 return false;
5063}
5064
Jim Grosbach4b905842013-09-20 23:08:21 +00005065/// parseDirectiveIrp
Rafael Espindola768b41c2012-06-15 14:02:34 +00005066/// ::= .irp symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00005067bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00005068 MCAsmMacroParameter Parameter;
Eli Bendersky38274122013-01-14 23:22:36 +00005069 MCAsmMacroArguments A;
Nirav Davea645433c2016-07-18 15:24:03 +00005070 if (check(parseIdentifier(Parameter.Name),
5071 "expected identifier in '.irp' directive") ||
5072 parseToken(AsmToken::Comma, "expected comma in '.irp' directive") ||
5073 parseMacroArguments(nullptr, A) ||
5074 parseToken(AsmToken::EndOfStatement, "expected End of Statement"))
Rafael Espindola768b41c2012-06-15 14:02:34 +00005075 return true;
5076
Rafael Espindola768b41c2012-06-15 14:02:34 +00005077 // Lex the irp definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005078 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola768b41c2012-06-15 14:02:34 +00005079 if (!M)
5080 return true;
5081
5082 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5083 // to hold the macro body with substitutions.
5084 SmallString<256> Buf;
5085 raw_svector_ostream OS(Buf);
5086
Craig Topper84008482015-10-10 05:38:14 +00005087 for (const MCAsmMacroArgument &Arg : A) {
Toma Tabacu217116e2015-04-27 10:50:29 +00005088 // Note that the AtPseudoVariable is enabled for instantiations of .irp.
5089 // This is undocumented, but GAS seems to support it.
Craig Topper84008482015-10-10 05:38:14 +00005090 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindola768b41c2012-06-15 14:02:34 +00005091 return true;
5092 }
5093
Jim Grosbach4b905842013-09-20 23:08:21 +00005094 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola768b41c2012-06-15 14:02:34 +00005095
5096 return false;
5097}
5098
Jim Grosbach4b905842013-09-20 23:08:21 +00005099/// parseDirectiveIrpc
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005100/// ::= .irpc symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00005101bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00005102 MCAsmMacroParameter Parameter;
Eli Bendersky38274122013-01-14 23:22:36 +00005103 MCAsmMacroArguments A;
Nirav Davea645433c2016-07-18 15:24:03 +00005104
5105 if (check(parseIdentifier(Parameter.Name),
5106 "expected identifier in '.irpc' directive") ||
5107 parseToken(AsmToken::Comma, "expected comma in '.irpc' directive") ||
5108 parseMacroArguments(nullptr, A))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005109 return true;
5110
5111 if (A.size() != 1 || A.front().size() != 1)
5112 return TokError("unexpected token in '.irpc' directive");
5113
5114 // Eat the end of statement.
Nirav Davea645433c2016-07-18 15:24:03 +00005115 if (parseToken(AsmToken::EndOfStatement, "expected end of statement"))
5116 return true;
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005117
5118 // Lex the irpc definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005119 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005120 if (!M)
5121 return true;
5122
5123 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5124 // to hold the macro body with substitutions.
5125 SmallString<256> Buf;
5126 raw_svector_ostream OS(Buf);
5127
5128 StringRef Values = A.front().front().getString();
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00005129 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
Eli Benderskya7b905e2013-01-14 19:00:26 +00005130 MCAsmMacroArgument Arg;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00005131 Arg.emplace_back(AsmToken::Identifier, Values.slice(I, I + 1));
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005132
Toma Tabacu217116e2015-04-27 10:50:29 +00005133 // Note that the AtPseudoVariable is enabled for instantiations of .irpc.
5134 // This is undocumented, but GAS seems to support it.
5135 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005136 return true;
5137 }
5138
Jim Grosbach4b905842013-09-20 23:08:21 +00005139 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005140
5141 return false;
5142}
5143
Jim Grosbach4b905842013-09-20 23:08:21 +00005144bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
Rafael Espindola34b9c512012-06-03 23:57:14 +00005145 if (ActiveMacros.empty())
Preston Gurdeb3ebf12012-09-19 20:23:43 +00005146 return TokError("unmatched '.endr' directive");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005147
5148 // The only .repl that should get here are the ones created by
Jim Grosbach4b905842013-09-20 23:08:21 +00005149 // instantiateMacroLikeBody.
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005150 assert(getLexer().is(AsmToken::EndOfStatement));
5151
Jim Grosbach4b905842013-09-20 23:08:21 +00005152 handleMacroExit();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005153 return false;
5154}
Rafael Espindola12d73d12010-09-11 16:45:15 +00005155
Jim Grosbach4b905842013-09-20 23:08:21 +00005156bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
Benjamin Kramer1a136112013-02-15 20:37:21 +00005157 size_t Len) {
Eli Friedman0f4871d2012-10-22 23:58:19 +00005158 const MCExpr *Value;
5159 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005160 if (parseExpression(Value))
Eli Friedman0f4871d2012-10-22 23:58:19 +00005161 return true;
5162 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5163 if (!MCE)
5164 return Error(ExprLoc, "unexpected expression in _emit");
5165 uint64_t IntValue = MCE->getValue();
Craig Topper55b1f292015-10-10 20:17:07 +00005166 if (!isUInt<8>(IntValue) && !isInt<8>(IntValue))
Eli Friedman0f4871d2012-10-22 23:58:19 +00005167 return Error(ExprLoc, "literal value out of range for directive");
5168
Craig Topper7d5b2312015-10-10 05:25:02 +00005169 Info.AsmRewrites->emplace_back(AOK_Emit, IDLoc, Len);
Chad Rosierc7f552c2013-02-12 21:33:51 +00005170 return false;
5171}
5172
Jim Grosbach4b905842013-09-20 23:08:21 +00005173bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
Chad Rosierc7f552c2013-02-12 21:33:51 +00005174 const MCExpr *Value;
5175 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005176 if (parseExpression(Value))
Chad Rosierc7f552c2013-02-12 21:33:51 +00005177 return true;
5178 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5179 if (!MCE)
5180 return Error(ExprLoc, "unexpected expression in align");
5181 uint64_t IntValue = MCE->getValue();
5182 if (!isPowerOf2_64(IntValue))
5183 return Error(ExprLoc, "literal value not a power of two greater then zero");
5184
Craig Topper7d5b2312015-10-10 05:25:02 +00005185 Info.AsmRewrites->emplace_back(AOK_Align, IDLoc, 5, Log2_64(IntValue));
Eli Friedman0f4871d2012-10-22 23:58:19 +00005186 return false;
5187}
5188
Chad Rosierf43fcf52013-02-13 21:27:17 +00005189// We are comparing pointers, but the pointers are relative to a single string.
5190// Thus, this should always be deterministic.
Benjamin Kramer8817cca2013-09-22 14:09:50 +00005191static int rewritesSort(const AsmRewrite *AsmRewriteA,
5192 const AsmRewrite *AsmRewriteB) {
Chad Rosiereb5c1682013-02-13 18:38:58 +00005193 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
5194 return -1;
5195 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
5196 return 1;
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005197
Chad Rosierfce4fab2013-04-08 17:43:47 +00005198 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
5199 // rewrite to the same location. Make sure the SizeDirective rewrite is
5200 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
5201 // ensures the sort algorithm is stable.
Jim Grosbach4b905842013-09-20 23:08:21 +00005202 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
5203 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005204 return -1;
Chad Rosierfce4fab2013-04-08 17:43:47 +00005205
Jim Grosbach4b905842013-09-20 23:08:21 +00005206 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
5207 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005208 return 1;
Jim Grosbach4b905842013-09-20 23:08:21 +00005209 llvm_unreachable("Unstable rewrite sort.");
Chad Rosierb2144ce2013-02-13 01:03:13 +00005210}
5211
Jim Grosbach4b905842013-09-20 23:08:21 +00005212bool AsmParser::parseMSInlineAsm(
5213 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00005214 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool>> &OpDecls,
Jim Grosbach4b905842013-09-20 23:08:21 +00005215 SmallVectorImpl<std::string> &Constraints,
5216 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
5217 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
Chad Rosier37e755c2012-10-23 17:43:43 +00005218 SmallVector<void *, 4> InputDecls;
5219 SmallVector<void *, 4> OutputDecls;
Chad Rosiera4bc9432013-01-10 22:10:27 +00005220 SmallVector<bool, 4> InputDeclsAddressOf;
5221 SmallVector<bool, 4> OutputDeclsAddressOf;
Chad Rosier8bce6642012-10-18 15:49:34 +00005222 SmallVector<std::string, 4> InputConstraints;
5223 SmallVector<std::string, 4> OutputConstraints;
Benjamin Kramer1a136112013-02-15 20:37:21 +00005224 SmallVector<unsigned, 4> ClobberRegs;
Chad Rosier8bce6642012-10-18 15:49:34 +00005225
Benjamin Kramer1a136112013-02-15 20:37:21 +00005226 SmallVector<AsmRewrite, 4> AsmStrRewrites;
Chad Rosier8bce6642012-10-18 15:49:34 +00005227
5228 // Prime the lexer.
5229 Lex();
5230
5231 // While we have input, parse each statement.
5232 unsigned InputIdx = 0;
5233 unsigned OutputIdx = 0;
5234 while (getLexer().isNot(AsmToken::Eof)) {
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00005235 // Parse curly braces marking block start/end
5236 if (parseCurlyBlockScope(AsmStrRewrites))
5237 continue;
5238
Eli Friedman0f4871d2012-10-22 23:58:19 +00005239 ParseStatementInfo Info(&AsmStrRewrites);
Nirav Dave2364748a2016-09-16 18:30:20 +00005240 bool StatementErr = parseStatement(Info, &SI);
Nirav Dave9fa8af22016-09-13 13:55:06 +00005241
Nirav Dave2364748a2016-09-16 18:30:20 +00005242 if (StatementErr || Info.ParseError) {
5243 // Emit pending errors if any exist.
5244 printPendingErrors();
Nico Webere204c482016-09-13 18:17:00 +00005245 return true;
Nirav Dave2364748a2016-09-16 18:30:20 +00005246 }
5247
5248 // No pending error should exist here.
5249 assert(!hasPendingError() && "unexpected error from parseStatement");
Chad Rosier149e8e02012-12-12 22:45:52 +00005250
Benjamin Kramer1a136112013-02-15 20:37:21 +00005251 if (Info.Opcode == ~0U)
5252 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00005253
Benjamin Kramer1a136112013-02-15 20:37:21 +00005254 const MCInstrDesc &Desc = MII->get(Info.Opcode);
Chad Rosier8bce6642012-10-18 15:49:34 +00005255
Benjamin Kramer1a136112013-02-15 20:37:21 +00005256 // Build the list of clobbers, outputs and inputs.
5257 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
David Blaikie960ea3f2014-06-08 16:18:35 +00005258 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005259
Benjamin Kramer1a136112013-02-15 20:37:21 +00005260 // Immediate.
David Blaikie960ea3f2014-06-08 16:18:35 +00005261 if (Operand.isImm())
Benjamin Kramer1a136112013-02-15 20:37:21 +00005262 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00005263
Benjamin Kramer1a136112013-02-15 20:37:21 +00005264 // Register operand.
Nico Weber42f79db2014-07-17 20:24:55 +00005265 if (Operand.isReg() && !Operand.needAddressOf() &&
5266 !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
Benjamin Kramer1a136112013-02-15 20:37:21 +00005267 unsigned NumDefs = Desc.getNumDefs();
5268 // Clobber.
David Blaikie960ea3f2014-06-08 16:18:35 +00005269 if (NumDefs && Operand.getMCOperandNum() < NumDefs)
5270 ClobberRegs.push_back(Operand.getReg());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005271 continue;
5272 }
5273
5274 // Expr/Input or Output.
David Blaikie960ea3f2014-06-08 16:18:35 +00005275 StringRef SymName = Operand.getSymName();
Chad Rosiere81309b2013-04-09 17:53:49 +00005276 if (SymName.empty())
5277 continue;
5278
David Blaikie960ea3f2014-06-08 16:18:35 +00005279 void *OpDecl = Operand.getOpDecl();
Benjamin Kramer1a136112013-02-15 20:37:21 +00005280 if (!OpDecl)
5281 continue;
5282
5283 bool isOutput = (i == 1) && Desc.mayStore();
Chad Rosiere81309b2013-04-09 17:53:49 +00005284 SMLoc Start = SMLoc::getFromPointer(SymName.data());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005285 if (isOutput) {
5286 ++InputIdx;
5287 OutputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00005288 OutputDeclsAddressOf.push_back(Operand.needAddressOf());
Yaron Keren075759a2015-03-30 15:42:36 +00005289 OutputConstraints.push_back(("=" + Operand.getConstraint()).str());
Craig Topper7d5b2312015-10-10 05:25:02 +00005290 AsmStrRewrites.emplace_back(AOK_Output, Start, SymName.size());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005291 } else {
5292 InputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00005293 InputDeclsAddressOf.push_back(Operand.needAddressOf());
5294 InputConstraints.push_back(Operand.getConstraint().str());
Craig Topper7d5b2312015-10-10 05:25:02 +00005295 AsmStrRewrites.emplace_back(AOK_Input, Start, SymName.size());
Chad Rosier8bce6642012-10-18 15:49:34 +00005296 }
Chad Rosier8bce6642012-10-18 15:49:34 +00005297 }
Reid Kleckneree088972013-12-10 18:27:32 +00005298
5299 // Consider implicit defs to be clobbers. Think of cpuid and push.
Craig Toppere5e035a32015-12-05 07:13:35 +00005300 ArrayRef<MCPhysReg> ImpDefs(Desc.getImplicitDefs(),
5301 Desc.getNumImplicitDefs());
David Majnemer8114c1a2014-06-23 02:17:16 +00005302 ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end());
Chad Rosier8bce6642012-10-18 15:49:34 +00005303 }
5304
5305 // Set the number of Outputs and Inputs.
Chad Rosierf641baa2012-10-18 19:39:30 +00005306 NumOutputs = OutputDecls.size();
5307 NumInputs = InputDecls.size();
Chad Rosier8bce6642012-10-18 15:49:34 +00005308
5309 // Set the unique clobbers.
Benjamin Kramer1a136112013-02-15 20:37:21 +00005310 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
5311 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
5312 ClobberRegs.end());
5313 Clobbers.assign(ClobberRegs.size(), std::string());
5314 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
5315 raw_string_ostream OS(Clobbers[I]);
5316 IP->printRegName(OS, ClobberRegs[I]);
5317 }
Chad Rosier8bce6642012-10-18 15:49:34 +00005318
5319 // Merge the various outputs and inputs. Output are expected first.
5320 if (NumOutputs || NumInputs) {
5321 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierf641baa2012-10-18 19:39:30 +00005322 OpDecls.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00005323 Constraints.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00005324 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00005325 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00005326 Constraints[i] = OutputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005327 }
5328 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00005329 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00005330 Constraints[j] = InputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005331 }
5332 }
5333
5334 // Build the IR assembly string.
Alp Tokere69170a2014-06-26 22:52:05 +00005335 std::string AsmStringIR;
5336 raw_string_ostream OS(AsmStringIR);
Alp Tokera55b95b2014-07-06 10:33:31 +00005337 StringRef ASMString =
5338 SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
5339 const char *AsmStart = ASMString.begin();
5340 const char *AsmEnd = ASMString.end();
Jim Grosbach4b905842013-09-20 23:08:21 +00005341 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
David Majnemer8114c1a2014-06-23 02:17:16 +00005342 for (const AsmRewrite &AR : AsmStrRewrites) {
5343 AsmRewriteKind Kind = AR.Kind;
Chad Rosierff10ed12013-04-12 16:26:42 +00005344 if (Kind == AOK_Delete)
5345 continue;
5346
David Majnemer8114c1a2014-06-23 02:17:16 +00005347 const char *Loc = AR.Loc.getPointer();
Chad Rosier17d37992013-03-19 21:12:14 +00005348 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
Chad Rosier0f48c552012-10-19 20:57:14 +00005349
Chad Rosier120eefd2013-03-19 17:32:17 +00005350 // Emit everything up to the immediate/expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00005351 if (unsigned Len = Loc - AsmStart)
Chad Rosier17d37992013-03-19 21:12:14 +00005352 OS << StringRef(AsmStart, Len);
Chad Rosier0f48c552012-10-19 20:57:14 +00005353
Chad Rosier37e755c2012-10-23 17:43:43 +00005354 // Skip the original expression.
5355 if (Kind == AOK_Skip) {
David Majnemer8114c1a2014-06-23 02:17:16 +00005356 AsmStart = Loc + AR.Len;
Chad Rosier37e755c2012-10-23 17:43:43 +00005357 continue;
5358 }
5359
Chad Rosierff10ed12013-04-12 16:26:42 +00005360 unsigned AdditionalSkip = 0;
Chad Rosier8bce6642012-10-18 15:49:34 +00005361 // Rewrite expressions in $N notation.
Chad Rosier0f48c552012-10-19 20:57:14 +00005362 switch (Kind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00005363 default:
5364 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005365 case AOK_Imm:
David Majnemer8114c1a2014-06-23 02:17:16 +00005366 OS << "$$" << AR.Val;
Chad Rosier11c42f22012-10-26 18:04:20 +00005367 break;
5368 case AOK_ImmPrefix:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005369 OS << "$$";
Chad Rosier8bce6642012-10-18 15:49:34 +00005370 break;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005371 case AOK_Label:
Matt Arsenault4e273432014-12-04 00:06:57 +00005372 OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005373 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005374 case AOK_Input:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005375 OS << '$' << InputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00005376 break;
5377 case AOK_Output:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005378 OS << '$' << OutputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00005379 break;
Chad Rosier0f48c552012-10-19 20:57:14 +00005380 case AOK_SizeDirective:
David Majnemer8114c1a2014-06-23 02:17:16 +00005381 switch (AR.Val) {
Chad Rosier0f48c552012-10-19 20:57:14 +00005382 default: break;
5383 case 8: OS << "byte ptr "; break;
5384 case 16: OS << "word ptr "; break;
5385 case 32: OS << "dword ptr "; break;
5386 case 64: OS << "qword ptr "; break;
5387 case 80: OS << "xword ptr "; break;
5388 case 128: OS << "xmmword ptr "; break;
5389 case 256: OS << "ymmword ptr "; break;
5390 }
Eli Friedman0f4871d2012-10-22 23:58:19 +00005391 break;
5392 case AOK_Emit:
5393 OS << ".byte";
5394 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00005395 case AOK_Align: {
Reid Klecknerfb1c1c72015-10-27 17:32:48 +00005396 // MS alignment directives are measured in bytes. If the native assembler
5397 // measures alignment in bytes, we can pass it straight through.
5398 OS << ".align";
5399 if (getContext().getAsmInfo()->getAlignmentIsInBytes())
5400 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00005401
Reid Klecknerfb1c1c72015-10-27 17:32:48 +00005402 // Alignment is in log2 form, so print that instead and skip the original
5403 // immediate.
5404 unsigned Val = AR.Val;
5405 OS << ' ' << Val;
Benjamin Kramer1a136112013-02-15 20:37:21 +00005406 assert(Val < 10 && "Expected alignment less then 2^10.");
Chad Rosierc7f552c2013-02-12 21:33:51 +00005407 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
5408 break;
5409 }
Michael Zuckerman02ecd432015-12-13 17:07:23 +00005410 case AOK_EVEN:
5411 OS << ".even";
5412 break;
Chad Rosierf0e87202012-10-25 20:41:34 +00005413 case AOK_DotOperator:
Reid Kleckner94a1c4d2014-03-06 19:19:12 +00005414 // Insert the dot if the user omitted it.
Alp Tokere69170a2014-06-26 22:52:05 +00005415 OS.flush();
5416 if (AsmStringIR.back() != '.')
Reid Kleckner94a1c4d2014-03-06 19:19:12 +00005417 OS << '.';
David Majnemer8114c1a2014-06-23 02:17:16 +00005418 OS << AR.Val;
Chad Rosierf0e87202012-10-25 20:41:34 +00005419 break;
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00005420 case AOK_EndOfStatement:
5421 OS << "\n\t";
5422 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005423 }
Chad Rosier0f48c552012-10-19 20:57:14 +00005424
Chad Rosier8bce6642012-10-18 15:49:34 +00005425 // Skip the original expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00005426 AsmStart = Loc + AR.Len + AdditionalSkip;
Chad Rosier8bce6642012-10-18 15:49:34 +00005427 }
5428
5429 // Emit the remainder of the asm string.
Chad Rosier17d37992013-03-19 21:12:14 +00005430 if (AsmStart != AsmEnd)
5431 OS << StringRef(AsmStart, AsmEnd - AsmStart);
Chad Rosier8bce6642012-10-18 15:49:34 +00005432
5433 AsmString = OS.str();
5434 return false;
5435}
5436
Pete Cooper80d21cb2015-06-22 19:35:57 +00005437namespace llvm {
5438namespace MCParserUtils {
5439
5440/// Returns whether the given symbol is used anywhere in the given expression,
5441/// or subexpressions.
5442static bool isSymbolUsedInExpression(const MCSymbol *Sym, const MCExpr *Value) {
5443 switch (Value->getKind()) {
5444 case MCExpr::Binary: {
5445 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
5446 return isSymbolUsedInExpression(Sym, BE->getLHS()) ||
5447 isSymbolUsedInExpression(Sym, BE->getRHS());
5448 }
5449 case MCExpr::Target:
5450 case MCExpr::Constant:
5451 return false;
5452 case MCExpr::SymbolRef: {
5453 const MCSymbol &S =
5454 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
5455 if (S.isVariable())
5456 return isSymbolUsedInExpression(Sym, S.getVariableValue());
5457 return &S == Sym;
5458 }
5459 case MCExpr::Unary:
5460 return isSymbolUsedInExpression(
5461 Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
5462 }
5463
5464 llvm_unreachable("Unknown expr kind!");
5465}
5466
5467bool parseAssignmentExpression(StringRef Name, bool allow_redef,
5468 MCAsmParser &Parser, MCSymbol *&Sym,
5469 const MCExpr *&Value) {
Pete Cooper80d21cb2015-06-22 19:35:57 +00005470
5471 // FIXME: Use better location, we should use proper tokens.
Nirav Davefd910412016-06-17 16:06:17 +00005472 SMLoc EqualLoc = Parser.getTok().getLoc();
Pete Cooper80d21cb2015-06-22 19:35:57 +00005473
5474 if (Parser.parseExpression(Value)) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00005475 return Parser.TokError("missing expression");
Pete Cooper80d21cb2015-06-22 19:35:57 +00005476 }
5477
5478 // Note: we don't count b as used in "a = b". This is to allow
5479 // a = b
5480 // b = c
5481
Nirav Dave1a9044b2016-10-24 14:35:29 +00005482 if (Parser.parseToken(AsmToken::EndOfStatement))
5483 return true;
Pete Cooper80d21cb2015-06-22 19:35:57 +00005484
5485 // Validate that the LHS is allowed to be a variable (either it has not been
5486 // used as a symbol, or it is an absolute symbol).
5487 Sym = Parser.getContext().lookupSymbol(Name);
5488 if (Sym) {
5489 // Diagnose assignment to a label.
5490 //
5491 // FIXME: Diagnostics. Note the location of the definition as a label.
5492 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
5493 if (isSymbolUsedInExpression(Sym, Value))
5494 return Parser.Error(EqualLoc, "Recursive use of '" + Name + "'");
Vedant Kumar86dbd922015-08-31 17:44:53 +00005495 else if (Sym->isUndefined(/*SetUsed*/ false) && !Sym->isUsed() &&
5496 !Sym->isVariable())
Pete Cooper80d21cb2015-06-22 19:35:57 +00005497 ; // Allow redefinitions of undefined symbols only used in directives.
5498 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
5499 ; // Allow redefinitions of variables that haven't yet been used.
5500 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
5501 return Parser.Error(EqualLoc, "redefinition of '" + Name + "'");
5502 else if (!Sym->isVariable())
5503 return Parser.Error(EqualLoc, "invalid assignment to '" + Name + "'");
5504 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
5505 return Parser.Error(EqualLoc,
5506 "invalid reassignment of non-absolute variable '" +
5507 Name + "'");
Pete Cooper80d21cb2015-06-22 19:35:57 +00005508 } else if (Name == ".") {
Oliver Stannard268f42f2016-12-14 10:43:58 +00005509 Parser.getStreamer().emitValueToOffset(Value, 0, EqualLoc);
Pete Cooper80d21cb2015-06-22 19:35:57 +00005510 return false;
5511 } else
5512 Sym = Parser.getContext().getOrCreateSymbol(Name);
5513
5514 Sym->setRedefinable(allow_redef);
5515
5516 return false;
5517}
5518
Eugene Zelenko33d7b762016-08-23 17:14:32 +00005519} // end namespace MCParserUtils
5520} // end namespace llvm
Pete Cooper80d21cb2015-06-22 19:35:57 +00005521
Daniel Dunbar01e36072010-07-17 02:26:10 +00005522/// \brief Create an MCAsmParser instance.
Jim Grosbach4b905842013-09-20 23:08:21 +00005523MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
Sanne Wouda29338752017-02-08 14:48:05 +00005524 MCStreamer &Out, const MCAsmInfo &MAI,
5525 unsigned CB) {
5526 return new AsmParser(SM, C, Out, MAI, CB);
Daniel Dunbar01e36072010-07-17 02:26:10 +00005527}