blob: 38b6171ede9d7d05a81e5cdb6d7628d2abafd179 [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
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000083/// Helper types for tracking macro definitions.
Eli Benderskya313ae62013-01-16 18:56:50 +000084typedef std::vector<AsmToken> MCAsmMacroArgument;
85typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +000086
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000087/// Helper class for storing information about an active macro
Daniel Dunbar43235712010-07-18 18:54:11 +000088/// 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 {
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000107 /// 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
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000110 /// 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
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000113 /// 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
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000123/// The concrete assembly parser instance.
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000124class 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
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000142 /// 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
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000147 /// Stack of active macro instantiations.
Daniel Dunbar43235712010-07-18 18:54:11 +0000148 std::vector<MacroInstantiation*> ActiveMacros;
149
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000150 /// 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
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000156 /// Keeps track of how many .macro's have been instantiated.
Toma Tabacu217116e2015-04-27 10:50:29 +0000157 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
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000168 /// List of forward directional labels for diagnosis at the end.
Tim Northoverc0bef992016-04-13 19:46:54 +0000169 SmallVector<std::tuple<SMLoc, CppHashInfoTy, MCSymbol *>, 4> DirLabels;
170
Devang Patela173ee52012-01-31 18:14:05 +0000171 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000172 unsigned AssemblerDialect = ~0U;
Devang Patela173ee52012-01-31 18:14:05 +0000173
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000174 /// is Darwin compatibility enabled?
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000175 bool IsDarwin = false;
Preston Gurd05500642012-09-19 20:36:12 +0000176
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000177 /// Are we parsing ms-style inline assembly?
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000178 bool ParsingInlineAsm = false;
Chad Rosier49963552012-10-13 00:26:04 +0000179
Paul Robinsoncc7344a2018-06-14 13:38:20 +0000180 /// Did we already inform the user about inconsistent MD5 usage?
181 bool ReportedInconsistentMD5 = false;
182
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000183public:
Jim Grosbach345768c2011-08-16 18:33:49 +0000184 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Sanne Wouda29338752017-02-08 14:48:05 +0000185 const MCAsmInfo &MAI, unsigned CB);
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000186 AsmParser(const AsmParser &) = delete;
187 AsmParser &operator=(const AsmParser &) = delete;
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000188 ~AsmParser() override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000189
Craig Topper59be68f2014-03-08 07:14:16 +0000190 bool Run(bool NoInitialTextSection, bool NoFinalize = false) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000191
Craig Topper59be68f2014-03-08 07:14:16 +0000192 void addDirectiveHandler(StringRef Directive,
193 ExtensionDirectiveHandler Handler) override {
Eli Bendersky29b9f472013-01-16 00:50:52 +0000194 ExtensionDirectiveMap[Directive] = Handler;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000195 }
196
Toma Tabacu11e14a92015-04-21 11:50:52 +0000197 void addAliasForDirective(StringRef Directive, StringRef Alias) override {
198 DirectiveKindMap[Directive] = DirectiveKindMap[Alias];
199 }
200
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000201 /// @name MCAsmParser Interface
202 /// {
203
Craig Topper59be68f2014-03-08 07:14:16 +0000204 SourceMgr &getSourceManager() override { return SrcMgr; }
205 MCAsmLexer &getLexer() override { return Lexer; }
206 MCContext &getContext() override { return Ctx; }
207 MCStreamer &getStreamer() override { return Out; }
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000208
Reid Klecknera5b1eef2016-08-26 17:58:37 +0000209 CodeViewContext &getCVContext() { return Ctx.getCVContext(); }
210
Craig Topper59be68f2014-03-08 07:14:16 +0000211 unsigned getAssemblerDialect() override {
Devang Patela173ee52012-01-31 18:14:05 +0000212 if (AssemblerDialect == ~0U)
Eric Christophera7c32732012-12-18 00:30:54 +0000213 return MAI.getAssemblerDialect();
Devang Patela173ee52012-01-31 18:14:05 +0000214 else
215 return AssemblerDialect;
216 }
Craig Topper59be68f2014-03-08 07:14:16 +0000217 void setAssemblerDialect(unsigned i) override {
Devang Patela173ee52012-01-31 18:14:05 +0000218 AssemblerDialect = i;
219 }
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000220
Nirav Dave2364748a2016-09-16 18:30:20 +0000221 void Note(SMLoc L, const Twine &Msg, SMRange Range = None) override;
222 bool Warning(SMLoc L, const Twine &Msg, SMRange Range = None) override;
223 bool printError(SMLoc L, const Twine &Msg, SMRange Range = None) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000224
Craig Topper59be68f2014-03-08 07:14:16 +0000225 const AsmToken &Lex() override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000226
Yunzhong Gao27ea29b2016-09-02 23:15:29 +0000227 void setParsingInlineAsm(bool V) override {
228 ParsingInlineAsm = V;
229 Lexer.setParsingMSInlineAsm(V);
230 }
Craig Topper59be68f2014-03-08 07:14:16 +0000231 bool isParsingInlineAsm() override { return ParsingInlineAsm; }
Chad Rosier8bce6642012-10-18 15:49:34 +0000232
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000233 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
Chad Rosier8bce6642012-10-18 15:49:34 +0000234 unsigned &NumOutputs, unsigned &NumInputs,
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000235 SmallVectorImpl<std::pair<void *,bool>> &OpDecls,
Chad Rosier8bce6642012-10-18 15:49:34 +0000236 SmallVectorImpl<std::string> &Constraints,
Chad Rosier8bce6642012-10-18 15:49:34 +0000237 SmallVectorImpl<std::string> &Clobbers,
Craig Topper59be68f2014-03-08 07:14:16 +0000238 const MCInstrInfo *MII, const MCInstPrinter *IP,
239 MCAsmParserSemaCallback &SI) override;
Chad Rosier49963552012-10-13 00:26:04 +0000240
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000241 bool parseExpression(const MCExpr *&Res);
Craig Topper59be68f2014-03-08 07:14:16 +0000242 bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
243 bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) override;
244 bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
Toma Tabacu7bc44dc2015-06-25 09:52:02 +0000245 bool parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
246 SMLoc &EndLoc) override;
Craig Topper59be68f2014-03-08 07:14:16 +0000247 bool parseAbsoluteExpression(int64_t &Res) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000248
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000249 /// Parse a floating point expression using the float \p Semantics
Petr Hosek4cb08ce2016-09-23 19:25:15 +0000250 /// and set \p Res to the value.
251 bool parseRealValue(const fltSemantics &Semantics, APInt &Res);
252
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000253 /// Parse an identifier or string (as a quoted identifier)
Eli Bendersky0cf0cb92013-01-12 00:05:00 +0000254 /// and set \p Res to the identifier contents.
Craig Topper59be68f2014-03-08 07:14:16 +0000255 bool parseIdentifier(StringRef &Res) override;
256 void eatToEndOfStatement() override;
Eli Bendersky0cf0cb92013-01-12 00:05:00 +0000257
Nirav Davef43cc9f2016-10-10 15:24:54 +0000258 bool checkForValidSection() override;
Nirav Davea645433c2016-07-18 15:24:03 +0000259
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000260 /// }
261
262private:
Michael Zuckerman763e60e2017-05-04 10:37:00 +0000263 bool isAltmacroString(SMLoc &StrLoc, SMLoc &EndLoc);
Michael Zuckerman1f1a9122017-05-10 13:08:11 +0000264 void altMacroString(StringRef AltMacroStr, std::string &Res);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +0000265 bool parseStatement(ParseStatementInfo &Info,
266 MCAsmParserSemaCallback *SI);
Marina Yatsina5f5de9f2016-03-07 18:11:16 +0000267 bool parseCurlyBlockScope(SmallVectorImpl<AsmRewrite>& AsmStrRewrites);
Craig Topper3c76c522015-09-20 23:35:59 +0000268 bool parseCppHashLineFilenameComment(SMLoc L);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000269
Jim Grosbach4b905842013-09-20 23:08:21 +0000270 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +0000271 ArrayRef<MCAsmMacroParameter> Parameters);
Rafael Espindola34b9c512012-06-03 23:57:14 +0000272 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +0000273 ArrayRef<MCAsmMacroParameter> Parameters,
Toma Tabacu217116e2015-04-27 10:50:29 +0000274 ArrayRef<MCAsmMacroArgument> A, bool EnableAtPseudoVariable,
Craig Topper3c76c522015-09-20 23:35:59 +0000275 SMLoc L);
Daniel Dunbar43235712010-07-18 18:54:11 +0000276
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000277 /// Are macros enabled in the parser?
Jim Grosbach4b905842013-09-20 23:08:21 +0000278 bool areMacrosEnabled() {return MacrosEnabledFlag;}
Eli Benderskya313ae62013-01-16 18:56:50 +0000279
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000280 /// Control a flag in the parser that enables or disables macros.
Jim Grosbach4b905842013-09-20 23:08:21 +0000281 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
Eli Benderskya313ae62013-01-16 18:56:50 +0000282
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000283 /// Are we inside a macro instantiation?
Jim Grosbach4b905842013-09-20 23:08:21 +0000284 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
Eli Benderskya313ae62013-01-16 18:56:50 +0000285
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000286 /// Handle entry to macro instantiation.
Eli Benderskya313ae62013-01-16 18:56:50 +0000287 ///
288 /// \param M The macro.
289 /// \param NameLoc Instantiation location.
Jim Grosbach4b905842013-09-20 23:08:21 +0000290 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
Eli Benderskya313ae62013-01-16 18:56:50 +0000291
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000292 /// Handle exit from macro instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +0000293 void handleMacroExit();
Eli Benderskya313ae62013-01-16 18:56:50 +0000294
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000295 /// Extract AsmTokens for a macro argument.
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +0000296 bool parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg);
Eli Benderskya313ae62013-01-16 18:56:50 +0000297
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000298 /// Parse all macro arguments for a given macro.
Jim Grosbach4b905842013-09-20 23:08:21 +0000299 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
Eli Benderskya313ae62013-01-16 18:56:50 +0000300
Jim Grosbach4b905842013-09-20 23:08:21 +0000301 void printMacroInstantiations();
302 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
Nirav Dave2364748a2016-09-16 18:30:20 +0000303 SMRange Range = None) const {
304 ArrayRef<SMRange> Ranges(Range);
Chris Lattner72845262011-10-16 05:47:55 +0000305 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
Benjamin Kramerc7583112010-09-27 17:42:11 +0000306 }
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000307 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
Benjamin Kramerc7583112010-09-27 17:42:11 +0000308
Paul Robinson938d9a02018-03-22 15:48:01 +0000309 /// Should we emit DWARF describing this assembler source? (Returns false if
310 /// the source has .file directives, which means we don't want to generate
311 /// info describing the assembler source itself.)
312 bool enabledGenDwarfForAssembly();
313
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000314 /// Enter the specified file. This returns true on failure.
Jim Grosbach4b905842013-09-20 23:08:21 +0000315 bool enterIncludeFile(const std::string &Filename);
316
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000317 /// 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
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000322 /// 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
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000330 /// Parse up to the end of statement and a return the contents from the
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000331 /// 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
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000335 /// Parse until the end of a statement or a comma is encountered,
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000336 /// 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,
Nirav Dave7fd992a2018-08-16 16:31:14 +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,
Peter Collingbourne3e227332018-07-17 22:17:18 +0000509 DK_ADDRSIG,
510 DK_ADDRSIG_SYM,
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000511 DK_END
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000512 };
513
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000514 /// Maps directive name --> DirectiveKind enum, for
Eli Bendersky17233942013-01-15 22:59:42 +0000515 /// directives parsed by this class.
516 StringMap<DirectiveKind> DirectiveKindMap;
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000517
518 // ".ascii", ".asciz", ".string"
Jim Grosbach4b905842013-09-20 23:08:21 +0000519 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
Daniel Sanders9f6ad492015-11-12 13:33:00 +0000520 bool parseDirectiveReloc(SMLoc DirectiveLoc); // ".reloc"
Nirav Dave1a9044b2016-10-24 14:35:29 +0000521 bool parseDirectiveValue(StringRef IDVal,
522 unsigned Size); // ".byte", ".long", ...
523 bool parseDirectiveOctaValue(StringRef IDVal); // ".octa", ...
524 bool parseDirectiveRealValue(StringRef IDVal,
525 const fltSemantics &); // ".single", ...
Jim Grosbach4b905842013-09-20 23:08:21 +0000526 bool parseDirectiveFill(); // ".fill"
527 bool parseDirectiveZero(); // ".zero"
Eric Christophera7c32732012-12-18 00:30:54 +0000528 // ".set", ".equ", ".equiv"
Jim Grosbach4b905842013-09-20 23:08:21 +0000529 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
530 bool parseDirectiveOrg(); // ".org"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000531 // ".align{,32}", ".p2align{,w,l}"
Jim Grosbach4b905842013-09-20 23:08:21 +0000532 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000533
Eli Bendersky17233942013-01-15 22:59:42 +0000534 // ".file", ".line", ".loc", ".stabs"
Jim Grosbach4b905842013-09-20 23:08:21 +0000535 bool parseDirectiveFile(SMLoc DirectiveLoc);
536 bool parseDirectiveLine();
537 bool parseDirectiveLoc();
538 bool parseDirectiveStabs();
Eli Bendersky17233942013-01-15 22:59:42 +0000539
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000540 // ".cv_file", ".cv_func_id", ".cv_inline_site_id", ".cv_loc", ".cv_linetable",
541 // ".cv_inline_linetable", ".cv_def_range"
Reid Kleckner2214ed82016-01-29 00:49:42 +0000542 bool parseDirectiveCVFile();
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000543 bool parseDirectiveCVFuncId();
544 bool parseDirectiveCVInlineSiteId();
Reid Kleckner2214ed82016-01-29 00:49:42 +0000545 bool parseDirectiveCVLoc();
546 bool parseDirectiveCVLinetable();
David Majnemer6fcbd7e2016-01-29 19:24:12 +0000547 bool parseDirectiveCVInlineLinetable();
David Majnemer408b5e62016-02-05 01:55:49 +0000548 bool parseDirectiveCVDefRange();
Reid Kleckner2214ed82016-01-29 00:49:42 +0000549 bool parseDirectiveCVStringTable();
550 bool parseDirectiveCVFileChecksums();
Reid Kleckner26fa1bf2017-09-19 18:14:45 +0000551 bool parseDirectiveCVFileChecksumOffset();
Reid Kleckner9cdd4df2017-10-11 21:24:33 +0000552 bool parseDirectiveCVFPOData();
Reid Kleckner2214ed82016-01-29 00:49:42 +0000553
Eli Bendersky17233942013-01-15 22:59:42 +0000554 // .cfi directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000555 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +0000556 bool parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +0000557 bool parseDirectiveCFISections();
558 bool parseDirectiveCFIStartProc();
559 bool parseDirectiveCFIEndProc();
560 bool parseDirectiveCFIDefCfaOffset();
561 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
562 bool parseDirectiveCFIAdjustCfaOffset();
563 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
564 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
565 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
566 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
567 bool parseDirectiveCFIRememberState();
568 bool parseDirectiveCFIRestoreState();
569 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
570 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
571 bool parseDirectiveCFIEscape();
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +0000572 bool parseDirectiveCFIReturnColumn(SMLoc DirectiveLoc);
Jim Grosbach4b905842013-09-20 23:08:21 +0000573 bool parseDirectiveCFISignalFrame();
574 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
Eli Bendersky17233942013-01-15 22:59:42 +0000575
576 // macro directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000577 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
Nico Weber155dccd12014-07-24 17:08:39 +0000578 bool parseDirectiveExitMacro(StringRef Directive);
Jim Grosbach4b905842013-09-20 23:08:21 +0000579 bool parseDirectiveEndMacro(StringRef Directive);
580 bool parseDirectiveMacro(SMLoc DirectiveLoc);
581 bool parseDirectiveMacrosOnOff(StringRef Directive);
Michael Zuckerman56704612017-05-01 13:20:12 +0000582 // alternate macro mode directives
583 bool parseDirectiveAltmacro(StringRef Directive);
Eli Benderskyf483ff92012-12-20 19:05:53 +0000584 // ".bundle_align_mode"
Jim Grosbach4b905842013-09-20 23:08:21 +0000585 bool parseDirectiveBundleAlignMode();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000586 // ".bundle_lock"
Jim Grosbach4b905842013-09-20 23:08:21 +0000587 bool parseDirectiveBundleLock();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000588 // ".bundle_unlock"
Jim Grosbach4b905842013-09-20 23:08:21 +0000589 bool parseDirectiveBundleUnlock();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000590
Eli Bendersky17233942013-01-15 22:59:42 +0000591 // ".space", ".skip"
Jim Grosbach4b905842013-09-20 23:08:21 +0000592 bool parseDirectiveSpace(StringRef IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +0000593
Petr Hosek4cb08ce2016-09-23 19:25:15 +0000594 // ".dcb"
595 bool parseDirectiveDCB(StringRef IDVal, unsigned Size);
596 bool parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &);
Petr Hosek85b2f672016-09-23 21:53:36 +0000597 // ".ds"
598 bool parseDirectiveDS(StringRef IDVal, unsigned Size);
Petr Hosek4cb08ce2016-09-23 19:25:15 +0000599
Eli Bendersky17233942013-01-15 22:59:42 +0000600 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
Jim Grosbach4b905842013-09-20 23:08:21 +0000601 bool parseDirectiveLEB128(bool Signed);
Eli Bendersky17233942013-01-15 22:59:42 +0000602
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000603 /// Parse a directive like ".globl" which
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000604 /// accepts a single symbol (which should be a label or an external).
Jim Grosbach4b905842013-09-20 23:08:21 +0000605 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000606
Jim Grosbach4b905842013-09-20 23:08:21 +0000607 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000608
Jim Grosbach4b905842013-09-20 23:08:21 +0000609 bool parseDirectiveAbort(); // ".abort"
610 bool parseDirectiveInclude(); // ".include"
611 bool parseDirectiveIncbin(); // ".incbin"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000612
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +0000613 // ".if", ".ifeq", ".ifge", ".ifgt" , ".ifle", ".iflt" or ".ifne"
614 bool parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind);
Benjamin Kramer62c18b02012-05-12 11:18:42 +0000615 // ".ifb" or ".ifnb", depending on ExpectBlank.
Jim Grosbach4b905842013-09-20 23:08:21 +0000616 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000617 // ".ifc" or ".ifnc", depending on ExpectEqual.
Jim Grosbach4b905842013-09-20 23:08:21 +0000618 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
Sid Manning51c35602015-03-18 14:20:54 +0000619 // ".ifeqs" or ".ifnes", depending on ExpectEqual.
620 bool parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +0000621 // ".ifdef" or ".ifndef", depending on expect_defined
Jim Grosbach4b905842013-09-20 23:08:21 +0000622 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
623 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
624 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
625 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
Craig Topper59be68f2014-03-08 07:14:16 +0000626 bool parseEscapedString(std::string &Data) override;
Daniel Dunbar55f16672010-09-17 02:47:07 +0000627
Jim Grosbach4b905842013-09-20 23:08:21 +0000628 const MCExpr *applyModifierToExpr(const MCExpr *E,
Daniel Dunbar55f16672010-09-17 02:47:07 +0000629 MCSymbolRefExpr::VariantKind Variant);
Rafael Espindola47b7dac2012-05-12 16:31:10 +0000630
Rafael Espindola34b9c512012-06-03 23:57:14 +0000631 // Macro-like directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000632 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
633 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +0000634 raw_svector_ostream &OS);
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +0000635 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
Jim Grosbach4b905842013-09-20 23:08:21 +0000636 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
637 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
638 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
Chad Rosier8bce6642012-10-18 15:49:34 +0000639
Chad Rosierc7f552c2013-02-12 21:33:51 +0000640 // "_emit" or "__emit"
Jim Grosbach4b905842013-09-20 23:08:21 +0000641 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
Chad Rosierc7f552c2013-02-12 21:33:51 +0000642 size_t Len);
643
644 // "align"
Jim Grosbach4b905842013-09-20 23:08:21 +0000645 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000646
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000647 // "end"
648 bool parseDirectiveEnd(SMLoc DirectiveLoc);
649
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +0000650 // ".err" or ".error"
651 bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +0000652
Nico Weber404012b2014-07-24 16:26:06 +0000653 // ".warning"
654 bool parseDirectiveWarning(SMLoc DirectiveLoc);
655
Coby Tayree01e53202017-10-02 14:36:31 +0000656 // .print <double-quotes-string>
657 bool parseDirectivePrint(SMLoc DirectiveLoc);
658
Peter Collingbourne3e227332018-07-17 22:17:18 +0000659 // Directives to support address-significance tables.
660 bool parseDirectiveAddrsig();
661 bool parseDirectiveAddrsigSym();
662
Eli Bendersky17233942013-01-15 22:59:42 +0000663 void initializeDirectiveKindMap();
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000664};
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000665
666} // end anonymous namespace
Daniel Dunbar86033402010-07-12 17:54:38 +0000667
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000668namespace llvm {
669
670extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbarab058b82010-07-12 21:23:32 +0000671extern MCAsmParserExtension *createELFAsmParser();
Michael J. Spencerc8dbdfd2010-10-09 11:01:07 +0000672extern MCAsmParserExtension *createCOFFAsmParser();
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000673
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000674} // end namespace llvm
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000675
Chris Lattnerc35681b2010-01-19 19:46:13 +0000676enum { DEFAULT_ADDRSPACE = 0 };
677
David Blaikie9f380a32015-03-16 18:06:57 +0000678AsmParser::AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Sanne Wouda29338752017-02-08 14:48:05 +0000679 const MCAsmInfo &MAI, unsigned CB = 0)
David Blaikie9f380a32015-03-16 18:06:57 +0000680 : Lexer(MAI), Ctx(Ctx), Out(Out), MAI(MAI), SrcMgr(SM),
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000681 CurBuffer(CB ? CB : SM.getMainFileID()), MacrosEnabledFlag(true) {
Nirav Dave2364748a2016-09-16 18:30:20 +0000682 HadError = false;
Benjamin Kramer47f5e302011-10-16 10:48:29 +0000683 // Save the old handler.
684 SavedDiagHandler = SrcMgr.getDiagHandler();
685 SavedDiagContext = SrcMgr.getDiagContext();
686 // Set our own handler which calls the saved handler.
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000687 SrcMgr.setDiagHandler(DiagHandler, this);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000688 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar86033402010-07-12 17:54:38 +0000689
Daniel Dunbarc5011082010-07-12 18:12:02 +0000690 // Initialize the platform / file format parser.
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000691 switch (Ctx.getObjectFileInfo()->getObjectFileType()) {
692 case MCObjectFileInfo::IsCOFF:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000693 PlatformParser.reset(createCOFFAsmParser());
694 break;
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000695 case MCObjectFileInfo::IsMachO:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000696 PlatformParser.reset(createDarwinAsmParser());
697 IsDarwin = true;
698 break;
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000699 case MCObjectFileInfo::IsELF:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000700 PlatformParser.reset(createELFAsmParser());
701 break;
Dan Gohman18eafb62017-02-22 01:23:18 +0000702 case MCObjectFileInfo::IsWasm:
Sam Cleggf009da22018-04-19 22:00:53 +0000703 // TODO: WASM will need its own MCAsmParserExtension implementation, but
704 // for now we can re-use the ELF one, since the directives can be the
Sam Cleggcf2a9e22018-07-16 23:09:29 +0000705 // same for now.
Sam Cleggf009da22018-04-19 22:00:53 +0000706 PlatformParser.reset(createELFAsmParser());
Dan Gohman18eafb62017-02-22 01:23:18 +0000707 break;
Daniel Dunbarc5011082010-07-12 18:12:02 +0000708 }
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000709
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000710 PlatformParser->Initialize(*this);
Eli Bendersky17233942013-01-15 22:59:42 +0000711 initializeDirectiveKindMap();
Toma Tabacu217116e2015-04-27 10:50:29 +0000712
713 NumOfMacroInstantiations = 0;
Chris Lattner351a7ef2009-09-27 21:16:52 +0000714}
715
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000716AsmParser::~AsmParser() {
Saleem Abdulrasool6eae1e62014-05-21 17:53:18 +0000717 assert((HadError || ActiveMacros.empty()) &&
718 "Unexpected active macro instantiation!");
Sanne Wouda29338752017-02-08 14:48:05 +0000719
720 // Restore the saved diagnostics handler and context for use during
721 // finalization.
722 SrcMgr.setDiagHandler(SavedDiagHandler, SavedDiagContext);
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000723}
724
Jim Grosbach4b905842013-09-20 23:08:21 +0000725void AsmParser::printMacroInstantiations() {
Daniel Dunbar43235712010-07-18 18:54:11 +0000726 // Print the active macro instantiation stack.
Jim Grosbach4b905842013-09-20 23:08:21 +0000727 for (std::vector<MacroInstantiation *>::const_reverse_iterator
728 it = ActiveMacros.rbegin(),
729 ie = ActiveMacros.rend();
730 it != ie; ++it)
731 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
Chris Lattner03b80a42011-10-16 05:43:57 +0000732 "while in macro instantiation");
Daniel Dunbar43235712010-07-18 18:54:11 +0000733}
734
Nirav Dave2364748a2016-09-16 18:30:20 +0000735void AsmParser::Note(SMLoc L, const Twine &Msg, SMRange Range) {
736 printPendingErrors();
737 printMessage(L, SourceMgr::DK_Note, Msg, Range);
Saleem Abdulrasool69c7caf2014-01-07 02:28:31 +0000738 printMacroInstantiations();
739}
740
Nirav Dave2364748a2016-09-16 18:30:20 +0000741bool AsmParser::Warning(SMLoc L, const Twine &Msg, SMRange Range) {
Colin LeMahieufe36f832015-07-27 22:39:14 +0000742 if(getTargetParser().getTargetOptions().MCNoWarn)
743 return false;
Joerg Sonnenberger29815912014-08-26 18:39:50 +0000744 if (getTargetParser().getTargetOptions().MCFatalWarnings)
Nirav Dave2364748a2016-09-16 18:30:20 +0000745 return Error(L, Msg, Range);
746 printMessage(L, SourceMgr::DK_Warning, Msg, Range);
Jim Grosbach4b905842013-09-20 23:08:21 +0000747 printMacroInstantiations();
Joerg Sonnenberger74ba2622011-05-19 18:00:13 +0000748 return false;
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +0000749}
750
Nirav Dave2364748a2016-09-16 18:30:20 +0000751bool AsmParser::printError(SMLoc L, const Twine &Msg, SMRange Range) {
Daniel Dunbar43325c42010-09-09 22:42:56 +0000752 HadError = true;
Nirav Dave2364748a2016-09-16 18:30:20 +0000753 printMessage(L, SourceMgr::DK_Error, Msg, Range);
Jim Grosbach4b905842013-09-20 23:08:21 +0000754 printMacroInstantiations();
Chris Lattner2adc9e72009-06-21 21:22:11 +0000755 return true;
756}
757
Jim Grosbach4b905842013-09-20 23:08:21 +0000758bool AsmParser::enterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergeraf5f23e2011-06-01 13:10:15 +0000759 std::string IncludedFile;
Alp Tokera55b95b2014-07-06 10:33:31 +0000760 unsigned NewBuf =
761 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
762 if (!NewBuf)
Sean Callanan7a77eae2010-01-21 00:19:58 +0000763 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +0000764
Sean Callanan7a77eae2010-01-21 00:19:58 +0000765 CurBuffer = NewBuf;
Rafael Espindola8026bd02014-07-06 14:17:29 +0000766 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Sean Callanan7a77eae2010-01-21 00:19:58 +0000767 return false;
768}
Daniel Dunbar43235712010-07-18 18:54:11 +0000769
Sylvestre Ledru149e2812013-05-14 23:36:24 +0000770/// Process the specified .incbin file by searching for it in the include paths
Benjamin Kramerbde91762012-06-02 10:20:22 +0000771/// then just emitting the byte contents of the file to the streamer. This
Kevin Enderby109f25c2011-12-14 21:47:48 +0000772/// returns true on failure.
Petr Hosek2f4ac442016-09-23 00:41:06 +0000773bool AsmParser::processIncbinFile(const std::string &Filename, int64_t Skip,
774 const MCExpr *Count, SMLoc Loc) {
Kevin Enderby109f25c2011-12-14 21:47:48 +0000775 std::string IncludedFile;
Alp Tokera55b95b2014-07-06 10:33:31 +0000776 unsigned NewBuf =
777 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
778 if (!NewBuf)
Kevin Enderby109f25c2011-12-14 21:47:48 +0000779 return true;
780
Kevin Enderbyad41ab52011-12-14 22:34:45 +0000781 // Pick up the bytes from the file and emit them.
Petr Hosek2f4ac442016-09-23 00:41:06 +0000782 StringRef Bytes = SrcMgr.getMemoryBuffer(NewBuf)->getBuffer();
783 Bytes = Bytes.drop_front(Skip);
784 if (Count) {
785 int64_t Res;
Nirav Dave6c0665e2018-04-30 19:22:40 +0000786 if (!Count->evaluateAsAbsolute(Res, getStreamer().getAssemblerPtr()))
Petr Hosek2f4ac442016-09-23 00:41:06 +0000787 return Error(Loc, "expected absolute expression");
788 if (Res < 0)
789 return Warning(Loc, "negative count has no effect");
790 Bytes = Bytes.take_front(Res);
791 }
792 getStreamer().EmitBytes(Bytes);
Kevin Enderby109f25c2011-12-14 21:47:48 +0000793 return false;
794}
795
Alp Tokera55b95b2014-07-06 10:33:31 +0000796void AsmParser::jumpToLoc(SMLoc Loc, unsigned InBuffer) {
797 CurBuffer = InBuffer ? InBuffer : SrcMgr.FindBufferContainingLoc(Loc);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000798 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(),
799 Loc.getPointer());
Daniel Dunbar43235712010-07-18 18:54:11 +0000800}
801
Sean Callanan7a77eae2010-01-21 00:19:58 +0000802const AsmToken &AsmParser::Lex() {
Nirav Dave1180e6892016-06-02 17:15:05 +0000803 if (Lexer.getTok().is(AsmToken::Error))
804 Error(Lexer.getErrLoc(), Lexer.getErr());
805
Nirav Dave53a72f42016-07-11 12:42:14 +0000806 // if it's a end of statement with a comment in it
807 if (getTok().is(AsmToken::EndOfStatement)) {
808 // if this is a line comment output it.
Nirav Dave670109d2017-06-09 14:04:03 +0000809 if (!getTok().getString().empty() && getTok().getString().front() != '\n' &&
Nirav Dave53a72f42016-07-11 12:42:14 +0000810 getTok().getString().front() != '\r' && MAI.preserveAsmComments())
811 Out.addExplicitComment(Twine(getTok().getString()));
812 }
813
Sean Callanan7a77eae2010-01-21 00:19:58 +0000814 const AsmToken *tok = &Lexer.Lex();
Nirav Dave53a72f42016-07-11 12:42:14 +0000815
816 // Parse comments here to be deferred until end of next statement.
Nirav Davefd910412016-06-17 16:06:17 +0000817 while (tok->is(AsmToken::Comment)) {
Nirav Dave53a72f42016-07-11 12:42:14 +0000818 if (MAI.preserveAsmComments())
819 Out.addExplicitComment(Twine(tok->getString()));
Nirav Davefd910412016-06-17 16:06:17 +0000820 tok = &Lexer.Lex();
821 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000822
Sean Callanan7a77eae2010-01-21 00:19:58 +0000823 if (tok->is(AsmToken::Eof)) {
824 // If this is the end of an included file, pop the parent file off the
825 // include stack.
826 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
827 if (ParentIncludeLoc != SMLoc()) {
Jim Grosbach4b905842013-09-20 23:08:21 +0000828 jumpToLoc(ParentIncludeLoc);
Nirav Davefd910412016-06-17 16:06:17 +0000829 return Lex();
Sean Callanan7a77eae2010-01-21 00:19:58 +0000830 }
831 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000832
Sean Callanan7a77eae2010-01-21 00:19:58 +0000833 return *tok;
Sean Callanan686ed8d2010-01-19 20:22:31 +0000834}
835
Paul Robinson938d9a02018-03-22 15:48:01 +0000836bool AsmParser::enabledGenDwarfForAssembly() {
837 // Check whether the user specified -g.
838 if (!getContext().getGenDwarfForAssembly())
839 return false;
840 // If we haven't encountered any .file directives (which would imply that
841 // the assembler source was produced with debug info already) then emit one
842 // describing the assembler source file itself.
843 if (getContext().getGenDwarfFileNumber() == 0)
844 getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective(
845 0, StringRef(), getContext().getMainFileName()));
846 return true;
847}
848
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000849bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar322fec62010-03-13 02:20:57 +0000850 // Create the initial section, if requested.
Daniel Dunbar322fec62010-03-13 02:20:57 +0000851 if (!NoInitialTextSection)
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000852 Out.InitSections(false);
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000853
Chris Lattner36e02122009-06-21 20:54:55 +0000854 // Prime the lexer.
Sean Callanan686ed8d2010-01-19 20:22:31 +0000855 Lex();
Daniel Dunbar43325c42010-09-09 22:42:56 +0000856
857 HadError = false;
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000858 AsmCond StartingCondState = TheCondState;
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +0000859 SmallVector<AsmRewrite, 4> AsmStrRewrites;
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000860
Kevin Enderby6469fc22011-11-01 22:27:22 +0000861 // If we are generating dwarf for assembly source files save the initial text
Paul Robinson938d9a02018-03-22 15:48:01 +0000862 // section. (Don't use enabledGenDwarfForAssembly() here, as we aren't
863 // emitting any actual debug info yet and haven't had a chance to parse any
864 // embedded .file directives.)
Kevin Enderby6469fc22011-11-01 22:27:22 +0000865 if (getContext().getGenDwarfForAssembly()) {
Eric Christopher445c9522016-10-14 05:47:37 +0000866 MCSection *Sec = getStreamer().getCurrentSectionOnly();
Rafael Espindola2f9bdd82015-05-27 20:52:32 +0000867 if (!Sec->getBeginSymbol()) {
868 MCSymbol *SectionStartSym = getContext().createTempSymbol();
869 getStreamer().EmitLabel(SectionStartSym);
870 Sec->setBeginSymbol(SectionStartSym);
871 }
Rafael Espindolae0746792015-05-21 16:52:32 +0000872 bool InsertResult = getContext().addGenDwarfSection(Sec);
873 assert(InsertResult && ".text section should not have debug info yet");
Rafael Espindolafa160c72015-05-21 17:09:22 +0000874 (void)InsertResult;
Kevin Enderby6469fc22011-11-01 22:27:22 +0000875 }
876
Chris Lattner73f36112009-07-02 21:53:43 +0000877 // While we have input, parse each statement.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000878 while (Lexer.isNot(AsmToken::Eof)) {
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +0000879 ParseStatementInfo Info(&AsmStrRewrites);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +0000880 if (!parseStatement(Info, nullptr))
Jim Grosbach4b905842013-09-20 23:08:21 +0000881 continue;
Michael J. Spencer530ce852010-10-09 11:00:50 +0000882
Nirav Dave2364748a2016-09-16 18:30:20 +0000883 // If we have a Lexer Error we are on an Error Token. Load in Lexer Error
884 // for printing ErrMsg via Lex() only if no (presumably better) parser error
885 // exists.
886 if (!hasPendingError() && Lexer.getTok().is(AsmToken::Error)) {
Nirav Dave1180e6892016-06-02 17:15:05 +0000887 Lex();
888 }
889
Nirav Dave2364748a2016-09-16 18:30:20 +0000890 // parseStatement returned true so may need to emit an error.
891 printPendingErrors();
892
893 // Skipping to the next line if needed.
894 if (!getLexer().isAtStartOfStatement())
895 eatToEndOfStatement();
Chris Lattner73f36112009-07-02 21:53:43 +0000896 }
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000897
Nirav Dave2364748a2016-09-16 18:30:20 +0000898 // All errors should have been emitted.
899 assert(!hasPendingError() && "unexpected error from parseStatement");
900
Oliver Stannard21718282016-07-26 14:19:47 +0000901 getTargetParser().flushPendingInstructions(getStreamer());
902
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000903 if (TheCondState.TheCond != StartingCondState.TheCond ||
904 TheCondState.Ignore != StartingCondState.Ignore)
Nirav Dave2364748a2016-09-16 18:30:20 +0000905 printError(getTok().getLoc(), "unmatched .ifs or .elses");
Kevin Enderbye5930f12010-07-28 20:55:35 +0000906 // Check to see there are no empty DwarfFile slots.
David Blaikie8bf66c42014-04-01 07:35:52 +0000907 const auto &LineTables = getContext().getMCDwarfLineTables();
908 if (!LineTables.empty()) {
909 unsigned Index = 0;
910 for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) {
911 if (File.Name.empty() && Index != 0)
Nirav Dave2364748a2016-09-16 18:30:20 +0000912 printError(getTok().getLoc(), "unassigned file number: " +
913 Twine(Index) +
914 " for .file directives");
David Blaikie8bf66c42014-04-01 07:35:52 +0000915 ++Index;
916 }
Kevin Enderbye5930f12010-07-28 20:55:35 +0000917 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000918
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000919 // Check to see that all assembler local symbols were actually defined.
920 // Targets that don't do subsections via symbols may not want this, though,
921 // so conservatively exclude them. Only do this if we're finalizing, though,
922 // as otherwise we won't necessarilly have seen everything yet.
Tim Northover6b3169b2016-04-11 19:50:46 +0000923 if (!NoFinalize) {
924 if (MAI.hasSubsectionsViaSymbols()) {
925 for (const auto &TableEntry : getContext().getSymbols()) {
926 MCSymbol *Sym = TableEntry.getValue();
927 // Variable symbols may not be marked as defined, so check those
928 // explicitly. If we know it's a variable, we have a definition for
929 // the purposes of this check.
930 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
931 // FIXME: We would really like to refer back to where the symbol was
932 // first referenced for a source location. We need to add something
933 // to track that. Currently, we just point to the end of the file.
Nirav Dave2364748a2016-09-16 18:30:20 +0000934 printError(getTok().getLoc(), "assembler local symbol '" +
935 Sym->getName() + "' not defined");
Tim Northover6b3169b2016-04-11 19:50:46 +0000936 }
937 }
938
939 // Temporary symbols like the ones for directional jumps don't go in the
940 // symbol table. They also need to be diagnosed in all (final) cases.
Tim Northoverc0bef992016-04-13 19:46:54 +0000941 for (std::tuple<SMLoc, CppHashInfoTy, MCSymbol *> &LocSym : DirLabels) {
942 if (std::get<2>(LocSym)->isUndefined()) {
943 // Reset the state of any "# line file" directives we've seen to the
944 // context as it was at the diagnostic site.
945 CppHashInfo = std::get<1>(LocSym);
Nirav Dave2364748a2016-09-16 18:30:20 +0000946 printError(std::get<0>(LocSym), "directional label undefined");
Tim Northoverc0bef992016-04-13 19:46:54 +0000947 }
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000948 }
949 }
950
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000951 // Finalize the output stream if there are no errors and if the client wants
952 // us to.
Jack Carter13d5f752013-10-04 22:52:31 +0000953 if (!HadError && !NoFinalize)
Daniel Dunbar9df5f332009-08-21 08:34:18 +0000954 Out.Finish();
955
Oliver Stannard07b43d32015-11-17 09:58:07 +0000956 return HadError || getContext().hadError();
Chris Lattner36e02122009-06-21 20:54:55 +0000957}
958
Nirav Davef43cc9f2016-10-10 15:24:54 +0000959bool AsmParser::checkForValidSection() {
Eric Christopher445c9522016-10-14 05:47:37 +0000960 if (!ParsingInlineAsm && !getStreamer().getCurrentSectionOnly()) {
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000961 Out.InitSections(false);
Nirav Davef43cc9f2016-10-10 15:24:54 +0000962 return Error(getTok().getLoc(),
963 "expected section directive before assembly directive");
Daniel Dunbare5444a82010-09-09 22:42:59 +0000964 }
Nirav Davef43cc9f2016-10-10 15:24:54 +0000965 return false;
Daniel Dunbare5444a82010-09-09 22:42:59 +0000966}
967
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000968/// Throw away the rest of the line for testing purposes.
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000969void AsmParser::eatToEndOfStatement() {
Jim Grosbach4b905842013-09-20 23:08:21 +0000970 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Nirav Dave1180e6892016-06-02 17:15:05 +0000971 Lexer.Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +0000972
Chris Lattnere5074c42009-06-22 01:29:09 +0000973 // Eat EOL.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000974 if (Lexer.is(AsmToken::EndOfStatement))
Nirav Dave1180e6892016-06-02 17:15:05 +0000975 Lexer.Lex();
Chris Lattnere5074c42009-06-22 01:29:09 +0000976}
977
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000978StringRef AsmParser::parseStringToEndOfStatement() {
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000979 const char *Start = getTok().getLoc().getPointer();
980
Jim Grosbach4b905842013-09-20 23:08:21 +0000981 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Nirav Davefd910412016-06-17 16:06:17 +0000982 Lexer.Lex();
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000983
984 const char *End = getTok().getLoc().getPointer();
985 return StringRef(Start, End - Start);
986}
Chris Lattner78db3622009-06-22 05:51:26 +0000987
Jim Grosbach4b905842013-09-20 23:08:21 +0000988StringRef AsmParser::parseStringToComma() {
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000989 const char *Start = getTok().getLoc().getPointer();
990
991 while (Lexer.isNot(AsmToken::EndOfStatement) &&
Jim Grosbach4b905842013-09-20 23:08:21 +0000992 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
Nirav Davefd910412016-06-17 16:06:17 +0000993 Lexer.Lex();
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000994
995 const char *End = getTok().getLoc().getPointer();
996 return StringRef(Start, End - Start);
997}
998
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000999/// Parse a paren expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +00001000/// NOTE: This assumes the leading '(' has already been consumed.
1001///
1002/// parenexpr ::= expr)
1003///
Jim Grosbach4b905842013-09-20 23:08:21 +00001004bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
1005 if (parseExpression(Res))
1006 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001007 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner7fdbce72009-06-22 06:32:03 +00001008 return TokError("expected ')' in parentheses expression");
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001009 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001010 Lex();
Chris Lattner7fdbce72009-06-22 06:32:03 +00001011 return false;
1012}
Chris Lattner78db3622009-06-22 05:51:26 +00001013
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001014/// Parse a bracket expression and return it.
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +00001015/// NOTE: This assumes the leading '[' has already been consumed.
1016///
1017/// bracketexpr ::= expr]
1018///
Jim Grosbach4b905842013-09-20 23:08:21 +00001019bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
1020 if (parseExpression(Res))
1021 return true;
Nirav Davea645433c2016-07-18 15:24:03 +00001022 EndLoc = getTok().getEndLoc();
1023 if (parseToken(AsmToken::RBrac, "expected ']' in brackets expression"))
1024 return true;
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +00001025 return false;
1026}
1027
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001028/// Parse a primary expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +00001029/// primaryexpr ::= (parenexpr
1030/// primaryexpr ::= symbol
1031/// primaryexpr ::= number
Chris Lattner6b55cb92010-04-14 04:40:28 +00001032/// primaryexpr ::= '.'
Chris Lattner7fdbce72009-06-22 06:32:03 +00001033/// primaryexpr ::= ~,+,- primaryexpr
Jim Grosbach4b905842013-09-20 23:08:21 +00001034bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Kevin Enderby0017d8a2013-01-22 21:09:20 +00001035 SMLoc FirstTokenLoc = getLexer().getLoc();
1036 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
1037 switch (FirstTokenKind) {
Chris Lattner78db3622009-06-22 05:51:26 +00001038 default:
1039 return TokError("unknown token in expression");
Eric Christopher104af062011-04-12 00:03:13 +00001040 // If we have an error assume that we've already handled it.
1041 case AsmToken::Error:
1042 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001043 case AsmToken::Exclaim:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001044 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001045 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001046 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +00001047 Res = MCUnaryExpr::createLNot(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001048 return false;
Daniel Dunbar24764322010-08-24 19:13:42 +00001049 case AsmToken::Dollar:
Hans Wennborgce69d772013-10-18 20:46:28 +00001050 case AsmToken::At:
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +00001051 case AsmToken::String:
Daniel Dunbard20cda02009-10-16 01:34:54 +00001052 case AsmToken::Identifier: {
Daniel Dunbar24764322010-08-24 19:13:42 +00001053 StringRef Identifier;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001054 if (parseIdentifier(Identifier)) {
Nirav Daved0463322016-10-12 13:58:07 +00001055 // We may have failed but $ may be a valid token.
1056 if (getTok().is(AsmToken::Dollar)) {
David Majnemer0c58bc62013-09-25 10:47:21 +00001057 if (Lexer.getMAI().getDollarIsPC()) {
Nirav Daved0463322016-10-12 13:58:07 +00001058 Lex();
David Majnemer0c58bc62013-09-25 10:47:21 +00001059 // This is a '$' reference, which references the current PC. Emit a
1060 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +00001061 MCSymbol *Sym = Ctx.createTempSymbol();
David Majnemer0c58bc62013-09-25 10:47:21 +00001062 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +00001063 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None,
Jack Carter721726a2013-10-04 21:26:15 +00001064 getContext());
David Majnemer0c58bc62013-09-25 10:47:21 +00001065 EndLoc = FirstTokenLoc;
1066 return false;
Ted Kremenek297febe2014-03-06 22:13:17 +00001067 }
1068 return Error(FirstTokenLoc, "invalid token in expression");
David Majnemer0c58bc62013-09-25 10:47:21 +00001069 }
Kevin Enderby0017d8a2013-01-22 21:09:20 +00001070 }
David Peixotto8ad70b32013-12-04 22:43:20 +00001071 // Parse symbol variant
1072 std::pair<StringRef, StringRef> Split;
1073 if (!MAI.useParensForSymbolVariant()) {
David Majnemer6a5b8122014-06-19 01:25:43 +00001074 if (FirstTokenKind == AsmToken::String) {
1075 if (Lexer.is(AsmToken::At)) {
Nirav Davefd910412016-06-17 16:06:17 +00001076 Lex(); // eat @
David Majnemer6a5b8122014-06-19 01:25:43 +00001077 SMLoc AtLoc = getLexer().getLoc();
1078 StringRef VName;
1079 if (parseIdentifier(VName))
1080 return Error(AtLoc, "expected symbol variant after '@'");
1081
1082 Split = std::make_pair(Identifier, VName);
1083 }
1084 } else {
1085 Split = Identifier.split('@');
1086 }
David Peixotto8ad70b32013-12-04 22:43:20 +00001087 } else if (Lexer.is(AsmToken::LParen)) {
Nirav Davefd910412016-06-17 16:06:17 +00001088 Lex(); // eat '('.
David Peixotto8ad70b32013-12-04 22:43:20 +00001089 StringRef VName;
1090 parseIdentifier(VName);
Nirav Davea645433c2016-07-18 15:24:03 +00001091 // eat ')'.
1092 if (parseToken(AsmToken::RParen,
1093 "unexpected token in variant, expected ')'"))
1094 return true;
David Peixotto8ad70b32013-12-04 22:43:20 +00001095 Split = std::make_pair(Identifier, VName);
1096 }
Daniel Dunbar24764322010-08-24 19:13:42 +00001097
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001098 EndLoc = SMLoc::getFromPointer(Identifier.end());
1099
Daniel Dunbard20cda02009-10-16 01:34:54 +00001100 // This is a symbol reference.
Hans Wennborgce69d772013-10-18 20:46:28 +00001101 StringRef SymbolName = Identifier;
Weiming Zhaocf26d562016-12-01 18:00:36 +00001102 if (SymbolName.empty())
1103 return true;
1104
Hans Wennborgce69d772013-10-18 20:46:28 +00001105 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Hans Wennborg69918bc2013-10-17 01:13:02 +00001106
Hans Wennborg7ddcdc82013-10-18 02:14:40 +00001107 // Lookup the symbol variant if used.
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00001108 if (!Split.second.empty()) {
Hans Wennborg7ddcdc82013-10-18 02:14:40 +00001109 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Hans Wennborgce69d772013-10-18 20:46:28 +00001110 if (Variant != MCSymbolRefExpr::VK_Invalid) {
1111 SymbolName = Split.first;
David Peixotto8ad70b32013-12-04 22:43:20 +00001112 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
Hans Wennborgce69d772013-10-18 20:46:28 +00001113 Variant = MCSymbolRefExpr::VK_None;
1114 } else {
Saleem Abdulrasoola25e1e42014-01-26 22:29:43 +00001115 return Error(SMLoc::getFromPointer(Split.second.begin()),
1116 "invalid variant '" + Split.second + "'");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001117 }
1118 }
Daniel Dunbar55992562010-03-15 23:51:06 +00001119
Jim Grosbach6f482002015-05-18 18:43:14 +00001120 MCSymbol *Sym = getContext().getOrCreateSymbol(SymbolName);
Hans Wennborgce69d772013-10-18 20:46:28 +00001121
Daniel Dunbard20cda02009-10-16 01:34:54 +00001122 // If this is an absolute variable reference, substitute it now to preserve
1123 // semantics in the face of reassignment.
Nirav Dave05b58912018-06-05 15:13:39 +00001124 if (Sym->isVariable()) {
1125 auto V = Sym->getVariableValue(/*SetUsed*/ false);
1126 bool DoInline = isa<MCConstantExpr>(V);
1127 if (auto TV = dyn_cast<MCTargetExpr>(V))
1128 DoInline = TV->inlineAssignedExpr();
1129 if (DoInline) {
1130 if (Variant)
1131 return Error(EndLoc, "unexpected modifier on variable reference");
1132 Res = Sym->getVariableValue(/*SetUsed*/ false);
1133 return false;
1134 }
Daniel Dunbard20cda02009-10-16 01:34:54 +00001135 }
1136
1137 // Otherwise create a symbol ref.
Chad Rosier9245e122017-01-19 20:06:32 +00001138 Res = MCSymbolRefExpr::create(Sym, Variant, getContext(), FirstTokenLoc);
Chris Lattner78db3622009-06-22 05:51:26 +00001139 return false;
Daniel Dunbard20cda02009-10-16 01:34:54 +00001140 }
David Woodhousef42a6662014-02-01 16:20:54 +00001141 case AsmToken::BigNum:
1142 return TokError("literal value out of range for directive");
Kevin Enderby0510b482010-05-17 23:08:19 +00001143 case AsmToken::Integer: {
1144 SMLoc Loc = getTok().getLoc();
1145 int64_t IntVal = getTok().getIntVal();
Jim Grosbach13760bd2015-05-30 01:25:56 +00001146 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001147 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001148 Lex(); // Eat token.
Kevin Enderby0510b482010-05-17 23:08:19 +00001149 // Look for 'b' or 'f' following an Integer as a directional label
1150 if (Lexer.getKind() == AsmToken::Identifier) {
1151 StringRef IDVal = getTok().getString();
Ulrich Weigandd4120982013-06-20 16:24:17 +00001152 // Lookup the symbol variant if used.
1153 std::pair<StringRef, StringRef> Split = IDVal.split('@');
1154 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
1155 if (Split.first.size() != IDVal.size()) {
1156 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Arnaud A. de Grandmaisonc97727a2014-03-21 21:54:46 +00001157 if (Variant == MCSymbolRefExpr::VK_Invalid)
Ulrich Weigandd4120982013-06-20 16:24:17 +00001158 return TokError("invalid variant '" + Split.second + "'");
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001159 IDVal = Split.first;
Ulrich Weigandd4120982013-06-20 16:24:17 +00001160 }
Jim Grosbach4b905842013-09-20 23:08:21 +00001161 if (IDVal == "f" || IDVal == "b") {
1162 MCSymbol *Sym =
Jim Grosbach6f482002015-05-18 18:43:14 +00001163 Ctx.getDirectionalLocalSymbol(IntVal, IDVal == "b");
Jim Grosbach13760bd2015-05-30 01:25:56 +00001164 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00001165 if (IDVal == "b" && Sym->isUndefined())
Tim Northover6b3169b2016-04-11 19:50:46 +00001166 return Error(Loc, "directional label undefined");
Tim Northoverc0bef992016-04-13 19:46:54 +00001167 DirLabels.push_back(std::make_tuple(Loc, CppHashInfo, Sym));
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001168 EndLoc = Lexer.getTok().getEndLoc();
Kevin Enderby0510b482010-05-17 23:08:19 +00001169 Lex(); // Eat identifier.
1170 }
1171 }
Chris Lattner78db3622009-06-22 05:51:26 +00001172 return false;
Kevin Enderby0510b482010-05-17 23:08:19 +00001173 }
Bill Wendlingcdbf17b2011-01-25 21:26:41 +00001174 case AsmToken::Real: {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001175 APFloat RealVal(APFloat::IEEEdouble(), getTok().getString());
Bob Wilson813bdf62011-02-03 23:17:47 +00001176 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Jim Grosbach13760bd2015-05-30 01:25:56 +00001177 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001178 EndLoc = Lexer.getTok().getEndLoc();
Bill Wendlingcdbf17b2011-01-25 21:26:41 +00001179 Lex(); // Eat token.
1180 return false;
1181 }
Chris Lattner6b55cb92010-04-14 04:40:28 +00001182 case AsmToken::Dot: {
1183 // This is a '.' reference, which references the current PC. Emit a
1184 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +00001185 MCSymbol *Sym = Ctx.createTempSymbol();
Chris Lattner6b55cb92010-04-14 04:40:28 +00001186 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +00001187 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001188 EndLoc = Lexer.getTok().getEndLoc();
Chris Lattner6b55cb92010-04-14 04:40:28 +00001189 Lex(); // Eat identifier.
1190 return false;
1191 }
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001192 case AsmToken::LParen:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001193 Lex(); // Eat the '('.
Jim Grosbach4b905842013-09-20 23:08:21 +00001194 return parseParenExpr(Res, EndLoc);
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +00001195 case AsmToken::LBrac:
1196 if (!PlatformParser->HasBracketExpressions())
1197 return TokError("brackets expression not supported on this target");
1198 Lex(); // Eat the '['.
Jim Grosbach4b905842013-09-20 23:08:21 +00001199 return parseBracketExpr(Res, EndLoc);
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001200 case AsmToken::Minus:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001201 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001202 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001203 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +00001204 Res = MCUnaryExpr::createMinus(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001205 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001206 case AsmToken::Plus:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001207 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001208 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001209 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +00001210 Res = MCUnaryExpr::createPlus(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001211 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001212 case AsmToken::Tilde:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001213 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001214 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001215 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +00001216 Res = MCUnaryExpr::createNot(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001217 return false;
Daniel Sanders3feeb9c2016-08-08 11:50:25 +00001218 // MIPS unary expression operators. The lexer won't generate these tokens if
1219 // MCAsmInfo::HasMipsExpressions is false for the target.
1220 case AsmToken::PercentCall16:
1221 case AsmToken::PercentCall_Hi:
1222 case AsmToken::PercentCall_Lo:
1223 case AsmToken::PercentDtprel_Hi:
1224 case AsmToken::PercentDtprel_Lo:
1225 case AsmToken::PercentGot:
1226 case AsmToken::PercentGot_Disp:
1227 case AsmToken::PercentGot_Hi:
1228 case AsmToken::PercentGot_Lo:
1229 case AsmToken::PercentGot_Ofst:
1230 case AsmToken::PercentGot_Page:
1231 case AsmToken::PercentGottprel:
1232 case AsmToken::PercentGp_Rel:
1233 case AsmToken::PercentHi:
1234 case AsmToken::PercentHigher:
1235 case AsmToken::PercentHighest:
1236 case AsmToken::PercentLo:
1237 case AsmToken::PercentNeg:
1238 case AsmToken::PercentPcrel_Hi:
1239 case AsmToken::PercentPcrel_Lo:
1240 case AsmToken::PercentTlsgd:
1241 case AsmToken::PercentTlsldm:
1242 case AsmToken::PercentTprel_Hi:
1243 case AsmToken::PercentTprel_Lo:
1244 Lex(); // Eat the operator.
1245 if (Lexer.isNot(AsmToken::LParen))
1246 return TokError("expected '(' after operator");
1247 Lex(); // Eat the operator.
1248 if (parseExpression(Res, EndLoc))
1249 return true;
1250 if (Lexer.isNot(AsmToken::RParen))
1251 return TokError("expected ')'");
1252 Lex(); // Eat the operator.
1253 Res = getTargetParser().createTargetUnaryExpr(Res, FirstTokenKind, Ctx);
1254 return !Res;
Chris Lattner78db3622009-06-22 05:51:26 +00001255 }
1256}
Chris Lattner7fdbce72009-06-22 06:32:03 +00001257
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001258bool AsmParser::parseExpression(const MCExpr *&Res) {
Chris Lattnere17df0b2010-01-15 19:39:23 +00001259 SMLoc EndLoc;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001260 return parseExpression(Res, EndLoc);
Chris Lattner528d00b2010-01-15 19:28:38 +00001261}
1262
Daniel Dunbar55f16672010-09-17 02:47:07 +00001263const MCExpr *
Jim Grosbach4b905842013-09-20 23:08:21 +00001264AsmParser::applyModifierToExpr(const MCExpr *E,
Daniel Dunbar55f16672010-09-17 02:47:07 +00001265 MCSymbolRefExpr::VariantKind Variant) {
Joerg Sonnenbergerb822af42013-08-27 20:23:19 +00001266 // Ask the target implementation about this expression first.
1267 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
1268 if (NewE)
1269 return NewE;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001270 // Recurse over the given expression, rebuilding it to apply the given variant
1271 // if there is exactly one symbol.
1272 switch (E->getKind()) {
1273 case MCExpr::Target:
1274 case MCExpr::Constant:
Craig Topper353eda42014-04-24 06:44:33 +00001275 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001276
1277 case MCExpr::SymbolRef: {
1278 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
1279
1280 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001281 TokError("invalid variant on expression '" + getTok().getIdentifier() +
1282 "' (already modified)");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001283 return E;
1284 }
1285
Jim Grosbach13760bd2015-05-30 01:25:56 +00001286 return MCSymbolRefExpr::create(&SRE->getSymbol(), Variant, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001287 }
1288
1289 case MCExpr::Unary: {
1290 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +00001291 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001292 if (!Sub)
Craig Topper353eda42014-04-24 06:44:33 +00001293 return nullptr;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001294 return MCUnaryExpr::create(UE->getOpcode(), Sub, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001295 }
1296
1297 case MCExpr::Binary: {
1298 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +00001299 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
1300 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001301
1302 if (!LHS && !RHS)
Craig Topper353eda42014-04-24 06:44:33 +00001303 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001304
Jim Grosbach4b905842013-09-20 23:08:21 +00001305 if (!LHS)
1306 LHS = BE->getLHS();
1307 if (!RHS)
1308 RHS = BE->getRHS();
Daniel Dunbar55f16672010-09-17 02:47:07 +00001309
Jim Grosbach13760bd2015-05-30 01:25:56 +00001310 return MCBinaryExpr::create(BE->getOpcode(), LHS, RHS, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001311 }
1312 }
Daniel Dunbarbaad46c2010-09-17 16:34:24 +00001313
Craig Toppera2886c22012-02-07 05:05:23 +00001314 llvm_unreachable("Invalid expression kind!");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001315}
1316
Michael Zuckerman763e60e2017-05-04 10:37:00 +00001317/// This function checks if the next token is <string> type or arithmetic.
1318/// string that begin with character '<' must end with character '>'.
1319/// otherwise it is arithmetics.
1320/// If the function returns a 'true' value,
1321/// the End argument will be filled with the last location pointed to the '>'
1322/// character.
1323
Sam Cleggf009da22018-04-19 22:00:53 +00001324/// There is a gap between the AltMacro's documentation and the single quote implementation.
Michael Zuckerman763e60e2017-05-04 10:37:00 +00001325/// GCC does not fully support this feature and so we will not support it.
1326/// TODO: Adding single quote as a string.
1327bool AsmParser::isAltmacroString(SMLoc &StrLoc, SMLoc &EndLoc) {
1328 assert((StrLoc.getPointer() != NULL) &&
1329 "Argument to the function cannot be a NULL value");
1330 const char *CharPtr = StrLoc.getPointer();
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00001331 while ((*CharPtr != '>') && (*CharPtr != '\n') && (*CharPtr != '\r') &&
1332 (*CharPtr != '\0')) {
1333 if (*CharPtr == '!')
1334 CharPtr++;
Michael Zuckerman763e60e2017-05-04 10:37:00 +00001335 CharPtr++;
1336 }
1337 if (*CharPtr == '>') {
1338 EndLoc = StrLoc.getFromPointer(CharPtr + 1);
1339 return true;
1340 }
1341 return false;
1342}
1343
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001344/// creating a string without the escape characters '!'.
Michael Zuckerman1f1a9122017-05-10 13:08:11 +00001345void AsmParser::altMacroString(StringRef AltMacroStr,std::string &Res) {
Michael Zuckermanff298792017-05-10 14:00:57 +00001346 for (size_t Pos = 0; Pos < AltMacroStr.size(); Pos++) {
Michael Zuckerman1f1a9122017-05-10 13:08:11 +00001347 if (AltMacroStr[Pos] == '!')
1348 Pos++;
1349 Res += AltMacroStr[Pos];
1350 }
1351}
1352
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001353/// Parse an expression and return it.
Michael J. Spencer530ce852010-10-09 11:00:50 +00001354///
Jim Grosbachbd164242011-08-20 16:24:13 +00001355/// expr ::= expr &&,|| expr -> lowest.
1356/// expr ::= expr |,^,&,! expr
1357/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1358/// expr ::= expr <<,>> expr
1359/// expr ::= expr +,- expr
1360/// expr ::= expr *,/,% expr -> highest.
Chris Lattner7fdbce72009-06-22 06:32:03 +00001361/// expr ::= primaryexpr
1362///
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001363bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001364 // Parse the expression.
Craig Topper353eda42014-04-24 06:44:33 +00001365 Res = nullptr;
Nirav Dave7fd992a2018-08-16 16:31:14 +00001366 if (getTargetParser().parsePrimaryExpr(Res, EndLoc) ||
1367 parseBinOpRHS(1, Res, EndLoc))
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001368 return true;
1369
Daniel Dunbar55f16672010-09-17 02:47:07 +00001370 // As a special case, we support 'a op b @ modifier' by rewriting the
1371 // expression to include the modifier. This is inefficient, but in general we
1372 // expect users to use 'a@modifier op b'.
1373 if (Lexer.getKind() == AsmToken::At) {
1374 Lex();
1375
1376 if (Lexer.isNot(AsmToken::Identifier))
1377 return TokError("unexpected symbol modifier following '@'");
1378
1379 MCSymbolRefExpr::VariantKind Variant =
Jim Grosbach4b905842013-09-20 23:08:21 +00001380 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001381 if (Variant == MCSymbolRefExpr::VK_Invalid)
1382 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1383
Jim Grosbach4b905842013-09-20 23:08:21 +00001384 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001385 if (!ModifiedRes) {
1386 return TokError("invalid modifier '" + getTok().getIdentifier() +
1387 "' (no symbols present)");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001388 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001389
Daniel Dunbar55f16672010-09-17 02:47:07 +00001390 Res = ModifiedRes;
1391 Lex();
1392 }
1393
Nirav Dave6c0665e2018-04-30 19:22:40 +00001394 // Try to constant fold it up front, if possible. Do not exploit
1395 // assembler here.
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001396 int64_t Value;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001397 if (Res->evaluateAsAbsolute(Value))
1398 Res = MCConstantExpr::create(Value, getContext());
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001399
1400 return false;
Chris Lattner7fdbce72009-06-22 06:32:03 +00001401}
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001402
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001403bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Craig Topper353eda42014-04-24 06:44:33 +00001404 Res = nullptr;
Jim Grosbach4b905842013-09-20 23:08:21 +00001405 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
Daniel Dunbar7c82d562009-08-31 08:08:17 +00001406}
1407
Toma Tabacu7bc44dc2015-06-25 09:52:02 +00001408bool AsmParser::parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
1409 SMLoc &EndLoc) {
1410 if (parseParenExpr(Res, EndLoc))
1411 return true;
1412
1413 for (; ParenDepth > 0; --ParenDepth) {
1414 if (parseBinOpRHS(1, Res, EndLoc))
1415 return true;
1416
1417 // We don't Lex() the last RParen.
1418 // This is the same behavior as parseParenExpression().
1419 if (ParenDepth - 1 > 0) {
Nirav Davea645433c2016-07-18 15:24:03 +00001420 EndLoc = getTok().getEndLoc();
1421 if (parseToken(AsmToken::RParen,
1422 "expected ')' in parentheses expression"))
1423 return true;
Toma Tabacu7bc44dc2015-06-25 09:52:02 +00001424 }
1425 }
1426 return false;
1427}
1428
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001429bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
Daniel Dunbarf3636452009-08-31 08:07:22 +00001430 const MCExpr *Expr;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001431
Daniel Dunbar75630b32009-06-30 02:10:03 +00001432 SMLoc StartLoc = Lexer.getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001433 if (parseExpression(Expr))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001434 return true;
1435
Nirav Dave6c0665e2018-04-30 19:22:40 +00001436 if (!Expr->evaluateAsAbsolute(Res, getStreamer().getAssemblerPtr()))
Daniel Dunbar75630b32009-06-30 02:10:03 +00001437 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001438
1439 return false;
1440}
1441
David Majnemer0993e0b2015-10-26 03:15:34 +00001442static unsigned getDarwinBinOpPrecedence(AsmToken::TokenKind K,
1443 MCBinaryExpr::Opcode &Kind,
1444 bool ShouldUseLogicalShr) {
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001445 switch (K) {
Daniel Dunbar940cda22009-08-31 08:07:44 +00001446 default:
Jim Grosbach4b905842013-09-20 23:08:21 +00001447 return 0; // not a binop.
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001448
Jim Grosbach4b905842013-09-20 23:08:21 +00001449 // Lowest Precedence: &&, ||
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001450 case AsmToken::AmpAmp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001451 Kind = MCBinaryExpr::LAnd;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001452 return 1;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001453 case AsmToken::PipePipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001454 Kind = MCBinaryExpr::LOr;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001455 return 1;
1456
Jim Grosbach4b905842013-09-20 23:08:21 +00001457 // Low Precedence: |, &, ^
1458 //
1459 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001460 case AsmToken::Pipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001461 Kind = MCBinaryExpr::Or;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001462 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001463 case AsmToken::Caret:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001464 Kind = MCBinaryExpr::Xor;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001465 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001466 case AsmToken::Amp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001467 Kind = MCBinaryExpr::And;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001468 return 2;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001469
Jim Grosbach4b905842013-09-20 23:08:21 +00001470 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001471 case AsmToken::EqualEqual:
1472 Kind = MCBinaryExpr::EQ;
1473 return 3;
1474 case AsmToken::ExclaimEqual:
1475 case AsmToken::LessGreater:
1476 Kind = MCBinaryExpr::NE;
1477 return 3;
1478 case AsmToken::Less:
1479 Kind = MCBinaryExpr::LT;
1480 return 3;
1481 case AsmToken::LessEqual:
1482 Kind = MCBinaryExpr::LTE;
1483 return 3;
1484 case AsmToken::Greater:
1485 Kind = MCBinaryExpr::GT;
1486 return 3;
1487 case AsmToken::GreaterEqual:
1488 Kind = MCBinaryExpr::GTE;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001489 return 3;
1490
Jim Grosbach4b905842013-09-20 23:08:21 +00001491 // Intermediate Precedence: <<, >>
Jim Grosbachbd164242011-08-20 16:24:13 +00001492 case AsmToken::LessLess:
1493 Kind = MCBinaryExpr::Shl;
1494 return 4;
1495 case AsmToken::GreaterGreater:
David Majnemer0993e0b2015-10-26 03:15:34 +00001496 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
Jim Grosbachbd164242011-08-20 16:24:13 +00001497 return 4;
1498
Jim Grosbach4b905842013-09-20 23:08:21 +00001499 // High Intermediate Precedence: +, -
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001500 case AsmToken::Plus:
1501 Kind = MCBinaryExpr::Add;
Jim Grosbachbd164242011-08-20 16:24:13 +00001502 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001503 case AsmToken::Minus:
1504 Kind = MCBinaryExpr::Sub;
Jim Grosbachbd164242011-08-20 16:24:13 +00001505 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001506
Jim Grosbach4b905842013-09-20 23:08:21 +00001507 // Highest Precedence: *, /, %
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001508 case AsmToken::Star:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001509 Kind = MCBinaryExpr::Mul;
Jim Grosbachbd164242011-08-20 16:24:13 +00001510 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001511 case AsmToken::Slash:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001512 Kind = MCBinaryExpr::Div;
Jim Grosbachbd164242011-08-20 16:24:13 +00001513 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001514 case AsmToken::Percent:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001515 Kind = MCBinaryExpr::Mod;
Jim Grosbachbd164242011-08-20 16:24:13 +00001516 return 6;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001517 }
1518}
1519
David Majnemer0993e0b2015-10-26 03:15:34 +00001520static unsigned getGNUBinOpPrecedence(AsmToken::TokenKind K,
1521 MCBinaryExpr::Opcode &Kind,
1522 bool ShouldUseLogicalShr) {
1523 switch (K) {
1524 default:
1525 return 0; // not a binop.
1526
1527 // Lowest Precedence: &&, ||
1528 case AsmToken::AmpAmp:
1529 Kind = MCBinaryExpr::LAnd;
1530 return 2;
1531 case AsmToken::PipePipe:
1532 Kind = MCBinaryExpr::LOr;
1533 return 1;
1534
1535 // Low Precedence: ==, !=, <>, <, <=, >, >=
1536 case AsmToken::EqualEqual:
1537 Kind = MCBinaryExpr::EQ;
1538 return 3;
1539 case AsmToken::ExclaimEqual:
1540 case AsmToken::LessGreater:
1541 Kind = MCBinaryExpr::NE;
1542 return 3;
1543 case AsmToken::Less:
1544 Kind = MCBinaryExpr::LT;
1545 return 3;
1546 case AsmToken::LessEqual:
1547 Kind = MCBinaryExpr::LTE;
1548 return 3;
1549 case AsmToken::Greater:
1550 Kind = MCBinaryExpr::GT;
1551 return 3;
1552 case AsmToken::GreaterEqual:
1553 Kind = MCBinaryExpr::GTE;
1554 return 3;
1555
1556 // Low Intermediate Precedence: +, -
1557 case AsmToken::Plus:
1558 Kind = MCBinaryExpr::Add;
1559 return 4;
1560 case AsmToken::Minus:
1561 Kind = MCBinaryExpr::Sub;
1562 return 4;
1563
1564 // High Intermediate Precedence: |, &, ^
1565 //
1566 // FIXME: gas seems to support '!' as an infix operator?
1567 case AsmToken::Pipe:
1568 Kind = MCBinaryExpr::Or;
1569 return 5;
1570 case AsmToken::Caret:
1571 Kind = MCBinaryExpr::Xor;
1572 return 5;
1573 case AsmToken::Amp:
1574 Kind = MCBinaryExpr::And;
1575 return 5;
1576
1577 // Highest Precedence: *, /, %, <<, >>
1578 case AsmToken::Star:
1579 Kind = MCBinaryExpr::Mul;
1580 return 6;
1581 case AsmToken::Slash:
1582 Kind = MCBinaryExpr::Div;
1583 return 6;
1584 case AsmToken::Percent:
1585 Kind = MCBinaryExpr::Mod;
1586 return 6;
1587 case AsmToken::LessLess:
1588 Kind = MCBinaryExpr::Shl;
1589 return 6;
1590 case AsmToken::GreaterGreater:
1591 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1592 return 6;
1593 }
1594}
1595
1596unsigned AsmParser::getBinOpPrecedence(AsmToken::TokenKind K,
1597 MCBinaryExpr::Opcode &Kind) {
1598 bool ShouldUseLogicalShr = MAI.shouldUseLogicalShr();
1599 return IsDarwin ? getDarwinBinOpPrecedence(K, Kind, ShouldUseLogicalShr)
1600 : getGNUBinOpPrecedence(K, Kind, ShouldUseLogicalShr);
1601}
1602
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001603/// Parse all binary operators with precedence >= 'Precedence'.
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001604/// Res contains the LHS of the expression on input.
Jim Grosbach4b905842013-09-20 23:08:21 +00001605bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
Chris Lattner528d00b2010-01-15 19:28:38 +00001606 SMLoc &EndLoc) {
Chad Rosier9245e122017-01-19 20:06:32 +00001607 SMLoc StartLoc = Lexer.getLoc();
Eugene Zelenko33d7b762016-08-23 17:14:32 +00001608 while (true) {
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001609 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001610 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001611
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001612 // If the next token is lower precedence than we are allowed to eat, return
1613 // successfully with what we ate already.
1614 if (TokPrec < Precedence)
1615 return false;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001616
Sean Callanan686ed8d2010-01-19 20:22:31 +00001617 Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +00001618
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001619 // Eat the next primary expression.
Daniel Dunbarf3636452009-08-31 08:07:22 +00001620 const MCExpr *RHS;
Nirav Dave7fd992a2018-08-16 16:31:14 +00001621 if (getTargetParser().parsePrimaryExpr(RHS, EndLoc))
Jim Grosbach4b905842013-09-20 23:08:21 +00001622 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001623
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001624 // If BinOp binds less tightly with RHS than the operator after RHS, let
1625 // the pending operator take RHS as its LHS.
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001626 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001627 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Jim Grosbach4b905842013-09-20 23:08:21 +00001628 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1629 return true;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001630
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001631 // Merge LHS and RHS according to operator.
Chad Rosier9245e122017-01-19 20:06:32 +00001632 Res = MCBinaryExpr::create(Kind, Res, RHS, getContext(), StartLoc);
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001633 }
1634}
1635
Chris Lattner36e02122009-06-21 20:54:55 +00001636/// ParseStatement:
1637/// ::= EndOfStatement
Chris Lattnere5074c42009-06-22 01:29:09 +00001638/// ::= Label* Directive ...Operands... EndOfStatement
1639/// ::= Label* Identifier OperandList* EndOfStatement
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001640bool AsmParser::parseStatement(ParseStatementInfo &Info,
1641 MCAsmParserSemaCallback *SI) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001642 assert(!hasPendingError() && "parseStatement started with pending error");
Nirav Davefd910412016-06-17 16:06:17 +00001643 // Eat initial spaces and comments
1644 while (Lexer.is(AsmToken::Space))
1645 Lex();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001646 if (Lexer.is(AsmToken::EndOfStatement)) {
Nirav Davefd910412016-06-17 16:06:17 +00001647 // if this is a line comment we can drop it safely
Nirav Dave670109d2017-06-09 14:04:03 +00001648 if (getTok().getString().empty() || getTok().getString().front() == '\r' ||
Nirav Davefd910412016-06-17 16:06:17 +00001649 getTok().getString().front() == '\n')
1650 Out.AddBlankLine();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001651 Lex();
Chris Lattner36e02122009-06-21 20:54:55 +00001652 return false;
Chris Lattner36e02122009-06-21 20:54:55 +00001653 }
Nirav Davefd910412016-06-17 16:06:17 +00001654 // Statements always start with an identifier.
Sean Callanan936b0d32010-01-19 21:44:56 +00001655 AsmToken ID = getTok();
Daniel Dunbaree4465c2009-07-28 16:38:40 +00001656 SMLoc IDLoc = ID.getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001657 StringRef IDVal;
Kevin Enderby0510b482010-05-17 23:08:19 +00001658 int64_t LocalLabelVal = -1;
Nirav Davefd910412016-06-17 16:06:17 +00001659 if (Lexer.is(AsmToken::HashDirective))
Jim Grosbach4b905842013-09-20 23:08:21 +00001660 return parseCppHashLineFilenameComment(IDLoc);
Kevin Enderbyfa3c6f12010-12-24 00:12:02 +00001661 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderby0510b482010-05-17 23:08:19 +00001662 if (Lexer.is(AsmToken::Integer)) {
1663 LocalLabelVal = getTok().getIntVal();
1664 if (LocalLabelVal < 0) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001665 if (!TheCondState.Ignore) {
1666 Lex(); // always eat a token
1667 return Error(IDLoc, "unexpected token at start of statement");
1668 }
Kevin Enderby0510b482010-05-17 23:08:19 +00001669 IDVal = "";
Eli Bendersky88024712013-01-16 19:32:36 +00001670 } else {
Kevin Enderby0510b482010-05-17 23:08:19 +00001671 IDVal = getTok().getString();
1672 Lex(); // Consume the integer token to be used as an identifier token.
1673 if (Lexer.getKind() != AsmToken::Colon) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001674 if (!TheCondState.Ignore) {
1675 Lex(); // always eat a token
1676 return Error(IDLoc, "unexpected token at start of statement");
1677 }
Kevin Enderby0510b482010-05-17 23:08:19 +00001678 }
1679 }
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001680 } else if (Lexer.is(AsmToken::Dot)) {
1681 // Treat '.' as a valid identifier in this context.
1682 Lex();
1683 IDVal = ".";
Colin LeMahieu8a0453e2015-11-09 00:31:07 +00001684 } else if (Lexer.is(AsmToken::LCurly)) {
1685 // Treat '{' as a valid identifier in this context.
1686 Lex();
1687 IDVal = "{";
1688
1689 } else if (Lexer.is(AsmToken::RCurly)) {
1690 // Treat '}' as a valid identifier in this context.
1691 Lex();
1692 IDVal = "}";
Yonghong Song06ff6552017-09-12 17:55:23 +00001693 } else if (Lexer.is(AsmToken::Star) &&
1694 getTargetParser().starIsStartOfStatement()) {
1695 // Accept '*' as a valid start of statement.
1696 Lex();
1697 IDVal = "*";
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001698 } else if (parseIdentifier(IDVal)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001699 if (!TheCondState.Ignore) {
1700 Lex(); // always eat a token
1701 return Error(IDLoc, "unexpected token at start of statement");
1702 }
Chris Lattner926885c2010-04-17 18:14:27 +00001703 IDVal = "";
1704 }
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001705
Chris Lattner926885c2010-04-17 18:14:27 +00001706 // Handle conditional assembly here before checking for skipping. We
1707 // have to do this so that .endif isn't skipped in a ".if 0" block for
1708 // example.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001709 StringMap<DirectiveKind>::const_iterator DirKindIt =
Jim Grosbach4b905842013-09-20 23:08:21 +00001710 DirectiveKindMap.find(IDVal);
1711 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1712 ? DK_NO_DIRECTIVE
1713 : DirKindIt->getValue();
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001714 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001715 default:
1716 break;
1717 case DK_IF:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001718 case DK_IFEQ:
1719 case DK_IFGE:
1720 case DK_IFGT:
1721 case DK_IFLE:
1722 case DK_IFLT:
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00001723 case DK_IFNE:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001724 return parseDirectiveIf(IDLoc, DirKind);
Jim Grosbach4b905842013-09-20 23:08:21 +00001725 case DK_IFB:
1726 return parseDirectiveIfb(IDLoc, true);
1727 case DK_IFNB:
1728 return parseDirectiveIfb(IDLoc, false);
1729 case DK_IFC:
1730 return parseDirectiveIfc(IDLoc, true);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00001731 case DK_IFEQS:
Sid Manning51c35602015-03-18 14:20:54 +00001732 return parseDirectiveIfeqs(IDLoc, true);
Jim Grosbach4b905842013-09-20 23:08:21 +00001733 case DK_IFNC:
1734 return parseDirectiveIfc(IDLoc, false);
Sid Manning51c35602015-03-18 14:20:54 +00001735 case DK_IFNES:
1736 return parseDirectiveIfeqs(IDLoc, false);
Jim Grosbach4b905842013-09-20 23:08:21 +00001737 case DK_IFDEF:
1738 return parseDirectiveIfdef(IDLoc, true);
1739 case DK_IFNDEF:
1740 case DK_IFNOTDEF:
1741 return parseDirectiveIfdef(IDLoc, false);
1742 case DK_ELSEIF:
1743 return parseDirectiveElseIf(IDLoc);
1744 case DK_ELSE:
1745 return parseDirectiveElse(IDLoc);
1746 case DK_ENDIF:
1747 return parseDirectiveEndIf(IDLoc);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001748 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001749
Eli Bendersky88024712013-01-16 19:32:36 +00001750 // Ignore the statement if in the middle of inactive conditional
1751 // (e.g. ".if 0").
Chad Rosiereda70b32012-10-20 00:47:08 +00001752 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001753 eatToEndOfStatement();
Chris Lattner926885c2010-04-17 18:14:27 +00001754 return false;
1755 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001756
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001757 // FIXME: Recurse on local labels?
1758
1759 // See what kind of statement we have.
1760 switch (Lexer.getKind()) {
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001761 case AsmToken::Colon: {
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001762 if (!getTargetParser().isLabel(ID))
1763 break;
Nirav Davef43cc9f2016-10-10 15:24:54 +00001764 if (checkForValidSection())
1765 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00001766
Chris Lattner36e02122009-06-21 20:54:55 +00001767 // identifier ':' -> Label.
Sean Callanan686ed8d2010-01-19 20:22:31 +00001768 Lex();
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001769
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001770 // Diagnose attempt to use '.' as a label.
1771 if (IDVal == ".")
1772 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1773
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001774 // Diagnose attempt to use a variable as a label.
1775 //
1776 // FIXME: Diagnostics. Note the location of the definition as a label.
1777 // FIXME: This doesn't diagnose assignment to a symbol which has been
1778 // implicitly marked as external.
Kevin Enderby0510b482010-05-17 23:08:19 +00001779 MCSymbol *Sym;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001780 if (LocalLabelVal == -1) {
1781 if (ParsingInlineAsm && SI) {
Nico Weber67e715f2015-06-19 23:43:47 +00001782 StringRef RewrittenLabel =
1783 SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true);
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00001784 assert(!RewrittenLabel.empty() &&
Nico Weber67e715f2015-06-19 23:43:47 +00001785 "We should have an internal name here.");
Craig Topper7d5b2312015-10-10 05:25:02 +00001786 Info.AsmRewrites->emplace_back(AOK_Label, IDLoc, IDVal.size(),
1787 RewrittenLabel);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001788 IDVal = RewrittenLabel;
1789 }
Jim Grosbach6f482002015-05-18 18:43:14 +00001790 Sym = getContext().getOrCreateSymbol(IDVal);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001791 } else
Jim Grosbach6f482002015-05-18 18:43:14 +00001792 Sym = Ctx.createDirectionalLocalSymbol(LocalLabelVal);
Nirav Dave9263ae32016-08-02 19:17:54 +00001793 // End of Labels should be treated as end of line for lexing
1794 // purposes but that information is not available to the Lexer who
1795 // does not understand Labels. This may cause us to see a Hash
1796 // here instead of a preprocessor line comment.
1797 if (getTok().is(AsmToken::Hash)) {
1798 StringRef CommentStr = parseStringToEndOfStatement();
1799 Lexer.Lex();
1800 Lexer.UnLex(AsmToken(AsmToken::EndOfStatement, CommentStr));
1801 }
1802
Nirav Dave8ea792d2016-07-13 14:03:12 +00001803 // Consume any end of statement token, if present, to avoid spurious
1804 // AddBlankLine calls().
1805 if (getTok().is(AsmToken::EndOfStatement)) {
1806 Lex();
1807 }
1808
Daniel Dunbare73b2672009-08-26 22:13:22 +00001809 // Emit the label.
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +00001810 if (!getTargetParser().isParsingInlineAsm())
Rafael Espindolabe991572017-02-10 15:13:12 +00001811 Out.EmitLabel(Sym, IDLoc);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001812
Kevin Enderbye7739d42011-12-09 18:09:40 +00001813 // If we are generating dwarf for assembly source files then gather the
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001814 // info to make a dwarf label entry for this label if needed.
Paul Robinson938d9a02018-03-22 15:48:01 +00001815 if (enabledGenDwarfForAssembly())
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001816 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1817 IDLoc);
Kevin Enderbye7739d42011-12-09 18:09:40 +00001818
Tim Northover1744d0a2013-10-25 12:49:50 +00001819 getTargetParser().onLabelParsed(Sym);
1820
Eli Friedman0f4871d2012-10-22 23:58:19 +00001821 return false;
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001822 }
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001823
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001824 case AsmToken::Equal:
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001825 if (!getTargetParser().equalIsAsmAssignment())
1826 break;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001827 // identifier '=' ... -> assignment statement
Sean Callanan686ed8d2010-01-19 20:22:31 +00001828 Lex();
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001829
Nirav Dave7fd992a2018-08-16 16:31:14 +00001830 return parseAssignment(IDVal, true);
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001831
1832 default: // Normal instruction or directive.
1833 break;
Chris Lattner36e02122009-06-21 20:54:55 +00001834 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001835
1836 // If macros are enabled, check to see if this is a macro instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00001837 if (areMacrosEnabled())
Rafael Espindola22c38a02018-02-14 16:34:27 +00001838 if (const MCAsmMacro *M = getContext().lookupMacro(IDVal)) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001839 return handleMacroEntry(M, IDLoc);
Eli Bendersky38274122013-01-14 23:22:36 +00001840 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001841
Michael J. Spencer530ce852010-10-09 11:00:50 +00001842 // Otherwise, we have a normal instruction or directive.
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001843
Eli Bendersky17233942013-01-15 22:59:42 +00001844 // Directives start with "."
Ana Pazos353f67a2018-08-25 01:34:32 +00001845 if (IDVal.startswith(".") && IDVal != ".") {
Eli Bendersky17233942013-01-15 22:59:42 +00001846 // There are several entities interested in parsing directives:
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001847 //
Eli Bendersky17233942013-01-15 22:59:42 +00001848 // 1. The target-specific assembly parser. Some directives are target
1849 // specific or may potentially behave differently on certain targets.
1850 // 2. Asm parser extensions. For example, platform-specific parsers
1851 // (like the ELF parser) register themselves as extensions.
1852 // 3. The generic directive parser implemented by this class. These are
1853 // all the directives that behave in a target and platform independent
1854 // manner, or at least have a default behavior that's shared between
1855 // all targets and platforms.
Akira Hatanakad3590752012-07-05 19:09:33 +00001856
Oliver Stannard21718282016-07-26 14:19:47 +00001857 getTargetParser().flushPendingInstructions(getStreamer());
1858
Nirav Dave2364748a2016-09-16 18:30:20 +00001859 SMLoc StartTokLoc = getTok().getLoc();
1860 bool TPDirectiveReturn = getTargetParser().ParseDirective(ID);
1861
1862 if (hasPendingError())
1863 return true;
1864 // Currently the return value should be true if we are
1865 // uninterested but as this is at odds with the standard parsing
1866 // convention (return true = error) we have instances of a parsed
1867 // directive that fails returning true as an error. Catch these
1868 // cases as best as possible errors here.
1869 if (TPDirectiveReturn && StartTokLoc != getTok().getLoc())
1870 return true;
1871 // Return if we did some parsing or believe we succeeded.
1872 if (!TPDirectiveReturn || StartTokLoc != getTok().getLoc())
Akira Hatanakad3590752012-07-05 19:09:33 +00001873 return false;
1874
Alp Tokercb402912014-01-24 17:20:08 +00001875 // Next, check the extension directive map to see if any extension has
Eli Bendersky17233942013-01-15 22:59:42 +00001876 // registered itself to parse this directive.
Jim Grosbach4b905842013-09-20 23:08:21 +00001877 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1878 ExtensionDirectiveMap.lookup(IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +00001879 if (Handler.first)
1880 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1881
1882 // Finally, if no one else is interested in this directive, it must be
1883 // generic and familiar to this class.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001884 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001885 default:
1886 break;
1887 case DK_SET:
1888 case DK_EQU:
1889 return parseDirectiveSet(IDVal, true);
1890 case DK_EQUIV:
1891 return parseDirectiveSet(IDVal, false);
1892 case DK_ASCII:
1893 return parseDirectiveAscii(IDVal, false);
1894 case DK_ASCIZ:
1895 case DK_STRING:
1896 return parseDirectiveAscii(IDVal, true);
1897 case DK_BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001898 case DK_DC_B:
1899 return parseDirectiveValue(IDVal, 1);
1900 case DK_DC:
1901 case DK_DC_W:
Jim Grosbach4b905842013-09-20 23:08:21 +00001902 case DK_SHORT:
1903 case DK_VALUE:
1904 case DK_2BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001905 return parseDirectiveValue(IDVal, 2);
Jim Grosbach4b905842013-09-20 23:08:21 +00001906 case DK_LONG:
1907 case DK_INT:
1908 case DK_4BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001909 case DK_DC_L:
1910 return parseDirectiveValue(IDVal, 4);
Jim Grosbach4b905842013-09-20 23:08:21 +00001911 case DK_QUAD:
1912 case DK_8BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001913 return parseDirectiveValue(IDVal, 8);
1914 case DK_DC_A:
Konstantin Zhuravlyovdc77b2e2017-04-17 17:41:25 +00001915 return parseDirectiveValue(
1916 IDVal, getContext().getAsmInfo()->getCodePointerSize());
David Woodhoused6de0d92014-02-01 16:20:59 +00001917 case DK_OCTA:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001918 return parseDirectiveOctaValue(IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001919 case DK_SINGLE:
1920 case DK_FLOAT:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001921 case DK_DC_S:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001922 return parseDirectiveRealValue(IDVal, APFloat::IEEEsingle());
Jim Grosbach4b905842013-09-20 23:08:21 +00001923 case DK_DOUBLE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001924 case DK_DC_D:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001925 return parseDirectiveRealValue(IDVal, APFloat::IEEEdouble());
Jim Grosbach4b905842013-09-20 23:08:21 +00001926 case DK_ALIGN: {
1927 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1928 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1929 }
1930 case DK_ALIGN32: {
1931 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1932 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1933 }
1934 case DK_BALIGN:
1935 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1936 case DK_BALIGNW:
1937 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1938 case DK_BALIGNL:
1939 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1940 case DK_P2ALIGN:
1941 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1942 case DK_P2ALIGNW:
1943 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1944 case DK_P2ALIGNL:
1945 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1946 case DK_ORG:
1947 return parseDirectiveOrg();
1948 case DK_FILL:
1949 return parseDirectiveFill();
1950 case DK_ZERO:
1951 return parseDirectiveZero();
1952 case DK_EXTERN:
1953 eatToEndOfStatement(); // .extern is the default, ignore it.
1954 return false;
1955 case DK_GLOBL:
1956 case DK_GLOBAL:
1957 return parseDirectiveSymbolAttribute(MCSA_Global);
1958 case DK_LAZY_REFERENCE:
1959 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1960 case DK_NO_DEAD_STRIP:
1961 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1962 case DK_SYMBOL_RESOLVER:
1963 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1964 case DK_PRIVATE_EXTERN:
1965 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1966 case DK_REFERENCE:
1967 return parseDirectiveSymbolAttribute(MCSA_Reference);
1968 case DK_WEAK_DEFINITION:
1969 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1970 case DK_WEAK_REFERENCE:
1971 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1972 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1973 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1974 case DK_COMM:
1975 case DK_COMMON:
1976 return parseDirectiveComm(/*IsLocal=*/false);
1977 case DK_LCOMM:
1978 return parseDirectiveComm(/*IsLocal=*/true);
1979 case DK_ABORT:
1980 return parseDirectiveAbort();
1981 case DK_INCLUDE:
1982 return parseDirectiveInclude();
1983 case DK_INCBIN:
1984 return parseDirectiveIncbin();
1985 case DK_CODE16:
1986 case DK_CODE16GCC:
Nirav Davefd910412016-06-17 16:06:17 +00001987 return TokError(Twine(IDVal) +
1988 " not currently supported for this target");
Jim Grosbach4b905842013-09-20 23:08:21 +00001989 case DK_REPT:
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00001990 return parseDirectiveRept(IDLoc, IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001991 case DK_IRP:
1992 return parseDirectiveIrp(IDLoc);
1993 case DK_IRPC:
1994 return parseDirectiveIrpc(IDLoc);
1995 case DK_ENDR:
1996 return parseDirectiveEndr(IDLoc);
1997 case DK_BUNDLE_ALIGN_MODE:
1998 return parseDirectiveBundleAlignMode();
1999 case DK_BUNDLE_LOCK:
2000 return parseDirectiveBundleLock();
2001 case DK_BUNDLE_UNLOCK:
2002 return parseDirectiveBundleUnlock();
2003 case DK_SLEB128:
2004 return parseDirectiveLEB128(true);
2005 case DK_ULEB128:
2006 return parseDirectiveLEB128(false);
2007 case DK_SPACE:
2008 case DK_SKIP:
2009 return parseDirectiveSpace(IDVal);
2010 case DK_FILE:
2011 return parseDirectiveFile(IDLoc);
2012 case DK_LINE:
2013 return parseDirectiveLine();
2014 case DK_LOC:
2015 return parseDirectiveLoc();
2016 case DK_STABS:
2017 return parseDirectiveStabs();
Reid Kleckner2214ed82016-01-29 00:49:42 +00002018 case DK_CV_FILE:
2019 return parseDirectiveCVFile();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00002020 case DK_CV_FUNC_ID:
2021 return parseDirectiveCVFuncId();
2022 case DK_CV_INLINE_SITE_ID:
2023 return parseDirectiveCVInlineSiteId();
Reid Kleckner2214ed82016-01-29 00:49:42 +00002024 case DK_CV_LOC:
2025 return parseDirectiveCVLoc();
2026 case DK_CV_LINETABLE:
2027 return parseDirectiveCVLinetable();
David Majnemer6fcbd7e2016-01-29 19:24:12 +00002028 case DK_CV_INLINE_LINETABLE:
2029 return parseDirectiveCVInlineLinetable();
David Majnemer408b5e62016-02-05 01:55:49 +00002030 case DK_CV_DEF_RANGE:
2031 return parseDirectiveCVDefRange();
Reid Kleckner2214ed82016-01-29 00:49:42 +00002032 case DK_CV_STRINGTABLE:
2033 return parseDirectiveCVStringTable();
2034 case DK_CV_FILECHECKSUMS:
2035 return parseDirectiveCVFileChecksums();
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00002036 case DK_CV_FILECHECKSUM_OFFSET:
2037 return parseDirectiveCVFileChecksumOffset();
Reid Kleckner9cdd4df2017-10-11 21:24:33 +00002038 case DK_CV_FPO_DATA:
2039 return parseDirectiveCVFPOData();
Jim Grosbach4b905842013-09-20 23:08:21 +00002040 case DK_CFI_SECTIONS:
2041 return parseDirectiveCFISections();
2042 case DK_CFI_STARTPROC:
2043 return parseDirectiveCFIStartProc();
2044 case DK_CFI_ENDPROC:
2045 return parseDirectiveCFIEndProc();
2046 case DK_CFI_DEF_CFA:
2047 return parseDirectiveCFIDefCfa(IDLoc);
2048 case DK_CFI_DEF_CFA_OFFSET:
2049 return parseDirectiveCFIDefCfaOffset();
2050 case DK_CFI_ADJUST_CFA_OFFSET:
2051 return parseDirectiveCFIAdjustCfaOffset();
2052 case DK_CFI_DEF_CFA_REGISTER:
2053 return parseDirectiveCFIDefCfaRegister(IDLoc);
2054 case DK_CFI_OFFSET:
2055 return parseDirectiveCFIOffset(IDLoc);
2056 case DK_CFI_REL_OFFSET:
2057 return parseDirectiveCFIRelOffset(IDLoc);
2058 case DK_CFI_PERSONALITY:
2059 return parseDirectiveCFIPersonalityOrLsda(true);
2060 case DK_CFI_LSDA:
2061 return parseDirectiveCFIPersonalityOrLsda(false);
2062 case DK_CFI_REMEMBER_STATE:
2063 return parseDirectiveCFIRememberState();
2064 case DK_CFI_RESTORE_STATE:
2065 return parseDirectiveCFIRestoreState();
2066 case DK_CFI_SAME_VALUE:
2067 return parseDirectiveCFISameValue(IDLoc);
2068 case DK_CFI_RESTORE:
2069 return parseDirectiveCFIRestore(IDLoc);
2070 case DK_CFI_ESCAPE:
2071 return parseDirectiveCFIEscape();
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +00002072 case DK_CFI_RETURN_COLUMN:
2073 return parseDirectiveCFIReturnColumn(IDLoc);
Jim Grosbach4b905842013-09-20 23:08:21 +00002074 case DK_CFI_SIGNAL_FRAME:
2075 return parseDirectiveCFISignalFrame();
2076 case DK_CFI_UNDEFINED:
2077 return parseDirectiveCFIUndefined(IDLoc);
2078 case DK_CFI_REGISTER:
2079 return parseDirectiveCFIRegister(IDLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00002080 case DK_CFI_WINDOW_SAVE:
2081 return parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +00002082 case DK_MACROS_ON:
2083 case DK_MACROS_OFF:
2084 return parseDirectiveMacrosOnOff(IDVal);
2085 case DK_MACRO:
2086 return parseDirectiveMacro(IDLoc);
Michael Zuckerman56704612017-05-01 13:20:12 +00002087 case DK_ALTMACRO:
2088 case DK_NOALTMACRO:
2089 return parseDirectiveAltmacro(IDVal);
Nico Weber155dccd12014-07-24 17:08:39 +00002090 case DK_EXITM:
2091 return parseDirectiveExitMacro(IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00002092 case DK_ENDM:
2093 case DK_ENDMACRO:
2094 return parseDirectiveEndMacro(IDVal);
2095 case DK_PURGEM:
2096 return parseDirectivePurgeMacro(IDLoc);
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00002097 case DK_END:
2098 return parseDirectiveEnd(IDLoc);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00002099 case DK_ERR:
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00002100 return parseDirectiveError(IDLoc, false);
2101 case DK_ERROR:
2102 return parseDirectiveError(IDLoc, true);
Nico Weber404012b2014-07-24 16:26:06 +00002103 case DK_WARNING:
2104 return parseDirectiveWarning(IDLoc);
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002105 case DK_RELOC:
2106 return parseDirectiveReloc(IDLoc);
Petr Hosek4cb08ce2016-09-23 19:25:15 +00002107 case DK_DCB:
2108 case DK_DCB_W:
2109 return parseDirectiveDCB(IDVal, 2);
2110 case DK_DCB_B:
2111 return parseDirectiveDCB(IDVal, 1);
2112 case DK_DCB_D:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002113 return parseDirectiveRealDCB(IDVal, APFloat::IEEEdouble());
Petr Hosek4cb08ce2016-09-23 19:25:15 +00002114 case DK_DCB_L:
2115 return parseDirectiveDCB(IDVal, 4);
2116 case DK_DCB_S:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002117 return parseDirectiveRealDCB(IDVal, APFloat::IEEEsingle());
Petr Hosek731bb9c2016-08-23 21:34:53 +00002118 case DK_DC_X:
Petr Hosek4cb08ce2016-09-23 19:25:15 +00002119 case DK_DCB_X:
Petr Hosek731bb9c2016-08-23 21:34:53 +00002120 return TokError(Twine(IDVal) +
2121 " not currently supported for this target");
Petr Hosek85b2f672016-09-23 21:53:36 +00002122 case DK_DS:
2123 case DK_DS_W:
2124 return parseDirectiveDS(IDVal, 2);
2125 case DK_DS_B:
2126 return parseDirectiveDS(IDVal, 1);
2127 case DK_DS_D:
2128 return parseDirectiveDS(IDVal, 8);
2129 case DK_DS_L:
2130 case DK_DS_S:
2131 return parseDirectiveDS(IDVal, 4);
2132 case DK_DS_P:
2133 case DK_DS_X:
2134 return parseDirectiveDS(IDVal, 12);
Coby Tayree01e53202017-10-02 14:36:31 +00002135 case DK_PRINT:
2136 return parseDirectivePrint(IDLoc);
Peter Collingbourne3e227332018-07-17 22:17:18 +00002137 case DK_ADDRSIG:
2138 return parseDirectiveAddrsig();
2139 case DK_ADDRSIG_SYM:
2140 return parseDirectiveAddrsigSym();
Eli Friedman20b02642010-07-19 04:17:25 +00002141 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002142
Jim Grosbach758e0cc2012-05-01 18:38:27 +00002143 return Error(IDLoc, "unknown directive");
Chris Lattnere5074c42009-06-22 01:29:09 +00002144 }
Chris Lattner36e02122009-06-21 20:54:55 +00002145
Chad Rosierc7f552c2013-02-12 21:33:51 +00002146 // __asm _emit or __asm __emit
2147 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
2148 IDVal == "_EMIT" || IDVal == "__EMIT"))
Jim Grosbach4b905842013-09-20 23:08:21 +00002149 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
Chad Rosierc7f552c2013-02-12 21:33:51 +00002150
2151 // __asm align
2152 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
Jim Grosbach4b905842013-09-20 23:08:21 +00002153 return parseDirectiveMSAlign(IDLoc, Info);
Eli Friedman0f4871d2012-10-22 23:58:19 +00002154
Coby Tayree3847be92017-04-04 17:57:23 +00002155 if (ParsingInlineAsm && (IDVal == "even" || IDVal == "EVEN"))
Michael Zuckerman02ecd432015-12-13 17:07:23 +00002156 Info.AsmRewrites->emplace_back(AOK_EVEN, IDLoc, 4);
Nirav Davef43cc9f2016-10-10 15:24:54 +00002157 if (checkForValidSection())
2158 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00002159
Chris Lattner7cbfa442010-05-19 23:34:33 +00002160 // Canonicalize the opcode to lower case.
Eli Bendersky88024712013-01-16 19:32:36 +00002161 std::string OpcodeStr = IDVal.lower();
Chad Rosierf0e87202012-10-25 20:41:34 +00002162 ParseInstructionInfo IInfo(Info.AsmRewrites);
Nirav Dave2364748a2016-09-16 18:30:20 +00002163 bool ParseHadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, ID,
2164 Info.ParsedOperands);
2165 Info.ParseError = ParseHadError;
Chris Lattnere5074c42009-06-22 01:29:09 +00002166
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002167 // Dump the parsed representation, if requested.
2168 if (getShowParsedOperands()) {
2169 SmallString<256> Str;
2170 raw_svector_ostream OS(Str);
2171 OS << "parsed instruction: [";
Eli Friedman0f4871d2012-10-22 23:58:19 +00002172 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002173 if (i != 0)
2174 OS << ", ";
Eli Friedman0f4871d2012-10-22 23:58:19 +00002175 Info.ParsedOperands[i]->print(OS);
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002176 }
2177 OS << "]";
2178
Jim Grosbach4b905842013-09-20 23:08:21 +00002179 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002180 }
2181
Nirav Dave2364748a2016-09-16 18:30:20 +00002182 // Fail even if ParseInstruction erroneously returns false.
2183 if (hasPendingError() || ParseHadError)
2184 return true;
2185
Oliver Stannard8b273082014-06-19 15:52:37 +00002186 // If we are generating dwarf for the current section then generate a .loc
2187 // directive for the instruction.
Paul Robinson938d9a02018-03-22 15:48:01 +00002188 if (!ParseHadError && enabledGenDwarfForAssembly() &&
Oliver Stannard8b273082014-06-19 15:52:37 +00002189 getContext().getGenDwarfSectionSyms().count(
Eric Christopher445c9522016-10-14 05:47:37 +00002190 getStreamer().getCurrentSectionOnly())) {
Saleem Abdulrasool4d6ed7c2014-12-24 06:32:43 +00002191 unsigned Line;
2192 if (ActiveMacros.empty())
2193 Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
2194 else
Frederic Riss16238d92015-06-25 21:57:33 +00002195 Line = SrcMgr.FindLineNumber(ActiveMacros.front()->InstantiationLoc,
2196 ActiveMacros.front()->ExitBuffer);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002197
Eli Bendersky88024712013-01-16 19:32:36 +00002198 // If we previously parsed a cpp hash file line comment then make sure the
2199 // current Dwarf File is for the CppHashFilename if not then emit the
2200 // Dwarf File table for it and adjust the line number for the .loc.
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00002201 if (!CppHashInfo.Filename.empty()) {
David Blaikiec714ef42014-03-17 01:52:11 +00002202 unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
Tim Northoverc0bef992016-04-13 19:46:54 +00002203 0, StringRef(), CppHashInfo.Filename);
David Blaikiec714ef42014-03-17 01:52:11 +00002204 getContext().setGenDwarfFileNumber(FileNumber);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002205
Graydon Hoare54fe2082018-04-07 00:44:02 +00002206 unsigned CppHashLocLineNo =
2207 SrcMgr.FindLineNumber(CppHashInfo.Loc, CppHashInfo.Buf);
Tim Northoverc0bef992016-04-13 19:46:54 +00002208 Line = CppHashInfo.LineNumber - 1 + (Line - CppHashLocLineNo);
Eli Bendersky88024712013-01-16 19:32:36 +00002209 }
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002210
Jim Grosbach4b905842013-09-20 23:08:21 +00002211 getStreamer().EmitDwarfLocDirective(
2212 getContext().getGenDwarfFileNumber(), Line, 0,
2213 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
2214 StringRef());
Kevin Enderby6469fc22011-11-01 22:27:22 +00002215 }
2216
Daniel Dunbarce0c1e12010-05-04 00:33:07 +00002217 // If parsing succeeded, match the instruction.
Nirav Dave2364748a2016-09-16 18:30:20 +00002218 if (!ParseHadError) {
Tim Northover26bb14e2014-08-18 11:49:42 +00002219 uint64_t ErrorInfo;
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +00002220 if (getTargetParser().MatchAndEmitInstruction(
2221 IDLoc, Info.Opcode, Info.ParsedOperands, Out, ErrorInfo,
2222 getTargetParser().isParsingInlineAsm()))
Nirav Dave2364748a2016-09-16 18:30:20 +00002223 return true;
Chad Rosier49963552012-10-13 00:26:04 +00002224 }
Chris Lattnera2a9d162010-09-11 16:18:25 +00002225 return false;
Chris Lattnerb0133452009-06-21 20:16:42 +00002226}
Chris Lattnerbedf6c22009-06-24 04:43:34 +00002227
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00002228// Parse and erase curly braces marking block start/end
Sam Cleggf009da22018-04-19 22:00:53 +00002229bool
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00002230AsmParser::parseCurlyBlockScope(SmallVectorImpl<AsmRewrite> &AsmStrRewrites) {
2231 // Identify curly brace marking block start/end
2232 if (Lexer.isNot(AsmToken::LCurly) && Lexer.isNot(AsmToken::RCurly))
2233 return false;
2234
2235 SMLoc StartLoc = Lexer.getLoc();
2236 Lex(); // Eat the brace
2237 if (Lexer.is(AsmToken::EndOfStatement))
2238 Lex(); // Eat EndOfStatement following the brace
2239
2240 // Erase the block start/end brace from the output asm string
2241 AsmStrRewrites.emplace_back(AOK_Skip, StartLoc, Lexer.getLoc().getPointer() -
2242 StartLoc.getPointer());
2243 return true;
2244}
2245
Jim Grosbach4b905842013-09-20 23:08:21 +00002246/// parseCppHashLineFilenameComment as this:
Kevin Enderby72553612011-09-13 23:45:18 +00002247/// ::= # number "filename"
Craig Topper3c76c522015-09-20 23:35:59 +00002248bool AsmParser::parseCppHashLineFilenameComment(SMLoc L) {
Kevin Enderby72553612011-09-13 23:45:18 +00002249 Lex(); // Eat the hash token.
Nirav Davefd910412016-06-17 16:06:17 +00002250 // Lexer only ever emits HashDirective if it fully formed if it's
2251 // done the checking already so this is an internal error.
2252 assert(getTok().is(AsmToken::Integer) &&
2253 "Lexing Cpp line comment: Expected Integer");
Kevin Enderby72553612011-09-13 23:45:18 +00002254 int64_t LineNumber = getTok().getIntVal();
Kevin Enderby72553612011-09-13 23:45:18 +00002255 Lex();
Nirav Davefd910412016-06-17 16:06:17 +00002256 assert(getTok().is(AsmToken::String) &&
2257 "Lexing Cpp line comment: Expected String");
Kevin Enderby72553612011-09-13 23:45:18 +00002258 StringRef Filename = getTok().getString();
Nirav Davefd910412016-06-17 16:06:17 +00002259 Lex();
Nirav Dave2364748a2016-09-16 18:30:20 +00002260
Kevin Enderby72553612011-09-13 23:45:18 +00002261 // Get rid of the enclosing quotes.
Jim Grosbach4b905842013-09-20 23:08:21 +00002262 Filename = Filename.substr(1, Filename.size() - 2);
Kevin Enderby72553612011-09-13 23:45:18 +00002263
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002264 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
Tim Northoverc0bef992016-04-13 19:46:54 +00002265 CppHashInfo.Loc = L;
2266 CppHashInfo.Filename = Filename;
2267 CppHashInfo.LineNumber = LineNumber;
2268 CppHashInfo.Buf = CurBuffer;
Kevin Enderby72553612011-09-13 23:45:18 +00002269 return false;
2270}
2271
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002272/// will use the last parsed cpp hash line filename comment
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002273/// for the Filename and LineNo if any in the diagnostic.
2274void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002275 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002276 raw_ostream &OS = errs();
2277
2278 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
Craig Topper3c76c522015-09-20 23:35:59 +00002279 SMLoc DiagLoc = Diag.getLoc();
Alp Tokera55b95b2014-07-06 10:33:31 +00002280 unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2281 unsigned CppHashBuf =
Tim Northoverc0bef992016-04-13 19:46:54 +00002282 Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashInfo.Loc);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002283
Jim Grosbach4b905842013-09-20 23:08:21 +00002284 // Like SourceMgr::printMessage() we need to print the include stack if any
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002285 // before printing the message.
Alp Tokera55b95b2014-07-06 10:33:31 +00002286 unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2287 if (!Parser->SavedDiagHandler && DiagCurBuffer &&
2288 DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002289 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
2290 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002291 }
2292
Eric Christophera7c32732012-12-18 00:30:54 +00002293 // If we have not parsed a cpp hash line filename comment or the source
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002294 // manager changed or buffer changed (like in a nested include) then just
2295 // print the normal diagnostic using its Filename and LineNo.
Tim Northoverc0bef992016-04-13 19:46:54 +00002296 if (!Parser->CppHashInfo.LineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002297 DiagBuf != CppHashBuf) {
Benjamin Kramer47f5e302011-10-16 10:48:29 +00002298 if (Parser->SavedDiagHandler)
2299 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
2300 else
Craig Topper353eda42014-04-24 06:44:33 +00002301 Diag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002302 return;
2303 }
2304
Eric Christophera7c32732012-12-18 00:30:54 +00002305 // Use the CppHashFilename and calculate a line number based on the
Tim Northoverc0bef992016-04-13 19:46:54 +00002306 // CppHashInfo.Loc and CppHashInfo.LineNumber relative to this Diag's SMLoc
2307 // for the diagnostic.
2308 const std::string &Filename = Parser->CppHashInfo.Filename;
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002309
2310 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
2311 int CppHashLocLineNo =
Tim Northoverc0bef992016-04-13 19:46:54 +00002312 Parser->SrcMgr.FindLineNumber(Parser->CppHashInfo.Loc, CppHashBuf);
Jim Grosbach4b905842013-09-20 23:08:21 +00002313 int LineNo =
Tim Northoverc0bef992016-04-13 19:46:54 +00002314 Parser->CppHashInfo.LineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002315
Jim Grosbach4b905842013-09-20 23:08:21 +00002316 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
2317 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
Chris Lattner72845262011-10-16 05:47:55 +00002318 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002319
Benjamin Kramer47f5e302011-10-16 10:48:29 +00002320 if (Parser->SavedDiagHandler)
2321 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
2322 else
Craig Topper353eda42014-04-24 06:44:33 +00002323 NewDiag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002324}
2325
Rafael Espindola2c064482012-08-21 18:29:30 +00002326// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
2327// difference being that that function accepts '@' as part of identifiers and
2328// we can't do that. AsmLexer.cpp should probably be changed to handle
2329// '@' as a special case when needed.
2330static bool isIdentifierChar(char c) {
Guy Benyei83c74e92013-02-12 21:21:59 +00002331 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
2332 c == '.';
Rafael Espindola2c064482012-08-21 18:29:30 +00002333}
2334
Rafael Espindola34b9c512012-06-03 23:57:14 +00002335bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00002336 ArrayRef<MCAsmMacroParameter> Parameters,
Toma Tabacu217116e2015-04-27 10:50:29 +00002337 ArrayRef<MCAsmMacroArgument> A,
Craig Topper3c76c522015-09-20 23:35:59 +00002338 bool EnableAtPseudoVariable, SMLoc L) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00002339 unsigned NParameters = Parameters.size();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002340 bool HasVararg = NParameters ? Parameters.back().Vararg : false;
Benjamin Kramer513e7442014-02-20 13:36:32 +00002341 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
Rafael Espindola1134ab232011-06-05 02:43:45 +00002342 return Error(L, "Wrong number of arguments");
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002343
Preston Gurd05500642012-09-19 20:36:12 +00002344 // A macro without parameters is handled differently on Darwin:
2345 // gas accepts no arguments and does no substitutions
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002346 while (!Body.empty()) {
2347 // Scan for the next substitution.
2348 std::size_t End = Body.size(), Pos = 0;
2349 for (; Pos != End; ++Pos) {
2350 // Check for a substitution or escape.
Benjamin Kramer513e7442014-02-20 13:36:32 +00002351 if (IsDarwin && !NParameters) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00002352 // This macro has no parameters, look for $0, $1, etc.
2353 if (Body[Pos] != '$' || Pos + 1 == End)
2354 continue;
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002355
Rafael Espindola1134ab232011-06-05 02:43:45 +00002356 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00002357 if (Next == '$' || Next == 'n' ||
2358 isdigit(static_cast<unsigned char>(Next)))
Rafael Espindola1134ab232011-06-05 02:43:45 +00002359 break;
2360 } else {
2361 // This macro has parameters, look for \foo, \bar, etc.
2362 if (Body[Pos] == '\\' && Pos + 1 != End)
2363 break;
2364 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002365 }
2366
2367 // Add the prefix.
2368 OS << Body.slice(0, Pos);
2369
2370 // Check if we reached the end.
2371 if (Pos == End)
2372 break;
2373
Benjamin Kramer513e7442014-02-20 13:36:32 +00002374 if (IsDarwin && !NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002375 switch (Body[Pos + 1]) {
2376 // $$ => $
Rafael Espindola1134ab232011-06-05 02:43:45 +00002377 case '$':
2378 OS << '$';
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002379 break;
2380
Jim Grosbach4b905842013-09-20 23:08:21 +00002381 // $n => number of arguments
Rafael Espindola1134ab232011-06-05 02:43:45 +00002382 case 'n':
2383 OS << A.size();
2384 break;
2385
Jim Grosbach4b905842013-09-20 23:08:21 +00002386 // $[0-9] => argument
Rafael Espindola1134ab232011-06-05 02:43:45 +00002387 default: {
2388 // Missing arguments are ignored.
Jim Grosbach4b905842013-09-20 23:08:21 +00002389 unsigned Index = Body[Pos + 1] - '0';
Rafael Espindola1134ab232011-06-05 02:43:45 +00002390 if (Index >= A.size())
2391 break;
2392
2393 // Otherwise substitute with the token values, with spaces eliminated.
Craig Topper84008482015-10-10 05:38:14 +00002394 for (const AsmToken &Token : A[Index])
2395 OS << Token.getString();
Rafael Espindola1134ab232011-06-05 02:43:45 +00002396 break;
2397 }
2398 }
2399 Pos += 2;
2400 } else {
2401 unsigned I = Pos + 1;
Toma Tabacu217116e2015-04-27 10:50:29 +00002402
2403 // Check for the \@ pseudo-variable.
2404 if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End)
Rafael Espindola1134ab232011-06-05 02:43:45 +00002405 ++I;
Toma Tabacu217116e2015-04-27 10:50:29 +00002406 else
2407 while (isIdentifierChar(Body[I]) && I + 1 != End)
2408 ++I;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002409
Jim Grosbach4b905842013-09-20 23:08:21 +00002410 const char *Begin = Body.data() + Pos + 1;
2411 StringRef Argument(Begin, I - (Pos + 1));
Rafael Espindola1134ab232011-06-05 02:43:45 +00002412 unsigned Index = 0;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002413
Toma Tabacu217116e2015-04-27 10:50:29 +00002414 if (Argument == "@") {
2415 OS << NumOfMacroInstantiations;
2416 Pos += 2;
Preston Gurd05500642012-09-19 20:36:12 +00002417 } else {
Toma Tabacu217116e2015-04-27 10:50:29 +00002418 for (; Index < NParameters; ++Index)
2419 if (Parameters[Index].Name == Argument)
2420 break;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002421
Toma Tabacu217116e2015-04-27 10:50:29 +00002422 if (Index == NParameters) {
2423 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
2424 Pos += 3;
2425 else {
2426 OS << '\\' << Argument;
2427 Pos = I;
2428 }
2429 } else {
2430 bool VarargParameter = HasVararg && Index == (NParameters - 1);
Craig Topper84008482015-10-10 05:38:14 +00002431 for (const AsmToken &Token : A[Index])
Michael Zuckerman56704612017-05-01 13:20:12 +00002432 // For altmacro mode, you can write '%expr'.
2433 // The prefix '%' evaluates the expression 'expr'
2434 // and uses the result as a string (e.g. replace %(1+2) with the string "3").
2435 // Here, we identify the integer token which is the result of the
2436 // absolute expression evaluation and replace it with its string representation.
2437 if ((Lexer.IsaAltMacroMode()) &&
2438 (*(Token.getString().begin()) == '%') && Token.is(AsmToken::Integer))
2439 // Emit an integer value to the buffer.
2440 OS << Token.getIntVal();
Michael Zuckerman1f1a9122017-05-10 13:08:11 +00002441 // Only Token that was validated as a string and begins with '<'
2442 // is considered altMacroString!!!
2443 else if ((Lexer.IsaAltMacroMode()) &&
2444 (*(Token.getString().begin()) == '<') &&
2445 Token.is(AsmToken::String)) {
2446 std::string Res;
2447 altMacroString(Token.getStringContents(), Res);
2448 OS << Res;
2449 }
Toma Tabacu217116e2015-04-27 10:50:29 +00002450 // We expect no quotes around the string's contents when
2451 // parsing for varargs.
Michael Zuckerman56704612017-05-01 13:20:12 +00002452 else if (Token.isNot(AsmToken::String) || VarargParameter)
Craig Topper84008482015-10-10 05:38:14 +00002453 OS << Token.getString();
Toma Tabacu217116e2015-04-27 10:50:29 +00002454 else
Craig Topper84008482015-10-10 05:38:14 +00002455 OS << Token.getStringContents();
Toma Tabacu217116e2015-04-27 10:50:29 +00002456
2457 Pos += 1 + Argument.size();
2458 }
Preston Gurd05500642012-09-19 20:36:12 +00002459 }
Rafael Espindola1134ab232011-06-05 02:43:45 +00002460 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002461 // Update the scan point.
Rafael Espindola1134ab232011-06-05 02:43:45 +00002462 Body = Body.substr(Pos);
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002463 }
Daniel Dunbar43235712010-07-18 18:54:11 +00002464
Rafael Espindola1134ab232011-06-05 02:43:45 +00002465 return false;
2466}
Daniel Dunbar43235712010-07-18 18:54:11 +00002467
Nico Weber2a8f9222014-07-24 16:29:04 +00002468MacroInstantiation::MacroInstantiation(SMLoc IL, int EB, SMLoc EL,
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002469 size_t CondStackDepth)
Rafael Espindolaf43a94e2014-08-17 22:48:55 +00002470 : InstantiationLoc(IL), ExitBuffer(EB), ExitLoc(EL),
Nico Weber155dccd12014-07-24 17:08:39 +00002471 CondStackDepth(CondStackDepth) {}
Daniel Dunbar43235712010-07-18 18:54:11 +00002472
Jim Grosbach4b905842013-09-20 23:08:21 +00002473static bool isOperator(AsmToken::TokenKind kind) {
2474 switch (kind) {
2475 default:
2476 return false;
2477 case AsmToken::Plus:
2478 case AsmToken::Minus:
2479 case AsmToken::Tilde:
2480 case AsmToken::Slash:
2481 case AsmToken::Star:
2482 case AsmToken::Dot:
2483 case AsmToken::Equal:
2484 case AsmToken::EqualEqual:
2485 case AsmToken::Pipe:
2486 case AsmToken::PipePipe:
2487 case AsmToken::Caret:
2488 case AsmToken::Amp:
2489 case AsmToken::AmpAmp:
2490 case AsmToken::Exclaim:
2491 case AsmToken::ExclaimEqual:
Jim Grosbach4b905842013-09-20 23:08:21 +00002492 case AsmToken::Less:
2493 case AsmToken::LessEqual:
2494 case AsmToken::LessLess:
2495 case AsmToken::LessGreater:
2496 case AsmToken::Greater:
2497 case AsmToken::GreaterEqual:
2498 case AsmToken::GreaterGreater:
2499 return true;
Preston Gurd05500642012-09-19 20:36:12 +00002500 }
2501}
2502
David Majnemer16252452014-01-29 00:07:39 +00002503namespace {
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002504
David Majnemer16252452014-01-29 00:07:39 +00002505class AsmLexerSkipSpaceRAII {
2506public:
2507 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
2508 Lexer.setSkipSpace(SkipSpace);
2509 }
2510
2511 ~AsmLexerSkipSpaceRAII() {
2512 Lexer.setSkipSpace(true);
2513 }
2514
2515private:
2516 AsmLexer &Lexer;
2517};
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002518
2519} // end anonymous namespace
David Majnemer16252452014-01-29 00:07:39 +00002520
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002521bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
2522
2523 if (Vararg) {
2524 if (Lexer.isNot(AsmToken::EndOfStatement)) {
2525 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002526 MA.emplace_back(AsmToken::String, Str);
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002527 }
2528 return false;
2529 }
2530
Rafael Espindola768b41c2012-06-15 14:02:34 +00002531 unsigned ParenLevel = 0;
Preston Gurd05500642012-09-19 20:36:12 +00002532
David Majnemer16252452014-01-29 00:07:39 +00002533 // Darwin doesn't use spaces to delmit arguments.
2534 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
Rafael Espindola768b41c2012-06-15 14:02:34 +00002535
Scott Egertona1fa68a2016-02-11 13:48:49 +00002536 bool SpaceEaten;
2537
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002538 while (true) {
Scott Egertona1fa68a2016-02-11 13:48:49 +00002539 SpaceEaten = false;
David Majnemer16252452014-01-29 00:07:39 +00002540 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002541 return TokError("unexpected token in macro instantiation");
Preston Gurd05500642012-09-19 20:36:12 +00002542
Scott Egertona1fa68a2016-02-11 13:48:49 +00002543 if (ParenLevel == 0) {
Preston Gurd05500642012-09-19 20:36:12 +00002544
Scott Egertona1fa68a2016-02-11 13:48:49 +00002545 if (Lexer.is(AsmToken::Comma))
2546 break;
2547
2548 if (Lexer.is(AsmToken::Space)) {
2549 SpaceEaten = true;
Nirav Dave1180e6892016-06-02 17:15:05 +00002550 Lexer.Lex(); // Eat spaces
Scott Egertona1fa68a2016-02-11 13:48:49 +00002551 }
Preston Gurd05500642012-09-19 20:36:12 +00002552
2553 // Spaces can delimit parameters, but could also be part an expression.
2554 // If the token after a space is an operator, add the token and the next
2555 // one into this argument
David Majnemer91fc4c22014-01-29 18:57:46 +00002556 if (!IsDarwin) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002557 if (isOperator(Lexer.getKind())) {
Scott Egertona1fa68a2016-02-11 13:48:49 +00002558 MA.push_back(getTok());
Nirav Dave1180e6892016-06-02 17:15:05 +00002559 Lexer.Lex();
Preston Gurd05500642012-09-19 20:36:12 +00002560
Scott Egertona1fa68a2016-02-11 13:48:49 +00002561 // Whitespace after an operator can be ignored.
2562 if (Lexer.is(AsmToken::Space))
Nirav Dave1180e6892016-06-02 17:15:05 +00002563 Lexer.Lex();
Scott Egertona1fa68a2016-02-11 13:48:49 +00002564
2565 continue;
Preston Gurd05500642012-09-19 20:36:12 +00002566 }
2567 }
Scott Egertona1fa68a2016-02-11 13:48:49 +00002568 if (SpaceEaten)
2569 break;
Preston Gurd05500642012-09-19 20:36:12 +00002570 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002571
Jim Grosbach4b905842013-09-20 23:08:21 +00002572 // handleMacroEntry relies on not advancing the lexer here
Rafael Espindola768b41c2012-06-15 14:02:34 +00002573 // to be able to fill in the remaining default parameter values
2574 if (Lexer.is(AsmToken::EndOfStatement))
2575 break;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002576
2577 // Adjust the current parentheses level.
2578 if (Lexer.is(AsmToken::LParen))
2579 ++ParenLevel;
2580 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
2581 --ParenLevel;
2582
2583 // Append the token to the current argument list.
2584 MA.push_back(getTok());
Nirav Dave1180e6892016-06-02 17:15:05 +00002585 Lexer.Lex();
Rafael Espindola768b41c2012-06-15 14:02:34 +00002586 }
Preston Gurd05500642012-09-19 20:36:12 +00002587
Rafael Espindola768b41c2012-06-15 14:02:34 +00002588 if (ParenLevel != 0)
Rafael Espindola3e5eb422012-08-21 15:55:04 +00002589 return TokError("unbalanced parentheses in macro argument");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002590 return false;
2591}
2592
2593// Parse the macro instantiation arguments.
Jim Grosbach4b905842013-09-20 23:08:21 +00002594bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
Vladimir Medic9bad0d332013-08-20 13:33:18 +00002595 MCAsmMacroArguments &A) {
Rafael Espindola768b41c2012-06-15 14:02:34 +00002596 const unsigned NParameters = M ? M->Parameters.size() : 0;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002597 bool NamedParametersFound = false;
2598 SmallVector<SMLoc, 4> FALocs;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002599
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002600 A.resize(NParameters);
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002601 FALocs.resize(NParameters);
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002602
Rafael Espindola768b41c2012-06-15 14:02:34 +00002603 // Parse two kinds of macro invocations:
2604 // - macros defined without any parameters accept an arbitrary number of them
2605 // - macros defined with parameters accept at most that many of them
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002606 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002607 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
2608 ++Parameter) {
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002609 SMLoc IDLoc = Lexer.getLoc();
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002610 MCAsmMacroParameter FA;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002611
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002612 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00002613 if (parseIdentifier(FA.Name))
2614 return Error(IDLoc, "invalid argument identifier for formal argument");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002615
Nirav Dave2364748a2016-09-16 18:30:20 +00002616 if (Lexer.isNot(AsmToken::Equal))
2617 return TokError("expected '=' after formal parameter identifier");
2618
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002619 Lex();
2620
2621 NamedParametersFound = true;
2622 }
Michael Zuckerman56704612017-05-01 13:20:12 +00002623 bool Vararg = HasVararg && Parameter == (NParameters - 1);
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002624
Nirav Dave2364748a2016-09-16 18:30:20 +00002625 if (NamedParametersFound && FA.Name.empty())
2626 return Error(IDLoc, "cannot mix positional and keyword arguments");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002627
Michael Zuckerman763e60e2017-05-04 10:37:00 +00002628 SMLoc StrLoc = Lexer.getLoc();
2629 SMLoc EndLoc;
Michael Zuckerman56704612017-05-01 13:20:12 +00002630 if (Lexer.IsaAltMacroMode() && Lexer.is(AsmToken::Percent)) {
Michael Zuckerman56704612017-05-01 13:20:12 +00002631 const MCExpr *AbsoluteExp;
2632 int64_t Value;
2633 /// Eat '%'
2634 Lex();
2635 if (parseExpression(AbsoluteExp, EndLoc))
2636 return false;
Nirav Dave6c0665e2018-04-30 19:22:40 +00002637 if (!AbsoluteExp->evaluateAsAbsolute(Value,
2638 getStreamer().getAssemblerPtr()))
Michael Zuckerman56704612017-05-01 13:20:12 +00002639 return Error(StrLoc, "expected absolute expression");
2640 const char *StrChar = StrLoc.getPointer();
2641 const char *EndChar = EndLoc.getPointer();
2642 AsmToken newToken(AsmToken::Integer, StringRef(StrChar , EndChar - StrChar), Value);
2643 FA.Value.push_back(newToken);
Michael Zuckerman763e60e2017-05-04 10:37:00 +00002644 } else if (Lexer.IsaAltMacroMode() && Lexer.is(AsmToken::Less) &&
2645 isAltmacroString(StrLoc, EndLoc)) {
2646 const char *StrChar = StrLoc.getPointer();
2647 const char *EndChar = EndLoc.getPointer();
2648 jumpToLoc(EndLoc, CurBuffer);
2649 /// Eat from '<' to '>'
2650 Lex();
2651 AsmToken newToken(AsmToken::String, StringRef(StrChar, EndChar - StrChar));
2652 FA.Value.push_back(newToken);
2653 } else if(parseMacroArgument(FA.Value, Vararg))
Michael Zuckerman56704612017-05-01 13:20:12 +00002654 return true;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002655
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002656 unsigned PI = Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002657 if (!FA.Name.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002658 unsigned FAI = 0;
2659 for (FAI = 0; FAI < NParameters; ++FAI)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002660 if (M->Parameters[FAI].Name == FA.Name)
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002661 break;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002662
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002663 if (FAI >= NParameters) {
Nirav Davefd910412016-06-17 16:06:17 +00002664 assert(M && "expected macro to be defined");
Nirav Dave2364748a2016-09-16 18:30:20 +00002665 return Error(IDLoc, "parameter named '" + FA.Name +
2666 "' does not exist for macro '" + M->Name + "'");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002667 }
2668 PI = FAI;
2669 }
2670
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002671 if (!FA.Value.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002672 if (A.size() <= PI)
2673 A.resize(PI + 1);
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002674 A[PI] = FA.Value;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002675
2676 if (FALocs.size() <= PI)
2677 FALocs.resize(PI + 1);
2678
2679 FALocs[PI] = Lexer.getLoc();
Preston Gurd242ed3152012-09-19 20:29:04 +00002680 }
Jim Grosbach206661622012-07-30 22:44:17 +00002681
Preston Gurd242ed3152012-09-19 20:29:04 +00002682 // At the end of the statement, fill in remaining arguments that have
2683 // default values. If there aren't any, then the next argument is
2684 // required but missing
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002685 if (Lexer.is(AsmToken::EndOfStatement)) {
2686 bool Failure = false;
2687 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2688 if (A[FAI].empty()) {
2689 if (M->Parameters[FAI].Required) {
2690 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2691 "missing value for required parameter "
2692 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2693 Failure = true;
2694 }
2695
2696 if (!M->Parameters[FAI].Value.empty())
2697 A[FAI] = M->Parameters[FAI].Value;
2698 }
2699 }
2700 return Failure;
2701 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002702
2703 if (Lexer.is(AsmToken::Comma))
2704 Lex();
2705 }
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002706
2707 return TokError("too many positional arguments");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002708}
2709
Jim Grosbach4b905842013-09-20 23:08:21 +00002710bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
Davide Italiano7c9fc732016-07-27 05:51:56 +00002711 // Arbitrarily limit macro nesting depth (default matches 'as'). We can
2712 // eliminate this, although we should protect against infinite loops.
2713 unsigned MaxNestingDepth = AsmMacroMaxNestingDepth;
2714 if (ActiveMacros.size() == MaxNestingDepth) {
2715 std::ostringstream MaxNestingDepthError;
2716 MaxNestingDepthError << "macros cannot be nested more than "
2717 << MaxNestingDepth << " levels deep."
2718 << " Use -asm-macro-max-nesting-depth to increase "
2719 "this limit.";
2720 return TokError(MaxNestingDepthError.str());
2721 }
Daniel Dunbar43235712010-07-18 18:54:11 +00002722
Eli Bendersky38274122013-01-14 23:22:36 +00002723 MCAsmMacroArguments A;
Jim Grosbach4b905842013-09-20 23:08:21 +00002724 if (parseMacroArguments(M, A))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002725 return true;
Daniel Dunbar43235712010-07-18 18:54:11 +00002726
Rafael Espindola1134ab232011-06-05 02:43:45 +00002727 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2728 // to hold the macro body with substitutions.
2729 SmallString<256> Buf;
2730 StringRef Body = M->Body;
Rafael Espindola34b9c512012-06-03 23:57:14 +00002731 raw_svector_ostream OS(Buf);
Rafael Espindola1134ab232011-06-05 02:43:45 +00002732
Toma Tabacu217116e2015-04-27 10:50:29 +00002733 if (expandMacro(OS, Body, M->Parameters, A, true, getTok().getLoc()))
Rafael Espindola1134ab232011-06-05 02:43:45 +00002734 return true;
2735
Eli Bendersky38274122013-01-14 23:22:36 +00002736 // We include the .endmacro in the buffer as our cue to exit the macro
Rafael Espindola34b9c512012-06-03 23:57:14 +00002737 // instantiation.
2738 OS << ".endmacro\n";
2739
Rafael Espindola3560ff22014-08-27 20:03:13 +00002740 std::unique_ptr<MemoryBuffer> Instantiation =
2741 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola1134ab232011-06-05 02:43:45 +00002742
Daniel Dunbar43235712010-07-18 18:54:11 +00002743 // Create the macro instantiation object and add to the current macro
2744 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002745 MacroInstantiation *MI = new MacroInstantiation(
2746 NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Daniel Dunbar43235712010-07-18 18:54:11 +00002747 ActiveMacros.push_back(MI);
2748
Toma Tabacu217116e2015-04-27 10:50:29 +00002749 ++NumOfMacroInstantiations;
2750
Daniel Dunbar43235712010-07-18 18:54:11 +00002751 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00002752 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00002753 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar43235712010-07-18 18:54:11 +00002754 Lex();
2755
2756 return false;
2757}
2758
Jim Grosbach4b905842013-09-20 23:08:21 +00002759void AsmParser::handleMacroExit() {
Daniel Dunbar43235712010-07-18 18:54:11 +00002760 // Jump to the EndOfStatement we should return to, and consume it.
Jim Grosbach4b905842013-09-20 23:08:21 +00002761 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
Daniel Dunbar43235712010-07-18 18:54:11 +00002762 Lex();
2763
2764 // Pop the instantiation entry.
2765 delete ActiveMacros.back();
2766 ActiveMacros.pop_back();
2767}
2768
Jim Grosbach4b905842013-09-20 23:08:21 +00002769bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
Nirav Dave7fd992a2018-08-16 16:31:14 +00002770 bool NoDeadStrip) {
Pete Cooper80d21cb2015-06-22 19:35:57 +00002771 MCSymbol *Sym;
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002772 const MCExpr *Value;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002773 if (MCParserUtils::parseAssignmentExpression(Name, allow_redef, *this, Sym,
Nirav Dave7fd992a2018-08-16 16:31:14 +00002774 Value))
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002775 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002776
Pete Cooper80d21cb2015-06-22 19:35:57 +00002777 if (!Sym) {
2778 // In the case where we parse an expression starting with a '.', we will
2779 // not generate an error, nor will we create a symbol. In this case we
2780 // should just return out.
Anders Waldenborg84809572014-02-17 20:48:32 +00002781 return false;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002782 }
David Majnemer58cb80c2014-12-24 10:27:50 +00002783
Daniel Dunbarae7ac012009-06-29 23:43:14 +00002784 // Do the assignment.
Daniel Dunbarb7b20972009-08-31 08:09:09 +00002785 Out.EmitAssignment(Sym, Value);
Jim Grosbachb7b750d2012-09-13 23:11:31 +00002786 if (NoDeadStrip)
2787 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2788
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002789 return false;
2790}
2791
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002792/// parseIdentifier:
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002793/// ::= identifier
2794/// ::= string
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002795bool AsmParser::parseIdentifier(StringRef &Res) {
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002796 // The assembler has relaxed rules for accepting identifiers, in particular we
Hans Wennborgce69d772013-10-18 20:46:28 +00002797 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2798 // separate tokens. At this level, we have already lexed so we cannot (currently)
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002799 // handle this as a context dependent token, instead we detect adjacent tokens
2800 // and return the combined identifier.
Hans Wennborgce69d772013-10-18 20:46:28 +00002801 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2802 SMLoc PrefixLoc = getLexer().getLoc();
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002803
Hans Wennborgce69d772013-10-18 20:46:28 +00002804 // Consume the prefix character, and check for a following identifier.
Nirav Daved0463322016-10-12 13:58:07 +00002805
2806 AsmToken Buf[1];
2807 Lexer.peekTokens(Buf, false);
2808
2809 if (Buf[0].isNot(AsmToken::Identifier))
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002810 return true;
2811
Hans Wennborgce69d772013-10-18 20:46:28 +00002812 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
Nirav Daved0463322016-10-12 13:58:07 +00002813 if (PrefixLoc.getPointer() + 1 != Buf[0].getLoc().getPointer())
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002814 return true;
2815
Nirav Daved0463322016-10-12 13:58:07 +00002816 // eat $ or @
2817 Lexer.Lex(); // Lexer's Lex guarantees consecutive token.
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002818 // Construct the joined identifier and consume the token.
Jim Grosbach4b905842013-09-20 23:08:21 +00002819 Res =
Hans Wennborgce69d772013-10-18 20:46:28 +00002820 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
Nirav Davefd910412016-06-17 16:06:17 +00002821 Lex(); // Parser Lex to maintain invariants.
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002822 return false;
2823 }
2824
Jim Grosbach4b905842013-09-20 23:08:21 +00002825 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002826 return true;
2827
Sean Callanan936b0d32010-01-19 21:44:56 +00002828 Res = getTok().getIdentifier();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002829
Sean Callanan686ed8d2010-01-19 20:22:31 +00002830 Lex(); // Consume the identifier token.
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002831
2832 return false;
2833}
2834
Jim Grosbach4b905842013-09-20 23:08:21 +00002835/// parseDirectiveSet:
Nico Weber4ada0d92011-01-28 03:04:41 +00002836/// ::= .equ identifier ',' expression
2837/// ::= .equiv identifier ',' expression
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002838/// ::= .set identifier ',' expression
Jim Grosbach4b905842013-09-20 23:08:21 +00002839bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002840 StringRef Name;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002841 if (check(parseIdentifier(Name), "expected identifier") ||
2842 parseToken(AsmToken::Comma) || parseAssignment(Name, allow_redef, true))
2843 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
2844 return false;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002845}
2846
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002847bool AsmParser::parseEscapedString(std::string &Data) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00002848 if (check(getTok().isNot(AsmToken::String), "expected string"))
2849 return true;
Daniel Dunbaref668c12009-08-14 18:19:52 +00002850
2851 Data = "";
Sean Callanan936b0d32010-01-19 21:44:56 +00002852 StringRef Str = getTok().getStringContents();
Daniel Dunbaref668c12009-08-14 18:19:52 +00002853 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2854 if (Str[i] != '\\') {
2855 Data += Str[i];
2856 continue;
2857 }
2858
2859 // Recognize escaped characters. Note that this escape semantics currently
2860 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2861 ++i;
2862 if (i == e)
2863 return TokError("unexpected backslash at end of string");
2864
2865 // Recognize octal sequences.
Jim Grosbach4b905842013-09-20 23:08:21 +00002866 if ((unsigned)(Str[i] - '0') <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002867 // Consume up to three octal characters.
2868 unsigned Value = Str[i] - '0';
2869
Jim Grosbach4b905842013-09-20 23:08:21 +00002870 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002871 ++i;
2872 Value = Value * 8 + (Str[i] - '0');
2873
Jim Grosbach4b905842013-09-20 23:08:21 +00002874 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002875 ++i;
2876 Value = Value * 8 + (Str[i] - '0');
2877 }
2878 }
2879
2880 if (Value > 255)
2881 return TokError("invalid octal escape sequence (out of range)");
2882
Jim Grosbach4b905842013-09-20 23:08:21 +00002883 Data += (unsigned char)Value;
Daniel Dunbaref668c12009-08-14 18:19:52 +00002884 continue;
2885 }
2886
2887 // Otherwise recognize individual escapes.
2888 switch (Str[i]) {
2889 default:
2890 // Just reject invalid escape sequences for now.
2891 return TokError("invalid escape sequence (unrecognized character)");
2892
2893 case 'b': Data += '\b'; break;
2894 case 'f': Data += '\f'; break;
2895 case 'n': Data += '\n'; break;
2896 case 'r': Data += '\r'; break;
2897 case 't': Data += '\t'; break;
2898 case '"': Data += '"'; break;
2899 case '\\': Data += '\\'; break;
2900 }
2901 }
2902
Nirav Davea645433c2016-07-18 15:24:03 +00002903 Lex();
Daniel Dunbaref668c12009-08-14 18:19:52 +00002904 return false;
2905}
2906
Jim Grosbach4b905842013-09-20 23:08:21 +00002907/// parseDirectiveAscii:
Rafael Espindola63760ba2010-10-28 20:02:27 +00002908/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002909bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00002910 auto parseOp = [&]() -> bool {
2911 std::string Data;
2912 if (checkForValidSection() || parseEscapedString(Data))
Nirav Davef43cc9f2016-10-10 15:24:54 +00002913 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002914 getStreamer().EmitBytes(Data);
2915 if (ZeroTerminated)
2916 getStreamer().EmitBytes(StringRef("\0", 1));
2917 return false;
2918 };
Daniel Dunbare5444a82010-09-09 22:42:59 +00002919
Nirav Dave1a9044b2016-10-24 14:35:29 +00002920 if (parseMany(parseOp))
2921 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbara10e5192009-06-24 23:30:00 +00002922 return false;
2923}
2924
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002925/// parseDirectiveReloc
2926/// ::= .reloc expression , identifier [ , expression ]
2927bool AsmParser::parseDirectiveReloc(SMLoc DirectiveLoc) {
2928 const MCExpr *Offset;
2929 const MCExpr *Expr = nullptr;
2930
2931 SMLoc OffsetLoc = Lexer.getTok().getLoc();
Nirav Dave1a9044b2016-10-24 14:35:29 +00002932 int64_t OffsetValue;
2933 // We can only deal with constant expressions at the moment.
2934
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002935 if (parseExpression(Offset))
2936 return true;
2937
Nirav Dave6c0665e2018-04-30 19:22:40 +00002938 if (check(!Offset->evaluateAsAbsolute(OffsetValue,
2939 getStreamer().getAssemblerPtr()),
2940 OffsetLoc, "expression is not a constant value") ||
Nirav Davea645433c2016-07-18 15:24:03 +00002941 check(OffsetValue < 0, OffsetLoc, "expression is negative") ||
2942 parseToken(AsmToken::Comma, "expected comma") ||
2943 check(getTok().isNot(AsmToken::Identifier), "expected relocation name"))
2944 return true;
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002945
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002946 SMLoc NameLoc = Lexer.getTok().getLoc();
2947 StringRef Name = Lexer.getTok().getIdentifier();
Nirav Davefd910412016-06-17 16:06:17 +00002948 Lex();
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002949
2950 if (Lexer.is(AsmToken::Comma)) {
Nirav Davefd910412016-06-17 16:06:17 +00002951 Lex();
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002952 SMLoc ExprLoc = Lexer.getLoc();
2953 if (parseExpression(Expr))
2954 return true;
2955
2956 MCValue Value;
2957 if (!Expr->evaluateAsRelocatable(Value, nullptr, nullptr))
2958 return Error(ExprLoc, "expression must be relocatable");
2959 }
2960
Nirav Davea645433c2016-07-18 15:24:03 +00002961 if (parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00002962 "unexpected token in .reloc directive"))
2963 return true;
2964
Peter Smith57f661b2018-06-06 09:40:06 +00002965 const MCTargetAsmParser &MCT = getTargetParser();
2966 const MCSubtargetInfo &STI = MCT.getSTI();
2967 if (getStreamer().EmitRelocDirective(*Offset, Name, Expr, DirectiveLoc, STI))
Nirav Dave1ab71992016-07-18 19:35:21 +00002968 return Error(NameLoc, "unknown relocation name");
2969
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002970 return false;
2971}
2972
Jim Grosbach4b905842013-09-20 23:08:21 +00002973/// parseDirectiveValue
Daniel Dunbara10e5192009-06-24 23:30:00 +00002974/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00002975bool AsmParser::parseDirectiveValue(StringRef IDVal, unsigned Size) {
2976 auto parseOp = [&]() -> bool {
2977 const MCExpr *Value;
2978 SMLoc ExprLoc = getLexer().getLoc();
2979 if (checkForValidSection() || parseExpression(Value))
Nirav Davef43cc9f2016-10-10 15:24:54 +00002980 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002981 // Special case constant expressions to match code generator.
2982 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2983 assert(Size <= 8 && "Invalid size");
2984 uint64_t IntValue = MCE->getValue();
2985 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2986 return Error(ExprLoc, "out of range literal value");
2987 getStreamer().EmitIntValue(IntValue, Size);
2988 } else
2989 getStreamer().EmitValue(Value, Size, ExprLoc);
2990 return false;
2991 };
Daniel Dunbare5444a82010-09-09 22:42:59 +00002992
Nirav Dave1a9044b2016-10-24 14:35:29 +00002993 if (parseMany(parseOp))
2994 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbara10e5192009-06-24 23:30:00 +00002995 return false;
2996}
2997
Paul Robinson01954692018-04-11 15:14:05 +00002998static bool parseHexOcta(AsmParser &Asm, uint64_t &hi, uint64_t &lo) {
2999 if (Asm.getTok().isNot(AsmToken::Integer) &&
3000 Asm.getTok().isNot(AsmToken::BigNum))
3001 return Asm.TokError("unknown token in expression");
3002 SMLoc ExprLoc = Asm.getTok().getLoc();
3003 APInt IntValue = Asm.getTok().getAPIntVal();
3004 Asm.Lex();
3005 if (!IntValue.isIntN(128))
3006 return Asm.Error(ExprLoc, "out of range literal value");
3007 if (!IntValue.isIntN(64)) {
3008 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
3009 lo = IntValue.getLoBits(64).getZExtValue();
3010 } else {
3011 hi = 0;
3012 lo = IntValue.getZExtValue();
3013 }
3014 return false;
3015}
3016
David Woodhoused6de0d92014-02-01 16:20:59 +00003017/// ParseDirectiveOctaValue
3018/// ::= .octa [ hexconstant (, hexconstant)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00003019
3020bool AsmParser::parseDirectiveOctaValue(StringRef IDVal) {
3021 auto parseOp = [&]() -> bool {
Nirav Davef43cc9f2016-10-10 15:24:54 +00003022 if (checkForValidSection())
3023 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003024 uint64_t hi, lo;
Paul Robinson01954692018-04-11 15:14:05 +00003025 if (parseHexOcta(*this, hi, lo))
3026 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003027 if (MAI.isLittleEndian()) {
3028 getStreamer().EmitIntValue(lo, 8);
3029 getStreamer().EmitIntValue(hi, 8);
3030 } else {
3031 getStreamer().EmitIntValue(hi, 8);
3032 getStreamer().EmitIntValue(lo, 8);
3033 }
3034 return false;
3035 };
David Woodhoused6de0d92014-02-01 16:20:59 +00003036
Nirav Dave1a9044b2016-10-24 14:35:29 +00003037 if (parseMany(parseOp))
3038 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
David Woodhoused6de0d92014-02-01 16:20:59 +00003039 return false;
3040}
3041
Petr Hosek4cb08ce2016-09-23 19:25:15 +00003042bool AsmParser::parseRealValue(const fltSemantics &Semantics, APInt &Res) {
3043 // We don't truly support arithmetic on floating point expressions, so we
3044 // have to manually parse unary prefixes.
3045 bool IsNeg = false;
3046 if (getLexer().is(AsmToken::Minus)) {
3047 Lexer.Lex();
3048 IsNeg = true;
3049 } else if (getLexer().is(AsmToken::Plus))
3050 Lexer.Lex();
3051
3052 if (Lexer.is(AsmToken::Error))
3053 return TokError(Lexer.getErr());
3054 if (Lexer.isNot(AsmToken::Integer) && Lexer.isNot(AsmToken::Real) &&
3055 Lexer.isNot(AsmToken::Identifier))
3056 return TokError("unexpected token in directive");
3057
3058 // Convert to an APFloat.
3059 APFloat Value(Semantics);
3060 StringRef IDVal = getTok().getString();
3061 if (getLexer().is(AsmToken::Identifier)) {
3062 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
3063 Value = APFloat::getInf(Semantics);
3064 else if (!IDVal.compare_lower("nan"))
3065 Value = APFloat::getNaN(Semantics, false, ~0);
3066 else
3067 return TokError("invalid floating point literal");
3068 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
3069 APFloat::opInvalidOp)
3070 return TokError("invalid floating point literal");
3071 if (IsNeg)
3072 Value.changeSign();
3073
3074 // Consume the numeric token.
3075 Lex();
3076
3077 Res = Value.bitcastToAPInt();
3078
3079 return false;
3080}
3081
Jim Grosbach4b905842013-09-20 23:08:21 +00003082/// parseDirectiveRealValue
Daniel Dunbar2af16532010-09-24 01:59:56 +00003083/// ::= (.single | .double) [ expression (, expression)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00003084bool AsmParser::parseDirectiveRealValue(StringRef IDVal,
3085 const fltSemantics &Semantics) {
3086 auto parseOp = [&]() -> bool {
3087 APInt AsInt;
3088 if (checkForValidSection() || parseRealValue(Semantics, AsInt))
Nirav Davef43cc9f2016-10-10 15:24:54 +00003089 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003090 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
3091 AsInt.getBitWidth() / 8);
3092 return false;
3093 };
Daniel Dunbar2af16532010-09-24 01:59:56 +00003094
Nirav Dave1a9044b2016-10-24 14:35:29 +00003095 if (parseMany(parseOp))
3096 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbar2af16532010-09-24 01:59:56 +00003097 return false;
3098}
3099
Jim Grosbach4b905842013-09-20 23:08:21 +00003100/// parseDirectiveZero
Rafael Espindola922e3f42010-09-16 15:03:59 +00003101/// ::= .zero expression
Jim Grosbach4b905842013-09-20 23:08:21 +00003102bool AsmParser::parseDirectiveZero() {
Petr Hosek67a94a72016-05-28 05:57:48 +00003103 SMLoc NumBytesLoc = Lexer.getLoc();
3104 const MCExpr *NumBytes;
Nirav Davef43cc9f2016-10-10 15:24:54 +00003105 if (checkForValidSection() || parseExpression(NumBytes))
Rafael Espindola922e3f42010-09-16 15:03:59 +00003106 return true;
3107
Rafael Espindolab91bac62010-10-05 19:42:57 +00003108 int64_t Val = 0;
3109 if (getLexer().is(AsmToken::Comma)) {
3110 Lex();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003111 if (parseAbsoluteExpression(Val))
Rafael Espindolab91bac62010-10-05 19:42:57 +00003112 return true;
3113 }
3114
Nirav Davea645433c2016-07-18 15:24:03 +00003115 if (parseToken(AsmToken::EndOfStatement,
3116 "unexpected token in '.zero' directive"))
3117 return true;
Petr Hosek67a94a72016-05-28 05:57:48 +00003118 getStreamer().emitFill(*NumBytes, Val, NumBytesLoc);
Rafael Espindola922e3f42010-09-16 15:03:59 +00003119
3120 return false;
3121}
3122
Jim Grosbach4b905842013-09-20 23:08:21 +00003123/// parseDirectiveFill
Roman Divackye33098f2013-09-24 17:44:41 +00003124/// ::= .fill expression [ , expression [ , expression ] ]
Jim Grosbach4b905842013-09-20 23:08:21 +00003125bool AsmParser::parseDirectiveFill() {
Petr Hosek67a94a72016-05-28 05:57:48 +00003126 SMLoc NumValuesLoc = Lexer.getLoc();
3127 const MCExpr *NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00003128 if (checkForValidSection() || parseExpression(NumValues))
Daniel Dunbara10e5192009-06-24 23:30:00 +00003129 return true;
3130
Roman Divackye33098f2013-09-24 17:44:41 +00003131 int64_t FillSize = 1;
3132 int64_t FillExpr = 0;
Michael J. Spencer530ce852010-10-09 11:00:50 +00003133
David Majnemer522d3db2014-02-01 07:19:38 +00003134 SMLoc SizeLoc, ExprLoc;
Daniel Dunbara10e5192009-06-24 23:30:00 +00003135
Nirav Dave1a9044b2016-10-24 14:35:29 +00003136 if (parseOptionalToken(AsmToken::Comma)) {
3137 SizeLoc = getTok().getLoc();
3138 if (parseAbsoluteExpression(FillSize))
Roman Divackye33098f2013-09-24 17:44:41 +00003139 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003140 if (parseOptionalToken(AsmToken::Comma)) {
3141 ExprLoc = getTok().getLoc();
3142 if (parseAbsoluteExpression(FillExpr))
Roman Divackye33098f2013-09-24 17:44:41 +00003143 return true;
Roman Divackye33098f2013-09-24 17:44:41 +00003144 }
3145 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003146 if (parseToken(AsmToken::EndOfStatement,
3147 "unexpected token in '.fill' directive"))
3148 return true;
Daniel Dunbara10e5192009-06-24 23:30:00 +00003149
David Majnemer522d3db2014-02-01 07:19:38 +00003150 if (FillSize < 0) {
3151 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
Petr Hosek6abd38b2016-05-28 08:20:08 +00003152 return false;
David Majnemer522d3db2014-02-01 07:19:38 +00003153 }
3154 if (FillSize > 8) {
3155 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
3156 FillSize = 8;
3157 }
Daniel Dunbara10e5192009-06-24 23:30:00 +00003158
David Majnemer522d3db2014-02-01 07:19:38 +00003159 if (!isUInt<32>(FillExpr) && FillSize > 4)
3160 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
3161
Petr Hosek67a94a72016-05-28 05:57:48 +00003162 getStreamer().emitFill(*NumValues, FillSize, FillExpr, NumValuesLoc);
Daniel Dunbara10e5192009-06-24 23:30:00 +00003163
3164 return false;
3165}
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00003166
Jim Grosbach4b905842013-09-20 23:08:21 +00003167/// parseDirectiveOrg
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00003168/// ::= .org expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00003169bool AsmParser::parseDirectiveOrg() {
Daniel Dunbar897ffad2009-08-31 08:09:28 +00003170 const MCExpr *Offset;
Oliver Stannard268f42f2016-12-14 10:43:58 +00003171 SMLoc OffsetLoc = Lexer.getLoc();
Nirav Davef43cc9f2016-10-10 15:24:54 +00003172 if (checkForValidSection() || parseExpression(Offset))
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00003173 return true;
3174
3175 // Parse optional fill expression.
3176 int64_t FillExpr = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003177 if (parseOptionalToken(AsmToken::Comma))
3178 if (parseAbsoluteExpression(FillExpr))
3179 return addErrorSuffix(" in '.org' directive");
3180 if (parseToken(AsmToken::EndOfStatement))
3181 return addErrorSuffix(" in '.org' directive");
Nirav Davea645433c2016-07-18 15:24:03 +00003182
Oliver Stannard268f42f2016-12-14 10:43:58 +00003183 getStreamer().emitValueToOffset(Offset, FillExpr, OffsetLoc);
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00003184 return false;
3185}
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003186
Jim Grosbach4b905842013-09-20 23:08:21 +00003187/// parseDirectiveAlign
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003188/// ::= {.align, ...} expression [ , expression [ , expression ]]
Jim Grosbach4b905842013-09-20 23:08:21 +00003189bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003190 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003191 int64_t Alignment;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003192 SMLoc MaxBytesLoc;
3193 bool HasFillExpr = false;
3194 int64_t FillExpr = 0;
3195 int64_t MaxBytesToFill = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003196
3197 auto parseAlign = [&]() -> bool {
Coby Tayreed483a102017-08-02 17:36:10 +00003198 if (parseAbsoluteExpression(Alignment))
Nirav Davea645433c2016-07-18 15:24:03 +00003199 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003200 if (parseOptionalToken(AsmToken::Comma)) {
3201 // The fill expression can be omitted while specifying a maximum number of
3202 // alignment bytes, e.g:
3203 // .align 3,,4
3204 if (getTok().isNot(AsmToken::Comma)) {
3205 HasFillExpr = true;
3206 if (parseAbsoluteExpression(FillExpr))
3207 return true;
3208 }
3209 if (parseOptionalToken(AsmToken::Comma))
3210 if (parseTokenLoc(MaxBytesLoc) ||
3211 parseAbsoluteExpression(MaxBytesToFill))
3212 return true;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003213 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003214 return parseToken(AsmToken::EndOfStatement);
3215 };
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003216
Coby Tayreed483a102017-08-02 17:36:10 +00003217 if (checkForValidSection())
3218 return addErrorSuffix(" in directive");
3219 // Ignore empty '.p2align' directives for GNU-as compatibility
3220 if (IsPow2 && (ValueSize == 1) && getTok().is(AsmToken::EndOfStatement)) {
3221 Warning(AlignmentLoc, "p2align directive with no operand(s) is ignored");
3222 return parseToken(AsmToken::EndOfStatement);
3223 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003224 if (parseAlign())
3225 return addErrorSuffix(" in directive");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003226
Nirav Dave2364748a2016-09-16 18:30:20 +00003227 // Always emit an alignment here even if we thrown an error.
3228 bool ReturnVal = false;
3229
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003230 // Compute alignment in bytes.
3231 if (IsPow2) {
3232 // FIXME: Diagnose overflow.
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003233 if (Alignment >= 32) {
Nirav Dave2364748a2016-09-16 18:30:20 +00003234 ReturnVal |= Error(AlignmentLoc, "invalid alignment value");
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003235 Alignment = 31;
3236 }
3237
Benjamin Kramer63951ad2009-09-06 09:35:10 +00003238 Alignment = 1ULL << Alignment;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00003239 } else {
Davide Italianocb2da712015-09-08 18:59:47 +00003240 // Reject alignments that aren't either a power of two or zero,
3241 // for gas compatibility. Alignment of zero is silently rounded
3242 // up to one.
3243 if (Alignment == 0)
3244 Alignment = 1;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00003245 if (!isPowerOf2_64(Alignment))
Nirav Dave2364748a2016-09-16 18:30:20 +00003246 ReturnVal |= Error(AlignmentLoc, "alignment must be a power of 2");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003247 }
3248
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003249 // Diagnose non-sensical max bytes to align.
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003250 if (MaxBytesLoc.isValid()) {
3251 if (MaxBytesToFill < 1) {
Nirav Dave2364748a2016-09-16 18:30:20 +00003252 ReturnVal |= Error(MaxBytesLoc,
3253 "alignment directive can never be satisfied in this "
Jim Grosbach4b905842013-09-20 23:08:21 +00003254 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar4abcccb2009-08-21 23:01:53 +00003255 MaxBytesToFill = 0;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003256 }
3257
3258 if (MaxBytesToFill >= Alignment) {
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +00003259 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
Jim Grosbach4b905842013-09-20 23:08:21 +00003260 "has no effect");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003261 MaxBytesToFill = 0;
3262 }
3263 }
3264
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003265 // Check whether we should use optimal code alignment for this .align
3266 // directive.
Eric Christopher445c9522016-10-14 05:47:37 +00003267 const MCSection *Section = getStreamer().getCurrentSectionOnly();
Saleem Abdulrasool7f2f9f42014-03-21 05:13:23 +00003268 assert(Section && "must have section to emit alignment");
3269 bool UseCodeAlign = Section->UseCodeAlign();
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003270 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
3271 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003272 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003273 } else {
Kevin Enderby7f993022010-02-25 18:46:04 +00003274 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnerc2b36752010-07-15 21:19:31 +00003275 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
3276 MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003277 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003278
Nirav Dave2364748a2016-09-16 18:30:20 +00003279 return ReturnVal;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003280}
3281
Jim Grosbach4b905842013-09-20 23:08:21 +00003282/// parseDirectiveFile
Paul Robinson29f5f982018-01-09 23:31:48 +00003283/// ::= .file filename
Scott Linder16c7bda2018-02-23 23:01:06 +00003284/// ::= .file number [directory] filename [md5 checksum] [source source-text]
Jim Grosbach4b905842013-09-20 23:08:21 +00003285bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003286 // FIXME: I'm not sure what this is.
3287 int64_t FileNumber = -1;
Eli Bendersky17233942013-01-15 22:59:42 +00003288 if (getLexer().is(AsmToken::Integer)) {
3289 FileNumber = getTok().getIntVal();
3290 Lex();
3291
Paul Robinsonb271f312018-03-29 17:16:41 +00003292 if (FileNumber < 0)
3293 return TokError("negative file number");
Eli Bendersky17233942013-01-15 22:59:42 +00003294 }
3295
Paul Robinson37fbb922018-06-20 16:12:03 +00003296 std::string Path;
Eli Bendersky17233942013-01-15 22:59:42 +00003297
3298 // Usually the directory and filename together, otherwise just the directory.
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003299 // Allow the strings to have escaped octal character sequence.
Nirav Davea645433c2016-07-18 15:24:03 +00003300 if (check(getTok().isNot(AsmToken::String),
3301 "unexpected token in '.file' directive") ||
3302 parseEscapedString(Path))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003303 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003304
3305 StringRef Directory;
3306 StringRef Filename;
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003307 std::string FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00003308 if (getLexer().is(AsmToken::String)) {
Nirav Davea645433c2016-07-18 15:24:03 +00003309 if (check(FileNumber == -1,
3310 "explicit path specified, but no file number") ||
3311 parseEscapedString(FilenameData))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003312 return true;
3313 Filename = FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00003314 Directory = Path;
Eli Bendersky17233942013-01-15 22:59:42 +00003315 } else {
3316 Filename = Path;
3317 }
3318
Paul Robinson01954692018-04-11 15:14:05 +00003319 uint64_t MD5Hi, MD5Lo;
3320 bool HasMD5 = false;
Scott Linder16c7bda2018-02-23 23:01:06 +00003321
3322 Optional<StringRef> Source;
3323 bool HasSource = false;
3324 std::string SourceString;
3325
3326 while (!parseOptionalToken(AsmToken::EndOfStatement)) {
Paul Robinson29f5f982018-01-09 23:31:48 +00003327 StringRef Keyword;
3328 if (check(getTok().isNot(AsmToken::Identifier),
3329 "unexpected token in '.file' directive") ||
Scott Linder16c7bda2018-02-23 23:01:06 +00003330 parseIdentifier(Keyword))
Paul Robinson29f5f982018-01-09 23:31:48 +00003331 return true;
Scott Linder16c7bda2018-02-23 23:01:06 +00003332 if (Keyword == "md5") {
Paul Robinson01954692018-04-11 15:14:05 +00003333 HasMD5 = true;
Scott Linder16c7bda2018-02-23 23:01:06 +00003334 if (check(FileNumber == -1,
3335 "MD5 checksum specified, but no file number") ||
Paul Robinson01954692018-04-11 15:14:05 +00003336 parseHexOcta(*this, MD5Hi, MD5Lo))
Scott Linder16c7bda2018-02-23 23:01:06 +00003337 return true;
3338 } else if (Keyword == "source") {
3339 HasSource = true;
3340 if (check(FileNumber == -1,
3341 "source specified, but no file number") ||
3342 check(getTok().isNot(AsmToken::String),
3343 "unexpected token in '.file' directive") ||
3344 parseEscapedString(SourceString))
3345 return true;
3346 } else {
3347 return TokError("unexpected token in '.file' directive");
3348 }
Paul Robinson29f5f982018-01-09 23:31:48 +00003349 }
Eli Bendersky17233942013-01-15 22:59:42 +00003350
3351 if (FileNumber == -1)
3352 getStreamer().EmitFileDirective(Filename);
3353 else {
Brian Cain3e0ca572018-08-28 16:23:39 +00003354 // In case there is a -g option as well as debug info from directive .file,
3355 // we turn off the -g option, directly use the existing debug info instead.
3356 // Also reset any implicit ".file 0" for the assembler source.
3357 if (Ctx.getGenDwarfForAssembly()) {
3358 Ctx.getMCDwarfLineTable(0).resetRootFile();
3359 Ctx.setGenDwarfForAssembly(false);
3360 }
3361
Paul Robinson29f5f982018-01-09 23:31:48 +00003362 MD5::MD5Result *CKMem = nullptr;
Paul Robinson01954692018-04-11 15:14:05 +00003363 if (HasMD5) {
Paul Robinson29f5f982018-01-09 23:31:48 +00003364 CKMem = (MD5::MD5Result *)Ctx.allocate(sizeof(MD5::MD5Result), 1);
Paul Robinson01954692018-04-11 15:14:05 +00003365 for (unsigned i = 0; i != 8; ++i) {
3366 CKMem->Bytes[i] = uint8_t(MD5Hi >> ((7 - i) * 8));
3367 CKMem->Bytes[i + 8] = uint8_t(MD5Lo >> ((7 - i) * 8));
3368 }
Paul Robinson29f5f982018-01-09 23:31:48 +00003369 }
Scott Linder16c7bda2018-02-23 23:01:06 +00003370 if (HasSource) {
3371 char *SourceBuf = static_cast<char *>(Ctx.allocate(SourceString.size()));
3372 memcpy(SourceBuf, SourceString.data(), SourceString.size());
3373 Source = StringRef(SourceBuf, SourceString.size());
3374 }
Paul Robinson547adca2018-06-21 16:42:03 +00003375 if (FileNumber == 0) {
3376 if (Ctx.getDwarfVersion() < 5)
3377 return Warning(DirectiveLoc, "file 0 not supported prior to DWARF-5");
Paul Robinsonb271f312018-03-29 17:16:41 +00003378 getStreamer().emitDwarfFile0Directive(Directory, Filename, CKMem, Source);
Paul Robinson547adca2018-06-21 16:42:03 +00003379 } else {
Paul Robinsonb271f312018-03-29 17:16:41 +00003380 Expected<unsigned> FileNumOrErr = getStreamer().tryEmitDwarfFileDirective(
3381 FileNumber, Directory, Filename, CKMem, Source);
3382 if (!FileNumOrErr)
3383 return Error(DirectiveLoc, toString(FileNumOrErr.takeError()));
3384 FileNumber = FileNumOrErr.get();
3385 }
Paul Robinsoncc7344a2018-06-14 13:38:20 +00003386 // Alert the user if there are some .file directives with MD5 and some not.
3387 // But only do that once.
3388 if (!ReportedInconsistentMD5 && !Ctx.isDwarfMD5UsageConsistent(0)) {
3389 ReportedInconsistentMD5 = true;
3390 return Warning(DirectiveLoc, "inconsistent use of MD5 checksums");
3391 }
Eli Bendersky17233942013-01-15 22:59:42 +00003392 }
3393
3394 return false;
3395}
3396
Jim Grosbach4b905842013-09-20 23:08:21 +00003397/// parseDirectiveLine
Eli Bendersky17233942013-01-15 22:59:42 +00003398/// ::= .line [number]
Jim Grosbach4b905842013-09-20 23:08:21 +00003399bool AsmParser::parseDirectiveLine() {
Nirav Davea645433c2016-07-18 15:24:03 +00003400 int64_t LineNumber;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003401 if (getLexer().is(AsmToken::Integer)) {
Nirav Davea645433c2016-07-18 15:24:03 +00003402 if (parseIntToken(LineNumber, "unexpected token in '.line' directive"))
3403 return true;
Jim Grosbach4b905842013-09-20 23:08:21 +00003404 (void)LineNumber;
Eli Bendersky17233942013-01-15 22:59:42 +00003405 // FIXME: Do something with the .line.
3406 }
Nirav Davea645433c2016-07-18 15:24:03 +00003407 if (parseToken(AsmToken::EndOfStatement,
3408 "unexpected token in '.line' directive"))
3409 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003410
3411 return false;
3412}
3413
Jim Grosbach4b905842013-09-20 23:08:21 +00003414/// parseDirectiveLoc
Eli Bendersky17233942013-01-15 22:59:42 +00003415/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
3416/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
3417/// The first number is a file number, must have been previously assigned with
3418/// a .file directive, the second number is the line number and optionally the
3419/// third number is a column position (zero if not specified). The remaining
3420/// optional items are .loc sub-directives.
Jim Grosbach4b905842013-09-20 23:08:21 +00003421bool AsmParser::parseDirectiveLoc() {
Nirav Davea645433c2016-07-18 15:24:03 +00003422 int64_t FileNumber = 0, LineNumber = 0;
3423 SMLoc Loc = getTok().getLoc();
3424 if (parseIntToken(FileNumber, "unexpected token in '.loc' directive") ||
Paul Robinson11539b02018-06-22 14:16:11 +00003425 check(FileNumber < 1 && Ctx.getDwarfVersion() < 5, Loc,
Nirav Davea645433c2016-07-18 15:24:03 +00003426 "file number less than one in '.loc' directive") ||
3427 check(!getContext().isValidDwarfFileNumber(FileNumber), Loc,
3428 "unassigned file number in '.loc' directive"))
3429 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003430
Nirav Davea645433c2016-07-18 15:24:03 +00003431 // optional
Eli Bendersky17233942013-01-15 22:59:42 +00003432 if (getLexer().is(AsmToken::Integer)) {
3433 LineNumber = getTok().getIntVal();
Adrian Prantl6ac40032013-09-26 23:37:11 +00003434 if (LineNumber < 0)
3435 return TokError("line number less than zero in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003436 Lex();
3437 }
3438
3439 int64_t ColumnPos = 0;
3440 if (getLexer().is(AsmToken::Integer)) {
3441 ColumnPos = getTok().getIntVal();
3442 if (ColumnPos < 0)
3443 return TokError("column position less than zero in '.loc' directive");
3444 Lex();
3445 }
3446
3447 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
3448 unsigned Isa = 0;
3449 int64_t Discriminator = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003450
Nirav Dave1a9044b2016-10-24 14:35:29 +00003451 auto parseLocOp = [&]() -> bool {
3452 StringRef Name;
3453 SMLoc Loc = getTok().getLoc();
3454 if (parseIdentifier(Name))
3455 return TokError("unexpected token in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003456
Nirav Dave1a9044b2016-10-24 14:35:29 +00003457 if (Name == "basic_block")
3458 Flags |= DWARF2_FLAG_BASIC_BLOCK;
3459 else if (Name == "prologue_end")
3460 Flags |= DWARF2_FLAG_PROLOGUE_END;
3461 else if (Name == "epilogue_begin")
3462 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
3463 else if (Name == "is_stmt") {
3464 Loc = getTok().getLoc();
3465 const MCExpr *Value;
3466 if (parseExpression(Value))
3467 return true;
3468 // The expression must be the constant 0 or 1.
3469 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3470 int Value = MCE->getValue();
3471 if (Value == 0)
3472 Flags &= ~DWARF2_FLAG_IS_STMT;
3473 else if (Value == 1)
3474 Flags |= DWARF2_FLAG_IS_STMT;
3475 else
3476 return Error(Loc, "is_stmt value not 0 or 1");
Craig Topperf15655b2013-04-22 04:22:40 +00003477 } else {
Nirav Dave1a9044b2016-10-24 14:35:29 +00003478 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
Eli Bendersky17233942013-01-15 22:59:42 +00003479 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003480 } else if (Name == "isa") {
3481 Loc = getTok().getLoc();
3482 const MCExpr *Value;
3483 if (parseExpression(Value))
3484 return true;
3485 // The expression must be a constant greater or equal to 0.
3486 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3487 int Value = MCE->getValue();
3488 if (Value < 0)
3489 return Error(Loc, "isa number less than zero");
3490 Isa = Value;
3491 } else {
3492 return Error(Loc, "isa number not a constant value");
3493 }
3494 } else if (Name == "discriminator") {
3495 if (parseAbsoluteExpression(Discriminator))
3496 return true;
3497 } else {
3498 return Error(Loc, "unknown sub-directive in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003499 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003500 return false;
3501 };
3502
Nirav Davee2369aa2016-10-26 17:28:58 +00003503 if (parseMany(parseLocOp, false /*hasComma*/))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003504 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003505
3506 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
3507 Isa, Discriminator, StringRef());
3508
3509 return false;
3510}
3511
Jim Grosbach4b905842013-09-20 23:08:21 +00003512/// parseDirectiveStabs
Eli Bendersky17233942013-01-15 22:59:42 +00003513/// ::= .stabs string, number, number, number
Jim Grosbach4b905842013-09-20 23:08:21 +00003514bool AsmParser::parseDirectiveStabs() {
Eli Bendersky17233942013-01-15 22:59:42 +00003515 return TokError("unsupported directive '.stabs'");
3516}
3517
Reid Kleckner2214ed82016-01-29 00:49:42 +00003518/// parseDirectiveCVFile
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003519/// ::= .cv_file number filename [checksum] [checksumkind]
Reid Kleckner2214ed82016-01-29 00:49:42 +00003520bool AsmParser::parseDirectiveCVFile() {
Nirav Davea645433c2016-07-18 15:24:03 +00003521 SMLoc FileNumberLoc = getTok().getLoc();
3522 int64_t FileNumber;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003523 std::string Filename;
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003524 std::string Checksum;
3525 int64_t ChecksumKind = 0;
Nirav Davea645433c2016-07-18 15:24:03 +00003526
3527 if (parseIntToken(FileNumber,
3528 "expected file number in '.cv_file' directive") ||
3529 check(FileNumber < 1, FileNumberLoc, "file number less than one") ||
3530 check(getTok().isNot(AsmToken::String),
3531 "unexpected token in '.cv_file' directive") ||
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003532 parseEscapedString(Filename))
Reid Klecknera5b1eef2016-08-26 17:58:37 +00003533 return true;
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003534 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
3535 if (check(getTok().isNot(AsmToken::String),
3536 "unexpected token in '.cv_file' directive") ||
3537 parseEscapedString(Checksum) ||
3538 parseIntToken(ChecksumKind,
3539 "expected checksum kind in '.cv_file' directive") ||
3540 parseToken(AsmToken::EndOfStatement,
3541 "unexpected token in '.cv_file' directive"))
3542 return true;
3543 }
Nirav Dave1ab71992016-07-18 19:35:21 +00003544
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003545 Checksum = fromHex(Checksum);
3546 void *CKMem = Ctx.allocate(Checksum.size(), 1);
3547 memcpy(CKMem, Checksum.data(), Checksum.size());
3548 ArrayRef<uint8_t> ChecksumAsBytes(reinterpret_cast<const uint8_t *>(CKMem),
3549 Checksum.size());
3550
3551 if (!getStreamer().EmitCVFileDirective(FileNumber, Filename, ChecksumAsBytes,
3552 static_cast<uint8_t>(ChecksumKind)))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003553 return Error(FileNumberLoc, "file number already allocated");
Reid Kleckner2214ed82016-01-29 00:49:42 +00003554
3555 return false;
3556}
3557
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003558bool AsmParser::parseCVFunctionId(int64_t &FunctionId,
3559 StringRef DirectiveName) {
3560 SMLoc Loc;
3561 return parseTokenLoc(Loc) ||
3562 parseIntToken(FunctionId, "expected function id in '" + DirectiveName +
3563 "' directive") ||
3564 check(FunctionId < 0 || FunctionId >= UINT_MAX, Loc,
3565 "expected function id within range [0, UINT_MAX)");
3566}
3567
3568bool AsmParser::parseCVFileId(int64_t &FileNumber, StringRef DirectiveName) {
3569 SMLoc Loc;
3570 return parseTokenLoc(Loc) ||
3571 parseIntToken(FileNumber, "expected integer in '" + DirectiveName +
3572 "' directive") ||
3573 check(FileNumber < 1, Loc, "file number less than one in '" +
3574 DirectiveName + "' directive") ||
3575 check(!getCVContext().isValidFileNumber(FileNumber), Loc,
3576 "unassigned file number in '" + DirectiveName + "' directive");
3577}
3578
3579/// parseDirectiveCVFuncId
3580/// ::= .cv_func_id FunctionId
3581///
3582/// Introduces a function ID that can be used with .cv_loc.
3583bool AsmParser::parseDirectiveCVFuncId() {
3584 SMLoc FunctionIdLoc = getTok().getLoc();
3585 int64_t FunctionId;
3586
3587 if (parseCVFunctionId(FunctionId, ".cv_func_id") ||
3588 parseToken(AsmToken::EndOfStatement,
3589 "unexpected token in '.cv_func_id' directive"))
3590 return true;
3591
3592 if (!getStreamer().EmitCVFuncIdDirective(FunctionId))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003593 return Error(FunctionIdLoc, "function id already allocated");
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003594
3595 return false;
3596}
3597
3598/// parseDirectiveCVInlineSiteId
3599/// ::= .cv_inline_site_id FunctionId
3600/// "within" IAFunc
3601/// "inlined_at" IAFile IALine [IACol]
3602///
3603/// Introduces a function ID that can be used with .cv_loc. Includes "inlined
3604/// at" source location information for use in the line table of the caller,
3605/// whether the caller is a real function or another inlined call site.
3606bool AsmParser::parseDirectiveCVInlineSiteId() {
3607 SMLoc FunctionIdLoc = getTok().getLoc();
3608 int64_t FunctionId;
3609 int64_t IAFunc;
3610 int64_t IAFile;
3611 int64_t IALine;
3612 int64_t IACol = 0;
3613
3614 // FunctionId
3615 if (parseCVFunctionId(FunctionId, ".cv_inline_site_id"))
3616 return true;
3617
3618 // "within"
3619 if (check((getLexer().isNot(AsmToken::Identifier) ||
3620 getTok().getIdentifier() != "within"),
3621 "expected 'within' identifier in '.cv_inline_site_id' directive"))
3622 return true;
3623 Lex();
3624
3625 // IAFunc
3626 if (parseCVFunctionId(IAFunc, ".cv_inline_site_id"))
3627 return true;
3628
3629 // "inlined_at"
3630 if (check((getLexer().isNot(AsmToken::Identifier) ||
3631 getTok().getIdentifier() != "inlined_at"),
3632 "expected 'inlined_at' identifier in '.cv_inline_site_id' "
3633 "directive") )
3634 return true;
3635 Lex();
3636
3637 // IAFile IALine
3638 if (parseCVFileId(IAFile, ".cv_inline_site_id") ||
3639 parseIntToken(IALine, "expected line number after 'inlined_at'"))
3640 return true;
3641
3642 // [IACol]
3643 if (getLexer().is(AsmToken::Integer)) {
3644 IACol = getTok().getIntVal();
3645 Lex();
3646 }
3647
3648 if (parseToken(AsmToken::EndOfStatement,
3649 "unexpected token in '.cv_inline_site_id' directive"))
3650 return true;
3651
3652 if (!getStreamer().EmitCVInlineSiteIdDirective(FunctionId, IAFunc, IAFile,
3653 IALine, IACol, FunctionIdLoc))
Nirav Dave2364748a2016-09-16 18:30:20 +00003654 return Error(FunctionIdLoc, "function id already allocated");
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003655
3656 return false;
3657}
3658
Reid Kleckner2214ed82016-01-29 00:49:42 +00003659/// parseDirectiveCVLoc
3660/// ::= .cv_loc FunctionId FileNumber [LineNumber] [ColumnPos] [prologue_end]
3661/// [is_stmt VALUE]
3662/// The first number is a file number, must have been previously assigned with
3663/// a .file directive, the second number is the line number and optionally the
3664/// third number is a column position (zero if not specified). The remaining
3665/// optional items are .loc sub-directives.
3666bool AsmParser::parseDirectiveCVLoc() {
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003667 SMLoc DirectiveLoc = getTok().getLoc();
Nirav Davea645433c2016-07-18 15:24:03 +00003668 int64_t FunctionId, FileNumber;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003669 if (parseCVFunctionId(FunctionId, ".cv_loc") ||
3670 parseCVFileId(FileNumber, ".cv_loc"))
Nirav Davea645433c2016-07-18 15:24:03 +00003671 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003672
3673 int64_t LineNumber = 0;
3674 if (getLexer().is(AsmToken::Integer)) {
3675 LineNumber = getTok().getIntVal();
3676 if (LineNumber < 0)
3677 return TokError("line number less than zero in '.cv_loc' directive");
3678 Lex();
3679 }
3680
3681 int64_t ColumnPos = 0;
3682 if (getLexer().is(AsmToken::Integer)) {
3683 ColumnPos = getTok().getIntVal();
3684 if (ColumnPos < 0)
3685 return TokError("column position less than zero in '.cv_loc' directive");
3686 Lex();
3687 }
3688
3689 bool PrologueEnd = false;
3690 uint64_t IsStmt = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003691
3692 auto parseOp = [&]() -> bool {
Reid Kleckner2214ed82016-01-29 00:49:42 +00003693 StringRef Name;
3694 SMLoc Loc = getTok().getLoc();
3695 if (parseIdentifier(Name))
3696 return TokError("unexpected token in '.cv_loc' directive");
Reid Kleckner2214ed82016-01-29 00:49:42 +00003697 if (Name == "prologue_end")
3698 PrologueEnd = true;
3699 else if (Name == "is_stmt") {
3700 Loc = getTok().getLoc();
3701 const MCExpr *Value;
3702 if (parseExpression(Value))
3703 return true;
3704 // The expression must be the constant 0 or 1.
3705 IsStmt = ~0ULL;
3706 if (const auto *MCE = dyn_cast<MCConstantExpr>(Value))
3707 IsStmt = MCE->getValue();
3708
3709 if (IsStmt > 1)
3710 return Error(Loc, "is_stmt value not 0 or 1");
3711 } else {
3712 return Error(Loc, "unknown sub-directive in '.cv_loc' directive");
3713 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003714 return false;
3715 };
3716
3717 if (parseMany(parseOp, false /*hasComma*/))
3718 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003719
3720 getStreamer().EmitCVLocDirective(FunctionId, FileNumber, LineNumber,
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003721 ColumnPos, PrologueEnd, IsStmt, StringRef(),
3722 DirectiveLoc);
Reid Kleckner2214ed82016-01-29 00:49:42 +00003723 return false;
3724}
3725
3726/// parseDirectiveCVLinetable
3727/// ::= .cv_linetable FunctionId, FnStart, FnEnd
3728bool AsmParser::parseDirectiveCVLinetable() {
Nirav Davea645433c2016-07-18 15:24:03 +00003729 int64_t FunctionId;
3730 StringRef FnStartName, FnEndName;
3731 SMLoc Loc = getTok().getLoc();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003732 if (parseCVFunctionId(FunctionId, ".cv_linetable") ||
Nirav Davea645433c2016-07-18 15:24:03 +00003733 parseToken(AsmToken::Comma,
3734 "unexpected token in '.cv_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003735 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3736 "expected identifier in directive") ||
Nirav Davea645433c2016-07-18 15:24:03 +00003737 parseToken(AsmToken::Comma,
3738 "unexpected token in '.cv_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003739 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3740 "expected identifier in directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00003741 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003742
3743 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3744 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
3745
3746 getStreamer().EmitCVLinetableDirective(FunctionId, FnStartSym, FnEndSym);
3747 return false;
3748}
3749
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003750/// parseDirectiveCVInlineLinetable
David Majnemerc9911f22016-02-02 19:22:34 +00003751/// ::= .cv_inline_linetable PrimaryFunctionId FileId LineNum FnStart FnEnd
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003752bool AsmParser::parseDirectiveCVInlineLinetable() {
Nirav Davea645433c2016-07-18 15:24:03 +00003753 int64_t PrimaryFunctionId, SourceFileId, SourceLineNum;
3754 StringRef FnStartName, FnEndName;
3755 SMLoc Loc = getTok().getLoc();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003756 if (parseCVFunctionId(PrimaryFunctionId, ".cv_inline_linetable") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003757 parseTokenLoc(Loc) ||
Nirav Davea645433c2016-07-18 15:24:03 +00003758 parseIntToken(
3759 SourceFileId,
3760 "expected SourceField in '.cv_inline_linetable' directive") ||
3761 check(SourceFileId <= 0, Loc,
3762 "File id less than zero in '.cv_inline_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003763 parseTokenLoc(Loc) ||
Nirav Davea645433c2016-07-18 15:24:03 +00003764 parseIntToken(
3765 SourceLineNum,
3766 "expected SourceLineNum in '.cv_inline_linetable' directive") ||
3767 check(SourceLineNum < 0, Loc,
3768 "Line number less than zero in '.cv_inline_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003769 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3770 "expected identifier in directive") ||
3771 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3772 "expected identifier in directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00003773 return true;
David Majnemerc9911f22016-02-02 19:22:34 +00003774
Nirav Davea645433c2016-07-18 15:24:03 +00003775 if (parseToken(AsmToken::EndOfStatement, "Expected End of Statement"))
3776 return true;
3777
3778 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3779 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
Reid Kleckner1fcd6102016-02-02 17:41:18 +00003780 getStreamer().EmitCVInlineLinetableDirective(PrimaryFunctionId, SourceFileId,
3781 SourceLineNum, FnStartSym,
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003782 FnEndSym);
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003783 return false;
3784}
3785
David Majnemer408b5e62016-02-05 01:55:49 +00003786/// parseDirectiveCVDefRange
3787/// ::= .cv_def_range RangeStart RangeEnd (GapStart GapEnd)*, bytes*
3788bool AsmParser::parseDirectiveCVDefRange() {
3789 SMLoc Loc;
3790 std::vector<std::pair<const MCSymbol *, const MCSymbol *>> Ranges;
3791 while (getLexer().is(AsmToken::Identifier)) {
3792 Loc = getLexer().getLoc();
3793 StringRef GapStartName;
3794 if (parseIdentifier(GapStartName))
3795 return Error(Loc, "expected identifier in directive");
3796 MCSymbol *GapStartSym = getContext().getOrCreateSymbol(GapStartName);
3797
3798 Loc = getLexer().getLoc();
3799 StringRef GapEndName;
3800 if (parseIdentifier(GapEndName))
3801 return Error(Loc, "expected identifier in directive");
3802 MCSymbol *GapEndSym = getContext().getOrCreateSymbol(GapEndName);
3803
3804 Ranges.push_back({GapStartSym, GapEndSym});
3805 }
3806
David Majnemer408b5e62016-02-05 01:55:49 +00003807 std::string FixedSizePortion;
Nirav Davea645433c2016-07-18 15:24:03 +00003808 if (parseToken(AsmToken::Comma, "unexpected token in directive") ||
3809 parseEscapedString(FixedSizePortion))
David Majnemer408b5e62016-02-05 01:55:49 +00003810 return true;
David Majnemer408b5e62016-02-05 01:55:49 +00003811
3812 getStreamer().EmitCVDefRangeDirective(Ranges, FixedSizePortion);
3813 return false;
3814}
3815
Reid Kleckner2214ed82016-01-29 00:49:42 +00003816/// parseDirectiveCVStringTable
3817/// ::= .cv_stringtable
3818bool AsmParser::parseDirectiveCVStringTable() {
3819 getStreamer().EmitCVStringTableDirective();
3820 return false;
3821}
3822
3823/// parseDirectiveCVFileChecksums
3824/// ::= .cv_filechecksums
3825bool AsmParser::parseDirectiveCVFileChecksums() {
3826 getStreamer().EmitCVFileChecksumsDirective();
3827 return false;
3828}
3829
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003830/// parseDirectiveCVFileChecksumOffset
3831/// ::= .cv_filechecksumoffset fileno
3832bool AsmParser::parseDirectiveCVFileChecksumOffset() {
3833 int64_t FileNo;
3834 if (parseIntToken(FileNo, "expected identifier in directive"))
3835 return true;
3836 if (parseToken(AsmToken::EndOfStatement, "Expected End of Statement"))
3837 return true;
3838 getStreamer().EmitCVFileChecksumOffsetDirective(FileNo);
3839 return false;
3840}
3841
Reid Kleckner9cdd4df2017-10-11 21:24:33 +00003842/// parseDirectiveCVFPOData
3843/// ::= .cv_fpo_data procsym
3844bool AsmParser::parseDirectiveCVFPOData() {
3845 SMLoc DirLoc = getLexer().getLoc();
3846 StringRef ProcName;
3847 if (parseIdentifier(ProcName))
3848 return TokError("expected symbol name");
3849 if (parseEOL("unexpected tokens"))
3850 return addErrorSuffix(" in '.cv_fpo_data' directive");
3851 MCSymbol *ProcSym = getContext().getOrCreateSymbol(ProcName);
3852 getStreamer().EmitCVFPOData(ProcSym, DirLoc);
3853 return false;
3854}
3855
Jim Grosbach4b905842013-09-20 23:08:21 +00003856/// parseDirectiveCFISections
Eli Bendersky17233942013-01-15 22:59:42 +00003857/// ::= .cfi_sections section [, section]
Jim Grosbach4b905842013-09-20 23:08:21 +00003858bool AsmParser::parseDirectiveCFISections() {
Eli Bendersky17233942013-01-15 22:59:42 +00003859 StringRef Name;
3860 bool EH = false;
3861 bool Debug = false;
3862
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003863 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003864 return TokError("Expected an identifier");
3865
3866 if (Name == ".eh_frame")
3867 EH = true;
3868 else if (Name == ".debug_frame")
3869 Debug = true;
3870
3871 if (getLexer().is(AsmToken::Comma)) {
3872 Lex();
3873
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003874 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003875 return TokError("Expected an identifier");
3876
3877 if (Name == ".eh_frame")
3878 EH = true;
3879 else if (Name == ".debug_frame")
3880 Debug = true;
3881 }
3882
3883 getStreamer().EmitCFISections(EH, Debug);
3884 return false;
3885}
3886
Jim Grosbach4b905842013-09-20 23:08:21 +00003887/// parseDirectiveCFIStartProc
David Majnemere035cf92014-01-27 17:20:25 +00003888/// ::= .cfi_startproc [simple]
Jim Grosbach4b905842013-09-20 23:08:21 +00003889bool AsmParser::parseDirectiveCFIStartProc() {
David Majnemere035cf92014-01-27 17:20:25 +00003890 StringRef Simple;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003891 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
3892 if (check(parseIdentifier(Simple) || Simple != "simple",
3893 "unexpected token") ||
3894 parseToken(AsmToken::EndOfStatement))
3895 return addErrorSuffix(" in '.cfi_startproc' directive");
3896 }
Nirav Davea645433c2016-07-18 15:24:03 +00003897
Oliver Stannardcf6bfb12014-11-03 12:19:03 +00003898 getStreamer().EmitCFIStartProc(!Simple.empty());
Eli Bendersky17233942013-01-15 22:59:42 +00003899 return false;
3900}
3901
Jim Grosbach4b905842013-09-20 23:08:21 +00003902/// parseDirectiveCFIEndProc
Eli Bendersky17233942013-01-15 22:59:42 +00003903/// ::= .cfi_endproc
Jim Grosbach4b905842013-09-20 23:08:21 +00003904bool AsmParser::parseDirectiveCFIEndProc() {
Eli Bendersky17233942013-01-15 22:59:42 +00003905 getStreamer().EmitCFIEndProc();
3906 return false;
3907}
3908
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003909/// parse register name or number.
Jim Grosbach4b905842013-09-20 23:08:21 +00003910bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
Eli Bendersky17233942013-01-15 22:59:42 +00003911 SMLoc DirectiveLoc) {
3912 unsigned RegNo;
3913
3914 if (getLexer().isNot(AsmToken::Integer)) {
3915 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
3916 return true;
Bill Wendlingbc07a892013-06-18 07:20:20 +00003917 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
Eli Bendersky17233942013-01-15 22:59:42 +00003918 } else
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003919 return parseAbsoluteExpression(Register);
Eli Bendersky17233942013-01-15 22:59:42 +00003920
3921 return false;
3922}
3923
Jim Grosbach4b905842013-09-20 23:08:21 +00003924/// parseDirectiveCFIDefCfa
Eli Bendersky17233942013-01-15 22:59:42 +00003925/// ::= .cfi_def_cfa register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003926bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003927 int64_t Register = 0, Offset = 0;
3928 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3929 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3930 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003931 return true;
3932
3933 getStreamer().EmitCFIDefCfa(Register, Offset);
3934 return false;
3935}
3936
Jim Grosbach4b905842013-09-20 23:08:21 +00003937/// parseDirectiveCFIDefCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003938/// ::= .cfi_def_cfa_offset offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003939bool AsmParser::parseDirectiveCFIDefCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00003940 int64_t Offset = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003941 if (parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003942 return true;
3943
3944 getStreamer().EmitCFIDefCfaOffset(Offset);
3945 return false;
3946}
3947
Jim Grosbach4b905842013-09-20 23:08:21 +00003948/// parseDirectiveCFIRegister
Eli Bendersky17233942013-01-15 22:59:42 +00003949/// ::= .cfi_register register, register
Jim Grosbach4b905842013-09-20 23:08:21 +00003950bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003951 int64_t Register1 = 0, Register2 = 0;
3952 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc) ||
3953 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3954 parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003955 return true;
3956
3957 getStreamer().EmitCFIRegister(Register1, Register2);
3958 return false;
3959}
3960
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00003961/// parseDirectiveCFIWindowSave
3962/// ::= .cfi_window_save
3963bool AsmParser::parseDirectiveCFIWindowSave() {
3964 getStreamer().EmitCFIWindowSave();
3965 return false;
3966}
3967
Jim Grosbach4b905842013-09-20 23:08:21 +00003968/// parseDirectiveCFIAdjustCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003969/// ::= .cfi_adjust_cfa_offset adjustment
Jim Grosbach4b905842013-09-20 23:08:21 +00003970bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00003971 int64_t Adjustment = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003972 if (parseAbsoluteExpression(Adjustment))
Eli Bendersky17233942013-01-15 22:59:42 +00003973 return true;
3974
3975 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3976 return false;
3977}
3978
Jim Grosbach4b905842013-09-20 23:08:21 +00003979/// parseDirectiveCFIDefCfaRegister
Eli Bendersky17233942013-01-15 22:59:42 +00003980/// ::= .cfi_def_cfa_register register
Jim Grosbach4b905842013-09-20 23:08:21 +00003981bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003982 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003983 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003984 return true;
3985
3986 getStreamer().EmitCFIDefCfaRegister(Register);
3987 return false;
3988}
3989
Jim Grosbach4b905842013-09-20 23:08:21 +00003990/// parseDirectiveCFIOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003991/// ::= .cfi_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003992bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003993 int64_t Register = 0;
3994 int64_t Offset = 0;
3995
Nirav Davea645433c2016-07-18 15:24:03 +00003996 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3997 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3998 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003999 return true;
4000
4001 getStreamer().EmitCFIOffset(Register, Offset);
4002 return false;
4003}
4004
Jim Grosbach4b905842013-09-20 23:08:21 +00004005/// parseDirectiveCFIRelOffset
Eli Bendersky17233942013-01-15 22:59:42 +00004006/// ::= .cfi_rel_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00004007bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00004008 int64_t Register = 0, Offset = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00004009
Nirav Davea645433c2016-07-18 15:24:03 +00004010 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
4011 parseToken(AsmToken::Comma, "unexpected token in directive") ||
4012 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00004013 return true;
4014
4015 getStreamer().EmitCFIRelOffset(Register, Offset);
4016 return false;
4017}
4018
4019static bool isValidEncoding(int64_t Encoding) {
4020 if (Encoding & ~0xff)
4021 return false;
4022
4023 if (Encoding == dwarf::DW_EH_PE_omit)
4024 return true;
4025
4026 const unsigned Format = Encoding & 0xf;
4027 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
4028 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
4029 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
4030 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
4031 return false;
4032
4033 const unsigned Application = Encoding & 0x70;
4034 if (Application != dwarf::DW_EH_PE_absptr &&
4035 Application != dwarf::DW_EH_PE_pcrel)
4036 return false;
4037
4038 return true;
4039}
4040
Jim Grosbach4b905842013-09-20 23:08:21 +00004041/// parseDirectiveCFIPersonalityOrLsda
Eli Bendersky17233942013-01-15 22:59:42 +00004042/// IsPersonality true for cfi_personality, false for cfi_lsda
4043/// ::= .cfi_personality encoding, [symbol_name]
4044/// ::= .cfi_lsda encoding, [symbol_name]
Jim Grosbach4b905842013-09-20 23:08:21 +00004045bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
Eli Bendersky17233942013-01-15 22:59:42 +00004046 int64_t Encoding = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004047 if (parseAbsoluteExpression(Encoding))
Eli Bendersky17233942013-01-15 22:59:42 +00004048 return true;
4049 if (Encoding == dwarf::DW_EH_PE_omit)
4050 return false;
4051
Eli Bendersky17233942013-01-15 22:59:42 +00004052 StringRef Name;
Nirav Davea645433c2016-07-18 15:24:03 +00004053 if (check(!isValidEncoding(Encoding), "unsupported encoding.") ||
4054 parseToken(AsmToken::Comma, "unexpected token in directive") ||
4055 check(parseIdentifier(Name), "expected identifier in directive"))
4056 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004057
Jim Grosbach6f482002015-05-18 18:43:14 +00004058 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Eli Bendersky17233942013-01-15 22:59:42 +00004059
4060 if (IsPersonality)
4061 getStreamer().EmitCFIPersonality(Sym, Encoding);
4062 else
4063 getStreamer().EmitCFILsda(Sym, Encoding);
4064 return false;
4065}
4066
Jim Grosbach4b905842013-09-20 23:08:21 +00004067/// parseDirectiveCFIRememberState
Eli Bendersky17233942013-01-15 22:59:42 +00004068/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00004069bool AsmParser::parseDirectiveCFIRememberState() {
Eli Bendersky17233942013-01-15 22:59:42 +00004070 getStreamer().EmitCFIRememberState();
4071 return false;
4072}
4073
Jim Grosbach4b905842013-09-20 23:08:21 +00004074/// parseDirectiveCFIRestoreState
Eli Bendersky17233942013-01-15 22:59:42 +00004075/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00004076bool AsmParser::parseDirectiveCFIRestoreState() {
Eli Bendersky17233942013-01-15 22:59:42 +00004077 getStreamer().EmitCFIRestoreState();
4078 return false;
4079}
4080
Jim Grosbach4b905842013-09-20 23:08:21 +00004081/// parseDirectiveCFISameValue
Eli Bendersky17233942013-01-15 22:59:42 +00004082/// ::= .cfi_same_value register
Jim Grosbach4b905842013-09-20 23:08:21 +00004083bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004084 int64_t Register = 0;
4085
Jim Grosbach4b905842013-09-20 23:08:21 +00004086 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00004087 return true;
4088
4089 getStreamer().EmitCFISameValue(Register);
4090 return false;
4091}
4092
Jim Grosbach4b905842013-09-20 23:08:21 +00004093/// parseDirectiveCFIRestore
Eli Bendersky17233942013-01-15 22:59:42 +00004094/// ::= .cfi_restore register
Jim Grosbach4b905842013-09-20 23:08:21 +00004095bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004096 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00004097 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00004098 return true;
4099
4100 getStreamer().EmitCFIRestore(Register);
4101 return false;
4102}
4103
Jim Grosbach4b905842013-09-20 23:08:21 +00004104/// parseDirectiveCFIEscape
Eli Bendersky17233942013-01-15 22:59:42 +00004105/// ::= .cfi_escape expression[,...]
Jim Grosbach4b905842013-09-20 23:08:21 +00004106bool AsmParser::parseDirectiveCFIEscape() {
Eli Bendersky17233942013-01-15 22:59:42 +00004107 std::string Values;
4108 int64_t CurrValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004109 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00004110 return true;
4111
4112 Values.push_back((uint8_t)CurrValue);
4113
4114 while (getLexer().is(AsmToken::Comma)) {
4115 Lex();
4116
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004117 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00004118 return true;
4119
4120 Values.push_back((uint8_t)CurrValue);
4121 }
4122
4123 getStreamer().EmitCFIEscape(Values);
4124 return false;
4125}
4126
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +00004127/// parseDirectiveCFIReturnColumn
4128/// ::= .cfi_return_column register
4129bool AsmParser::parseDirectiveCFIReturnColumn(SMLoc DirectiveLoc) {
4130 int64_t Register = 0;
4131 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
4132 return true;
4133 getStreamer().EmitCFIReturnColumn(Register);
4134 return false;
4135}
4136
Jim Grosbach4b905842013-09-20 23:08:21 +00004137/// parseDirectiveCFISignalFrame
Eli Bendersky17233942013-01-15 22:59:42 +00004138/// ::= .cfi_signal_frame
Jim Grosbach4b905842013-09-20 23:08:21 +00004139bool AsmParser::parseDirectiveCFISignalFrame() {
Nirav Davea645433c2016-07-18 15:24:03 +00004140 if (parseToken(AsmToken::EndOfStatement,
4141 "unexpected token in '.cfi_signal_frame'"))
4142 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004143
4144 getStreamer().EmitCFISignalFrame();
4145 return false;
4146}
4147
Jim Grosbach4b905842013-09-20 23:08:21 +00004148/// parseDirectiveCFIUndefined
Eli Bendersky17233942013-01-15 22:59:42 +00004149/// ::= .cfi_undefined register
Jim Grosbach4b905842013-09-20 23:08:21 +00004150bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004151 int64_t Register = 0;
4152
Jim Grosbach4b905842013-09-20 23:08:21 +00004153 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00004154 return true;
4155
4156 getStreamer().EmitCFIUndefined(Register);
4157 return false;
4158}
4159
Michael Zuckerman56704612017-05-01 13:20:12 +00004160/// parseDirectiveAltmacro
4161/// ::= .altmacro
4162/// ::= .noaltmacro
4163bool AsmParser::parseDirectiveAltmacro(StringRef Directive) {
4164 if (getLexer().isNot(AsmToken::EndOfStatement))
4165 return TokError("unexpected token in '" + Directive + "' directive");
4166 if (Directive == ".altmacro")
4167 getLexer().SetAltMacroMode(true);
4168 else
4169 getLexer().SetAltMacroMode(false);
4170 return false;
4171}
4172
Jim Grosbach4b905842013-09-20 23:08:21 +00004173/// parseDirectiveMacrosOnOff
Eli Bendersky17233942013-01-15 22:59:42 +00004174/// ::= .macros_on
4175/// ::= .macros_off
Jim Grosbach4b905842013-09-20 23:08:21 +00004176bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
Nirav Davea645433c2016-07-18 15:24:03 +00004177 if (parseToken(AsmToken::EndOfStatement,
4178 "unexpected token in '" + Directive + "' directive"))
4179 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004180
Jim Grosbach4b905842013-09-20 23:08:21 +00004181 setMacrosEnabled(Directive == ".macros_on");
Eli Bendersky17233942013-01-15 22:59:42 +00004182 return false;
4183}
4184
Jim Grosbach4b905842013-09-20 23:08:21 +00004185/// parseDirectiveMacro
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00004186/// ::= .macro name[,] [parameters]
Jim Grosbach4b905842013-09-20 23:08:21 +00004187bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004188 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004189 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00004190 return TokError("expected identifier in '.macro' directive");
4191
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00004192 if (getLexer().is(AsmToken::Comma))
4193 Lex();
4194
Eli Bendersky17233942013-01-15 22:59:42 +00004195 MCAsmMacroParameters Parameters;
David Majnemer91fc4c22014-01-29 18:57:46 +00004196 while (getLexer().isNot(AsmToken::EndOfStatement)) {
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00004197
Alexander Kornienko8c0809c2015-01-15 11:41:30 +00004198 if (!Parameters.empty() && Parameters.back().Vararg)
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00004199 return Error(Lexer.getLoc(),
4200 "Vararg parameter '" + Parameters.back().Name +
4201 "' should be last one in the list of parameters.");
4202
David Majnemer91fc4c22014-01-29 18:57:46 +00004203 MCAsmMacroParameter Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00004204 if (parseIdentifier(Parameter.Name))
David Majnemer91fc4c22014-01-29 18:57:46 +00004205 return TokError("expected identifier in '.macro' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00004206
Coby Tayreebedaae02017-04-08 20:29:03 +00004207 // Emit an error if two (or more) named parameters share the same name
4208 for (const MCAsmMacroParameter& CurrParam : Parameters)
4209 if (CurrParam.Name.equals(Parameter.Name))
4210 return TokError("macro '" + Name + "' has multiple parameters"
4211 " named '" + Parameter.Name + "'");
4212
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00004213 if (Lexer.is(AsmToken::Colon)) {
4214 Lex(); // consume ':'
4215
4216 SMLoc QualLoc;
4217 StringRef Qualifier;
4218
4219 QualLoc = Lexer.getLoc();
4220 if (parseIdentifier(Qualifier))
4221 return Error(QualLoc, "missing parameter qualifier for "
4222 "'" + Parameter.Name + "' in macro '" + Name + "'");
4223
4224 if (Qualifier == "req")
4225 Parameter.Required = true;
Kevin Enderbye3c13462014-08-04 23:14:37 +00004226 else if (Qualifier == "vararg")
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00004227 Parameter.Vararg = true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00004228 else
4229 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
4230 "for '" + Parameter.Name + "' in macro '" + Name + "'");
4231 }
4232
David Majnemer91fc4c22014-01-29 18:57:46 +00004233 if (getLexer().is(AsmToken::Equal)) {
4234 Lex();
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00004235
4236 SMLoc ParamLoc;
4237
4238 ParamLoc = Lexer.getLoc();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00004239 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
David Majnemer91fc4c22014-01-29 18:57:46 +00004240 return true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00004241
4242 if (Parameter.Required)
4243 Warning(ParamLoc, "pointless default value for required parameter "
4244 "'" + Parameter.Name + "' in macro '" + Name + "'");
Eli Bendersky17233942013-01-15 22:59:42 +00004245 }
David Majnemer91fc4c22014-01-29 18:57:46 +00004246
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00004247 Parameters.push_back(std::move(Parameter));
David Majnemer91fc4c22014-01-29 18:57:46 +00004248
4249 if (getLexer().is(AsmToken::Comma))
4250 Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00004251 }
4252
Nirav Dave1180e6892016-06-02 17:15:05 +00004253 // Eat just the end of statement.
4254 Lexer.Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00004255
Nirav Dave1180e6892016-06-02 17:15:05 +00004256 // Consuming deferred text, so use Lexer.Lex to ignore Lexing Errors
Eli Bendersky17233942013-01-15 22:59:42 +00004257 AsmToken EndToken, StartToken = getTok();
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00004258 unsigned MacroDepth = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00004259 // Lex the macro definition.
Eugene Zelenko33d7b762016-08-23 17:14:32 +00004260 while (true) {
Nirav Dave1180e6892016-06-02 17:15:05 +00004261 // Ignore Lexing errors in macros.
4262 while (Lexer.is(AsmToken::Error)) {
4263 Lexer.Lex();
4264 }
4265
Eli Bendersky17233942013-01-15 22:59:42 +00004266 // Check whether we have reached the end of the file.
4267 if (getLexer().is(AsmToken::Eof))
4268 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
4269
4270 // Otherwise, check whether we have reach the .endmacro.
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00004271 if (getLexer().is(AsmToken::Identifier)) {
4272 if (getTok().getIdentifier() == ".endm" ||
4273 getTok().getIdentifier() == ".endmacro") {
4274 if (MacroDepth == 0) { // Outermost macro.
4275 EndToken = getTok();
Nirav Dave1180e6892016-06-02 17:15:05 +00004276 Lexer.Lex();
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00004277 if (getLexer().isNot(AsmToken::EndOfStatement))
4278 return TokError("unexpected token in '" + EndToken.getIdentifier() +
4279 "' directive");
4280 break;
4281 } else {
4282 // Otherwise we just found the end of an inner macro.
4283 --MacroDepth;
4284 }
4285 } else if (getTok().getIdentifier() == ".macro") {
4286 // We allow nested macros. Those aren't instantiated until the outermost
4287 // macro is expanded so just ignore them for now.
4288 ++MacroDepth;
4289 }
Eli Bendersky17233942013-01-15 22:59:42 +00004290 }
4291
4292 // Otherwise, scan til the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004293 eatToEndOfStatement();
Eli Bendersky17233942013-01-15 22:59:42 +00004294 }
4295
Rafael Espindola22c38a02018-02-14 16:34:27 +00004296 if (getContext().lookupMacro(Name)) {
Eli Bendersky17233942013-01-15 22:59:42 +00004297 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
4298 }
4299
4300 const char *BodyStart = StartToken.getLoc().getPointer();
4301 const char *BodyEnd = EndToken.getLoc().getPointer();
4302 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Jim Grosbach4b905842013-09-20 23:08:21 +00004303 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
Oliver Stannardc3e7c6d2018-03-06 15:32:34 +00004304 MCAsmMacro Macro(Name, Body, std::move(Parameters));
4305 DEBUG_WITH_TYPE("asm-macros", dbgs() << "Defining new macro:\n";
4306 Macro.dump());
4307 getContext().defineMacro(Name, std::move(Macro));
Eli Bendersky17233942013-01-15 22:59:42 +00004308 return false;
4309}
4310
Jim Grosbach4b905842013-09-20 23:08:21 +00004311/// checkForBadMacro
Kevin Enderby81c944c2013-01-22 21:44:53 +00004312///
4313/// With the support added for named parameters there may be code out there that
4314/// is transitioning from positional parameters. In versions of gas that did
Alp Tokercb402912014-01-24 17:20:08 +00004315/// not support named parameters they would be ignored on the macro definition.
Kevin Enderby81c944c2013-01-22 21:44:53 +00004316/// But to support both styles of parameters this is not possible so if a macro
Alp Tokercb402912014-01-24 17:20:08 +00004317/// definition has named parameters but does not use them and has what appears
Kevin Enderby81c944c2013-01-22 21:44:53 +00004318/// to be positional parameters, strings like $1, $2, ... and $n, then issue a
4319/// warning that the positional parameter found in body which have no effect.
4320/// Hoping the developer will either remove the named parameters from the macro
Alp Tokercb402912014-01-24 17:20:08 +00004321/// definition so the positional parameters get used if that was what was
Kevin Enderby81c944c2013-01-22 21:44:53 +00004322/// intended or change the macro to use the named parameters. It is possible
4323/// this warning will trigger when the none of the named parameters are used
4324/// and the strings like $1 are infact to simply to be passed trough unchanged.
Jim Grosbach4b905842013-09-20 23:08:21 +00004325void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
Kevin Enderby81c944c2013-01-22 21:44:53 +00004326 StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00004327 ArrayRef<MCAsmMacroParameter> Parameters) {
Kevin Enderby81c944c2013-01-22 21:44:53 +00004328 // If this macro is not defined with named parameters the warning we are
4329 // checking for here doesn't apply.
4330 unsigned NParameters = Parameters.size();
4331 if (NParameters == 0)
4332 return;
4333
4334 bool NamedParametersFound = false;
4335 bool PositionalParametersFound = false;
4336
4337 // Look at the body of the macro for use of both the named parameters and what
4338 // are likely to be positional parameters. This is what expandMacro() is
4339 // doing when it finds the parameters in the body.
4340 while (!Body.empty()) {
4341 // Scan for the next possible parameter.
4342 std::size_t End = Body.size(), Pos = 0;
4343 for (; Pos != End; ++Pos) {
4344 // Check for a substitution or escape.
4345 // This macro is defined with parameters, look for \foo, \bar, etc.
4346 if (Body[Pos] == '\\' && Pos + 1 != End)
4347 break;
4348
4349 // This macro should have parameters, but look for $0, $1, ..., $n too.
4350 if (Body[Pos] != '$' || Pos + 1 == End)
4351 continue;
4352 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00004353 if (Next == '$' || Next == 'n' ||
4354 isdigit(static_cast<unsigned char>(Next)))
Kevin Enderby81c944c2013-01-22 21:44:53 +00004355 break;
4356 }
4357
4358 // Check if we reached the end.
4359 if (Pos == End)
4360 break;
4361
4362 if (Body[Pos] == '$') {
Jim Grosbach4b905842013-09-20 23:08:21 +00004363 switch (Body[Pos + 1]) {
4364 // $$ => $
Kevin Enderby81c944c2013-01-22 21:44:53 +00004365 case '$':
4366 break;
4367
Jim Grosbach4b905842013-09-20 23:08:21 +00004368 // $n => number of arguments
Kevin Enderby81c944c2013-01-22 21:44:53 +00004369 case 'n':
4370 PositionalParametersFound = true;
4371 break;
4372
Jim Grosbach4b905842013-09-20 23:08:21 +00004373 // $[0-9] => argument
Kevin Enderby81c944c2013-01-22 21:44:53 +00004374 default: {
4375 PositionalParametersFound = true;
4376 break;
Jim Grosbach4b905842013-09-20 23:08:21 +00004377 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00004378 }
4379 Pos += 2;
4380 } else {
4381 unsigned I = Pos + 1;
4382 while (isIdentifierChar(Body[I]) && I + 1 != End)
4383 ++I;
4384
Jim Grosbach4b905842013-09-20 23:08:21 +00004385 const char *Begin = Body.data() + Pos + 1;
4386 StringRef Argument(Begin, I - (Pos + 1));
Kevin Enderby81c944c2013-01-22 21:44:53 +00004387 unsigned Index = 0;
4388 for (; Index < NParameters; ++Index)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00004389 if (Parameters[Index].Name == Argument)
Kevin Enderby81c944c2013-01-22 21:44:53 +00004390 break;
4391
4392 if (Index == NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00004393 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
4394 Pos += 3;
4395 else {
4396 Pos = I;
4397 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00004398 } else {
4399 NamedParametersFound = true;
4400 Pos += 1 + Argument.size();
4401 }
4402 }
4403 // Update the scan point.
4404 Body = Body.substr(Pos);
4405 }
4406
4407 if (!NamedParametersFound && PositionalParametersFound)
4408 Warning(DirectiveLoc, "macro defined with named parameters which are not "
4409 "used in macro body, possible positional parameter "
4410 "found in body which will have no effect");
4411}
4412
Nico Weber155dccd12014-07-24 17:08:39 +00004413/// parseDirectiveExitMacro
4414/// ::= .exitm
4415bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
Nirav Davea645433c2016-07-18 15:24:03 +00004416 if (parseToken(AsmToken::EndOfStatement,
4417 "unexpected token in '" + Directive + "' directive"))
4418 return true;
Nico Weber155dccd12014-07-24 17:08:39 +00004419
4420 if (!isInsideMacroInstantiation())
4421 return TokError("unexpected '" + Directive + "' in file, "
4422 "no current macro definition");
4423
4424 // Exit all conditionals that are active in the current macro.
4425 while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
4426 TheCondState = TheCondStack.back();
4427 TheCondStack.pop_back();
4428 }
4429
4430 handleMacroExit();
4431 return false;
4432}
4433
Jim Grosbach4b905842013-09-20 23:08:21 +00004434/// parseDirectiveEndMacro
Eli Bendersky17233942013-01-15 22:59:42 +00004435/// ::= .endm
4436/// ::= .endmacro
Jim Grosbach4b905842013-09-20 23:08:21 +00004437bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
Eli Bendersky17233942013-01-15 22:59:42 +00004438 if (getLexer().isNot(AsmToken::EndOfStatement))
4439 return TokError("unexpected token in '" + Directive + "' directive");
4440
4441 // If we are inside a macro instantiation, terminate the current
4442 // instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00004443 if (isInsideMacroInstantiation()) {
4444 handleMacroExit();
Eli Bendersky17233942013-01-15 22:59:42 +00004445 return false;
4446 }
4447
4448 // Otherwise, this .endmacro is a stray entry in the file; well formed
4449 // .endmacro directives are handled during the macro definition parsing.
4450 return TokError("unexpected '" + Directive + "' in file, "
Jim Grosbach4b905842013-09-20 23:08:21 +00004451 "no current macro definition");
Eli Bendersky17233942013-01-15 22:59:42 +00004452}
4453
Jim Grosbach4b905842013-09-20 23:08:21 +00004454/// parseDirectivePurgeMacro
Eli Bendersky17233942013-01-15 22:59:42 +00004455/// ::= .purgem
Jim Grosbach4b905842013-09-20 23:08:21 +00004456bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004457 StringRef Name;
Nirav Davea645433c2016-07-18 15:24:03 +00004458 SMLoc Loc;
Nirav Daved8858ca2016-08-30 14:15:43 +00004459 if (parseTokenLoc(Loc) ||
4460 check(parseIdentifier(Name), Loc,
4461 "expected identifier in '.purgem' directive") ||
Nirav Davea645433c2016-07-18 15:24:03 +00004462 parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00004463 "unexpected token in '.purgem' directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00004464 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004465
Rafael Espindola22c38a02018-02-14 16:34:27 +00004466 if (!getContext().lookupMacro(Name))
Nirav Dave1ab71992016-07-18 19:35:21 +00004467 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
4468
Rafael Espindola22c38a02018-02-14 16:34:27 +00004469 getContext().undefineMacro(Name);
Oliver Stannardc3e7c6d2018-03-06 15:32:34 +00004470 DEBUG_WITH_TYPE("asm-macros", dbgs()
4471 << "Un-defining macro: " << Name << "\n");
Eli Bendersky17233942013-01-15 22:59:42 +00004472 return false;
4473}
Eli Benderskyf483ff92012-12-20 19:05:53 +00004474
Jim Grosbach4b905842013-09-20 23:08:21 +00004475/// parseDirectiveBundleAlignMode
Eli Benderskyf483ff92012-12-20 19:05:53 +00004476/// ::= {.bundle_align_mode} expression
Jim Grosbach4b905842013-09-20 23:08:21 +00004477bool AsmParser::parseDirectiveBundleAlignMode() {
Eli Benderskyf483ff92012-12-20 19:05:53 +00004478 // Expect a single argument: an expression that evaluates to a constant
4479 // in the inclusive range 0-30.
4480 SMLoc ExprLoc = getLexer().getLoc();
4481 int64_t AlignSizePow2;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004482 if (checkForValidSection() || parseAbsoluteExpression(AlignSizePow2) ||
Nirav Davea645433c2016-07-18 15:24:03 +00004483 parseToken(AsmToken::EndOfStatement, "unexpected token after expression "
4484 "in '.bundle_align_mode' "
4485 "directive") ||
4486 check(AlignSizePow2 < 0 || AlignSizePow2 > 30, ExprLoc,
4487 "invalid bundle alignment size (expected between 0 and 30)"))
Eli Benderskyf483ff92012-12-20 19:05:53 +00004488 return true;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004489
4490 // Because of AlignSizePow2's verified range we can safely truncate it to
4491 // unsigned.
4492 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
4493 return false;
4494}
4495
Jim Grosbach4b905842013-09-20 23:08:21 +00004496/// parseDirectiveBundleLock
Eli Bendersky802b6282013-01-07 21:51:08 +00004497/// ::= {.bundle_lock} [align_to_end]
Jim Grosbach4b905842013-09-20 23:08:21 +00004498bool AsmParser::parseDirectiveBundleLock() {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004499 if (checkForValidSection())
4500 return true;
Eli Bendersky802b6282013-01-07 21:51:08 +00004501 bool AlignToEnd = false;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004502
Nirav Dave1a9044b2016-10-24 14:35:29 +00004503 StringRef Option;
4504 SMLoc Loc = getTok().getLoc();
4505 const char *kInvalidOptionError =
4506 "invalid option for '.bundle_lock' directive";
Eli Bendersky802b6282013-01-07 21:51:08 +00004507
Nirav Dave1a9044b2016-10-24 14:35:29 +00004508 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
Nirav Davea645433c2016-07-18 15:24:03 +00004509 if (check(parseIdentifier(Option), Loc, kInvalidOptionError) ||
4510 check(Option != "align_to_end", Loc, kInvalidOptionError) ||
Nirav Dave1a9044b2016-10-24 14:35:29 +00004511 parseToken(AsmToken::EndOfStatement,
4512 "unexpected token after '.bundle_lock' directive option"))
Nirav Davea645433c2016-07-18 15:24:03 +00004513 return true;
Eli Bendersky802b6282013-01-07 21:51:08 +00004514 AlignToEnd = true;
4515 }
4516
Eli Bendersky802b6282013-01-07 21:51:08 +00004517 getStreamer().EmitBundleLock(AlignToEnd);
Eli Benderskyf483ff92012-12-20 19:05:53 +00004518 return false;
4519}
4520
Jim Grosbach4b905842013-09-20 23:08:21 +00004521/// parseDirectiveBundleLock
Eli Benderskyf483ff92012-12-20 19:05:53 +00004522/// ::= {.bundle_lock}
Jim Grosbach4b905842013-09-20 23:08:21 +00004523bool AsmParser::parseDirectiveBundleUnlock() {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004524 if (checkForValidSection() ||
4525 parseToken(AsmToken::EndOfStatement,
Nirav Davea645433c2016-07-18 15:24:03 +00004526 "unexpected token in '.bundle_unlock' directive"))
4527 return true;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004528
4529 getStreamer().EmitBundleUnlock();
4530 return false;
4531}
4532
Jim Grosbach4b905842013-09-20 23:08:21 +00004533/// parseDirectiveSpace
Eli Bendersky17233942013-01-15 22:59:42 +00004534/// ::= (.skip | .space) expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004535bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
Petr Hosek67a94a72016-05-28 05:57:48 +00004536 SMLoc NumBytesLoc = Lexer.getLoc();
4537 const MCExpr *NumBytes;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004538 if (checkForValidSection() || parseExpression(NumBytes))
Eli Bendersky17233942013-01-15 22:59:42 +00004539 return true;
4540
4541 int64_t FillExpr = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00004542 if (parseOptionalToken(AsmToken::Comma))
4543 if (parseAbsoluteExpression(FillExpr))
4544 return addErrorSuffix("in '" + Twine(IDVal) + "' directive");
4545 if (parseToken(AsmToken::EndOfStatement))
4546 return addErrorSuffix("in '" + Twine(IDVal) + "' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00004547
Eli Bendersky17233942013-01-15 22:59:42 +00004548 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
Petr Hosek67a94a72016-05-28 05:57:48 +00004549 getStreamer().emitFill(*NumBytes, FillExpr, NumBytesLoc);
Eli Bendersky17233942013-01-15 22:59:42 +00004550
4551 return false;
4552}
4553
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004554/// parseDirectiveDCB
4555/// ::= .dcb.{b, l, w} expression, expression
4556bool AsmParser::parseDirectiveDCB(StringRef IDVal, unsigned Size) {
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004557 SMLoc NumValuesLoc = Lexer.getLoc();
4558 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004559 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004560 return true;
4561
4562 if (NumValues < 0) {
4563 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4564 return false;
4565 }
4566
4567 if (parseToken(AsmToken::Comma,
4568 "unexpected token in '" + Twine(IDVal) + "' directive"))
4569 return true;
4570
4571 const MCExpr *Value;
4572 SMLoc ExprLoc = getLexer().getLoc();
4573 if (parseExpression(Value))
4574 return true;
4575
4576 // Special case constant expressions to match code generator.
4577 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
4578 assert(Size <= 8 && "Invalid size");
4579 uint64_t IntValue = MCE->getValue();
4580 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
4581 return Error(ExprLoc, "literal value out of range for directive");
4582 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4583 getStreamer().EmitIntValue(IntValue, Size);
4584 } else {
4585 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4586 getStreamer().EmitValue(Value, Size, ExprLoc);
4587 }
4588
4589 if (parseToken(AsmToken::EndOfStatement,
4590 "unexpected token in '" + Twine(IDVal) + "' directive"))
4591 return true;
4592
4593 return false;
4594}
4595
4596/// parseDirectiveRealDCB
4597/// ::= .dcb.{d, s} expression, expression
4598bool AsmParser::parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &Semantics) {
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004599 SMLoc NumValuesLoc = Lexer.getLoc();
4600 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004601 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004602 return true;
4603
4604 if (NumValues < 0) {
4605 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4606 return false;
4607 }
4608
4609 if (parseToken(AsmToken::Comma,
4610 "unexpected token in '" + Twine(IDVal) + "' directive"))
4611 return true;
4612
4613 APInt AsInt;
4614 if (parseRealValue(Semantics, AsInt))
4615 return true;
4616
4617 if (parseToken(AsmToken::EndOfStatement,
4618 "unexpected token in '" + Twine(IDVal) + "' directive"))
4619 return true;
4620
4621 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4622 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
4623 AsInt.getBitWidth() / 8);
4624
4625 return false;
4626}
4627
Petr Hosek85b2f672016-09-23 21:53:36 +00004628/// parseDirectiveDS
4629/// ::= .ds.{b, d, l, p, s, w, x} expression
4630bool AsmParser::parseDirectiveDS(StringRef IDVal, unsigned Size) {
Petr Hosek85b2f672016-09-23 21:53:36 +00004631 SMLoc NumValuesLoc = Lexer.getLoc();
4632 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004633 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek85b2f672016-09-23 21:53:36 +00004634 return true;
4635
4636 if (NumValues < 0) {
4637 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4638 return false;
4639 }
4640
4641 if (parseToken(AsmToken::EndOfStatement,
4642 "unexpected token in '" + Twine(IDVal) + "' directive"))
4643 return true;
4644
4645 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4646 getStreamer().emitFill(Size, 0);
4647
4648 return false;
4649}
4650
Jim Grosbach4b905842013-09-20 23:08:21 +00004651/// parseDirectiveLEB128
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004652/// ::= (.sleb128 | .uleb128) [ expression (, expression)* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004653bool AsmParser::parseDirectiveLEB128(bool Signed) {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004654 if (checkForValidSection())
4655 return true;
4656
Nirav Dave1a9044b2016-10-24 14:35:29 +00004657 auto parseOp = [&]() -> bool {
4658 const MCExpr *Value;
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004659 if (parseExpression(Value))
4660 return true;
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004661 if (Signed)
4662 getStreamer().EmitSLEB128Value(Value);
4663 else
4664 getStreamer().EmitULEB128Value(Value);
Nirav Dave1a9044b2016-10-24 14:35:29 +00004665 return false;
4666 };
Eli Bendersky17233942013-01-15 22:59:42 +00004667
Nirav Dave1a9044b2016-10-24 14:35:29 +00004668 if (parseMany(parseOp))
4669 return addErrorSuffix(" in directive");
Eli Bendersky17233942013-01-15 22:59:42 +00004670
4671 return false;
4672}
4673
Jim Grosbach4b905842013-09-20 23:08:21 +00004674/// parseDirectiveSymbolAttribute
Daniel Dunbara5508c82009-06-30 00:33:19 +00004675/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004676bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00004677 auto parseOp = [&]() -> bool {
4678 StringRef Name;
4679 SMLoc Loc = getTok().getLoc();
4680 if (parseIdentifier(Name))
4681 return Error(Loc, "expected identifier");
4682 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004683
Nirav Dave1a9044b2016-10-24 14:35:29 +00004684 // Assembler local symbols don't make any sense here. Complain loudly.
4685 if (Sym->isTemporary())
4686 return Error(Loc, "non-local symbol required");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004687
Nirav Dave1a9044b2016-10-24 14:35:29 +00004688 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
4689 return Error(Loc, "unable to emit symbol attribute");
4690 return false;
4691 };
Daniel Dunbara5508c82009-06-30 00:33:19 +00004692
Nirav Dave1a9044b2016-10-24 14:35:29 +00004693 if (parseMany(parseOp))
4694 return addErrorSuffix(" in directive");
Jan Wen Voungc7682872010-09-30 01:09:20 +00004695 return false;
Daniel Dunbara5508c82009-06-30 00:33:19 +00004696}
Chris Lattnera1e11f52009-07-07 20:30:46 +00004697
Jim Grosbach4b905842013-09-20 23:08:21 +00004698/// parseDirectiveComm
Chris Lattner28ad7542009-07-09 17:25:12 +00004699/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004700bool AsmParser::parseDirectiveComm(bool IsLocal) {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004701 if (checkForValidSection())
4702 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00004703
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004704 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004705 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004706 if (parseIdentifier(Name))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004707 return TokError("expected identifier in directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004708
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +00004709 // Handle the identifier as the key symbol.
Jim Grosbach6f482002015-05-18 18:43:14 +00004710 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Chris Lattnera1e11f52009-07-07 20:30:46 +00004711
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004712 if (getLexer().isNot(AsmToken::Comma))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004713 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00004714 Lex();
Chris Lattnera1e11f52009-07-07 20:30:46 +00004715
4716 int64_t Size;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004717 SMLoc SizeLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004718 if (parseAbsoluteExpression(Size))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004719 return true;
4720
4721 int64_t Pow2Alignment = 0;
4722 SMLoc Pow2AlignmentLoc;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004723 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan686ed8d2010-01-19 20:22:31 +00004724 Lex();
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004725 Pow2AlignmentLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004726 if (parseAbsoluteExpression(Pow2Alignment))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004727 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00004728
Benjamin Kramer68b9f052012-09-07 21:08:01 +00004729 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
4730 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00004731 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
4732
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00004733 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramer68b9f052012-09-07 21:08:01 +00004734 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
4735 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00004736 if (!isPowerOf2_64(Pow2Alignment))
4737 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
4738 Pow2Alignment = Log2_64(Pow2Alignment);
4739 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00004740 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00004741
Nirav Dave1a9044b2016-10-24 14:35:29 +00004742 if (parseToken(AsmToken::EndOfStatement,
4743 "unexpected token in '.comm' or '.lcomm' directive"))
4744 return true;
Chris Lattnera1e11f52009-07-07 20:30:46 +00004745
Chris Lattner28ad7542009-07-09 17:25:12 +00004746 // NOTE: a size of zero for a .comm should create a undefined symbol
4747 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattnera1e11f52009-07-07 20:30:46 +00004748 if (Size < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00004749 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
Jim Grosbach4b905842013-09-20 23:08:21 +00004750 "be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00004751
Eric Christopherbc818852010-05-14 01:38:54 +00004752 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattnera1e11f52009-07-07 20:30:46 +00004753 // may internally end up wanting an alignment in bytes.
4754 // FIXME: Diagnose overflow.
4755 if (Pow2Alignment < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00004756 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
Jim Grosbach4b905842013-09-20 23:08:21 +00004757 "alignment, can't be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00004758
Rafael Espindola13a79bb2017-02-02 21:26:06 +00004759 Sym->redefineIfPossible();
Daniel Dunbar6860ac72009-08-22 07:22:36 +00004760 if (!Sym->isUndefined())
Chris Lattnera1e11f52009-07-07 20:30:46 +00004761 return Error(IDLoc, "invalid symbol redefinition");
4762
Chris Lattner28ad7542009-07-09 17:25:12 +00004763 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00004764 if (IsLocal) {
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00004765 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00004766 return false;
4767 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00004768
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004769 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattnera1e11f52009-07-07 20:30:46 +00004770 return false;
4771}
Chris Lattner07cadaf2009-07-10 22:20:30 +00004772
Jim Grosbach4b905842013-09-20 23:08:21 +00004773/// parseDirectiveAbort
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004774/// ::= .abort [... message ...]
Jim Grosbach4b905842013-09-20 23:08:21 +00004775bool AsmParser::parseDirectiveAbort() {
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004776 // FIXME: Use loc from directive.
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004777 SMLoc Loc = getLexer().getLoc();
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004778
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004779 StringRef Str = parseStringToEndOfStatement();
Nirav Davea645433c2016-07-18 15:24:03 +00004780 if (parseToken(AsmToken::EndOfStatement,
4781 "unexpected token in '.abort' directive"))
4782 return true;
Kevin Enderby56523ce2009-07-13 23:15:14 +00004783
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004784 if (Str.empty())
Nirav Dave2364748a2016-09-16 18:30:20 +00004785 return Error(Loc, ".abort detected. Assembly stopping.");
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004786 else
Nirav Dave2364748a2016-09-16 18:30:20 +00004787 return Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004788 // FIXME: Actually abort assembly here.
Kevin Enderby56523ce2009-07-13 23:15:14 +00004789
4790 return false;
4791}
Kevin Enderbycbe475d2009-07-14 21:35:03 +00004792
Jim Grosbach4b905842013-09-20 23:08:21 +00004793/// parseDirectiveInclude
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004794/// ::= .include "filename"
Jim Grosbach4b905842013-09-20 23:08:21 +00004795bool AsmParser::parseDirectiveInclude() {
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004796 // Allow the strings to have escaped octal character sequence.
4797 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00004798 SMLoc IncludeLoc = getTok().getLoc();
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004799
Nirav Davea645433c2016-07-18 15:24:03 +00004800 if (check(getTok().isNot(AsmToken::String),
4801 "expected string in '.include' directive") ||
4802 parseEscapedString(Filename) ||
4803 check(getTok().isNot(AsmToken::EndOfStatement),
4804 "unexpected token in '.include' directive") ||
4805 // Attempt to switch the lexer to the included file before consuming the
4806 // end of statement to avoid losing it when we switch.
4807 check(enterIncludeFile(Filename), IncludeLoc,
4808 "Could not find include file '" + Filename + "'"))
Chris Lattner693fbb82009-07-16 06:14:39 +00004809 return true;
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004810
4811 return false;
4812}
Kevin Enderby09ea5702009-07-15 15:30:11 +00004813
Jim Grosbach4b905842013-09-20 23:08:21 +00004814/// parseDirectiveIncbin
Petr Hosek2f4ac442016-09-23 00:41:06 +00004815/// ::= .incbin "filename" [ , skip [ , count ] ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004816bool AsmParser::parseDirectiveIncbin() {
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004817 // Allow the strings to have escaped octal character sequence.
4818 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00004819 SMLoc IncbinLoc = getTok().getLoc();
4820 if (check(getTok().isNot(AsmToken::String),
4821 "expected string in '.incbin' directive") ||
Petr Hosek2f4ac442016-09-23 00:41:06 +00004822 parseEscapedString(Filename))
4823 return true;
4824
4825 int64_t Skip = 0;
4826 const MCExpr *Count = nullptr;
4827 SMLoc SkipLoc, CountLoc;
Nirav Dave1a9044b2016-10-24 14:35:29 +00004828 if (parseOptionalToken(AsmToken::Comma)) {
Petr Hosek2f4ac442016-09-23 00:41:06 +00004829 // The skip expression can be omitted while specifying the count, e.g:
4830 // .incbin "filename",,4
4831 if (getTok().isNot(AsmToken::Comma)) {
4832 if (parseTokenLoc(SkipLoc) || parseAbsoluteExpression(Skip))
4833 return true;
4834 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00004835 if (parseOptionalToken(AsmToken::Comma)) {
4836 CountLoc = getTok().getLoc();
4837 if (parseExpression(Count))
Petr Hosek2f4ac442016-09-23 00:41:06 +00004838 return true;
4839 }
4840 }
4841
4842 if (parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00004843 "unexpected token in '.incbin' directive"))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004844 return true;
Nirav Dave1ab71992016-07-18 19:35:21 +00004845
Petr Hosek2f4ac442016-09-23 00:41:06 +00004846 if (check(Skip < 0, SkipLoc, "skip is negative"))
4847 return true;
4848
Nirav Dave1ab71992016-07-18 19:35:21 +00004849 // Attempt to process the included file.
Petr Hosek2f4ac442016-09-23 00:41:06 +00004850 if (processIncbinFile(Filename, Skip, Count, CountLoc))
Nirav Dave1ab71992016-07-18 19:35:21 +00004851 return Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
Kevin Enderby109f25c2011-12-14 21:47:48 +00004852 return false;
4853}
4854
Jim Grosbach4b905842013-09-20 23:08:21 +00004855/// parseDirectiveIf
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004856/// ::= .if{,eq,ge,gt,le,lt,ne} expression
4857bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004858 TheCondStack.push_back(TheCondState);
4859 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004860 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004861 eatToEndOfStatement();
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004862 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004863 int64_t ExprValue;
Nirav Davea645433c2016-07-18 15:24:03 +00004864 if (parseAbsoluteExpression(ExprValue) ||
4865 parseToken(AsmToken::EndOfStatement,
4866 "unexpected token in '.if' directive"))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004867 return true;
4868
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004869 switch (DirKind) {
4870 default:
4871 llvm_unreachable("unsupported directive");
4872 case DK_IF:
4873 case DK_IFNE:
4874 break;
4875 case DK_IFEQ:
4876 ExprValue = ExprValue == 0;
4877 break;
4878 case DK_IFGE:
4879 ExprValue = ExprValue >= 0;
4880 break;
4881 case DK_IFGT:
4882 ExprValue = ExprValue > 0;
4883 break;
4884 case DK_IFLE:
4885 ExprValue = ExprValue <= 0;
4886 break;
4887 case DK_IFLT:
4888 ExprValue = ExprValue < 0;
4889 break;
4890 }
4891
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004892 TheCondState.CondMet = ExprValue;
4893 TheCondState.Ignore = !TheCondState.CondMet;
4894 }
4895
4896 return false;
4897}
4898
Jim Grosbach4b905842013-09-20 23:08:21 +00004899/// parseDirectiveIfb
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004900/// ::= .ifb string
Jim Grosbach4b905842013-09-20 23:08:21 +00004901bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004902 TheCondStack.push_back(TheCondState);
4903 TheCondState.TheCond = AsmCond::IfCond;
4904
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004905 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004906 eatToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004907 } else {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004908 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004909
Nirav Davea645433c2016-07-18 15:24:03 +00004910 if (parseToken(AsmToken::EndOfStatement,
4911 "unexpected token in '.ifb' directive"))
4912 return true;
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004913
4914 TheCondState.CondMet = ExpectBlank == Str.empty();
4915 TheCondState.Ignore = !TheCondState.CondMet;
4916 }
4917
4918 return false;
4919}
4920
Jim Grosbach4b905842013-09-20 23:08:21 +00004921/// parseDirectiveIfc
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004922/// ::= .ifc string1, string2
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00004923/// ::= .ifnc string1, string2
Jim Grosbach4b905842013-09-20 23:08:21 +00004924bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004925 TheCondStack.push_back(TheCondState);
4926 TheCondState.TheCond = AsmCond::IfCond;
4927
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004928 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004929 eatToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004930 } else {
Jim Grosbach4b905842013-09-20 23:08:21 +00004931 StringRef Str1 = parseStringToComma();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004932
Nirav Davea645433c2016-07-18 15:24:03 +00004933 if (parseToken(AsmToken::Comma, "unexpected token in '.ifc' directive"))
4934 return true;
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004935
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004936 StringRef Str2 = parseStringToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004937
Nirav Davea645433c2016-07-18 15:24:03 +00004938 if (parseToken(AsmToken::EndOfStatement,
4939 "unexpected token in '.ifc' directive"))
4940 return true;
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004941
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00004942 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004943 TheCondState.Ignore = !TheCondState.CondMet;
4944 }
4945
4946 return false;
4947}
4948
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004949/// parseDirectiveIfeqs
4950/// ::= .ifeqs string1, string2
Sid Manning51c35602015-03-18 14:20:54 +00004951bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual) {
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004952 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00004953 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00004954 return TokError("expected string parameter for '.ifeqs' directive");
4955 return TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004956 }
4957
4958 StringRef String1 = getTok().getStringContents();
4959 Lex();
4960
4961 if (Lexer.isNot(AsmToken::Comma)) {
Sid Manning51c35602015-03-18 14:20:54 +00004962 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00004963 return TokError(
4964 "expected comma after first string for '.ifeqs' directive");
4965 return TokError("expected comma after first string for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004966 }
4967
4968 Lex();
4969
4970 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00004971 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00004972 return TokError("expected string parameter for '.ifeqs' directive");
4973 return TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004974 }
4975
4976 StringRef String2 = getTok().getStringContents();
4977 Lex();
4978
4979 TheCondStack.push_back(TheCondState);
4980 TheCondState.TheCond = AsmCond::IfCond;
Sid Manning51c35602015-03-18 14:20:54 +00004981 TheCondState.CondMet = ExpectEqual == (String1 == String2);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004982 TheCondState.Ignore = !TheCondState.CondMet;
4983
4984 return false;
4985}
4986
Jim Grosbach4b905842013-09-20 23:08:21 +00004987/// parseDirectiveIfdef
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004988/// ::= .ifdef symbol
Jim Grosbach4b905842013-09-20 23:08:21 +00004989bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004990 StringRef Name;
4991 TheCondStack.push_back(TheCondState);
4992 TheCondState.TheCond = AsmCond::IfCond;
4993
4994 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004995 eatToEndOfStatement();
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004996 } else {
Nirav Davea645433c2016-07-18 15:24:03 +00004997 if (check(parseIdentifier(Name), "expected identifier after '.ifdef'") ||
4998 parseToken(AsmToken::EndOfStatement, "unexpected token in '.ifdef'"))
4999 return true;
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00005000
Jim Grosbach6f482002015-05-18 18:43:14 +00005001 MCSymbol *Sym = getContext().lookupSymbol(Name);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00005002
5003 if (expect_defined)
Craig Topper353eda42014-04-24 06:44:33 +00005004 TheCondState.CondMet = (Sym && !Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00005005 else
Craig Topper353eda42014-04-24 06:44:33 +00005006 TheCondState.CondMet = (!Sym || Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00005007 TheCondState.Ignore = !TheCondState.CondMet;
5008 }
5009
5010 return false;
5011}
5012
Jim Grosbach4b905842013-09-20 23:08:21 +00005013/// parseDirectiveElseIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005014/// ::= .elseif expression
Jim Grosbach4b905842013-09-20 23:08:21 +00005015bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005016 if (TheCondState.TheCond != AsmCond::IfCond &&
5017 TheCondState.TheCond != AsmCond::ElseIfCond)
Nirav Dave2364748a2016-09-16 18:30:20 +00005018 return Error(DirectiveLoc, "Encountered a .elseif that doesn't follow an"
5019 " .if or an .elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005020 TheCondState.TheCond = AsmCond::ElseIfCond;
5021
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005022 bool LastIgnoreState = false;
5023 if (!TheCondStack.empty())
Craig Topper2172ad62013-04-22 04:24:02 +00005024 LastIgnoreState = TheCondStack.back().Ignore;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005025 if (LastIgnoreState || TheCondState.CondMet) {
5026 TheCondState.Ignore = true;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005027 eatToEndOfStatement();
Craig Topperf15655b2013-04-22 04:22:40 +00005028 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005029 int64_t ExprValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005030 if (parseAbsoluteExpression(ExprValue))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005031 return true;
5032
Nirav Dave1a9044b2016-10-24 14:35:29 +00005033 if (parseToken(AsmToken::EndOfStatement,
5034 "unexpected token in '.elseif' directive"))
5035 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00005036
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005037 TheCondState.CondMet = ExprValue;
5038 TheCondState.Ignore = !TheCondState.CondMet;
5039 }
5040
5041 return false;
5042}
5043
Jim Grosbach4b905842013-09-20 23:08:21 +00005044/// parseDirectiveElse
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005045/// ::= .else
Jim Grosbach4b905842013-09-20 23:08:21 +00005046bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00005047 if (parseToken(AsmToken::EndOfStatement,
5048 "unexpected token in '.else' directive"))
5049 return true;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005050
5051 if (TheCondState.TheCond != AsmCond::IfCond &&
5052 TheCondState.TheCond != AsmCond::ElseIfCond)
Nirav Dave2364748a2016-09-16 18:30:20 +00005053 return Error(DirectiveLoc, "Encountered a .else that doesn't follow "
5054 " an .if or an .elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005055 TheCondState.TheCond = AsmCond::ElseCond;
5056 bool LastIgnoreState = false;
5057 if (!TheCondStack.empty())
5058 LastIgnoreState = TheCondStack.back().Ignore;
5059 if (LastIgnoreState || TheCondState.CondMet)
5060 TheCondState.Ignore = true;
5061 else
5062 TheCondState.Ignore = false;
5063
5064 return false;
5065}
5066
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00005067/// parseDirectiveEnd
5068/// ::= .end
5069bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00005070 if (parseToken(AsmToken::EndOfStatement,
5071 "unexpected token in '.end' directive"))
5072 return true;
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00005073
5074 while (Lexer.isNot(AsmToken::Eof))
Nirav Dave1a9044b2016-10-24 14:35:29 +00005075 Lexer.Lex();
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00005076
5077 return false;
5078}
5079
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00005080/// parseDirectiveError
5081/// ::= .err
5082/// ::= .error [string]
5083bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
5084 if (!TheCondStack.empty()) {
5085 if (TheCondStack.back().Ignore) {
5086 eatToEndOfStatement();
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00005087 return false;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00005088 }
5089 }
5090
5091 if (!WithMessage)
5092 return Error(L, ".err encountered");
5093
5094 StringRef Message = ".error directive invoked in source file";
5095 if (Lexer.isNot(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00005096 if (Lexer.isNot(AsmToken::String))
5097 return TokError(".error argument must be a string");
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00005098
5099 Message = getTok().getStringContents();
5100 Lex();
5101 }
5102
Nirav Dave2364748a2016-09-16 18:30:20 +00005103 return Error(L, Message);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00005104}
5105
Nico Weber404012b2014-07-24 16:26:06 +00005106/// parseDirectiveWarning
5107/// ::= .warning [string]
5108bool AsmParser::parseDirectiveWarning(SMLoc L) {
5109 if (!TheCondStack.empty()) {
5110 if (TheCondStack.back().Ignore) {
5111 eatToEndOfStatement();
5112 return false;
5113 }
5114 }
5115
5116 StringRef Message = ".warning directive invoked in source file";
Nirav Dave1a9044b2016-10-24 14:35:29 +00005117
5118 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00005119 if (Lexer.isNot(AsmToken::String))
5120 return TokError(".warning argument must be a string");
Nico Weber404012b2014-07-24 16:26:06 +00005121
5122 Message = getTok().getStringContents();
5123 Lex();
Nirav Dave1a9044b2016-10-24 14:35:29 +00005124 if (parseToken(AsmToken::EndOfStatement,
5125 "expected end of statement in '.warning' directive"))
5126 return true;
Nico Weber404012b2014-07-24 16:26:06 +00005127 }
5128
Nirav Dave2364748a2016-09-16 18:30:20 +00005129 return Warning(L, Message);
Nico Weber404012b2014-07-24 16:26:06 +00005130}
5131
Jim Grosbach4b905842013-09-20 23:08:21 +00005132/// parseDirectiveEndIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005133/// ::= .endif
Jim Grosbach4b905842013-09-20 23:08:21 +00005134bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00005135 if (parseToken(AsmToken::EndOfStatement,
5136 "unexpected token in '.endif' directive"))
5137 return true;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005138
Jim Grosbach4b905842013-09-20 23:08:21 +00005139 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
Nirav Dave2364748a2016-09-16 18:30:20 +00005140 return Error(DirectiveLoc, "Encountered a .endif that doesn't follow "
5141 "an .if or .else");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005142 if (!TheCondStack.empty()) {
5143 TheCondState = TheCondStack.back();
5144 TheCondStack.pop_back();
5145 }
5146
5147 return false;
5148}
Daniel Dunbara4b069c2009-08-11 04:24:50 +00005149
Eli Bendersky17233942013-01-15 22:59:42 +00005150void AsmParser::initializeDirectiveKindMap() {
5151 DirectiveKindMap[".set"] = DK_SET;
5152 DirectiveKindMap[".equ"] = DK_EQU;
5153 DirectiveKindMap[".equiv"] = DK_EQUIV;
5154 DirectiveKindMap[".ascii"] = DK_ASCII;
5155 DirectiveKindMap[".asciz"] = DK_ASCIZ;
5156 DirectiveKindMap[".string"] = DK_STRING;
5157 DirectiveKindMap[".byte"] = DK_BYTE;
5158 DirectiveKindMap[".short"] = DK_SHORT;
5159 DirectiveKindMap[".value"] = DK_VALUE;
5160 DirectiveKindMap[".2byte"] = DK_2BYTE;
5161 DirectiveKindMap[".long"] = DK_LONG;
5162 DirectiveKindMap[".int"] = DK_INT;
5163 DirectiveKindMap[".4byte"] = DK_4BYTE;
5164 DirectiveKindMap[".quad"] = DK_QUAD;
5165 DirectiveKindMap[".8byte"] = DK_8BYTE;
David Woodhoused6de0d92014-02-01 16:20:59 +00005166 DirectiveKindMap[".octa"] = DK_OCTA;
Eli Bendersky17233942013-01-15 22:59:42 +00005167 DirectiveKindMap[".single"] = DK_SINGLE;
5168 DirectiveKindMap[".float"] = DK_FLOAT;
5169 DirectiveKindMap[".double"] = DK_DOUBLE;
5170 DirectiveKindMap[".align"] = DK_ALIGN;
5171 DirectiveKindMap[".align32"] = DK_ALIGN32;
5172 DirectiveKindMap[".balign"] = DK_BALIGN;
5173 DirectiveKindMap[".balignw"] = DK_BALIGNW;
5174 DirectiveKindMap[".balignl"] = DK_BALIGNL;
5175 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
5176 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
5177 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
5178 DirectiveKindMap[".org"] = DK_ORG;
5179 DirectiveKindMap[".fill"] = DK_FILL;
5180 DirectiveKindMap[".zero"] = DK_ZERO;
5181 DirectiveKindMap[".extern"] = DK_EXTERN;
5182 DirectiveKindMap[".globl"] = DK_GLOBL;
5183 DirectiveKindMap[".global"] = DK_GLOBAL;
Eli Bendersky17233942013-01-15 22:59:42 +00005184 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
5185 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
5186 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
5187 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
5188 DirectiveKindMap[".reference"] = DK_REFERENCE;
5189 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
5190 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
5191 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
5192 DirectiveKindMap[".comm"] = DK_COMM;
5193 DirectiveKindMap[".common"] = DK_COMMON;
5194 DirectiveKindMap[".lcomm"] = DK_LCOMM;
5195 DirectiveKindMap[".abort"] = DK_ABORT;
5196 DirectiveKindMap[".include"] = DK_INCLUDE;
5197 DirectiveKindMap[".incbin"] = DK_INCBIN;
5198 DirectiveKindMap[".code16"] = DK_CODE16;
5199 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
5200 DirectiveKindMap[".rept"] = DK_REPT;
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00005201 DirectiveKindMap[".rep"] = DK_REPT;
Eli Bendersky17233942013-01-15 22:59:42 +00005202 DirectiveKindMap[".irp"] = DK_IRP;
5203 DirectiveKindMap[".irpc"] = DK_IRPC;
5204 DirectiveKindMap[".endr"] = DK_ENDR;
5205 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
5206 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
5207 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
5208 DirectiveKindMap[".if"] = DK_IF;
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00005209 DirectiveKindMap[".ifeq"] = DK_IFEQ;
5210 DirectiveKindMap[".ifge"] = DK_IFGE;
5211 DirectiveKindMap[".ifgt"] = DK_IFGT;
5212 DirectiveKindMap[".ifle"] = DK_IFLE;
5213 DirectiveKindMap[".iflt"] = DK_IFLT;
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00005214 DirectiveKindMap[".ifne"] = DK_IFNE;
Eli Bendersky17233942013-01-15 22:59:42 +00005215 DirectiveKindMap[".ifb"] = DK_IFB;
5216 DirectiveKindMap[".ifnb"] = DK_IFNB;
5217 DirectiveKindMap[".ifc"] = DK_IFC;
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00005218 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
Eli Bendersky17233942013-01-15 22:59:42 +00005219 DirectiveKindMap[".ifnc"] = DK_IFNC;
Sid Manning51c35602015-03-18 14:20:54 +00005220 DirectiveKindMap[".ifnes"] = DK_IFNES;
Eli Bendersky17233942013-01-15 22:59:42 +00005221 DirectiveKindMap[".ifdef"] = DK_IFDEF;
5222 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
5223 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
5224 DirectiveKindMap[".elseif"] = DK_ELSEIF;
5225 DirectiveKindMap[".else"] = DK_ELSE;
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00005226 DirectiveKindMap[".end"] = DK_END;
Eli Bendersky17233942013-01-15 22:59:42 +00005227 DirectiveKindMap[".endif"] = DK_ENDIF;
5228 DirectiveKindMap[".skip"] = DK_SKIP;
5229 DirectiveKindMap[".space"] = DK_SPACE;
5230 DirectiveKindMap[".file"] = DK_FILE;
5231 DirectiveKindMap[".line"] = DK_LINE;
5232 DirectiveKindMap[".loc"] = DK_LOC;
5233 DirectiveKindMap[".stabs"] = DK_STABS;
Reid Kleckner2214ed82016-01-29 00:49:42 +00005234 DirectiveKindMap[".cv_file"] = DK_CV_FILE;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00005235 DirectiveKindMap[".cv_func_id"] = DK_CV_FUNC_ID;
Reid Kleckner2214ed82016-01-29 00:49:42 +00005236 DirectiveKindMap[".cv_loc"] = DK_CV_LOC;
5237 DirectiveKindMap[".cv_linetable"] = DK_CV_LINETABLE;
David Majnemer6fcbd7e2016-01-29 19:24:12 +00005238 DirectiveKindMap[".cv_inline_linetable"] = DK_CV_INLINE_LINETABLE;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00005239 DirectiveKindMap[".cv_inline_site_id"] = DK_CV_INLINE_SITE_ID;
David Majnemer408b5e62016-02-05 01:55:49 +00005240 DirectiveKindMap[".cv_def_range"] = DK_CV_DEF_RANGE;
Reid Kleckner2214ed82016-01-29 00:49:42 +00005241 DirectiveKindMap[".cv_stringtable"] = DK_CV_STRINGTABLE;
5242 DirectiveKindMap[".cv_filechecksums"] = DK_CV_FILECHECKSUMS;
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00005243 DirectiveKindMap[".cv_filechecksumoffset"] = DK_CV_FILECHECKSUM_OFFSET;
Reid Kleckner9cdd4df2017-10-11 21:24:33 +00005244 DirectiveKindMap[".cv_fpo_data"] = DK_CV_FPO_DATA;
Eli Bendersky17233942013-01-15 22:59:42 +00005245 DirectiveKindMap[".sleb128"] = DK_SLEB128;
5246 DirectiveKindMap[".uleb128"] = DK_ULEB128;
5247 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
5248 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
5249 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
5250 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
5251 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
5252 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
5253 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
5254 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
5255 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
5256 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
5257 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
5258 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
5259 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
5260 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
5261 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
5262 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +00005263 DirectiveKindMap[".cfi_return_column"] = DK_CFI_RETURN_COLUMN;
Eli Bendersky17233942013-01-15 22:59:42 +00005264 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
5265 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
5266 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00005267 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
Eli Bendersky17233942013-01-15 22:59:42 +00005268 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
5269 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
5270 DirectiveKindMap[".macro"] = DK_MACRO;
Nico Weber155dccd12014-07-24 17:08:39 +00005271 DirectiveKindMap[".exitm"] = DK_EXITM;
Eli Bendersky17233942013-01-15 22:59:42 +00005272 DirectiveKindMap[".endm"] = DK_ENDM;
5273 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
5274 DirectiveKindMap[".purgem"] = DK_PURGEM;
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00005275 DirectiveKindMap[".err"] = DK_ERR;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00005276 DirectiveKindMap[".error"] = DK_ERROR;
Nico Weber404012b2014-07-24 16:26:06 +00005277 DirectiveKindMap[".warning"] = DK_WARNING;
Michael Zuckerman56704612017-05-01 13:20:12 +00005278 DirectiveKindMap[".altmacro"] = DK_ALTMACRO;
5279 DirectiveKindMap[".noaltmacro"] = DK_NOALTMACRO;
Daniel Sanders9f6ad492015-11-12 13:33:00 +00005280 DirectiveKindMap[".reloc"] = DK_RELOC;
Petr Hosek731bb9c2016-08-23 21:34:53 +00005281 DirectiveKindMap[".dc"] = DK_DC;
5282 DirectiveKindMap[".dc.a"] = DK_DC_A;
5283 DirectiveKindMap[".dc.b"] = DK_DC_B;
5284 DirectiveKindMap[".dc.d"] = DK_DC_D;
5285 DirectiveKindMap[".dc.l"] = DK_DC_L;
5286 DirectiveKindMap[".dc.s"] = DK_DC_S;
5287 DirectiveKindMap[".dc.w"] = DK_DC_W;
5288 DirectiveKindMap[".dc.x"] = DK_DC_X;
Petr Hosek4cb08ce2016-09-23 19:25:15 +00005289 DirectiveKindMap[".dcb"] = DK_DCB;
5290 DirectiveKindMap[".dcb.b"] = DK_DCB_B;
5291 DirectiveKindMap[".dcb.d"] = DK_DCB_D;
5292 DirectiveKindMap[".dcb.l"] = DK_DCB_L;
5293 DirectiveKindMap[".dcb.s"] = DK_DCB_S;
5294 DirectiveKindMap[".dcb.w"] = DK_DCB_W;
5295 DirectiveKindMap[".dcb.x"] = DK_DCB_X;
Petr Hosek85b2f672016-09-23 21:53:36 +00005296 DirectiveKindMap[".ds"] = DK_DS;
5297 DirectiveKindMap[".ds.b"] = DK_DS_B;
5298 DirectiveKindMap[".ds.d"] = DK_DS_D;
5299 DirectiveKindMap[".ds.l"] = DK_DS_L;
5300 DirectiveKindMap[".ds.p"] = DK_DS_P;
5301 DirectiveKindMap[".ds.s"] = DK_DS_S;
5302 DirectiveKindMap[".ds.w"] = DK_DS_W;
5303 DirectiveKindMap[".ds.x"] = DK_DS_X;
Coby Tayree01e53202017-10-02 14:36:31 +00005304 DirectiveKindMap[".print"] = DK_PRINT;
Peter Collingbourne3e227332018-07-17 22:17:18 +00005305 DirectiveKindMap[".addrsig"] = DK_ADDRSIG;
5306 DirectiveKindMap[".addrsig_sym"] = DK_ADDRSIG_SYM;
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00005307}
5308
Jim Grosbach4b905842013-09-20 23:08:21 +00005309MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005310 AsmToken EndToken, StartToken = getTok();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005311
Rafael Espindola34b9c512012-06-03 23:57:14 +00005312 unsigned NestLevel = 0;
Eugene Zelenko33d7b762016-08-23 17:14:32 +00005313 while (true) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005314 // Check whether we have reached the end of the file.
Rafael Espindola34b9c512012-06-03 23:57:14 +00005315 if (getLexer().is(AsmToken::Eof)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00005316 printError(DirectiveLoc, "no matching '.endr' in definition");
Craig Topper353eda42014-04-24 06:44:33 +00005317 return nullptr;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005318 }
5319
Rafael Espindola34b9c512012-06-03 23:57:14 +00005320 if (Lexer.is(AsmToken::Identifier) &&
Nirav Davee24fcd52018-07-18 16:17:03 +00005321 (getTok().getIdentifier() == ".rep" ||
5322 getTok().getIdentifier() == ".rept" ||
Nikolay Haustov95b4fcd2016-03-01 08:18:28 +00005323 getTok().getIdentifier() == ".irp" ||
5324 getTok().getIdentifier() == ".irpc")) {
Rafael Espindola34b9c512012-06-03 23:57:14 +00005325 ++NestLevel;
5326 }
5327
5328 // Otherwise, check whether we have reached the .endr.
Jim Grosbach4b905842013-09-20 23:08:21 +00005329 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
Rafael Espindola34b9c512012-06-03 23:57:14 +00005330 if (NestLevel == 0) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005331 EndToken = getTok();
5332 Lex();
Rafael Espindola34b9c512012-06-03 23:57:14 +00005333 if (Lexer.isNot(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00005334 printError(getTok().getLoc(),
5335 "unexpected token in '.endr' directive");
Craig Topper353eda42014-04-24 06:44:33 +00005336 return nullptr;
Rafael Espindola34b9c512012-06-03 23:57:14 +00005337 }
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005338 break;
5339 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00005340 --NestLevel;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005341 }
5342
Rafael Espindola34b9c512012-06-03 23:57:14 +00005343 // Otherwise, scan till the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005344 eatToEndOfStatement();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005345 }
5346
5347 const char *BodyStart = StartToken.getLoc().getPointer();
5348 const char *BodyEnd = EndToken.getLoc().getPointer();
5349 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
5350
Rafael Espindola34b9c512012-06-03 23:57:14 +00005351 // We Are Anonymous.
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00005352 MacroLikeBodies.emplace_back(StringRef(), Body, MCAsmMacroParameters());
Benjamin Kramer1df3a1f2013-08-04 09:06:29 +00005353 return &MacroLikeBodies.back();
Rafael Espindola34b9c512012-06-03 23:57:14 +00005354}
5355
Jim Grosbach4b905842013-09-20 23:08:21 +00005356void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +00005357 raw_svector_ostream &OS) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005358 OS << ".endr\n";
5359
Rafael Espindola3560ff22014-08-27 20:03:13 +00005360 std::unique_ptr<MemoryBuffer> Instantiation =
5361 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005362
Rafael Espindola34b9c512012-06-03 23:57:14 +00005363 // Create the macro instantiation object and add to the current macro
5364 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00005365 MacroInstantiation *MI = new MacroInstantiation(
5366 DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Rafael Espindola34b9c512012-06-03 23:57:14 +00005367 ActiveMacros.push_back(MI);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005368
Rafael Espindola34b9c512012-06-03 23:57:14 +00005369 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00005370 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00005371 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Rafael Espindola34b9c512012-06-03 23:57:14 +00005372 Lex();
5373}
5374
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00005375/// parseDirectiveRept
5376/// ::= .rep | .rept count
5377bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00005378 const MCExpr *CountExpr;
5379 SMLoc CountLoc = getTok().getLoc();
5380 if (parseExpression(CountExpr))
5381 return true;
5382
Rafael Espindola34b9c512012-06-03 23:57:14 +00005383 int64_t Count;
Nirav Dave6c0665e2018-04-30 19:22:40 +00005384 if (!CountExpr->evaluateAsAbsolute(Count, getStreamer().getAssemblerPtr())) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00005385 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
5386 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00005387
Nirav Davea645433c2016-07-18 15:24:03 +00005388 if (check(Count < 0, CountLoc, "Count is negative") ||
5389 parseToken(AsmToken::EndOfStatement,
5390 "unexpected token in '" + Dir + "' directive"))
5391 return true;
Rafael Espindola34b9c512012-06-03 23:57:14 +00005392
5393 // Lex the rept definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005394 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola34b9c512012-06-03 23:57:14 +00005395 if (!M)
5396 return true;
5397
5398 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5399 // to hold the macro body with substitutions.
5400 SmallString<256> Buf;
Rafael Espindola34b9c512012-06-03 23:57:14 +00005401 raw_svector_ostream OS(Buf);
5402 while (Count--) {
Toma Tabacu217116e2015-04-27 10:50:29 +00005403 // Note that the AtPseudoVariable is disabled for instantiations of .rep(t).
5404 if (expandMacro(OS, M->Body, None, None, false, getTok().getLoc()))
Rafael Espindola34b9c512012-06-03 23:57:14 +00005405 return true;
5406 }
Jim Grosbach4b905842013-09-20 23:08:21 +00005407 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005408
5409 return false;
5410}
5411
Jim Grosbach4b905842013-09-20 23:08:21 +00005412/// parseDirectiveIrp
Rafael Espindola768b41c2012-06-15 14:02:34 +00005413/// ::= .irp symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00005414bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00005415 MCAsmMacroParameter Parameter;
Eli Bendersky38274122013-01-14 23:22:36 +00005416 MCAsmMacroArguments A;
Nirav Davea645433c2016-07-18 15:24:03 +00005417 if (check(parseIdentifier(Parameter.Name),
5418 "expected identifier in '.irp' directive") ||
5419 parseToken(AsmToken::Comma, "expected comma in '.irp' directive") ||
5420 parseMacroArguments(nullptr, A) ||
5421 parseToken(AsmToken::EndOfStatement, "expected End of Statement"))
Rafael Espindola768b41c2012-06-15 14:02:34 +00005422 return true;
5423
Rafael Espindola768b41c2012-06-15 14:02:34 +00005424 // Lex the irp definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005425 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola768b41c2012-06-15 14:02:34 +00005426 if (!M)
5427 return true;
5428
5429 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5430 // to hold the macro body with substitutions.
5431 SmallString<256> Buf;
5432 raw_svector_ostream OS(Buf);
5433
Craig Topper84008482015-10-10 05:38:14 +00005434 for (const MCAsmMacroArgument &Arg : A) {
Toma Tabacu217116e2015-04-27 10:50:29 +00005435 // Note that the AtPseudoVariable is enabled for instantiations of .irp.
5436 // This is undocumented, but GAS seems to support it.
Craig Topper84008482015-10-10 05:38:14 +00005437 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindola768b41c2012-06-15 14:02:34 +00005438 return true;
5439 }
5440
Jim Grosbach4b905842013-09-20 23:08:21 +00005441 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola768b41c2012-06-15 14:02:34 +00005442
5443 return false;
5444}
5445
Jim Grosbach4b905842013-09-20 23:08:21 +00005446/// parseDirectiveIrpc
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005447/// ::= .irpc symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00005448bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00005449 MCAsmMacroParameter Parameter;
Eli Bendersky38274122013-01-14 23:22:36 +00005450 MCAsmMacroArguments A;
Nirav Davea645433c2016-07-18 15:24:03 +00005451
5452 if (check(parseIdentifier(Parameter.Name),
5453 "expected identifier in '.irpc' directive") ||
5454 parseToken(AsmToken::Comma, "expected comma in '.irpc' directive") ||
5455 parseMacroArguments(nullptr, A))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005456 return true;
5457
5458 if (A.size() != 1 || A.front().size() != 1)
5459 return TokError("unexpected token in '.irpc' directive");
5460
5461 // Eat the end of statement.
Nirav Davea645433c2016-07-18 15:24:03 +00005462 if (parseToken(AsmToken::EndOfStatement, "expected end of statement"))
5463 return true;
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005464
5465 // Lex the irpc definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005466 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005467 if (!M)
5468 return true;
5469
5470 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5471 // to hold the macro body with substitutions.
5472 SmallString<256> Buf;
5473 raw_svector_ostream OS(Buf);
5474
5475 StringRef Values = A.front().front().getString();
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00005476 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
Eli Benderskya7b905e2013-01-14 19:00:26 +00005477 MCAsmMacroArgument Arg;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00005478 Arg.emplace_back(AsmToken::Identifier, Values.slice(I, I + 1));
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005479
Toma Tabacu217116e2015-04-27 10:50:29 +00005480 // Note that the AtPseudoVariable is enabled for instantiations of .irpc.
5481 // This is undocumented, but GAS seems to support it.
5482 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005483 return true;
5484 }
5485
Jim Grosbach4b905842013-09-20 23:08:21 +00005486 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005487
5488 return false;
5489}
5490
Jim Grosbach4b905842013-09-20 23:08:21 +00005491bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
Rafael Espindola34b9c512012-06-03 23:57:14 +00005492 if (ActiveMacros.empty())
Preston Gurdeb3ebf12012-09-19 20:23:43 +00005493 return TokError("unmatched '.endr' directive");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005494
5495 // The only .repl that should get here are the ones created by
Jim Grosbach4b905842013-09-20 23:08:21 +00005496 // instantiateMacroLikeBody.
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005497 assert(getLexer().is(AsmToken::EndOfStatement));
5498
Jim Grosbach4b905842013-09-20 23:08:21 +00005499 handleMacroExit();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005500 return false;
5501}
Rafael Espindola12d73d12010-09-11 16:45:15 +00005502
Jim Grosbach4b905842013-09-20 23:08:21 +00005503bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
Benjamin Kramer1a136112013-02-15 20:37:21 +00005504 size_t Len) {
Eli Friedman0f4871d2012-10-22 23:58:19 +00005505 const MCExpr *Value;
5506 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005507 if (parseExpression(Value))
Eli Friedman0f4871d2012-10-22 23:58:19 +00005508 return true;
5509 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5510 if (!MCE)
5511 return Error(ExprLoc, "unexpected expression in _emit");
5512 uint64_t IntValue = MCE->getValue();
Craig Topper55b1f292015-10-10 20:17:07 +00005513 if (!isUInt<8>(IntValue) && !isInt<8>(IntValue))
Eli Friedman0f4871d2012-10-22 23:58:19 +00005514 return Error(ExprLoc, "literal value out of range for directive");
5515
Craig Topper7d5b2312015-10-10 05:25:02 +00005516 Info.AsmRewrites->emplace_back(AOK_Emit, IDLoc, Len);
Chad Rosierc7f552c2013-02-12 21:33:51 +00005517 return false;
5518}
5519
Jim Grosbach4b905842013-09-20 23:08:21 +00005520bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
Chad Rosierc7f552c2013-02-12 21:33:51 +00005521 const MCExpr *Value;
5522 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005523 if (parseExpression(Value))
Chad Rosierc7f552c2013-02-12 21:33:51 +00005524 return true;
5525 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5526 if (!MCE)
5527 return Error(ExprLoc, "unexpected expression in align");
5528 uint64_t IntValue = MCE->getValue();
5529 if (!isPowerOf2_64(IntValue))
5530 return Error(ExprLoc, "literal value not a power of two greater then zero");
5531
Craig Topper7d5b2312015-10-10 05:25:02 +00005532 Info.AsmRewrites->emplace_back(AOK_Align, IDLoc, 5, Log2_64(IntValue));
Eli Friedman0f4871d2012-10-22 23:58:19 +00005533 return false;
5534}
5535
Coby Tayree01e53202017-10-02 14:36:31 +00005536bool AsmParser::parseDirectivePrint(SMLoc DirectiveLoc) {
5537 const AsmToken StrTok = getTok();
5538 Lex();
5539 if (StrTok.isNot(AsmToken::String) || StrTok.getString().front() != '"')
5540 return Error(DirectiveLoc, "expected double quoted string after .print");
5541 if (parseToken(AsmToken::EndOfStatement, "expected end of statement"))
5542 return true;
5543 llvm::outs() << StrTok.getStringContents() << '\n';
5544 return false;
5545}
5546
Peter Collingbourne3e227332018-07-17 22:17:18 +00005547bool AsmParser::parseDirectiveAddrsig() {
5548 getStreamer().EmitAddrsig();
5549 return false;
5550}
5551
5552bool AsmParser::parseDirectiveAddrsigSym() {
5553 StringRef Name;
5554 if (check(parseIdentifier(Name),
5555 "expected identifier in '.addrsig_sym' directive"))
5556 return true;
5557 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
5558 getStreamer().EmitAddrsigSym(Sym);
5559 return false;
5560}
5561
Chad Rosierf43fcf52013-02-13 21:27:17 +00005562// We are comparing pointers, but the pointers are relative to a single string.
5563// Thus, this should always be deterministic.
Benjamin Kramer8817cca2013-09-22 14:09:50 +00005564static int rewritesSort(const AsmRewrite *AsmRewriteA,
5565 const AsmRewrite *AsmRewriteB) {
Chad Rosiereb5c1682013-02-13 18:38:58 +00005566 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
5567 return -1;
5568 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
5569 return 1;
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005570
Chad Rosierfce4fab2013-04-08 17:43:47 +00005571 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
5572 // rewrite to the same location. Make sure the SizeDirective rewrite is
5573 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
5574 // ensures the sort algorithm is stable.
Jim Grosbach4b905842013-09-20 23:08:21 +00005575 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
5576 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005577 return -1;
Chad Rosierfce4fab2013-04-08 17:43:47 +00005578
Jim Grosbach4b905842013-09-20 23:08:21 +00005579 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
5580 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005581 return 1;
Jim Grosbach4b905842013-09-20 23:08:21 +00005582 llvm_unreachable("Unstable rewrite sort.");
Chad Rosierb2144ce2013-02-13 01:03:13 +00005583}
5584
Jim Grosbach4b905842013-09-20 23:08:21 +00005585bool AsmParser::parseMSInlineAsm(
5586 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00005587 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool>> &OpDecls,
Jim Grosbach4b905842013-09-20 23:08:21 +00005588 SmallVectorImpl<std::string> &Constraints,
5589 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
5590 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
Chad Rosier37e755c2012-10-23 17:43:43 +00005591 SmallVector<void *, 4> InputDecls;
5592 SmallVector<void *, 4> OutputDecls;
Chad Rosiera4bc9432013-01-10 22:10:27 +00005593 SmallVector<bool, 4> InputDeclsAddressOf;
5594 SmallVector<bool, 4> OutputDeclsAddressOf;
Chad Rosier8bce6642012-10-18 15:49:34 +00005595 SmallVector<std::string, 4> InputConstraints;
5596 SmallVector<std::string, 4> OutputConstraints;
Benjamin Kramer1a136112013-02-15 20:37:21 +00005597 SmallVector<unsigned, 4> ClobberRegs;
Chad Rosier8bce6642012-10-18 15:49:34 +00005598
Benjamin Kramer1a136112013-02-15 20:37:21 +00005599 SmallVector<AsmRewrite, 4> AsmStrRewrites;
Chad Rosier8bce6642012-10-18 15:49:34 +00005600
5601 // Prime the lexer.
5602 Lex();
5603
5604 // While we have input, parse each statement.
5605 unsigned InputIdx = 0;
5606 unsigned OutputIdx = 0;
5607 while (getLexer().isNot(AsmToken::Eof)) {
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00005608 // Parse curly braces marking block start/end
5609 if (parseCurlyBlockScope(AsmStrRewrites))
5610 continue;
5611
Eli Friedman0f4871d2012-10-22 23:58:19 +00005612 ParseStatementInfo Info(&AsmStrRewrites);
Nirav Dave2364748a2016-09-16 18:30:20 +00005613 bool StatementErr = parseStatement(Info, &SI);
Nirav Dave9fa8af22016-09-13 13:55:06 +00005614
Nirav Dave2364748a2016-09-16 18:30:20 +00005615 if (StatementErr || Info.ParseError) {
5616 // Emit pending errors if any exist.
5617 printPendingErrors();
Nico Webere204c482016-09-13 18:17:00 +00005618 return true;
Nirav Dave2364748a2016-09-16 18:30:20 +00005619 }
5620
5621 // No pending error should exist here.
5622 assert(!hasPendingError() && "unexpected error from parseStatement");
Chad Rosier149e8e02012-12-12 22:45:52 +00005623
Benjamin Kramer1a136112013-02-15 20:37:21 +00005624 if (Info.Opcode == ~0U)
5625 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00005626
Benjamin Kramer1a136112013-02-15 20:37:21 +00005627 const MCInstrDesc &Desc = MII->get(Info.Opcode);
Chad Rosier8bce6642012-10-18 15:49:34 +00005628
Benjamin Kramer1a136112013-02-15 20:37:21 +00005629 // Build the list of clobbers, outputs and inputs.
5630 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
David Blaikie960ea3f2014-06-08 16:18:35 +00005631 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005632
Benjamin Kramer1a136112013-02-15 20:37:21 +00005633 // Immediate.
David Blaikie960ea3f2014-06-08 16:18:35 +00005634 if (Operand.isImm())
Benjamin Kramer1a136112013-02-15 20:37:21 +00005635 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00005636
Benjamin Kramer1a136112013-02-15 20:37:21 +00005637 // Register operand.
Nico Weber42f79db2014-07-17 20:24:55 +00005638 if (Operand.isReg() && !Operand.needAddressOf() &&
5639 !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
Benjamin Kramer1a136112013-02-15 20:37:21 +00005640 unsigned NumDefs = Desc.getNumDefs();
5641 // Clobber.
David Blaikie960ea3f2014-06-08 16:18:35 +00005642 if (NumDefs && Operand.getMCOperandNum() < NumDefs)
5643 ClobberRegs.push_back(Operand.getReg());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005644 continue;
5645 }
5646
5647 // Expr/Input or Output.
David Blaikie960ea3f2014-06-08 16:18:35 +00005648 StringRef SymName = Operand.getSymName();
Chad Rosiere81309b2013-04-09 17:53:49 +00005649 if (SymName.empty())
5650 continue;
5651
David Blaikie960ea3f2014-06-08 16:18:35 +00005652 void *OpDecl = Operand.getOpDecl();
Benjamin Kramer1a136112013-02-15 20:37:21 +00005653 if (!OpDecl)
5654 continue;
5655
5656 bool isOutput = (i == 1) && Desc.mayStore();
Chad Rosiere81309b2013-04-09 17:53:49 +00005657 SMLoc Start = SMLoc::getFromPointer(SymName.data());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005658 if (isOutput) {
5659 ++InputIdx;
5660 OutputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00005661 OutputDeclsAddressOf.push_back(Operand.needAddressOf());
Yaron Keren075759a2015-03-30 15:42:36 +00005662 OutputConstraints.push_back(("=" + Operand.getConstraint()).str());
Craig Topper7d5b2312015-10-10 05:25:02 +00005663 AsmStrRewrites.emplace_back(AOK_Output, Start, SymName.size());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005664 } else {
5665 InputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00005666 InputDeclsAddressOf.push_back(Operand.needAddressOf());
5667 InputConstraints.push_back(Operand.getConstraint().str());
Craig Topper7d5b2312015-10-10 05:25:02 +00005668 AsmStrRewrites.emplace_back(AOK_Input, Start, SymName.size());
Chad Rosier8bce6642012-10-18 15:49:34 +00005669 }
Chad Rosier8bce6642012-10-18 15:49:34 +00005670 }
Reid Kleckneree088972013-12-10 18:27:32 +00005671
5672 // Consider implicit defs to be clobbers. Think of cpuid and push.
Craig Toppere5e035a32015-12-05 07:13:35 +00005673 ArrayRef<MCPhysReg> ImpDefs(Desc.getImplicitDefs(),
5674 Desc.getNumImplicitDefs());
David Majnemer8114c1a2014-06-23 02:17:16 +00005675 ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end());
Chad Rosier8bce6642012-10-18 15:49:34 +00005676 }
5677
5678 // Set the number of Outputs and Inputs.
Chad Rosierf641baa2012-10-18 19:39:30 +00005679 NumOutputs = OutputDecls.size();
5680 NumInputs = InputDecls.size();
Chad Rosier8bce6642012-10-18 15:49:34 +00005681
5682 // Set the unique clobbers.
Benjamin Kramer1a136112013-02-15 20:37:21 +00005683 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
5684 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
5685 ClobberRegs.end());
5686 Clobbers.assign(ClobberRegs.size(), std::string());
5687 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
5688 raw_string_ostream OS(Clobbers[I]);
5689 IP->printRegName(OS, ClobberRegs[I]);
5690 }
Chad Rosier8bce6642012-10-18 15:49:34 +00005691
5692 // Merge the various outputs and inputs. Output are expected first.
5693 if (NumOutputs || NumInputs) {
5694 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierf641baa2012-10-18 19:39:30 +00005695 OpDecls.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00005696 Constraints.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00005697 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00005698 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00005699 Constraints[i] = OutputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005700 }
5701 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00005702 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00005703 Constraints[j] = InputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005704 }
5705 }
5706
5707 // Build the IR assembly string.
Alp Tokere69170a2014-06-26 22:52:05 +00005708 std::string AsmStringIR;
5709 raw_string_ostream OS(AsmStringIR);
Alp Tokera55b95b2014-07-06 10:33:31 +00005710 StringRef ASMString =
5711 SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
5712 const char *AsmStart = ASMString.begin();
5713 const char *AsmEnd = ASMString.end();
Jim Grosbach4b905842013-09-20 23:08:21 +00005714 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
David Majnemer8114c1a2014-06-23 02:17:16 +00005715 for (const AsmRewrite &AR : AsmStrRewrites) {
5716 AsmRewriteKind Kind = AR.Kind;
Chad Rosierff10ed12013-04-12 16:26:42 +00005717
David Majnemer8114c1a2014-06-23 02:17:16 +00005718 const char *Loc = AR.Loc.getPointer();
Chad Rosier17d37992013-03-19 21:12:14 +00005719 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
Chad Rosier0f48c552012-10-19 20:57:14 +00005720
Chad Rosier120eefd2013-03-19 17:32:17 +00005721 // Emit everything up to the immediate/expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00005722 if (unsigned Len = Loc - AsmStart)
Chad Rosier17d37992013-03-19 21:12:14 +00005723 OS << StringRef(AsmStart, Len);
Chad Rosier0f48c552012-10-19 20:57:14 +00005724
Chad Rosier37e755c2012-10-23 17:43:43 +00005725 // Skip the original expression.
5726 if (Kind == AOK_Skip) {
David Majnemer8114c1a2014-06-23 02:17:16 +00005727 AsmStart = Loc + AR.Len;
Chad Rosier37e755c2012-10-23 17:43:43 +00005728 continue;
5729 }
5730
Chad Rosierff10ed12013-04-12 16:26:42 +00005731 unsigned AdditionalSkip = 0;
Chad Rosier8bce6642012-10-18 15:49:34 +00005732 // Rewrite expressions in $N notation.
Chad Rosier0f48c552012-10-19 20:57:14 +00005733 switch (Kind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00005734 default:
5735 break;
Coby Tayreed8912892017-08-24 08:46:25 +00005736 case AOK_IntelExpr:
5737 assert(AR.IntelExp.isValid() && "cannot write invalid intel expression");
5738 if (AR.IntelExp.NeedBracs)
5739 OS << "[";
5740 if (AR.IntelExp.hasBaseReg())
5741 OS << AR.IntelExp.BaseReg;
5742 if (AR.IntelExp.hasIndexReg())
5743 OS << (AR.IntelExp.hasBaseReg() ? " + " : "")
5744 << AR.IntelExp.IndexReg;
5745 if (AR.IntelExp.Scale > 1)
5746 OS << " * $$" << AR.IntelExp.Scale;
5747 if (AR.IntelExp.Imm || !AR.IntelExp.hasRegs())
5748 OS << (AR.IntelExp.hasRegs() ? " + $$" : "$$") << AR.IntelExp.Imm;
5749 if (AR.IntelExp.NeedBracs)
5750 OS << "]";
Chad Rosier8bce6642012-10-18 15:49:34 +00005751 break;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005752 case AOK_Label:
Matt Arsenault4e273432014-12-04 00:06:57 +00005753 OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005754 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005755 case AOK_Input:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005756 OS << '$' << InputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00005757 break;
5758 case AOK_Output:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005759 OS << '$' << OutputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00005760 break;
Chad Rosier0f48c552012-10-19 20:57:14 +00005761 case AOK_SizeDirective:
David Majnemer8114c1a2014-06-23 02:17:16 +00005762 switch (AR.Val) {
Chad Rosier0f48c552012-10-19 20:57:14 +00005763 default: break;
5764 case 8: OS << "byte ptr "; break;
5765 case 16: OS << "word ptr "; break;
5766 case 32: OS << "dword ptr "; break;
5767 case 64: OS << "qword ptr "; break;
5768 case 80: OS << "xword ptr "; break;
5769 case 128: OS << "xmmword ptr "; break;
5770 case 256: OS << "ymmword ptr "; break;
5771 }
Eli Friedman0f4871d2012-10-22 23:58:19 +00005772 break;
5773 case AOK_Emit:
5774 OS << ".byte";
5775 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00005776 case AOK_Align: {
Reid Klecknerfb1c1c72015-10-27 17:32:48 +00005777 // MS alignment directives are measured in bytes. If the native assembler
5778 // measures alignment in bytes, we can pass it straight through.
5779 OS << ".align";
5780 if (getContext().getAsmInfo()->getAlignmentIsInBytes())
5781 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00005782
Reid Klecknerfb1c1c72015-10-27 17:32:48 +00005783 // Alignment is in log2 form, so print that instead and skip the original
5784 // immediate.
5785 unsigned Val = AR.Val;
5786 OS << ' ' << Val;
Benjamin Kramer1a136112013-02-15 20:37:21 +00005787 assert(Val < 10 && "Expected alignment less then 2^10.");
Chad Rosierc7f552c2013-02-12 21:33:51 +00005788 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
5789 break;
5790 }
Michael Zuckerman02ecd432015-12-13 17:07:23 +00005791 case AOK_EVEN:
5792 OS << ".even";
5793 break;
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00005794 case AOK_EndOfStatement:
5795 OS << "\n\t";
5796 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005797 }
Chad Rosier0f48c552012-10-19 20:57:14 +00005798
Chad Rosier8bce6642012-10-18 15:49:34 +00005799 // Skip the original expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00005800 AsmStart = Loc + AR.Len + AdditionalSkip;
Chad Rosier8bce6642012-10-18 15:49:34 +00005801 }
5802
5803 // Emit the remainder of the asm string.
Chad Rosier17d37992013-03-19 21:12:14 +00005804 if (AsmStart != AsmEnd)
5805 OS << StringRef(AsmStart, AsmEnd - AsmStart);
Chad Rosier8bce6642012-10-18 15:49:34 +00005806
5807 AsmString = OS.str();
5808 return false;
5809}
5810
Pete Cooper80d21cb2015-06-22 19:35:57 +00005811namespace llvm {
5812namespace MCParserUtils {
5813
5814/// Returns whether the given symbol is used anywhere in the given expression,
5815/// or subexpressions.
5816static bool isSymbolUsedInExpression(const MCSymbol *Sym, const MCExpr *Value) {
5817 switch (Value->getKind()) {
5818 case MCExpr::Binary: {
5819 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
5820 return isSymbolUsedInExpression(Sym, BE->getLHS()) ||
5821 isSymbolUsedInExpression(Sym, BE->getRHS());
5822 }
5823 case MCExpr::Target:
5824 case MCExpr::Constant:
5825 return false;
5826 case MCExpr::SymbolRef: {
5827 const MCSymbol &S =
5828 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
5829 if (S.isVariable())
5830 return isSymbolUsedInExpression(Sym, S.getVariableValue());
5831 return &S == Sym;
5832 }
5833 case MCExpr::Unary:
5834 return isSymbolUsedInExpression(
5835 Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
5836 }
5837
5838 llvm_unreachable("Unknown expr kind!");
5839}
5840
5841bool parseAssignmentExpression(StringRef Name, bool allow_redef,
5842 MCAsmParser &Parser, MCSymbol *&Sym,
Nirav Dave7fd992a2018-08-16 16:31:14 +00005843 const MCExpr *&Value) {
Pete Cooper80d21cb2015-06-22 19:35:57 +00005844
5845 // FIXME: Use better location, we should use proper tokens.
Nirav Davefd910412016-06-17 16:06:17 +00005846 SMLoc EqualLoc = Parser.getTok().getLoc();
Nirav Dave7fd992a2018-08-16 16:31:14 +00005847 if (Parser.parseExpression(Value))
5848 return Parser.TokError("missing expression");
Pete Cooper80d21cb2015-06-22 19:35:57 +00005849
5850 // Note: we don't count b as used in "a = b". This is to allow
5851 // a = b
5852 // b = c
5853
Nirav Dave1a9044b2016-10-24 14:35:29 +00005854 if (Parser.parseToken(AsmToken::EndOfStatement))
5855 return true;
Pete Cooper80d21cb2015-06-22 19:35:57 +00005856
5857 // Validate that the LHS is allowed to be a variable (either it has not been
5858 // used as a symbol, or it is an absolute symbol).
5859 Sym = Parser.getContext().lookupSymbol(Name);
5860 if (Sym) {
5861 // Diagnose assignment to a label.
5862 //
5863 // FIXME: Diagnostics. Note the location of the definition as a label.
5864 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
5865 if (isSymbolUsedInExpression(Sym, Value))
5866 return Parser.Error(EqualLoc, "Recursive use of '" + Name + "'");
Vedant Kumar86dbd922015-08-31 17:44:53 +00005867 else if (Sym->isUndefined(/*SetUsed*/ false) && !Sym->isUsed() &&
5868 !Sym->isVariable())
Pete Cooper80d21cb2015-06-22 19:35:57 +00005869 ; // Allow redefinitions of undefined symbols only used in directives.
5870 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
5871 ; // Allow redefinitions of variables that haven't yet been used.
5872 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
5873 return Parser.Error(EqualLoc, "redefinition of '" + Name + "'");
5874 else if (!Sym->isVariable())
5875 return Parser.Error(EqualLoc, "invalid assignment to '" + Name + "'");
5876 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
5877 return Parser.Error(EqualLoc,
5878 "invalid reassignment of non-absolute variable '" +
5879 Name + "'");
Pete Cooper80d21cb2015-06-22 19:35:57 +00005880 } else if (Name == ".") {
Oliver Stannard268f42f2016-12-14 10:43:58 +00005881 Parser.getStreamer().emitValueToOffset(Value, 0, EqualLoc);
Pete Cooper80d21cb2015-06-22 19:35:57 +00005882 return false;
5883 } else
5884 Sym = Parser.getContext().getOrCreateSymbol(Name);
5885
5886 Sym->setRedefinable(allow_redef);
5887
5888 return false;
5889}
5890
Eugene Zelenko33d7b762016-08-23 17:14:32 +00005891} // end namespace MCParserUtils
5892} // end namespace llvm
Pete Cooper80d21cb2015-06-22 19:35:57 +00005893
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00005894/// Create an MCAsmParser instance.
Jim Grosbach4b905842013-09-20 23:08:21 +00005895MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
Sanne Wouda29338752017-02-08 14:48:05 +00005896 MCStreamer &Out, const MCAsmInfo &MAI,
5897 unsigned CB) {
5898 return new AsmParser(SM, C, Out, MAI, CB);
Daniel Dunbar01e36072010-07-17 02:26:10 +00005899}