blob: 76eef5e3725d2308f79b33f7b6f8f8c2e4da7b31 [file] [log] [blame]
Chris Lattnerb0133452009-06-21 20:16:42 +00001//===- AsmParser.cpp - Parser for Assembly Files --------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This class implements the parser for assembly files.
11//
12//===----------------------------------------------------------------------===//
13
Daniel Dunbar2af16532010-09-24 01:59:56 +000014#include "llvm/ADT/APFloat.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000015#include "llvm/ADT/APInt.h"
16#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/None.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000018#include "llvm/ADT/STLExtras.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000019#include "llvm/ADT/SmallString.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000020#include "llvm/ADT/SmallVector.h"
Reid Kleckner26fa1bf2017-09-19 18:14:45 +000021#include "llvm/ADT/StringExtras.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000022#include "llvm/ADT/StringMap.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000023#include "llvm/ADT/StringRef.h"
Daniel Dunbareb6bb322009-07-27 23:20:52 +000024#include "llvm/ADT/Twine.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000025#include "llvm/BinaryFormat/Dwarf.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000026#include "llvm/MC/MCAsmInfo.h"
Reid Klecknera5b1eef2016-08-26 17:58:37 +000027#include "llvm/MC/MCCodeView.h"
Daniel Dunbarca29e4d2009-06-23 22:01:43 +000028#include "llvm/MC/MCContext.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000029#include "llvm/MC/MCDirectives.h"
Evan Cheng11424442011-07-26 00:24:13 +000030#include "llvm/MC/MCDwarf.h"
Daniel Dunbar115e4d62009-08-31 08:06:59 +000031#include "llvm/MC/MCExpr.h"
Chad Rosier8bce6642012-10-18 15:49:34 +000032#include "llvm/MC/MCInstPrinter.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000033#include "llvm/MC/MCInstrDesc.h"
Chad Rosier8bce6642012-10-18 15:49:34 +000034#include "llvm/MC/MCInstrInfo.h"
Rafael Espindolae28610d2013-12-09 20:26:40 +000035#include "llvm/MC/MCObjectFileInfo.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000036#include "llvm/MC/MCParser/AsmCond.h"
37#include "llvm/MC/MCParser/AsmLexer.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000038#include "llvm/MC/MCParser/MCAsmLexer.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000039#include "llvm/MC/MCParser/MCAsmParser.h"
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +000040#include "llvm/MC/MCParser/MCAsmParserExtension.h"
Pete Cooper80d21cb2015-06-22 19:35:57 +000041#include "llvm/MC/MCParser/MCAsmParserUtils.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000042#include "llvm/MC/MCParser/MCParsedAsmOperand.h"
Benjamin Kramerb3e8a6d2016-01-27 10:01:28 +000043#include "llvm/MC/MCParser/MCTargetAsmParser.h"
Evan Cheng76792992011-07-20 05:58:47 +000044#include "llvm/MC/MCRegisterInfo.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000045#include "llvm/MC/MCSection.h"
Daniel Dunbarca29e4d2009-06-23 22:01:43 +000046#include "llvm/MC/MCStreamer.h"
Daniel Dunbarae7ac012009-06-29 23:43:14 +000047#include "llvm/MC/MCSymbol.h"
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +000048#include "llvm/MC/MCTargetOptions.h"
Daniel Sanders9f6ad492015-11-12 13:33:00 +000049#include "llvm/MC/MCValue.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000050#include "llvm/Support/Casting.h"
Davide Italiano7c9fc732016-07-27 05:51:56 +000051#include "llvm/Support/CommandLine.h"
Benjamin Kramer4efe5062012-01-28 15:28:41 +000052#include "llvm/Support/ErrorHandling.h"
Paul Robinson29f5f982018-01-09 23:31:48 +000053#include "llvm/Support/MD5.h"
Jim Grosbach76346c32011-06-29 16:05:14 +000054#include "llvm/Support/MathExtras.h"
Kevin Enderbye233dda2010-06-28 21:45:58 +000055#include "llvm/Support/MemoryBuffer.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000056#include "llvm/Support/SMLoc.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000057#include "llvm/Support/SourceMgr.h"
Chris Lattner36e02122009-06-21 20:54:55 +000058#include "llvm/Support/raw_ostream.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000059#include <algorithm>
60#include <cassert>
Nick Lewycky0de20af2010-12-19 20:43:38 +000061#include <cctype>
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +000062#include <climits>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000063#include <cstddef>
64#include <cstdint>
Benjamin Kramerd59664f2014-04-29 23:26:49 +000065#include <deque>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000066#include <memory>
Davide Italiano7c9fc732016-07-27 05:51:56 +000067#include <sstream>
Chad Rosier8bce6642012-10-18 15:49:34 +000068#include <string>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000069#include <tuple>
70#include <utility>
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000071#include <vector>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000072
Chris Lattnerb0133452009-06-21 20:16:42 +000073using namespace llvm;
74
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +000075MCAsmParserSemaCallback::~MCAsmParserSemaCallback() = default;
Nick Lewyckyac612272012-10-19 07:00:09 +000076
Davide Italiano7c9fc732016-07-27 05:51:56 +000077static cl::opt<unsigned> AsmMacroMaxNestingDepth(
78 "asm-macro-max-nesting-depth", cl::init(20), cl::Hidden,
79 cl::desc("The maximum nesting depth allowed for assembly macros."));
80
Daniel Dunbar86033402010-07-12 17:54:38 +000081namespace {
Eugene Zelenko33d7b762016-08-23 17:14:32 +000082
Eli Benderskya313ae62013-01-16 18:56:50 +000083/// \brief Helper types for tracking macro definitions.
84typedef std::vector<AsmToken> MCAsmMacroArgument;
85typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +000086
Daniel Dunbar43235712010-07-18 18:54:11 +000087/// \brief Helper class for storing information about an active macro
88/// instantiation.
89struct MacroInstantiation {
Daniel Dunbar43235712010-07-18 18:54:11 +000090 /// The location of the instantiation.
91 SMLoc InstantiationLoc;
92
Daniel Dunbar40f1d852012-12-01 01:38:48 +000093 /// The buffer where parsing should resume upon instantiation completion.
94 int ExitBuffer;
95
Daniel Dunbar43235712010-07-18 18:54:11 +000096 /// The location where parsing should resume upon instantiation completion.
97 SMLoc ExitLoc;
98
Nico Weber155dccd12014-07-24 17:08:39 +000099 /// The depth of TheCondStack at the start of the instantiation.
100 size_t CondStackDepth;
101
Daniel Dunbar43235712010-07-18 18:54:11 +0000102public:
Rafael Espindola9eef18c2014-08-27 19:49:03 +0000103 MacroInstantiation(SMLoc IL, int EB, SMLoc EL, size_t CondStackDepth);
Daniel Dunbar43235712010-07-18 18:54:11 +0000104};
105
Eli Friedman0f4871d2012-10-22 23:58:19 +0000106struct ParseStatementInfo {
Jim Grosbach4b905842013-09-20 23:08:21 +0000107 /// \brief The parsed operands from the last parsed statement.
David Blaikie960ea3f2014-06-08 16:18:35 +0000108 SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> ParsedOperands;
Eli Friedman0f4871d2012-10-22 23:58:19 +0000109
Jim Grosbach4b905842013-09-20 23:08:21 +0000110 /// \brief The opcode from the last parsed instruction.
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000111 unsigned Opcode = ~0U;
Eli Friedman0f4871d2012-10-22 23:58:19 +0000112
Jim Grosbach4b905842013-09-20 23:08:21 +0000113 /// \brief Was there an error parsing the inline assembly?
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000114 bool ParseError = false;
Chad Rosier149e8e02012-12-12 22:45:52 +0000115
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000116 SmallVectorImpl<AsmRewrite> *AsmRewrites = nullptr;
Eli Friedman0f4871d2012-10-22 23:58:19 +0000117
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +0000118 ParseStatementInfo() = delete;
Eli Friedman0f4871d2012-10-22 23:58:19 +0000119 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000120 : AsmRewrites(rewrites) {}
Eli Friedman0f4871d2012-10-22 23:58:19 +0000121};
122
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000123/// \brief The concrete assembly parser instance.
124class AsmParser : public MCAsmParser {
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000125private:
126 AsmLexer Lexer;
127 MCContext &Ctx;
128 MCStreamer &Out;
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000129 const MCAsmInfo &MAI;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000130 SourceMgr &SrcMgr;
Benjamin Kramer47f5e302011-10-16 10:48:29 +0000131 SourceMgr::DiagHandlerTy SavedDiagHandler;
132 void *SavedDiagContext;
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000133 std::unique_ptr<MCAsmParserExtension> PlatformParser;
Rafael Espindola82065cb2011-04-11 21:49:50 +0000134
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000135 /// This is the current buffer index we're lexing from as managed by the
136 /// SourceMgr object.
Alp Tokera55b95b2014-07-06 10:33:31 +0000137 unsigned CurBuffer;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000138
139 AsmCond TheCondState;
140 std::vector<AsmCond> TheCondStack;
141
Jim Grosbach4b905842013-09-20 23:08:21 +0000142 /// \brief maps directive names to handler methods in parser
Eli Bendersky17233942013-01-15 22:59:42 +0000143 /// extensions. Extensions register themselves in this map by calling
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000144 /// addDirectiveHandler.
Eli Bendersky17233942013-01-15 22:59:42 +0000145 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
Daniel Dunbar828984f2010-07-18 18:38:02 +0000146
Jim Grosbach4b905842013-09-20 23:08:21 +0000147 /// \brief Stack of active macro instantiations.
Daniel Dunbar43235712010-07-18 18:54:11 +0000148 std::vector<MacroInstantiation*> ActiveMacros;
149
Jim Grosbach4b905842013-09-20 23:08:21 +0000150 /// \brief List of bodies of anonymous macros.
Benjamin Kramer1df3a1f2013-08-04 09:06:29 +0000151 std::deque<MCAsmMacro> MacroLikeBodies;
152
Daniel Dunbar828984f2010-07-18 18:38:02 +0000153 /// Boolean tracking whether macro substitution is enabled.
Eli Benderskyc2f6f922013-01-14 18:08:41 +0000154 unsigned MacrosEnabledFlag : 1;
Daniel Dunbar828984f2010-07-18 18:38:02 +0000155
Toma Tabacu217116e2015-04-27 10:50:29 +0000156 /// \brief Keeps track of how many .macro's have been instantiated.
157 unsigned NumOfMacroInstantiations;
158
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000159 /// The values from the last parsed cpp hash file line comment if any.
Tim Northoverc0bef992016-04-13 19:46:54 +0000160 struct CppHashInfoTy {
161 StringRef Filename;
Andrew Kaylorca196472016-04-21 20:09:35 +0000162 int64_t LineNumber = 0;
Tim Northoverc0bef992016-04-13 19:46:54 +0000163 SMLoc Loc;
Andrew Kaylorca196472016-04-21 20:09:35 +0000164 unsigned Buf = 0;
Tim Northoverc0bef992016-04-13 19:46:54 +0000165 };
166 CppHashInfoTy CppHashInfo;
167
168 /// \brief List of forward directional labels for diagnosis at the end.
169 SmallVector<std::tuple<SMLoc, CppHashInfoTy, MCSymbol *>, 4> DirLabels;
170
Kevin Enderby0fd064c2013-06-21 20:51:39 +0000171 /// When generating dwarf for assembly source files we need to calculate the
172 /// logical line number based on the last parsed cpp hash file line comment
Vladimir Medic9bad0d332013-08-20 13:33:18 +0000173 /// and current line. Since this is slow and messes up the SourceMgr's
Kevin Enderby0fd064c2013-06-21 20:51:39 +0000174 /// cache we save the last info we queried with SrcMgr.FindLineNumber().
175 SMLoc LastQueryIDLoc;
Alp Tokera55b95b2014-07-06 10:33:31 +0000176 unsigned LastQueryBuffer;
Kevin Enderby0fd064c2013-06-21 20:51:39 +0000177 unsigned LastQueryLine;
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000178
Devang Patela173ee52012-01-31 18:14:05 +0000179 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000180 unsigned AssemblerDialect = ~0U;
Devang Patela173ee52012-01-31 18:14:05 +0000181
Jim Grosbach4b905842013-09-20 23:08:21 +0000182 /// \brief is Darwin compatibility enabled?
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000183 bool IsDarwin = false;
Preston Gurd05500642012-09-19 20:36:12 +0000184
Jim Grosbach4b905842013-09-20 23:08:21 +0000185 /// \brief Are we parsing ms-style inline assembly?
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000186 bool ParsingInlineAsm = false;
Chad Rosier49963552012-10-13 00:26:04 +0000187
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000188public:
Jim Grosbach345768c2011-08-16 18:33:49 +0000189 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Sanne Wouda29338752017-02-08 14:48:05 +0000190 const MCAsmInfo &MAI, unsigned CB);
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000191 AsmParser(const AsmParser &) = delete;
192 AsmParser &operator=(const AsmParser &) = delete;
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000193 ~AsmParser() override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000194
Craig Topper59be68f2014-03-08 07:14:16 +0000195 bool Run(bool NoInitialTextSection, bool NoFinalize = false) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000196
Craig Topper59be68f2014-03-08 07:14:16 +0000197 void addDirectiveHandler(StringRef Directive,
198 ExtensionDirectiveHandler Handler) override {
Eli Bendersky29b9f472013-01-16 00:50:52 +0000199 ExtensionDirectiveMap[Directive] = Handler;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000200 }
201
Toma Tabacu11e14a92015-04-21 11:50:52 +0000202 void addAliasForDirective(StringRef Directive, StringRef Alias) override {
203 DirectiveKindMap[Directive] = DirectiveKindMap[Alias];
204 }
205
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000206 /// @name MCAsmParser Interface
207 /// {
208
Craig Topper59be68f2014-03-08 07:14:16 +0000209 SourceMgr &getSourceManager() override { return SrcMgr; }
210 MCAsmLexer &getLexer() override { return Lexer; }
211 MCContext &getContext() override { return Ctx; }
212 MCStreamer &getStreamer() override { return Out; }
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000213
Reid Klecknera5b1eef2016-08-26 17:58:37 +0000214 CodeViewContext &getCVContext() { return Ctx.getCVContext(); }
215
Craig Topper59be68f2014-03-08 07:14:16 +0000216 unsigned getAssemblerDialect() override {
Devang Patela173ee52012-01-31 18:14:05 +0000217 if (AssemblerDialect == ~0U)
Eric Christophera7c32732012-12-18 00:30:54 +0000218 return MAI.getAssemblerDialect();
Devang Patela173ee52012-01-31 18:14:05 +0000219 else
220 return AssemblerDialect;
221 }
Craig Topper59be68f2014-03-08 07:14:16 +0000222 void setAssemblerDialect(unsigned i) override {
Devang Patela173ee52012-01-31 18:14:05 +0000223 AssemblerDialect = i;
224 }
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000225
Nirav Dave2364748a2016-09-16 18:30:20 +0000226 void Note(SMLoc L, const Twine &Msg, SMRange Range = None) override;
227 bool Warning(SMLoc L, const Twine &Msg, SMRange Range = None) override;
228 bool printError(SMLoc L, const Twine &Msg, SMRange Range = None) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000229
Craig Topper59be68f2014-03-08 07:14:16 +0000230 const AsmToken &Lex() override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000231
Yunzhong Gao27ea29b2016-09-02 23:15:29 +0000232 void setParsingInlineAsm(bool V) override {
233 ParsingInlineAsm = V;
234 Lexer.setParsingMSInlineAsm(V);
235 }
Craig Topper59be68f2014-03-08 07:14:16 +0000236 bool isParsingInlineAsm() override { return ParsingInlineAsm; }
Chad Rosier8bce6642012-10-18 15:49:34 +0000237
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000238 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
Chad Rosier8bce6642012-10-18 15:49:34 +0000239 unsigned &NumOutputs, unsigned &NumInputs,
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000240 SmallVectorImpl<std::pair<void *,bool>> &OpDecls,
Chad Rosier8bce6642012-10-18 15:49:34 +0000241 SmallVectorImpl<std::string> &Constraints,
Chad Rosier8bce6642012-10-18 15:49:34 +0000242 SmallVectorImpl<std::string> &Clobbers,
Craig Topper59be68f2014-03-08 07:14:16 +0000243 const MCInstrInfo *MII, const MCInstPrinter *IP,
244 MCAsmParserSemaCallback &SI) override;
Chad Rosier49963552012-10-13 00:26:04 +0000245
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000246 bool parseExpression(const MCExpr *&Res);
Craig Topper59be68f2014-03-08 07:14:16 +0000247 bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
248 bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) override;
249 bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
Toma Tabacu7bc44dc2015-06-25 09:52:02 +0000250 bool parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
251 SMLoc &EndLoc) override;
Craig Topper59be68f2014-03-08 07:14:16 +0000252 bool parseAbsoluteExpression(int64_t &Res) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000253
Petr Hosek4cb08ce2016-09-23 19:25:15 +0000254 /// \brief Parse a floating point expression using the float \p Semantics
255 /// and set \p Res to the value.
256 bool parseRealValue(const fltSemantics &Semantics, APInt &Res);
257
Jim Grosbach4b905842013-09-20 23:08:21 +0000258 /// \brief Parse an identifier or string (as a quoted identifier)
Eli Bendersky0cf0cb92013-01-12 00:05:00 +0000259 /// and set \p Res to the identifier contents.
Craig Topper59be68f2014-03-08 07:14:16 +0000260 bool parseIdentifier(StringRef &Res) override;
261 void eatToEndOfStatement() override;
Eli Bendersky0cf0cb92013-01-12 00:05:00 +0000262
Nirav Davef43cc9f2016-10-10 15:24:54 +0000263 bool checkForValidSection() override;
Nirav Davea645433c2016-07-18 15:24:03 +0000264
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000265 /// }
266
267private:
Michael Zuckerman763e60e2017-05-04 10:37:00 +0000268 bool isAltmacroString(SMLoc &StrLoc, SMLoc &EndLoc);
Michael Zuckerman1f1a9122017-05-10 13:08:11 +0000269 void altMacroString(StringRef AltMacroStr, std::string &Res);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +0000270 bool parseStatement(ParseStatementInfo &Info,
271 MCAsmParserSemaCallback *SI);
Marina Yatsina5f5de9f2016-03-07 18:11:16 +0000272 bool parseCurlyBlockScope(SmallVectorImpl<AsmRewrite>& AsmStrRewrites);
Craig Topper3c76c522015-09-20 23:35:59 +0000273 bool parseCppHashLineFilenameComment(SMLoc L);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000274
Jim Grosbach4b905842013-09-20 23:08:21 +0000275 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +0000276 ArrayRef<MCAsmMacroParameter> Parameters);
Rafael Espindola34b9c512012-06-03 23:57:14 +0000277 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +0000278 ArrayRef<MCAsmMacroParameter> Parameters,
Toma Tabacu217116e2015-04-27 10:50:29 +0000279 ArrayRef<MCAsmMacroArgument> A, bool EnableAtPseudoVariable,
Craig Topper3c76c522015-09-20 23:35:59 +0000280 SMLoc L);
Daniel Dunbar43235712010-07-18 18:54:11 +0000281
Eli Benderskya313ae62013-01-16 18:56:50 +0000282 /// \brief Are macros enabled in the parser?
Jim Grosbach4b905842013-09-20 23:08:21 +0000283 bool areMacrosEnabled() {return MacrosEnabledFlag;}
Eli Benderskya313ae62013-01-16 18:56:50 +0000284
285 /// \brief Control a flag in the parser that enables or disables macros.
Jim Grosbach4b905842013-09-20 23:08:21 +0000286 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
Eli Benderskya313ae62013-01-16 18:56:50 +0000287
Eli Benderskya313ae62013-01-16 18:56:50 +0000288 /// \brief Are we inside a macro instantiation?
Jim Grosbach4b905842013-09-20 23:08:21 +0000289 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
Eli Benderskya313ae62013-01-16 18:56:50 +0000290
Vladimir Medic9bad0d332013-08-20 13:33:18 +0000291 /// \brief Handle entry to macro instantiation.
Eli Benderskya313ae62013-01-16 18:56:50 +0000292 ///
293 /// \param M The macro.
294 /// \param NameLoc Instantiation location.
Jim Grosbach4b905842013-09-20 23:08:21 +0000295 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
Eli Benderskya313ae62013-01-16 18:56:50 +0000296
297 /// \brief Handle exit from macro instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +0000298 void handleMacroExit();
Eli Benderskya313ae62013-01-16 18:56:50 +0000299
David Majnemer91fc4c22014-01-29 18:57:46 +0000300 /// \brief Extract AsmTokens for a macro argument.
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +0000301 bool parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg);
Eli Benderskya313ae62013-01-16 18:56:50 +0000302
303 /// \brief Parse all macro arguments for a given macro.
Jim Grosbach4b905842013-09-20 23:08:21 +0000304 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
Eli Benderskya313ae62013-01-16 18:56:50 +0000305
Jim Grosbach4b905842013-09-20 23:08:21 +0000306 void printMacroInstantiations();
307 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
Nirav Dave2364748a2016-09-16 18:30:20 +0000308 SMRange Range = None) const {
309 ArrayRef<SMRange> Ranges(Range);
Chris Lattner72845262011-10-16 05:47:55 +0000310 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
Benjamin Kramerc7583112010-09-27 17:42:11 +0000311 }
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000312 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
Benjamin Kramerc7583112010-09-27 17:42:11 +0000313
Jim Grosbach4b905842013-09-20 23:08:21 +0000314 /// \brief Enter the specified file. This returns true on failure.
315 bool enterIncludeFile(const std::string &Filename);
316
317 /// \brief Process the specified file for the .incbin directive.
Kevin Enderby109f25c2011-12-14 21:47:48 +0000318 /// This returns true on failure.
Petr Hosek2f4ac442016-09-23 00:41:06 +0000319 bool processIncbinFile(const std::string &Filename, int64_t Skip = 0,
320 const MCExpr *Count = nullptr, SMLoc Loc = SMLoc());
Daniel Dunbar43235712010-07-18 18:54:11 +0000321
Dmitri Gribenko5485acd2012-09-14 14:57:36 +0000322 /// \brief Reset the current lexer position to that given by \p Loc. The
Daniel Dunbar43235712010-07-18 18:54:11 +0000323 /// current token is not set; clients should ensure Lex() is called
324 /// subsequently.
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000325 ///
Alp Tokera55b95b2014-07-06 10:33:31 +0000326 /// \param InBuffer If not 0, should be the known buffer id that contains the
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000327 /// location.
Alp Tokera55b95b2014-07-06 10:33:31 +0000328 void jumpToLoc(SMLoc Loc, unsigned InBuffer = 0);
Daniel Dunbar43235712010-07-18 18:54:11 +0000329
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000330 /// \brief Parse up to the end of statement and a return the contents from the
331 /// current token until the end of the statement; the current token on exit
332 /// will be either the EndOfStatement or EOF.
Craig Topper59be68f2014-03-08 07:14:16 +0000333 StringRef parseStringToEndOfStatement() override;
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000334
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000335 /// \brief Parse until the end of a statement or a comma is encountered,
336 /// return the contents from the current token up to the end or comma.
Jim Grosbach4b905842013-09-20 23:08:21 +0000337 StringRef parseStringToComma();
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000338
Jim Grosbach4b905842013-09-20 23:08:21 +0000339 bool parseAssignment(StringRef Name, bool allow_redef,
Jim Grosbachb7b750d2012-09-13 23:11:31 +0000340 bool NoDeadStrip = false);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000341
Ahmed Bougacha457852f2015-04-28 00:17:39 +0000342 unsigned getBinOpPrecedence(AsmToken::TokenKind K,
343 MCBinaryExpr::Opcode &Kind);
344
Jim Grosbach4b905842013-09-20 23:08:21 +0000345 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
346 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
347 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000348
Jim Grosbach4b905842013-09-20 23:08:21 +0000349 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
Rafael Espindola63760ba2010-10-28 20:02:27 +0000350
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000351 bool parseCVFunctionId(int64_t &FunctionId, StringRef DirectiveName);
352 bool parseCVFileId(int64_t &FileId, StringRef DirectiveName);
353
Eli Bendersky17233942013-01-15 22:59:42 +0000354 // Generic (target and platform independent) directive parsing.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000355 enum DirectiveKind {
Eli Bendersky4d21fa02013-01-10 23:40:56 +0000356 DK_NO_DIRECTIVE, // Placeholder
Saleem Abdulrasoolb3c70c02017-07-28 03:39:18 +0000357 DK_SET,
358 DK_EQU,
359 DK_EQUIV,
360 DK_ASCII,
361 DK_ASCIZ,
362 DK_STRING,
363 DK_BYTE,
364 DK_SHORT,
Daniel Sanders9f6ad492015-11-12 13:33:00 +0000365 DK_RELOC,
Saleem Abdulrasoolb3c70c02017-07-28 03:39:18 +0000366 DK_VALUE,
367 DK_2BYTE,
368 DK_LONG,
369 DK_INT,
370 DK_4BYTE,
371 DK_QUAD,
372 DK_8BYTE,
373 DK_OCTA,
374 DK_DC,
375 DK_DC_A,
376 DK_DC_B,
377 DK_DC_D,
378 DK_DC_L,
379 DK_DC_S,
380 DK_DC_W,
381 DK_DC_X,
382 DK_DCB,
383 DK_DCB_B,
384 DK_DCB_D,
385 DK_DCB_L,
386 DK_DCB_S,
387 DK_DCB_W,
388 DK_DCB_X,
389 DK_DS,
390 DK_DS_B,
391 DK_DS_D,
392 DK_DS_L,
393 DK_DS_P,
394 DK_DS_S,
395 DK_DS_W,
396 DK_DS_X,
397 DK_SINGLE,
398 DK_FLOAT,
399 DK_DOUBLE,
400 DK_ALIGN,
401 DK_ALIGN32,
402 DK_BALIGN,
403 DK_BALIGNW,
404 DK_BALIGNL,
405 DK_P2ALIGN,
406 DK_P2ALIGNW,
407 DK_P2ALIGNL,
408 DK_ORG,
409 DK_FILL,
410 DK_ENDR,
411 DK_BUNDLE_ALIGN_MODE,
412 DK_BUNDLE_LOCK,
413 DK_BUNDLE_UNLOCK,
414 DK_ZERO,
415 DK_EXTERN,
416 DK_GLOBL,
417 DK_GLOBAL,
418 DK_LAZY_REFERENCE,
419 DK_NO_DEAD_STRIP,
420 DK_SYMBOL_RESOLVER,
421 DK_PRIVATE_EXTERN,
422 DK_REFERENCE,
423 DK_WEAK_DEFINITION,
424 DK_WEAK_REFERENCE,
425 DK_WEAK_DEF_CAN_BE_HIDDEN,
426 DK_COMM,
427 DK_COMMON,
428 DK_LCOMM,
429 DK_ABORT,
430 DK_INCLUDE,
431 DK_INCBIN,
432 DK_CODE16,
433 DK_CODE16GCC,
434 DK_REPT,
435 DK_IRP,
436 DK_IRPC,
437 DK_IF,
438 DK_IFEQ,
439 DK_IFGE,
440 DK_IFGT,
441 DK_IFLE,
442 DK_IFLT,
443 DK_IFNE,
444 DK_IFB,
445 DK_IFNB,
446 DK_IFC,
447 DK_IFEQS,
448 DK_IFNC,
449 DK_IFNES,
450 DK_IFDEF,
451 DK_IFNDEF,
452 DK_IFNOTDEF,
453 DK_ELSEIF,
454 DK_ELSE,
455 DK_ENDIF,
456 DK_SPACE,
457 DK_SKIP,
458 DK_FILE,
459 DK_LINE,
460 DK_LOC,
461 DK_STABS,
462 DK_CV_FILE,
463 DK_CV_FUNC_ID,
464 DK_CV_INLINE_SITE_ID,
465 DK_CV_LOC,
466 DK_CV_LINETABLE,
467 DK_CV_INLINE_LINETABLE,
468 DK_CV_DEF_RANGE,
469 DK_CV_STRINGTABLE,
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000470 DK_CV_FILECHECKSUMS,
Reid Kleckner26fa1bf2017-09-19 18:14:45 +0000471 DK_CV_FILECHECKSUM_OFFSET,
Reid Kleckner9cdd4df2017-10-11 21:24:33 +0000472 DK_CV_FPO_DATA,
Saleem Abdulrasoolb3c70c02017-07-28 03:39:18 +0000473 DK_CFI_SECTIONS,
474 DK_CFI_STARTPROC,
475 DK_CFI_ENDPROC,
476 DK_CFI_DEF_CFA,
477 DK_CFI_DEF_CFA_OFFSET,
478 DK_CFI_ADJUST_CFA_OFFSET,
479 DK_CFI_DEF_CFA_REGISTER,
480 DK_CFI_OFFSET,
481 DK_CFI_REL_OFFSET,
482 DK_CFI_PERSONALITY,
483 DK_CFI_LSDA,
484 DK_CFI_REMEMBER_STATE,
485 DK_CFI_RESTORE_STATE,
486 DK_CFI_SAME_VALUE,
487 DK_CFI_RESTORE,
488 DK_CFI_ESCAPE,
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +0000489 DK_CFI_RETURN_COLUMN,
Saleem Abdulrasoolb3c70c02017-07-28 03:39:18 +0000490 DK_CFI_SIGNAL_FRAME,
491 DK_CFI_UNDEFINED,
492 DK_CFI_REGISTER,
493 DK_CFI_WINDOW_SAVE,
494 DK_MACROS_ON,
495 DK_MACROS_OFF,
496 DK_ALTMACRO,
497 DK_NOALTMACRO,
498 DK_MACRO,
499 DK_EXITM,
500 DK_ENDM,
501 DK_ENDMACRO,
502 DK_PURGEM,
503 DK_SLEB128,
504 DK_ULEB128,
505 DK_ERR,
506 DK_ERROR,
507 DK_WARNING,
Coby Tayree01e53202017-10-02 14:36:31 +0000508 DK_PRINT,
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000509 DK_END
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000510 };
511
Jim Grosbach4b905842013-09-20 23:08:21 +0000512 /// \brief Maps directive name --> DirectiveKind enum, for
Eli Bendersky17233942013-01-15 22:59:42 +0000513 /// directives parsed by this class.
514 StringMap<DirectiveKind> DirectiveKindMap;
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000515
516 // ".ascii", ".asciz", ".string"
Jim Grosbach4b905842013-09-20 23:08:21 +0000517 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
Daniel Sanders9f6ad492015-11-12 13:33:00 +0000518 bool parseDirectiveReloc(SMLoc DirectiveLoc); // ".reloc"
Nirav Dave1a9044b2016-10-24 14:35:29 +0000519 bool parseDirectiveValue(StringRef IDVal,
520 unsigned Size); // ".byte", ".long", ...
521 bool parseDirectiveOctaValue(StringRef IDVal); // ".octa", ...
522 bool parseDirectiveRealValue(StringRef IDVal,
523 const fltSemantics &); // ".single", ...
Jim Grosbach4b905842013-09-20 23:08:21 +0000524 bool parseDirectiveFill(); // ".fill"
525 bool parseDirectiveZero(); // ".zero"
Eric Christophera7c32732012-12-18 00:30:54 +0000526 // ".set", ".equ", ".equiv"
Jim Grosbach4b905842013-09-20 23:08:21 +0000527 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
528 bool parseDirectiveOrg(); // ".org"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000529 // ".align{,32}", ".p2align{,w,l}"
Jim Grosbach4b905842013-09-20 23:08:21 +0000530 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000531
Eli Bendersky17233942013-01-15 22:59:42 +0000532 // ".file", ".line", ".loc", ".stabs"
Jim Grosbach4b905842013-09-20 23:08:21 +0000533 bool parseDirectiveFile(SMLoc DirectiveLoc);
534 bool parseDirectiveLine();
535 bool parseDirectiveLoc();
536 bool parseDirectiveStabs();
Eli Bendersky17233942013-01-15 22:59:42 +0000537
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000538 // ".cv_file", ".cv_func_id", ".cv_inline_site_id", ".cv_loc", ".cv_linetable",
539 // ".cv_inline_linetable", ".cv_def_range"
Reid Kleckner2214ed82016-01-29 00:49:42 +0000540 bool parseDirectiveCVFile();
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000541 bool parseDirectiveCVFuncId();
542 bool parseDirectiveCVInlineSiteId();
Reid Kleckner2214ed82016-01-29 00:49:42 +0000543 bool parseDirectiveCVLoc();
544 bool parseDirectiveCVLinetable();
David Majnemer6fcbd7e2016-01-29 19:24:12 +0000545 bool parseDirectiveCVInlineLinetable();
David Majnemer408b5e62016-02-05 01:55:49 +0000546 bool parseDirectiveCVDefRange();
Reid Kleckner2214ed82016-01-29 00:49:42 +0000547 bool parseDirectiveCVStringTable();
548 bool parseDirectiveCVFileChecksums();
Reid Kleckner26fa1bf2017-09-19 18:14:45 +0000549 bool parseDirectiveCVFileChecksumOffset();
Reid Kleckner9cdd4df2017-10-11 21:24:33 +0000550 bool parseDirectiveCVFPOData();
Reid Kleckner2214ed82016-01-29 00:49:42 +0000551
Eli Bendersky17233942013-01-15 22:59:42 +0000552 // .cfi directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000553 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +0000554 bool parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +0000555 bool parseDirectiveCFISections();
556 bool parseDirectiveCFIStartProc();
557 bool parseDirectiveCFIEndProc();
558 bool parseDirectiveCFIDefCfaOffset();
559 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
560 bool parseDirectiveCFIAdjustCfaOffset();
561 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
562 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
563 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
564 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
565 bool parseDirectiveCFIRememberState();
566 bool parseDirectiveCFIRestoreState();
567 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
568 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
569 bool parseDirectiveCFIEscape();
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +0000570 bool parseDirectiveCFIReturnColumn(SMLoc DirectiveLoc);
Jim Grosbach4b905842013-09-20 23:08:21 +0000571 bool parseDirectiveCFISignalFrame();
572 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
Eli Bendersky17233942013-01-15 22:59:42 +0000573
574 // macro directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000575 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
Nico Weber155dccd12014-07-24 17:08:39 +0000576 bool parseDirectiveExitMacro(StringRef Directive);
Jim Grosbach4b905842013-09-20 23:08:21 +0000577 bool parseDirectiveEndMacro(StringRef Directive);
578 bool parseDirectiveMacro(SMLoc DirectiveLoc);
579 bool parseDirectiveMacrosOnOff(StringRef Directive);
Michael Zuckerman56704612017-05-01 13:20:12 +0000580 // alternate macro mode directives
581 bool parseDirectiveAltmacro(StringRef Directive);
Eli Benderskyf483ff92012-12-20 19:05:53 +0000582 // ".bundle_align_mode"
Jim Grosbach4b905842013-09-20 23:08:21 +0000583 bool parseDirectiveBundleAlignMode();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000584 // ".bundle_lock"
Jim Grosbach4b905842013-09-20 23:08:21 +0000585 bool parseDirectiveBundleLock();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000586 // ".bundle_unlock"
Jim Grosbach4b905842013-09-20 23:08:21 +0000587 bool parseDirectiveBundleUnlock();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000588
Eli Bendersky17233942013-01-15 22:59:42 +0000589 // ".space", ".skip"
Jim Grosbach4b905842013-09-20 23:08:21 +0000590 bool parseDirectiveSpace(StringRef IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +0000591
Petr Hosek4cb08ce2016-09-23 19:25:15 +0000592 // ".dcb"
593 bool parseDirectiveDCB(StringRef IDVal, unsigned Size);
594 bool parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &);
Petr Hosek85b2f672016-09-23 21:53:36 +0000595 // ".ds"
596 bool parseDirectiveDS(StringRef IDVal, unsigned Size);
Petr Hosek4cb08ce2016-09-23 19:25:15 +0000597
Eli Bendersky17233942013-01-15 22:59:42 +0000598 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
Jim Grosbach4b905842013-09-20 23:08:21 +0000599 bool parseDirectiveLEB128(bool Signed);
Eli Bendersky17233942013-01-15 22:59:42 +0000600
Jim Grosbach4b905842013-09-20 23:08:21 +0000601 /// \brief Parse a directive like ".globl" which
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000602 /// accepts a single symbol (which should be a label or an external).
Jim Grosbach4b905842013-09-20 23:08:21 +0000603 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000604
Jim Grosbach4b905842013-09-20 23:08:21 +0000605 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000606
Jim Grosbach4b905842013-09-20 23:08:21 +0000607 bool parseDirectiveAbort(); // ".abort"
608 bool parseDirectiveInclude(); // ".include"
609 bool parseDirectiveIncbin(); // ".incbin"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000610
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +0000611 // ".if", ".ifeq", ".ifge", ".ifgt" , ".ifle", ".iflt" or ".ifne"
612 bool parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind);
Benjamin Kramer62c18b02012-05-12 11:18:42 +0000613 // ".ifb" or ".ifnb", depending on ExpectBlank.
Jim Grosbach4b905842013-09-20 23:08:21 +0000614 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000615 // ".ifc" or ".ifnc", depending on ExpectEqual.
Jim Grosbach4b905842013-09-20 23:08:21 +0000616 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
Sid Manning51c35602015-03-18 14:20:54 +0000617 // ".ifeqs" or ".ifnes", depending on ExpectEqual.
618 bool parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +0000619 // ".ifdef" or ".ifndef", depending on expect_defined
Jim Grosbach4b905842013-09-20 23:08:21 +0000620 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
621 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
622 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
623 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
Craig Topper59be68f2014-03-08 07:14:16 +0000624 bool parseEscapedString(std::string &Data) override;
Daniel Dunbar55f16672010-09-17 02:47:07 +0000625
Jim Grosbach4b905842013-09-20 23:08:21 +0000626 const MCExpr *applyModifierToExpr(const MCExpr *E,
Daniel Dunbar55f16672010-09-17 02:47:07 +0000627 MCSymbolRefExpr::VariantKind Variant);
Rafael Espindola47b7dac2012-05-12 16:31:10 +0000628
Rafael Espindola34b9c512012-06-03 23:57:14 +0000629 // Macro-like directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000630 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
631 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +0000632 raw_svector_ostream &OS);
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +0000633 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
Jim Grosbach4b905842013-09-20 23:08:21 +0000634 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
635 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
636 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
Chad Rosier8bce6642012-10-18 15:49:34 +0000637
Chad Rosierc7f552c2013-02-12 21:33:51 +0000638 // "_emit" or "__emit"
Jim Grosbach4b905842013-09-20 23:08:21 +0000639 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
Chad Rosierc7f552c2013-02-12 21:33:51 +0000640 size_t Len);
641
642 // "align"
Jim Grosbach4b905842013-09-20 23:08:21 +0000643 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000644
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000645 // "end"
646 bool parseDirectiveEnd(SMLoc DirectiveLoc);
647
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +0000648 // ".err" or ".error"
649 bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +0000650
Nico Weber404012b2014-07-24 16:26:06 +0000651 // ".warning"
652 bool parseDirectiveWarning(SMLoc DirectiveLoc);
653
Coby Tayree01e53202017-10-02 14:36:31 +0000654 // .print <double-quotes-string>
655 bool parseDirectivePrint(SMLoc DirectiveLoc);
656
Eli Bendersky17233942013-01-15 22:59:42 +0000657 void initializeDirectiveKindMap();
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000658};
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000659
660} // end anonymous namespace
Daniel Dunbar86033402010-07-12 17:54:38 +0000661
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000662namespace llvm {
663
664extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbarab058b82010-07-12 21:23:32 +0000665extern MCAsmParserExtension *createELFAsmParser();
Michael J. Spencerc8dbdfd2010-10-09 11:01:07 +0000666extern MCAsmParserExtension *createCOFFAsmParser();
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000667
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000668} // end namespace llvm
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000669
Chris Lattnerc35681b2010-01-19 19:46:13 +0000670enum { DEFAULT_ADDRSPACE = 0 };
671
David Blaikie9f380a32015-03-16 18:06:57 +0000672AsmParser::AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Sanne Wouda29338752017-02-08 14:48:05 +0000673 const MCAsmInfo &MAI, unsigned CB = 0)
David Blaikie9f380a32015-03-16 18:06:57 +0000674 : Lexer(MAI), Ctx(Ctx), Out(Out), MAI(MAI), SrcMgr(SM),
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000675 CurBuffer(CB ? CB : SM.getMainFileID()), MacrosEnabledFlag(true) {
Nirav Dave2364748a2016-09-16 18:30:20 +0000676 HadError = false;
Benjamin Kramer47f5e302011-10-16 10:48:29 +0000677 // Save the old handler.
678 SavedDiagHandler = SrcMgr.getDiagHandler();
679 SavedDiagContext = SrcMgr.getDiagContext();
680 // Set our own handler which calls the saved handler.
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000681 SrcMgr.setDiagHandler(DiagHandler, this);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000682 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar86033402010-07-12 17:54:38 +0000683
Daniel Dunbarc5011082010-07-12 18:12:02 +0000684 // Initialize the platform / file format parser.
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000685 switch (Ctx.getObjectFileInfo()->getObjectFileType()) {
686 case MCObjectFileInfo::IsCOFF:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000687 PlatformParser.reset(createCOFFAsmParser());
688 break;
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000689 case MCObjectFileInfo::IsMachO:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000690 PlatformParser.reset(createDarwinAsmParser());
691 IsDarwin = true;
692 break;
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000693 case MCObjectFileInfo::IsELF:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000694 PlatformParser.reset(createELFAsmParser());
695 break;
Dan Gohman18eafb62017-02-22 01:23:18 +0000696 case MCObjectFileInfo::IsWasm:
697 llvm_unreachable("Wasm parsing not supported yet");
698 break;
Daniel Dunbarc5011082010-07-12 18:12:02 +0000699 }
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000700
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000701 PlatformParser->Initialize(*this);
Eli Bendersky17233942013-01-15 22:59:42 +0000702 initializeDirectiveKindMap();
Toma Tabacu217116e2015-04-27 10:50:29 +0000703
704 NumOfMacroInstantiations = 0;
Chris Lattner351a7ef2009-09-27 21:16:52 +0000705}
706
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000707AsmParser::~AsmParser() {
Saleem Abdulrasool6eae1e62014-05-21 17:53:18 +0000708 assert((HadError || ActiveMacros.empty()) &&
709 "Unexpected active macro instantiation!");
Sanne Wouda29338752017-02-08 14:48:05 +0000710
711 // Restore the saved diagnostics handler and context for use during
712 // finalization.
713 SrcMgr.setDiagHandler(SavedDiagHandler, SavedDiagContext);
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000714}
715
Jim Grosbach4b905842013-09-20 23:08:21 +0000716void AsmParser::printMacroInstantiations() {
Daniel Dunbar43235712010-07-18 18:54:11 +0000717 // Print the active macro instantiation stack.
Jim Grosbach4b905842013-09-20 23:08:21 +0000718 for (std::vector<MacroInstantiation *>::const_reverse_iterator
719 it = ActiveMacros.rbegin(),
720 ie = ActiveMacros.rend();
721 it != ie; ++it)
722 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
Chris Lattner03b80a42011-10-16 05:43:57 +0000723 "while in macro instantiation");
Daniel Dunbar43235712010-07-18 18:54:11 +0000724}
725
Nirav Dave2364748a2016-09-16 18:30:20 +0000726void AsmParser::Note(SMLoc L, const Twine &Msg, SMRange Range) {
727 printPendingErrors();
728 printMessage(L, SourceMgr::DK_Note, Msg, Range);
Saleem Abdulrasool69c7caf2014-01-07 02:28:31 +0000729 printMacroInstantiations();
730}
731
Nirav Dave2364748a2016-09-16 18:30:20 +0000732bool AsmParser::Warning(SMLoc L, const Twine &Msg, SMRange Range) {
Colin LeMahieufe36f832015-07-27 22:39:14 +0000733 if(getTargetParser().getTargetOptions().MCNoWarn)
734 return false;
Joerg Sonnenberger29815912014-08-26 18:39:50 +0000735 if (getTargetParser().getTargetOptions().MCFatalWarnings)
Nirav Dave2364748a2016-09-16 18:30:20 +0000736 return Error(L, Msg, Range);
737 printMessage(L, SourceMgr::DK_Warning, Msg, Range);
Jim Grosbach4b905842013-09-20 23:08:21 +0000738 printMacroInstantiations();
Joerg Sonnenberger74ba2622011-05-19 18:00:13 +0000739 return false;
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +0000740}
741
Nirav Dave2364748a2016-09-16 18:30:20 +0000742bool AsmParser::printError(SMLoc L, const Twine &Msg, SMRange Range) {
Daniel Dunbar43325c42010-09-09 22:42:56 +0000743 HadError = true;
Nirav Dave2364748a2016-09-16 18:30:20 +0000744 printMessage(L, SourceMgr::DK_Error, Msg, Range);
Jim Grosbach4b905842013-09-20 23:08:21 +0000745 printMacroInstantiations();
Chris Lattner2adc9e72009-06-21 21:22:11 +0000746 return true;
747}
748
Jim Grosbach4b905842013-09-20 23:08:21 +0000749bool AsmParser::enterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergeraf5f23e2011-06-01 13:10:15 +0000750 std::string IncludedFile;
Alp Tokera55b95b2014-07-06 10:33:31 +0000751 unsigned NewBuf =
752 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
753 if (!NewBuf)
Sean Callanan7a77eae2010-01-21 00:19:58 +0000754 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +0000755
Sean Callanan7a77eae2010-01-21 00:19:58 +0000756 CurBuffer = NewBuf;
Rafael Espindola8026bd02014-07-06 14:17:29 +0000757 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Sean Callanan7a77eae2010-01-21 00:19:58 +0000758 return false;
759}
Daniel Dunbar43235712010-07-18 18:54:11 +0000760
Sylvestre Ledru149e2812013-05-14 23:36:24 +0000761/// Process the specified .incbin file by searching for it in the include paths
Benjamin Kramerbde91762012-06-02 10:20:22 +0000762/// then just emitting the byte contents of the file to the streamer. This
Kevin Enderby109f25c2011-12-14 21:47:48 +0000763/// returns true on failure.
Petr Hosek2f4ac442016-09-23 00:41:06 +0000764bool AsmParser::processIncbinFile(const std::string &Filename, int64_t Skip,
765 const MCExpr *Count, SMLoc Loc) {
Kevin Enderby109f25c2011-12-14 21:47:48 +0000766 std::string IncludedFile;
Alp Tokera55b95b2014-07-06 10:33:31 +0000767 unsigned NewBuf =
768 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
769 if (!NewBuf)
Kevin Enderby109f25c2011-12-14 21:47:48 +0000770 return true;
771
Kevin Enderbyad41ab52011-12-14 22:34:45 +0000772 // Pick up the bytes from the file and emit them.
Petr Hosek2f4ac442016-09-23 00:41:06 +0000773 StringRef Bytes = SrcMgr.getMemoryBuffer(NewBuf)->getBuffer();
774 Bytes = Bytes.drop_front(Skip);
775 if (Count) {
776 int64_t Res;
777 if (!Count->evaluateAsAbsolute(Res))
778 return Error(Loc, "expected absolute expression");
779 if (Res < 0)
780 return Warning(Loc, "negative count has no effect");
781 Bytes = Bytes.take_front(Res);
782 }
783 getStreamer().EmitBytes(Bytes);
Kevin Enderby109f25c2011-12-14 21:47:48 +0000784 return false;
785}
786
Alp Tokera55b95b2014-07-06 10:33:31 +0000787void AsmParser::jumpToLoc(SMLoc Loc, unsigned InBuffer) {
788 CurBuffer = InBuffer ? InBuffer : SrcMgr.FindBufferContainingLoc(Loc);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000789 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(),
790 Loc.getPointer());
Daniel Dunbar43235712010-07-18 18:54:11 +0000791}
792
Sean Callanan7a77eae2010-01-21 00:19:58 +0000793const AsmToken &AsmParser::Lex() {
Nirav Dave1180e6892016-06-02 17:15:05 +0000794 if (Lexer.getTok().is(AsmToken::Error))
795 Error(Lexer.getErrLoc(), Lexer.getErr());
796
Nirav Dave53a72f42016-07-11 12:42:14 +0000797 // if it's a end of statement with a comment in it
798 if (getTok().is(AsmToken::EndOfStatement)) {
799 // if this is a line comment output it.
Nirav Dave670109d2017-06-09 14:04:03 +0000800 if (!getTok().getString().empty() && getTok().getString().front() != '\n' &&
Nirav Dave53a72f42016-07-11 12:42:14 +0000801 getTok().getString().front() != '\r' && MAI.preserveAsmComments())
802 Out.addExplicitComment(Twine(getTok().getString()));
803 }
804
Sean Callanan7a77eae2010-01-21 00:19:58 +0000805 const AsmToken *tok = &Lexer.Lex();
Nirav Dave53a72f42016-07-11 12:42:14 +0000806
807 // Parse comments here to be deferred until end of next statement.
Nirav Davefd910412016-06-17 16:06:17 +0000808 while (tok->is(AsmToken::Comment)) {
Nirav Dave53a72f42016-07-11 12:42:14 +0000809 if (MAI.preserveAsmComments())
810 Out.addExplicitComment(Twine(tok->getString()));
Nirav Davefd910412016-06-17 16:06:17 +0000811 tok = &Lexer.Lex();
812 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000813
Sean Callanan7a77eae2010-01-21 00:19:58 +0000814 if (tok->is(AsmToken::Eof)) {
815 // If this is the end of an included file, pop the parent file off the
816 // include stack.
817 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
818 if (ParentIncludeLoc != SMLoc()) {
Jim Grosbach4b905842013-09-20 23:08:21 +0000819 jumpToLoc(ParentIncludeLoc);
Nirav Davefd910412016-06-17 16:06:17 +0000820 return Lex();
Sean Callanan7a77eae2010-01-21 00:19:58 +0000821 }
822 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000823
Sean Callanan7a77eae2010-01-21 00:19:58 +0000824 return *tok;
Sean Callanan686ed8d2010-01-19 20:22:31 +0000825}
826
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000827bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar322fec62010-03-13 02:20:57 +0000828 // Create the initial section, if requested.
Daniel Dunbar322fec62010-03-13 02:20:57 +0000829 if (!NoInitialTextSection)
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000830 Out.InitSections(false);
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000831
Chris Lattner36e02122009-06-21 20:54:55 +0000832 // Prime the lexer.
Sean Callanan686ed8d2010-01-19 20:22:31 +0000833 Lex();
Daniel Dunbar43325c42010-09-09 22:42:56 +0000834
835 HadError = false;
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000836 AsmCond StartingCondState = TheCondState;
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +0000837 SmallVector<AsmRewrite, 4> AsmStrRewrites;
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000838
Kevin Enderby6469fc22011-11-01 22:27:22 +0000839 // If we are generating dwarf for assembly source files save the initial text
840 // section and generate a .file directive.
841 if (getContext().getGenDwarfForAssembly()) {
Eric Christopher445c9522016-10-14 05:47:37 +0000842 MCSection *Sec = getStreamer().getCurrentSectionOnly();
Rafael Espindola2f9bdd82015-05-27 20:52:32 +0000843 if (!Sec->getBeginSymbol()) {
844 MCSymbol *SectionStartSym = getContext().createTempSymbol();
845 getStreamer().EmitLabel(SectionStartSym);
846 Sec->setBeginSymbol(SectionStartSym);
847 }
Rafael Espindolae0746792015-05-21 16:52:32 +0000848 bool InsertResult = getContext().addGenDwarfSection(Sec);
849 assert(InsertResult && ".text section should not have debug info yet");
Rafael Espindolafa160c72015-05-21 17:09:22 +0000850 (void)InsertResult;
David Blaikiec714ef42014-03-17 01:52:11 +0000851 getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective(
852 0, StringRef(), getContext().getMainFileName()));
Kevin Enderby6469fc22011-11-01 22:27:22 +0000853 }
854
Chris Lattner73f36112009-07-02 21:53:43 +0000855 // While we have input, parse each statement.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000856 while (Lexer.isNot(AsmToken::Eof)) {
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +0000857 ParseStatementInfo Info(&AsmStrRewrites);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +0000858 if (!parseStatement(Info, nullptr))
Jim Grosbach4b905842013-09-20 23:08:21 +0000859 continue;
Michael J. Spencer530ce852010-10-09 11:00:50 +0000860
Nirav Dave2364748a2016-09-16 18:30:20 +0000861 // If we have a Lexer Error we are on an Error Token. Load in Lexer Error
862 // for printing ErrMsg via Lex() only if no (presumably better) parser error
863 // exists.
864 if (!hasPendingError() && Lexer.getTok().is(AsmToken::Error)) {
Nirav Dave1180e6892016-06-02 17:15:05 +0000865 Lex();
866 }
867
Nirav Dave2364748a2016-09-16 18:30:20 +0000868 // parseStatement returned true so may need to emit an error.
869 printPendingErrors();
870
871 // Skipping to the next line if needed.
872 if (!getLexer().isAtStartOfStatement())
873 eatToEndOfStatement();
Chris Lattner73f36112009-07-02 21:53:43 +0000874 }
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000875
Nirav Dave2364748a2016-09-16 18:30:20 +0000876 // All errors should have been emitted.
877 assert(!hasPendingError() && "unexpected error from parseStatement");
878
Oliver Stannard21718282016-07-26 14:19:47 +0000879 getTargetParser().flushPendingInstructions(getStreamer());
880
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000881 if (TheCondState.TheCond != StartingCondState.TheCond ||
882 TheCondState.Ignore != StartingCondState.Ignore)
Nirav Dave2364748a2016-09-16 18:30:20 +0000883 printError(getTok().getLoc(), "unmatched .ifs or .elses");
Kevin Enderbye5930f12010-07-28 20:55:35 +0000884 // Check to see there are no empty DwarfFile slots.
David Blaikie8bf66c42014-04-01 07:35:52 +0000885 const auto &LineTables = getContext().getMCDwarfLineTables();
886 if (!LineTables.empty()) {
887 unsigned Index = 0;
888 for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) {
889 if (File.Name.empty() && Index != 0)
Nirav Dave2364748a2016-09-16 18:30:20 +0000890 printError(getTok().getLoc(), "unassigned file number: " +
891 Twine(Index) +
892 " for .file directives");
David Blaikie8bf66c42014-04-01 07:35:52 +0000893 ++Index;
894 }
Kevin Enderbye5930f12010-07-28 20:55:35 +0000895 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000896
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000897 // Check to see that all assembler local symbols were actually defined.
898 // Targets that don't do subsections via symbols may not want this, though,
899 // so conservatively exclude them. Only do this if we're finalizing, though,
900 // as otherwise we won't necessarilly have seen everything yet.
Tim Northover6b3169b2016-04-11 19:50:46 +0000901 if (!NoFinalize) {
902 if (MAI.hasSubsectionsViaSymbols()) {
903 for (const auto &TableEntry : getContext().getSymbols()) {
904 MCSymbol *Sym = TableEntry.getValue();
905 // Variable symbols may not be marked as defined, so check those
906 // explicitly. If we know it's a variable, we have a definition for
907 // the purposes of this check.
908 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
909 // FIXME: We would really like to refer back to where the symbol was
910 // first referenced for a source location. We need to add something
911 // to track that. Currently, we just point to the end of the file.
Nirav Dave2364748a2016-09-16 18:30:20 +0000912 printError(getTok().getLoc(), "assembler local symbol '" +
913 Sym->getName() + "' not defined");
Tim Northover6b3169b2016-04-11 19:50:46 +0000914 }
915 }
916
917 // Temporary symbols like the ones for directional jumps don't go in the
918 // symbol table. They also need to be diagnosed in all (final) cases.
Tim Northoverc0bef992016-04-13 19:46:54 +0000919 for (std::tuple<SMLoc, CppHashInfoTy, MCSymbol *> &LocSym : DirLabels) {
920 if (std::get<2>(LocSym)->isUndefined()) {
921 // Reset the state of any "# line file" directives we've seen to the
922 // context as it was at the diagnostic site.
923 CppHashInfo = std::get<1>(LocSym);
Nirav Dave2364748a2016-09-16 18:30:20 +0000924 printError(std::get<0>(LocSym), "directional label undefined");
Tim Northoverc0bef992016-04-13 19:46:54 +0000925 }
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000926 }
927 }
928
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000929 // Finalize the output stream if there are no errors and if the client wants
930 // us to.
Jack Carter13d5f752013-10-04 22:52:31 +0000931 if (!HadError && !NoFinalize)
Daniel Dunbar9df5f332009-08-21 08:34:18 +0000932 Out.Finish();
933
Oliver Stannard07b43d32015-11-17 09:58:07 +0000934 return HadError || getContext().hadError();
Chris Lattner36e02122009-06-21 20:54:55 +0000935}
936
Nirav Davef43cc9f2016-10-10 15:24:54 +0000937bool AsmParser::checkForValidSection() {
Eric Christopher445c9522016-10-14 05:47:37 +0000938 if (!ParsingInlineAsm && !getStreamer().getCurrentSectionOnly()) {
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000939 Out.InitSections(false);
Nirav Davef43cc9f2016-10-10 15:24:54 +0000940 return Error(getTok().getLoc(),
941 "expected section directive before assembly directive");
Daniel Dunbare5444a82010-09-09 22:42:59 +0000942 }
Nirav Davef43cc9f2016-10-10 15:24:54 +0000943 return false;
Daniel Dunbare5444a82010-09-09 22:42:59 +0000944}
945
Jim Grosbach4b905842013-09-20 23:08:21 +0000946/// \brief Throw away the rest of the line for testing purposes.
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000947void AsmParser::eatToEndOfStatement() {
Jim Grosbach4b905842013-09-20 23:08:21 +0000948 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Nirav Dave1180e6892016-06-02 17:15:05 +0000949 Lexer.Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +0000950
Chris Lattnere5074c42009-06-22 01:29:09 +0000951 // Eat EOL.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000952 if (Lexer.is(AsmToken::EndOfStatement))
Nirav Dave1180e6892016-06-02 17:15:05 +0000953 Lexer.Lex();
Chris Lattnere5074c42009-06-22 01:29:09 +0000954}
955
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000956StringRef AsmParser::parseStringToEndOfStatement() {
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000957 const char *Start = getTok().getLoc().getPointer();
958
Jim Grosbach4b905842013-09-20 23:08:21 +0000959 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Nirav Davefd910412016-06-17 16:06:17 +0000960 Lexer.Lex();
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000961
962 const char *End = getTok().getLoc().getPointer();
963 return StringRef(Start, End - Start);
964}
Chris Lattner78db3622009-06-22 05:51:26 +0000965
Jim Grosbach4b905842013-09-20 23:08:21 +0000966StringRef AsmParser::parseStringToComma() {
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000967 const char *Start = getTok().getLoc().getPointer();
968
969 while (Lexer.isNot(AsmToken::EndOfStatement) &&
Jim Grosbach4b905842013-09-20 23:08:21 +0000970 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
Nirav Davefd910412016-06-17 16:06:17 +0000971 Lexer.Lex();
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000972
973 const char *End = getTok().getLoc().getPointer();
974 return StringRef(Start, End - Start);
975}
976
Jim Grosbach4b905842013-09-20 23:08:21 +0000977/// \brief Parse a paren expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +0000978/// NOTE: This assumes the leading '(' has already been consumed.
979///
980/// parenexpr ::= expr)
981///
Jim Grosbach4b905842013-09-20 23:08:21 +0000982bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
983 if (parseExpression(Res))
984 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000985 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner7fdbce72009-06-22 06:32:03 +0000986 return TokError("expected ')' in parentheses expression");
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000987 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +0000988 Lex();
Chris Lattner7fdbce72009-06-22 06:32:03 +0000989 return false;
990}
Chris Lattner78db3622009-06-22 05:51:26 +0000991
Jim Grosbach4b905842013-09-20 23:08:21 +0000992/// \brief Parse a bracket expression and return it.
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +0000993/// NOTE: This assumes the leading '[' has already been consumed.
994///
995/// bracketexpr ::= expr]
996///
Jim Grosbach4b905842013-09-20 23:08:21 +0000997bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
998 if (parseExpression(Res))
999 return true;
Nirav Davea645433c2016-07-18 15:24:03 +00001000 EndLoc = getTok().getEndLoc();
1001 if (parseToken(AsmToken::RBrac, "expected ']' in brackets expression"))
1002 return true;
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +00001003 return false;
1004}
1005
Jim Grosbach4b905842013-09-20 23:08:21 +00001006/// \brief Parse a primary expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +00001007/// primaryexpr ::= (parenexpr
1008/// primaryexpr ::= symbol
1009/// primaryexpr ::= number
Chris Lattner6b55cb92010-04-14 04:40:28 +00001010/// primaryexpr ::= '.'
Chris Lattner7fdbce72009-06-22 06:32:03 +00001011/// primaryexpr ::= ~,+,- primaryexpr
Jim Grosbach4b905842013-09-20 23:08:21 +00001012bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Kevin Enderby0017d8a2013-01-22 21:09:20 +00001013 SMLoc FirstTokenLoc = getLexer().getLoc();
1014 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
1015 switch (FirstTokenKind) {
Chris Lattner78db3622009-06-22 05:51:26 +00001016 default:
1017 return TokError("unknown token in expression");
Eric Christopher104af062011-04-12 00:03:13 +00001018 // If we have an error assume that we've already handled it.
1019 case AsmToken::Error:
1020 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001021 case AsmToken::Exclaim:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001022 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001023 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001024 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +00001025 Res = MCUnaryExpr::createLNot(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001026 return false;
Daniel Dunbar24764322010-08-24 19:13:42 +00001027 case AsmToken::Dollar:
Hans Wennborgce69d772013-10-18 20:46:28 +00001028 case AsmToken::At:
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +00001029 case AsmToken::String:
Daniel Dunbard20cda02009-10-16 01:34:54 +00001030 case AsmToken::Identifier: {
Daniel Dunbar24764322010-08-24 19:13:42 +00001031 StringRef Identifier;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001032 if (parseIdentifier(Identifier)) {
Nirav Daved0463322016-10-12 13:58:07 +00001033 // We may have failed but $ may be a valid token.
1034 if (getTok().is(AsmToken::Dollar)) {
David Majnemer0c58bc62013-09-25 10:47:21 +00001035 if (Lexer.getMAI().getDollarIsPC()) {
Nirav Daved0463322016-10-12 13:58:07 +00001036 Lex();
David Majnemer0c58bc62013-09-25 10:47:21 +00001037 // This is a '$' reference, which references the current PC. Emit a
1038 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +00001039 MCSymbol *Sym = Ctx.createTempSymbol();
David Majnemer0c58bc62013-09-25 10:47:21 +00001040 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +00001041 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None,
Jack Carter721726a2013-10-04 21:26:15 +00001042 getContext());
David Majnemer0c58bc62013-09-25 10:47:21 +00001043 EndLoc = FirstTokenLoc;
1044 return false;
Ted Kremenek297febe2014-03-06 22:13:17 +00001045 }
1046 return Error(FirstTokenLoc, "invalid token in expression");
David Majnemer0c58bc62013-09-25 10:47:21 +00001047 }
Kevin Enderby0017d8a2013-01-22 21:09:20 +00001048 }
David Peixotto8ad70b32013-12-04 22:43:20 +00001049 // Parse symbol variant
1050 std::pair<StringRef, StringRef> Split;
1051 if (!MAI.useParensForSymbolVariant()) {
David Majnemer6a5b8122014-06-19 01:25:43 +00001052 if (FirstTokenKind == AsmToken::String) {
1053 if (Lexer.is(AsmToken::At)) {
Nirav Davefd910412016-06-17 16:06:17 +00001054 Lex(); // eat @
David Majnemer6a5b8122014-06-19 01:25:43 +00001055 SMLoc AtLoc = getLexer().getLoc();
1056 StringRef VName;
1057 if (parseIdentifier(VName))
1058 return Error(AtLoc, "expected symbol variant after '@'");
1059
1060 Split = std::make_pair(Identifier, VName);
1061 }
1062 } else {
1063 Split = Identifier.split('@');
1064 }
David Peixotto8ad70b32013-12-04 22:43:20 +00001065 } else if (Lexer.is(AsmToken::LParen)) {
Nirav Davefd910412016-06-17 16:06:17 +00001066 Lex(); // eat '('.
David Peixotto8ad70b32013-12-04 22:43:20 +00001067 StringRef VName;
1068 parseIdentifier(VName);
Nirav Davea645433c2016-07-18 15:24:03 +00001069 // eat ')'.
1070 if (parseToken(AsmToken::RParen,
1071 "unexpected token in variant, expected ')'"))
1072 return true;
David Peixotto8ad70b32013-12-04 22:43:20 +00001073 Split = std::make_pair(Identifier, VName);
1074 }
Daniel Dunbar24764322010-08-24 19:13:42 +00001075
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001076 EndLoc = SMLoc::getFromPointer(Identifier.end());
1077
Daniel Dunbard20cda02009-10-16 01:34:54 +00001078 // This is a symbol reference.
Hans Wennborgce69d772013-10-18 20:46:28 +00001079 StringRef SymbolName = Identifier;
Weiming Zhaocf26d562016-12-01 18:00:36 +00001080 if (SymbolName.empty())
1081 return true;
1082
Hans Wennborgce69d772013-10-18 20:46:28 +00001083 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Hans Wennborg69918bc2013-10-17 01:13:02 +00001084
Hans Wennborg7ddcdc82013-10-18 02:14:40 +00001085 // Lookup the symbol variant if used.
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00001086 if (!Split.second.empty()) {
Hans Wennborg7ddcdc82013-10-18 02:14:40 +00001087 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Hans Wennborgce69d772013-10-18 20:46:28 +00001088 if (Variant != MCSymbolRefExpr::VK_Invalid) {
1089 SymbolName = Split.first;
David Peixotto8ad70b32013-12-04 22:43:20 +00001090 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
Hans Wennborgce69d772013-10-18 20:46:28 +00001091 Variant = MCSymbolRefExpr::VK_None;
1092 } else {
Saleem Abdulrasoola25e1e42014-01-26 22:29:43 +00001093 return Error(SMLoc::getFromPointer(Split.second.begin()),
1094 "invalid variant '" + Split.second + "'");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001095 }
1096 }
Daniel Dunbar55992562010-03-15 23:51:06 +00001097
Jim Grosbach6f482002015-05-18 18:43:14 +00001098 MCSymbol *Sym = getContext().getOrCreateSymbol(SymbolName);
Hans Wennborgce69d772013-10-18 20:46:28 +00001099
Daniel Dunbard20cda02009-10-16 01:34:54 +00001100 // If this is an absolute variable reference, substitute it now to preserve
1101 // semantics in the face of reassignment.
Vedant Kumar86dbd922015-08-31 17:44:53 +00001102 if (Sym->isVariable() &&
1103 isa<MCConstantExpr>(Sym->getVariableValue(/*SetUsed*/ false))) {
Daniel Dunbar55992562010-03-15 23:51:06 +00001104 if (Variant)
Daniel Dunbar8a3c3f22010-11-08 17:53:02 +00001105 return Error(EndLoc, "unexpected modifier on variable reference");
Daniel Dunbar55992562010-03-15 23:51:06 +00001106
Vedant Kumar86dbd922015-08-31 17:44:53 +00001107 Res = Sym->getVariableValue(/*SetUsed*/ false);
Daniel Dunbard20cda02009-10-16 01:34:54 +00001108 return false;
1109 }
1110
1111 // Otherwise create a symbol ref.
Chad Rosier9245e122017-01-19 20:06:32 +00001112 Res = MCSymbolRefExpr::create(Sym, Variant, getContext(), FirstTokenLoc);
Chris Lattner78db3622009-06-22 05:51:26 +00001113 return false;
Daniel Dunbard20cda02009-10-16 01:34:54 +00001114 }
David Woodhousef42a6662014-02-01 16:20:54 +00001115 case AsmToken::BigNum:
1116 return TokError("literal value out of range for directive");
Kevin Enderby0510b482010-05-17 23:08:19 +00001117 case AsmToken::Integer: {
1118 SMLoc Loc = getTok().getLoc();
1119 int64_t IntVal = getTok().getIntVal();
Jim Grosbach13760bd2015-05-30 01:25:56 +00001120 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001121 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001122 Lex(); // Eat token.
Kevin Enderby0510b482010-05-17 23:08:19 +00001123 // Look for 'b' or 'f' following an Integer as a directional label
1124 if (Lexer.getKind() == AsmToken::Identifier) {
1125 StringRef IDVal = getTok().getString();
Ulrich Weigandd4120982013-06-20 16:24:17 +00001126 // Lookup the symbol variant if used.
1127 std::pair<StringRef, StringRef> Split = IDVal.split('@');
1128 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
1129 if (Split.first.size() != IDVal.size()) {
1130 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Arnaud A. de Grandmaisonc97727a2014-03-21 21:54:46 +00001131 if (Variant == MCSymbolRefExpr::VK_Invalid)
Ulrich Weigandd4120982013-06-20 16:24:17 +00001132 return TokError("invalid variant '" + Split.second + "'");
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001133 IDVal = Split.first;
Ulrich Weigandd4120982013-06-20 16:24:17 +00001134 }
Jim Grosbach4b905842013-09-20 23:08:21 +00001135 if (IDVal == "f" || IDVal == "b") {
1136 MCSymbol *Sym =
Jim Grosbach6f482002015-05-18 18:43:14 +00001137 Ctx.getDirectionalLocalSymbol(IntVal, IDVal == "b");
Jim Grosbach13760bd2015-05-30 01:25:56 +00001138 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00001139 if (IDVal == "b" && Sym->isUndefined())
Tim Northover6b3169b2016-04-11 19:50:46 +00001140 return Error(Loc, "directional label undefined");
Tim Northoverc0bef992016-04-13 19:46:54 +00001141 DirLabels.push_back(std::make_tuple(Loc, CppHashInfo, Sym));
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001142 EndLoc = Lexer.getTok().getEndLoc();
Kevin Enderby0510b482010-05-17 23:08:19 +00001143 Lex(); // Eat identifier.
1144 }
1145 }
Chris Lattner78db3622009-06-22 05:51:26 +00001146 return false;
Kevin Enderby0510b482010-05-17 23:08:19 +00001147 }
Bill Wendlingcdbf17b2011-01-25 21:26:41 +00001148 case AsmToken::Real: {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001149 APFloat RealVal(APFloat::IEEEdouble(), getTok().getString());
Bob Wilson813bdf62011-02-03 23:17:47 +00001150 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Jim Grosbach13760bd2015-05-30 01:25:56 +00001151 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001152 EndLoc = Lexer.getTok().getEndLoc();
Bill Wendlingcdbf17b2011-01-25 21:26:41 +00001153 Lex(); // Eat token.
1154 return false;
1155 }
Chris Lattner6b55cb92010-04-14 04:40:28 +00001156 case AsmToken::Dot: {
1157 // This is a '.' reference, which references the current PC. Emit a
1158 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +00001159 MCSymbol *Sym = Ctx.createTempSymbol();
Chris Lattner6b55cb92010-04-14 04:40:28 +00001160 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +00001161 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001162 EndLoc = Lexer.getTok().getEndLoc();
Chris Lattner6b55cb92010-04-14 04:40:28 +00001163 Lex(); // Eat identifier.
1164 return false;
1165 }
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001166 case AsmToken::LParen:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001167 Lex(); // Eat the '('.
Jim Grosbach4b905842013-09-20 23:08:21 +00001168 return parseParenExpr(Res, EndLoc);
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +00001169 case AsmToken::LBrac:
1170 if (!PlatformParser->HasBracketExpressions())
1171 return TokError("brackets expression not supported on this target");
1172 Lex(); // Eat the '['.
Jim Grosbach4b905842013-09-20 23:08:21 +00001173 return parseBracketExpr(Res, EndLoc);
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001174 case AsmToken::Minus:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001175 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001176 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001177 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +00001178 Res = MCUnaryExpr::createMinus(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001179 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001180 case AsmToken::Plus:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001181 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001182 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001183 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +00001184 Res = MCUnaryExpr::createPlus(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001185 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001186 case AsmToken::Tilde:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001187 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001188 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001189 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +00001190 Res = MCUnaryExpr::createNot(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001191 return false;
Daniel Sanders3feeb9c2016-08-08 11:50:25 +00001192 // MIPS unary expression operators. The lexer won't generate these tokens if
1193 // MCAsmInfo::HasMipsExpressions is false for the target.
1194 case AsmToken::PercentCall16:
1195 case AsmToken::PercentCall_Hi:
1196 case AsmToken::PercentCall_Lo:
1197 case AsmToken::PercentDtprel_Hi:
1198 case AsmToken::PercentDtprel_Lo:
1199 case AsmToken::PercentGot:
1200 case AsmToken::PercentGot_Disp:
1201 case AsmToken::PercentGot_Hi:
1202 case AsmToken::PercentGot_Lo:
1203 case AsmToken::PercentGot_Ofst:
1204 case AsmToken::PercentGot_Page:
1205 case AsmToken::PercentGottprel:
1206 case AsmToken::PercentGp_Rel:
1207 case AsmToken::PercentHi:
1208 case AsmToken::PercentHigher:
1209 case AsmToken::PercentHighest:
1210 case AsmToken::PercentLo:
1211 case AsmToken::PercentNeg:
1212 case AsmToken::PercentPcrel_Hi:
1213 case AsmToken::PercentPcrel_Lo:
1214 case AsmToken::PercentTlsgd:
1215 case AsmToken::PercentTlsldm:
1216 case AsmToken::PercentTprel_Hi:
1217 case AsmToken::PercentTprel_Lo:
1218 Lex(); // Eat the operator.
1219 if (Lexer.isNot(AsmToken::LParen))
1220 return TokError("expected '(' after operator");
1221 Lex(); // Eat the operator.
1222 if (parseExpression(Res, EndLoc))
1223 return true;
1224 if (Lexer.isNot(AsmToken::RParen))
1225 return TokError("expected ')'");
1226 Lex(); // Eat the operator.
1227 Res = getTargetParser().createTargetUnaryExpr(Res, FirstTokenKind, Ctx);
1228 return !Res;
Chris Lattner78db3622009-06-22 05:51:26 +00001229 }
1230}
Chris Lattner7fdbce72009-06-22 06:32:03 +00001231
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001232bool AsmParser::parseExpression(const MCExpr *&Res) {
Chris Lattnere17df0b2010-01-15 19:39:23 +00001233 SMLoc EndLoc;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001234 return parseExpression(Res, EndLoc);
Chris Lattner528d00b2010-01-15 19:28:38 +00001235}
1236
Daniel Dunbar55f16672010-09-17 02:47:07 +00001237const MCExpr *
Jim Grosbach4b905842013-09-20 23:08:21 +00001238AsmParser::applyModifierToExpr(const MCExpr *E,
Daniel Dunbar55f16672010-09-17 02:47:07 +00001239 MCSymbolRefExpr::VariantKind Variant) {
Joerg Sonnenbergerb822af42013-08-27 20:23:19 +00001240 // Ask the target implementation about this expression first.
1241 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
1242 if (NewE)
1243 return NewE;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001244 // Recurse over the given expression, rebuilding it to apply the given variant
1245 // if there is exactly one symbol.
1246 switch (E->getKind()) {
1247 case MCExpr::Target:
1248 case MCExpr::Constant:
Craig Topper353eda42014-04-24 06:44:33 +00001249 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001250
1251 case MCExpr::SymbolRef: {
1252 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
1253
1254 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001255 TokError("invalid variant on expression '" + getTok().getIdentifier() +
1256 "' (already modified)");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001257 return E;
1258 }
1259
Jim Grosbach13760bd2015-05-30 01:25:56 +00001260 return MCSymbolRefExpr::create(&SRE->getSymbol(), Variant, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001261 }
1262
1263 case MCExpr::Unary: {
1264 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +00001265 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001266 if (!Sub)
Craig Topper353eda42014-04-24 06:44:33 +00001267 return nullptr;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001268 return MCUnaryExpr::create(UE->getOpcode(), Sub, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001269 }
1270
1271 case MCExpr::Binary: {
1272 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +00001273 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
1274 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001275
1276 if (!LHS && !RHS)
Craig Topper353eda42014-04-24 06:44:33 +00001277 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001278
Jim Grosbach4b905842013-09-20 23:08:21 +00001279 if (!LHS)
1280 LHS = BE->getLHS();
1281 if (!RHS)
1282 RHS = BE->getRHS();
Daniel Dunbar55f16672010-09-17 02:47:07 +00001283
Jim Grosbach13760bd2015-05-30 01:25:56 +00001284 return MCBinaryExpr::create(BE->getOpcode(), LHS, RHS, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001285 }
1286 }
Daniel Dunbarbaad46c2010-09-17 16:34:24 +00001287
Craig Toppera2886c22012-02-07 05:05:23 +00001288 llvm_unreachable("Invalid expression kind!");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001289}
1290
Michael Zuckerman763e60e2017-05-04 10:37:00 +00001291/// This function checks if the next token is <string> type or arithmetic.
1292/// string that begin with character '<' must end with character '>'.
1293/// otherwise it is arithmetics.
1294/// If the function returns a 'true' value,
1295/// the End argument will be filled with the last location pointed to the '>'
1296/// character.
1297
1298/// There is a gap between the AltMacro's documentation and the single quote implementation.
1299/// GCC does not fully support this feature and so we will not support it.
1300/// TODO: Adding single quote as a string.
1301bool AsmParser::isAltmacroString(SMLoc &StrLoc, SMLoc &EndLoc) {
1302 assert((StrLoc.getPointer() != NULL) &&
1303 "Argument to the function cannot be a NULL value");
1304 const char *CharPtr = StrLoc.getPointer();
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00001305 while ((*CharPtr != '>') && (*CharPtr != '\n') && (*CharPtr != '\r') &&
1306 (*CharPtr != '\0')) {
1307 if (*CharPtr == '!')
1308 CharPtr++;
Michael Zuckerman763e60e2017-05-04 10:37:00 +00001309 CharPtr++;
1310 }
1311 if (*CharPtr == '>') {
1312 EndLoc = StrLoc.getFromPointer(CharPtr + 1);
1313 return true;
1314 }
1315 return false;
1316}
1317
Michael Zuckerman1f1a9122017-05-10 13:08:11 +00001318/// \brief creating a string without the escape characters '!'.
1319void AsmParser::altMacroString(StringRef AltMacroStr,std::string &Res) {
Michael Zuckermanff298792017-05-10 14:00:57 +00001320 for (size_t Pos = 0; Pos < AltMacroStr.size(); Pos++) {
Michael Zuckerman1f1a9122017-05-10 13:08:11 +00001321 if (AltMacroStr[Pos] == '!')
1322 Pos++;
1323 Res += AltMacroStr[Pos];
1324 }
1325}
1326
Jim Grosbach4b905842013-09-20 23:08:21 +00001327/// \brief Parse an expression and return it.
Michael J. Spencer530ce852010-10-09 11:00:50 +00001328///
Jim Grosbachbd164242011-08-20 16:24:13 +00001329/// expr ::= expr &&,|| expr -> lowest.
1330/// expr ::= expr |,^,&,! expr
1331/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1332/// expr ::= expr <<,>> expr
1333/// expr ::= expr +,- expr
1334/// expr ::= expr *,/,% expr -> highest.
Chris Lattner7fdbce72009-06-22 06:32:03 +00001335/// expr ::= primaryexpr
1336///
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001337bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001338 // Parse the expression.
Craig Topper353eda42014-04-24 06:44:33 +00001339 Res = nullptr;
Jim Grosbach4b905842013-09-20 23:08:21 +00001340 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001341 return true;
1342
Daniel Dunbar55f16672010-09-17 02:47:07 +00001343 // As a special case, we support 'a op b @ modifier' by rewriting the
1344 // expression to include the modifier. This is inefficient, but in general we
1345 // expect users to use 'a@modifier op b'.
1346 if (Lexer.getKind() == AsmToken::At) {
1347 Lex();
1348
1349 if (Lexer.isNot(AsmToken::Identifier))
1350 return TokError("unexpected symbol modifier following '@'");
1351
1352 MCSymbolRefExpr::VariantKind Variant =
Jim Grosbach4b905842013-09-20 23:08:21 +00001353 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001354 if (Variant == MCSymbolRefExpr::VK_Invalid)
1355 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1356
Jim Grosbach4b905842013-09-20 23:08:21 +00001357 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001358 if (!ModifiedRes) {
1359 return TokError("invalid modifier '" + getTok().getIdentifier() +
1360 "' (no symbols present)");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001361 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001362
Daniel Dunbar55f16672010-09-17 02:47:07 +00001363 Res = ModifiedRes;
1364 Lex();
1365 }
1366
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001367 // Try to constant fold it up front, if possible.
1368 int64_t Value;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001369 if (Res->evaluateAsAbsolute(Value))
1370 Res = MCConstantExpr::create(Value, getContext());
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001371
1372 return false;
Chris Lattner7fdbce72009-06-22 06:32:03 +00001373}
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001374
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001375bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Craig Topper353eda42014-04-24 06:44:33 +00001376 Res = nullptr;
Jim Grosbach4b905842013-09-20 23:08:21 +00001377 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
Daniel Dunbar7c82d562009-08-31 08:08:17 +00001378}
1379
Toma Tabacu7bc44dc2015-06-25 09:52:02 +00001380bool AsmParser::parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
1381 SMLoc &EndLoc) {
1382 if (parseParenExpr(Res, EndLoc))
1383 return true;
1384
1385 for (; ParenDepth > 0; --ParenDepth) {
1386 if (parseBinOpRHS(1, Res, EndLoc))
1387 return true;
1388
1389 // We don't Lex() the last RParen.
1390 // This is the same behavior as parseParenExpression().
1391 if (ParenDepth - 1 > 0) {
Nirav Davea645433c2016-07-18 15:24:03 +00001392 EndLoc = getTok().getEndLoc();
1393 if (parseToken(AsmToken::RParen,
1394 "expected ')' in parentheses expression"))
1395 return true;
Toma Tabacu7bc44dc2015-06-25 09:52:02 +00001396 }
1397 }
1398 return false;
1399}
1400
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001401bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
Daniel Dunbarf3636452009-08-31 08:07:22 +00001402 const MCExpr *Expr;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001403
Daniel Dunbar75630b32009-06-30 02:10:03 +00001404 SMLoc StartLoc = Lexer.getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001405 if (parseExpression(Expr))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001406 return true;
1407
Jim Grosbach13760bd2015-05-30 01:25:56 +00001408 if (!Expr->evaluateAsAbsolute(Res))
Daniel Dunbar75630b32009-06-30 02:10:03 +00001409 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001410
1411 return false;
1412}
1413
David Majnemer0993e0b2015-10-26 03:15:34 +00001414static unsigned getDarwinBinOpPrecedence(AsmToken::TokenKind K,
1415 MCBinaryExpr::Opcode &Kind,
1416 bool ShouldUseLogicalShr) {
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001417 switch (K) {
Daniel Dunbar940cda22009-08-31 08:07:44 +00001418 default:
Jim Grosbach4b905842013-09-20 23:08:21 +00001419 return 0; // not a binop.
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001420
Jim Grosbach4b905842013-09-20 23:08:21 +00001421 // Lowest Precedence: &&, ||
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001422 case AsmToken::AmpAmp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001423 Kind = MCBinaryExpr::LAnd;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001424 return 1;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001425 case AsmToken::PipePipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001426 Kind = MCBinaryExpr::LOr;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001427 return 1;
1428
Jim Grosbach4b905842013-09-20 23:08:21 +00001429 // Low Precedence: |, &, ^
1430 //
1431 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001432 case AsmToken::Pipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001433 Kind = MCBinaryExpr::Or;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001434 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001435 case AsmToken::Caret:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001436 Kind = MCBinaryExpr::Xor;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001437 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001438 case AsmToken::Amp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001439 Kind = MCBinaryExpr::And;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001440 return 2;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001441
Jim Grosbach4b905842013-09-20 23:08:21 +00001442 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001443 case AsmToken::EqualEqual:
1444 Kind = MCBinaryExpr::EQ;
1445 return 3;
1446 case AsmToken::ExclaimEqual:
1447 case AsmToken::LessGreater:
1448 Kind = MCBinaryExpr::NE;
1449 return 3;
1450 case AsmToken::Less:
1451 Kind = MCBinaryExpr::LT;
1452 return 3;
1453 case AsmToken::LessEqual:
1454 Kind = MCBinaryExpr::LTE;
1455 return 3;
1456 case AsmToken::Greater:
1457 Kind = MCBinaryExpr::GT;
1458 return 3;
1459 case AsmToken::GreaterEqual:
1460 Kind = MCBinaryExpr::GTE;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001461 return 3;
1462
Jim Grosbach4b905842013-09-20 23:08:21 +00001463 // Intermediate Precedence: <<, >>
Jim Grosbachbd164242011-08-20 16:24:13 +00001464 case AsmToken::LessLess:
1465 Kind = MCBinaryExpr::Shl;
1466 return 4;
1467 case AsmToken::GreaterGreater:
David Majnemer0993e0b2015-10-26 03:15:34 +00001468 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
Jim Grosbachbd164242011-08-20 16:24:13 +00001469 return 4;
1470
Jim Grosbach4b905842013-09-20 23:08:21 +00001471 // High Intermediate Precedence: +, -
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001472 case AsmToken::Plus:
1473 Kind = MCBinaryExpr::Add;
Jim Grosbachbd164242011-08-20 16:24:13 +00001474 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001475 case AsmToken::Minus:
1476 Kind = MCBinaryExpr::Sub;
Jim Grosbachbd164242011-08-20 16:24:13 +00001477 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001478
Jim Grosbach4b905842013-09-20 23:08:21 +00001479 // Highest Precedence: *, /, %
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001480 case AsmToken::Star:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001481 Kind = MCBinaryExpr::Mul;
Jim Grosbachbd164242011-08-20 16:24:13 +00001482 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001483 case AsmToken::Slash:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001484 Kind = MCBinaryExpr::Div;
Jim Grosbachbd164242011-08-20 16:24:13 +00001485 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001486 case AsmToken::Percent:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001487 Kind = MCBinaryExpr::Mod;
Jim Grosbachbd164242011-08-20 16:24:13 +00001488 return 6;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001489 }
1490}
1491
David Majnemer0993e0b2015-10-26 03:15:34 +00001492static unsigned getGNUBinOpPrecedence(AsmToken::TokenKind K,
1493 MCBinaryExpr::Opcode &Kind,
1494 bool ShouldUseLogicalShr) {
1495 switch (K) {
1496 default:
1497 return 0; // not a binop.
1498
1499 // Lowest Precedence: &&, ||
1500 case AsmToken::AmpAmp:
1501 Kind = MCBinaryExpr::LAnd;
1502 return 2;
1503 case AsmToken::PipePipe:
1504 Kind = MCBinaryExpr::LOr;
1505 return 1;
1506
1507 // Low Precedence: ==, !=, <>, <, <=, >, >=
1508 case AsmToken::EqualEqual:
1509 Kind = MCBinaryExpr::EQ;
1510 return 3;
1511 case AsmToken::ExclaimEqual:
1512 case AsmToken::LessGreater:
1513 Kind = MCBinaryExpr::NE;
1514 return 3;
1515 case AsmToken::Less:
1516 Kind = MCBinaryExpr::LT;
1517 return 3;
1518 case AsmToken::LessEqual:
1519 Kind = MCBinaryExpr::LTE;
1520 return 3;
1521 case AsmToken::Greater:
1522 Kind = MCBinaryExpr::GT;
1523 return 3;
1524 case AsmToken::GreaterEqual:
1525 Kind = MCBinaryExpr::GTE;
1526 return 3;
1527
1528 // Low Intermediate Precedence: +, -
1529 case AsmToken::Plus:
1530 Kind = MCBinaryExpr::Add;
1531 return 4;
1532 case AsmToken::Minus:
1533 Kind = MCBinaryExpr::Sub;
1534 return 4;
1535
1536 // High Intermediate Precedence: |, &, ^
1537 //
1538 // FIXME: gas seems to support '!' as an infix operator?
1539 case AsmToken::Pipe:
1540 Kind = MCBinaryExpr::Or;
1541 return 5;
1542 case AsmToken::Caret:
1543 Kind = MCBinaryExpr::Xor;
1544 return 5;
1545 case AsmToken::Amp:
1546 Kind = MCBinaryExpr::And;
1547 return 5;
1548
1549 // Highest Precedence: *, /, %, <<, >>
1550 case AsmToken::Star:
1551 Kind = MCBinaryExpr::Mul;
1552 return 6;
1553 case AsmToken::Slash:
1554 Kind = MCBinaryExpr::Div;
1555 return 6;
1556 case AsmToken::Percent:
1557 Kind = MCBinaryExpr::Mod;
1558 return 6;
1559 case AsmToken::LessLess:
1560 Kind = MCBinaryExpr::Shl;
1561 return 6;
1562 case AsmToken::GreaterGreater:
1563 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1564 return 6;
1565 }
1566}
1567
1568unsigned AsmParser::getBinOpPrecedence(AsmToken::TokenKind K,
1569 MCBinaryExpr::Opcode &Kind) {
1570 bool ShouldUseLogicalShr = MAI.shouldUseLogicalShr();
1571 return IsDarwin ? getDarwinBinOpPrecedence(K, Kind, ShouldUseLogicalShr)
1572 : getGNUBinOpPrecedence(K, Kind, ShouldUseLogicalShr);
1573}
1574
Jim Grosbach4b905842013-09-20 23:08:21 +00001575/// \brief Parse all binary operators with precedence >= 'Precedence'.
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001576/// Res contains the LHS of the expression on input.
Jim Grosbach4b905842013-09-20 23:08:21 +00001577bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
Chris Lattner528d00b2010-01-15 19:28:38 +00001578 SMLoc &EndLoc) {
Chad Rosier9245e122017-01-19 20:06:32 +00001579 SMLoc StartLoc = Lexer.getLoc();
Eugene Zelenko33d7b762016-08-23 17:14:32 +00001580 while (true) {
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001581 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001582 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001583
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001584 // If the next token is lower precedence than we are allowed to eat, return
1585 // successfully with what we ate already.
1586 if (TokPrec < Precedence)
1587 return false;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001588
Sean Callanan686ed8d2010-01-19 20:22:31 +00001589 Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +00001590
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001591 // Eat the next primary expression.
Daniel Dunbarf3636452009-08-31 08:07:22 +00001592 const MCExpr *RHS;
Jim Grosbach4b905842013-09-20 23:08:21 +00001593 if (parsePrimaryExpr(RHS, EndLoc))
1594 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001595
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001596 // If BinOp binds less tightly with RHS than the operator after RHS, let
1597 // the pending operator take RHS as its LHS.
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001598 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001599 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Jim Grosbach4b905842013-09-20 23:08:21 +00001600 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1601 return true;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001602
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001603 // Merge LHS and RHS according to operator.
Chad Rosier9245e122017-01-19 20:06:32 +00001604 Res = MCBinaryExpr::create(Kind, Res, RHS, getContext(), StartLoc);
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001605 }
1606}
1607
Chris Lattner36e02122009-06-21 20:54:55 +00001608/// ParseStatement:
1609/// ::= EndOfStatement
Chris Lattnere5074c42009-06-22 01:29:09 +00001610/// ::= Label* Directive ...Operands... EndOfStatement
1611/// ::= Label* Identifier OperandList* EndOfStatement
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001612bool AsmParser::parseStatement(ParseStatementInfo &Info,
1613 MCAsmParserSemaCallback *SI) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001614 assert(!hasPendingError() && "parseStatement started with pending error");
Nirav Davefd910412016-06-17 16:06:17 +00001615 // Eat initial spaces and comments
1616 while (Lexer.is(AsmToken::Space))
1617 Lex();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001618 if (Lexer.is(AsmToken::EndOfStatement)) {
Nirav Davefd910412016-06-17 16:06:17 +00001619 // if this is a line comment we can drop it safely
Nirav Dave670109d2017-06-09 14:04:03 +00001620 if (getTok().getString().empty() || getTok().getString().front() == '\r' ||
Nirav Davefd910412016-06-17 16:06:17 +00001621 getTok().getString().front() == '\n')
1622 Out.AddBlankLine();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001623 Lex();
Chris Lattner36e02122009-06-21 20:54:55 +00001624 return false;
Chris Lattner36e02122009-06-21 20:54:55 +00001625 }
Nirav Davefd910412016-06-17 16:06:17 +00001626 // Statements always start with an identifier.
Sean Callanan936b0d32010-01-19 21:44:56 +00001627 AsmToken ID = getTok();
Daniel Dunbaree4465c2009-07-28 16:38:40 +00001628 SMLoc IDLoc = ID.getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001629 StringRef IDVal;
Kevin Enderby0510b482010-05-17 23:08:19 +00001630 int64_t LocalLabelVal = -1;
Nirav Davefd910412016-06-17 16:06:17 +00001631 if (Lexer.is(AsmToken::HashDirective))
Jim Grosbach4b905842013-09-20 23:08:21 +00001632 return parseCppHashLineFilenameComment(IDLoc);
Kevin Enderbyfa3c6f12010-12-24 00:12:02 +00001633 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderby0510b482010-05-17 23:08:19 +00001634 if (Lexer.is(AsmToken::Integer)) {
1635 LocalLabelVal = getTok().getIntVal();
1636 if (LocalLabelVal < 0) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001637 if (!TheCondState.Ignore) {
1638 Lex(); // always eat a token
1639 return Error(IDLoc, "unexpected token at start of statement");
1640 }
Kevin Enderby0510b482010-05-17 23:08:19 +00001641 IDVal = "";
Eli Bendersky88024712013-01-16 19:32:36 +00001642 } else {
Kevin Enderby0510b482010-05-17 23:08:19 +00001643 IDVal = getTok().getString();
1644 Lex(); // Consume the integer token to be used as an identifier token.
1645 if (Lexer.getKind() != AsmToken::Colon) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001646 if (!TheCondState.Ignore) {
1647 Lex(); // always eat a token
1648 return Error(IDLoc, "unexpected token at start of statement");
1649 }
Kevin Enderby0510b482010-05-17 23:08:19 +00001650 }
1651 }
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001652 } else if (Lexer.is(AsmToken::Dot)) {
1653 // Treat '.' as a valid identifier in this context.
1654 Lex();
1655 IDVal = ".";
Colin LeMahieu8a0453e2015-11-09 00:31:07 +00001656 } else if (Lexer.is(AsmToken::LCurly)) {
1657 // Treat '{' as a valid identifier in this context.
1658 Lex();
1659 IDVal = "{";
1660
1661 } else if (Lexer.is(AsmToken::RCurly)) {
1662 // Treat '}' as a valid identifier in this context.
1663 Lex();
1664 IDVal = "}";
Yonghong Song06ff6552017-09-12 17:55:23 +00001665 } else if (Lexer.is(AsmToken::Star) &&
1666 getTargetParser().starIsStartOfStatement()) {
1667 // Accept '*' as a valid start of statement.
1668 Lex();
1669 IDVal = "*";
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001670 } else if (parseIdentifier(IDVal)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001671 if (!TheCondState.Ignore) {
1672 Lex(); // always eat a token
1673 return Error(IDLoc, "unexpected token at start of statement");
1674 }
Chris Lattner926885c2010-04-17 18:14:27 +00001675 IDVal = "";
1676 }
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001677
Chris Lattner926885c2010-04-17 18:14:27 +00001678 // Handle conditional assembly here before checking for skipping. We
1679 // have to do this so that .endif isn't skipped in a ".if 0" block for
1680 // example.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001681 StringMap<DirectiveKind>::const_iterator DirKindIt =
Jim Grosbach4b905842013-09-20 23:08:21 +00001682 DirectiveKindMap.find(IDVal);
1683 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1684 ? DK_NO_DIRECTIVE
1685 : DirKindIt->getValue();
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001686 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001687 default:
1688 break;
1689 case DK_IF:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001690 case DK_IFEQ:
1691 case DK_IFGE:
1692 case DK_IFGT:
1693 case DK_IFLE:
1694 case DK_IFLT:
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00001695 case DK_IFNE:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001696 return parseDirectiveIf(IDLoc, DirKind);
Jim Grosbach4b905842013-09-20 23:08:21 +00001697 case DK_IFB:
1698 return parseDirectiveIfb(IDLoc, true);
1699 case DK_IFNB:
1700 return parseDirectiveIfb(IDLoc, false);
1701 case DK_IFC:
1702 return parseDirectiveIfc(IDLoc, true);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00001703 case DK_IFEQS:
Sid Manning51c35602015-03-18 14:20:54 +00001704 return parseDirectiveIfeqs(IDLoc, true);
Jim Grosbach4b905842013-09-20 23:08:21 +00001705 case DK_IFNC:
1706 return parseDirectiveIfc(IDLoc, false);
Sid Manning51c35602015-03-18 14:20:54 +00001707 case DK_IFNES:
1708 return parseDirectiveIfeqs(IDLoc, false);
Jim Grosbach4b905842013-09-20 23:08:21 +00001709 case DK_IFDEF:
1710 return parseDirectiveIfdef(IDLoc, true);
1711 case DK_IFNDEF:
1712 case DK_IFNOTDEF:
1713 return parseDirectiveIfdef(IDLoc, false);
1714 case DK_ELSEIF:
1715 return parseDirectiveElseIf(IDLoc);
1716 case DK_ELSE:
1717 return parseDirectiveElse(IDLoc);
1718 case DK_ENDIF:
1719 return parseDirectiveEndIf(IDLoc);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001720 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001721
Eli Bendersky88024712013-01-16 19:32:36 +00001722 // Ignore the statement if in the middle of inactive conditional
1723 // (e.g. ".if 0").
Chad Rosiereda70b32012-10-20 00:47:08 +00001724 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001725 eatToEndOfStatement();
Chris Lattner926885c2010-04-17 18:14:27 +00001726 return false;
1727 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001728
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001729 // FIXME: Recurse on local labels?
1730
1731 // See what kind of statement we have.
1732 switch (Lexer.getKind()) {
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001733 case AsmToken::Colon: {
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001734 if (!getTargetParser().isLabel(ID))
1735 break;
Nirav Davef43cc9f2016-10-10 15:24:54 +00001736 if (checkForValidSection())
1737 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00001738
Chris Lattner36e02122009-06-21 20:54:55 +00001739 // identifier ':' -> Label.
Sean Callanan686ed8d2010-01-19 20:22:31 +00001740 Lex();
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001741
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001742 // Diagnose attempt to use '.' as a label.
1743 if (IDVal == ".")
1744 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1745
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001746 // Diagnose attempt to use a variable as a label.
1747 //
1748 // FIXME: Diagnostics. Note the location of the definition as a label.
1749 // FIXME: This doesn't diagnose assignment to a symbol which has been
1750 // implicitly marked as external.
Kevin Enderby0510b482010-05-17 23:08:19 +00001751 MCSymbol *Sym;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001752 if (LocalLabelVal == -1) {
1753 if (ParsingInlineAsm && SI) {
Nico Weber67e715f2015-06-19 23:43:47 +00001754 StringRef RewrittenLabel =
1755 SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true);
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00001756 assert(!RewrittenLabel.empty() &&
Nico Weber67e715f2015-06-19 23:43:47 +00001757 "We should have an internal name here.");
Craig Topper7d5b2312015-10-10 05:25:02 +00001758 Info.AsmRewrites->emplace_back(AOK_Label, IDLoc, IDVal.size(),
1759 RewrittenLabel);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001760 IDVal = RewrittenLabel;
1761 }
Jim Grosbach6f482002015-05-18 18:43:14 +00001762 Sym = getContext().getOrCreateSymbol(IDVal);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001763 } else
Jim Grosbach6f482002015-05-18 18:43:14 +00001764 Sym = Ctx.createDirectionalLocalSymbol(LocalLabelVal);
Nirav Dave9263ae32016-08-02 19:17:54 +00001765 // End of Labels should be treated as end of line for lexing
1766 // purposes but that information is not available to the Lexer who
1767 // does not understand Labels. This may cause us to see a Hash
1768 // here instead of a preprocessor line comment.
1769 if (getTok().is(AsmToken::Hash)) {
1770 StringRef CommentStr = parseStringToEndOfStatement();
1771 Lexer.Lex();
1772 Lexer.UnLex(AsmToken(AsmToken::EndOfStatement, CommentStr));
1773 }
1774
Nirav Dave8ea792d2016-07-13 14:03:12 +00001775 // Consume any end of statement token, if present, to avoid spurious
1776 // AddBlankLine calls().
1777 if (getTok().is(AsmToken::EndOfStatement)) {
1778 Lex();
1779 }
1780
Daniel Dunbare73b2672009-08-26 22:13:22 +00001781 // Emit the label.
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +00001782 if (!getTargetParser().isParsingInlineAsm())
Rafael Espindolabe991572017-02-10 15:13:12 +00001783 Out.EmitLabel(Sym, IDLoc);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001784
Kevin Enderbye7739d42011-12-09 18:09:40 +00001785 // If we are generating dwarf for assembly source files then gather the
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001786 // info to make a dwarf label entry for this label if needed.
Kevin Enderbye7739d42011-12-09 18:09:40 +00001787 if (getContext().getGenDwarfForAssembly())
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001788 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1789 IDLoc);
Kevin Enderbye7739d42011-12-09 18:09:40 +00001790
Tim Northover1744d0a2013-10-25 12:49:50 +00001791 getTargetParser().onLabelParsed(Sym);
1792
Eli Friedman0f4871d2012-10-22 23:58:19 +00001793 return false;
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001794 }
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001795
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001796 case AsmToken::Equal:
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001797 if (!getTargetParser().equalIsAsmAssignment())
1798 break;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001799 // identifier '=' ... -> assignment statement
Sean Callanan686ed8d2010-01-19 20:22:31 +00001800 Lex();
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001801
Jim Grosbach4b905842013-09-20 23:08:21 +00001802 return parseAssignment(IDVal, true);
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001803
1804 default: // Normal instruction or directive.
1805 break;
Chris Lattner36e02122009-06-21 20:54:55 +00001806 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001807
1808 // If macros are enabled, check to see if this is a macro instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00001809 if (areMacrosEnabled())
Rafael Espindola22c38a02018-02-14 16:34:27 +00001810 if (const MCAsmMacro *M = getContext().lookupMacro(IDVal)) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001811 return handleMacroEntry(M, IDLoc);
Eli Bendersky38274122013-01-14 23:22:36 +00001812 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001813
Michael J. Spencer530ce852010-10-09 11:00:50 +00001814 // Otherwise, we have a normal instruction or directive.
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001815
Eli Bendersky17233942013-01-15 22:59:42 +00001816 // Directives start with "."
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001817 if (IDVal[0] == '.' && IDVal != ".") {
Eli Bendersky17233942013-01-15 22:59:42 +00001818 // There are several entities interested in parsing directives:
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001819 //
Eli Bendersky17233942013-01-15 22:59:42 +00001820 // 1. The target-specific assembly parser. Some directives are target
1821 // specific or may potentially behave differently on certain targets.
1822 // 2. Asm parser extensions. For example, platform-specific parsers
1823 // (like the ELF parser) register themselves as extensions.
1824 // 3. The generic directive parser implemented by this class. These are
1825 // all the directives that behave in a target and platform independent
1826 // manner, or at least have a default behavior that's shared between
1827 // all targets and platforms.
Akira Hatanakad3590752012-07-05 19:09:33 +00001828
Oliver Stannard21718282016-07-26 14:19:47 +00001829 getTargetParser().flushPendingInstructions(getStreamer());
1830
Nirav Dave2364748a2016-09-16 18:30:20 +00001831 SMLoc StartTokLoc = getTok().getLoc();
1832 bool TPDirectiveReturn = getTargetParser().ParseDirective(ID);
1833
1834 if (hasPendingError())
1835 return true;
1836 // Currently the return value should be true if we are
1837 // uninterested but as this is at odds with the standard parsing
1838 // convention (return true = error) we have instances of a parsed
1839 // directive that fails returning true as an error. Catch these
1840 // cases as best as possible errors here.
1841 if (TPDirectiveReturn && StartTokLoc != getTok().getLoc())
1842 return true;
1843 // Return if we did some parsing or believe we succeeded.
1844 if (!TPDirectiveReturn || StartTokLoc != getTok().getLoc())
Akira Hatanakad3590752012-07-05 19:09:33 +00001845 return false;
1846
Alp Tokercb402912014-01-24 17:20:08 +00001847 // Next, check the extension directive map to see if any extension has
Eli Bendersky17233942013-01-15 22:59:42 +00001848 // registered itself to parse this directive.
Jim Grosbach4b905842013-09-20 23:08:21 +00001849 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1850 ExtensionDirectiveMap.lookup(IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +00001851 if (Handler.first)
1852 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1853
1854 // Finally, if no one else is interested in this directive, it must be
1855 // generic and familiar to this class.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001856 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001857 default:
1858 break;
1859 case DK_SET:
1860 case DK_EQU:
1861 return parseDirectiveSet(IDVal, true);
1862 case DK_EQUIV:
1863 return parseDirectiveSet(IDVal, false);
1864 case DK_ASCII:
1865 return parseDirectiveAscii(IDVal, false);
1866 case DK_ASCIZ:
1867 case DK_STRING:
1868 return parseDirectiveAscii(IDVal, true);
1869 case DK_BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001870 case DK_DC_B:
1871 return parseDirectiveValue(IDVal, 1);
1872 case DK_DC:
1873 case DK_DC_W:
Jim Grosbach4b905842013-09-20 23:08:21 +00001874 case DK_SHORT:
1875 case DK_VALUE:
1876 case DK_2BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001877 return parseDirectiveValue(IDVal, 2);
Jim Grosbach4b905842013-09-20 23:08:21 +00001878 case DK_LONG:
1879 case DK_INT:
1880 case DK_4BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001881 case DK_DC_L:
1882 return parseDirectiveValue(IDVal, 4);
Jim Grosbach4b905842013-09-20 23:08:21 +00001883 case DK_QUAD:
1884 case DK_8BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001885 return parseDirectiveValue(IDVal, 8);
1886 case DK_DC_A:
Konstantin Zhuravlyovdc77b2e2017-04-17 17:41:25 +00001887 return parseDirectiveValue(
1888 IDVal, getContext().getAsmInfo()->getCodePointerSize());
David Woodhoused6de0d92014-02-01 16:20:59 +00001889 case DK_OCTA:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001890 return parseDirectiveOctaValue(IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001891 case DK_SINGLE:
1892 case DK_FLOAT:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001893 case DK_DC_S:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001894 return parseDirectiveRealValue(IDVal, APFloat::IEEEsingle());
Jim Grosbach4b905842013-09-20 23:08:21 +00001895 case DK_DOUBLE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001896 case DK_DC_D:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001897 return parseDirectiveRealValue(IDVal, APFloat::IEEEdouble());
Jim Grosbach4b905842013-09-20 23:08:21 +00001898 case DK_ALIGN: {
1899 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1900 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1901 }
1902 case DK_ALIGN32: {
1903 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1904 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1905 }
1906 case DK_BALIGN:
1907 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1908 case DK_BALIGNW:
1909 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1910 case DK_BALIGNL:
1911 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1912 case DK_P2ALIGN:
1913 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1914 case DK_P2ALIGNW:
1915 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1916 case DK_P2ALIGNL:
1917 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1918 case DK_ORG:
1919 return parseDirectiveOrg();
1920 case DK_FILL:
1921 return parseDirectiveFill();
1922 case DK_ZERO:
1923 return parseDirectiveZero();
1924 case DK_EXTERN:
1925 eatToEndOfStatement(); // .extern is the default, ignore it.
1926 return false;
1927 case DK_GLOBL:
1928 case DK_GLOBAL:
1929 return parseDirectiveSymbolAttribute(MCSA_Global);
1930 case DK_LAZY_REFERENCE:
1931 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1932 case DK_NO_DEAD_STRIP:
1933 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1934 case DK_SYMBOL_RESOLVER:
1935 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1936 case DK_PRIVATE_EXTERN:
1937 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1938 case DK_REFERENCE:
1939 return parseDirectiveSymbolAttribute(MCSA_Reference);
1940 case DK_WEAK_DEFINITION:
1941 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1942 case DK_WEAK_REFERENCE:
1943 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1944 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1945 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1946 case DK_COMM:
1947 case DK_COMMON:
1948 return parseDirectiveComm(/*IsLocal=*/false);
1949 case DK_LCOMM:
1950 return parseDirectiveComm(/*IsLocal=*/true);
1951 case DK_ABORT:
1952 return parseDirectiveAbort();
1953 case DK_INCLUDE:
1954 return parseDirectiveInclude();
1955 case DK_INCBIN:
1956 return parseDirectiveIncbin();
1957 case DK_CODE16:
1958 case DK_CODE16GCC:
Nirav Davefd910412016-06-17 16:06:17 +00001959 return TokError(Twine(IDVal) +
1960 " not currently supported for this target");
Jim Grosbach4b905842013-09-20 23:08:21 +00001961 case DK_REPT:
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00001962 return parseDirectiveRept(IDLoc, IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001963 case DK_IRP:
1964 return parseDirectiveIrp(IDLoc);
1965 case DK_IRPC:
1966 return parseDirectiveIrpc(IDLoc);
1967 case DK_ENDR:
1968 return parseDirectiveEndr(IDLoc);
1969 case DK_BUNDLE_ALIGN_MODE:
1970 return parseDirectiveBundleAlignMode();
1971 case DK_BUNDLE_LOCK:
1972 return parseDirectiveBundleLock();
1973 case DK_BUNDLE_UNLOCK:
1974 return parseDirectiveBundleUnlock();
1975 case DK_SLEB128:
1976 return parseDirectiveLEB128(true);
1977 case DK_ULEB128:
1978 return parseDirectiveLEB128(false);
1979 case DK_SPACE:
1980 case DK_SKIP:
1981 return parseDirectiveSpace(IDVal);
1982 case DK_FILE:
1983 return parseDirectiveFile(IDLoc);
1984 case DK_LINE:
1985 return parseDirectiveLine();
1986 case DK_LOC:
1987 return parseDirectiveLoc();
1988 case DK_STABS:
1989 return parseDirectiveStabs();
Reid Kleckner2214ed82016-01-29 00:49:42 +00001990 case DK_CV_FILE:
1991 return parseDirectiveCVFile();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00001992 case DK_CV_FUNC_ID:
1993 return parseDirectiveCVFuncId();
1994 case DK_CV_INLINE_SITE_ID:
1995 return parseDirectiveCVInlineSiteId();
Reid Kleckner2214ed82016-01-29 00:49:42 +00001996 case DK_CV_LOC:
1997 return parseDirectiveCVLoc();
1998 case DK_CV_LINETABLE:
1999 return parseDirectiveCVLinetable();
David Majnemer6fcbd7e2016-01-29 19:24:12 +00002000 case DK_CV_INLINE_LINETABLE:
2001 return parseDirectiveCVInlineLinetable();
David Majnemer408b5e62016-02-05 01:55:49 +00002002 case DK_CV_DEF_RANGE:
2003 return parseDirectiveCVDefRange();
Reid Kleckner2214ed82016-01-29 00:49:42 +00002004 case DK_CV_STRINGTABLE:
2005 return parseDirectiveCVStringTable();
2006 case DK_CV_FILECHECKSUMS:
2007 return parseDirectiveCVFileChecksums();
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00002008 case DK_CV_FILECHECKSUM_OFFSET:
2009 return parseDirectiveCVFileChecksumOffset();
Reid Kleckner9cdd4df2017-10-11 21:24:33 +00002010 case DK_CV_FPO_DATA:
2011 return parseDirectiveCVFPOData();
Jim Grosbach4b905842013-09-20 23:08:21 +00002012 case DK_CFI_SECTIONS:
2013 return parseDirectiveCFISections();
2014 case DK_CFI_STARTPROC:
2015 return parseDirectiveCFIStartProc();
2016 case DK_CFI_ENDPROC:
2017 return parseDirectiveCFIEndProc();
2018 case DK_CFI_DEF_CFA:
2019 return parseDirectiveCFIDefCfa(IDLoc);
2020 case DK_CFI_DEF_CFA_OFFSET:
2021 return parseDirectiveCFIDefCfaOffset();
2022 case DK_CFI_ADJUST_CFA_OFFSET:
2023 return parseDirectiveCFIAdjustCfaOffset();
2024 case DK_CFI_DEF_CFA_REGISTER:
2025 return parseDirectiveCFIDefCfaRegister(IDLoc);
2026 case DK_CFI_OFFSET:
2027 return parseDirectiveCFIOffset(IDLoc);
2028 case DK_CFI_REL_OFFSET:
2029 return parseDirectiveCFIRelOffset(IDLoc);
2030 case DK_CFI_PERSONALITY:
2031 return parseDirectiveCFIPersonalityOrLsda(true);
2032 case DK_CFI_LSDA:
2033 return parseDirectiveCFIPersonalityOrLsda(false);
2034 case DK_CFI_REMEMBER_STATE:
2035 return parseDirectiveCFIRememberState();
2036 case DK_CFI_RESTORE_STATE:
2037 return parseDirectiveCFIRestoreState();
2038 case DK_CFI_SAME_VALUE:
2039 return parseDirectiveCFISameValue(IDLoc);
2040 case DK_CFI_RESTORE:
2041 return parseDirectiveCFIRestore(IDLoc);
2042 case DK_CFI_ESCAPE:
2043 return parseDirectiveCFIEscape();
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +00002044 case DK_CFI_RETURN_COLUMN:
2045 return parseDirectiveCFIReturnColumn(IDLoc);
Jim Grosbach4b905842013-09-20 23:08:21 +00002046 case DK_CFI_SIGNAL_FRAME:
2047 return parseDirectiveCFISignalFrame();
2048 case DK_CFI_UNDEFINED:
2049 return parseDirectiveCFIUndefined(IDLoc);
2050 case DK_CFI_REGISTER:
2051 return parseDirectiveCFIRegister(IDLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00002052 case DK_CFI_WINDOW_SAVE:
2053 return parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +00002054 case DK_MACROS_ON:
2055 case DK_MACROS_OFF:
2056 return parseDirectiveMacrosOnOff(IDVal);
2057 case DK_MACRO:
2058 return parseDirectiveMacro(IDLoc);
Michael Zuckerman56704612017-05-01 13:20:12 +00002059 case DK_ALTMACRO:
2060 case DK_NOALTMACRO:
2061 return parseDirectiveAltmacro(IDVal);
Nico Weber155dccd12014-07-24 17:08:39 +00002062 case DK_EXITM:
2063 return parseDirectiveExitMacro(IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00002064 case DK_ENDM:
2065 case DK_ENDMACRO:
2066 return parseDirectiveEndMacro(IDVal);
2067 case DK_PURGEM:
2068 return parseDirectivePurgeMacro(IDLoc);
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00002069 case DK_END:
2070 return parseDirectiveEnd(IDLoc);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00002071 case DK_ERR:
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00002072 return parseDirectiveError(IDLoc, false);
2073 case DK_ERROR:
2074 return parseDirectiveError(IDLoc, true);
Nico Weber404012b2014-07-24 16:26:06 +00002075 case DK_WARNING:
2076 return parseDirectiveWarning(IDLoc);
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002077 case DK_RELOC:
2078 return parseDirectiveReloc(IDLoc);
Petr Hosek4cb08ce2016-09-23 19:25:15 +00002079 case DK_DCB:
2080 case DK_DCB_W:
2081 return parseDirectiveDCB(IDVal, 2);
2082 case DK_DCB_B:
2083 return parseDirectiveDCB(IDVal, 1);
2084 case DK_DCB_D:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002085 return parseDirectiveRealDCB(IDVal, APFloat::IEEEdouble());
Petr Hosek4cb08ce2016-09-23 19:25:15 +00002086 case DK_DCB_L:
2087 return parseDirectiveDCB(IDVal, 4);
2088 case DK_DCB_S:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002089 return parseDirectiveRealDCB(IDVal, APFloat::IEEEsingle());
Petr Hosek731bb9c2016-08-23 21:34:53 +00002090 case DK_DC_X:
Petr Hosek4cb08ce2016-09-23 19:25:15 +00002091 case DK_DCB_X:
Petr Hosek731bb9c2016-08-23 21:34:53 +00002092 return TokError(Twine(IDVal) +
2093 " not currently supported for this target");
Petr Hosek85b2f672016-09-23 21:53:36 +00002094 case DK_DS:
2095 case DK_DS_W:
2096 return parseDirectiveDS(IDVal, 2);
2097 case DK_DS_B:
2098 return parseDirectiveDS(IDVal, 1);
2099 case DK_DS_D:
2100 return parseDirectiveDS(IDVal, 8);
2101 case DK_DS_L:
2102 case DK_DS_S:
2103 return parseDirectiveDS(IDVal, 4);
2104 case DK_DS_P:
2105 case DK_DS_X:
2106 return parseDirectiveDS(IDVal, 12);
Coby Tayree01e53202017-10-02 14:36:31 +00002107 case DK_PRINT:
2108 return parseDirectivePrint(IDLoc);
Eli Friedman20b02642010-07-19 04:17:25 +00002109 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002110
Jim Grosbach758e0cc2012-05-01 18:38:27 +00002111 return Error(IDLoc, "unknown directive");
Chris Lattnere5074c42009-06-22 01:29:09 +00002112 }
Chris Lattner36e02122009-06-21 20:54:55 +00002113
Chad Rosierc7f552c2013-02-12 21:33:51 +00002114 // __asm _emit or __asm __emit
2115 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
2116 IDVal == "_EMIT" || IDVal == "__EMIT"))
Jim Grosbach4b905842013-09-20 23:08:21 +00002117 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
Chad Rosierc7f552c2013-02-12 21:33:51 +00002118
2119 // __asm align
2120 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
Jim Grosbach4b905842013-09-20 23:08:21 +00002121 return parseDirectiveMSAlign(IDLoc, Info);
Eli Friedman0f4871d2012-10-22 23:58:19 +00002122
Coby Tayree3847be92017-04-04 17:57:23 +00002123 if (ParsingInlineAsm && (IDVal == "even" || IDVal == "EVEN"))
Michael Zuckerman02ecd432015-12-13 17:07:23 +00002124 Info.AsmRewrites->emplace_back(AOK_EVEN, IDLoc, 4);
Nirav Davef43cc9f2016-10-10 15:24:54 +00002125 if (checkForValidSection())
2126 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00002127
Chris Lattner7cbfa442010-05-19 23:34:33 +00002128 // Canonicalize the opcode to lower case.
Eli Bendersky88024712013-01-16 19:32:36 +00002129 std::string OpcodeStr = IDVal.lower();
Chad Rosierf0e87202012-10-25 20:41:34 +00002130 ParseInstructionInfo IInfo(Info.AsmRewrites);
Nirav Dave2364748a2016-09-16 18:30:20 +00002131 bool ParseHadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, ID,
2132 Info.ParsedOperands);
2133 Info.ParseError = ParseHadError;
Chris Lattnere5074c42009-06-22 01:29:09 +00002134
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002135 // Dump the parsed representation, if requested.
2136 if (getShowParsedOperands()) {
2137 SmallString<256> Str;
2138 raw_svector_ostream OS(Str);
2139 OS << "parsed instruction: [";
Eli Friedman0f4871d2012-10-22 23:58:19 +00002140 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002141 if (i != 0)
2142 OS << ", ";
Eli Friedman0f4871d2012-10-22 23:58:19 +00002143 Info.ParsedOperands[i]->print(OS);
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002144 }
2145 OS << "]";
2146
Jim Grosbach4b905842013-09-20 23:08:21 +00002147 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002148 }
2149
Nirav Dave2364748a2016-09-16 18:30:20 +00002150 // Fail even if ParseInstruction erroneously returns false.
2151 if (hasPendingError() || ParseHadError)
2152 return true;
2153
Oliver Stannard8b273082014-06-19 15:52:37 +00002154 // If we are generating dwarf for the current section then generate a .loc
2155 // directive for the instruction.
Nirav Dave2364748a2016-09-16 18:30:20 +00002156 if (!ParseHadError && getContext().getGenDwarfForAssembly() &&
Oliver Stannard8b273082014-06-19 15:52:37 +00002157 getContext().getGenDwarfSectionSyms().count(
Eric Christopher445c9522016-10-14 05:47:37 +00002158 getStreamer().getCurrentSectionOnly())) {
Saleem Abdulrasool4d6ed7c2014-12-24 06:32:43 +00002159 unsigned Line;
2160 if (ActiveMacros.empty())
2161 Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
2162 else
Frederic Riss16238d92015-06-25 21:57:33 +00002163 Line = SrcMgr.FindLineNumber(ActiveMacros.front()->InstantiationLoc,
2164 ActiveMacros.front()->ExitBuffer);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002165
Eli Bendersky88024712013-01-16 19:32:36 +00002166 // If we previously parsed a cpp hash file line comment then make sure the
2167 // current Dwarf File is for the CppHashFilename if not then emit the
2168 // Dwarf File table for it and adjust the line number for the .loc.
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00002169 if (!CppHashInfo.Filename.empty()) {
David Blaikiec714ef42014-03-17 01:52:11 +00002170 unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
Tim Northoverc0bef992016-04-13 19:46:54 +00002171 0, StringRef(), CppHashInfo.Filename);
David Blaikiec714ef42014-03-17 01:52:11 +00002172 getContext().setGenDwarfFileNumber(FileNumber);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002173
Jim Grosbach4b905842013-09-20 23:08:21 +00002174 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
2175 // cache with the different Loc from the call above we save the last
2176 // info we queried here with SrcMgr.FindLineNumber().
2177 unsigned CppHashLocLineNo;
Tim Northoverc0bef992016-04-13 19:46:54 +00002178 if (LastQueryIDLoc == CppHashInfo.Loc &&
2179 LastQueryBuffer == CppHashInfo.Buf)
Jim Grosbach4b905842013-09-20 23:08:21 +00002180 CppHashLocLineNo = LastQueryLine;
2181 else {
Tim Northoverc0bef992016-04-13 19:46:54 +00002182 CppHashLocLineNo =
2183 SrcMgr.FindLineNumber(CppHashInfo.Loc, CppHashInfo.Buf);
Jim Grosbach4b905842013-09-20 23:08:21 +00002184 LastQueryLine = CppHashLocLineNo;
Tim Northoverc0bef992016-04-13 19:46:54 +00002185 LastQueryIDLoc = CppHashInfo.Loc;
2186 LastQueryBuffer = CppHashInfo.Buf;
Jim Grosbach4b905842013-09-20 23:08:21 +00002187 }
Tim Northoverc0bef992016-04-13 19:46:54 +00002188 Line = CppHashInfo.LineNumber - 1 + (Line - CppHashLocLineNo);
Eli Bendersky88024712013-01-16 19:32:36 +00002189 }
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002190
Jim Grosbach4b905842013-09-20 23:08:21 +00002191 getStreamer().EmitDwarfLocDirective(
2192 getContext().getGenDwarfFileNumber(), Line, 0,
2193 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
2194 StringRef());
Kevin Enderby6469fc22011-11-01 22:27:22 +00002195 }
2196
Daniel Dunbarce0c1e12010-05-04 00:33:07 +00002197 // If parsing succeeded, match the instruction.
Nirav Dave2364748a2016-09-16 18:30:20 +00002198 if (!ParseHadError) {
Tim Northover26bb14e2014-08-18 11:49:42 +00002199 uint64_t ErrorInfo;
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +00002200 if (getTargetParser().MatchAndEmitInstruction(
2201 IDLoc, Info.Opcode, Info.ParsedOperands, Out, ErrorInfo,
2202 getTargetParser().isParsingInlineAsm()))
Nirav Dave2364748a2016-09-16 18:30:20 +00002203 return true;
Chad Rosier49963552012-10-13 00:26:04 +00002204 }
Chris Lattnera2a9d162010-09-11 16:18:25 +00002205 return false;
Chris Lattnerb0133452009-06-21 20:16:42 +00002206}
Chris Lattnerbedf6c22009-06-24 04:43:34 +00002207
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00002208// Parse and erase curly braces marking block start/end
2209bool
2210AsmParser::parseCurlyBlockScope(SmallVectorImpl<AsmRewrite> &AsmStrRewrites) {
2211 // Identify curly brace marking block start/end
2212 if (Lexer.isNot(AsmToken::LCurly) && Lexer.isNot(AsmToken::RCurly))
2213 return false;
2214
2215 SMLoc StartLoc = Lexer.getLoc();
2216 Lex(); // Eat the brace
2217 if (Lexer.is(AsmToken::EndOfStatement))
2218 Lex(); // Eat EndOfStatement following the brace
2219
2220 // Erase the block start/end brace from the output asm string
2221 AsmStrRewrites.emplace_back(AOK_Skip, StartLoc, Lexer.getLoc().getPointer() -
2222 StartLoc.getPointer());
2223 return true;
2224}
2225
Jim Grosbach4b905842013-09-20 23:08:21 +00002226/// parseCppHashLineFilenameComment as this:
Kevin Enderby72553612011-09-13 23:45:18 +00002227/// ::= # number "filename"
Craig Topper3c76c522015-09-20 23:35:59 +00002228bool AsmParser::parseCppHashLineFilenameComment(SMLoc L) {
Kevin Enderby72553612011-09-13 23:45:18 +00002229 Lex(); // Eat the hash token.
Nirav Davefd910412016-06-17 16:06:17 +00002230 // Lexer only ever emits HashDirective if it fully formed if it's
2231 // done the checking already so this is an internal error.
2232 assert(getTok().is(AsmToken::Integer) &&
2233 "Lexing Cpp line comment: Expected Integer");
Kevin Enderby72553612011-09-13 23:45:18 +00002234 int64_t LineNumber = getTok().getIntVal();
Kevin Enderby72553612011-09-13 23:45:18 +00002235 Lex();
Nirav Davefd910412016-06-17 16:06:17 +00002236 assert(getTok().is(AsmToken::String) &&
2237 "Lexing Cpp line comment: Expected String");
Kevin Enderby72553612011-09-13 23:45:18 +00002238 StringRef Filename = getTok().getString();
Nirav Davefd910412016-06-17 16:06:17 +00002239 Lex();
Nirav Dave2364748a2016-09-16 18:30:20 +00002240
Kevin Enderby72553612011-09-13 23:45:18 +00002241 // Get rid of the enclosing quotes.
Jim Grosbach4b905842013-09-20 23:08:21 +00002242 Filename = Filename.substr(1, Filename.size() - 2);
Kevin Enderby72553612011-09-13 23:45:18 +00002243
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002244 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
Tim Northoverc0bef992016-04-13 19:46:54 +00002245 CppHashInfo.Loc = L;
2246 CppHashInfo.Filename = Filename;
2247 CppHashInfo.LineNumber = LineNumber;
2248 CppHashInfo.Buf = CurBuffer;
Kevin Enderby72553612011-09-13 23:45:18 +00002249 return false;
2250}
2251
Jim Grosbach4b905842013-09-20 23:08:21 +00002252/// \brief will use the last parsed cpp hash line filename comment
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002253/// for the Filename and LineNo if any in the diagnostic.
2254void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002255 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002256 raw_ostream &OS = errs();
2257
2258 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
Craig Topper3c76c522015-09-20 23:35:59 +00002259 SMLoc DiagLoc = Diag.getLoc();
Alp Tokera55b95b2014-07-06 10:33:31 +00002260 unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2261 unsigned CppHashBuf =
Tim Northoverc0bef992016-04-13 19:46:54 +00002262 Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashInfo.Loc);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002263
Jim Grosbach4b905842013-09-20 23:08:21 +00002264 // Like SourceMgr::printMessage() we need to print the include stack if any
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002265 // before printing the message.
Alp Tokera55b95b2014-07-06 10:33:31 +00002266 unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2267 if (!Parser->SavedDiagHandler && DiagCurBuffer &&
2268 DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002269 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
2270 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002271 }
2272
Eric Christophera7c32732012-12-18 00:30:54 +00002273 // If we have not parsed a cpp hash line filename comment or the source
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002274 // manager changed or buffer changed (like in a nested include) then just
2275 // print the normal diagnostic using its Filename and LineNo.
Tim Northoverc0bef992016-04-13 19:46:54 +00002276 if (!Parser->CppHashInfo.LineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002277 DiagBuf != CppHashBuf) {
Benjamin Kramer47f5e302011-10-16 10:48:29 +00002278 if (Parser->SavedDiagHandler)
2279 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
2280 else
Craig Topper353eda42014-04-24 06:44:33 +00002281 Diag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002282 return;
2283 }
2284
Eric Christophera7c32732012-12-18 00:30:54 +00002285 // Use the CppHashFilename and calculate a line number based on the
Tim Northoverc0bef992016-04-13 19:46:54 +00002286 // CppHashInfo.Loc and CppHashInfo.LineNumber relative to this Diag's SMLoc
2287 // for the diagnostic.
2288 const std::string &Filename = Parser->CppHashInfo.Filename;
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002289
2290 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
2291 int CppHashLocLineNo =
Tim Northoverc0bef992016-04-13 19:46:54 +00002292 Parser->SrcMgr.FindLineNumber(Parser->CppHashInfo.Loc, CppHashBuf);
Jim Grosbach4b905842013-09-20 23:08:21 +00002293 int LineNo =
Tim Northoverc0bef992016-04-13 19:46:54 +00002294 Parser->CppHashInfo.LineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002295
Jim Grosbach4b905842013-09-20 23:08:21 +00002296 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
2297 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
Chris Lattner72845262011-10-16 05:47:55 +00002298 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002299
Benjamin Kramer47f5e302011-10-16 10:48:29 +00002300 if (Parser->SavedDiagHandler)
2301 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
2302 else
Craig Topper353eda42014-04-24 06:44:33 +00002303 NewDiag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002304}
2305
Rafael Espindola2c064482012-08-21 18:29:30 +00002306// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
2307// difference being that that function accepts '@' as part of identifiers and
2308// we can't do that. AsmLexer.cpp should probably be changed to handle
2309// '@' as a special case when needed.
2310static bool isIdentifierChar(char c) {
Guy Benyei83c74e92013-02-12 21:21:59 +00002311 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
2312 c == '.';
Rafael Espindola2c064482012-08-21 18:29:30 +00002313}
2314
Rafael Espindola34b9c512012-06-03 23:57:14 +00002315bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00002316 ArrayRef<MCAsmMacroParameter> Parameters,
Toma Tabacu217116e2015-04-27 10:50:29 +00002317 ArrayRef<MCAsmMacroArgument> A,
Craig Topper3c76c522015-09-20 23:35:59 +00002318 bool EnableAtPseudoVariable, SMLoc L) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00002319 unsigned NParameters = Parameters.size();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002320 bool HasVararg = NParameters ? Parameters.back().Vararg : false;
Benjamin Kramer513e7442014-02-20 13:36:32 +00002321 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
Rafael Espindola1134ab232011-06-05 02:43:45 +00002322 return Error(L, "Wrong number of arguments");
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002323
Preston Gurd05500642012-09-19 20:36:12 +00002324 // A macro without parameters is handled differently on Darwin:
2325 // gas accepts no arguments and does no substitutions
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002326 while (!Body.empty()) {
2327 // Scan for the next substitution.
2328 std::size_t End = Body.size(), Pos = 0;
2329 for (; Pos != End; ++Pos) {
2330 // Check for a substitution or escape.
Benjamin Kramer513e7442014-02-20 13:36:32 +00002331 if (IsDarwin && !NParameters) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00002332 // This macro has no parameters, look for $0, $1, etc.
2333 if (Body[Pos] != '$' || Pos + 1 == End)
2334 continue;
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002335
Rafael Espindola1134ab232011-06-05 02:43:45 +00002336 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00002337 if (Next == '$' || Next == 'n' ||
2338 isdigit(static_cast<unsigned char>(Next)))
Rafael Espindola1134ab232011-06-05 02:43:45 +00002339 break;
2340 } else {
2341 // This macro has parameters, look for \foo, \bar, etc.
2342 if (Body[Pos] == '\\' && Pos + 1 != End)
2343 break;
2344 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002345 }
2346
2347 // Add the prefix.
2348 OS << Body.slice(0, Pos);
2349
2350 // Check if we reached the end.
2351 if (Pos == End)
2352 break;
2353
Benjamin Kramer513e7442014-02-20 13:36:32 +00002354 if (IsDarwin && !NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002355 switch (Body[Pos + 1]) {
2356 // $$ => $
Rafael Espindola1134ab232011-06-05 02:43:45 +00002357 case '$':
2358 OS << '$';
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002359 break;
2360
Jim Grosbach4b905842013-09-20 23:08:21 +00002361 // $n => number of arguments
Rafael Espindola1134ab232011-06-05 02:43:45 +00002362 case 'n':
2363 OS << A.size();
2364 break;
2365
Jim Grosbach4b905842013-09-20 23:08:21 +00002366 // $[0-9] => argument
Rafael Espindola1134ab232011-06-05 02:43:45 +00002367 default: {
2368 // Missing arguments are ignored.
Jim Grosbach4b905842013-09-20 23:08:21 +00002369 unsigned Index = Body[Pos + 1] - '0';
Rafael Espindola1134ab232011-06-05 02:43:45 +00002370 if (Index >= A.size())
2371 break;
2372
2373 // Otherwise substitute with the token values, with spaces eliminated.
Craig Topper84008482015-10-10 05:38:14 +00002374 for (const AsmToken &Token : A[Index])
2375 OS << Token.getString();
Rafael Espindola1134ab232011-06-05 02:43:45 +00002376 break;
2377 }
2378 }
2379 Pos += 2;
2380 } else {
2381 unsigned I = Pos + 1;
Toma Tabacu217116e2015-04-27 10:50:29 +00002382
2383 // Check for the \@ pseudo-variable.
2384 if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End)
Rafael Espindola1134ab232011-06-05 02:43:45 +00002385 ++I;
Toma Tabacu217116e2015-04-27 10:50:29 +00002386 else
2387 while (isIdentifierChar(Body[I]) && I + 1 != End)
2388 ++I;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002389
Jim Grosbach4b905842013-09-20 23:08:21 +00002390 const char *Begin = Body.data() + Pos + 1;
2391 StringRef Argument(Begin, I - (Pos + 1));
Rafael Espindola1134ab232011-06-05 02:43:45 +00002392 unsigned Index = 0;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002393
Toma Tabacu217116e2015-04-27 10:50:29 +00002394 if (Argument == "@") {
2395 OS << NumOfMacroInstantiations;
2396 Pos += 2;
Preston Gurd05500642012-09-19 20:36:12 +00002397 } else {
Toma Tabacu217116e2015-04-27 10:50:29 +00002398 for (; Index < NParameters; ++Index)
2399 if (Parameters[Index].Name == Argument)
2400 break;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002401
Toma Tabacu217116e2015-04-27 10:50:29 +00002402 if (Index == NParameters) {
2403 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
2404 Pos += 3;
2405 else {
2406 OS << '\\' << Argument;
2407 Pos = I;
2408 }
2409 } else {
2410 bool VarargParameter = HasVararg && Index == (NParameters - 1);
Craig Topper84008482015-10-10 05:38:14 +00002411 for (const AsmToken &Token : A[Index])
Michael Zuckerman56704612017-05-01 13:20:12 +00002412 // For altmacro mode, you can write '%expr'.
2413 // The prefix '%' evaluates the expression 'expr'
2414 // and uses the result as a string (e.g. replace %(1+2) with the string "3").
2415 // Here, we identify the integer token which is the result of the
2416 // absolute expression evaluation and replace it with its string representation.
2417 if ((Lexer.IsaAltMacroMode()) &&
2418 (*(Token.getString().begin()) == '%') && Token.is(AsmToken::Integer))
2419 // Emit an integer value to the buffer.
2420 OS << Token.getIntVal();
Michael Zuckerman1f1a9122017-05-10 13:08:11 +00002421 // Only Token that was validated as a string and begins with '<'
2422 // is considered altMacroString!!!
2423 else if ((Lexer.IsaAltMacroMode()) &&
2424 (*(Token.getString().begin()) == '<') &&
2425 Token.is(AsmToken::String)) {
2426 std::string Res;
2427 altMacroString(Token.getStringContents(), Res);
2428 OS << Res;
2429 }
Toma Tabacu217116e2015-04-27 10:50:29 +00002430 // We expect no quotes around the string's contents when
2431 // parsing for varargs.
Michael Zuckerman56704612017-05-01 13:20:12 +00002432 else if (Token.isNot(AsmToken::String) || VarargParameter)
Craig Topper84008482015-10-10 05:38:14 +00002433 OS << Token.getString();
Toma Tabacu217116e2015-04-27 10:50:29 +00002434 else
Craig Topper84008482015-10-10 05:38:14 +00002435 OS << Token.getStringContents();
Toma Tabacu217116e2015-04-27 10:50:29 +00002436
2437 Pos += 1 + Argument.size();
2438 }
Preston Gurd05500642012-09-19 20:36:12 +00002439 }
Rafael Espindola1134ab232011-06-05 02:43:45 +00002440 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002441 // Update the scan point.
Rafael Espindola1134ab232011-06-05 02:43:45 +00002442 Body = Body.substr(Pos);
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002443 }
Daniel Dunbar43235712010-07-18 18:54:11 +00002444
Rafael Espindola1134ab232011-06-05 02:43:45 +00002445 return false;
2446}
Daniel Dunbar43235712010-07-18 18:54:11 +00002447
Nico Weber2a8f9222014-07-24 16:29:04 +00002448MacroInstantiation::MacroInstantiation(SMLoc IL, int EB, SMLoc EL,
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002449 size_t CondStackDepth)
Rafael Espindolaf43a94e2014-08-17 22:48:55 +00002450 : InstantiationLoc(IL), ExitBuffer(EB), ExitLoc(EL),
Nico Weber155dccd12014-07-24 17:08:39 +00002451 CondStackDepth(CondStackDepth) {}
Daniel Dunbar43235712010-07-18 18:54:11 +00002452
Jim Grosbach4b905842013-09-20 23:08:21 +00002453static bool isOperator(AsmToken::TokenKind kind) {
2454 switch (kind) {
2455 default:
2456 return false;
2457 case AsmToken::Plus:
2458 case AsmToken::Minus:
2459 case AsmToken::Tilde:
2460 case AsmToken::Slash:
2461 case AsmToken::Star:
2462 case AsmToken::Dot:
2463 case AsmToken::Equal:
2464 case AsmToken::EqualEqual:
2465 case AsmToken::Pipe:
2466 case AsmToken::PipePipe:
2467 case AsmToken::Caret:
2468 case AsmToken::Amp:
2469 case AsmToken::AmpAmp:
2470 case AsmToken::Exclaim:
2471 case AsmToken::ExclaimEqual:
Jim Grosbach4b905842013-09-20 23:08:21 +00002472 case AsmToken::Less:
2473 case AsmToken::LessEqual:
2474 case AsmToken::LessLess:
2475 case AsmToken::LessGreater:
2476 case AsmToken::Greater:
2477 case AsmToken::GreaterEqual:
2478 case AsmToken::GreaterGreater:
2479 return true;
Preston Gurd05500642012-09-19 20:36:12 +00002480 }
2481}
2482
David Majnemer16252452014-01-29 00:07:39 +00002483namespace {
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002484
David Majnemer16252452014-01-29 00:07:39 +00002485class AsmLexerSkipSpaceRAII {
2486public:
2487 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
2488 Lexer.setSkipSpace(SkipSpace);
2489 }
2490
2491 ~AsmLexerSkipSpaceRAII() {
2492 Lexer.setSkipSpace(true);
2493 }
2494
2495private:
2496 AsmLexer &Lexer;
2497};
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002498
2499} // end anonymous namespace
David Majnemer16252452014-01-29 00:07:39 +00002500
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002501bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
2502
2503 if (Vararg) {
2504 if (Lexer.isNot(AsmToken::EndOfStatement)) {
2505 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002506 MA.emplace_back(AsmToken::String, Str);
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002507 }
2508 return false;
2509 }
2510
Rafael Espindola768b41c2012-06-15 14:02:34 +00002511 unsigned ParenLevel = 0;
Preston Gurd05500642012-09-19 20:36:12 +00002512
David Majnemer16252452014-01-29 00:07:39 +00002513 // Darwin doesn't use spaces to delmit arguments.
2514 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
Rafael Espindola768b41c2012-06-15 14:02:34 +00002515
Scott Egertona1fa68a2016-02-11 13:48:49 +00002516 bool SpaceEaten;
2517
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002518 while (true) {
Scott Egertona1fa68a2016-02-11 13:48:49 +00002519 SpaceEaten = false;
David Majnemer16252452014-01-29 00:07:39 +00002520 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002521 return TokError("unexpected token in macro instantiation");
Preston Gurd05500642012-09-19 20:36:12 +00002522
Scott Egertona1fa68a2016-02-11 13:48:49 +00002523 if (ParenLevel == 0) {
Preston Gurd05500642012-09-19 20:36:12 +00002524
Scott Egertona1fa68a2016-02-11 13:48:49 +00002525 if (Lexer.is(AsmToken::Comma))
2526 break;
2527
2528 if (Lexer.is(AsmToken::Space)) {
2529 SpaceEaten = true;
Nirav Dave1180e6892016-06-02 17:15:05 +00002530 Lexer.Lex(); // Eat spaces
Scott Egertona1fa68a2016-02-11 13:48:49 +00002531 }
Preston Gurd05500642012-09-19 20:36:12 +00002532
2533 // Spaces can delimit parameters, but could also be part an expression.
2534 // If the token after a space is an operator, add the token and the next
2535 // one into this argument
David Majnemer91fc4c22014-01-29 18:57:46 +00002536 if (!IsDarwin) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002537 if (isOperator(Lexer.getKind())) {
Scott Egertona1fa68a2016-02-11 13:48:49 +00002538 MA.push_back(getTok());
Nirav Dave1180e6892016-06-02 17:15:05 +00002539 Lexer.Lex();
Preston Gurd05500642012-09-19 20:36:12 +00002540
Scott Egertona1fa68a2016-02-11 13:48:49 +00002541 // Whitespace after an operator can be ignored.
2542 if (Lexer.is(AsmToken::Space))
Nirav Dave1180e6892016-06-02 17:15:05 +00002543 Lexer.Lex();
Scott Egertona1fa68a2016-02-11 13:48:49 +00002544
2545 continue;
Preston Gurd05500642012-09-19 20:36:12 +00002546 }
2547 }
Scott Egertona1fa68a2016-02-11 13:48:49 +00002548 if (SpaceEaten)
2549 break;
Preston Gurd05500642012-09-19 20:36:12 +00002550 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002551
Jim Grosbach4b905842013-09-20 23:08:21 +00002552 // handleMacroEntry relies on not advancing the lexer here
Rafael Espindola768b41c2012-06-15 14:02:34 +00002553 // to be able to fill in the remaining default parameter values
2554 if (Lexer.is(AsmToken::EndOfStatement))
2555 break;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002556
2557 // Adjust the current parentheses level.
2558 if (Lexer.is(AsmToken::LParen))
2559 ++ParenLevel;
2560 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
2561 --ParenLevel;
2562
2563 // Append the token to the current argument list.
2564 MA.push_back(getTok());
Nirav Dave1180e6892016-06-02 17:15:05 +00002565 Lexer.Lex();
Rafael Espindola768b41c2012-06-15 14:02:34 +00002566 }
Preston Gurd05500642012-09-19 20:36:12 +00002567
Rafael Espindola768b41c2012-06-15 14:02:34 +00002568 if (ParenLevel != 0)
Rafael Espindola3e5eb422012-08-21 15:55:04 +00002569 return TokError("unbalanced parentheses in macro argument");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002570 return false;
2571}
2572
2573// Parse the macro instantiation arguments.
Jim Grosbach4b905842013-09-20 23:08:21 +00002574bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
Vladimir Medic9bad0d332013-08-20 13:33:18 +00002575 MCAsmMacroArguments &A) {
Rafael Espindola768b41c2012-06-15 14:02:34 +00002576 const unsigned NParameters = M ? M->Parameters.size() : 0;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002577 bool NamedParametersFound = false;
2578 SmallVector<SMLoc, 4> FALocs;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002579
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002580 A.resize(NParameters);
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002581 FALocs.resize(NParameters);
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002582
Rafael Espindola768b41c2012-06-15 14:02:34 +00002583 // Parse two kinds of macro invocations:
2584 // - macros defined without any parameters accept an arbitrary number of them
2585 // - macros defined with parameters accept at most that many of them
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002586 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002587 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
2588 ++Parameter) {
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002589 SMLoc IDLoc = Lexer.getLoc();
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002590 MCAsmMacroParameter FA;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002591
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002592 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00002593 if (parseIdentifier(FA.Name))
2594 return Error(IDLoc, "invalid argument identifier for formal argument");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002595
Nirav Dave2364748a2016-09-16 18:30:20 +00002596 if (Lexer.isNot(AsmToken::Equal))
2597 return TokError("expected '=' after formal parameter identifier");
2598
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002599 Lex();
2600
2601 NamedParametersFound = true;
2602 }
Michael Zuckerman56704612017-05-01 13:20:12 +00002603 bool Vararg = HasVararg && Parameter == (NParameters - 1);
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002604
Nirav Dave2364748a2016-09-16 18:30:20 +00002605 if (NamedParametersFound && FA.Name.empty())
2606 return Error(IDLoc, "cannot mix positional and keyword arguments");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002607
Michael Zuckerman763e60e2017-05-04 10:37:00 +00002608 SMLoc StrLoc = Lexer.getLoc();
2609 SMLoc EndLoc;
Michael Zuckerman56704612017-05-01 13:20:12 +00002610 if (Lexer.IsaAltMacroMode() && Lexer.is(AsmToken::Percent)) {
Michael Zuckerman56704612017-05-01 13:20:12 +00002611 const MCExpr *AbsoluteExp;
2612 int64_t Value;
2613 /// Eat '%'
2614 Lex();
2615 if (parseExpression(AbsoluteExp, EndLoc))
2616 return false;
2617 if (!AbsoluteExp->evaluateAsAbsolute(Value))
2618 return Error(StrLoc, "expected absolute expression");
2619 const char *StrChar = StrLoc.getPointer();
2620 const char *EndChar = EndLoc.getPointer();
2621 AsmToken newToken(AsmToken::Integer, StringRef(StrChar , EndChar - StrChar), Value);
2622 FA.Value.push_back(newToken);
Michael Zuckerman763e60e2017-05-04 10:37:00 +00002623 } else if (Lexer.IsaAltMacroMode() && Lexer.is(AsmToken::Less) &&
2624 isAltmacroString(StrLoc, EndLoc)) {
2625 const char *StrChar = StrLoc.getPointer();
2626 const char *EndChar = EndLoc.getPointer();
2627 jumpToLoc(EndLoc, CurBuffer);
2628 /// Eat from '<' to '>'
2629 Lex();
2630 AsmToken newToken(AsmToken::String, StringRef(StrChar, EndChar - StrChar));
2631 FA.Value.push_back(newToken);
2632 } else if(parseMacroArgument(FA.Value, Vararg))
Michael Zuckerman56704612017-05-01 13:20:12 +00002633 return true;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002634
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002635 unsigned PI = Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002636 if (!FA.Name.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002637 unsigned FAI = 0;
2638 for (FAI = 0; FAI < NParameters; ++FAI)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002639 if (M->Parameters[FAI].Name == FA.Name)
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002640 break;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002641
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002642 if (FAI >= NParameters) {
Nirav Davefd910412016-06-17 16:06:17 +00002643 assert(M && "expected macro to be defined");
Nirav Dave2364748a2016-09-16 18:30:20 +00002644 return Error(IDLoc, "parameter named '" + FA.Name +
2645 "' does not exist for macro '" + M->Name + "'");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002646 }
2647 PI = FAI;
2648 }
2649
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002650 if (!FA.Value.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002651 if (A.size() <= PI)
2652 A.resize(PI + 1);
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002653 A[PI] = FA.Value;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002654
2655 if (FALocs.size() <= PI)
2656 FALocs.resize(PI + 1);
2657
2658 FALocs[PI] = Lexer.getLoc();
Preston Gurd242ed3152012-09-19 20:29:04 +00002659 }
Jim Grosbach206661622012-07-30 22:44:17 +00002660
Preston Gurd242ed3152012-09-19 20:29:04 +00002661 // At the end of the statement, fill in remaining arguments that have
2662 // default values. If there aren't any, then the next argument is
2663 // required but missing
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002664 if (Lexer.is(AsmToken::EndOfStatement)) {
2665 bool Failure = false;
2666 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2667 if (A[FAI].empty()) {
2668 if (M->Parameters[FAI].Required) {
2669 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2670 "missing value for required parameter "
2671 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2672 Failure = true;
2673 }
2674
2675 if (!M->Parameters[FAI].Value.empty())
2676 A[FAI] = M->Parameters[FAI].Value;
2677 }
2678 }
2679 return Failure;
2680 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002681
2682 if (Lexer.is(AsmToken::Comma))
2683 Lex();
2684 }
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002685
2686 return TokError("too many positional arguments");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002687}
2688
Jim Grosbach4b905842013-09-20 23:08:21 +00002689bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
Davide Italiano7c9fc732016-07-27 05:51:56 +00002690 // Arbitrarily limit macro nesting depth (default matches 'as'). We can
2691 // eliminate this, although we should protect against infinite loops.
2692 unsigned MaxNestingDepth = AsmMacroMaxNestingDepth;
2693 if (ActiveMacros.size() == MaxNestingDepth) {
2694 std::ostringstream MaxNestingDepthError;
2695 MaxNestingDepthError << "macros cannot be nested more than "
2696 << MaxNestingDepth << " levels deep."
2697 << " Use -asm-macro-max-nesting-depth to increase "
2698 "this limit.";
2699 return TokError(MaxNestingDepthError.str());
2700 }
Daniel Dunbar43235712010-07-18 18:54:11 +00002701
Eli Bendersky38274122013-01-14 23:22:36 +00002702 MCAsmMacroArguments A;
Jim Grosbach4b905842013-09-20 23:08:21 +00002703 if (parseMacroArguments(M, A))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002704 return true;
Daniel Dunbar43235712010-07-18 18:54:11 +00002705
Rafael Espindola1134ab232011-06-05 02:43:45 +00002706 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2707 // to hold the macro body with substitutions.
2708 SmallString<256> Buf;
2709 StringRef Body = M->Body;
Rafael Espindola34b9c512012-06-03 23:57:14 +00002710 raw_svector_ostream OS(Buf);
Rafael Espindola1134ab232011-06-05 02:43:45 +00002711
Toma Tabacu217116e2015-04-27 10:50:29 +00002712 if (expandMacro(OS, Body, M->Parameters, A, true, getTok().getLoc()))
Rafael Espindola1134ab232011-06-05 02:43:45 +00002713 return true;
2714
Eli Bendersky38274122013-01-14 23:22:36 +00002715 // We include the .endmacro in the buffer as our cue to exit the macro
Rafael Espindola34b9c512012-06-03 23:57:14 +00002716 // instantiation.
2717 OS << ".endmacro\n";
2718
Rafael Espindola3560ff22014-08-27 20:03:13 +00002719 std::unique_ptr<MemoryBuffer> Instantiation =
2720 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola1134ab232011-06-05 02:43:45 +00002721
Daniel Dunbar43235712010-07-18 18:54:11 +00002722 // Create the macro instantiation object and add to the current macro
2723 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002724 MacroInstantiation *MI = new MacroInstantiation(
2725 NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Daniel Dunbar43235712010-07-18 18:54:11 +00002726 ActiveMacros.push_back(MI);
2727
Toma Tabacu217116e2015-04-27 10:50:29 +00002728 ++NumOfMacroInstantiations;
2729
Daniel Dunbar43235712010-07-18 18:54:11 +00002730 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00002731 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00002732 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar43235712010-07-18 18:54:11 +00002733 Lex();
2734
2735 return false;
2736}
2737
Jim Grosbach4b905842013-09-20 23:08:21 +00002738void AsmParser::handleMacroExit() {
Daniel Dunbar43235712010-07-18 18:54:11 +00002739 // Jump to the EndOfStatement we should return to, and consume it.
Jim Grosbach4b905842013-09-20 23:08:21 +00002740 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
Daniel Dunbar43235712010-07-18 18:54:11 +00002741 Lex();
2742
2743 // Pop the instantiation entry.
2744 delete ActiveMacros.back();
2745 ActiveMacros.pop_back();
2746}
2747
Jim Grosbach4b905842013-09-20 23:08:21 +00002748bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
Jim Grosbachb7b750d2012-09-13 23:11:31 +00002749 bool NoDeadStrip) {
Pete Cooper80d21cb2015-06-22 19:35:57 +00002750 MCSymbol *Sym;
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002751 const MCExpr *Value;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002752 if (MCParserUtils::parseAssignmentExpression(Name, allow_redef, *this, Sym,
2753 Value))
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002754 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002755
Pete Cooper80d21cb2015-06-22 19:35:57 +00002756 if (!Sym) {
2757 // In the case where we parse an expression starting with a '.', we will
2758 // not generate an error, nor will we create a symbol. In this case we
2759 // should just return out.
Anders Waldenborg84809572014-02-17 20:48:32 +00002760 return false;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002761 }
David Majnemer58cb80c2014-12-24 10:27:50 +00002762
Daniel Dunbarae7ac012009-06-29 23:43:14 +00002763 // Do the assignment.
Daniel Dunbarb7b20972009-08-31 08:09:09 +00002764 Out.EmitAssignment(Sym, Value);
Jim Grosbachb7b750d2012-09-13 23:11:31 +00002765 if (NoDeadStrip)
2766 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2767
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002768 return false;
2769}
2770
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002771/// parseIdentifier:
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002772/// ::= identifier
2773/// ::= string
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002774bool AsmParser::parseIdentifier(StringRef &Res) {
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002775 // The assembler has relaxed rules for accepting identifiers, in particular we
Hans Wennborgce69d772013-10-18 20:46:28 +00002776 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2777 // separate tokens. At this level, we have already lexed so we cannot (currently)
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002778 // handle this as a context dependent token, instead we detect adjacent tokens
2779 // and return the combined identifier.
Hans Wennborgce69d772013-10-18 20:46:28 +00002780 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2781 SMLoc PrefixLoc = getLexer().getLoc();
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002782
Hans Wennborgce69d772013-10-18 20:46:28 +00002783 // Consume the prefix character, and check for a following identifier.
Nirav Daved0463322016-10-12 13:58:07 +00002784
2785 AsmToken Buf[1];
2786 Lexer.peekTokens(Buf, false);
2787
2788 if (Buf[0].isNot(AsmToken::Identifier))
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002789 return true;
2790
Hans Wennborgce69d772013-10-18 20:46:28 +00002791 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
Nirav Daved0463322016-10-12 13:58:07 +00002792 if (PrefixLoc.getPointer() + 1 != Buf[0].getLoc().getPointer())
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002793 return true;
2794
Nirav Daved0463322016-10-12 13:58:07 +00002795 // eat $ or @
2796 Lexer.Lex(); // Lexer's Lex guarantees consecutive token.
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002797 // Construct the joined identifier and consume the token.
Jim Grosbach4b905842013-09-20 23:08:21 +00002798 Res =
Hans Wennborgce69d772013-10-18 20:46:28 +00002799 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
Nirav Davefd910412016-06-17 16:06:17 +00002800 Lex(); // Parser Lex to maintain invariants.
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002801 return false;
2802 }
2803
Jim Grosbach4b905842013-09-20 23:08:21 +00002804 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002805 return true;
2806
Sean Callanan936b0d32010-01-19 21:44:56 +00002807 Res = getTok().getIdentifier();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002808
Sean Callanan686ed8d2010-01-19 20:22:31 +00002809 Lex(); // Consume the identifier token.
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002810
2811 return false;
2812}
2813
Jim Grosbach4b905842013-09-20 23:08:21 +00002814/// parseDirectiveSet:
Nico Weber4ada0d92011-01-28 03:04:41 +00002815/// ::= .equ identifier ',' expression
2816/// ::= .equiv identifier ',' expression
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002817/// ::= .set identifier ',' expression
Jim Grosbach4b905842013-09-20 23:08:21 +00002818bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002819 StringRef Name;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002820 if (check(parseIdentifier(Name), "expected identifier") ||
2821 parseToken(AsmToken::Comma) || parseAssignment(Name, allow_redef, true))
2822 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
2823 return false;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002824}
2825
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002826bool AsmParser::parseEscapedString(std::string &Data) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00002827 if (check(getTok().isNot(AsmToken::String), "expected string"))
2828 return true;
Daniel Dunbaref668c12009-08-14 18:19:52 +00002829
2830 Data = "";
Sean Callanan936b0d32010-01-19 21:44:56 +00002831 StringRef Str = getTok().getStringContents();
Daniel Dunbaref668c12009-08-14 18:19:52 +00002832 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2833 if (Str[i] != '\\') {
2834 Data += Str[i];
2835 continue;
2836 }
2837
2838 // Recognize escaped characters. Note that this escape semantics currently
2839 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2840 ++i;
2841 if (i == e)
2842 return TokError("unexpected backslash at end of string");
2843
2844 // Recognize octal sequences.
Jim Grosbach4b905842013-09-20 23:08:21 +00002845 if ((unsigned)(Str[i] - '0') <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002846 // Consume up to three octal characters.
2847 unsigned Value = Str[i] - '0';
2848
Jim Grosbach4b905842013-09-20 23:08:21 +00002849 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002850 ++i;
2851 Value = Value * 8 + (Str[i] - '0');
2852
Jim Grosbach4b905842013-09-20 23:08:21 +00002853 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002854 ++i;
2855 Value = Value * 8 + (Str[i] - '0');
2856 }
2857 }
2858
2859 if (Value > 255)
2860 return TokError("invalid octal escape sequence (out of range)");
2861
Jim Grosbach4b905842013-09-20 23:08:21 +00002862 Data += (unsigned char)Value;
Daniel Dunbaref668c12009-08-14 18:19:52 +00002863 continue;
2864 }
2865
2866 // Otherwise recognize individual escapes.
2867 switch (Str[i]) {
2868 default:
2869 // Just reject invalid escape sequences for now.
2870 return TokError("invalid escape sequence (unrecognized character)");
2871
2872 case 'b': Data += '\b'; break;
2873 case 'f': Data += '\f'; break;
2874 case 'n': Data += '\n'; break;
2875 case 'r': Data += '\r'; break;
2876 case 't': Data += '\t'; break;
2877 case '"': Data += '"'; break;
2878 case '\\': Data += '\\'; break;
2879 }
2880 }
2881
Nirav Davea645433c2016-07-18 15:24:03 +00002882 Lex();
Daniel Dunbaref668c12009-08-14 18:19:52 +00002883 return false;
2884}
2885
Jim Grosbach4b905842013-09-20 23:08:21 +00002886/// parseDirectiveAscii:
Rafael Espindola63760ba2010-10-28 20:02:27 +00002887/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002888bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00002889 auto parseOp = [&]() -> bool {
2890 std::string Data;
2891 if (checkForValidSection() || parseEscapedString(Data))
Nirav Davef43cc9f2016-10-10 15:24:54 +00002892 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002893 getStreamer().EmitBytes(Data);
2894 if (ZeroTerminated)
2895 getStreamer().EmitBytes(StringRef("\0", 1));
2896 return false;
2897 };
Daniel Dunbare5444a82010-09-09 22:42:59 +00002898
Nirav Dave1a9044b2016-10-24 14:35:29 +00002899 if (parseMany(parseOp))
2900 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbara10e5192009-06-24 23:30:00 +00002901 return false;
2902}
2903
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002904/// parseDirectiveReloc
2905/// ::= .reloc expression , identifier [ , expression ]
2906bool AsmParser::parseDirectiveReloc(SMLoc DirectiveLoc) {
2907 const MCExpr *Offset;
2908 const MCExpr *Expr = nullptr;
2909
2910 SMLoc OffsetLoc = Lexer.getTok().getLoc();
Nirav Dave1a9044b2016-10-24 14:35:29 +00002911 int64_t OffsetValue;
2912 // We can only deal with constant expressions at the moment.
2913
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002914 if (parseExpression(Offset))
2915 return true;
2916
Nirav Davea645433c2016-07-18 15:24:03 +00002917 if (check(!Offset->evaluateAsAbsolute(OffsetValue), OffsetLoc,
2918 "expression is not a constant value") ||
2919 check(OffsetValue < 0, OffsetLoc, "expression is negative") ||
2920 parseToken(AsmToken::Comma, "expected comma") ||
2921 check(getTok().isNot(AsmToken::Identifier), "expected relocation name"))
2922 return true;
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002923
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002924 SMLoc NameLoc = Lexer.getTok().getLoc();
2925 StringRef Name = Lexer.getTok().getIdentifier();
Nirav Davefd910412016-06-17 16:06:17 +00002926 Lex();
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002927
2928 if (Lexer.is(AsmToken::Comma)) {
Nirav Davefd910412016-06-17 16:06:17 +00002929 Lex();
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002930 SMLoc ExprLoc = Lexer.getLoc();
2931 if (parseExpression(Expr))
2932 return true;
2933
2934 MCValue Value;
2935 if (!Expr->evaluateAsRelocatable(Value, nullptr, nullptr))
2936 return Error(ExprLoc, "expression must be relocatable");
2937 }
2938
Nirav Davea645433c2016-07-18 15:24:03 +00002939 if (parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00002940 "unexpected token in .reloc directive"))
2941 return true;
2942
2943 if (getStreamer().EmitRelocDirective(*Offset, Name, Expr, DirectiveLoc))
2944 return Error(NameLoc, "unknown relocation name");
2945
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002946 return false;
2947}
2948
Jim Grosbach4b905842013-09-20 23:08:21 +00002949/// parseDirectiveValue
Daniel Dunbara10e5192009-06-24 23:30:00 +00002950/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00002951bool AsmParser::parseDirectiveValue(StringRef IDVal, unsigned Size) {
2952 auto parseOp = [&]() -> bool {
2953 const MCExpr *Value;
2954 SMLoc ExprLoc = getLexer().getLoc();
2955 if (checkForValidSection() || parseExpression(Value))
Nirav Davef43cc9f2016-10-10 15:24:54 +00002956 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002957 // Special case constant expressions to match code generator.
2958 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2959 assert(Size <= 8 && "Invalid size");
2960 uint64_t IntValue = MCE->getValue();
2961 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2962 return Error(ExprLoc, "out of range literal value");
2963 getStreamer().EmitIntValue(IntValue, Size);
2964 } else
2965 getStreamer().EmitValue(Value, Size, ExprLoc);
2966 return false;
2967 };
Daniel Dunbare5444a82010-09-09 22:42:59 +00002968
Nirav Dave1a9044b2016-10-24 14:35:29 +00002969 if (parseMany(parseOp))
2970 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbara10e5192009-06-24 23:30:00 +00002971 return false;
2972}
2973
David Woodhoused6de0d92014-02-01 16:20:59 +00002974/// ParseDirectiveOctaValue
2975/// ::= .octa [ hexconstant (, hexconstant)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00002976
2977bool AsmParser::parseDirectiveOctaValue(StringRef IDVal) {
2978 auto parseOp = [&]() -> bool {
Nirav Davef43cc9f2016-10-10 15:24:54 +00002979 if (checkForValidSection())
2980 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002981 if (getTok().isNot(AsmToken::Integer) && getTok().isNot(AsmToken::BigNum))
2982 return TokError("unknown token in expression");
2983 SMLoc ExprLoc = getTok().getLoc();
2984 APInt IntValue = getTok().getAPIntVal();
2985 uint64_t hi, lo;
2986 Lex();
2987 if (!IntValue.isIntN(128))
2988 return Error(ExprLoc, "out of range literal value");
2989 if (!IntValue.isIntN(64)) {
2990 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
2991 lo = IntValue.getLoBits(64).getZExtValue();
2992 } else {
2993 hi = 0;
2994 lo = IntValue.getZExtValue();
David Woodhoused6de0d92014-02-01 16:20:59 +00002995 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00002996 if (MAI.isLittleEndian()) {
2997 getStreamer().EmitIntValue(lo, 8);
2998 getStreamer().EmitIntValue(hi, 8);
2999 } else {
3000 getStreamer().EmitIntValue(hi, 8);
3001 getStreamer().EmitIntValue(lo, 8);
3002 }
3003 return false;
3004 };
David Woodhoused6de0d92014-02-01 16:20:59 +00003005
Nirav Dave1a9044b2016-10-24 14:35:29 +00003006 if (parseMany(parseOp))
3007 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
David Woodhoused6de0d92014-02-01 16:20:59 +00003008 return false;
3009}
3010
Petr Hosek4cb08ce2016-09-23 19:25:15 +00003011bool AsmParser::parseRealValue(const fltSemantics &Semantics, APInt &Res) {
3012 // We don't truly support arithmetic on floating point expressions, so we
3013 // have to manually parse unary prefixes.
3014 bool IsNeg = false;
3015 if (getLexer().is(AsmToken::Minus)) {
3016 Lexer.Lex();
3017 IsNeg = true;
3018 } else if (getLexer().is(AsmToken::Plus))
3019 Lexer.Lex();
3020
3021 if (Lexer.is(AsmToken::Error))
3022 return TokError(Lexer.getErr());
3023 if (Lexer.isNot(AsmToken::Integer) && Lexer.isNot(AsmToken::Real) &&
3024 Lexer.isNot(AsmToken::Identifier))
3025 return TokError("unexpected token in directive");
3026
3027 // Convert to an APFloat.
3028 APFloat Value(Semantics);
3029 StringRef IDVal = getTok().getString();
3030 if (getLexer().is(AsmToken::Identifier)) {
3031 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
3032 Value = APFloat::getInf(Semantics);
3033 else if (!IDVal.compare_lower("nan"))
3034 Value = APFloat::getNaN(Semantics, false, ~0);
3035 else
3036 return TokError("invalid floating point literal");
3037 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
3038 APFloat::opInvalidOp)
3039 return TokError("invalid floating point literal");
3040 if (IsNeg)
3041 Value.changeSign();
3042
3043 // Consume the numeric token.
3044 Lex();
3045
3046 Res = Value.bitcastToAPInt();
3047
3048 return false;
3049}
3050
Jim Grosbach4b905842013-09-20 23:08:21 +00003051/// parseDirectiveRealValue
Daniel Dunbar2af16532010-09-24 01:59:56 +00003052/// ::= (.single | .double) [ expression (, expression)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00003053bool AsmParser::parseDirectiveRealValue(StringRef IDVal,
3054 const fltSemantics &Semantics) {
3055 auto parseOp = [&]() -> bool {
3056 APInt AsInt;
3057 if (checkForValidSection() || parseRealValue(Semantics, AsInt))
Nirav Davef43cc9f2016-10-10 15:24:54 +00003058 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003059 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
3060 AsInt.getBitWidth() / 8);
3061 return false;
3062 };
Daniel Dunbar2af16532010-09-24 01:59:56 +00003063
Nirav Dave1a9044b2016-10-24 14:35:29 +00003064 if (parseMany(parseOp))
3065 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbar2af16532010-09-24 01:59:56 +00003066 return false;
3067}
3068
Jim Grosbach4b905842013-09-20 23:08:21 +00003069/// parseDirectiveZero
Rafael Espindola922e3f42010-09-16 15:03:59 +00003070/// ::= .zero expression
Jim Grosbach4b905842013-09-20 23:08:21 +00003071bool AsmParser::parseDirectiveZero() {
Petr Hosek67a94a72016-05-28 05:57:48 +00003072 SMLoc NumBytesLoc = Lexer.getLoc();
3073 const MCExpr *NumBytes;
Nirav Davef43cc9f2016-10-10 15:24:54 +00003074 if (checkForValidSection() || parseExpression(NumBytes))
Rafael Espindola922e3f42010-09-16 15:03:59 +00003075 return true;
3076
Rafael Espindolab91bac62010-10-05 19:42:57 +00003077 int64_t Val = 0;
3078 if (getLexer().is(AsmToken::Comma)) {
3079 Lex();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003080 if (parseAbsoluteExpression(Val))
Rafael Espindolab91bac62010-10-05 19:42:57 +00003081 return true;
3082 }
3083
Nirav Davea645433c2016-07-18 15:24:03 +00003084 if (parseToken(AsmToken::EndOfStatement,
3085 "unexpected token in '.zero' directive"))
3086 return true;
Petr Hosek67a94a72016-05-28 05:57:48 +00003087 getStreamer().emitFill(*NumBytes, Val, NumBytesLoc);
Rafael Espindola922e3f42010-09-16 15:03:59 +00003088
3089 return false;
3090}
3091
Jim Grosbach4b905842013-09-20 23:08:21 +00003092/// parseDirectiveFill
Roman Divackye33098f2013-09-24 17:44:41 +00003093/// ::= .fill expression [ , expression [ , expression ] ]
Jim Grosbach4b905842013-09-20 23:08:21 +00003094bool AsmParser::parseDirectiveFill() {
Petr Hosek67a94a72016-05-28 05:57:48 +00003095 SMLoc NumValuesLoc = Lexer.getLoc();
3096 const MCExpr *NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00003097 if (checkForValidSection() || parseExpression(NumValues))
Daniel Dunbara10e5192009-06-24 23:30:00 +00003098 return true;
3099
Roman Divackye33098f2013-09-24 17:44:41 +00003100 int64_t FillSize = 1;
3101 int64_t FillExpr = 0;
Michael J. Spencer530ce852010-10-09 11:00:50 +00003102
David Majnemer522d3db2014-02-01 07:19:38 +00003103 SMLoc SizeLoc, ExprLoc;
Daniel Dunbara10e5192009-06-24 23:30:00 +00003104
Nirav Dave1a9044b2016-10-24 14:35:29 +00003105 if (parseOptionalToken(AsmToken::Comma)) {
3106 SizeLoc = getTok().getLoc();
3107 if (parseAbsoluteExpression(FillSize))
Roman Divackye33098f2013-09-24 17:44:41 +00003108 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003109 if (parseOptionalToken(AsmToken::Comma)) {
3110 ExprLoc = getTok().getLoc();
3111 if (parseAbsoluteExpression(FillExpr))
Roman Divackye33098f2013-09-24 17:44:41 +00003112 return true;
Roman Divackye33098f2013-09-24 17:44:41 +00003113 }
3114 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003115 if (parseToken(AsmToken::EndOfStatement,
3116 "unexpected token in '.fill' directive"))
3117 return true;
Daniel Dunbara10e5192009-06-24 23:30:00 +00003118
David Majnemer522d3db2014-02-01 07:19:38 +00003119 if (FillSize < 0) {
3120 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
Petr Hosek6abd38b2016-05-28 08:20:08 +00003121 return false;
David Majnemer522d3db2014-02-01 07:19:38 +00003122 }
3123 if (FillSize > 8) {
3124 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
3125 FillSize = 8;
3126 }
Daniel Dunbara10e5192009-06-24 23:30:00 +00003127
David Majnemer522d3db2014-02-01 07:19:38 +00003128 if (!isUInt<32>(FillExpr) && FillSize > 4)
3129 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
3130
Petr Hosek67a94a72016-05-28 05:57:48 +00003131 getStreamer().emitFill(*NumValues, FillSize, FillExpr, NumValuesLoc);
Daniel Dunbara10e5192009-06-24 23:30:00 +00003132
3133 return false;
3134}
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00003135
Jim Grosbach4b905842013-09-20 23:08:21 +00003136/// parseDirectiveOrg
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00003137/// ::= .org expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00003138bool AsmParser::parseDirectiveOrg() {
Daniel Dunbar897ffad2009-08-31 08:09:28 +00003139 const MCExpr *Offset;
Oliver Stannard268f42f2016-12-14 10:43:58 +00003140 SMLoc OffsetLoc = Lexer.getLoc();
Nirav Davef43cc9f2016-10-10 15:24:54 +00003141 if (checkForValidSection() || parseExpression(Offset))
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00003142 return true;
3143
3144 // Parse optional fill expression.
3145 int64_t FillExpr = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003146 if (parseOptionalToken(AsmToken::Comma))
3147 if (parseAbsoluteExpression(FillExpr))
3148 return addErrorSuffix(" in '.org' directive");
3149 if (parseToken(AsmToken::EndOfStatement))
3150 return addErrorSuffix(" in '.org' directive");
Nirav Davea645433c2016-07-18 15:24:03 +00003151
Oliver Stannard268f42f2016-12-14 10:43:58 +00003152 getStreamer().emitValueToOffset(Offset, FillExpr, OffsetLoc);
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00003153 return false;
3154}
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003155
Jim Grosbach4b905842013-09-20 23:08:21 +00003156/// parseDirectiveAlign
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003157/// ::= {.align, ...} expression [ , expression [ , expression ]]
Jim Grosbach4b905842013-09-20 23:08:21 +00003158bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003159 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003160 int64_t Alignment;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003161 SMLoc MaxBytesLoc;
3162 bool HasFillExpr = false;
3163 int64_t FillExpr = 0;
3164 int64_t MaxBytesToFill = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003165
3166 auto parseAlign = [&]() -> bool {
Coby Tayreed483a102017-08-02 17:36:10 +00003167 if (parseAbsoluteExpression(Alignment))
Nirav Davea645433c2016-07-18 15:24:03 +00003168 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003169 if (parseOptionalToken(AsmToken::Comma)) {
3170 // The fill expression can be omitted while specifying a maximum number of
3171 // alignment bytes, e.g:
3172 // .align 3,,4
3173 if (getTok().isNot(AsmToken::Comma)) {
3174 HasFillExpr = true;
3175 if (parseAbsoluteExpression(FillExpr))
3176 return true;
3177 }
3178 if (parseOptionalToken(AsmToken::Comma))
3179 if (parseTokenLoc(MaxBytesLoc) ||
3180 parseAbsoluteExpression(MaxBytesToFill))
3181 return true;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003182 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003183 return parseToken(AsmToken::EndOfStatement);
3184 };
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003185
Coby Tayreed483a102017-08-02 17:36:10 +00003186 if (checkForValidSection())
3187 return addErrorSuffix(" in directive");
3188 // Ignore empty '.p2align' directives for GNU-as compatibility
3189 if (IsPow2 && (ValueSize == 1) && getTok().is(AsmToken::EndOfStatement)) {
3190 Warning(AlignmentLoc, "p2align directive with no operand(s) is ignored");
3191 return parseToken(AsmToken::EndOfStatement);
3192 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003193 if (parseAlign())
3194 return addErrorSuffix(" in directive");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003195
Nirav Dave2364748a2016-09-16 18:30:20 +00003196 // Always emit an alignment here even if we thrown an error.
3197 bool ReturnVal = false;
3198
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003199 // Compute alignment in bytes.
3200 if (IsPow2) {
3201 // FIXME: Diagnose overflow.
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003202 if (Alignment >= 32) {
Nirav Dave2364748a2016-09-16 18:30:20 +00003203 ReturnVal |= Error(AlignmentLoc, "invalid alignment value");
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003204 Alignment = 31;
3205 }
3206
Benjamin Kramer63951ad2009-09-06 09:35:10 +00003207 Alignment = 1ULL << Alignment;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00003208 } else {
Davide Italianocb2da712015-09-08 18:59:47 +00003209 // Reject alignments that aren't either a power of two or zero,
3210 // for gas compatibility. Alignment of zero is silently rounded
3211 // up to one.
3212 if (Alignment == 0)
3213 Alignment = 1;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00003214 if (!isPowerOf2_64(Alignment))
Nirav Dave2364748a2016-09-16 18:30:20 +00003215 ReturnVal |= Error(AlignmentLoc, "alignment must be a power of 2");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003216 }
3217
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003218 // Diagnose non-sensical max bytes to align.
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003219 if (MaxBytesLoc.isValid()) {
3220 if (MaxBytesToFill < 1) {
Nirav Dave2364748a2016-09-16 18:30:20 +00003221 ReturnVal |= Error(MaxBytesLoc,
3222 "alignment directive can never be satisfied in this "
Jim Grosbach4b905842013-09-20 23:08:21 +00003223 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar4abcccb2009-08-21 23:01:53 +00003224 MaxBytesToFill = 0;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003225 }
3226
3227 if (MaxBytesToFill >= Alignment) {
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +00003228 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
Jim Grosbach4b905842013-09-20 23:08:21 +00003229 "has no effect");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003230 MaxBytesToFill = 0;
3231 }
3232 }
3233
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003234 // Check whether we should use optimal code alignment for this .align
3235 // directive.
Eric Christopher445c9522016-10-14 05:47:37 +00003236 const MCSection *Section = getStreamer().getCurrentSectionOnly();
Saleem Abdulrasool7f2f9f42014-03-21 05:13:23 +00003237 assert(Section && "must have section to emit alignment");
3238 bool UseCodeAlign = Section->UseCodeAlign();
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003239 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
3240 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003241 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003242 } else {
Kevin Enderby7f993022010-02-25 18:46:04 +00003243 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnerc2b36752010-07-15 21:19:31 +00003244 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
3245 MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003246 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003247
Nirav Dave2364748a2016-09-16 18:30:20 +00003248 return ReturnVal;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003249}
3250
Jim Grosbach4b905842013-09-20 23:08:21 +00003251/// parseDirectiveFile
Paul Robinson29f5f982018-01-09 23:31:48 +00003252/// ::= .file filename
Scott Linder16c7bda2018-02-23 23:01:06 +00003253/// ::= .file number [directory] filename [md5 checksum] [source source-text]
Jim Grosbach4b905842013-09-20 23:08:21 +00003254bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003255 // FIXME: I'm not sure what this is.
3256 int64_t FileNumber = -1;
Eli Bendersky17233942013-01-15 22:59:42 +00003257 if (getLexer().is(AsmToken::Integer)) {
3258 FileNumber = getTok().getIntVal();
3259 Lex();
3260
Paul Robinson732e4432018-03-06 03:15:21 +00003261 if (FileNumber < 1)
3262 return TokError("file number less than one");
Eli Bendersky17233942013-01-15 22:59:42 +00003263 }
3264
Nirav Davea645433c2016-07-18 15:24:03 +00003265 std::string Path = getTok().getString();
Eli Bendersky17233942013-01-15 22:59:42 +00003266
3267 // Usually the directory and filename together, otherwise just the directory.
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003268 // Allow the strings to have escaped octal character sequence.
Nirav Davea645433c2016-07-18 15:24:03 +00003269 if (check(getTok().isNot(AsmToken::String),
3270 "unexpected token in '.file' directive") ||
3271 parseEscapedString(Path))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003272 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003273
3274 StringRef Directory;
3275 StringRef Filename;
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003276 std::string FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00003277 if (getLexer().is(AsmToken::String)) {
Nirav Davea645433c2016-07-18 15:24:03 +00003278 if (check(FileNumber == -1,
3279 "explicit path specified, but no file number") ||
3280 parseEscapedString(FilenameData))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003281 return true;
3282 Filename = FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00003283 Directory = Path;
Eli Bendersky17233942013-01-15 22:59:42 +00003284 } else {
3285 Filename = Path;
3286 }
3287
Paul Robinson29f5f982018-01-09 23:31:48 +00003288 std::string Checksum;
Scott Linder16c7bda2018-02-23 23:01:06 +00003289
3290 Optional<StringRef> Source;
3291 bool HasSource = false;
3292 std::string SourceString;
3293
3294 while (!parseOptionalToken(AsmToken::EndOfStatement)) {
Paul Robinson29f5f982018-01-09 23:31:48 +00003295 StringRef Keyword;
3296 if (check(getTok().isNot(AsmToken::Identifier),
3297 "unexpected token in '.file' directive") ||
Scott Linder16c7bda2018-02-23 23:01:06 +00003298 parseIdentifier(Keyword))
Paul Robinson29f5f982018-01-09 23:31:48 +00003299 return true;
Scott Linder16c7bda2018-02-23 23:01:06 +00003300 if (Keyword == "md5") {
3301 if (check(FileNumber == -1,
3302 "MD5 checksum specified, but no file number") ||
3303 check(getTok().isNot(AsmToken::String),
3304 "unexpected token in '.file' directive") ||
3305 parseEscapedString(Checksum) ||
3306 check(Checksum.size() != 32, "invalid MD5 checksum specified"))
3307 return true;
3308 } else if (Keyword == "source") {
3309 HasSource = true;
3310 if (check(FileNumber == -1,
3311 "source specified, but no file number") ||
3312 check(getTok().isNot(AsmToken::String),
3313 "unexpected token in '.file' directive") ||
3314 parseEscapedString(SourceString))
3315 return true;
3316 } else {
3317 return TokError("unexpected token in '.file' directive");
3318 }
Paul Robinson29f5f982018-01-09 23:31:48 +00003319 }
Eli Bendersky17233942013-01-15 22:59:42 +00003320
3321 if (FileNumber == -1)
3322 getStreamer().EmitFileDirective(Filename);
3323 else {
Paul Robinson29f5f982018-01-09 23:31:48 +00003324 MD5::MD5Result *CKMem = nullptr;
3325 if (!Checksum.empty()) {
3326 Checksum = fromHex(Checksum);
3327 if (check(Checksum.size() != 16, "invalid MD5 checksum specified"))
3328 return true;
3329 CKMem = (MD5::MD5Result *)Ctx.allocate(sizeof(MD5::MD5Result), 1);
3330 memcpy(&CKMem->Bytes, Checksum.data(), 16);
3331 }
Scott Linder16c7bda2018-02-23 23:01:06 +00003332 if (HasSource) {
3333 char *SourceBuf = static_cast<char *>(Ctx.allocate(SourceString.size()));
3334 memcpy(SourceBuf, SourceString.data(), SourceString.size());
3335 Source = StringRef(SourceBuf, SourceString.size());
3336 }
David Blaikie22748082016-05-26 00:22:26 +00003337 // If there is -g option as well as debug info from directive file,
3338 // we turn off -g option, directly use the existing debug info instead.
David Blaikiedc3f01e2015-03-09 01:57:13 +00003339 if (getContext().getGenDwarfForAssembly())
David Blaikie22748082016-05-26 00:22:26 +00003340 getContext().setGenDwarfForAssembly(false);
Paul Robinson70def122018-02-22 21:03:33 +00003341 else {
3342 Expected<unsigned> FileNumOrErr = getStreamer().tryEmitDwarfFileDirective(
Scott Linder16c7bda2018-02-23 23:01:06 +00003343 FileNumber, Directory, Filename, CKMem, Source);
Paul Robinson70def122018-02-22 21:03:33 +00003344 if (!FileNumOrErr)
3345 return Error(DirectiveLoc, toString(FileNumOrErr.takeError()));
3346 FileNumber = FileNumOrErr.get();
3347 }
Eli Bendersky17233942013-01-15 22:59:42 +00003348 }
3349
3350 return false;
3351}
3352
Jim Grosbach4b905842013-09-20 23:08:21 +00003353/// parseDirectiveLine
Eli Bendersky17233942013-01-15 22:59:42 +00003354/// ::= .line [number]
Jim Grosbach4b905842013-09-20 23:08:21 +00003355bool AsmParser::parseDirectiveLine() {
Nirav Davea645433c2016-07-18 15:24:03 +00003356 int64_t LineNumber;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003357 if (getLexer().is(AsmToken::Integer)) {
Nirav Davea645433c2016-07-18 15:24:03 +00003358 if (parseIntToken(LineNumber, "unexpected token in '.line' directive"))
3359 return true;
Jim Grosbach4b905842013-09-20 23:08:21 +00003360 (void)LineNumber;
Eli Bendersky17233942013-01-15 22:59:42 +00003361 // FIXME: Do something with the .line.
3362 }
Nirav Davea645433c2016-07-18 15:24:03 +00003363 if (parseToken(AsmToken::EndOfStatement,
3364 "unexpected token in '.line' directive"))
3365 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003366
3367 return false;
3368}
3369
Jim Grosbach4b905842013-09-20 23:08:21 +00003370/// parseDirectiveLoc
Eli Bendersky17233942013-01-15 22:59:42 +00003371/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
3372/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
3373/// The first number is a file number, must have been previously assigned with
3374/// a .file directive, the second number is the line number and optionally the
3375/// third number is a column position (zero if not specified). The remaining
3376/// optional items are .loc sub-directives.
Jim Grosbach4b905842013-09-20 23:08:21 +00003377bool AsmParser::parseDirectiveLoc() {
Nirav Davea645433c2016-07-18 15:24:03 +00003378 int64_t FileNumber = 0, LineNumber = 0;
3379 SMLoc Loc = getTok().getLoc();
3380 if (parseIntToken(FileNumber, "unexpected token in '.loc' directive") ||
3381 check(FileNumber < 1, Loc,
3382 "file number less than one in '.loc' directive") ||
3383 check(!getContext().isValidDwarfFileNumber(FileNumber), Loc,
3384 "unassigned file number in '.loc' directive"))
3385 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003386
Nirav Davea645433c2016-07-18 15:24:03 +00003387 // optional
Eli Bendersky17233942013-01-15 22:59:42 +00003388 if (getLexer().is(AsmToken::Integer)) {
3389 LineNumber = getTok().getIntVal();
Adrian Prantl6ac40032013-09-26 23:37:11 +00003390 if (LineNumber < 0)
3391 return TokError("line number less than zero in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003392 Lex();
3393 }
3394
3395 int64_t ColumnPos = 0;
3396 if (getLexer().is(AsmToken::Integer)) {
3397 ColumnPos = getTok().getIntVal();
3398 if (ColumnPos < 0)
3399 return TokError("column position less than zero in '.loc' directive");
3400 Lex();
3401 }
3402
3403 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
3404 unsigned Isa = 0;
3405 int64_t Discriminator = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003406
Nirav Dave1a9044b2016-10-24 14:35:29 +00003407 auto parseLocOp = [&]() -> bool {
3408 StringRef Name;
3409 SMLoc Loc = getTok().getLoc();
3410 if (parseIdentifier(Name))
3411 return TokError("unexpected token in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003412
Nirav Dave1a9044b2016-10-24 14:35:29 +00003413 if (Name == "basic_block")
3414 Flags |= DWARF2_FLAG_BASIC_BLOCK;
3415 else if (Name == "prologue_end")
3416 Flags |= DWARF2_FLAG_PROLOGUE_END;
3417 else if (Name == "epilogue_begin")
3418 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
3419 else if (Name == "is_stmt") {
3420 Loc = getTok().getLoc();
3421 const MCExpr *Value;
3422 if (parseExpression(Value))
3423 return true;
3424 // The expression must be the constant 0 or 1.
3425 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3426 int Value = MCE->getValue();
3427 if (Value == 0)
3428 Flags &= ~DWARF2_FLAG_IS_STMT;
3429 else if (Value == 1)
3430 Flags |= DWARF2_FLAG_IS_STMT;
3431 else
3432 return Error(Loc, "is_stmt value not 0 or 1");
Craig Topperf15655b2013-04-22 04:22:40 +00003433 } else {
Nirav Dave1a9044b2016-10-24 14:35:29 +00003434 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
Eli Bendersky17233942013-01-15 22:59:42 +00003435 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003436 } else if (Name == "isa") {
3437 Loc = getTok().getLoc();
3438 const MCExpr *Value;
3439 if (parseExpression(Value))
3440 return true;
3441 // The expression must be a constant greater or equal to 0.
3442 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3443 int Value = MCE->getValue();
3444 if (Value < 0)
3445 return Error(Loc, "isa number less than zero");
3446 Isa = Value;
3447 } else {
3448 return Error(Loc, "isa number not a constant value");
3449 }
3450 } else if (Name == "discriminator") {
3451 if (parseAbsoluteExpression(Discriminator))
3452 return true;
3453 } else {
3454 return Error(Loc, "unknown sub-directive in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003455 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003456 return false;
3457 };
3458
Nirav Davee2369aa2016-10-26 17:28:58 +00003459 if (parseMany(parseLocOp, false /*hasComma*/))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003460 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003461
3462 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
3463 Isa, Discriminator, StringRef());
3464
3465 return false;
3466}
3467
Jim Grosbach4b905842013-09-20 23:08:21 +00003468/// parseDirectiveStabs
Eli Bendersky17233942013-01-15 22:59:42 +00003469/// ::= .stabs string, number, number, number
Jim Grosbach4b905842013-09-20 23:08:21 +00003470bool AsmParser::parseDirectiveStabs() {
Eli Bendersky17233942013-01-15 22:59:42 +00003471 return TokError("unsupported directive '.stabs'");
3472}
3473
Reid Kleckner2214ed82016-01-29 00:49:42 +00003474/// parseDirectiveCVFile
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003475/// ::= .cv_file number filename [checksum] [checksumkind]
Reid Kleckner2214ed82016-01-29 00:49:42 +00003476bool AsmParser::parseDirectiveCVFile() {
Nirav Davea645433c2016-07-18 15:24:03 +00003477 SMLoc FileNumberLoc = getTok().getLoc();
3478 int64_t FileNumber;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003479 std::string Filename;
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003480 std::string Checksum;
3481 int64_t ChecksumKind = 0;
Nirav Davea645433c2016-07-18 15:24:03 +00003482
3483 if (parseIntToken(FileNumber,
3484 "expected file number in '.cv_file' directive") ||
3485 check(FileNumber < 1, FileNumberLoc, "file number less than one") ||
3486 check(getTok().isNot(AsmToken::String),
3487 "unexpected token in '.cv_file' directive") ||
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003488 parseEscapedString(Filename))
Reid Klecknera5b1eef2016-08-26 17:58:37 +00003489 return true;
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003490 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
3491 if (check(getTok().isNot(AsmToken::String),
3492 "unexpected token in '.cv_file' directive") ||
3493 parseEscapedString(Checksum) ||
3494 parseIntToken(ChecksumKind,
3495 "expected checksum kind in '.cv_file' directive") ||
3496 parseToken(AsmToken::EndOfStatement,
3497 "unexpected token in '.cv_file' directive"))
3498 return true;
3499 }
Nirav Dave1ab71992016-07-18 19:35:21 +00003500
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003501 Checksum = fromHex(Checksum);
3502 void *CKMem = Ctx.allocate(Checksum.size(), 1);
3503 memcpy(CKMem, Checksum.data(), Checksum.size());
3504 ArrayRef<uint8_t> ChecksumAsBytes(reinterpret_cast<const uint8_t *>(CKMem),
3505 Checksum.size());
3506
3507 if (!getStreamer().EmitCVFileDirective(FileNumber, Filename, ChecksumAsBytes,
3508 static_cast<uint8_t>(ChecksumKind)))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003509 return Error(FileNumberLoc, "file number already allocated");
Reid Kleckner2214ed82016-01-29 00:49:42 +00003510
3511 return false;
3512}
3513
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003514bool AsmParser::parseCVFunctionId(int64_t &FunctionId,
3515 StringRef DirectiveName) {
3516 SMLoc Loc;
3517 return parseTokenLoc(Loc) ||
3518 parseIntToken(FunctionId, "expected function id in '" + DirectiveName +
3519 "' directive") ||
3520 check(FunctionId < 0 || FunctionId >= UINT_MAX, Loc,
3521 "expected function id within range [0, UINT_MAX)");
3522}
3523
3524bool AsmParser::parseCVFileId(int64_t &FileNumber, StringRef DirectiveName) {
3525 SMLoc Loc;
3526 return parseTokenLoc(Loc) ||
3527 parseIntToken(FileNumber, "expected integer in '" + DirectiveName +
3528 "' directive") ||
3529 check(FileNumber < 1, Loc, "file number less than one in '" +
3530 DirectiveName + "' directive") ||
3531 check(!getCVContext().isValidFileNumber(FileNumber), Loc,
3532 "unassigned file number in '" + DirectiveName + "' directive");
3533}
3534
3535/// parseDirectiveCVFuncId
3536/// ::= .cv_func_id FunctionId
3537///
3538/// Introduces a function ID that can be used with .cv_loc.
3539bool AsmParser::parseDirectiveCVFuncId() {
3540 SMLoc FunctionIdLoc = getTok().getLoc();
3541 int64_t FunctionId;
3542
3543 if (parseCVFunctionId(FunctionId, ".cv_func_id") ||
3544 parseToken(AsmToken::EndOfStatement,
3545 "unexpected token in '.cv_func_id' directive"))
3546 return true;
3547
3548 if (!getStreamer().EmitCVFuncIdDirective(FunctionId))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003549 return Error(FunctionIdLoc, "function id already allocated");
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003550
3551 return false;
3552}
3553
3554/// parseDirectiveCVInlineSiteId
3555/// ::= .cv_inline_site_id FunctionId
3556/// "within" IAFunc
3557/// "inlined_at" IAFile IALine [IACol]
3558///
3559/// Introduces a function ID that can be used with .cv_loc. Includes "inlined
3560/// at" source location information for use in the line table of the caller,
3561/// whether the caller is a real function or another inlined call site.
3562bool AsmParser::parseDirectiveCVInlineSiteId() {
3563 SMLoc FunctionIdLoc = getTok().getLoc();
3564 int64_t FunctionId;
3565 int64_t IAFunc;
3566 int64_t IAFile;
3567 int64_t IALine;
3568 int64_t IACol = 0;
3569
3570 // FunctionId
3571 if (parseCVFunctionId(FunctionId, ".cv_inline_site_id"))
3572 return true;
3573
3574 // "within"
3575 if (check((getLexer().isNot(AsmToken::Identifier) ||
3576 getTok().getIdentifier() != "within"),
3577 "expected 'within' identifier in '.cv_inline_site_id' directive"))
3578 return true;
3579 Lex();
3580
3581 // IAFunc
3582 if (parseCVFunctionId(IAFunc, ".cv_inline_site_id"))
3583 return true;
3584
3585 // "inlined_at"
3586 if (check((getLexer().isNot(AsmToken::Identifier) ||
3587 getTok().getIdentifier() != "inlined_at"),
3588 "expected 'inlined_at' identifier in '.cv_inline_site_id' "
3589 "directive") )
3590 return true;
3591 Lex();
3592
3593 // IAFile IALine
3594 if (parseCVFileId(IAFile, ".cv_inline_site_id") ||
3595 parseIntToken(IALine, "expected line number after 'inlined_at'"))
3596 return true;
3597
3598 // [IACol]
3599 if (getLexer().is(AsmToken::Integer)) {
3600 IACol = getTok().getIntVal();
3601 Lex();
3602 }
3603
3604 if (parseToken(AsmToken::EndOfStatement,
3605 "unexpected token in '.cv_inline_site_id' directive"))
3606 return true;
3607
3608 if (!getStreamer().EmitCVInlineSiteIdDirective(FunctionId, IAFunc, IAFile,
3609 IALine, IACol, FunctionIdLoc))
Nirav Dave2364748a2016-09-16 18:30:20 +00003610 return Error(FunctionIdLoc, "function id already allocated");
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003611
3612 return false;
3613}
3614
Reid Kleckner2214ed82016-01-29 00:49:42 +00003615/// parseDirectiveCVLoc
3616/// ::= .cv_loc FunctionId FileNumber [LineNumber] [ColumnPos] [prologue_end]
3617/// [is_stmt VALUE]
3618/// The first number is a file number, must have been previously assigned with
3619/// a .file directive, the second number is the line number and optionally the
3620/// third number is a column position (zero if not specified). The remaining
3621/// optional items are .loc sub-directives.
3622bool AsmParser::parseDirectiveCVLoc() {
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003623 SMLoc DirectiveLoc = getTok().getLoc();
Nirav Davea645433c2016-07-18 15:24:03 +00003624 int64_t FunctionId, FileNumber;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003625 if (parseCVFunctionId(FunctionId, ".cv_loc") ||
3626 parseCVFileId(FileNumber, ".cv_loc"))
Nirav Davea645433c2016-07-18 15:24:03 +00003627 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003628
3629 int64_t LineNumber = 0;
3630 if (getLexer().is(AsmToken::Integer)) {
3631 LineNumber = getTok().getIntVal();
3632 if (LineNumber < 0)
3633 return TokError("line number less than zero in '.cv_loc' directive");
3634 Lex();
3635 }
3636
3637 int64_t ColumnPos = 0;
3638 if (getLexer().is(AsmToken::Integer)) {
3639 ColumnPos = getTok().getIntVal();
3640 if (ColumnPos < 0)
3641 return TokError("column position less than zero in '.cv_loc' directive");
3642 Lex();
3643 }
3644
3645 bool PrologueEnd = false;
3646 uint64_t IsStmt = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003647
3648 auto parseOp = [&]() -> bool {
Reid Kleckner2214ed82016-01-29 00:49:42 +00003649 StringRef Name;
3650 SMLoc Loc = getTok().getLoc();
3651 if (parseIdentifier(Name))
3652 return TokError("unexpected token in '.cv_loc' directive");
Reid Kleckner2214ed82016-01-29 00:49:42 +00003653 if (Name == "prologue_end")
3654 PrologueEnd = true;
3655 else if (Name == "is_stmt") {
3656 Loc = getTok().getLoc();
3657 const MCExpr *Value;
3658 if (parseExpression(Value))
3659 return true;
3660 // The expression must be the constant 0 or 1.
3661 IsStmt = ~0ULL;
3662 if (const auto *MCE = dyn_cast<MCConstantExpr>(Value))
3663 IsStmt = MCE->getValue();
3664
3665 if (IsStmt > 1)
3666 return Error(Loc, "is_stmt value not 0 or 1");
3667 } else {
3668 return Error(Loc, "unknown sub-directive in '.cv_loc' directive");
3669 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003670 return false;
3671 };
3672
3673 if (parseMany(parseOp, false /*hasComma*/))
3674 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003675
3676 getStreamer().EmitCVLocDirective(FunctionId, FileNumber, LineNumber,
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003677 ColumnPos, PrologueEnd, IsStmt, StringRef(),
3678 DirectiveLoc);
Reid Kleckner2214ed82016-01-29 00:49:42 +00003679 return false;
3680}
3681
3682/// parseDirectiveCVLinetable
3683/// ::= .cv_linetable FunctionId, FnStart, FnEnd
3684bool AsmParser::parseDirectiveCVLinetable() {
Nirav Davea645433c2016-07-18 15:24:03 +00003685 int64_t FunctionId;
3686 StringRef FnStartName, FnEndName;
3687 SMLoc Loc = getTok().getLoc();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003688 if (parseCVFunctionId(FunctionId, ".cv_linetable") ||
Nirav Davea645433c2016-07-18 15:24:03 +00003689 parseToken(AsmToken::Comma,
3690 "unexpected token in '.cv_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003691 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3692 "expected identifier in directive") ||
Nirav Davea645433c2016-07-18 15:24:03 +00003693 parseToken(AsmToken::Comma,
3694 "unexpected token in '.cv_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003695 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3696 "expected identifier in directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00003697 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003698
3699 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3700 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
3701
3702 getStreamer().EmitCVLinetableDirective(FunctionId, FnStartSym, FnEndSym);
3703 return false;
3704}
3705
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003706/// parseDirectiveCVInlineLinetable
David Majnemerc9911f22016-02-02 19:22:34 +00003707/// ::= .cv_inline_linetable PrimaryFunctionId FileId LineNum FnStart FnEnd
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003708bool AsmParser::parseDirectiveCVInlineLinetable() {
Nirav Davea645433c2016-07-18 15:24:03 +00003709 int64_t PrimaryFunctionId, SourceFileId, SourceLineNum;
3710 StringRef FnStartName, FnEndName;
3711 SMLoc Loc = getTok().getLoc();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003712 if (parseCVFunctionId(PrimaryFunctionId, ".cv_inline_linetable") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003713 parseTokenLoc(Loc) ||
Nirav Davea645433c2016-07-18 15:24:03 +00003714 parseIntToken(
3715 SourceFileId,
3716 "expected SourceField in '.cv_inline_linetable' directive") ||
3717 check(SourceFileId <= 0, Loc,
3718 "File id less than zero in '.cv_inline_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003719 parseTokenLoc(Loc) ||
Nirav Davea645433c2016-07-18 15:24:03 +00003720 parseIntToken(
3721 SourceLineNum,
3722 "expected SourceLineNum in '.cv_inline_linetable' directive") ||
3723 check(SourceLineNum < 0, Loc,
3724 "Line number less than zero in '.cv_inline_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003725 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3726 "expected identifier in directive") ||
3727 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3728 "expected identifier in directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00003729 return true;
David Majnemerc9911f22016-02-02 19:22:34 +00003730
Nirav Davea645433c2016-07-18 15:24:03 +00003731 if (parseToken(AsmToken::EndOfStatement, "Expected End of Statement"))
3732 return true;
3733
3734 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3735 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
Reid Kleckner1fcd6102016-02-02 17:41:18 +00003736 getStreamer().EmitCVInlineLinetableDirective(PrimaryFunctionId, SourceFileId,
3737 SourceLineNum, FnStartSym,
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003738 FnEndSym);
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003739 return false;
3740}
3741
David Majnemer408b5e62016-02-05 01:55:49 +00003742/// parseDirectiveCVDefRange
3743/// ::= .cv_def_range RangeStart RangeEnd (GapStart GapEnd)*, bytes*
3744bool AsmParser::parseDirectiveCVDefRange() {
3745 SMLoc Loc;
3746 std::vector<std::pair<const MCSymbol *, const MCSymbol *>> Ranges;
3747 while (getLexer().is(AsmToken::Identifier)) {
3748 Loc = getLexer().getLoc();
3749 StringRef GapStartName;
3750 if (parseIdentifier(GapStartName))
3751 return Error(Loc, "expected identifier in directive");
3752 MCSymbol *GapStartSym = getContext().getOrCreateSymbol(GapStartName);
3753
3754 Loc = getLexer().getLoc();
3755 StringRef GapEndName;
3756 if (parseIdentifier(GapEndName))
3757 return Error(Loc, "expected identifier in directive");
3758 MCSymbol *GapEndSym = getContext().getOrCreateSymbol(GapEndName);
3759
3760 Ranges.push_back({GapStartSym, GapEndSym});
3761 }
3762
David Majnemer408b5e62016-02-05 01:55:49 +00003763 std::string FixedSizePortion;
Nirav Davea645433c2016-07-18 15:24:03 +00003764 if (parseToken(AsmToken::Comma, "unexpected token in directive") ||
3765 parseEscapedString(FixedSizePortion))
David Majnemer408b5e62016-02-05 01:55:49 +00003766 return true;
David Majnemer408b5e62016-02-05 01:55:49 +00003767
3768 getStreamer().EmitCVDefRangeDirective(Ranges, FixedSizePortion);
3769 return false;
3770}
3771
Reid Kleckner2214ed82016-01-29 00:49:42 +00003772/// parseDirectiveCVStringTable
3773/// ::= .cv_stringtable
3774bool AsmParser::parseDirectiveCVStringTable() {
3775 getStreamer().EmitCVStringTableDirective();
3776 return false;
3777}
3778
3779/// parseDirectiveCVFileChecksums
3780/// ::= .cv_filechecksums
3781bool AsmParser::parseDirectiveCVFileChecksums() {
3782 getStreamer().EmitCVFileChecksumsDirective();
3783 return false;
3784}
3785
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003786/// parseDirectiveCVFileChecksumOffset
3787/// ::= .cv_filechecksumoffset fileno
3788bool AsmParser::parseDirectiveCVFileChecksumOffset() {
3789 int64_t FileNo;
3790 if (parseIntToken(FileNo, "expected identifier in directive"))
3791 return true;
3792 if (parseToken(AsmToken::EndOfStatement, "Expected End of Statement"))
3793 return true;
3794 getStreamer().EmitCVFileChecksumOffsetDirective(FileNo);
3795 return false;
3796}
3797
Reid Kleckner9cdd4df2017-10-11 21:24:33 +00003798/// parseDirectiveCVFPOData
3799/// ::= .cv_fpo_data procsym
3800bool AsmParser::parseDirectiveCVFPOData() {
3801 SMLoc DirLoc = getLexer().getLoc();
3802 StringRef ProcName;
3803 if (parseIdentifier(ProcName))
3804 return TokError("expected symbol name");
3805 if (parseEOL("unexpected tokens"))
3806 return addErrorSuffix(" in '.cv_fpo_data' directive");
3807 MCSymbol *ProcSym = getContext().getOrCreateSymbol(ProcName);
3808 getStreamer().EmitCVFPOData(ProcSym, DirLoc);
3809 return false;
3810}
3811
Jim Grosbach4b905842013-09-20 23:08:21 +00003812/// parseDirectiveCFISections
Eli Bendersky17233942013-01-15 22:59:42 +00003813/// ::= .cfi_sections section [, section]
Jim Grosbach4b905842013-09-20 23:08:21 +00003814bool AsmParser::parseDirectiveCFISections() {
Eli Bendersky17233942013-01-15 22:59:42 +00003815 StringRef Name;
3816 bool EH = false;
3817 bool Debug = false;
3818
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003819 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003820 return TokError("Expected an identifier");
3821
3822 if (Name == ".eh_frame")
3823 EH = true;
3824 else if (Name == ".debug_frame")
3825 Debug = true;
3826
3827 if (getLexer().is(AsmToken::Comma)) {
3828 Lex();
3829
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003830 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003831 return TokError("Expected an identifier");
3832
3833 if (Name == ".eh_frame")
3834 EH = true;
3835 else if (Name == ".debug_frame")
3836 Debug = true;
3837 }
3838
3839 getStreamer().EmitCFISections(EH, Debug);
3840 return false;
3841}
3842
Jim Grosbach4b905842013-09-20 23:08:21 +00003843/// parseDirectiveCFIStartProc
David Majnemere035cf92014-01-27 17:20:25 +00003844/// ::= .cfi_startproc [simple]
Jim Grosbach4b905842013-09-20 23:08:21 +00003845bool AsmParser::parseDirectiveCFIStartProc() {
David Majnemere035cf92014-01-27 17:20:25 +00003846 StringRef Simple;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003847 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
3848 if (check(parseIdentifier(Simple) || Simple != "simple",
3849 "unexpected token") ||
3850 parseToken(AsmToken::EndOfStatement))
3851 return addErrorSuffix(" in '.cfi_startproc' directive");
3852 }
Nirav Davea645433c2016-07-18 15:24:03 +00003853
Oliver Stannardcf6bfb12014-11-03 12:19:03 +00003854 getStreamer().EmitCFIStartProc(!Simple.empty());
Eli Bendersky17233942013-01-15 22:59:42 +00003855 return false;
3856}
3857
Jim Grosbach4b905842013-09-20 23:08:21 +00003858/// parseDirectiveCFIEndProc
Eli Bendersky17233942013-01-15 22:59:42 +00003859/// ::= .cfi_endproc
Jim Grosbach4b905842013-09-20 23:08:21 +00003860bool AsmParser::parseDirectiveCFIEndProc() {
Eli Bendersky17233942013-01-15 22:59:42 +00003861 getStreamer().EmitCFIEndProc();
3862 return false;
3863}
3864
Jim Grosbach4b905842013-09-20 23:08:21 +00003865/// \brief parse register name or number.
3866bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
Eli Bendersky17233942013-01-15 22:59:42 +00003867 SMLoc DirectiveLoc) {
3868 unsigned RegNo;
3869
3870 if (getLexer().isNot(AsmToken::Integer)) {
3871 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
3872 return true;
Bill Wendlingbc07a892013-06-18 07:20:20 +00003873 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
Eli Bendersky17233942013-01-15 22:59:42 +00003874 } else
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003875 return parseAbsoluteExpression(Register);
Eli Bendersky17233942013-01-15 22:59:42 +00003876
3877 return false;
3878}
3879
Jim Grosbach4b905842013-09-20 23:08:21 +00003880/// parseDirectiveCFIDefCfa
Eli Bendersky17233942013-01-15 22:59:42 +00003881/// ::= .cfi_def_cfa register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003882bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003883 int64_t Register = 0, Offset = 0;
3884 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3885 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3886 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003887 return true;
3888
3889 getStreamer().EmitCFIDefCfa(Register, Offset);
3890 return false;
3891}
3892
Jim Grosbach4b905842013-09-20 23:08:21 +00003893/// parseDirectiveCFIDefCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003894/// ::= .cfi_def_cfa_offset offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003895bool AsmParser::parseDirectiveCFIDefCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00003896 int64_t Offset = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003897 if (parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003898 return true;
3899
3900 getStreamer().EmitCFIDefCfaOffset(Offset);
3901 return false;
3902}
3903
Jim Grosbach4b905842013-09-20 23:08:21 +00003904/// parseDirectiveCFIRegister
Eli Bendersky17233942013-01-15 22:59:42 +00003905/// ::= .cfi_register register, register
Jim Grosbach4b905842013-09-20 23:08:21 +00003906bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003907 int64_t Register1 = 0, Register2 = 0;
3908 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc) ||
3909 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3910 parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003911 return true;
3912
3913 getStreamer().EmitCFIRegister(Register1, Register2);
3914 return false;
3915}
3916
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00003917/// parseDirectiveCFIWindowSave
3918/// ::= .cfi_window_save
3919bool AsmParser::parseDirectiveCFIWindowSave() {
3920 getStreamer().EmitCFIWindowSave();
3921 return false;
3922}
3923
Jim Grosbach4b905842013-09-20 23:08:21 +00003924/// parseDirectiveCFIAdjustCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003925/// ::= .cfi_adjust_cfa_offset adjustment
Jim Grosbach4b905842013-09-20 23:08:21 +00003926bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00003927 int64_t Adjustment = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003928 if (parseAbsoluteExpression(Adjustment))
Eli Bendersky17233942013-01-15 22:59:42 +00003929 return true;
3930
3931 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3932 return false;
3933}
3934
Jim Grosbach4b905842013-09-20 23:08:21 +00003935/// parseDirectiveCFIDefCfaRegister
Eli Bendersky17233942013-01-15 22:59:42 +00003936/// ::= .cfi_def_cfa_register register
Jim Grosbach4b905842013-09-20 23:08:21 +00003937bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003938 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003939 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003940 return true;
3941
3942 getStreamer().EmitCFIDefCfaRegister(Register);
3943 return false;
3944}
3945
Jim Grosbach4b905842013-09-20 23:08:21 +00003946/// parseDirectiveCFIOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003947/// ::= .cfi_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003948bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003949 int64_t Register = 0;
3950 int64_t Offset = 0;
3951
Nirav Davea645433c2016-07-18 15:24:03 +00003952 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3953 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3954 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003955 return true;
3956
3957 getStreamer().EmitCFIOffset(Register, Offset);
3958 return false;
3959}
3960
Jim Grosbach4b905842013-09-20 23:08:21 +00003961/// parseDirectiveCFIRelOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003962/// ::= .cfi_rel_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003963bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003964 int64_t Register = 0, Offset = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003965
Nirav Davea645433c2016-07-18 15:24:03 +00003966 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3967 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3968 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003969 return true;
3970
3971 getStreamer().EmitCFIRelOffset(Register, Offset);
3972 return false;
3973}
3974
3975static bool isValidEncoding(int64_t Encoding) {
3976 if (Encoding & ~0xff)
3977 return false;
3978
3979 if (Encoding == dwarf::DW_EH_PE_omit)
3980 return true;
3981
3982 const unsigned Format = Encoding & 0xf;
3983 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3984 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3985 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3986 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3987 return false;
3988
3989 const unsigned Application = Encoding & 0x70;
3990 if (Application != dwarf::DW_EH_PE_absptr &&
3991 Application != dwarf::DW_EH_PE_pcrel)
3992 return false;
3993
3994 return true;
3995}
3996
Jim Grosbach4b905842013-09-20 23:08:21 +00003997/// parseDirectiveCFIPersonalityOrLsda
Eli Bendersky17233942013-01-15 22:59:42 +00003998/// IsPersonality true for cfi_personality, false for cfi_lsda
3999/// ::= .cfi_personality encoding, [symbol_name]
4000/// ::= .cfi_lsda encoding, [symbol_name]
Jim Grosbach4b905842013-09-20 23:08:21 +00004001bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
Eli Bendersky17233942013-01-15 22:59:42 +00004002 int64_t Encoding = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004003 if (parseAbsoluteExpression(Encoding))
Eli Bendersky17233942013-01-15 22:59:42 +00004004 return true;
4005 if (Encoding == dwarf::DW_EH_PE_omit)
4006 return false;
4007
Eli Bendersky17233942013-01-15 22:59:42 +00004008 StringRef Name;
Nirav Davea645433c2016-07-18 15:24:03 +00004009 if (check(!isValidEncoding(Encoding), "unsupported encoding.") ||
4010 parseToken(AsmToken::Comma, "unexpected token in directive") ||
4011 check(parseIdentifier(Name), "expected identifier in directive"))
4012 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004013
Jim Grosbach6f482002015-05-18 18:43:14 +00004014 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Eli Bendersky17233942013-01-15 22:59:42 +00004015
4016 if (IsPersonality)
4017 getStreamer().EmitCFIPersonality(Sym, Encoding);
4018 else
4019 getStreamer().EmitCFILsda(Sym, Encoding);
4020 return false;
4021}
4022
Jim Grosbach4b905842013-09-20 23:08:21 +00004023/// parseDirectiveCFIRememberState
Eli Bendersky17233942013-01-15 22:59:42 +00004024/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00004025bool AsmParser::parseDirectiveCFIRememberState() {
Eli Bendersky17233942013-01-15 22:59:42 +00004026 getStreamer().EmitCFIRememberState();
4027 return false;
4028}
4029
Jim Grosbach4b905842013-09-20 23:08:21 +00004030/// parseDirectiveCFIRestoreState
Eli Bendersky17233942013-01-15 22:59:42 +00004031/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00004032bool AsmParser::parseDirectiveCFIRestoreState() {
Eli Bendersky17233942013-01-15 22:59:42 +00004033 getStreamer().EmitCFIRestoreState();
4034 return false;
4035}
4036
Jim Grosbach4b905842013-09-20 23:08:21 +00004037/// parseDirectiveCFISameValue
Eli Bendersky17233942013-01-15 22:59:42 +00004038/// ::= .cfi_same_value register
Jim Grosbach4b905842013-09-20 23:08:21 +00004039bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004040 int64_t Register = 0;
4041
Jim Grosbach4b905842013-09-20 23:08:21 +00004042 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00004043 return true;
4044
4045 getStreamer().EmitCFISameValue(Register);
4046 return false;
4047}
4048
Jim Grosbach4b905842013-09-20 23:08:21 +00004049/// parseDirectiveCFIRestore
Eli Bendersky17233942013-01-15 22:59:42 +00004050/// ::= .cfi_restore register
Jim Grosbach4b905842013-09-20 23:08:21 +00004051bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004052 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00004053 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00004054 return true;
4055
4056 getStreamer().EmitCFIRestore(Register);
4057 return false;
4058}
4059
Jim Grosbach4b905842013-09-20 23:08:21 +00004060/// parseDirectiveCFIEscape
Eli Bendersky17233942013-01-15 22:59:42 +00004061/// ::= .cfi_escape expression[,...]
Jim Grosbach4b905842013-09-20 23:08:21 +00004062bool AsmParser::parseDirectiveCFIEscape() {
Eli Bendersky17233942013-01-15 22:59:42 +00004063 std::string Values;
4064 int64_t CurrValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004065 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00004066 return true;
4067
4068 Values.push_back((uint8_t)CurrValue);
4069
4070 while (getLexer().is(AsmToken::Comma)) {
4071 Lex();
4072
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004073 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00004074 return true;
4075
4076 Values.push_back((uint8_t)CurrValue);
4077 }
4078
4079 getStreamer().EmitCFIEscape(Values);
4080 return false;
4081}
4082
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +00004083/// parseDirectiveCFIReturnColumn
4084/// ::= .cfi_return_column register
4085bool AsmParser::parseDirectiveCFIReturnColumn(SMLoc DirectiveLoc) {
4086 int64_t Register = 0;
4087 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
4088 return true;
4089 getStreamer().EmitCFIReturnColumn(Register);
4090 return false;
4091}
4092
Jim Grosbach4b905842013-09-20 23:08:21 +00004093/// parseDirectiveCFISignalFrame
Eli Bendersky17233942013-01-15 22:59:42 +00004094/// ::= .cfi_signal_frame
Jim Grosbach4b905842013-09-20 23:08:21 +00004095bool AsmParser::parseDirectiveCFISignalFrame() {
Nirav Davea645433c2016-07-18 15:24:03 +00004096 if (parseToken(AsmToken::EndOfStatement,
4097 "unexpected token in '.cfi_signal_frame'"))
4098 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004099
4100 getStreamer().EmitCFISignalFrame();
4101 return false;
4102}
4103
Jim Grosbach4b905842013-09-20 23:08:21 +00004104/// parseDirectiveCFIUndefined
Eli Bendersky17233942013-01-15 22:59:42 +00004105/// ::= .cfi_undefined register
Jim Grosbach4b905842013-09-20 23:08:21 +00004106bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004107 int64_t Register = 0;
4108
Jim Grosbach4b905842013-09-20 23:08:21 +00004109 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00004110 return true;
4111
4112 getStreamer().EmitCFIUndefined(Register);
4113 return false;
4114}
4115
Michael Zuckerman56704612017-05-01 13:20:12 +00004116/// parseDirectiveAltmacro
4117/// ::= .altmacro
4118/// ::= .noaltmacro
4119bool AsmParser::parseDirectiveAltmacro(StringRef Directive) {
4120 if (getLexer().isNot(AsmToken::EndOfStatement))
4121 return TokError("unexpected token in '" + Directive + "' directive");
4122 if (Directive == ".altmacro")
4123 getLexer().SetAltMacroMode(true);
4124 else
4125 getLexer().SetAltMacroMode(false);
4126 return false;
4127}
4128
Jim Grosbach4b905842013-09-20 23:08:21 +00004129/// parseDirectiveMacrosOnOff
Eli Bendersky17233942013-01-15 22:59:42 +00004130/// ::= .macros_on
4131/// ::= .macros_off
Jim Grosbach4b905842013-09-20 23:08:21 +00004132bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
Nirav Davea645433c2016-07-18 15:24:03 +00004133 if (parseToken(AsmToken::EndOfStatement,
4134 "unexpected token in '" + Directive + "' directive"))
4135 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004136
Jim Grosbach4b905842013-09-20 23:08:21 +00004137 setMacrosEnabled(Directive == ".macros_on");
Eli Bendersky17233942013-01-15 22:59:42 +00004138 return false;
4139}
4140
Jim Grosbach4b905842013-09-20 23:08:21 +00004141/// parseDirectiveMacro
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00004142/// ::= .macro name[,] [parameters]
Jim Grosbach4b905842013-09-20 23:08:21 +00004143bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004144 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004145 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00004146 return TokError("expected identifier in '.macro' directive");
4147
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00004148 if (getLexer().is(AsmToken::Comma))
4149 Lex();
4150
Eli Bendersky17233942013-01-15 22:59:42 +00004151 MCAsmMacroParameters Parameters;
David Majnemer91fc4c22014-01-29 18:57:46 +00004152 while (getLexer().isNot(AsmToken::EndOfStatement)) {
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00004153
Alexander Kornienko8c0809c2015-01-15 11:41:30 +00004154 if (!Parameters.empty() && Parameters.back().Vararg)
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00004155 return Error(Lexer.getLoc(),
4156 "Vararg parameter '" + Parameters.back().Name +
4157 "' should be last one in the list of parameters.");
4158
David Majnemer91fc4c22014-01-29 18:57:46 +00004159 MCAsmMacroParameter Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00004160 if (parseIdentifier(Parameter.Name))
David Majnemer91fc4c22014-01-29 18:57:46 +00004161 return TokError("expected identifier in '.macro' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00004162
Coby Tayreebedaae02017-04-08 20:29:03 +00004163 // Emit an error if two (or more) named parameters share the same name
4164 for (const MCAsmMacroParameter& CurrParam : Parameters)
4165 if (CurrParam.Name.equals(Parameter.Name))
4166 return TokError("macro '" + Name + "' has multiple parameters"
4167 " named '" + Parameter.Name + "'");
4168
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00004169 if (Lexer.is(AsmToken::Colon)) {
4170 Lex(); // consume ':'
4171
4172 SMLoc QualLoc;
4173 StringRef Qualifier;
4174
4175 QualLoc = Lexer.getLoc();
4176 if (parseIdentifier(Qualifier))
4177 return Error(QualLoc, "missing parameter qualifier for "
4178 "'" + Parameter.Name + "' in macro '" + Name + "'");
4179
4180 if (Qualifier == "req")
4181 Parameter.Required = true;
Kevin Enderbye3c13462014-08-04 23:14:37 +00004182 else if (Qualifier == "vararg")
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00004183 Parameter.Vararg = true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00004184 else
4185 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
4186 "for '" + Parameter.Name + "' in macro '" + Name + "'");
4187 }
4188
David Majnemer91fc4c22014-01-29 18:57:46 +00004189 if (getLexer().is(AsmToken::Equal)) {
4190 Lex();
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00004191
4192 SMLoc ParamLoc;
4193
4194 ParamLoc = Lexer.getLoc();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00004195 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
David Majnemer91fc4c22014-01-29 18:57:46 +00004196 return true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00004197
4198 if (Parameter.Required)
4199 Warning(ParamLoc, "pointless default value for required parameter "
4200 "'" + Parameter.Name + "' in macro '" + Name + "'");
Eli Bendersky17233942013-01-15 22:59:42 +00004201 }
David Majnemer91fc4c22014-01-29 18:57:46 +00004202
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00004203 Parameters.push_back(std::move(Parameter));
David Majnemer91fc4c22014-01-29 18:57:46 +00004204
4205 if (getLexer().is(AsmToken::Comma))
4206 Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00004207 }
4208
Nirav Dave1180e6892016-06-02 17:15:05 +00004209 // Eat just the end of statement.
4210 Lexer.Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00004211
Nirav Dave1180e6892016-06-02 17:15:05 +00004212 // Consuming deferred text, so use Lexer.Lex to ignore Lexing Errors
Eli Bendersky17233942013-01-15 22:59:42 +00004213 AsmToken EndToken, StartToken = getTok();
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00004214 unsigned MacroDepth = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00004215 // Lex the macro definition.
Eugene Zelenko33d7b762016-08-23 17:14:32 +00004216 while (true) {
Nirav Dave1180e6892016-06-02 17:15:05 +00004217 // Ignore Lexing errors in macros.
4218 while (Lexer.is(AsmToken::Error)) {
4219 Lexer.Lex();
4220 }
4221
Eli Bendersky17233942013-01-15 22:59:42 +00004222 // Check whether we have reached the end of the file.
4223 if (getLexer().is(AsmToken::Eof))
4224 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
4225
4226 // Otherwise, check whether we have reach the .endmacro.
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00004227 if (getLexer().is(AsmToken::Identifier)) {
4228 if (getTok().getIdentifier() == ".endm" ||
4229 getTok().getIdentifier() == ".endmacro") {
4230 if (MacroDepth == 0) { // Outermost macro.
4231 EndToken = getTok();
Nirav Dave1180e6892016-06-02 17:15:05 +00004232 Lexer.Lex();
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00004233 if (getLexer().isNot(AsmToken::EndOfStatement))
4234 return TokError("unexpected token in '" + EndToken.getIdentifier() +
4235 "' directive");
4236 break;
4237 } else {
4238 // Otherwise we just found the end of an inner macro.
4239 --MacroDepth;
4240 }
4241 } else if (getTok().getIdentifier() == ".macro") {
4242 // We allow nested macros. Those aren't instantiated until the outermost
4243 // macro is expanded so just ignore them for now.
4244 ++MacroDepth;
4245 }
Eli Bendersky17233942013-01-15 22:59:42 +00004246 }
4247
4248 // Otherwise, scan til the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004249 eatToEndOfStatement();
Eli Bendersky17233942013-01-15 22:59:42 +00004250 }
4251
Rafael Espindola22c38a02018-02-14 16:34:27 +00004252 if (getContext().lookupMacro(Name)) {
Eli Bendersky17233942013-01-15 22:59:42 +00004253 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
4254 }
4255
4256 const char *BodyStart = StartToken.getLoc().getPointer();
4257 const char *BodyEnd = EndToken.getLoc().getPointer();
4258 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Jim Grosbach4b905842013-09-20 23:08:21 +00004259 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
Rafael Espindola22c38a02018-02-14 16:34:27 +00004260 getContext().defineMacro(Name, MCAsmMacro(Name, Body, std::move(Parameters)));
Eli Bendersky17233942013-01-15 22:59:42 +00004261 return false;
4262}
4263
Jim Grosbach4b905842013-09-20 23:08:21 +00004264/// checkForBadMacro
Kevin Enderby81c944c2013-01-22 21:44:53 +00004265///
4266/// With the support added for named parameters there may be code out there that
4267/// is transitioning from positional parameters. In versions of gas that did
Alp Tokercb402912014-01-24 17:20:08 +00004268/// not support named parameters they would be ignored on the macro definition.
Kevin Enderby81c944c2013-01-22 21:44:53 +00004269/// But to support both styles of parameters this is not possible so if a macro
Alp Tokercb402912014-01-24 17:20:08 +00004270/// definition has named parameters but does not use them and has what appears
Kevin Enderby81c944c2013-01-22 21:44:53 +00004271/// to be positional parameters, strings like $1, $2, ... and $n, then issue a
4272/// warning that the positional parameter found in body which have no effect.
4273/// Hoping the developer will either remove the named parameters from the macro
Alp Tokercb402912014-01-24 17:20:08 +00004274/// definition so the positional parameters get used if that was what was
Kevin Enderby81c944c2013-01-22 21:44:53 +00004275/// intended or change the macro to use the named parameters. It is possible
4276/// this warning will trigger when the none of the named parameters are used
4277/// and the strings like $1 are infact to simply to be passed trough unchanged.
Jim Grosbach4b905842013-09-20 23:08:21 +00004278void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
Kevin Enderby81c944c2013-01-22 21:44:53 +00004279 StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00004280 ArrayRef<MCAsmMacroParameter> Parameters) {
Kevin Enderby81c944c2013-01-22 21:44:53 +00004281 // If this macro is not defined with named parameters the warning we are
4282 // checking for here doesn't apply.
4283 unsigned NParameters = Parameters.size();
4284 if (NParameters == 0)
4285 return;
4286
4287 bool NamedParametersFound = false;
4288 bool PositionalParametersFound = false;
4289
4290 // Look at the body of the macro for use of both the named parameters and what
4291 // are likely to be positional parameters. This is what expandMacro() is
4292 // doing when it finds the parameters in the body.
4293 while (!Body.empty()) {
4294 // Scan for the next possible parameter.
4295 std::size_t End = Body.size(), Pos = 0;
4296 for (; Pos != End; ++Pos) {
4297 // Check for a substitution or escape.
4298 // This macro is defined with parameters, look for \foo, \bar, etc.
4299 if (Body[Pos] == '\\' && Pos + 1 != End)
4300 break;
4301
4302 // This macro should have parameters, but look for $0, $1, ..., $n too.
4303 if (Body[Pos] != '$' || Pos + 1 == End)
4304 continue;
4305 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00004306 if (Next == '$' || Next == 'n' ||
4307 isdigit(static_cast<unsigned char>(Next)))
Kevin Enderby81c944c2013-01-22 21:44:53 +00004308 break;
4309 }
4310
4311 // Check if we reached the end.
4312 if (Pos == End)
4313 break;
4314
4315 if (Body[Pos] == '$') {
Jim Grosbach4b905842013-09-20 23:08:21 +00004316 switch (Body[Pos + 1]) {
4317 // $$ => $
Kevin Enderby81c944c2013-01-22 21:44:53 +00004318 case '$':
4319 break;
4320
Jim Grosbach4b905842013-09-20 23:08:21 +00004321 // $n => number of arguments
Kevin Enderby81c944c2013-01-22 21:44:53 +00004322 case 'n':
4323 PositionalParametersFound = true;
4324 break;
4325
Jim Grosbach4b905842013-09-20 23:08:21 +00004326 // $[0-9] => argument
Kevin Enderby81c944c2013-01-22 21:44:53 +00004327 default: {
4328 PositionalParametersFound = true;
4329 break;
Jim Grosbach4b905842013-09-20 23:08:21 +00004330 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00004331 }
4332 Pos += 2;
4333 } else {
4334 unsigned I = Pos + 1;
4335 while (isIdentifierChar(Body[I]) && I + 1 != End)
4336 ++I;
4337
Jim Grosbach4b905842013-09-20 23:08:21 +00004338 const char *Begin = Body.data() + Pos + 1;
4339 StringRef Argument(Begin, I - (Pos + 1));
Kevin Enderby81c944c2013-01-22 21:44:53 +00004340 unsigned Index = 0;
4341 for (; Index < NParameters; ++Index)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00004342 if (Parameters[Index].Name == Argument)
Kevin Enderby81c944c2013-01-22 21:44:53 +00004343 break;
4344
4345 if (Index == NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00004346 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
4347 Pos += 3;
4348 else {
4349 Pos = I;
4350 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00004351 } else {
4352 NamedParametersFound = true;
4353 Pos += 1 + Argument.size();
4354 }
4355 }
4356 // Update the scan point.
4357 Body = Body.substr(Pos);
4358 }
4359
4360 if (!NamedParametersFound && PositionalParametersFound)
4361 Warning(DirectiveLoc, "macro defined with named parameters which are not "
4362 "used in macro body, possible positional parameter "
4363 "found in body which will have no effect");
4364}
4365
Nico Weber155dccd12014-07-24 17:08:39 +00004366/// parseDirectiveExitMacro
4367/// ::= .exitm
4368bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
Nirav Davea645433c2016-07-18 15:24:03 +00004369 if (parseToken(AsmToken::EndOfStatement,
4370 "unexpected token in '" + Directive + "' directive"))
4371 return true;
Nico Weber155dccd12014-07-24 17:08:39 +00004372
4373 if (!isInsideMacroInstantiation())
4374 return TokError("unexpected '" + Directive + "' in file, "
4375 "no current macro definition");
4376
4377 // Exit all conditionals that are active in the current macro.
4378 while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
4379 TheCondState = TheCondStack.back();
4380 TheCondStack.pop_back();
4381 }
4382
4383 handleMacroExit();
4384 return false;
4385}
4386
Jim Grosbach4b905842013-09-20 23:08:21 +00004387/// parseDirectiveEndMacro
Eli Bendersky17233942013-01-15 22:59:42 +00004388/// ::= .endm
4389/// ::= .endmacro
Jim Grosbach4b905842013-09-20 23:08:21 +00004390bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
Eli Bendersky17233942013-01-15 22:59:42 +00004391 if (getLexer().isNot(AsmToken::EndOfStatement))
4392 return TokError("unexpected token in '" + Directive + "' directive");
4393
4394 // If we are inside a macro instantiation, terminate the current
4395 // instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00004396 if (isInsideMacroInstantiation()) {
4397 handleMacroExit();
Eli Bendersky17233942013-01-15 22:59:42 +00004398 return false;
4399 }
4400
4401 // Otherwise, this .endmacro is a stray entry in the file; well formed
4402 // .endmacro directives are handled during the macro definition parsing.
4403 return TokError("unexpected '" + Directive + "' in file, "
Jim Grosbach4b905842013-09-20 23:08:21 +00004404 "no current macro definition");
Eli Bendersky17233942013-01-15 22:59:42 +00004405}
4406
Jim Grosbach4b905842013-09-20 23:08:21 +00004407/// parseDirectivePurgeMacro
Eli Bendersky17233942013-01-15 22:59:42 +00004408/// ::= .purgem
Jim Grosbach4b905842013-09-20 23:08:21 +00004409bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004410 StringRef Name;
Nirav Davea645433c2016-07-18 15:24:03 +00004411 SMLoc Loc;
Nirav Daved8858ca2016-08-30 14:15:43 +00004412 if (parseTokenLoc(Loc) ||
4413 check(parseIdentifier(Name), Loc,
4414 "expected identifier in '.purgem' directive") ||
Nirav Davea645433c2016-07-18 15:24:03 +00004415 parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00004416 "unexpected token in '.purgem' directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00004417 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004418
Rafael Espindola22c38a02018-02-14 16:34:27 +00004419 if (!getContext().lookupMacro(Name))
Nirav Dave1ab71992016-07-18 19:35:21 +00004420 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
4421
Rafael Espindola22c38a02018-02-14 16:34:27 +00004422 getContext().undefineMacro(Name);
Eli Bendersky17233942013-01-15 22:59:42 +00004423 return false;
4424}
Eli Benderskyf483ff92012-12-20 19:05:53 +00004425
Jim Grosbach4b905842013-09-20 23:08:21 +00004426/// parseDirectiveBundleAlignMode
Eli Benderskyf483ff92012-12-20 19:05:53 +00004427/// ::= {.bundle_align_mode} expression
Jim Grosbach4b905842013-09-20 23:08:21 +00004428bool AsmParser::parseDirectiveBundleAlignMode() {
Eli Benderskyf483ff92012-12-20 19:05:53 +00004429 // Expect a single argument: an expression that evaluates to a constant
4430 // in the inclusive range 0-30.
4431 SMLoc ExprLoc = getLexer().getLoc();
4432 int64_t AlignSizePow2;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004433 if (checkForValidSection() || parseAbsoluteExpression(AlignSizePow2) ||
Nirav Davea645433c2016-07-18 15:24:03 +00004434 parseToken(AsmToken::EndOfStatement, "unexpected token after expression "
4435 "in '.bundle_align_mode' "
4436 "directive") ||
4437 check(AlignSizePow2 < 0 || AlignSizePow2 > 30, ExprLoc,
4438 "invalid bundle alignment size (expected between 0 and 30)"))
Eli Benderskyf483ff92012-12-20 19:05:53 +00004439 return true;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004440
4441 // Because of AlignSizePow2's verified range we can safely truncate it to
4442 // unsigned.
4443 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
4444 return false;
4445}
4446
Jim Grosbach4b905842013-09-20 23:08:21 +00004447/// parseDirectiveBundleLock
Eli Bendersky802b6282013-01-07 21:51:08 +00004448/// ::= {.bundle_lock} [align_to_end]
Jim Grosbach4b905842013-09-20 23:08:21 +00004449bool AsmParser::parseDirectiveBundleLock() {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004450 if (checkForValidSection())
4451 return true;
Eli Bendersky802b6282013-01-07 21:51:08 +00004452 bool AlignToEnd = false;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004453
Nirav Dave1a9044b2016-10-24 14:35:29 +00004454 StringRef Option;
4455 SMLoc Loc = getTok().getLoc();
4456 const char *kInvalidOptionError =
4457 "invalid option for '.bundle_lock' directive";
Eli Bendersky802b6282013-01-07 21:51:08 +00004458
Nirav Dave1a9044b2016-10-24 14:35:29 +00004459 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
Nirav Davea645433c2016-07-18 15:24:03 +00004460 if (check(parseIdentifier(Option), Loc, kInvalidOptionError) ||
4461 check(Option != "align_to_end", Loc, kInvalidOptionError) ||
Nirav Dave1a9044b2016-10-24 14:35:29 +00004462 parseToken(AsmToken::EndOfStatement,
4463 "unexpected token after '.bundle_lock' directive option"))
Nirav Davea645433c2016-07-18 15:24:03 +00004464 return true;
Eli Bendersky802b6282013-01-07 21:51:08 +00004465 AlignToEnd = true;
4466 }
4467
Eli Bendersky802b6282013-01-07 21:51:08 +00004468 getStreamer().EmitBundleLock(AlignToEnd);
Eli Benderskyf483ff92012-12-20 19:05:53 +00004469 return false;
4470}
4471
Jim Grosbach4b905842013-09-20 23:08:21 +00004472/// parseDirectiveBundleLock
Eli Benderskyf483ff92012-12-20 19:05:53 +00004473/// ::= {.bundle_lock}
Jim Grosbach4b905842013-09-20 23:08:21 +00004474bool AsmParser::parseDirectiveBundleUnlock() {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004475 if (checkForValidSection() ||
4476 parseToken(AsmToken::EndOfStatement,
Nirav Davea645433c2016-07-18 15:24:03 +00004477 "unexpected token in '.bundle_unlock' directive"))
4478 return true;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004479
4480 getStreamer().EmitBundleUnlock();
4481 return false;
4482}
4483
Jim Grosbach4b905842013-09-20 23:08:21 +00004484/// parseDirectiveSpace
Eli Bendersky17233942013-01-15 22:59:42 +00004485/// ::= (.skip | .space) expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004486bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
Petr Hosek67a94a72016-05-28 05:57:48 +00004487 SMLoc NumBytesLoc = Lexer.getLoc();
4488 const MCExpr *NumBytes;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004489 if (checkForValidSection() || parseExpression(NumBytes))
Eli Bendersky17233942013-01-15 22:59:42 +00004490 return true;
4491
4492 int64_t FillExpr = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00004493 if (parseOptionalToken(AsmToken::Comma))
4494 if (parseAbsoluteExpression(FillExpr))
4495 return addErrorSuffix("in '" + Twine(IDVal) + "' directive");
4496 if (parseToken(AsmToken::EndOfStatement))
4497 return addErrorSuffix("in '" + Twine(IDVal) + "' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00004498
Eli Bendersky17233942013-01-15 22:59:42 +00004499 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
Petr Hosek67a94a72016-05-28 05:57:48 +00004500 getStreamer().emitFill(*NumBytes, FillExpr, NumBytesLoc);
Eli Bendersky17233942013-01-15 22:59:42 +00004501
4502 return false;
4503}
4504
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004505/// parseDirectiveDCB
4506/// ::= .dcb.{b, l, w} expression, expression
4507bool AsmParser::parseDirectiveDCB(StringRef IDVal, unsigned Size) {
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004508 SMLoc NumValuesLoc = Lexer.getLoc();
4509 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004510 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004511 return true;
4512
4513 if (NumValues < 0) {
4514 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4515 return false;
4516 }
4517
4518 if (parseToken(AsmToken::Comma,
4519 "unexpected token in '" + Twine(IDVal) + "' directive"))
4520 return true;
4521
4522 const MCExpr *Value;
4523 SMLoc ExprLoc = getLexer().getLoc();
4524 if (parseExpression(Value))
4525 return true;
4526
4527 // Special case constant expressions to match code generator.
4528 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
4529 assert(Size <= 8 && "Invalid size");
4530 uint64_t IntValue = MCE->getValue();
4531 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
4532 return Error(ExprLoc, "literal value out of range for directive");
4533 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4534 getStreamer().EmitIntValue(IntValue, Size);
4535 } else {
4536 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4537 getStreamer().EmitValue(Value, Size, ExprLoc);
4538 }
4539
4540 if (parseToken(AsmToken::EndOfStatement,
4541 "unexpected token in '" + Twine(IDVal) + "' directive"))
4542 return true;
4543
4544 return false;
4545}
4546
4547/// parseDirectiveRealDCB
4548/// ::= .dcb.{d, s} expression, expression
4549bool AsmParser::parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &Semantics) {
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004550 SMLoc NumValuesLoc = Lexer.getLoc();
4551 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004552 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004553 return true;
4554
4555 if (NumValues < 0) {
4556 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4557 return false;
4558 }
4559
4560 if (parseToken(AsmToken::Comma,
4561 "unexpected token in '" + Twine(IDVal) + "' directive"))
4562 return true;
4563
4564 APInt AsInt;
4565 if (parseRealValue(Semantics, AsInt))
4566 return true;
4567
4568 if (parseToken(AsmToken::EndOfStatement,
4569 "unexpected token in '" + Twine(IDVal) + "' directive"))
4570 return true;
4571
4572 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4573 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
4574 AsInt.getBitWidth() / 8);
4575
4576 return false;
4577}
4578
Petr Hosek85b2f672016-09-23 21:53:36 +00004579/// parseDirectiveDS
4580/// ::= .ds.{b, d, l, p, s, w, x} expression
4581bool AsmParser::parseDirectiveDS(StringRef IDVal, unsigned Size) {
Petr Hosek85b2f672016-09-23 21:53:36 +00004582 SMLoc NumValuesLoc = Lexer.getLoc();
4583 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004584 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek85b2f672016-09-23 21:53:36 +00004585 return true;
4586
4587 if (NumValues < 0) {
4588 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4589 return false;
4590 }
4591
4592 if (parseToken(AsmToken::EndOfStatement,
4593 "unexpected token in '" + Twine(IDVal) + "' directive"))
4594 return true;
4595
4596 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4597 getStreamer().emitFill(Size, 0);
4598
4599 return false;
4600}
4601
Jim Grosbach4b905842013-09-20 23:08:21 +00004602/// parseDirectiveLEB128
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004603/// ::= (.sleb128 | .uleb128) [ expression (, expression)* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004604bool AsmParser::parseDirectiveLEB128(bool Signed) {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004605 if (checkForValidSection())
4606 return true;
4607
Nirav Dave1a9044b2016-10-24 14:35:29 +00004608 auto parseOp = [&]() -> bool {
4609 const MCExpr *Value;
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004610 if (parseExpression(Value))
4611 return true;
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004612 if (Signed)
4613 getStreamer().EmitSLEB128Value(Value);
4614 else
4615 getStreamer().EmitULEB128Value(Value);
Nirav Dave1a9044b2016-10-24 14:35:29 +00004616 return false;
4617 };
Eli Bendersky17233942013-01-15 22:59:42 +00004618
Nirav Dave1a9044b2016-10-24 14:35:29 +00004619 if (parseMany(parseOp))
4620 return addErrorSuffix(" in directive");
Eli Bendersky17233942013-01-15 22:59:42 +00004621
4622 return false;
4623}
4624
Jim Grosbach4b905842013-09-20 23:08:21 +00004625/// parseDirectiveSymbolAttribute
Daniel Dunbara5508c82009-06-30 00:33:19 +00004626/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004627bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00004628 auto parseOp = [&]() -> bool {
4629 StringRef Name;
4630 SMLoc Loc = getTok().getLoc();
4631 if (parseIdentifier(Name))
4632 return Error(Loc, "expected identifier");
4633 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004634
Nirav Dave1a9044b2016-10-24 14:35:29 +00004635 // Assembler local symbols don't make any sense here. Complain loudly.
4636 if (Sym->isTemporary())
4637 return Error(Loc, "non-local symbol required");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004638
Nirav Dave1a9044b2016-10-24 14:35:29 +00004639 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
4640 return Error(Loc, "unable to emit symbol attribute");
4641 return false;
4642 };
Daniel Dunbara5508c82009-06-30 00:33:19 +00004643
Nirav Dave1a9044b2016-10-24 14:35:29 +00004644 if (parseMany(parseOp))
4645 return addErrorSuffix(" in directive");
Jan Wen Voungc7682872010-09-30 01:09:20 +00004646 return false;
Daniel Dunbara5508c82009-06-30 00:33:19 +00004647}
Chris Lattnera1e11f52009-07-07 20:30:46 +00004648
Jim Grosbach4b905842013-09-20 23:08:21 +00004649/// parseDirectiveComm
Chris Lattner28ad7542009-07-09 17:25:12 +00004650/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004651bool AsmParser::parseDirectiveComm(bool IsLocal) {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004652 if (checkForValidSection())
4653 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00004654
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004655 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004656 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004657 if (parseIdentifier(Name))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004658 return TokError("expected identifier in directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004659
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +00004660 // Handle the identifier as the key symbol.
Jim Grosbach6f482002015-05-18 18:43:14 +00004661 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Chris Lattnera1e11f52009-07-07 20:30:46 +00004662
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004663 if (getLexer().isNot(AsmToken::Comma))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004664 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00004665 Lex();
Chris Lattnera1e11f52009-07-07 20:30:46 +00004666
4667 int64_t Size;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004668 SMLoc SizeLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004669 if (parseAbsoluteExpression(Size))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004670 return true;
4671
4672 int64_t Pow2Alignment = 0;
4673 SMLoc Pow2AlignmentLoc;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004674 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan686ed8d2010-01-19 20:22:31 +00004675 Lex();
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004676 Pow2AlignmentLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004677 if (parseAbsoluteExpression(Pow2Alignment))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004678 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00004679
Benjamin Kramer68b9f052012-09-07 21:08:01 +00004680 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
4681 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00004682 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
4683
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00004684 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramer68b9f052012-09-07 21:08:01 +00004685 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
4686 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00004687 if (!isPowerOf2_64(Pow2Alignment))
4688 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
4689 Pow2Alignment = Log2_64(Pow2Alignment);
4690 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00004691 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00004692
Nirav Dave1a9044b2016-10-24 14:35:29 +00004693 if (parseToken(AsmToken::EndOfStatement,
4694 "unexpected token in '.comm' or '.lcomm' directive"))
4695 return true;
Chris Lattnera1e11f52009-07-07 20:30:46 +00004696
Chris Lattner28ad7542009-07-09 17:25:12 +00004697 // NOTE: a size of zero for a .comm should create a undefined symbol
4698 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattnera1e11f52009-07-07 20:30:46 +00004699 if (Size < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00004700 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
Jim Grosbach4b905842013-09-20 23:08:21 +00004701 "be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00004702
Eric Christopherbc818852010-05-14 01:38:54 +00004703 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattnera1e11f52009-07-07 20:30:46 +00004704 // may internally end up wanting an alignment in bytes.
4705 // FIXME: Diagnose overflow.
4706 if (Pow2Alignment < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00004707 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
Jim Grosbach4b905842013-09-20 23:08:21 +00004708 "alignment, can't be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00004709
Rafael Espindola13a79bb2017-02-02 21:26:06 +00004710 Sym->redefineIfPossible();
Daniel Dunbar6860ac72009-08-22 07:22:36 +00004711 if (!Sym->isUndefined())
Chris Lattnera1e11f52009-07-07 20:30:46 +00004712 return Error(IDLoc, "invalid symbol redefinition");
4713
Chris Lattner28ad7542009-07-09 17:25:12 +00004714 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00004715 if (IsLocal) {
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00004716 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00004717 return false;
4718 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00004719
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004720 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattnera1e11f52009-07-07 20:30:46 +00004721 return false;
4722}
Chris Lattner07cadaf2009-07-10 22:20:30 +00004723
Jim Grosbach4b905842013-09-20 23:08:21 +00004724/// parseDirectiveAbort
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004725/// ::= .abort [... message ...]
Jim Grosbach4b905842013-09-20 23:08:21 +00004726bool AsmParser::parseDirectiveAbort() {
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004727 // FIXME: Use loc from directive.
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004728 SMLoc Loc = getLexer().getLoc();
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004729
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004730 StringRef Str = parseStringToEndOfStatement();
Nirav Davea645433c2016-07-18 15:24:03 +00004731 if (parseToken(AsmToken::EndOfStatement,
4732 "unexpected token in '.abort' directive"))
4733 return true;
Kevin Enderby56523ce2009-07-13 23:15:14 +00004734
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004735 if (Str.empty())
Nirav Dave2364748a2016-09-16 18:30:20 +00004736 return Error(Loc, ".abort detected. Assembly stopping.");
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004737 else
Nirav Dave2364748a2016-09-16 18:30:20 +00004738 return Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004739 // FIXME: Actually abort assembly here.
Kevin Enderby56523ce2009-07-13 23:15:14 +00004740
4741 return false;
4742}
Kevin Enderbycbe475d2009-07-14 21:35:03 +00004743
Jim Grosbach4b905842013-09-20 23:08:21 +00004744/// parseDirectiveInclude
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004745/// ::= .include "filename"
Jim Grosbach4b905842013-09-20 23:08:21 +00004746bool AsmParser::parseDirectiveInclude() {
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004747 // Allow the strings to have escaped octal character sequence.
4748 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00004749 SMLoc IncludeLoc = getTok().getLoc();
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004750
Nirav Davea645433c2016-07-18 15:24:03 +00004751 if (check(getTok().isNot(AsmToken::String),
4752 "expected string in '.include' directive") ||
4753 parseEscapedString(Filename) ||
4754 check(getTok().isNot(AsmToken::EndOfStatement),
4755 "unexpected token in '.include' directive") ||
4756 // Attempt to switch the lexer to the included file before consuming the
4757 // end of statement to avoid losing it when we switch.
4758 check(enterIncludeFile(Filename), IncludeLoc,
4759 "Could not find include file '" + Filename + "'"))
Chris Lattner693fbb82009-07-16 06:14:39 +00004760 return true;
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004761
4762 return false;
4763}
Kevin Enderby09ea5702009-07-15 15:30:11 +00004764
Jim Grosbach4b905842013-09-20 23:08:21 +00004765/// parseDirectiveIncbin
Petr Hosek2f4ac442016-09-23 00:41:06 +00004766/// ::= .incbin "filename" [ , skip [ , count ] ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004767bool AsmParser::parseDirectiveIncbin() {
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004768 // Allow the strings to have escaped octal character sequence.
4769 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00004770 SMLoc IncbinLoc = getTok().getLoc();
4771 if (check(getTok().isNot(AsmToken::String),
4772 "expected string in '.incbin' directive") ||
Petr Hosek2f4ac442016-09-23 00:41:06 +00004773 parseEscapedString(Filename))
4774 return true;
4775
4776 int64_t Skip = 0;
4777 const MCExpr *Count = nullptr;
4778 SMLoc SkipLoc, CountLoc;
Nirav Dave1a9044b2016-10-24 14:35:29 +00004779 if (parseOptionalToken(AsmToken::Comma)) {
Petr Hosek2f4ac442016-09-23 00:41:06 +00004780 // The skip expression can be omitted while specifying the count, e.g:
4781 // .incbin "filename",,4
4782 if (getTok().isNot(AsmToken::Comma)) {
4783 if (parseTokenLoc(SkipLoc) || parseAbsoluteExpression(Skip))
4784 return true;
4785 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00004786 if (parseOptionalToken(AsmToken::Comma)) {
4787 CountLoc = getTok().getLoc();
4788 if (parseExpression(Count))
Petr Hosek2f4ac442016-09-23 00:41:06 +00004789 return true;
4790 }
4791 }
4792
4793 if (parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00004794 "unexpected token in '.incbin' directive"))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004795 return true;
Nirav Dave1ab71992016-07-18 19:35:21 +00004796
Petr Hosek2f4ac442016-09-23 00:41:06 +00004797 if (check(Skip < 0, SkipLoc, "skip is negative"))
4798 return true;
4799
Nirav Dave1ab71992016-07-18 19:35:21 +00004800 // Attempt to process the included file.
Petr Hosek2f4ac442016-09-23 00:41:06 +00004801 if (processIncbinFile(Filename, Skip, Count, CountLoc))
Nirav Dave1ab71992016-07-18 19:35:21 +00004802 return Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
Kevin Enderby109f25c2011-12-14 21:47:48 +00004803 return false;
4804}
4805
Jim Grosbach4b905842013-09-20 23:08:21 +00004806/// parseDirectiveIf
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004807/// ::= .if{,eq,ge,gt,le,lt,ne} expression
4808bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004809 TheCondStack.push_back(TheCondState);
4810 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004811 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004812 eatToEndOfStatement();
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004813 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004814 int64_t ExprValue;
Nirav Davea645433c2016-07-18 15:24:03 +00004815 if (parseAbsoluteExpression(ExprValue) ||
4816 parseToken(AsmToken::EndOfStatement,
4817 "unexpected token in '.if' directive"))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004818 return true;
4819
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004820 switch (DirKind) {
4821 default:
4822 llvm_unreachable("unsupported directive");
4823 case DK_IF:
4824 case DK_IFNE:
4825 break;
4826 case DK_IFEQ:
4827 ExprValue = ExprValue == 0;
4828 break;
4829 case DK_IFGE:
4830 ExprValue = ExprValue >= 0;
4831 break;
4832 case DK_IFGT:
4833 ExprValue = ExprValue > 0;
4834 break;
4835 case DK_IFLE:
4836 ExprValue = ExprValue <= 0;
4837 break;
4838 case DK_IFLT:
4839 ExprValue = ExprValue < 0;
4840 break;
4841 }
4842
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004843 TheCondState.CondMet = ExprValue;
4844 TheCondState.Ignore = !TheCondState.CondMet;
4845 }
4846
4847 return false;
4848}
4849
Jim Grosbach4b905842013-09-20 23:08:21 +00004850/// parseDirectiveIfb
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004851/// ::= .ifb string
Jim Grosbach4b905842013-09-20 23:08:21 +00004852bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004853 TheCondStack.push_back(TheCondState);
4854 TheCondState.TheCond = AsmCond::IfCond;
4855
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004856 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004857 eatToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004858 } else {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004859 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004860
Nirav Davea645433c2016-07-18 15:24:03 +00004861 if (parseToken(AsmToken::EndOfStatement,
4862 "unexpected token in '.ifb' directive"))
4863 return true;
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004864
4865 TheCondState.CondMet = ExpectBlank == Str.empty();
4866 TheCondState.Ignore = !TheCondState.CondMet;
4867 }
4868
4869 return false;
4870}
4871
Jim Grosbach4b905842013-09-20 23:08:21 +00004872/// parseDirectiveIfc
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004873/// ::= .ifc string1, string2
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00004874/// ::= .ifnc string1, string2
Jim Grosbach4b905842013-09-20 23:08:21 +00004875bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004876 TheCondStack.push_back(TheCondState);
4877 TheCondState.TheCond = AsmCond::IfCond;
4878
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004879 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004880 eatToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004881 } else {
Jim Grosbach4b905842013-09-20 23:08:21 +00004882 StringRef Str1 = parseStringToComma();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004883
Nirav Davea645433c2016-07-18 15:24:03 +00004884 if (parseToken(AsmToken::Comma, "unexpected token in '.ifc' directive"))
4885 return true;
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004886
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004887 StringRef Str2 = parseStringToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004888
Nirav Davea645433c2016-07-18 15:24:03 +00004889 if (parseToken(AsmToken::EndOfStatement,
4890 "unexpected token in '.ifc' directive"))
4891 return true;
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004892
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00004893 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004894 TheCondState.Ignore = !TheCondState.CondMet;
4895 }
4896
4897 return false;
4898}
4899
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004900/// parseDirectiveIfeqs
4901/// ::= .ifeqs string1, string2
Sid Manning51c35602015-03-18 14:20:54 +00004902bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual) {
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004903 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00004904 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00004905 return TokError("expected string parameter for '.ifeqs' directive");
4906 return TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004907 }
4908
4909 StringRef String1 = getTok().getStringContents();
4910 Lex();
4911
4912 if (Lexer.isNot(AsmToken::Comma)) {
Sid Manning51c35602015-03-18 14:20:54 +00004913 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00004914 return TokError(
4915 "expected comma after first string for '.ifeqs' directive");
4916 return TokError("expected comma after first string for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004917 }
4918
4919 Lex();
4920
4921 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00004922 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00004923 return TokError("expected string parameter for '.ifeqs' directive");
4924 return TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004925 }
4926
4927 StringRef String2 = getTok().getStringContents();
4928 Lex();
4929
4930 TheCondStack.push_back(TheCondState);
4931 TheCondState.TheCond = AsmCond::IfCond;
Sid Manning51c35602015-03-18 14:20:54 +00004932 TheCondState.CondMet = ExpectEqual == (String1 == String2);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004933 TheCondState.Ignore = !TheCondState.CondMet;
4934
4935 return false;
4936}
4937
Jim Grosbach4b905842013-09-20 23:08:21 +00004938/// parseDirectiveIfdef
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004939/// ::= .ifdef symbol
Jim Grosbach4b905842013-09-20 23:08:21 +00004940bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004941 StringRef Name;
4942 TheCondStack.push_back(TheCondState);
4943 TheCondState.TheCond = AsmCond::IfCond;
4944
4945 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004946 eatToEndOfStatement();
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004947 } else {
Nirav Davea645433c2016-07-18 15:24:03 +00004948 if (check(parseIdentifier(Name), "expected identifier after '.ifdef'") ||
4949 parseToken(AsmToken::EndOfStatement, "unexpected token in '.ifdef'"))
4950 return true;
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004951
Jim Grosbach6f482002015-05-18 18:43:14 +00004952 MCSymbol *Sym = getContext().lookupSymbol(Name);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004953
4954 if (expect_defined)
Craig Topper353eda42014-04-24 06:44:33 +00004955 TheCondState.CondMet = (Sym && !Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004956 else
Craig Topper353eda42014-04-24 06:44:33 +00004957 TheCondState.CondMet = (!Sym || Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004958 TheCondState.Ignore = !TheCondState.CondMet;
4959 }
4960
4961 return false;
4962}
4963
Jim Grosbach4b905842013-09-20 23:08:21 +00004964/// parseDirectiveElseIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004965/// ::= .elseif expression
Jim Grosbach4b905842013-09-20 23:08:21 +00004966bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004967 if (TheCondState.TheCond != AsmCond::IfCond &&
4968 TheCondState.TheCond != AsmCond::ElseIfCond)
Nirav Dave2364748a2016-09-16 18:30:20 +00004969 return Error(DirectiveLoc, "Encountered a .elseif that doesn't follow an"
4970 " .if or an .elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004971 TheCondState.TheCond = AsmCond::ElseIfCond;
4972
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004973 bool LastIgnoreState = false;
4974 if (!TheCondStack.empty())
Craig Topper2172ad62013-04-22 04:24:02 +00004975 LastIgnoreState = TheCondStack.back().Ignore;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004976 if (LastIgnoreState || TheCondState.CondMet) {
4977 TheCondState.Ignore = true;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004978 eatToEndOfStatement();
Craig Topperf15655b2013-04-22 04:22:40 +00004979 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004980 int64_t ExprValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004981 if (parseAbsoluteExpression(ExprValue))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004982 return true;
4983
Nirav Dave1a9044b2016-10-24 14:35:29 +00004984 if (parseToken(AsmToken::EndOfStatement,
4985 "unexpected token in '.elseif' directive"))
4986 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00004987
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004988 TheCondState.CondMet = ExprValue;
4989 TheCondState.Ignore = !TheCondState.CondMet;
4990 }
4991
4992 return false;
4993}
4994
Jim Grosbach4b905842013-09-20 23:08:21 +00004995/// parseDirectiveElse
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004996/// ::= .else
Jim Grosbach4b905842013-09-20 23:08:21 +00004997bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00004998 if (parseToken(AsmToken::EndOfStatement,
4999 "unexpected token in '.else' directive"))
5000 return true;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005001
5002 if (TheCondState.TheCond != AsmCond::IfCond &&
5003 TheCondState.TheCond != AsmCond::ElseIfCond)
Nirav Dave2364748a2016-09-16 18:30:20 +00005004 return Error(DirectiveLoc, "Encountered a .else that doesn't follow "
5005 " an .if or an .elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005006 TheCondState.TheCond = AsmCond::ElseCond;
5007 bool LastIgnoreState = false;
5008 if (!TheCondStack.empty())
5009 LastIgnoreState = TheCondStack.back().Ignore;
5010 if (LastIgnoreState || TheCondState.CondMet)
5011 TheCondState.Ignore = true;
5012 else
5013 TheCondState.Ignore = false;
5014
5015 return false;
5016}
5017
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00005018/// parseDirectiveEnd
5019/// ::= .end
5020bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00005021 if (parseToken(AsmToken::EndOfStatement,
5022 "unexpected token in '.end' directive"))
5023 return true;
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00005024
5025 while (Lexer.isNot(AsmToken::Eof))
Nirav Dave1a9044b2016-10-24 14:35:29 +00005026 Lexer.Lex();
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00005027
5028 return false;
5029}
5030
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00005031/// parseDirectiveError
5032/// ::= .err
5033/// ::= .error [string]
5034bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
5035 if (!TheCondStack.empty()) {
5036 if (TheCondStack.back().Ignore) {
5037 eatToEndOfStatement();
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00005038 return false;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00005039 }
5040 }
5041
5042 if (!WithMessage)
5043 return Error(L, ".err encountered");
5044
5045 StringRef Message = ".error directive invoked in source file";
5046 if (Lexer.isNot(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00005047 if (Lexer.isNot(AsmToken::String))
5048 return TokError(".error argument must be a string");
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00005049
5050 Message = getTok().getStringContents();
5051 Lex();
5052 }
5053
Nirav Dave2364748a2016-09-16 18:30:20 +00005054 return Error(L, Message);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00005055}
5056
Nico Weber404012b2014-07-24 16:26:06 +00005057/// parseDirectiveWarning
5058/// ::= .warning [string]
5059bool AsmParser::parseDirectiveWarning(SMLoc L) {
5060 if (!TheCondStack.empty()) {
5061 if (TheCondStack.back().Ignore) {
5062 eatToEndOfStatement();
5063 return false;
5064 }
5065 }
5066
5067 StringRef Message = ".warning directive invoked in source file";
Nirav Dave1a9044b2016-10-24 14:35:29 +00005068
5069 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00005070 if (Lexer.isNot(AsmToken::String))
5071 return TokError(".warning argument must be a string");
Nico Weber404012b2014-07-24 16:26:06 +00005072
5073 Message = getTok().getStringContents();
5074 Lex();
Nirav Dave1a9044b2016-10-24 14:35:29 +00005075 if (parseToken(AsmToken::EndOfStatement,
5076 "expected end of statement in '.warning' directive"))
5077 return true;
Nico Weber404012b2014-07-24 16:26:06 +00005078 }
5079
Nirav Dave2364748a2016-09-16 18:30:20 +00005080 return Warning(L, Message);
Nico Weber404012b2014-07-24 16:26:06 +00005081}
5082
Jim Grosbach4b905842013-09-20 23:08:21 +00005083/// parseDirectiveEndIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005084/// ::= .endif
Jim Grosbach4b905842013-09-20 23:08:21 +00005085bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00005086 if (parseToken(AsmToken::EndOfStatement,
5087 "unexpected token in '.endif' directive"))
5088 return true;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005089
Jim Grosbach4b905842013-09-20 23:08:21 +00005090 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
Nirav Dave2364748a2016-09-16 18:30:20 +00005091 return Error(DirectiveLoc, "Encountered a .endif that doesn't follow "
5092 "an .if or .else");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005093 if (!TheCondStack.empty()) {
5094 TheCondState = TheCondStack.back();
5095 TheCondStack.pop_back();
5096 }
5097
5098 return false;
5099}
Daniel Dunbara4b069c2009-08-11 04:24:50 +00005100
Eli Bendersky17233942013-01-15 22:59:42 +00005101void AsmParser::initializeDirectiveKindMap() {
5102 DirectiveKindMap[".set"] = DK_SET;
5103 DirectiveKindMap[".equ"] = DK_EQU;
5104 DirectiveKindMap[".equiv"] = DK_EQUIV;
5105 DirectiveKindMap[".ascii"] = DK_ASCII;
5106 DirectiveKindMap[".asciz"] = DK_ASCIZ;
5107 DirectiveKindMap[".string"] = DK_STRING;
5108 DirectiveKindMap[".byte"] = DK_BYTE;
5109 DirectiveKindMap[".short"] = DK_SHORT;
5110 DirectiveKindMap[".value"] = DK_VALUE;
5111 DirectiveKindMap[".2byte"] = DK_2BYTE;
5112 DirectiveKindMap[".long"] = DK_LONG;
5113 DirectiveKindMap[".int"] = DK_INT;
5114 DirectiveKindMap[".4byte"] = DK_4BYTE;
5115 DirectiveKindMap[".quad"] = DK_QUAD;
5116 DirectiveKindMap[".8byte"] = DK_8BYTE;
David Woodhoused6de0d92014-02-01 16:20:59 +00005117 DirectiveKindMap[".octa"] = DK_OCTA;
Eli Bendersky17233942013-01-15 22:59:42 +00005118 DirectiveKindMap[".single"] = DK_SINGLE;
5119 DirectiveKindMap[".float"] = DK_FLOAT;
5120 DirectiveKindMap[".double"] = DK_DOUBLE;
5121 DirectiveKindMap[".align"] = DK_ALIGN;
5122 DirectiveKindMap[".align32"] = DK_ALIGN32;
5123 DirectiveKindMap[".balign"] = DK_BALIGN;
5124 DirectiveKindMap[".balignw"] = DK_BALIGNW;
5125 DirectiveKindMap[".balignl"] = DK_BALIGNL;
5126 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
5127 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
5128 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
5129 DirectiveKindMap[".org"] = DK_ORG;
5130 DirectiveKindMap[".fill"] = DK_FILL;
5131 DirectiveKindMap[".zero"] = DK_ZERO;
5132 DirectiveKindMap[".extern"] = DK_EXTERN;
5133 DirectiveKindMap[".globl"] = DK_GLOBL;
5134 DirectiveKindMap[".global"] = DK_GLOBAL;
Eli Bendersky17233942013-01-15 22:59:42 +00005135 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
5136 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
5137 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
5138 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
5139 DirectiveKindMap[".reference"] = DK_REFERENCE;
5140 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
5141 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
5142 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
5143 DirectiveKindMap[".comm"] = DK_COMM;
5144 DirectiveKindMap[".common"] = DK_COMMON;
5145 DirectiveKindMap[".lcomm"] = DK_LCOMM;
5146 DirectiveKindMap[".abort"] = DK_ABORT;
5147 DirectiveKindMap[".include"] = DK_INCLUDE;
5148 DirectiveKindMap[".incbin"] = DK_INCBIN;
5149 DirectiveKindMap[".code16"] = DK_CODE16;
5150 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
5151 DirectiveKindMap[".rept"] = DK_REPT;
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00005152 DirectiveKindMap[".rep"] = DK_REPT;
Eli Bendersky17233942013-01-15 22:59:42 +00005153 DirectiveKindMap[".irp"] = DK_IRP;
5154 DirectiveKindMap[".irpc"] = DK_IRPC;
5155 DirectiveKindMap[".endr"] = DK_ENDR;
5156 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
5157 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
5158 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
5159 DirectiveKindMap[".if"] = DK_IF;
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00005160 DirectiveKindMap[".ifeq"] = DK_IFEQ;
5161 DirectiveKindMap[".ifge"] = DK_IFGE;
5162 DirectiveKindMap[".ifgt"] = DK_IFGT;
5163 DirectiveKindMap[".ifle"] = DK_IFLE;
5164 DirectiveKindMap[".iflt"] = DK_IFLT;
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00005165 DirectiveKindMap[".ifne"] = DK_IFNE;
Eli Bendersky17233942013-01-15 22:59:42 +00005166 DirectiveKindMap[".ifb"] = DK_IFB;
5167 DirectiveKindMap[".ifnb"] = DK_IFNB;
5168 DirectiveKindMap[".ifc"] = DK_IFC;
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00005169 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
Eli Bendersky17233942013-01-15 22:59:42 +00005170 DirectiveKindMap[".ifnc"] = DK_IFNC;
Sid Manning51c35602015-03-18 14:20:54 +00005171 DirectiveKindMap[".ifnes"] = DK_IFNES;
Eli Bendersky17233942013-01-15 22:59:42 +00005172 DirectiveKindMap[".ifdef"] = DK_IFDEF;
5173 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
5174 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
5175 DirectiveKindMap[".elseif"] = DK_ELSEIF;
5176 DirectiveKindMap[".else"] = DK_ELSE;
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00005177 DirectiveKindMap[".end"] = DK_END;
Eli Bendersky17233942013-01-15 22:59:42 +00005178 DirectiveKindMap[".endif"] = DK_ENDIF;
5179 DirectiveKindMap[".skip"] = DK_SKIP;
5180 DirectiveKindMap[".space"] = DK_SPACE;
5181 DirectiveKindMap[".file"] = DK_FILE;
5182 DirectiveKindMap[".line"] = DK_LINE;
5183 DirectiveKindMap[".loc"] = DK_LOC;
5184 DirectiveKindMap[".stabs"] = DK_STABS;
Reid Kleckner2214ed82016-01-29 00:49:42 +00005185 DirectiveKindMap[".cv_file"] = DK_CV_FILE;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00005186 DirectiveKindMap[".cv_func_id"] = DK_CV_FUNC_ID;
Reid Kleckner2214ed82016-01-29 00:49:42 +00005187 DirectiveKindMap[".cv_loc"] = DK_CV_LOC;
5188 DirectiveKindMap[".cv_linetable"] = DK_CV_LINETABLE;
David Majnemer6fcbd7e2016-01-29 19:24:12 +00005189 DirectiveKindMap[".cv_inline_linetable"] = DK_CV_INLINE_LINETABLE;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00005190 DirectiveKindMap[".cv_inline_site_id"] = DK_CV_INLINE_SITE_ID;
David Majnemer408b5e62016-02-05 01:55:49 +00005191 DirectiveKindMap[".cv_def_range"] = DK_CV_DEF_RANGE;
Reid Kleckner2214ed82016-01-29 00:49:42 +00005192 DirectiveKindMap[".cv_stringtable"] = DK_CV_STRINGTABLE;
5193 DirectiveKindMap[".cv_filechecksums"] = DK_CV_FILECHECKSUMS;
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00005194 DirectiveKindMap[".cv_filechecksumoffset"] = DK_CV_FILECHECKSUM_OFFSET;
Reid Kleckner9cdd4df2017-10-11 21:24:33 +00005195 DirectiveKindMap[".cv_fpo_data"] = DK_CV_FPO_DATA;
Eli Bendersky17233942013-01-15 22:59:42 +00005196 DirectiveKindMap[".sleb128"] = DK_SLEB128;
5197 DirectiveKindMap[".uleb128"] = DK_ULEB128;
5198 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
5199 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
5200 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
5201 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
5202 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
5203 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
5204 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
5205 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
5206 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
5207 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
5208 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
5209 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
5210 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
5211 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
5212 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
5213 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +00005214 DirectiveKindMap[".cfi_return_column"] = DK_CFI_RETURN_COLUMN;
Eli Bendersky17233942013-01-15 22:59:42 +00005215 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
5216 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
5217 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00005218 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
Eli Bendersky17233942013-01-15 22:59:42 +00005219 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
5220 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
5221 DirectiveKindMap[".macro"] = DK_MACRO;
Nico Weber155dccd12014-07-24 17:08:39 +00005222 DirectiveKindMap[".exitm"] = DK_EXITM;
Eli Bendersky17233942013-01-15 22:59:42 +00005223 DirectiveKindMap[".endm"] = DK_ENDM;
5224 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
5225 DirectiveKindMap[".purgem"] = DK_PURGEM;
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00005226 DirectiveKindMap[".err"] = DK_ERR;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00005227 DirectiveKindMap[".error"] = DK_ERROR;
Nico Weber404012b2014-07-24 16:26:06 +00005228 DirectiveKindMap[".warning"] = DK_WARNING;
Michael Zuckerman56704612017-05-01 13:20:12 +00005229 DirectiveKindMap[".altmacro"] = DK_ALTMACRO;
5230 DirectiveKindMap[".noaltmacro"] = DK_NOALTMACRO;
Daniel Sanders9f6ad492015-11-12 13:33:00 +00005231 DirectiveKindMap[".reloc"] = DK_RELOC;
Petr Hosek731bb9c2016-08-23 21:34:53 +00005232 DirectiveKindMap[".dc"] = DK_DC;
5233 DirectiveKindMap[".dc.a"] = DK_DC_A;
5234 DirectiveKindMap[".dc.b"] = DK_DC_B;
5235 DirectiveKindMap[".dc.d"] = DK_DC_D;
5236 DirectiveKindMap[".dc.l"] = DK_DC_L;
5237 DirectiveKindMap[".dc.s"] = DK_DC_S;
5238 DirectiveKindMap[".dc.w"] = DK_DC_W;
5239 DirectiveKindMap[".dc.x"] = DK_DC_X;
Petr Hosek4cb08ce2016-09-23 19:25:15 +00005240 DirectiveKindMap[".dcb"] = DK_DCB;
5241 DirectiveKindMap[".dcb.b"] = DK_DCB_B;
5242 DirectiveKindMap[".dcb.d"] = DK_DCB_D;
5243 DirectiveKindMap[".dcb.l"] = DK_DCB_L;
5244 DirectiveKindMap[".dcb.s"] = DK_DCB_S;
5245 DirectiveKindMap[".dcb.w"] = DK_DCB_W;
5246 DirectiveKindMap[".dcb.x"] = DK_DCB_X;
Petr Hosek85b2f672016-09-23 21:53:36 +00005247 DirectiveKindMap[".ds"] = DK_DS;
5248 DirectiveKindMap[".ds.b"] = DK_DS_B;
5249 DirectiveKindMap[".ds.d"] = DK_DS_D;
5250 DirectiveKindMap[".ds.l"] = DK_DS_L;
5251 DirectiveKindMap[".ds.p"] = DK_DS_P;
5252 DirectiveKindMap[".ds.s"] = DK_DS_S;
5253 DirectiveKindMap[".ds.w"] = DK_DS_W;
5254 DirectiveKindMap[".ds.x"] = DK_DS_X;
Coby Tayree01e53202017-10-02 14:36:31 +00005255 DirectiveKindMap[".print"] = DK_PRINT;
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00005256}
5257
Jim Grosbach4b905842013-09-20 23:08:21 +00005258MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005259 AsmToken EndToken, StartToken = getTok();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005260
Rafael Espindola34b9c512012-06-03 23:57:14 +00005261 unsigned NestLevel = 0;
Eugene Zelenko33d7b762016-08-23 17:14:32 +00005262 while (true) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005263 // Check whether we have reached the end of the file.
Rafael Espindola34b9c512012-06-03 23:57:14 +00005264 if (getLexer().is(AsmToken::Eof)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00005265 printError(DirectiveLoc, "no matching '.endr' in definition");
Craig Topper353eda42014-04-24 06:44:33 +00005266 return nullptr;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005267 }
5268
Rafael Espindola34b9c512012-06-03 23:57:14 +00005269 if (Lexer.is(AsmToken::Identifier) &&
Nikolay Haustov95b4fcd2016-03-01 08:18:28 +00005270 (getTok().getIdentifier() == ".rept" ||
5271 getTok().getIdentifier() == ".irp" ||
5272 getTok().getIdentifier() == ".irpc")) {
Rafael Espindola34b9c512012-06-03 23:57:14 +00005273 ++NestLevel;
5274 }
5275
5276 // Otherwise, check whether we have reached the .endr.
Jim Grosbach4b905842013-09-20 23:08:21 +00005277 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
Rafael Espindola34b9c512012-06-03 23:57:14 +00005278 if (NestLevel == 0) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005279 EndToken = getTok();
5280 Lex();
Rafael Espindola34b9c512012-06-03 23:57:14 +00005281 if (Lexer.isNot(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00005282 printError(getTok().getLoc(),
5283 "unexpected token in '.endr' directive");
Craig Topper353eda42014-04-24 06:44:33 +00005284 return nullptr;
Rafael Espindola34b9c512012-06-03 23:57:14 +00005285 }
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005286 break;
5287 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00005288 --NestLevel;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005289 }
5290
Rafael Espindola34b9c512012-06-03 23:57:14 +00005291 // Otherwise, scan till the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005292 eatToEndOfStatement();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005293 }
5294
5295 const char *BodyStart = StartToken.getLoc().getPointer();
5296 const char *BodyEnd = EndToken.getLoc().getPointer();
5297 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
5298
Rafael Espindola34b9c512012-06-03 23:57:14 +00005299 // We Are Anonymous.
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00005300 MacroLikeBodies.emplace_back(StringRef(), Body, MCAsmMacroParameters());
Benjamin Kramer1df3a1f2013-08-04 09:06:29 +00005301 return &MacroLikeBodies.back();
Rafael Espindola34b9c512012-06-03 23:57:14 +00005302}
5303
Jim Grosbach4b905842013-09-20 23:08:21 +00005304void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +00005305 raw_svector_ostream &OS) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005306 OS << ".endr\n";
5307
Rafael Espindola3560ff22014-08-27 20:03:13 +00005308 std::unique_ptr<MemoryBuffer> Instantiation =
5309 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005310
Rafael Espindola34b9c512012-06-03 23:57:14 +00005311 // Create the macro instantiation object and add to the current macro
5312 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00005313 MacroInstantiation *MI = new MacroInstantiation(
5314 DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Rafael Espindola34b9c512012-06-03 23:57:14 +00005315 ActiveMacros.push_back(MI);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005316
Rafael Espindola34b9c512012-06-03 23:57:14 +00005317 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00005318 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00005319 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Rafael Espindola34b9c512012-06-03 23:57:14 +00005320 Lex();
5321}
5322
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00005323/// parseDirectiveRept
5324/// ::= .rep | .rept count
5325bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00005326 const MCExpr *CountExpr;
5327 SMLoc CountLoc = getTok().getLoc();
5328 if (parseExpression(CountExpr))
5329 return true;
5330
Rafael Espindola34b9c512012-06-03 23:57:14 +00005331 int64_t Count;
Jim Grosbach13760bd2015-05-30 01:25:56 +00005332 if (!CountExpr->evaluateAsAbsolute(Count)) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00005333 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
5334 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00005335
Nirav Davea645433c2016-07-18 15:24:03 +00005336 if (check(Count < 0, CountLoc, "Count is negative") ||
5337 parseToken(AsmToken::EndOfStatement,
5338 "unexpected token in '" + Dir + "' directive"))
5339 return true;
Rafael Espindola34b9c512012-06-03 23:57:14 +00005340
5341 // Lex the rept definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005342 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola34b9c512012-06-03 23:57:14 +00005343 if (!M)
5344 return true;
5345
5346 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5347 // to hold the macro body with substitutions.
5348 SmallString<256> Buf;
Rafael Espindola34b9c512012-06-03 23:57:14 +00005349 raw_svector_ostream OS(Buf);
5350 while (Count--) {
Toma Tabacu217116e2015-04-27 10:50:29 +00005351 // Note that the AtPseudoVariable is disabled for instantiations of .rep(t).
5352 if (expandMacro(OS, M->Body, None, None, false, getTok().getLoc()))
Rafael Espindola34b9c512012-06-03 23:57:14 +00005353 return true;
5354 }
Jim Grosbach4b905842013-09-20 23:08:21 +00005355 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005356
5357 return false;
5358}
5359
Jim Grosbach4b905842013-09-20 23:08:21 +00005360/// parseDirectiveIrp
Rafael Espindola768b41c2012-06-15 14:02:34 +00005361/// ::= .irp symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00005362bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00005363 MCAsmMacroParameter Parameter;
Eli Bendersky38274122013-01-14 23:22:36 +00005364 MCAsmMacroArguments A;
Nirav Davea645433c2016-07-18 15:24:03 +00005365 if (check(parseIdentifier(Parameter.Name),
5366 "expected identifier in '.irp' directive") ||
5367 parseToken(AsmToken::Comma, "expected comma in '.irp' directive") ||
5368 parseMacroArguments(nullptr, A) ||
5369 parseToken(AsmToken::EndOfStatement, "expected End of Statement"))
Rafael Espindola768b41c2012-06-15 14:02:34 +00005370 return true;
5371
Rafael Espindola768b41c2012-06-15 14:02:34 +00005372 // Lex the irp definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005373 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola768b41c2012-06-15 14:02:34 +00005374 if (!M)
5375 return true;
5376
5377 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5378 // to hold the macro body with substitutions.
5379 SmallString<256> Buf;
5380 raw_svector_ostream OS(Buf);
5381
Craig Topper84008482015-10-10 05:38:14 +00005382 for (const MCAsmMacroArgument &Arg : A) {
Toma Tabacu217116e2015-04-27 10:50:29 +00005383 // Note that the AtPseudoVariable is enabled for instantiations of .irp.
5384 // This is undocumented, but GAS seems to support it.
Craig Topper84008482015-10-10 05:38:14 +00005385 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindola768b41c2012-06-15 14:02:34 +00005386 return true;
5387 }
5388
Jim Grosbach4b905842013-09-20 23:08:21 +00005389 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola768b41c2012-06-15 14:02:34 +00005390
5391 return false;
5392}
5393
Jim Grosbach4b905842013-09-20 23:08:21 +00005394/// parseDirectiveIrpc
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005395/// ::= .irpc symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00005396bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00005397 MCAsmMacroParameter Parameter;
Eli Bendersky38274122013-01-14 23:22:36 +00005398 MCAsmMacroArguments A;
Nirav Davea645433c2016-07-18 15:24:03 +00005399
5400 if (check(parseIdentifier(Parameter.Name),
5401 "expected identifier in '.irpc' directive") ||
5402 parseToken(AsmToken::Comma, "expected comma in '.irpc' directive") ||
5403 parseMacroArguments(nullptr, A))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005404 return true;
5405
5406 if (A.size() != 1 || A.front().size() != 1)
5407 return TokError("unexpected token in '.irpc' directive");
5408
5409 // Eat the end of statement.
Nirav Davea645433c2016-07-18 15:24:03 +00005410 if (parseToken(AsmToken::EndOfStatement, "expected end of statement"))
5411 return true;
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005412
5413 // Lex the irpc definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005414 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005415 if (!M)
5416 return true;
5417
5418 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5419 // to hold the macro body with substitutions.
5420 SmallString<256> Buf;
5421 raw_svector_ostream OS(Buf);
5422
5423 StringRef Values = A.front().front().getString();
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00005424 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
Eli Benderskya7b905e2013-01-14 19:00:26 +00005425 MCAsmMacroArgument Arg;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00005426 Arg.emplace_back(AsmToken::Identifier, Values.slice(I, I + 1));
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005427
Toma Tabacu217116e2015-04-27 10:50:29 +00005428 // Note that the AtPseudoVariable is enabled for instantiations of .irpc.
5429 // This is undocumented, but GAS seems to support it.
5430 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005431 return true;
5432 }
5433
Jim Grosbach4b905842013-09-20 23:08:21 +00005434 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005435
5436 return false;
5437}
5438
Jim Grosbach4b905842013-09-20 23:08:21 +00005439bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
Rafael Espindola34b9c512012-06-03 23:57:14 +00005440 if (ActiveMacros.empty())
Preston Gurdeb3ebf12012-09-19 20:23:43 +00005441 return TokError("unmatched '.endr' directive");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005442
5443 // The only .repl that should get here are the ones created by
Jim Grosbach4b905842013-09-20 23:08:21 +00005444 // instantiateMacroLikeBody.
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005445 assert(getLexer().is(AsmToken::EndOfStatement));
5446
Jim Grosbach4b905842013-09-20 23:08:21 +00005447 handleMacroExit();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005448 return false;
5449}
Rafael Espindola12d73d12010-09-11 16:45:15 +00005450
Jim Grosbach4b905842013-09-20 23:08:21 +00005451bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
Benjamin Kramer1a136112013-02-15 20:37:21 +00005452 size_t Len) {
Eli Friedman0f4871d2012-10-22 23:58:19 +00005453 const MCExpr *Value;
5454 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005455 if (parseExpression(Value))
Eli Friedman0f4871d2012-10-22 23:58:19 +00005456 return true;
5457 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5458 if (!MCE)
5459 return Error(ExprLoc, "unexpected expression in _emit");
5460 uint64_t IntValue = MCE->getValue();
Craig Topper55b1f292015-10-10 20:17:07 +00005461 if (!isUInt<8>(IntValue) && !isInt<8>(IntValue))
Eli Friedman0f4871d2012-10-22 23:58:19 +00005462 return Error(ExprLoc, "literal value out of range for directive");
5463
Craig Topper7d5b2312015-10-10 05:25:02 +00005464 Info.AsmRewrites->emplace_back(AOK_Emit, IDLoc, Len);
Chad Rosierc7f552c2013-02-12 21:33:51 +00005465 return false;
5466}
5467
Jim Grosbach4b905842013-09-20 23:08:21 +00005468bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
Chad Rosierc7f552c2013-02-12 21:33:51 +00005469 const MCExpr *Value;
5470 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005471 if (parseExpression(Value))
Chad Rosierc7f552c2013-02-12 21:33:51 +00005472 return true;
5473 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5474 if (!MCE)
5475 return Error(ExprLoc, "unexpected expression in align");
5476 uint64_t IntValue = MCE->getValue();
5477 if (!isPowerOf2_64(IntValue))
5478 return Error(ExprLoc, "literal value not a power of two greater then zero");
5479
Craig Topper7d5b2312015-10-10 05:25:02 +00005480 Info.AsmRewrites->emplace_back(AOK_Align, IDLoc, 5, Log2_64(IntValue));
Eli Friedman0f4871d2012-10-22 23:58:19 +00005481 return false;
5482}
5483
Coby Tayree01e53202017-10-02 14:36:31 +00005484bool AsmParser::parseDirectivePrint(SMLoc DirectiveLoc) {
5485 const AsmToken StrTok = getTok();
5486 Lex();
5487 if (StrTok.isNot(AsmToken::String) || StrTok.getString().front() != '"')
5488 return Error(DirectiveLoc, "expected double quoted string after .print");
5489 if (parseToken(AsmToken::EndOfStatement, "expected end of statement"))
5490 return true;
5491 llvm::outs() << StrTok.getStringContents() << '\n';
5492 return false;
5493}
5494
Chad Rosierf43fcf52013-02-13 21:27:17 +00005495// We are comparing pointers, but the pointers are relative to a single string.
5496// Thus, this should always be deterministic.
Benjamin Kramer8817cca2013-09-22 14:09:50 +00005497static int rewritesSort(const AsmRewrite *AsmRewriteA,
5498 const AsmRewrite *AsmRewriteB) {
Chad Rosiereb5c1682013-02-13 18:38:58 +00005499 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
5500 return -1;
5501 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
5502 return 1;
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005503
Chad Rosierfce4fab2013-04-08 17:43:47 +00005504 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
5505 // rewrite to the same location. Make sure the SizeDirective rewrite is
5506 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
5507 // ensures the sort algorithm is stable.
Jim Grosbach4b905842013-09-20 23:08:21 +00005508 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
5509 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005510 return -1;
Chad Rosierfce4fab2013-04-08 17:43:47 +00005511
Jim Grosbach4b905842013-09-20 23:08:21 +00005512 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
5513 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005514 return 1;
Jim Grosbach4b905842013-09-20 23:08:21 +00005515 llvm_unreachable("Unstable rewrite sort.");
Chad Rosierb2144ce2013-02-13 01:03:13 +00005516}
5517
Jim Grosbach4b905842013-09-20 23:08:21 +00005518bool AsmParser::parseMSInlineAsm(
5519 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00005520 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool>> &OpDecls,
Jim Grosbach4b905842013-09-20 23:08:21 +00005521 SmallVectorImpl<std::string> &Constraints,
5522 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
5523 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
Chad Rosier37e755c2012-10-23 17:43:43 +00005524 SmallVector<void *, 4> InputDecls;
5525 SmallVector<void *, 4> OutputDecls;
Chad Rosiera4bc9432013-01-10 22:10:27 +00005526 SmallVector<bool, 4> InputDeclsAddressOf;
5527 SmallVector<bool, 4> OutputDeclsAddressOf;
Chad Rosier8bce6642012-10-18 15:49:34 +00005528 SmallVector<std::string, 4> InputConstraints;
5529 SmallVector<std::string, 4> OutputConstraints;
Benjamin Kramer1a136112013-02-15 20:37:21 +00005530 SmallVector<unsigned, 4> ClobberRegs;
Chad Rosier8bce6642012-10-18 15:49:34 +00005531
Benjamin Kramer1a136112013-02-15 20:37:21 +00005532 SmallVector<AsmRewrite, 4> AsmStrRewrites;
Chad Rosier8bce6642012-10-18 15:49:34 +00005533
5534 // Prime the lexer.
5535 Lex();
5536
5537 // While we have input, parse each statement.
5538 unsigned InputIdx = 0;
5539 unsigned OutputIdx = 0;
5540 while (getLexer().isNot(AsmToken::Eof)) {
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00005541 // Parse curly braces marking block start/end
5542 if (parseCurlyBlockScope(AsmStrRewrites))
5543 continue;
5544
Eli Friedman0f4871d2012-10-22 23:58:19 +00005545 ParseStatementInfo Info(&AsmStrRewrites);
Nirav Dave2364748a2016-09-16 18:30:20 +00005546 bool StatementErr = parseStatement(Info, &SI);
Nirav Dave9fa8af22016-09-13 13:55:06 +00005547
Nirav Dave2364748a2016-09-16 18:30:20 +00005548 if (StatementErr || Info.ParseError) {
5549 // Emit pending errors if any exist.
5550 printPendingErrors();
Nico Webere204c482016-09-13 18:17:00 +00005551 return true;
Nirav Dave2364748a2016-09-16 18:30:20 +00005552 }
5553
5554 // No pending error should exist here.
5555 assert(!hasPendingError() && "unexpected error from parseStatement");
Chad Rosier149e8e02012-12-12 22:45:52 +00005556
Benjamin Kramer1a136112013-02-15 20:37:21 +00005557 if (Info.Opcode == ~0U)
5558 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00005559
Benjamin Kramer1a136112013-02-15 20:37:21 +00005560 const MCInstrDesc &Desc = MII->get(Info.Opcode);
Chad Rosier8bce6642012-10-18 15:49:34 +00005561
Benjamin Kramer1a136112013-02-15 20:37:21 +00005562 // Build the list of clobbers, outputs and inputs.
5563 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
David Blaikie960ea3f2014-06-08 16:18:35 +00005564 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005565
Benjamin Kramer1a136112013-02-15 20:37:21 +00005566 // Immediate.
David Blaikie960ea3f2014-06-08 16:18:35 +00005567 if (Operand.isImm())
Benjamin Kramer1a136112013-02-15 20:37:21 +00005568 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00005569
Benjamin Kramer1a136112013-02-15 20:37:21 +00005570 // Register operand.
Nico Weber42f79db2014-07-17 20:24:55 +00005571 if (Operand.isReg() && !Operand.needAddressOf() &&
5572 !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
Benjamin Kramer1a136112013-02-15 20:37:21 +00005573 unsigned NumDefs = Desc.getNumDefs();
5574 // Clobber.
David Blaikie960ea3f2014-06-08 16:18:35 +00005575 if (NumDefs && Operand.getMCOperandNum() < NumDefs)
5576 ClobberRegs.push_back(Operand.getReg());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005577 continue;
5578 }
5579
5580 // Expr/Input or Output.
David Blaikie960ea3f2014-06-08 16:18:35 +00005581 StringRef SymName = Operand.getSymName();
Chad Rosiere81309b2013-04-09 17:53:49 +00005582 if (SymName.empty())
5583 continue;
5584
David Blaikie960ea3f2014-06-08 16:18:35 +00005585 void *OpDecl = Operand.getOpDecl();
Benjamin Kramer1a136112013-02-15 20:37:21 +00005586 if (!OpDecl)
5587 continue;
5588
5589 bool isOutput = (i == 1) && Desc.mayStore();
Chad Rosiere81309b2013-04-09 17:53:49 +00005590 SMLoc Start = SMLoc::getFromPointer(SymName.data());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005591 if (isOutput) {
5592 ++InputIdx;
5593 OutputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00005594 OutputDeclsAddressOf.push_back(Operand.needAddressOf());
Yaron Keren075759a2015-03-30 15:42:36 +00005595 OutputConstraints.push_back(("=" + Operand.getConstraint()).str());
Craig Topper7d5b2312015-10-10 05:25:02 +00005596 AsmStrRewrites.emplace_back(AOK_Output, Start, SymName.size());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005597 } else {
5598 InputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00005599 InputDeclsAddressOf.push_back(Operand.needAddressOf());
5600 InputConstraints.push_back(Operand.getConstraint().str());
Craig Topper7d5b2312015-10-10 05:25:02 +00005601 AsmStrRewrites.emplace_back(AOK_Input, Start, SymName.size());
Chad Rosier8bce6642012-10-18 15:49:34 +00005602 }
Chad Rosier8bce6642012-10-18 15:49:34 +00005603 }
Reid Kleckneree088972013-12-10 18:27:32 +00005604
5605 // Consider implicit defs to be clobbers. Think of cpuid and push.
Craig Toppere5e035a32015-12-05 07:13:35 +00005606 ArrayRef<MCPhysReg> ImpDefs(Desc.getImplicitDefs(),
5607 Desc.getNumImplicitDefs());
David Majnemer8114c1a2014-06-23 02:17:16 +00005608 ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end());
Chad Rosier8bce6642012-10-18 15:49:34 +00005609 }
5610
5611 // Set the number of Outputs and Inputs.
Chad Rosierf641baa2012-10-18 19:39:30 +00005612 NumOutputs = OutputDecls.size();
5613 NumInputs = InputDecls.size();
Chad Rosier8bce6642012-10-18 15:49:34 +00005614
5615 // Set the unique clobbers.
Benjamin Kramer1a136112013-02-15 20:37:21 +00005616 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
5617 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
5618 ClobberRegs.end());
5619 Clobbers.assign(ClobberRegs.size(), std::string());
5620 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
5621 raw_string_ostream OS(Clobbers[I]);
5622 IP->printRegName(OS, ClobberRegs[I]);
5623 }
Chad Rosier8bce6642012-10-18 15:49:34 +00005624
5625 // Merge the various outputs and inputs. Output are expected first.
5626 if (NumOutputs || NumInputs) {
5627 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierf641baa2012-10-18 19:39:30 +00005628 OpDecls.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00005629 Constraints.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00005630 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00005631 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00005632 Constraints[i] = OutputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005633 }
5634 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00005635 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00005636 Constraints[j] = InputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005637 }
5638 }
5639
5640 // Build the IR assembly string.
Alp Tokere69170a2014-06-26 22:52:05 +00005641 std::string AsmStringIR;
5642 raw_string_ostream OS(AsmStringIR);
Alp Tokera55b95b2014-07-06 10:33:31 +00005643 StringRef ASMString =
5644 SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
5645 const char *AsmStart = ASMString.begin();
5646 const char *AsmEnd = ASMString.end();
Jim Grosbach4b905842013-09-20 23:08:21 +00005647 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
David Majnemer8114c1a2014-06-23 02:17:16 +00005648 for (const AsmRewrite &AR : AsmStrRewrites) {
5649 AsmRewriteKind Kind = AR.Kind;
Chad Rosierff10ed12013-04-12 16:26:42 +00005650
David Majnemer8114c1a2014-06-23 02:17:16 +00005651 const char *Loc = AR.Loc.getPointer();
Chad Rosier17d37992013-03-19 21:12:14 +00005652 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
Chad Rosier0f48c552012-10-19 20:57:14 +00005653
Chad Rosier120eefd2013-03-19 17:32:17 +00005654 // Emit everything up to the immediate/expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00005655 if (unsigned Len = Loc - AsmStart)
Chad Rosier17d37992013-03-19 21:12:14 +00005656 OS << StringRef(AsmStart, Len);
Chad Rosier0f48c552012-10-19 20:57:14 +00005657
Chad Rosier37e755c2012-10-23 17:43:43 +00005658 // Skip the original expression.
5659 if (Kind == AOK_Skip) {
David Majnemer8114c1a2014-06-23 02:17:16 +00005660 AsmStart = Loc + AR.Len;
Chad Rosier37e755c2012-10-23 17:43:43 +00005661 continue;
5662 }
5663
Chad Rosierff10ed12013-04-12 16:26:42 +00005664 unsigned AdditionalSkip = 0;
Chad Rosier8bce6642012-10-18 15:49:34 +00005665 // Rewrite expressions in $N notation.
Chad Rosier0f48c552012-10-19 20:57:14 +00005666 switch (Kind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00005667 default:
5668 break;
Coby Tayreed8912892017-08-24 08:46:25 +00005669 case AOK_IntelExpr:
5670 assert(AR.IntelExp.isValid() && "cannot write invalid intel expression");
5671 if (AR.IntelExp.NeedBracs)
5672 OS << "[";
5673 if (AR.IntelExp.hasBaseReg())
5674 OS << AR.IntelExp.BaseReg;
5675 if (AR.IntelExp.hasIndexReg())
5676 OS << (AR.IntelExp.hasBaseReg() ? " + " : "")
5677 << AR.IntelExp.IndexReg;
5678 if (AR.IntelExp.Scale > 1)
5679 OS << " * $$" << AR.IntelExp.Scale;
5680 if (AR.IntelExp.Imm || !AR.IntelExp.hasRegs())
5681 OS << (AR.IntelExp.hasRegs() ? " + $$" : "$$") << AR.IntelExp.Imm;
5682 if (AR.IntelExp.NeedBracs)
5683 OS << "]";
Chad Rosier8bce6642012-10-18 15:49:34 +00005684 break;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005685 case AOK_Label:
Matt Arsenault4e273432014-12-04 00:06:57 +00005686 OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005687 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005688 case AOK_Input:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005689 OS << '$' << InputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00005690 break;
5691 case AOK_Output:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005692 OS << '$' << OutputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00005693 break;
Chad Rosier0f48c552012-10-19 20:57:14 +00005694 case AOK_SizeDirective:
David Majnemer8114c1a2014-06-23 02:17:16 +00005695 switch (AR.Val) {
Chad Rosier0f48c552012-10-19 20:57:14 +00005696 default: break;
5697 case 8: OS << "byte ptr "; break;
5698 case 16: OS << "word ptr "; break;
5699 case 32: OS << "dword ptr "; break;
5700 case 64: OS << "qword ptr "; break;
5701 case 80: OS << "xword ptr "; break;
5702 case 128: OS << "xmmword ptr "; break;
5703 case 256: OS << "ymmword ptr "; break;
5704 }
Eli Friedman0f4871d2012-10-22 23:58:19 +00005705 break;
5706 case AOK_Emit:
5707 OS << ".byte";
5708 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00005709 case AOK_Align: {
Reid Klecknerfb1c1c72015-10-27 17:32:48 +00005710 // MS alignment directives are measured in bytes. If the native assembler
5711 // measures alignment in bytes, we can pass it straight through.
5712 OS << ".align";
5713 if (getContext().getAsmInfo()->getAlignmentIsInBytes())
5714 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00005715
Reid Klecknerfb1c1c72015-10-27 17:32:48 +00005716 // Alignment is in log2 form, so print that instead and skip the original
5717 // immediate.
5718 unsigned Val = AR.Val;
5719 OS << ' ' << Val;
Benjamin Kramer1a136112013-02-15 20:37:21 +00005720 assert(Val < 10 && "Expected alignment less then 2^10.");
Chad Rosierc7f552c2013-02-12 21:33:51 +00005721 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
5722 break;
5723 }
Michael Zuckerman02ecd432015-12-13 17:07:23 +00005724 case AOK_EVEN:
5725 OS << ".even";
5726 break;
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00005727 case AOK_EndOfStatement:
5728 OS << "\n\t";
5729 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005730 }
Chad Rosier0f48c552012-10-19 20:57:14 +00005731
Chad Rosier8bce6642012-10-18 15:49:34 +00005732 // Skip the original expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00005733 AsmStart = Loc + AR.Len + AdditionalSkip;
Chad Rosier8bce6642012-10-18 15:49:34 +00005734 }
5735
5736 // Emit the remainder of the asm string.
Chad Rosier17d37992013-03-19 21:12:14 +00005737 if (AsmStart != AsmEnd)
5738 OS << StringRef(AsmStart, AsmEnd - AsmStart);
Chad Rosier8bce6642012-10-18 15:49:34 +00005739
5740 AsmString = OS.str();
5741 return false;
5742}
5743
Pete Cooper80d21cb2015-06-22 19:35:57 +00005744namespace llvm {
5745namespace MCParserUtils {
5746
5747/// Returns whether the given symbol is used anywhere in the given expression,
5748/// or subexpressions.
5749static bool isSymbolUsedInExpression(const MCSymbol *Sym, const MCExpr *Value) {
5750 switch (Value->getKind()) {
5751 case MCExpr::Binary: {
5752 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
5753 return isSymbolUsedInExpression(Sym, BE->getLHS()) ||
5754 isSymbolUsedInExpression(Sym, BE->getRHS());
5755 }
5756 case MCExpr::Target:
5757 case MCExpr::Constant:
5758 return false;
5759 case MCExpr::SymbolRef: {
5760 const MCSymbol &S =
5761 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
5762 if (S.isVariable())
5763 return isSymbolUsedInExpression(Sym, S.getVariableValue());
5764 return &S == Sym;
5765 }
5766 case MCExpr::Unary:
5767 return isSymbolUsedInExpression(
5768 Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
5769 }
5770
5771 llvm_unreachable("Unknown expr kind!");
5772}
5773
5774bool parseAssignmentExpression(StringRef Name, bool allow_redef,
5775 MCAsmParser &Parser, MCSymbol *&Sym,
5776 const MCExpr *&Value) {
Pete Cooper80d21cb2015-06-22 19:35:57 +00005777
5778 // FIXME: Use better location, we should use proper tokens.
Nirav Davefd910412016-06-17 16:06:17 +00005779 SMLoc EqualLoc = Parser.getTok().getLoc();
Pete Cooper80d21cb2015-06-22 19:35:57 +00005780
5781 if (Parser.parseExpression(Value)) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00005782 return Parser.TokError("missing expression");
Pete Cooper80d21cb2015-06-22 19:35:57 +00005783 }
5784
5785 // Note: we don't count b as used in "a = b". This is to allow
5786 // a = b
5787 // b = c
5788
Nirav Dave1a9044b2016-10-24 14:35:29 +00005789 if (Parser.parseToken(AsmToken::EndOfStatement))
5790 return true;
Pete Cooper80d21cb2015-06-22 19:35:57 +00005791
5792 // Validate that the LHS is allowed to be a variable (either it has not been
5793 // used as a symbol, or it is an absolute symbol).
5794 Sym = Parser.getContext().lookupSymbol(Name);
5795 if (Sym) {
5796 // Diagnose assignment to a label.
5797 //
5798 // FIXME: Diagnostics. Note the location of the definition as a label.
5799 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
5800 if (isSymbolUsedInExpression(Sym, Value))
5801 return Parser.Error(EqualLoc, "Recursive use of '" + Name + "'");
Vedant Kumar86dbd922015-08-31 17:44:53 +00005802 else if (Sym->isUndefined(/*SetUsed*/ false) && !Sym->isUsed() &&
5803 !Sym->isVariable())
Pete Cooper80d21cb2015-06-22 19:35:57 +00005804 ; // Allow redefinitions of undefined symbols only used in directives.
5805 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
5806 ; // Allow redefinitions of variables that haven't yet been used.
5807 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
5808 return Parser.Error(EqualLoc, "redefinition of '" + Name + "'");
5809 else if (!Sym->isVariable())
5810 return Parser.Error(EqualLoc, "invalid assignment to '" + Name + "'");
5811 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
5812 return Parser.Error(EqualLoc,
5813 "invalid reassignment of non-absolute variable '" +
5814 Name + "'");
Pete Cooper80d21cb2015-06-22 19:35:57 +00005815 } else if (Name == ".") {
Oliver Stannard268f42f2016-12-14 10:43:58 +00005816 Parser.getStreamer().emitValueToOffset(Value, 0, EqualLoc);
Pete Cooper80d21cb2015-06-22 19:35:57 +00005817 return false;
5818 } else
5819 Sym = Parser.getContext().getOrCreateSymbol(Name);
5820
5821 Sym->setRedefinable(allow_redef);
5822
5823 return false;
5824}
5825
Eugene Zelenko33d7b762016-08-23 17:14:32 +00005826} // end namespace MCParserUtils
5827} // end namespace llvm
Pete Cooper80d21cb2015-06-22 19:35:57 +00005828
Daniel Dunbar01e36072010-07-17 02:26:10 +00005829/// \brief Create an MCAsmParser instance.
Jim Grosbach4b905842013-09-20 23:08:21 +00005830MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
Sanne Wouda29338752017-02-08 14:48:05 +00005831 MCStreamer &Out, const MCAsmInfo &MAI,
5832 unsigned CB) {
5833 return new AsmParser(SM, C, Out, MAI, CB);
Daniel Dunbar01e36072010-07-17 02:26:10 +00005834}