blob: 00418ac70ba9493bfc5330d6d164655ab2ae7f3c [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 Dave05b58912018-06-05 15:13:39 +0000340 bool NoDeadStrip = false, bool AllowExtendedExpr = false);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000341
Ahmed Bougacha457852f2015-04-28 00:17:39 +0000342 unsigned getBinOpPrecedence(AsmToken::TokenKind K,
343 MCBinaryExpr::Opcode &Kind);
344
Jim Grosbach4b905842013-09-20 23:08:21 +0000345 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
346 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
347 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000348
Jim Grosbach4b905842013-09-20 23:08:21 +0000349 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
Rafael Espindola63760ba2010-10-28 20:02:27 +0000350
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000351 bool parseCVFunctionId(int64_t &FunctionId, StringRef DirectiveName);
352 bool parseCVFileId(int64_t &FileId, StringRef DirectiveName);
353
Eli Bendersky17233942013-01-15 22:59:42 +0000354 // Generic (target and platform independent) directive parsing.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000355 enum DirectiveKind {
Eli Bendersky4d21fa02013-01-10 23:40:56 +0000356 DK_NO_DIRECTIVE, // Placeholder
Saleem Abdulrasoolb3c70c02017-07-28 03:39:18 +0000357 DK_SET,
358 DK_EQU,
359 DK_EQUIV,
360 DK_ASCII,
361 DK_ASCIZ,
362 DK_STRING,
363 DK_BYTE,
364 DK_SHORT,
Daniel Sanders9f6ad492015-11-12 13:33:00 +0000365 DK_RELOC,
Saleem Abdulrasoolb3c70c02017-07-28 03:39:18 +0000366 DK_VALUE,
367 DK_2BYTE,
368 DK_LONG,
369 DK_INT,
370 DK_4BYTE,
371 DK_QUAD,
372 DK_8BYTE,
373 DK_OCTA,
374 DK_DC,
375 DK_DC_A,
376 DK_DC_B,
377 DK_DC_D,
378 DK_DC_L,
379 DK_DC_S,
380 DK_DC_W,
381 DK_DC_X,
382 DK_DCB,
383 DK_DCB_B,
384 DK_DCB_D,
385 DK_DCB_L,
386 DK_DCB_S,
387 DK_DCB_W,
388 DK_DCB_X,
389 DK_DS,
390 DK_DS_B,
391 DK_DS_D,
392 DK_DS_L,
393 DK_DS_P,
394 DK_DS_S,
395 DK_DS_W,
396 DK_DS_X,
397 DK_SINGLE,
398 DK_FLOAT,
399 DK_DOUBLE,
400 DK_ALIGN,
401 DK_ALIGN32,
402 DK_BALIGN,
403 DK_BALIGNW,
404 DK_BALIGNL,
405 DK_P2ALIGN,
406 DK_P2ALIGNW,
407 DK_P2ALIGNL,
408 DK_ORG,
409 DK_FILL,
410 DK_ENDR,
411 DK_BUNDLE_ALIGN_MODE,
412 DK_BUNDLE_LOCK,
413 DK_BUNDLE_UNLOCK,
414 DK_ZERO,
415 DK_EXTERN,
416 DK_GLOBL,
417 DK_GLOBAL,
418 DK_LAZY_REFERENCE,
419 DK_NO_DEAD_STRIP,
420 DK_SYMBOL_RESOLVER,
421 DK_PRIVATE_EXTERN,
422 DK_REFERENCE,
423 DK_WEAK_DEFINITION,
424 DK_WEAK_REFERENCE,
425 DK_WEAK_DEF_CAN_BE_HIDDEN,
426 DK_COMM,
427 DK_COMMON,
428 DK_LCOMM,
429 DK_ABORT,
430 DK_INCLUDE,
431 DK_INCBIN,
432 DK_CODE16,
433 DK_CODE16GCC,
434 DK_REPT,
435 DK_IRP,
436 DK_IRPC,
437 DK_IF,
438 DK_IFEQ,
439 DK_IFGE,
440 DK_IFGT,
441 DK_IFLE,
442 DK_IFLT,
443 DK_IFNE,
444 DK_IFB,
445 DK_IFNB,
446 DK_IFC,
447 DK_IFEQS,
448 DK_IFNC,
449 DK_IFNES,
450 DK_IFDEF,
451 DK_IFNDEF,
452 DK_IFNOTDEF,
453 DK_ELSEIF,
454 DK_ELSE,
455 DK_ENDIF,
456 DK_SPACE,
457 DK_SKIP,
458 DK_FILE,
459 DK_LINE,
460 DK_LOC,
461 DK_STABS,
462 DK_CV_FILE,
463 DK_CV_FUNC_ID,
464 DK_CV_INLINE_SITE_ID,
465 DK_CV_LOC,
466 DK_CV_LINETABLE,
467 DK_CV_INLINE_LINETABLE,
468 DK_CV_DEF_RANGE,
469 DK_CV_STRINGTABLE,
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000470 DK_CV_FILECHECKSUMS,
Reid Kleckner26fa1bf2017-09-19 18:14:45 +0000471 DK_CV_FILECHECKSUM_OFFSET,
Reid Kleckner9cdd4df2017-10-11 21:24:33 +0000472 DK_CV_FPO_DATA,
Saleem Abdulrasoolb3c70c02017-07-28 03:39:18 +0000473 DK_CFI_SECTIONS,
474 DK_CFI_STARTPROC,
475 DK_CFI_ENDPROC,
476 DK_CFI_DEF_CFA,
477 DK_CFI_DEF_CFA_OFFSET,
478 DK_CFI_ADJUST_CFA_OFFSET,
479 DK_CFI_DEF_CFA_REGISTER,
480 DK_CFI_OFFSET,
481 DK_CFI_REL_OFFSET,
482 DK_CFI_PERSONALITY,
483 DK_CFI_LSDA,
484 DK_CFI_REMEMBER_STATE,
485 DK_CFI_RESTORE_STATE,
486 DK_CFI_SAME_VALUE,
487 DK_CFI_RESTORE,
488 DK_CFI_ESCAPE,
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +0000489 DK_CFI_RETURN_COLUMN,
Saleem Abdulrasoolb3c70c02017-07-28 03:39:18 +0000490 DK_CFI_SIGNAL_FRAME,
491 DK_CFI_UNDEFINED,
492 DK_CFI_REGISTER,
493 DK_CFI_WINDOW_SAVE,
494 DK_MACROS_ON,
495 DK_MACROS_OFF,
496 DK_ALTMACRO,
497 DK_NOALTMACRO,
498 DK_MACRO,
499 DK_EXITM,
500 DK_ENDM,
501 DK_ENDMACRO,
502 DK_PURGEM,
503 DK_SLEB128,
504 DK_ULEB128,
505 DK_ERR,
506 DK_ERROR,
507 DK_WARNING,
Coby Tayree01e53202017-10-02 14:36:31 +0000508 DK_PRINT,
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000509 DK_END
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000510 };
511
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000512 /// Maps directive name --> DirectiveKind enum, for
Eli Bendersky17233942013-01-15 22:59:42 +0000513 /// directives parsed by this class.
514 StringMap<DirectiveKind> DirectiveKindMap;
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000515
516 // ".ascii", ".asciz", ".string"
Jim Grosbach4b905842013-09-20 23:08:21 +0000517 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
Daniel Sanders9f6ad492015-11-12 13:33:00 +0000518 bool parseDirectiveReloc(SMLoc DirectiveLoc); // ".reloc"
Nirav Dave1a9044b2016-10-24 14:35:29 +0000519 bool parseDirectiveValue(StringRef IDVal,
520 unsigned Size); // ".byte", ".long", ...
521 bool parseDirectiveOctaValue(StringRef IDVal); // ".octa", ...
522 bool parseDirectiveRealValue(StringRef IDVal,
523 const fltSemantics &); // ".single", ...
Jim Grosbach4b905842013-09-20 23:08:21 +0000524 bool parseDirectiveFill(); // ".fill"
525 bool parseDirectiveZero(); // ".zero"
Eric Christophera7c32732012-12-18 00:30:54 +0000526 // ".set", ".equ", ".equiv"
Jim Grosbach4b905842013-09-20 23:08:21 +0000527 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
528 bool parseDirectiveOrg(); // ".org"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000529 // ".align{,32}", ".p2align{,w,l}"
Jim Grosbach4b905842013-09-20 23:08:21 +0000530 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000531
Eli Bendersky17233942013-01-15 22:59:42 +0000532 // ".file", ".line", ".loc", ".stabs"
Jim Grosbach4b905842013-09-20 23:08:21 +0000533 bool parseDirectiveFile(SMLoc DirectiveLoc);
534 bool parseDirectiveLine();
535 bool parseDirectiveLoc();
536 bool parseDirectiveStabs();
Eli Bendersky17233942013-01-15 22:59:42 +0000537
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000538 // ".cv_file", ".cv_func_id", ".cv_inline_site_id", ".cv_loc", ".cv_linetable",
539 // ".cv_inline_linetable", ".cv_def_range"
Reid Kleckner2214ed82016-01-29 00:49:42 +0000540 bool parseDirectiveCVFile();
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000541 bool parseDirectiveCVFuncId();
542 bool parseDirectiveCVInlineSiteId();
Reid Kleckner2214ed82016-01-29 00:49:42 +0000543 bool parseDirectiveCVLoc();
544 bool parseDirectiveCVLinetable();
David Majnemer6fcbd7e2016-01-29 19:24:12 +0000545 bool parseDirectiveCVInlineLinetable();
David Majnemer408b5e62016-02-05 01:55:49 +0000546 bool parseDirectiveCVDefRange();
Reid Kleckner2214ed82016-01-29 00:49:42 +0000547 bool parseDirectiveCVStringTable();
548 bool parseDirectiveCVFileChecksums();
Reid Kleckner26fa1bf2017-09-19 18:14:45 +0000549 bool parseDirectiveCVFileChecksumOffset();
Reid Kleckner9cdd4df2017-10-11 21:24:33 +0000550 bool parseDirectiveCVFPOData();
Reid Kleckner2214ed82016-01-29 00:49:42 +0000551
Eli Bendersky17233942013-01-15 22:59:42 +0000552 // .cfi directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000553 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +0000554 bool parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +0000555 bool parseDirectiveCFISections();
556 bool parseDirectiveCFIStartProc();
557 bool parseDirectiveCFIEndProc();
558 bool parseDirectiveCFIDefCfaOffset();
559 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
560 bool parseDirectiveCFIAdjustCfaOffset();
561 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
562 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
563 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
564 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
565 bool parseDirectiveCFIRememberState();
566 bool parseDirectiveCFIRestoreState();
567 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
568 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
569 bool parseDirectiveCFIEscape();
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +0000570 bool parseDirectiveCFIReturnColumn(SMLoc DirectiveLoc);
Jim Grosbach4b905842013-09-20 23:08:21 +0000571 bool parseDirectiveCFISignalFrame();
572 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
Eli Bendersky17233942013-01-15 22:59:42 +0000573
574 // macro directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000575 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
Nico Weber155dccd12014-07-24 17:08:39 +0000576 bool parseDirectiveExitMacro(StringRef Directive);
Jim Grosbach4b905842013-09-20 23:08:21 +0000577 bool parseDirectiveEndMacro(StringRef Directive);
578 bool parseDirectiveMacro(SMLoc DirectiveLoc);
579 bool parseDirectiveMacrosOnOff(StringRef Directive);
Michael Zuckerman56704612017-05-01 13:20:12 +0000580 // alternate macro mode directives
581 bool parseDirectiveAltmacro(StringRef Directive);
Eli Benderskyf483ff92012-12-20 19:05:53 +0000582 // ".bundle_align_mode"
Jim Grosbach4b905842013-09-20 23:08:21 +0000583 bool parseDirectiveBundleAlignMode();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000584 // ".bundle_lock"
Jim Grosbach4b905842013-09-20 23:08:21 +0000585 bool parseDirectiveBundleLock();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000586 // ".bundle_unlock"
Jim Grosbach4b905842013-09-20 23:08:21 +0000587 bool parseDirectiveBundleUnlock();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000588
Eli Bendersky17233942013-01-15 22:59:42 +0000589 // ".space", ".skip"
Jim Grosbach4b905842013-09-20 23:08:21 +0000590 bool parseDirectiveSpace(StringRef IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +0000591
Petr Hosek4cb08ce2016-09-23 19:25:15 +0000592 // ".dcb"
593 bool parseDirectiveDCB(StringRef IDVal, unsigned Size);
594 bool parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &);
Petr Hosek85b2f672016-09-23 21:53:36 +0000595 // ".ds"
596 bool parseDirectiveDS(StringRef IDVal, unsigned Size);
Petr Hosek4cb08ce2016-09-23 19:25:15 +0000597
Eli Bendersky17233942013-01-15 22:59:42 +0000598 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
Jim Grosbach4b905842013-09-20 23:08:21 +0000599 bool parseDirectiveLEB128(bool Signed);
Eli Bendersky17233942013-01-15 22:59:42 +0000600
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000601 /// Parse a directive like ".globl" which
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000602 /// accepts a single symbol (which should be a label or an external).
Jim Grosbach4b905842013-09-20 23:08:21 +0000603 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000604
Jim Grosbach4b905842013-09-20 23:08:21 +0000605 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000606
Jim Grosbach4b905842013-09-20 23:08:21 +0000607 bool parseDirectiveAbort(); // ".abort"
608 bool parseDirectiveInclude(); // ".include"
609 bool parseDirectiveIncbin(); // ".incbin"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000610
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +0000611 // ".if", ".ifeq", ".ifge", ".ifgt" , ".ifle", ".iflt" or ".ifne"
612 bool parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind);
Benjamin Kramer62c18b02012-05-12 11:18:42 +0000613 // ".ifb" or ".ifnb", depending on ExpectBlank.
Jim Grosbach4b905842013-09-20 23:08:21 +0000614 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000615 // ".ifc" or ".ifnc", depending on ExpectEqual.
Jim Grosbach4b905842013-09-20 23:08:21 +0000616 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
Sid Manning51c35602015-03-18 14:20:54 +0000617 // ".ifeqs" or ".ifnes", depending on ExpectEqual.
618 bool parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +0000619 // ".ifdef" or ".ifndef", depending on expect_defined
Jim Grosbach4b905842013-09-20 23:08:21 +0000620 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
621 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
622 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
623 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
Craig Topper59be68f2014-03-08 07:14:16 +0000624 bool parseEscapedString(std::string &Data) override;
Daniel Dunbar55f16672010-09-17 02:47:07 +0000625
Jim Grosbach4b905842013-09-20 23:08:21 +0000626 const MCExpr *applyModifierToExpr(const MCExpr *E,
Daniel Dunbar55f16672010-09-17 02:47:07 +0000627 MCSymbolRefExpr::VariantKind Variant);
Rafael Espindola47b7dac2012-05-12 16:31:10 +0000628
Rafael Espindola34b9c512012-06-03 23:57:14 +0000629 // Macro-like directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000630 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
631 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +0000632 raw_svector_ostream &OS);
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +0000633 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
Jim Grosbach4b905842013-09-20 23:08:21 +0000634 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
635 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
636 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
Chad Rosier8bce6642012-10-18 15:49:34 +0000637
Chad Rosierc7f552c2013-02-12 21:33:51 +0000638 // "_emit" or "__emit"
Jim Grosbach4b905842013-09-20 23:08:21 +0000639 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
Chad Rosierc7f552c2013-02-12 21:33:51 +0000640 size_t Len);
641
642 // "align"
Jim Grosbach4b905842013-09-20 23:08:21 +0000643 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000644
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000645 // "end"
646 bool parseDirectiveEnd(SMLoc DirectiveLoc);
647
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +0000648 // ".err" or ".error"
649 bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +0000650
Nico Weber404012b2014-07-24 16:26:06 +0000651 // ".warning"
652 bool parseDirectiveWarning(SMLoc DirectiveLoc);
653
Coby Tayree01e53202017-10-02 14:36:31 +0000654 // .print <double-quotes-string>
655 bool parseDirectivePrint(SMLoc DirectiveLoc);
656
Eli Bendersky17233942013-01-15 22:59:42 +0000657 void initializeDirectiveKindMap();
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000658};
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000659
660} // end anonymous namespace
Daniel Dunbar86033402010-07-12 17:54:38 +0000661
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000662namespace llvm {
663
664extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbarab058b82010-07-12 21:23:32 +0000665extern MCAsmParserExtension *createELFAsmParser();
Michael J. Spencerc8dbdfd2010-10-09 11:01:07 +0000666extern MCAsmParserExtension *createCOFFAsmParser();
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000667
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000668} // end namespace llvm
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000669
Chris Lattnerc35681b2010-01-19 19:46:13 +0000670enum { DEFAULT_ADDRSPACE = 0 };
671
David Blaikie9f380a32015-03-16 18:06:57 +0000672AsmParser::AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Sanne Wouda29338752017-02-08 14:48:05 +0000673 const MCAsmInfo &MAI, unsigned CB = 0)
David Blaikie9f380a32015-03-16 18:06:57 +0000674 : Lexer(MAI), Ctx(Ctx), Out(Out), MAI(MAI), SrcMgr(SM),
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000675 CurBuffer(CB ? CB : SM.getMainFileID()), MacrosEnabledFlag(true) {
Nirav Dave2364748a2016-09-16 18:30:20 +0000676 HadError = false;
Benjamin Kramer47f5e302011-10-16 10:48:29 +0000677 // Save the old handler.
678 SavedDiagHandler = SrcMgr.getDiagHandler();
679 SavedDiagContext = SrcMgr.getDiagContext();
680 // Set our own handler which calls the saved handler.
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000681 SrcMgr.setDiagHandler(DiagHandler, this);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000682 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar86033402010-07-12 17:54:38 +0000683
Daniel Dunbarc5011082010-07-12 18:12:02 +0000684 // Initialize the platform / file format parser.
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000685 switch (Ctx.getObjectFileInfo()->getObjectFileType()) {
686 case MCObjectFileInfo::IsCOFF:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000687 PlatformParser.reset(createCOFFAsmParser());
688 break;
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000689 case MCObjectFileInfo::IsMachO:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000690 PlatformParser.reset(createDarwinAsmParser());
691 IsDarwin = true;
692 break;
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000693 case MCObjectFileInfo::IsELF:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000694 PlatformParser.reset(createELFAsmParser());
695 break;
Dan Gohman18eafb62017-02-22 01:23:18 +0000696 case MCObjectFileInfo::IsWasm:
Sam Cleggf009da22018-04-19 22:00:53 +0000697 // TODO: WASM will need its own MCAsmParserExtension implementation, but
698 // for now we can re-use the ELF one, since the directives can be the
699 // same for now, and this makes the -triple=wasm32-unknown-unknown-wasm
700 // path work.
701 PlatformParser.reset(createELFAsmParser());
Dan Gohman18eafb62017-02-22 01:23:18 +0000702 break;
Daniel Dunbarc5011082010-07-12 18:12:02 +0000703 }
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000704
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000705 PlatformParser->Initialize(*this);
Eli Bendersky17233942013-01-15 22:59:42 +0000706 initializeDirectiveKindMap();
Toma Tabacu217116e2015-04-27 10:50:29 +0000707
708 NumOfMacroInstantiations = 0;
Chris Lattner351a7ef2009-09-27 21:16:52 +0000709}
710
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000711AsmParser::~AsmParser() {
Saleem Abdulrasool6eae1e62014-05-21 17:53:18 +0000712 assert((HadError || ActiveMacros.empty()) &&
713 "Unexpected active macro instantiation!");
Sanne Wouda29338752017-02-08 14:48:05 +0000714
715 // Restore the saved diagnostics handler and context for use during
716 // finalization.
717 SrcMgr.setDiagHandler(SavedDiagHandler, SavedDiagContext);
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000718}
719
Jim Grosbach4b905842013-09-20 23:08:21 +0000720void AsmParser::printMacroInstantiations() {
Daniel Dunbar43235712010-07-18 18:54:11 +0000721 // Print the active macro instantiation stack.
Jim Grosbach4b905842013-09-20 23:08:21 +0000722 for (std::vector<MacroInstantiation *>::const_reverse_iterator
723 it = ActiveMacros.rbegin(),
724 ie = ActiveMacros.rend();
725 it != ie; ++it)
726 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
Chris Lattner03b80a42011-10-16 05:43:57 +0000727 "while in macro instantiation");
Daniel Dunbar43235712010-07-18 18:54:11 +0000728}
729
Nirav Dave2364748a2016-09-16 18:30:20 +0000730void AsmParser::Note(SMLoc L, const Twine &Msg, SMRange Range) {
731 printPendingErrors();
732 printMessage(L, SourceMgr::DK_Note, Msg, Range);
Saleem Abdulrasool69c7caf2014-01-07 02:28:31 +0000733 printMacroInstantiations();
734}
735
Nirav Dave2364748a2016-09-16 18:30:20 +0000736bool AsmParser::Warning(SMLoc L, const Twine &Msg, SMRange Range) {
Colin LeMahieufe36f832015-07-27 22:39:14 +0000737 if(getTargetParser().getTargetOptions().MCNoWarn)
738 return false;
Joerg Sonnenberger29815912014-08-26 18:39:50 +0000739 if (getTargetParser().getTargetOptions().MCFatalWarnings)
Nirav Dave2364748a2016-09-16 18:30:20 +0000740 return Error(L, Msg, Range);
741 printMessage(L, SourceMgr::DK_Warning, Msg, Range);
Jim Grosbach4b905842013-09-20 23:08:21 +0000742 printMacroInstantiations();
Joerg Sonnenberger74ba2622011-05-19 18:00:13 +0000743 return false;
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +0000744}
745
Nirav Dave2364748a2016-09-16 18:30:20 +0000746bool AsmParser::printError(SMLoc L, const Twine &Msg, SMRange Range) {
Daniel Dunbar43325c42010-09-09 22:42:56 +0000747 HadError = true;
Nirav Dave2364748a2016-09-16 18:30:20 +0000748 printMessage(L, SourceMgr::DK_Error, Msg, Range);
Jim Grosbach4b905842013-09-20 23:08:21 +0000749 printMacroInstantiations();
Chris Lattner2adc9e72009-06-21 21:22:11 +0000750 return true;
751}
752
Jim Grosbach4b905842013-09-20 23:08:21 +0000753bool AsmParser::enterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergeraf5f23e2011-06-01 13:10:15 +0000754 std::string IncludedFile;
Alp Tokera55b95b2014-07-06 10:33:31 +0000755 unsigned NewBuf =
756 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
757 if (!NewBuf)
Sean Callanan7a77eae2010-01-21 00:19:58 +0000758 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +0000759
Sean Callanan7a77eae2010-01-21 00:19:58 +0000760 CurBuffer = NewBuf;
Rafael Espindola8026bd02014-07-06 14:17:29 +0000761 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Sean Callanan7a77eae2010-01-21 00:19:58 +0000762 return false;
763}
Daniel Dunbar43235712010-07-18 18:54:11 +0000764
Sylvestre Ledru149e2812013-05-14 23:36:24 +0000765/// Process the specified .incbin file by searching for it in the include paths
Benjamin Kramerbde91762012-06-02 10:20:22 +0000766/// then just emitting the byte contents of the file to the streamer. This
Kevin Enderby109f25c2011-12-14 21:47:48 +0000767/// returns true on failure.
Petr Hosek2f4ac442016-09-23 00:41:06 +0000768bool AsmParser::processIncbinFile(const std::string &Filename, int64_t Skip,
769 const MCExpr *Count, SMLoc Loc) {
Kevin Enderby109f25c2011-12-14 21:47:48 +0000770 std::string IncludedFile;
Alp Tokera55b95b2014-07-06 10:33:31 +0000771 unsigned NewBuf =
772 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
773 if (!NewBuf)
Kevin Enderby109f25c2011-12-14 21:47:48 +0000774 return true;
775
Kevin Enderbyad41ab52011-12-14 22:34:45 +0000776 // Pick up the bytes from the file and emit them.
Petr Hosek2f4ac442016-09-23 00:41:06 +0000777 StringRef Bytes = SrcMgr.getMemoryBuffer(NewBuf)->getBuffer();
778 Bytes = Bytes.drop_front(Skip);
779 if (Count) {
780 int64_t Res;
Nirav Dave6c0665e2018-04-30 19:22:40 +0000781 if (!Count->evaluateAsAbsolute(Res, getStreamer().getAssemblerPtr()))
Petr Hosek2f4ac442016-09-23 00:41:06 +0000782 return Error(Loc, "expected absolute expression");
783 if (Res < 0)
784 return Warning(Loc, "negative count has no effect");
785 Bytes = Bytes.take_front(Res);
786 }
787 getStreamer().EmitBytes(Bytes);
Kevin Enderby109f25c2011-12-14 21:47:48 +0000788 return false;
789}
790
Alp Tokera55b95b2014-07-06 10:33:31 +0000791void AsmParser::jumpToLoc(SMLoc Loc, unsigned InBuffer) {
792 CurBuffer = InBuffer ? InBuffer : SrcMgr.FindBufferContainingLoc(Loc);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000793 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(),
794 Loc.getPointer());
Daniel Dunbar43235712010-07-18 18:54:11 +0000795}
796
Sean Callanan7a77eae2010-01-21 00:19:58 +0000797const AsmToken &AsmParser::Lex() {
Nirav Dave1180e6892016-06-02 17:15:05 +0000798 if (Lexer.getTok().is(AsmToken::Error))
799 Error(Lexer.getErrLoc(), Lexer.getErr());
800
Nirav Dave53a72f42016-07-11 12:42:14 +0000801 // if it's a end of statement with a comment in it
802 if (getTok().is(AsmToken::EndOfStatement)) {
803 // if this is a line comment output it.
Nirav Dave670109d2017-06-09 14:04:03 +0000804 if (!getTok().getString().empty() && getTok().getString().front() != '\n' &&
Nirav Dave53a72f42016-07-11 12:42:14 +0000805 getTok().getString().front() != '\r' && MAI.preserveAsmComments())
806 Out.addExplicitComment(Twine(getTok().getString()));
807 }
808
Sean Callanan7a77eae2010-01-21 00:19:58 +0000809 const AsmToken *tok = &Lexer.Lex();
Nirav Dave53a72f42016-07-11 12:42:14 +0000810
811 // Parse comments here to be deferred until end of next statement.
Nirav Davefd910412016-06-17 16:06:17 +0000812 while (tok->is(AsmToken::Comment)) {
Nirav Dave53a72f42016-07-11 12:42:14 +0000813 if (MAI.preserveAsmComments())
814 Out.addExplicitComment(Twine(tok->getString()));
Nirav Davefd910412016-06-17 16:06:17 +0000815 tok = &Lexer.Lex();
816 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000817
Sean Callanan7a77eae2010-01-21 00:19:58 +0000818 if (tok->is(AsmToken::Eof)) {
819 // If this is the end of an included file, pop the parent file off the
820 // include stack.
821 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
822 if (ParentIncludeLoc != SMLoc()) {
Jim Grosbach4b905842013-09-20 23:08:21 +0000823 jumpToLoc(ParentIncludeLoc);
Nirav Davefd910412016-06-17 16:06:17 +0000824 return Lex();
Sean Callanan7a77eae2010-01-21 00:19:58 +0000825 }
826 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000827
Sean Callanan7a77eae2010-01-21 00:19:58 +0000828 return *tok;
Sean Callanan686ed8d2010-01-19 20:22:31 +0000829}
830
Paul Robinson938d9a02018-03-22 15:48:01 +0000831bool AsmParser::enabledGenDwarfForAssembly() {
832 // Check whether the user specified -g.
833 if (!getContext().getGenDwarfForAssembly())
834 return false;
835 // If we haven't encountered any .file directives (which would imply that
836 // the assembler source was produced with debug info already) then emit one
837 // describing the assembler source file itself.
838 if (getContext().getGenDwarfFileNumber() == 0)
839 getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective(
840 0, StringRef(), getContext().getMainFileName()));
841 return true;
842}
843
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000844bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar322fec62010-03-13 02:20:57 +0000845 // Create the initial section, if requested.
Daniel Dunbar322fec62010-03-13 02:20:57 +0000846 if (!NoInitialTextSection)
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000847 Out.InitSections(false);
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000848
Chris Lattner36e02122009-06-21 20:54:55 +0000849 // Prime the lexer.
Sean Callanan686ed8d2010-01-19 20:22:31 +0000850 Lex();
Daniel Dunbar43325c42010-09-09 22:42:56 +0000851
852 HadError = false;
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000853 AsmCond StartingCondState = TheCondState;
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +0000854 SmallVector<AsmRewrite, 4> AsmStrRewrites;
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000855
Kevin Enderby6469fc22011-11-01 22:27:22 +0000856 // If we are generating dwarf for assembly source files save the initial text
Paul Robinson938d9a02018-03-22 15:48:01 +0000857 // section. (Don't use enabledGenDwarfForAssembly() here, as we aren't
858 // emitting any actual debug info yet and haven't had a chance to parse any
859 // embedded .file directives.)
Kevin Enderby6469fc22011-11-01 22:27:22 +0000860 if (getContext().getGenDwarfForAssembly()) {
Eric Christopher445c9522016-10-14 05:47:37 +0000861 MCSection *Sec = getStreamer().getCurrentSectionOnly();
Rafael Espindola2f9bdd82015-05-27 20:52:32 +0000862 if (!Sec->getBeginSymbol()) {
863 MCSymbol *SectionStartSym = getContext().createTempSymbol();
864 getStreamer().EmitLabel(SectionStartSym);
865 Sec->setBeginSymbol(SectionStartSym);
866 }
Rafael Espindolae0746792015-05-21 16:52:32 +0000867 bool InsertResult = getContext().addGenDwarfSection(Sec);
868 assert(InsertResult && ".text section should not have debug info yet");
Rafael Espindolafa160c72015-05-21 17:09:22 +0000869 (void)InsertResult;
Kevin Enderby6469fc22011-11-01 22:27:22 +0000870 }
871
Chris Lattner73f36112009-07-02 21:53:43 +0000872 // While we have input, parse each statement.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000873 while (Lexer.isNot(AsmToken::Eof)) {
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +0000874 ParseStatementInfo Info(&AsmStrRewrites);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +0000875 if (!parseStatement(Info, nullptr))
Jim Grosbach4b905842013-09-20 23:08:21 +0000876 continue;
Michael J. Spencer530ce852010-10-09 11:00:50 +0000877
Nirav Dave2364748a2016-09-16 18:30:20 +0000878 // If we have a Lexer Error we are on an Error Token. Load in Lexer Error
879 // for printing ErrMsg via Lex() only if no (presumably better) parser error
880 // exists.
881 if (!hasPendingError() && Lexer.getTok().is(AsmToken::Error)) {
Nirav Dave1180e6892016-06-02 17:15:05 +0000882 Lex();
883 }
884
Nirav Dave2364748a2016-09-16 18:30:20 +0000885 // parseStatement returned true so may need to emit an error.
886 printPendingErrors();
887
888 // Skipping to the next line if needed.
889 if (!getLexer().isAtStartOfStatement())
890 eatToEndOfStatement();
Chris Lattner73f36112009-07-02 21:53:43 +0000891 }
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000892
Nirav Dave2364748a2016-09-16 18:30:20 +0000893 // All errors should have been emitted.
894 assert(!hasPendingError() && "unexpected error from parseStatement");
895
Oliver Stannard21718282016-07-26 14:19:47 +0000896 getTargetParser().flushPendingInstructions(getStreamer());
897
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000898 if (TheCondState.TheCond != StartingCondState.TheCond ||
899 TheCondState.Ignore != StartingCondState.Ignore)
Nirav Dave2364748a2016-09-16 18:30:20 +0000900 printError(getTok().getLoc(), "unmatched .ifs or .elses");
Kevin Enderbye5930f12010-07-28 20:55:35 +0000901 // Check to see there are no empty DwarfFile slots.
David Blaikie8bf66c42014-04-01 07:35:52 +0000902 const auto &LineTables = getContext().getMCDwarfLineTables();
903 if (!LineTables.empty()) {
904 unsigned Index = 0;
905 for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) {
906 if (File.Name.empty() && Index != 0)
Nirav Dave2364748a2016-09-16 18:30:20 +0000907 printError(getTok().getLoc(), "unassigned file number: " +
908 Twine(Index) +
909 " for .file directives");
David Blaikie8bf66c42014-04-01 07:35:52 +0000910 ++Index;
911 }
Kevin Enderbye5930f12010-07-28 20:55:35 +0000912 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000913
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000914 // Check to see that all assembler local symbols were actually defined.
915 // Targets that don't do subsections via symbols may not want this, though,
916 // so conservatively exclude them. Only do this if we're finalizing, though,
917 // as otherwise we won't necessarilly have seen everything yet.
Tim Northover6b3169b2016-04-11 19:50:46 +0000918 if (!NoFinalize) {
919 if (MAI.hasSubsectionsViaSymbols()) {
920 for (const auto &TableEntry : getContext().getSymbols()) {
921 MCSymbol *Sym = TableEntry.getValue();
922 // Variable symbols may not be marked as defined, so check those
923 // explicitly. If we know it's a variable, we have a definition for
924 // the purposes of this check.
925 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
926 // FIXME: We would really like to refer back to where the symbol was
927 // first referenced for a source location. We need to add something
928 // to track that. Currently, we just point to the end of the file.
Nirav Dave2364748a2016-09-16 18:30:20 +0000929 printError(getTok().getLoc(), "assembler local symbol '" +
930 Sym->getName() + "' not defined");
Tim Northover6b3169b2016-04-11 19:50:46 +0000931 }
932 }
933
934 // Temporary symbols like the ones for directional jumps don't go in the
935 // symbol table. They also need to be diagnosed in all (final) cases.
Tim Northoverc0bef992016-04-13 19:46:54 +0000936 for (std::tuple<SMLoc, CppHashInfoTy, MCSymbol *> &LocSym : DirLabels) {
937 if (std::get<2>(LocSym)->isUndefined()) {
938 // Reset the state of any "# line file" directives we've seen to the
939 // context as it was at the diagnostic site.
940 CppHashInfo = std::get<1>(LocSym);
Nirav Dave2364748a2016-09-16 18:30:20 +0000941 printError(std::get<0>(LocSym), "directional label undefined");
Tim Northoverc0bef992016-04-13 19:46:54 +0000942 }
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000943 }
944 }
945
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000946 // Finalize the output stream if there are no errors and if the client wants
947 // us to.
Jack Carter13d5f752013-10-04 22:52:31 +0000948 if (!HadError && !NoFinalize)
Daniel Dunbar9df5f332009-08-21 08:34:18 +0000949 Out.Finish();
950
Oliver Stannard07b43d32015-11-17 09:58:07 +0000951 return HadError || getContext().hadError();
Chris Lattner36e02122009-06-21 20:54:55 +0000952}
953
Nirav Davef43cc9f2016-10-10 15:24:54 +0000954bool AsmParser::checkForValidSection() {
Eric Christopher445c9522016-10-14 05:47:37 +0000955 if (!ParsingInlineAsm && !getStreamer().getCurrentSectionOnly()) {
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000956 Out.InitSections(false);
Nirav Davef43cc9f2016-10-10 15:24:54 +0000957 return Error(getTok().getLoc(),
958 "expected section directive before assembly directive");
Daniel Dunbare5444a82010-09-09 22:42:59 +0000959 }
Nirav Davef43cc9f2016-10-10 15:24:54 +0000960 return false;
Daniel Dunbare5444a82010-09-09 22:42:59 +0000961}
962
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000963/// Throw away the rest of the line for testing purposes.
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000964void AsmParser::eatToEndOfStatement() {
Jim Grosbach4b905842013-09-20 23:08:21 +0000965 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Nirav Dave1180e6892016-06-02 17:15:05 +0000966 Lexer.Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +0000967
Chris Lattnere5074c42009-06-22 01:29:09 +0000968 // Eat EOL.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000969 if (Lexer.is(AsmToken::EndOfStatement))
Nirav Dave1180e6892016-06-02 17:15:05 +0000970 Lexer.Lex();
Chris Lattnere5074c42009-06-22 01:29:09 +0000971}
972
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000973StringRef AsmParser::parseStringToEndOfStatement() {
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000974 const char *Start = getTok().getLoc().getPointer();
975
Jim Grosbach4b905842013-09-20 23:08:21 +0000976 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Nirav Davefd910412016-06-17 16:06:17 +0000977 Lexer.Lex();
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000978
979 const char *End = getTok().getLoc().getPointer();
980 return StringRef(Start, End - Start);
981}
Chris Lattner78db3622009-06-22 05:51:26 +0000982
Jim Grosbach4b905842013-09-20 23:08:21 +0000983StringRef AsmParser::parseStringToComma() {
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000984 const char *Start = getTok().getLoc().getPointer();
985
986 while (Lexer.isNot(AsmToken::EndOfStatement) &&
Jim Grosbach4b905842013-09-20 23:08:21 +0000987 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
Nirav Davefd910412016-06-17 16:06:17 +0000988 Lexer.Lex();
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000989
990 const char *End = getTok().getLoc().getPointer();
991 return StringRef(Start, End - Start);
992}
993
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000994/// Parse a paren expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +0000995/// NOTE: This assumes the leading '(' has already been consumed.
996///
997/// parenexpr ::= expr)
998///
Jim Grosbach4b905842013-09-20 23:08:21 +0000999bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
1000 if (parseExpression(Res))
1001 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001002 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner7fdbce72009-06-22 06:32:03 +00001003 return TokError("expected ')' in parentheses expression");
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001004 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001005 Lex();
Chris Lattner7fdbce72009-06-22 06:32:03 +00001006 return false;
1007}
Chris Lattner78db3622009-06-22 05:51:26 +00001008
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001009/// Parse a bracket expression and return it.
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +00001010/// NOTE: This assumes the leading '[' has already been consumed.
1011///
1012/// bracketexpr ::= expr]
1013///
Jim Grosbach4b905842013-09-20 23:08:21 +00001014bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
1015 if (parseExpression(Res))
1016 return true;
Nirav Davea645433c2016-07-18 15:24:03 +00001017 EndLoc = getTok().getEndLoc();
1018 if (parseToken(AsmToken::RBrac, "expected ']' in brackets expression"))
1019 return true;
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +00001020 return false;
1021}
1022
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001023/// Parse a primary expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +00001024/// primaryexpr ::= (parenexpr
1025/// primaryexpr ::= symbol
1026/// primaryexpr ::= number
Chris Lattner6b55cb92010-04-14 04:40:28 +00001027/// primaryexpr ::= '.'
Chris Lattner7fdbce72009-06-22 06:32:03 +00001028/// primaryexpr ::= ~,+,- primaryexpr
Jim Grosbach4b905842013-09-20 23:08:21 +00001029bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Kevin Enderby0017d8a2013-01-22 21:09:20 +00001030 SMLoc FirstTokenLoc = getLexer().getLoc();
1031 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
1032 switch (FirstTokenKind) {
Chris Lattner78db3622009-06-22 05:51:26 +00001033 default:
1034 return TokError("unknown token in expression");
Eric Christopher104af062011-04-12 00:03:13 +00001035 // If we have an error assume that we've already handled it.
1036 case AsmToken::Error:
1037 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001038 case AsmToken::Exclaim:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001039 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001040 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001041 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +00001042 Res = MCUnaryExpr::createLNot(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001043 return false;
Daniel Dunbar24764322010-08-24 19:13:42 +00001044 case AsmToken::Dollar:
Hans Wennborgce69d772013-10-18 20:46:28 +00001045 case AsmToken::At:
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +00001046 case AsmToken::String:
Daniel Dunbard20cda02009-10-16 01:34:54 +00001047 case AsmToken::Identifier: {
Daniel Dunbar24764322010-08-24 19:13:42 +00001048 StringRef Identifier;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001049 if (parseIdentifier(Identifier)) {
Nirav Daved0463322016-10-12 13:58:07 +00001050 // We may have failed but $ may be a valid token.
1051 if (getTok().is(AsmToken::Dollar)) {
David Majnemer0c58bc62013-09-25 10:47:21 +00001052 if (Lexer.getMAI().getDollarIsPC()) {
Nirav Daved0463322016-10-12 13:58:07 +00001053 Lex();
David Majnemer0c58bc62013-09-25 10:47:21 +00001054 // This is a '$' reference, which references the current PC. Emit a
1055 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +00001056 MCSymbol *Sym = Ctx.createTempSymbol();
David Majnemer0c58bc62013-09-25 10:47:21 +00001057 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +00001058 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None,
Jack Carter721726a2013-10-04 21:26:15 +00001059 getContext());
David Majnemer0c58bc62013-09-25 10:47:21 +00001060 EndLoc = FirstTokenLoc;
1061 return false;
Ted Kremenek297febe2014-03-06 22:13:17 +00001062 }
1063 return Error(FirstTokenLoc, "invalid token in expression");
David Majnemer0c58bc62013-09-25 10:47:21 +00001064 }
Kevin Enderby0017d8a2013-01-22 21:09:20 +00001065 }
David Peixotto8ad70b32013-12-04 22:43:20 +00001066 // Parse symbol variant
1067 std::pair<StringRef, StringRef> Split;
1068 if (!MAI.useParensForSymbolVariant()) {
David Majnemer6a5b8122014-06-19 01:25:43 +00001069 if (FirstTokenKind == AsmToken::String) {
1070 if (Lexer.is(AsmToken::At)) {
Nirav Davefd910412016-06-17 16:06:17 +00001071 Lex(); // eat @
David Majnemer6a5b8122014-06-19 01:25:43 +00001072 SMLoc AtLoc = getLexer().getLoc();
1073 StringRef VName;
1074 if (parseIdentifier(VName))
1075 return Error(AtLoc, "expected symbol variant after '@'");
1076
1077 Split = std::make_pair(Identifier, VName);
1078 }
1079 } else {
1080 Split = Identifier.split('@');
1081 }
David Peixotto8ad70b32013-12-04 22:43:20 +00001082 } else if (Lexer.is(AsmToken::LParen)) {
Nirav Davefd910412016-06-17 16:06:17 +00001083 Lex(); // eat '('.
David Peixotto8ad70b32013-12-04 22:43:20 +00001084 StringRef VName;
1085 parseIdentifier(VName);
Nirav Davea645433c2016-07-18 15:24:03 +00001086 // eat ')'.
1087 if (parseToken(AsmToken::RParen,
1088 "unexpected token in variant, expected ')'"))
1089 return true;
David Peixotto8ad70b32013-12-04 22:43:20 +00001090 Split = std::make_pair(Identifier, VName);
1091 }
Daniel Dunbar24764322010-08-24 19:13:42 +00001092
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001093 EndLoc = SMLoc::getFromPointer(Identifier.end());
1094
Daniel Dunbard20cda02009-10-16 01:34:54 +00001095 // This is a symbol reference.
Hans Wennborgce69d772013-10-18 20:46:28 +00001096 StringRef SymbolName = Identifier;
Weiming Zhaocf26d562016-12-01 18:00:36 +00001097 if (SymbolName.empty())
1098 return true;
1099
Hans Wennborgce69d772013-10-18 20:46:28 +00001100 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Hans Wennborg69918bc2013-10-17 01:13:02 +00001101
Hans Wennborg7ddcdc82013-10-18 02:14:40 +00001102 // Lookup the symbol variant if used.
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00001103 if (!Split.second.empty()) {
Hans Wennborg7ddcdc82013-10-18 02:14:40 +00001104 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Hans Wennborgce69d772013-10-18 20:46:28 +00001105 if (Variant != MCSymbolRefExpr::VK_Invalid) {
1106 SymbolName = Split.first;
David Peixotto8ad70b32013-12-04 22:43:20 +00001107 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
Hans Wennborgce69d772013-10-18 20:46:28 +00001108 Variant = MCSymbolRefExpr::VK_None;
1109 } else {
Saleem Abdulrasoola25e1e42014-01-26 22:29:43 +00001110 return Error(SMLoc::getFromPointer(Split.second.begin()),
1111 "invalid variant '" + Split.second + "'");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001112 }
1113 }
Daniel Dunbar55992562010-03-15 23:51:06 +00001114
Jim Grosbach6f482002015-05-18 18:43:14 +00001115 MCSymbol *Sym = getContext().getOrCreateSymbol(SymbolName);
Hans Wennborgce69d772013-10-18 20:46:28 +00001116
Daniel Dunbard20cda02009-10-16 01:34:54 +00001117 // If this is an absolute variable reference, substitute it now to preserve
1118 // semantics in the face of reassignment.
Nirav Dave05b58912018-06-05 15:13:39 +00001119 if (Sym->isVariable()) {
1120 auto V = Sym->getVariableValue(/*SetUsed*/ false);
1121 bool DoInline = isa<MCConstantExpr>(V);
1122 if (auto TV = dyn_cast<MCTargetExpr>(V))
1123 DoInline = TV->inlineAssignedExpr();
1124 if (DoInline) {
1125 if (Variant)
1126 return Error(EndLoc, "unexpected modifier on variable reference");
1127 Res = Sym->getVariableValue(/*SetUsed*/ false);
1128 return false;
1129 }
Daniel Dunbard20cda02009-10-16 01:34:54 +00001130 }
1131
1132 // Otherwise create a symbol ref.
Chad Rosier9245e122017-01-19 20:06:32 +00001133 Res = MCSymbolRefExpr::create(Sym, Variant, getContext(), FirstTokenLoc);
Chris Lattner78db3622009-06-22 05:51:26 +00001134 return false;
Daniel Dunbard20cda02009-10-16 01:34:54 +00001135 }
David Woodhousef42a6662014-02-01 16:20:54 +00001136 case AsmToken::BigNum:
1137 return TokError("literal value out of range for directive");
Kevin Enderby0510b482010-05-17 23:08:19 +00001138 case AsmToken::Integer: {
1139 SMLoc Loc = getTok().getLoc();
1140 int64_t IntVal = getTok().getIntVal();
Jim Grosbach13760bd2015-05-30 01:25:56 +00001141 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001142 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001143 Lex(); // Eat token.
Kevin Enderby0510b482010-05-17 23:08:19 +00001144 // Look for 'b' or 'f' following an Integer as a directional label
1145 if (Lexer.getKind() == AsmToken::Identifier) {
1146 StringRef IDVal = getTok().getString();
Ulrich Weigandd4120982013-06-20 16:24:17 +00001147 // Lookup the symbol variant if used.
1148 std::pair<StringRef, StringRef> Split = IDVal.split('@');
1149 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
1150 if (Split.first.size() != IDVal.size()) {
1151 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Arnaud A. de Grandmaisonc97727a2014-03-21 21:54:46 +00001152 if (Variant == MCSymbolRefExpr::VK_Invalid)
Ulrich Weigandd4120982013-06-20 16:24:17 +00001153 return TokError("invalid variant '" + Split.second + "'");
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001154 IDVal = Split.first;
Ulrich Weigandd4120982013-06-20 16:24:17 +00001155 }
Jim Grosbach4b905842013-09-20 23:08:21 +00001156 if (IDVal == "f" || IDVal == "b") {
1157 MCSymbol *Sym =
Jim Grosbach6f482002015-05-18 18:43:14 +00001158 Ctx.getDirectionalLocalSymbol(IntVal, IDVal == "b");
Jim Grosbach13760bd2015-05-30 01:25:56 +00001159 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00001160 if (IDVal == "b" && Sym->isUndefined())
Tim Northover6b3169b2016-04-11 19:50:46 +00001161 return Error(Loc, "directional label undefined");
Tim Northoverc0bef992016-04-13 19:46:54 +00001162 DirLabels.push_back(std::make_tuple(Loc, CppHashInfo, Sym));
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001163 EndLoc = Lexer.getTok().getEndLoc();
Kevin Enderby0510b482010-05-17 23:08:19 +00001164 Lex(); // Eat identifier.
1165 }
1166 }
Chris Lattner78db3622009-06-22 05:51:26 +00001167 return false;
Kevin Enderby0510b482010-05-17 23:08:19 +00001168 }
Bill Wendlingcdbf17b2011-01-25 21:26:41 +00001169 case AsmToken::Real: {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001170 APFloat RealVal(APFloat::IEEEdouble(), getTok().getString());
Bob Wilson813bdf62011-02-03 23:17:47 +00001171 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Jim Grosbach13760bd2015-05-30 01:25:56 +00001172 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001173 EndLoc = Lexer.getTok().getEndLoc();
Bill Wendlingcdbf17b2011-01-25 21:26:41 +00001174 Lex(); // Eat token.
1175 return false;
1176 }
Chris Lattner6b55cb92010-04-14 04:40:28 +00001177 case AsmToken::Dot: {
1178 // This is a '.' reference, which references the current PC. Emit a
1179 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +00001180 MCSymbol *Sym = Ctx.createTempSymbol();
Chris Lattner6b55cb92010-04-14 04:40:28 +00001181 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +00001182 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001183 EndLoc = Lexer.getTok().getEndLoc();
Chris Lattner6b55cb92010-04-14 04:40:28 +00001184 Lex(); // Eat identifier.
1185 return false;
1186 }
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001187 case AsmToken::LParen:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001188 Lex(); // Eat the '('.
Jim Grosbach4b905842013-09-20 23:08:21 +00001189 return parseParenExpr(Res, EndLoc);
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +00001190 case AsmToken::LBrac:
1191 if (!PlatformParser->HasBracketExpressions())
1192 return TokError("brackets expression not supported on this target");
1193 Lex(); // Eat the '['.
Jim Grosbach4b905842013-09-20 23:08:21 +00001194 return parseBracketExpr(Res, EndLoc);
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001195 case AsmToken::Minus:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001196 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001197 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001198 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +00001199 Res = MCUnaryExpr::createMinus(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001200 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001201 case AsmToken::Plus:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001202 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001203 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001204 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +00001205 Res = MCUnaryExpr::createPlus(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001206 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001207 case AsmToken::Tilde:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001208 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001209 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001210 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +00001211 Res = MCUnaryExpr::createNot(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001212 return false;
Daniel Sanders3feeb9c2016-08-08 11:50:25 +00001213 // MIPS unary expression operators. The lexer won't generate these tokens if
1214 // MCAsmInfo::HasMipsExpressions is false for the target.
1215 case AsmToken::PercentCall16:
1216 case AsmToken::PercentCall_Hi:
1217 case AsmToken::PercentCall_Lo:
1218 case AsmToken::PercentDtprel_Hi:
1219 case AsmToken::PercentDtprel_Lo:
1220 case AsmToken::PercentGot:
1221 case AsmToken::PercentGot_Disp:
1222 case AsmToken::PercentGot_Hi:
1223 case AsmToken::PercentGot_Lo:
1224 case AsmToken::PercentGot_Ofst:
1225 case AsmToken::PercentGot_Page:
1226 case AsmToken::PercentGottprel:
1227 case AsmToken::PercentGp_Rel:
1228 case AsmToken::PercentHi:
1229 case AsmToken::PercentHigher:
1230 case AsmToken::PercentHighest:
1231 case AsmToken::PercentLo:
1232 case AsmToken::PercentNeg:
1233 case AsmToken::PercentPcrel_Hi:
1234 case AsmToken::PercentPcrel_Lo:
1235 case AsmToken::PercentTlsgd:
1236 case AsmToken::PercentTlsldm:
1237 case AsmToken::PercentTprel_Hi:
1238 case AsmToken::PercentTprel_Lo:
1239 Lex(); // Eat the operator.
1240 if (Lexer.isNot(AsmToken::LParen))
1241 return TokError("expected '(' after operator");
1242 Lex(); // Eat the operator.
1243 if (parseExpression(Res, EndLoc))
1244 return true;
1245 if (Lexer.isNot(AsmToken::RParen))
1246 return TokError("expected ')'");
1247 Lex(); // Eat the operator.
1248 Res = getTargetParser().createTargetUnaryExpr(Res, FirstTokenKind, Ctx);
1249 return !Res;
Chris Lattner78db3622009-06-22 05:51:26 +00001250 }
1251}
Chris Lattner7fdbce72009-06-22 06:32:03 +00001252
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001253bool AsmParser::parseExpression(const MCExpr *&Res) {
Chris Lattnere17df0b2010-01-15 19:39:23 +00001254 SMLoc EndLoc;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001255 return parseExpression(Res, EndLoc);
Chris Lattner528d00b2010-01-15 19:28:38 +00001256}
1257
Daniel Dunbar55f16672010-09-17 02:47:07 +00001258const MCExpr *
Jim Grosbach4b905842013-09-20 23:08:21 +00001259AsmParser::applyModifierToExpr(const MCExpr *E,
Daniel Dunbar55f16672010-09-17 02:47:07 +00001260 MCSymbolRefExpr::VariantKind Variant) {
Joerg Sonnenbergerb822af42013-08-27 20:23:19 +00001261 // Ask the target implementation about this expression first.
1262 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
1263 if (NewE)
1264 return NewE;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001265 // Recurse over the given expression, rebuilding it to apply the given variant
1266 // if there is exactly one symbol.
1267 switch (E->getKind()) {
1268 case MCExpr::Target:
1269 case MCExpr::Constant:
Craig Topper353eda42014-04-24 06:44:33 +00001270 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001271
1272 case MCExpr::SymbolRef: {
1273 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
1274
1275 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001276 TokError("invalid variant on expression '" + getTok().getIdentifier() +
1277 "' (already modified)");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001278 return E;
1279 }
1280
Jim Grosbach13760bd2015-05-30 01:25:56 +00001281 return MCSymbolRefExpr::create(&SRE->getSymbol(), Variant, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001282 }
1283
1284 case MCExpr::Unary: {
1285 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +00001286 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001287 if (!Sub)
Craig Topper353eda42014-04-24 06:44:33 +00001288 return nullptr;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001289 return MCUnaryExpr::create(UE->getOpcode(), Sub, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001290 }
1291
1292 case MCExpr::Binary: {
1293 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +00001294 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
1295 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001296
1297 if (!LHS && !RHS)
Craig Topper353eda42014-04-24 06:44:33 +00001298 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001299
Jim Grosbach4b905842013-09-20 23:08:21 +00001300 if (!LHS)
1301 LHS = BE->getLHS();
1302 if (!RHS)
1303 RHS = BE->getRHS();
Daniel Dunbar55f16672010-09-17 02:47:07 +00001304
Jim Grosbach13760bd2015-05-30 01:25:56 +00001305 return MCBinaryExpr::create(BE->getOpcode(), LHS, RHS, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001306 }
1307 }
Daniel Dunbarbaad46c2010-09-17 16:34:24 +00001308
Craig Toppera2886c22012-02-07 05:05:23 +00001309 llvm_unreachable("Invalid expression kind!");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001310}
1311
Michael Zuckerman763e60e2017-05-04 10:37:00 +00001312/// This function checks if the next token is <string> type or arithmetic.
1313/// string that begin with character '<' must end with character '>'.
1314/// otherwise it is arithmetics.
1315/// If the function returns a 'true' value,
1316/// the End argument will be filled with the last location pointed to the '>'
1317/// character.
1318
Sam Cleggf009da22018-04-19 22:00:53 +00001319/// There is a gap between the AltMacro's documentation and the single quote implementation.
Michael Zuckerman763e60e2017-05-04 10:37:00 +00001320/// GCC does not fully support this feature and so we will not support it.
1321/// TODO: Adding single quote as a string.
1322bool AsmParser::isAltmacroString(SMLoc &StrLoc, SMLoc &EndLoc) {
1323 assert((StrLoc.getPointer() != NULL) &&
1324 "Argument to the function cannot be a NULL value");
1325 const char *CharPtr = StrLoc.getPointer();
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00001326 while ((*CharPtr != '>') && (*CharPtr != '\n') && (*CharPtr != '\r') &&
1327 (*CharPtr != '\0')) {
1328 if (*CharPtr == '!')
1329 CharPtr++;
Michael Zuckerman763e60e2017-05-04 10:37:00 +00001330 CharPtr++;
1331 }
1332 if (*CharPtr == '>') {
1333 EndLoc = StrLoc.getFromPointer(CharPtr + 1);
1334 return true;
1335 }
1336 return false;
1337}
1338
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001339/// creating a string without the escape characters '!'.
Michael Zuckerman1f1a9122017-05-10 13:08:11 +00001340void AsmParser::altMacroString(StringRef AltMacroStr,std::string &Res) {
Michael Zuckermanff298792017-05-10 14:00:57 +00001341 for (size_t Pos = 0; Pos < AltMacroStr.size(); Pos++) {
Michael Zuckerman1f1a9122017-05-10 13:08:11 +00001342 if (AltMacroStr[Pos] == '!')
1343 Pos++;
1344 Res += AltMacroStr[Pos];
1345 }
1346}
1347
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001348/// Parse an expression and return it.
Michael J. Spencer530ce852010-10-09 11:00:50 +00001349///
Jim Grosbachbd164242011-08-20 16:24:13 +00001350/// expr ::= expr &&,|| expr -> lowest.
1351/// expr ::= expr |,^,&,! expr
1352/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1353/// expr ::= expr <<,>> expr
1354/// expr ::= expr +,- expr
1355/// expr ::= expr *,/,% expr -> highest.
Chris Lattner7fdbce72009-06-22 06:32:03 +00001356/// expr ::= primaryexpr
1357///
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001358bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001359 // Parse the expression.
Craig Topper353eda42014-04-24 06:44:33 +00001360 Res = nullptr;
Jim Grosbach4b905842013-09-20 23:08:21 +00001361 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001362 return true;
1363
Daniel Dunbar55f16672010-09-17 02:47:07 +00001364 // As a special case, we support 'a op b @ modifier' by rewriting the
1365 // expression to include the modifier. This is inefficient, but in general we
1366 // expect users to use 'a@modifier op b'.
1367 if (Lexer.getKind() == AsmToken::At) {
1368 Lex();
1369
1370 if (Lexer.isNot(AsmToken::Identifier))
1371 return TokError("unexpected symbol modifier following '@'");
1372
1373 MCSymbolRefExpr::VariantKind Variant =
Jim Grosbach4b905842013-09-20 23:08:21 +00001374 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001375 if (Variant == MCSymbolRefExpr::VK_Invalid)
1376 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1377
Jim Grosbach4b905842013-09-20 23:08:21 +00001378 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001379 if (!ModifiedRes) {
1380 return TokError("invalid modifier '" + getTok().getIdentifier() +
1381 "' (no symbols present)");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001382 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001383
Daniel Dunbar55f16672010-09-17 02:47:07 +00001384 Res = ModifiedRes;
1385 Lex();
1386 }
1387
Nirav Dave6c0665e2018-04-30 19:22:40 +00001388 // Try to constant fold it up front, if possible. Do not exploit
1389 // assembler here.
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001390 int64_t Value;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001391 if (Res->evaluateAsAbsolute(Value))
1392 Res = MCConstantExpr::create(Value, getContext());
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001393
1394 return false;
Chris Lattner7fdbce72009-06-22 06:32:03 +00001395}
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001396
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001397bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Craig Topper353eda42014-04-24 06:44:33 +00001398 Res = nullptr;
Jim Grosbach4b905842013-09-20 23:08:21 +00001399 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
Daniel Dunbar7c82d562009-08-31 08:08:17 +00001400}
1401
Toma Tabacu7bc44dc2015-06-25 09:52:02 +00001402bool AsmParser::parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
1403 SMLoc &EndLoc) {
1404 if (parseParenExpr(Res, EndLoc))
1405 return true;
1406
1407 for (; ParenDepth > 0; --ParenDepth) {
1408 if (parseBinOpRHS(1, Res, EndLoc))
1409 return true;
1410
1411 // We don't Lex() the last RParen.
1412 // This is the same behavior as parseParenExpression().
1413 if (ParenDepth - 1 > 0) {
Nirav Davea645433c2016-07-18 15:24:03 +00001414 EndLoc = getTok().getEndLoc();
1415 if (parseToken(AsmToken::RParen,
1416 "expected ')' in parentheses expression"))
1417 return true;
Toma Tabacu7bc44dc2015-06-25 09:52:02 +00001418 }
1419 }
1420 return false;
1421}
1422
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001423bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
Daniel Dunbarf3636452009-08-31 08:07:22 +00001424 const MCExpr *Expr;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001425
Daniel Dunbar75630b32009-06-30 02:10:03 +00001426 SMLoc StartLoc = Lexer.getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001427 if (parseExpression(Expr))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001428 return true;
1429
Nirav Dave6c0665e2018-04-30 19:22:40 +00001430 if (!Expr->evaluateAsAbsolute(Res, getStreamer().getAssemblerPtr()))
Daniel Dunbar75630b32009-06-30 02:10:03 +00001431 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001432
1433 return false;
1434}
1435
David Majnemer0993e0b2015-10-26 03:15:34 +00001436static unsigned getDarwinBinOpPrecedence(AsmToken::TokenKind K,
1437 MCBinaryExpr::Opcode &Kind,
1438 bool ShouldUseLogicalShr) {
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001439 switch (K) {
Daniel Dunbar940cda22009-08-31 08:07:44 +00001440 default:
Jim Grosbach4b905842013-09-20 23:08:21 +00001441 return 0; // not a binop.
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001442
Jim Grosbach4b905842013-09-20 23:08:21 +00001443 // Lowest Precedence: &&, ||
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001444 case AsmToken::AmpAmp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001445 Kind = MCBinaryExpr::LAnd;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001446 return 1;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001447 case AsmToken::PipePipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001448 Kind = MCBinaryExpr::LOr;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001449 return 1;
1450
Jim Grosbach4b905842013-09-20 23:08:21 +00001451 // Low Precedence: |, &, ^
1452 //
1453 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001454 case AsmToken::Pipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001455 Kind = MCBinaryExpr::Or;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001456 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001457 case AsmToken::Caret:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001458 Kind = MCBinaryExpr::Xor;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001459 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001460 case AsmToken::Amp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001461 Kind = MCBinaryExpr::And;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001462 return 2;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001463
Jim Grosbach4b905842013-09-20 23:08:21 +00001464 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001465 case AsmToken::EqualEqual:
1466 Kind = MCBinaryExpr::EQ;
1467 return 3;
1468 case AsmToken::ExclaimEqual:
1469 case AsmToken::LessGreater:
1470 Kind = MCBinaryExpr::NE;
1471 return 3;
1472 case AsmToken::Less:
1473 Kind = MCBinaryExpr::LT;
1474 return 3;
1475 case AsmToken::LessEqual:
1476 Kind = MCBinaryExpr::LTE;
1477 return 3;
1478 case AsmToken::Greater:
1479 Kind = MCBinaryExpr::GT;
1480 return 3;
1481 case AsmToken::GreaterEqual:
1482 Kind = MCBinaryExpr::GTE;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001483 return 3;
1484
Jim Grosbach4b905842013-09-20 23:08:21 +00001485 // Intermediate Precedence: <<, >>
Jim Grosbachbd164242011-08-20 16:24:13 +00001486 case AsmToken::LessLess:
1487 Kind = MCBinaryExpr::Shl;
1488 return 4;
1489 case AsmToken::GreaterGreater:
David Majnemer0993e0b2015-10-26 03:15:34 +00001490 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
Jim Grosbachbd164242011-08-20 16:24:13 +00001491 return 4;
1492
Jim Grosbach4b905842013-09-20 23:08:21 +00001493 // High Intermediate Precedence: +, -
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001494 case AsmToken::Plus:
1495 Kind = MCBinaryExpr::Add;
Jim Grosbachbd164242011-08-20 16:24:13 +00001496 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001497 case AsmToken::Minus:
1498 Kind = MCBinaryExpr::Sub;
Jim Grosbachbd164242011-08-20 16:24:13 +00001499 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001500
Jim Grosbach4b905842013-09-20 23:08:21 +00001501 // Highest Precedence: *, /, %
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001502 case AsmToken::Star:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001503 Kind = MCBinaryExpr::Mul;
Jim Grosbachbd164242011-08-20 16:24:13 +00001504 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001505 case AsmToken::Slash:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001506 Kind = MCBinaryExpr::Div;
Jim Grosbachbd164242011-08-20 16:24:13 +00001507 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001508 case AsmToken::Percent:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001509 Kind = MCBinaryExpr::Mod;
Jim Grosbachbd164242011-08-20 16:24:13 +00001510 return 6;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001511 }
1512}
1513
David Majnemer0993e0b2015-10-26 03:15:34 +00001514static unsigned getGNUBinOpPrecedence(AsmToken::TokenKind K,
1515 MCBinaryExpr::Opcode &Kind,
1516 bool ShouldUseLogicalShr) {
1517 switch (K) {
1518 default:
1519 return 0; // not a binop.
1520
1521 // Lowest Precedence: &&, ||
1522 case AsmToken::AmpAmp:
1523 Kind = MCBinaryExpr::LAnd;
1524 return 2;
1525 case AsmToken::PipePipe:
1526 Kind = MCBinaryExpr::LOr;
1527 return 1;
1528
1529 // Low Precedence: ==, !=, <>, <, <=, >, >=
1530 case AsmToken::EqualEqual:
1531 Kind = MCBinaryExpr::EQ;
1532 return 3;
1533 case AsmToken::ExclaimEqual:
1534 case AsmToken::LessGreater:
1535 Kind = MCBinaryExpr::NE;
1536 return 3;
1537 case AsmToken::Less:
1538 Kind = MCBinaryExpr::LT;
1539 return 3;
1540 case AsmToken::LessEqual:
1541 Kind = MCBinaryExpr::LTE;
1542 return 3;
1543 case AsmToken::Greater:
1544 Kind = MCBinaryExpr::GT;
1545 return 3;
1546 case AsmToken::GreaterEqual:
1547 Kind = MCBinaryExpr::GTE;
1548 return 3;
1549
1550 // Low Intermediate Precedence: +, -
1551 case AsmToken::Plus:
1552 Kind = MCBinaryExpr::Add;
1553 return 4;
1554 case AsmToken::Minus:
1555 Kind = MCBinaryExpr::Sub;
1556 return 4;
1557
1558 // High Intermediate Precedence: |, &, ^
1559 //
1560 // FIXME: gas seems to support '!' as an infix operator?
1561 case AsmToken::Pipe:
1562 Kind = MCBinaryExpr::Or;
1563 return 5;
1564 case AsmToken::Caret:
1565 Kind = MCBinaryExpr::Xor;
1566 return 5;
1567 case AsmToken::Amp:
1568 Kind = MCBinaryExpr::And;
1569 return 5;
1570
1571 // Highest Precedence: *, /, %, <<, >>
1572 case AsmToken::Star:
1573 Kind = MCBinaryExpr::Mul;
1574 return 6;
1575 case AsmToken::Slash:
1576 Kind = MCBinaryExpr::Div;
1577 return 6;
1578 case AsmToken::Percent:
1579 Kind = MCBinaryExpr::Mod;
1580 return 6;
1581 case AsmToken::LessLess:
1582 Kind = MCBinaryExpr::Shl;
1583 return 6;
1584 case AsmToken::GreaterGreater:
1585 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1586 return 6;
1587 }
1588}
1589
1590unsigned AsmParser::getBinOpPrecedence(AsmToken::TokenKind K,
1591 MCBinaryExpr::Opcode &Kind) {
1592 bool ShouldUseLogicalShr = MAI.shouldUseLogicalShr();
1593 return IsDarwin ? getDarwinBinOpPrecedence(K, Kind, ShouldUseLogicalShr)
1594 : getGNUBinOpPrecedence(K, Kind, ShouldUseLogicalShr);
1595}
1596
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001597/// Parse all binary operators with precedence >= 'Precedence'.
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001598/// Res contains the LHS of the expression on input.
Jim Grosbach4b905842013-09-20 23:08:21 +00001599bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
Chris Lattner528d00b2010-01-15 19:28:38 +00001600 SMLoc &EndLoc) {
Chad Rosier9245e122017-01-19 20:06:32 +00001601 SMLoc StartLoc = Lexer.getLoc();
Eugene Zelenko33d7b762016-08-23 17:14:32 +00001602 while (true) {
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001603 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001604 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001605
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001606 // If the next token is lower precedence than we are allowed to eat, return
1607 // successfully with what we ate already.
1608 if (TokPrec < Precedence)
1609 return false;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001610
Sean Callanan686ed8d2010-01-19 20:22:31 +00001611 Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +00001612
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001613 // Eat the next primary expression.
Daniel Dunbarf3636452009-08-31 08:07:22 +00001614 const MCExpr *RHS;
Jim Grosbach4b905842013-09-20 23:08:21 +00001615 if (parsePrimaryExpr(RHS, EndLoc))
1616 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001617
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001618 // If BinOp binds less tightly with RHS than the operator after RHS, let
1619 // the pending operator take RHS as its LHS.
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001620 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001621 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Jim Grosbach4b905842013-09-20 23:08:21 +00001622 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1623 return true;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001624
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001625 // Merge LHS and RHS according to operator.
Chad Rosier9245e122017-01-19 20:06:32 +00001626 Res = MCBinaryExpr::create(Kind, Res, RHS, getContext(), StartLoc);
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001627 }
1628}
1629
Chris Lattner36e02122009-06-21 20:54:55 +00001630/// ParseStatement:
1631/// ::= EndOfStatement
Chris Lattnere5074c42009-06-22 01:29:09 +00001632/// ::= Label* Directive ...Operands... EndOfStatement
1633/// ::= Label* Identifier OperandList* EndOfStatement
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001634bool AsmParser::parseStatement(ParseStatementInfo &Info,
1635 MCAsmParserSemaCallback *SI) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001636 assert(!hasPendingError() && "parseStatement started with pending error");
Nirav Davefd910412016-06-17 16:06:17 +00001637 // Eat initial spaces and comments
1638 while (Lexer.is(AsmToken::Space))
1639 Lex();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001640 if (Lexer.is(AsmToken::EndOfStatement)) {
Nirav Davefd910412016-06-17 16:06:17 +00001641 // if this is a line comment we can drop it safely
Nirav Dave670109d2017-06-09 14:04:03 +00001642 if (getTok().getString().empty() || getTok().getString().front() == '\r' ||
Nirav Davefd910412016-06-17 16:06:17 +00001643 getTok().getString().front() == '\n')
1644 Out.AddBlankLine();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001645 Lex();
Chris Lattner36e02122009-06-21 20:54:55 +00001646 return false;
Chris Lattner36e02122009-06-21 20:54:55 +00001647 }
Nirav Davefd910412016-06-17 16:06:17 +00001648 // Statements always start with an identifier.
Sean Callanan936b0d32010-01-19 21:44:56 +00001649 AsmToken ID = getTok();
Daniel Dunbaree4465c2009-07-28 16:38:40 +00001650 SMLoc IDLoc = ID.getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001651 StringRef IDVal;
Kevin Enderby0510b482010-05-17 23:08:19 +00001652 int64_t LocalLabelVal = -1;
Nirav Davefd910412016-06-17 16:06:17 +00001653 if (Lexer.is(AsmToken::HashDirective))
Jim Grosbach4b905842013-09-20 23:08:21 +00001654 return parseCppHashLineFilenameComment(IDLoc);
Kevin Enderbyfa3c6f12010-12-24 00:12:02 +00001655 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderby0510b482010-05-17 23:08:19 +00001656 if (Lexer.is(AsmToken::Integer)) {
1657 LocalLabelVal = getTok().getIntVal();
1658 if (LocalLabelVal < 0) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001659 if (!TheCondState.Ignore) {
1660 Lex(); // always eat a token
1661 return Error(IDLoc, "unexpected token at start of statement");
1662 }
Kevin Enderby0510b482010-05-17 23:08:19 +00001663 IDVal = "";
Eli Bendersky88024712013-01-16 19:32:36 +00001664 } else {
Kevin Enderby0510b482010-05-17 23:08:19 +00001665 IDVal = getTok().getString();
1666 Lex(); // Consume the integer token to be used as an identifier token.
1667 if (Lexer.getKind() != AsmToken::Colon) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001668 if (!TheCondState.Ignore) {
1669 Lex(); // always eat a token
1670 return Error(IDLoc, "unexpected token at start of statement");
1671 }
Kevin Enderby0510b482010-05-17 23:08:19 +00001672 }
1673 }
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001674 } else if (Lexer.is(AsmToken::Dot)) {
1675 // Treat '.' as a valid identifier in this context.
1676 Lex();
1677 IDVal = ".";
Colin LeMahieu8a0453e2015-11-09 00:31:07 +00001678 } else if (Lexer.is(AsmToken::LCurly)) {
1679 // Treat '{' as a valid identifier in this context.
1680 Lex();
1681 IDVal = "{";
1682
1683 } else if (Lexer.is(AsmToken::RCurly)) {
1684 // Treat '}' as a valid identifier in this context.
1685 Lex();
1686 IDVal = "}";
Yonghong Song06ff6552017-09-12 17:55:23 +00001687 } else if (Lexer.is(AsmToken::Star) &&
1688 getTargetParser().starIsStartOfStatement()) {
1689 // Accept '*' as a valid start of statement.
1690 Lex();
1691 IDVal = "*";
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001692 } else if (parseIdentifier(IDVal)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001693 if (!TheCondState.Ignore) {
1694 Lex(); // always eat a token
1695 return Error(IDLoc, "unexpected token at start of statement");
1696 }
Chris Lattner926885c2010-04-17 18:14:27 +00001697 IDVal = "";
1698 }
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001699
Chris Lattner926885c2010-04-17 18:14:27 +00001700 // Handle conditional assembly here before checking for skipping. We
1701 // have to do this so that .endif isn't skipped in a ".if 0" block for
1702 // example.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001703 StringMap<DirectiveKind>::const_iterator DirKindIt =
Jim Grosbach4b905842013-09-20 23:08:21 +00001704 DirectiveKindMap.find(IDVal);
1705 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1706 ? DK_NO_DIRECTIVE
1707 : DirKindIt->getValue();
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001708 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001709 default:
1710 break;
1711 case DK_IF:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001712 case DK_IFEQ:
1713 case DK_IFGE:
1714 case DK_IFGT:
1715 case DK_IFLE:
1716 case DK_IFLT:
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00001717 case DK_IFNE:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001718 return parseDirectiveIf(IDLoc, DirKind);
Jim Grosbach4b905842013-09-20 23:08:21 +00001719 case DK_IFB:
1720 return parseDirectiveIfb(IDLoc, true);
1721 case DK_IFNB:
1722 return parseDirectiveIfb(IDLoc, false);
1723 case DK_IFC:
1724 return parseDirectiveIfc(IDLoc, true);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00001725 case DK_IFEQS:
Sid Manning51c35602015-03-18 14:20:54 +00001726 return parseDirectiveIfeqs(IDLoc, true);
Jim Grosbach4b905842013-09-20 23:08:21 +00001727 case DK_IFNC:
1728 return parseDirectiveIfc(IDLoc, false);
Sid Manning51c35602015-03-18 14:20:54 +00001729 case DK_IFNES:
1730 return parseDirectiveIfeqs(IDLoc, false);
Jim Grosbach4b905842013-09-20 23:08:21 +00001731 case DK_IFDEF:
1732 return parseDirectiveIfdef(IDLoc, true);
1733 case DK_IFNDEF:
1734 case DK_IFNOTDEF:
1735 return parseDirectiveIfdef(IDLoc, false);
1736 case DK_ELSEIF:
1737 return parseDirectiveElseIf(IDLoc);
1738 case DK_ELSE:
1739 return parseDirectiveElse(IDLoc);
1740 case DK_ENDIF:
1741 return parseDirectiveEndIf(IDLoc);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001742 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001743
Eli Bendersky88024712013-01-16 19:32:36 +00001744 // Ignore the statement if in the middle of inactive conditional
1745 // (e.g. ".if 0").
Chad Rosiereda70b32012-10-20 00:47:08 +00001746 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001747 eatToEndOfStatement();
Chris Lattner926885c2010-04-17 18:14:27 +00001748 return false;
1749 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001750
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001751 // FIXME: Recurse on local labels?
1752
1753 // See what kind of statement we have.
1754 switch (Lexer.getKind()) {
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001755 case AsmToken::Colon: {
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001756 if (!getTargetParser().isLabel(ID))
1757 break;
Nirav Davef43cc9f2016-10-10 15:24:54 +00001758 if (checkForValidSection())
1759 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00001760
Chris Lattner36e02122009-06-21 20:54:55 +00001761 // identifier ':' -> Label.
Sean Callanan686ed8d2010-01-19 20:22:31 +00001762 Lex();
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001763
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001764 // Diagnose attempt to use '.' as a label.
1765 if (IDVal == ".")
1766 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1767
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001768 // Diagnose attempt to use a variable as a label.
1769 //
1770 // FIXME: Diagnostics. Note the location of the definition as a label.
1771 // FIXME: This doesn't diagnose assignment to a symbol which has been
1772 // implicitly marked as external.
Kevin Enderby0510b482010-05-17 23:08:19 +00001773 MCSymbol *Sym;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001774 if (LocalLabelVal == -1) {
1775 if (ParsingInlineAsm && SI) {
Nico Weber67e715f2015-06-19 23:43:47 +00001776 StringRef RewrittenLabel =
1777 SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true);
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00001778 assert(!RewrittenLabel.empty() &&
Nico Weber67e715f2015-06-19 23:43:47 +00001779 "We should have an internal name here.");
Craig Topper7d5b2312015-10-10 05:25:02 +00001780 Info.AsmRewrites->emplace_back(AOK_Label, IDLoc, IDVal.size(),
1781 RewrittenLabel);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001782 IDVal = RewrittenLabel;
1783 }
Jim Grosbach6f482002015-05-18 18:43:14 +00001784 Sym = getContext().getOrCreateSymbol(IDVal);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001785 } else
Jim Grosbach6f482002015-05-18 18:43:14 +00001786 Sym = Ctx.createDirectionalLocalSymbol(LocalLabelVal);
Nirav Dave9263ae32016-08-02 19:17:54 +00001787 // End of Labels should be treated as end of line for lexing
1788 // purposes but that information is not available to the Lexer who
1789 // does not understand Labels. This may cause us to see a Hash
1790 // here instead of a preprocessor line comment.
1791 if (getTok().is(AsmToken::Hash)) {
1792 StringRef CommentStr = parseStringToEndOfStatement();
1793 Lexer.Lex();
1794 Lexer.UnLex(AsmToken(AsmToken::EndOfStatement, CommentStr));
1795 }
1796
Nirav Dave8ea792d2016-07-13 14:03:12 +00001797 // Consume any end of statement token, if present, to avoid spurious
1798 // AddBlankLine calls().
1799 if (getTok().is(AsmToken::EndOfStatement)) {
1800 Lex();
1801 }
1802
Daniel Dunbare73b2672009-08-26 22:13:22 +00001803 // Emit the label.
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +00001804 if (!getTargetParser().isParsingInlineAsm())
Rafael Espindolabe991572017-02-10 15:13:12 +00001805 Out.EmitLabel(Sym, IDLoc);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001806
Kevin Enderbye7739d42011-12-09 18:09:40 +00001807 // If we are generating dwarf for assembly source files then gather the
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001808 // info to make a dwarf label entry for this label if needed.
Paul Robinson938d9a02018-03-22 15:48:01 +00001809 if (enabledGenDwarfForAssembly())
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001810 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1811 IDLoc);
Kevin Enderbye7739d42011-12-09 18:09:40 +00001812
Tim Northover1744d0a2013-10-25 12:49:50 +00001813 getTargetParser().onLabelParsed(Sym);
1814
Eli Friedman0f4871d2012-10-22 23:58:19 +00001815 return false;
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001816 }
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001817
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001818 case AsmToken::Equal:
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001819 if (!getTargetParser().equalIsAsmAssignment())
1820 break;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001821 // identifier '=' ... -> assignment statement
Sean Callanan686ed8d2010-01-19 20:22:31 +00001822 Lex();
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001823
Nirav Dave05b58912018-06-05 15:13:39 +00001824 return parseAssignment(IDVal, true, /*NoDeadStrip*/ false, /*AllowExtendedExpr*/true);
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001825
1826 default: // Normal instruction or directive.
1827 break;
Chris Lattner36e02122009-06-21 20:54:55 +00001828 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001829
1830 // If macros are enabled, check to see if this is a macro instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00001831 if (areMacrosEnabled())
Rafael Espindola22c38a02018-02-14 16:34:27 +00001832 if (const MCAsmMacro *M = getContext().lookupMacro(IDVal)) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001833 return handleMacroEntry(M, IDLoc);
Eli Bendersky38274122013-01-14 23:22:36 +00001834 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001835
Michael J. Spencer530ce852010-10-09 11:00:50 +00001836 // Otherwise, we have a normal instruction or directive.
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001837
Eli Bendersky17233942013-01-15 22:59:42 +00001838 // Directives start with "."
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001839 if (IDVal[0] == '.' && IDVal != ".") {
Eli Bendersky17233942013-01-15 22:59:42 +00001840 // There are several entities interested in parsing directives:
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001841 //
Eli Bendersky17233942013-01-15 22:59:42 +00001842 // 1. The target-specific assembly parser. Some directives are target
1843 // specific or may potentially behave differently on certain targets.
1844 // 2. Asm parser extensions. For example, platform-specific parsers
1845 // (like the ELF parser) register themselves as extensions.
1846 // 3. The generic directive parser implemented by this class. These are
1847 // all the directives that behave in a target and platform independent
1848 // manner, or at least have a default behavior that's shared between
1849 // all targets and platforms.
Akira Hatanakad3590752012-07-05 19:09:33 +00001850
Oliver Stannard21718282016-07-26 14:19:47 +00001851 getTargetParser().flushPendingInstructions(getStreamer());
1852
Nirav Dave2364748a2016-09-16 18:30:20 +00001853 SMLoc StartTokLoc = getTok().getLoc();
1854 bool TPDirectiveReturn = getTargetParser().ParseDirective(ID);
1855
1856 if (hasPendingError())
1857 return true;
1858 // Currently the return value should be true if we are
1859 // uninterested but as this is at odds with the standard parsing
1860 // convention (return true = error) we have instances of a parsed
1861 // directive that fails returning true as an error. Catch these
1862 // cases as best as possible errors here.
1863 if (TPDirectiveReturn && StartTokLoc != getTok().getLoc())
1864 return true;
1865 // Return if we did some parsing or believe we succeeded.
1866 if (!TPDirectiveReturn || StartTokLoc != getTok().getLoc())
Akira Hatanakad3590752012-07-05 19:09:33 +00001867 return false;
1868
Alp Tokercb402912014-01-24 17:20:08 +00001869 // Next, check the extension directive map to see if any extension has
Eli Bendersky17233942013-01-15 22:59:42 +00001870 // registered itself to parse this directive.
Jim Grosbach4b905842013-09-20 23:08:21 +00001871 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1872 ExtensionDirectiveMap.lookup(IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +00001873 if (Handler.first)
1874 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1875
1876 // Finally, if no one else is interested in this directive, it must be
1877 // generic and familiar to this class.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001878 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001879 default:
1880 break;
1881 case DK_SET:
1882 case DK_EQU:
1883 return parseDirectiveSet(IDVal, true);
1884 case DK_EQUIV:
1885 return parseDirectiveSet(IDVal, false);
1886 case DK_ASCII:
1887 return parseDirectiveAscii(IDVal, false);
1888 case DK_ASCIZ:
1889 case DK_STRING:
1890 return parseDirectiveAscii(IDVal, true);
1891 case DK_BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001892 case DK_DC_B:
1893 return parseDirectiveValue(IDVal, 1);
1894 case DK_DC:
1895 case DK_DC_W:
Jim Grosbach4b905842013-09-20 23:08:21 +00001896 case DK_SHORT:
1897 case DK_VALUE:
1898 case DK_2BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001899 return parseDirectiveValue(IDVal, 2);
Jim Grosbach4b905842013-09-20 23:08:21 +00001900 case DK_LONG:
1901 case DK_INT:
1902 case DK_4BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001903 case DK_DC_L:
1904 return parseDirectiveValue(IDVal, 4);
Jim Grosbach4b905842013-09-20 23:08:21 +00001905 case DK_QUAD:
1906 case DK_8BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001907 return parseDirectiveValue(IDVal, 8);
1908 case DK_DC_A:
Konstantin Zhuravlyovdc77b2e2017-04-17 17:41:25 +00001909 return parseDirectiveValue(
1910 IDVal, getContext().getAsmInfo()->getCodePointerSize());
David Woodhoused6de0d92014-02-01 16:20:59 +00001911 case DK_OCTA:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001912 return parseDirectiveOctaValue(IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001913 case DK_SINGLE:
1914 case DK_FLOAT:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001915 case DK_DC_S:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001916 return parseDirectiveRealValue(IDVal, APFloat::IEEEsingle());
Jim Grosbach4b905842013-09-20 23:08:21 +00001917 case DK_DOUBLE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001918 case DK_DC_D:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001919 return parseDirectiveRealValue(IDVal, APFloat::IEEEdouble());
Jim Grosbach4b905842013-09-20 23:08:21 +00001920 case DK_ALIGN: {
1921 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1922 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1923 }
1924 case DK_ALIGN32: {
1925 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1926 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1927 }
1928 case DK_BALIGN:
1929 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1930 case DK_BALIGNW:
1931 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1932 case DK_BALIGNL:
1933 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1934 case DK_P2ALIGN:
1935 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1936 case DK_P2ALIGNW:
1937 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1938 case DK_P2ALIGNL:
1939 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1940 case DK_ORG:
1941 return parseDirectiveOrg();
1942 case DK_FILL:
1943 return parseDirectiveFill();
1944 case DK_ZERO:
1945 return parseDirectiveZero();
1946 case DK_EXTERN:
1947 eatToEndOfStatement(); // .extern is the default, ignore it.
1948 return false;
1949 case DK_GLOBL:
1950 case DK_GLOBAL:
1951 return parseDirectiveSymbolAttribute(MCSA_Global);
1952 case DK_LAZY_REFERENCE:
1953 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1954 case DK_NO_DEAD_STRIP:
1955 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1956 case DK_SYMBOL_RESOLVER:
1957 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1958 case DK_PRIVATE_EXTERN:
1959 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1960 case DK_REFERENCE:
1961 return parseDirectiveSymbolAttribute(MCSA_Reference);
1962 case DK_WEAK_DEFINITION:
1963 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1964 case DK_WEAK_REFERENCE:
1965 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1966 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1967 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1968 case DK_COMM:
1969 case DK_COMMON:
1970 return parseDirectiveComm(/*IsLocal=*/false);
1971 case DK_LCOMM:
1972 return parseDirectiveComm(/*IsLocal=*/true);
1973 case DK_ABORT:
1974 return parseDirectiveAbort();
1975 case DK_INCLUDE:
1976 return parseDirectiveInclude();
1977 case DK_INCBIN:
1978 return parseDirectiveIncbin();
1979 case DK_CODE16:
1980 case DK_CODE16GCC:
Nirav Davefd910412016-06-17 16:06:17 +00001981 return TokError(Twine(IDVal) +
1982 " not currently supported for this target");
Jim Grosbach4b905842013-09-20 23:08:21 +00001983 case DK_REPT:
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00001984 return parseDirectiveRept(IDLoc, IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001985 case DK_IRP:
1986 return parseDirectiveIrp(IDLoc);
1987 case DK_IRPC:
1988 return parseDirectiveIrpc(IDLoc);
1989 case DK_ENDR:
1990 return parseDirectiveEndr(IDLoc);
1991 case DK_BUNDLE_ALIGN_MODE:
1992 return parseDirectiveBundleAlignMode();
1993 case DK_BUNDLE_LOCK:
1994 return parseDirectiveBundleLock();
1995 case DK_BUNDLE_UNLOCK:
1996 return parseDirectiveBundleUnlock();
1997 case DK_SLEB128:
1998 return parseDirectiveLEB128(true);
1999 case DK_ULEB128:
2000 return parseDirectiveLEB128(false);
2001 case DK_SPACE:
2002 case DK_SKIP:
2003 return parseDirectiveSpace(IDVal);
2004 case DK_FILE:
2005 return parseDirectiveFile(IDLoc);
2006 case DK_LINE:
2007 return parseDirectiveLine();
2008 case DK_LOC:
2009 return parseDirectiveLoc();
2010 case DK_STABS:
2011 return parseDirectiveStabs();
Reid Kleckner2214ed82016-01-29 00:49:42 +00002012 case DK_CV_FILE:
2013 return parseDirectiveCVFile();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00002014 case DK_CV_FUNC_ID:
2015 return parseDirectiveCVFuncId();
2016 case DK_CV_INLINE_SITE_ID:
2017 return parseDirectiveCVInlineSiteId();
Reid Kleckner2214ed82016-01-29 00:49:42 +00002018 case DK_CV_LOC:
2019 return parseDirectiveCVLoc();
2020 case DK_CV_LINETABLE:
2021 return parseDirectiveCVLinetable();
David Majnemer6fcbd7e2016-01-29 19:24:12 +00002022 case DK_CV_INLINE_LINETABLE:
2023 return parseDirectiveCVInlineLinetable();
David Majnemer408b5e62016-02-05 01:55:49 +00002024 case DK_CV_DEF_RANGE:
2025 return parseDirectiveCVDefRange();
Reid Kleckner2214ed82016-01-29 00:49:42 +00002026 case DK_CV_STRINGTABLE:
2027 return parseDirectiveCVStringTable();
2028 case DK_CV_FILECHECKSUMS:
2029 return parseDirectiveCVFileChecksums();
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00002030 case DK_CV_FILECHECKSUM_OFFSET:
2031 return parseDirectiveCVFileChecksumOffset();
Reid Kleckner9cdd4df2017-10-11 21:24:33 +00002032 case DK_CV_FPO_DATA:
2033 return parseDirectiveCVFPOData();
Jim Grosbach4b905842013-09-20 23:08:21 +00002034 case DK_CFI_SECTIONS:
2035 return parseDirectiveCFISections();
2036 case DK_CFI_STARTPROC:
2037 return parseDirectiveCFIStartProc();
2038 case DK_CFI_ENDPROC:
2039 return parseDirectiveCFIEndProc();
2040 case DK_CFI_DEF_CFA:
2041 return parseDirectiveCFIDefCfa(IDLoc);
2042 case DK_CFI_DEF_CFA_OFFSET:
2043 return parseDirectiveCFIDefCfaOffset();
2044 case DK_CFI_ADJUST_CFA_OFFSET:
2045 return parseDirectiveCFIAdjustCfaOffset();
2046 case DK_CFI_DEF_CFA_REGISTER:
2047 return parseDirectiveCFIDefCfaRegister(IDLoc);
2048 case DK_CFI_OFFSET:
2049 return parseDirectiveCFIOffset(IDLoc);
2050 case DK_CFI_REL_OFFSET:
2051 return parseDirectiveCFIRelOffset(IDLoc);
2052 case DK_CFI_PERSONALITY:
2053 return parseDirectiveCFIPersonalityOrLsda(true);
2054 case DK_CFI_LSDA:
2055 return parseDirectiveCFIPersonalityOrLsda(false);
2056 case DK_CFI_REMEMBER_STATE:
2057 return parseDirectiveCFIRememberState();
2058 case DK_CFI_RESTORE_STATE:
2059 return parseDirectiveCFIRestoreState();
2060 case DK_CFI_SAME_VALUE:
2061 return parseDirectiveCFISameValue(IDLoc);
2062 case DK_CFI_RESTORE:
2063 return parseDirectiveCFIRestore(IDLoc);
2064 case DK_CFI_ESCAPE:
2065 return parseDirectiveCFIEscape();
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +00002066 case DK_CFI_RETURN_COLUMN:
2067 return parseDirectiveCFIReturnColumn(IDLoc);
Jim Grosbach4b905842013-09-20 23:08:21 +00002068 case DK_CFI_SIGNAL_FRAME:
2069 return parseDirectiveCFISignalFrame();
2070 case DK_CFI_UNDEFINED:
2071 return parseDirectiveCFIUndefined(IDLoc);
2072 case DK_CFI_REGISTER:
2073 return parseDirectiveCFIRegister(IDLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00002074 case DK_CFI_WINDOW_SAVE:
2075 return parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +00002076 case DK_MACROS_ON:
2077 case DK_MACROS_OFF:
2078 return parseDirectiveMacrosOnOff(IDVal);
2079 case DK_MACRO:
2080 return parseDirectiveMacro(IDLoc);
Michael Zuckerman56704612017-05-01 13:20:12 +00002081 case DK_ALTMACRO:
2082 case DK_NOALTMACRO:
2083 return parseDirectiveAltmacro(IDVal);
Nico Weber155dccd12014-07-24 17:08:39 +00002084 case DK_EXITM:
2085 return parseDirectiveExitMacro(IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00002086 case DK_ENDM:
2087 case DK_ENDMACRO:
2088 return parseDirectiveEndMacro(IDVal);
2089 case DK_PURGEM:
2090 return parseDirectivePurgeMacro(IDLoc);
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00002091 case DK_END:
2092 return parseDirectiveEnd(IDLoc);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00002093 case DK_ERR:
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00002094 return parseDirectiveError(IDLoc, false);
2095 case DK_ERROR:
2096 return parseDirectiveError(IDLoc, true);
Nico Weber404012b2014-07-24 16:26:06 +00002097 case DK_WARNING:
2098 return parseDirectiveWarning(IDLoc);
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002099 case DK_RELOC:
2100 return parseDirectiveReloc(IDLoc);
Petr Hosek4cb08ce2016-09-23 19:25:15 +00002101 case DK_DCB:
2102 case DK_DCB_W:
2103 return parseDirectiveDCB(IDVal, 2);
2104 case DK_DCB_B:
2105 return parseDirectiveDCB(IDVal, 1);
2106 case DK_DCB_D:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002107 return parseDirectiveRealDCB(IDVal, APFloat::IEEEdouble());
Petr Hosek4cb08ce2016-09-23 19:25:15 +00002108 case DK_DCB_L:
2109 return parseDirectiveDCB(IDVal, 4);
2110 case DK_DCB_S:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002111 return parseDirectiveRealDCB(IDVal, APFloat::IEEEsingle());
Petr Hosek731bb9c2016-08-23 21:34:53 +00002112 case DK_DC_X:
Petr Hosek4cb08ce2016-09-23 19:25:15 +00002113 case DK_DCB_X:
Petr Hosek731bb9c2016-08-23 21:34:53 +00002114 return TokError(Twine(IDVal) +
2115 " not currently supported for this target");
Petr Hosek85b2f672016-09-23 21:53:36 +00002116 case DK_DS:
2117 case DK_DS_W:
2118 return parseDirectiveDS(IDVal, 2);
2119 case DK_DS_B:
2120 return parseDirectiveDS(IDVal, 1);
2121 case DK_DS_D:
2122 return parseDirectiveDS(IDVal, 8);
2123 case DK_DS_L:
2124 case DK_DS_S:
2125 return parseDirectiveDS(IDVal, 4);
2126 case DK_DS_P:
2127 case DK_DS_X:
2128 return parseDirectiveDS(IDVal, 12);
Coby Tayree01e53202017-10-02 14:36:31 +00002129 case DK_PRINT:
2130 return parseDirectivePrint(IDLoc);
Eli Friedman20b02642010-07-19 04:17:25 +00002131 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002132
Jim Grosbach758e0cc2012-05-01 18:38:27 +00002133 return Error(IDLoc, "unknown directive");
Chris Lattnere5074c42009-06-22 01:29:09 +00002134 }
Chris Lattner36e02122009-06-21 20:54:55 +00002135
Chad Rosierc7f552c2013-02-12 21:33:51 +00002136 // __asm _emit or __asm __emit
2137 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
2138 IDVal == "_EMIT" || IDVal == "__EMIT"))
Jim Grosbach4b905842013-09-20 23:08:21 +00002139 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
Chad Rosierc7f552c2013-02-12 21:33:51 +00002140
2141 // __asm align
2142 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
Jim Grosbach4b905842013-09-20 23:08:21 +00002143 return parseDirectiveMSAlign(IDLoc, Info);
Eli Friedman0f4871d2012-10-22 23:58:19 +00002144
Coby Tayree3847be92017-04-04 17:57:23 +00002145 if (ParsingInlineAsm && (IDVal == "even" || IDVal == "EVEN"))
Michael Zuckerman02ecd432015-12-13 17:07:23 +00002146 Info.AsmRewrites->emplace_back(AOK_EVEN, IDLoc, 4);
Nirav Davef43cc9f2016-10-10 15:24:54 +00002147 if (checkForValidSection())
2148 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00002149
Chris Lattner7cbfa442010-05-19 23:34:33 +00002150 // Canonicalize the opcode to lower case.
Eli Bendersky88024712013-01-16 19:32:36 +00002151 std::string OpcodeStr = IDVal.lower();
Chad Rosierf0e87202012-10-25 20:41:34 +00002152 ParseInstructionInfo IInfo(Info.AsmRewrites);
Nirav Dave2364748a2016-09-16 18:30:20 +00002153 bool ParseHadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, ID,
2154 Info.ParsedOperands);
2155 Info.ParseError = ParseHadError;
Chris Lattnere5074c42009-06-22 01:29:09 +00002156
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002157 // Dump the parsed representation, if requested.
2158 if (getShowParsedOperands()) {
2159 SmallString<256> Str;
2160 raw_svector_ostream OS(Str);
2161 OS << "parsed instruction: [";
Eli Friedman0f4871d2012-10-22 23:58:19 +00002162 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002163 if (i != 0)
2164 OS << ", ";
Eli Friedman0f4871d2012-10-22 23:58:19 +00002165 Info.ParsedOperands[i]->print(OS);
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002166 }
2167 OS << "]";
2168
Jim Grosbach4b905842013-09-20 23:08:21 +00002169 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002170 }
2171
Nirav Dave2364748a2016-09-16 18:30:20 +00002172 // Fail even if ParseInstruction erroneously returns false.
2173 if (hasPendingError() || ParseHadError)
2174 return true;
2175
Oliver Stannard8b273082014-06-19 15:52:37 +00002176 // If we are generating dwarf for the current section then generate a .loc
2177 // directive for the instruction.
Paul Robinson938d9a02018-03-22 15:48:01 +00002178 if (!ParseHadError && enabledGenDwarfForAssembly() &&
Oliver Stannard8b273082014-06-19 15:52:37 +00002179 getContext().getGenDwarfSectionSyms().count(
Eric Christopher445c9522016-10-14 05:47:37 +00002180 getStreamer().getCurrentSectionOnly())) {
Saleem Abdulrasool4d6ed7c2014-12-24 06:32:43 +00002181 unsigned Line;
2182 if (ActiveMacros.empty())
2183 Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
2184 else
Frederic Riss16238d92015-06-25 21:57:33 +00002185 Line = SrcMgr.FindLineNumber(ActiveMacros.front()->InstantiationLoc,
2186 ActiveMacros.front()->ExitBuffer);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002187
Eli Bendersky88024712013-01-16 19:32:36 +00002188 // If we previously parsed a cpp hash file line comment then make sure the
2189 // current Dwarf File is for the CppHashFilename if not then emit the
2190 // Dwarf File table for it and adjust the line number for the .loc.
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00002191 if (!CppHashInfo.Filename.empty()) {
David Blaikiec714ef42014-03-17 01:52:11 +00002192 unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
Tim Northoverc0bef992016-04-13 19:46:54 +00002193 0, StringRef(), CppHashInfo.Filename);
David Blaikiec714ef42014-03-17 01:52:11 +00002194 getContext().setGenDwarfFileNumber(FileNumber);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002195
Graydon Hoare54fe2082018-04-07 00:44:02 +00002196 unsigned CppHashLocLineNo =
2197 SrcMgr.FindLineNumber(CppHashInfo.Loc, CppHashInfo.Buf);
Tim Northoverc0bef992016-04-13 19:46:54 +00002198 Line = CppHashInfo.LineNumber - 1 + (Line - CppHashLocLineNo);
Eli Bendersky88024712013-01-16 19:32:36 +00002199 }
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002200
Jim Grosbach4b905842013-09-20 23:08:21 +00002201 getStreamer().EmitDwarfLocDirective(
2202 getContext().getGenDwarfFileNumber(), Line, 0,
2203 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
2204 StringRef());
Kevin Enderby6469fc22011-11-01 22:27:22 +00002205 }
2206
Daniel Dunbarce0c1e12010-05-04 00:33:07 +00002207 // If parsing succeeded, match the instruction.
Nirav Dave2364748a2016-09-16 18:30:20 +00002208 if (!ParseHadError) {
Tim Northover26bb14e2014-08-18 11:49:42 +00002209 uint64_t ErrorInfo;
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +00002210 if (getTargetParser().MatchAndEmitInstruction(
2211 IDLoc, Info.Opcode, Info.ParsedOperands, Out, ErrorInfo,
2212 getTargetParser().isParsingInlineAsm()))
Nirav Dave2364748a2016-09-16 18:30:20 +00002213 return true;
Chad Rosier49963552012-10-13 00:26:04 +00002214 }
Chris Lattnera2a9d162010-09-11 16:18:25 +00002215 return false;
Chris Lattnerb0133452009-06-21 20:16:42 +00002216}
Chris Lattnerbedf6c22009-06-24 04:43:34 +00002217
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00002218// Parse and erase curly braces marking block start/end
Sam Cleggf009da22018-04-19 22:00:53 +00002219bool
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00002220AsmParser::parseCurlyBlockScope(SmallVectorImpl<AsmRewrite> &AsmStrRewrites) {
2221 // Identify curly brace marking block start/end
2222 if (Lexer.isNot(AsmToken::LCurly) && Lexer.isNot(AsmToken::RCurly))
2223 return false;
2224
2225 SMLoc StartLoc = Lexer.getLoc();
2226 Lex(); // Eat the brace
2227 if (Lexer.is(AsmToken::EndOfStatement))
2228 Lex(); // Eat EndOfStatement following the brace
2229
2230 // Erase the block start/end brace from the output asm string
2231 AsmStrRewrites.emplace_back(AOK_Skip, StartLoc, Lexer.getLoc().getPointer() -
2232 StartLoc.getPointer());
2233 return true;
2234}
2235
Jim Grosbach4b905842013-09-20 23:08:21 +00002236/// parseCppHashLineFilenameComment as this:
Kevin Enderby72553612011-09-13 23:45:18 +00002237/// ::= # number "filename"
Craig Topper3c76c522015-09-20 23:35:59 +00002238bool AsmParser::parseCppHashLineFilenameComment(SMLoc L) {
Kevin Enderby72553612011-09-13 23:45:18 +00002239 Lex(); // Eat the hash token.
Nirav Davefd910412016-06-17 16:06:17 +00002240 // Lexer only ever emits HashDirective if it fully formed if it's
2241 // done the checking already so this is an internal error.
2242 assert(getTok().is(AsmToken::Integer) &&
2243 "Lexing Cpp line comment: Expected Integer");
Kevin Enderby72553612011-09-13 23:45:18 +00002244 int64_t LineNumber = getTok().getIntVal();
Kevin Enderby72553612011-09-13 23:45:18 +00002245 Lex();
Nirav Davefd910412016-06-17 16:06:17 +00002246 assert(getTok().is(AsmToken::String) &&
2247 "Lexing Cpp line comment: Expected String");
Kevin Enderby72553612011-09-13 23:45:18 +00002248 StringRef Filename = getTok().getString();
Nirav Davefd910412016-06-17 16:06:17 +00002249 Lex();
Nirav Dave2364748a2016-09-16 18:30:20 +00002250
Kevin Enderby72553612011-09-13 23:45:18 +00002251 // Get rid of the enclosing quotes.
Jim Grosbach4b905842013-09-20 23:08:21 +00002252 Filename = Filename.substr(1, Filename.size() - 2);
Kevin Enderby72553612011-09-13 23:45:18 +00002253
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002254 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
Tim Northoverc0bef992016-04-13 19:46:54 +00002255 CppHashInfo.Loc = L;
2256 CppHashInfo.Filename = Filename;
2257 CppHashInfo.LineNumber = LineNumber;
2258 CppHashInfo.Buf = CurBuffer;
Kevin Enderby72553612011-09-13 23:45:18 +00002259 return false;
2260}
2261
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002262/// will use the last parsed cpp hash line filename comment
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002263/// for the Filename and LineNo if any in the diagnostic.
2264void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002265 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002266 raw_ostream &OS = errs();
2267
2268 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
Craig Topper3c76c522015-09-20 23:35:59 +00002269 SMLoc DiagLoc = Diag.getLoc();
Alp Tokera55b95b2014-07-06 10:33:31 +00002270 unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2271 unsigned CppHashBuf =
Tim Northoverc0bef992016-04-13 19:46:54 +00002272 Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashInfo.Loc);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002273
Jim Grosbach4b905842013-09-20 23:08:21 +00002274 // Like SourceMgr::printMessage() we need to print the include stack if any
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002275 // before printing the message.
Alp Tokera55b95b2014-07-06 10:33:31 +00002276 unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2277 if (!Parser->SavedDiagHandler && DiagCurBuffer &&
2278 DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002279 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
2280 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002281 }
2282
Eric Christophera7c32732012-12-18 00:30:54 +00002283 // If we have not parsed a cpp hash line filename comment or the source
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002284 // manager changed or buffer changed (like in a nested include) then just
2285 // print the normal diagnostic using its Filename and LineNo.
Tim Northoverc0bef992016-04-13 19:46:54 +00002286 if (!Parser->CppHashInfo.LineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002287 DiagBuf != CppHashBuf) {
Benjamin Kramer47f5e302011-10-16 10:48:29 +00002288 if (Parser->SavedDiagHandler)
2289 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
2290 else
Craig Topper353eda42014-04-24 06:44:33 +00002291 Diag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002292 return;
2293 }
2294
Eric Christophera7c32732012-12-18 00:30:54 +00002295 // Use the CppHashFilename and calculate a line number based on the
Tim Northoverc0bef992016-04-13 19:46:54 +00002296 // CppHashInfo.Loc and CppHashInfo.LineNumber relative to this Diag's SMLoc
2297 // for the diagnostic.
2298 const std::string &Filename = Parser->CppHashInfo.Filename;
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002299
2300 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
2301 int CppHashLocLineNo =
Tim Northoverc0bef992016-04-13 19:46:54 +00002302 Parser->SrcMgr.FindLineNumber(Parser->CppHashInfo.Loc, CppHashBuf);
Jim Grosbach4b905842013-09-20 23:08:21 +00002303 int LineNo =
Tim Northoverc0bef992016-04-13 19:46:54 +00002304 Parser->CppHashInfo.LineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002305
Jim Grosbach4b905842013-09-20 23:08:21 +00002306 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
2307 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
Chris Lattner72845262011-10-16 05:47:55 +00002308 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002309
Benjamin Kramer47f5e302011-10-16 10:48:29 +00002310 if (Parser->SavedDiagHandler)
2311 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
2312 else
Craig Topper353eda42014-04-24 06:44:33 +00002313 NewDiag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002314}
2315
Rafael Espindola2c064482012-08-21 18:29:30 +00002316// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
2317// difference being that that function accepts '@' as part of identifiers and
2318// we can't do that. AsmLexer.cpp should probably be changed to handle
2319// '@' as a special case when needed.
2320static bool isIdentifierChar(char c) {
Guy Benyei83c74e92013-02-12 21:21:59 +00002321 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
2322 c == '.';
Rafael Espindola2c064482012-08-21 18:29:30 +00002323}
2324
Rafael Espindola34b9c512012-06-03 23:57:14 +00002325bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00002326 ArrayRef<MCAsmMacroParameter> Parameters,
Toma Tabacu217116e2015-04-27 10:50:29 +00002327 ArrayRef<MCAsmMacroArgument> A,
Craig Topper3c76c522015-09-20 23:35:59 +00002328 bool EnableAtPseudoVariable, SMLoc L) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00002329 unsigned NParameters = Parameters.size();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002330 bool HasVararg = NParameters ? Parameters.back().Vararg : false;
Benjamin Kramer513e7442014-02-20 13:36:32 +00002331 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
Rafael Espindola1134ab232011-06-05 02:43:45 +00002332 return Error(L, "Wrong number of arguments");
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002333
Preston Gurd05500642012-09-19 20:36:12 +00002334 // A macro without parameters is handled differently on Darwin:
2335 // gas accepts no arguments and does no substitutions
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002336 while (!Body.empty()) {
2337 // Scan for the next substitution.
2338 std::size_t End = Body.size(), Pos = 0;
2339 for (; Pos != End; ++Pos) {
2340 // Check for a substitution or escape.
Benjamin Kramer513e7442014-02-20 13:36:32 +00002341 if (IsDarwin && !NParameters) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00002342 // This macro has no parameters, look for $0, $1, etc.
2343 if (Body[Pos] != '$' || Pos + 1 == End)
2344 continue;
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002345
Rafael Espindola1134ab232011-06-05 02:43:45 +00002346 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00002347 if (Next == '$' || Next == 'n' ||
2348 isdigit(static_cast<unsigned char>(Next)))
Rafael Espindola1134ab232011-06-05 02:43:45 +00002349 break;
2350 } else {
2351 // This macro has parameters, look for \foo, \bar, etc.
2352 if (Body[Pos] == '\\' && Pos + 1 != End)
2353 break;
2354 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002355 }
2356
2357 // Add the prefix.
2358 OS << Body.slice(0, Pos);
2359
2360 // Check if we reached the end.
2361 if (Pos == End)
2362 break;
2363
Benjamin Kramer513e7442014-02-20 13:36:32 +00002364 if (IsDarwin && !NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002365 switch (Body[Pos + 1]) {
2366 // $$ => $
Rafael Espindola1134ab232011-06-05 02:43:45 +00002367 case '$':
2368 OS << '$';
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002369 break;
2370
Jim Grosbach4b905842013-09-20 23:08:21 +00002371 // $n => number of arguments
Rafael Espindola1134ab232011-06-05 02:43:45 +00002372 case 'n':
2373 OS << A.size();
2374 break;
2375
Jim Grosbach4b905842013-09-20 23:08:21 +00002376 // $[0-9] => argument
Rafael Espindola1134ab232011-06-05 02:43:45 +00002377 default: {
2378 // Missing arguments are ignored.
Jim Grosbach4b905842013-09-20 23:08:21 +00002379 unsigned Index = Body[Pos + 1] - '0';
Rafael Espindola1134ab232011-06-05 02:43:45 +00002380 if (Index >= A.size())
2381 break;
2382
2383 // Otherwise substitute with the token values, with spaces eliminated.
Craig Topper84008482015-10-10 05:38:14 +00002384 for (const AsmToken &Token : A[Index])
2385 OS << Token.getString();
Rafael Espindola1134ab232011-06-05 02:43:45 +00002386 break;
2387 }
2388 }
2389 Pos += 2;
2390 } else {
2391 unsigned I = Pos + 1;
Toma Tabacu217116e2015-04-27 10:50:29 +00002392
2393 // Check for the \@ pseudo-variable.
2394 if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End)
Rafael Espindola1134ab232011-06-05 02:43:45 +00002395 ++I;
Toma Tabacu217116e2015-04-27 10:50:29 +00002396 else
2397 while (isIdentifierChar(Body[I]) && I + 1 != End)
2398 ++I;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002399
Jim Grosbach4b905842013-09-20 23:08:21 +00002400 const char *Begin = Body.data() + Pos + 1;
2401 StringRef Argument(Begin, I - (Pos + 1));
Rafael Espindola1134ab232011-06-05 02:43:45 +00002402 unsigned Index = 0;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002403
Toma Tabacu217116e2015-04-27 10:50:29 +00002404 if (Argument == "@") {
2405 OS << NumOfMacroInstantiations;
2406 Pos += 2;
Preston Gurd05500642012-09-19 20:36:12 +00002407 } else {
Toma Tabacu217116e2015-04-27 10:50:29 +00002408 for (; Index < NParameters; ++Index)
2409 if (Parameters[Index].Name == Argument)
2410 break;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002411
Toma Tabacu217116e2015-04-27 10:50:29 +00002412 if (Index == NParameters) {
2413 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
2414 Pos += 3;
2415 else {
2416 OS << '\\' << Argument;
2417 Pos = I;
2418 }
2419 } else {
2420 bool VarargParameter = HasVararg && Index == (NParameters - 1);
Craig Topper84008482015-10-10 05:38:14 +00002421 for (const AsmToken &Token : A[Index])
Michael Zuckerman56704612017-05-01 13:20:12 +00002422 // For altmacro mode, you can write '%expr'.
2423 // The prefix '%' evaluates the expression 'expr'
2424 // and uses the result as a string (e.g. replace %(1+2) with the string "3").
2425 // Here, we identify the integer token which is the result of the
2426 // absolute expression evaluation and replace it with its string representation.
2427 if ((Lexer.IsaAltMacroMode()) &&
2428 (*(Token.getString().begin()) == '%') && Token.is(AsmToken::Integer))
2429 // Emit an integer value to the buffer.
2430 OS << Token.getIntVal();
Michael Zuckerman1f1a9122017-05-10 13:08:11 +00002431 // Only Token that was validated as a string and begins with '<'
2432 // is considered altMacroString!!!
2433 else if ((Lexer.IsaAltMacroMode()) &&
2434 (*(Token.getString().begin()) == '<') &&
2435 Token.is(AsmToken::String)) {
2436 std::string Res;
2437 altMacroString(Token.getStringContents(), Res);
2438 OS << Res;
2439 }
Toma Tabacu217116e2015-04-27 10:50:29 +00002440 // We expect no quotes around the string's contents when
2441 // parsing for varargs.
Michael Zuckerman56704612017-05-01 13:20:12 +00002442 else if (Token.isNot(AsmToken::String) || VarargParameter)
Craig Topper84008482015-10-10 05:38:14 +00002443 OS << Token.getString();
Toma Tabacu217116e2015-04-27 10:50:29 +00002444 else
Craig Topper84008482015-10-10 05:38:14 +00002445 OS << Token.getStringContents();
Toma Tabacu217116e2015-04-27 10:50:29 +00002446
2447 Pos += 1 + Argument.size();
2448 }
Preston Gurd05500642012-09-19 20:36:12 +00002449 }
Rafael Espindola1134ab232011-06-05 02:43:45 +00002450 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002451 // Update the scan point.
Rafael Espindola1134ab232011-06-05 02:43:45 +00002452 Body = Body.substr(Pos);
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002453 }
Daniel Dunbar43235712010-07-18 18:54:11 +00002454
Rafael Espindola1134ab232011-06-05 02:43:45 +00002455 return false;
2456}
Daniel Dunbar43235712010-07-18 18:54:11 +00002457
Nico Weber2a8f9222014-07-24 16:29:04 +00002458MacroInstantiation::MacroInstantiation(SMLoc IL, int EB, SMLoc EL,
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002459 size_t CondStackDepth)
Rafael Espindolaf43a94e2014-08-17 22:48:55 +00002460 : InstantiationLoc(IL), ExitBuffer(EB), ExitLoc(EL),
Nico Weber155dccd12014-07-24 17:08:39 +00002461 CondStackDepth(CondStackDepth) {}
Daniel Dunbar43235712010-07-18 18:54:11 +00002462
Jim Grosbach4b905842013-09-20 23:08:21 +00002463static bool isOperator(AsmToken::TokenKind kind) {
2464 switch (kind) {
2465 default:
2466 return false;
2467 case AsmToken::Plus:
2468 case AsmToken::Minus:
2469 case AsmToken::Tilde:
2470 case AsmToken::Slash:
2471 case AsmToken::Star:
2472 case AsmToken::Dot:
2473 case AsmToken::Equal:
2474 case AsmToken::EqualEqual:
2475 case AsmToken::Pipe:
2476 case AsmToken::PipePipe:
2477 case AsmToken::Caret:
2478 case AsmToken::Amp:
2479 case AsmToken::AmpAmp:
2480 case AsmToken::Exclaim:
2481 case AsmToken::ExclaimEqual:
Jim Grosbach4b905842013-09-20 23:08:21 +00002482 case AsmToken::Less:
2483 case AsmToken::LessEqual:
2484 case AsmToken::LessLess:
2485 case AsmToken::LessGreater:
2486 case AsmToken::Greater:
2487 case AsmToken::GreaterEqual:
2488 case AsmToken::GreaterGreater:
2489 return true;
Preston Gurd05500642012-09-19 20:36:12 +00002490 }
2491}
2492
David Majnemer16252452014-01-29 00:07:39 +00002493namespace {
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002494
David Majnemer16252452014-01-29 00:07:39 +00002495class AsmLexerSkipSpaceRAII {
2496public:
2497 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
2498 Lexer.setSkipSpace(SkipSpace);
2499 }
2500
2501 ~AsmLexerSkipSpaceRAII() {
2502 Lexer.setSkipSpace(true);
2503 }
2504
2505private:
2506 AsmLexer &Lexer;
2507};
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002508
2509} // end anonymous namespace
David Majnemer16252452014-01-29 00:07:39 +00002510
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002511bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
2512
2513 if (Vararg) {
2514 if (Lexer.isNot(AsmToken::EndOfStatement)) {
2515 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002516 MA.emplace_back(AsmToken::String, Str);
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002517 }
2518 return false;
2519 }
2520
Rafael Espindola768b41c2012-06-15 14:02:34 +00002521 unsigned ParenLevel = 0;
Preston Gurd05500642012-09-19 20:36:12 +00002522
David Majnemer16252452014-01-29 00:07:39 +00002523 // Darwin doesn't use spaces to delmit arguments.
2524 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
Rafael Espindola768b41c2012-06-15 14:02:34 +00002525
Scott Egertona1fa68a2016-02-11 13:48:49 +00002526 bool SpaceEaten;
2527
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002528 while (true) {
Scott Egertona1fa68a2016-02-11 13:48:49 +00002529 SpaceEaten = false;
David Majnemer16252452014-01-29 00:07:39 +00002530 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002531 return TokError("unexpected token in macro instantiation");
Preston Gurd05500642012-09-19 20:36:12 +00002532
Scott Egertona1fa68a2016-02-11 13:48:49 +00002533 if (ParenLevel == 0) {
Preston Gurd05500642012-09-19 20:36:12 +00002534
Scott Egertona1fa68a2016-02-11 13:48:49 +00002535 if (Lexer.is(AsmToken::Comma))
2536 break;
2537
2538 if (Lexer.is(AsmToken::Space)) {
2539 SpaceEaten = true;
Nirav Dave1180e6892016-06-02 17:15:05 +00002540 Lexer.Lex(); // Eat spaces
Scott Egertona1fa68a2016-02-11 13:48:49 +00002541 }
Preston Gurd05500642012-09-19 20:36:12 +00002542
2543 // Spaces can delimit parameters, but could also be part an expression.
2544 // If the token after a space is an operator, add the token and the next
2545 // one into this argument
David Majnemer91fc4c22014-01-29 18:57:46 +00002546 if (!IsDarwin) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002547 if (isOperator(Lexer.getKind())) {
Scott Egertona1fa68a2016-02-11 13:48:49 +00002548 MA.push_back(getTok());
Nirav Dave1180e6892016-06-02 17:15:05 +00002549 Lexer.Lex();
Preston Gurd05500642012-09-19 20:36:12 +00002550
Scott Egertona1fa68a2016-02-11 13:48:49 +00002551 // Whitespace after an operator can be ignored.
2552 if (Lexer.is(AsmToken::Space))
Nirav Dave1180e6892016-06-02 17:15:05 +00002553 Lexer.Lex();
Scott Egertona1fa68a2016-02-11 13:48:49 +00002554
2555 continue;
Preston Gurd05500642012-09-19 20:36:12 +00002556 }
2557 }
Scott Egertona1fa68a2016-02-11 13:48:49 +00002558 if (SpaceEaten)
2559 break;
Preston Gurd05500642012-09-19 20:36:12 +00002560 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002561
Jim Grosbach4b905842013-09-20 23:08:21 +00002562 // handleMacroEntry relies on not advancing the lexer here
Rafael Espindola768b41c2012-06-15 14:02:34 +00002563 // to be able to fill in the remaining default parameter values
2564 if (Lexer.is(AsmToken::EndOfStatement))
2565 break;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002566
2567 // Adjust the current parentheses level.
2568 if (Lexer.is(AsmToken::LParen))
2569 ++ParenLevel;
2570 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
2571 --ParenLevel;
2572
2573 // Append the token to the current argument list.
2574 MA.push_back(getTok());
Nirav Dave1180e6892016-06-02 17:15:05 +00002575 Lexer.Lex();
Rafael Espindola768b41c2012-06-15 14:02:34 +00002576 }
Preston Gurd05500642012-09-19 20:36:12 +00002577
Rafael Espindola768b41c2012-06-15 14:02:34 +00002578 if (ParenLevel != 0)
Rafael Espindola3e5eb422012-08-21 15:55:04 +00002579 return TokError("unbalanced parentheses in macro argument");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002580 return false;
2581}
2582
2583// Parse the macro instantiation arguments.
Jim Grosbach4b905842013-09-20 23:08:21 +00002584bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
Vladimir Medic9bad0d332013-08-20 13:33:18 +00002585 MCAsmMacroArguments &A) {
Rafael Espindola768b41c2012-06-15 14:02:34 +00002586 const unsigned NParameters = M ? M->Parameters.size() : 0;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002587 bool NamedParametersFound = false;
2588 SmallVector<SMLoc, 4> FALocs;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002589
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002590 A.resize(NParameters);
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002591 FALocs.resize(NParameters);
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002592
Rafael Espindola768b41c2012-06-15 14:02:34 +00002593 // Parse two kinds of macro invocations:
2594 // - macros defined without any parameters accept an arbitrary number of them
2595 // - macros defined with parameters accept at most that many of them
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002596 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002597 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
2598 ++Parameter) {
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002599 SMLoc IDLoc = Lexer.getLoc();
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002600 MCAsmMacroParameter FA;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002601
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002602 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00002603 if (parseIdentifier(FA.Name))
2604 return Error(IDLoc, "invalid argument identifier for formal argument");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002605
Nirav Dave2364748a2016-09-16 18:30:20 +00002606 if (Lexer.isNot(AsmToken::Equal))
2607 return TokError("expected '=' after formal parameter identifier");
2608
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002609 Lex();
2610
2611 NamedParametersFound = true;
2612 }
Michael Zuckerman56704612017-05-01 13:20:12 +00002613 bool Vararg = HasVararg && Parameter == (NParameters - 1);
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002614
Nirav Dave2364748a2016-09-16 18:30:20 +00002615 if (NamedParametersFound && FA.Name.empty())
2616 return Error(IDLoc, "cannot mix positional and keyword arguments");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002617
Michael Zuckerman763e60e2017-05-04 10:37:00 +00002618 SMLoc StrLoc = Lexer.getLoc();
2619 SMLoc EndLoc;
Michael Zuckerman56704612017-05-01 13:20:12 +00002620 if (Lexer.IsaAltMacroMode() && Lexer.is(AsmToken::Percent)) {
Michael Zuckerman56704612017-05-01 13:20:12 +00002621 const MCExpr *AbsoluteExp;
2622 int64_t Value;
2623 /// Eat '%'
2624 Lex();
2625 if (parseExpression(AbsoluteExp, EndLoc))
2626 return false;
Nirav Dave6c0665e2018-04-30 19:22:40 +00002627 if (!AbsoluteExp->evaluateAsAbsolute(Value,
2628 getStreamer().getAssemblerPtr()))
Michael Zuckerman56704612017-05-01 13:20:12 +00002629 return Error(StrLoc, "expected absolute expression");
2630 const char *StrChar = StrLoc.getPointer();
2631 const char *EndChar = EndLoc.getPointer();
2632 AsmToken newToken(AsmToken::Integer, StringRef(StrChar , EndChar - StrChar), Value);
2633 FA.Value.push_back(newToken);
Michael Zuckerman763e60e2017-05-04 10:37:00 +00002634 } else if (Lexer.IsaAltMacroMode() && Lexer.is(AsmToken::Less) &&
2635 isAltmacroString(StrLoc, EndLoc)) {
2636 const char *StrChar = StrLoc.getPointer();
2637 const char *EndChar = EndLoc.getPointer();
2638 jumpToLoc(EndLoc, CurBuffer);
2639 /// Eat from '<' to '>'
2640 Lex();
2641 AsmToken newToken(AsmToken::String, StringRef(StrChar, EndChar - StrChar));
2642 FA.Value.push_back(newToken);
2643 } else if(parseMacroArgument(FA.Value, Vararg))
Michael Zuckerman56704612017-05-01 13:20:12 +00002644 return true;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002645
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002646 unsigned PI = Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002647 if (!FA.Name.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002648 unsigned FAI = 0;
2649 for (FAI = 0; FAI < NParameters; ++FAI)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002650 if (M->Parameters[FAI].Name == FA.Name)
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002651 break;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002652
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002653 if (FAI >= NParameters) {
Nirav Davefd910412016-06-17 16:06:17 +00002654 assert(M && "expected macro to be defined");
Nirav Dave2364748a2016-09-16 18:30:20 +00002655 return Error(IDLoc, "parameter named '" + FA.Name +
2656 "' does not exist for macro '" + M->Name + "'");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002657 }
2658 PI = FAI;
2659 }
2660
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002661 if (!FA.Value.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002662 if (A.size() <= PI)
2663 A.resize(PI + 1);
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002664 A[PI] = FA.Value;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002665
2666 if (FALocs.size() <= PI)
2667 FALocs.resize(PI + 1);
2668
2669 FALocs[PI] = Lexer.getLoc();
Preston Gurd242ed3152012-09-19 20:29:04 +00002670 }
Jim Grosbach206661622012-07-30 22:44:17 +00002671
Preston Gurd242ed3152012-09-19 20:29:04 +00002672 // At the end of the statement, fill in remaining arguments that have
2673 // default values. If there aren't any, then the next argument is
2674 // required but missing
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002675 if (Lexer.is(AsmToken::EndOfStatement)) {
2676 bool Failure = false;
2677 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2678 if (A[FAI].empty()) {
2679 if (M->Parameters[FAI].Required) {
2680 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2681 "missing value for required parameter "
2682 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2683 Failure = true;
2684 }
2685
2686 if (!M->Parameters[FAI].Value.empty())
2687 A[FAI] = M->Parameters[FAI].Value;
2688 }
2689 }
2690 return Failure;
2691 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002692
2693 if (Lexer.is(AsmToken::Comma))
2694 Lex();
2695 }
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002696
2697 return TokError("too many positional arguments");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002698}
2699
Jim Grosbach4b905842013-09-20 23:08:21 +00002700bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
Davide Italiano7c9fc732016-07-27 05:51:56 +00002701 // Arbitrarily limit macro nesting depth (default matches 'as'). We can
2702 // eliminate this, although we should protect against infinite loops.
2703 unsigned MaxNestingDepth = AsmMacroMaxNestingDepth;
2704 if (ActiveMacros.size() == MaxNestingDepth) {
2705 std::ostringstream MaxNestingDepthError;
2706 MaxNestingDepthError << "macros cannot be nested more than "
2707 << MaxNestingDepth << " levels deep."
2708 << " Use -asm-macro-max-nesting-depth to increase "
2709 "this limit.";
2710 return TokError(MaxNestingDepthError.str());
2711 }
Daniel Dunbar43235712010-07-18 18:54:11 +00002712
Eli Bendersky38274122013-01-14 23:22:36 +00002713 MCAsmMacroArguments A;
Jim Grosbach4b905842013-09-20 23:08:21 +00002714 if (parseMacroArguments(M, A))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002715 return true;
Daniel Dunbar43235712010-07-18 18:54:11 +00002716
Rafael Espindola1134ab232011-06-05 02:43:45 +00002717 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2718 // to hold the macro body with substitutions.
2719 SmallString<256> Buf;
2720 StringRef Body = M->Body;
Rafael Espindola34b9c512012-06-03 23:57:14 +00002721 raw_svector_ostream OS(Buf);
Rafael Espindola1134ab232011-06-05 02:43:45 +00002722
Toma Tabacu217116e2015-04-27 10:50:29 +00002723 if (expandMacro(OS, Body, M->Parameters, A, true, getTok().getLoc()))
Rafael Espindola1134ab232011-06-05 02:43:45 +00002724 return true;
2725
Eli Bendersky38274122013-01-14 23:22:36 +00002726 // We include the .endmacro in the buffer as our cue to exit the macro
Rafael Espindola34b9c512012-06-03 23:57:14 +00002727 // instantiation.
2728 OS << ".endmacro\n";
2729
Rafael Espindola3560ff22014-08-27 20:03:13 +00002730 std::unique_ptr<MemoryBuffer> Instantiation =
2731 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola1134ab232011-06-05 02:43:45 +00002732
Daniel Dunbar43235712010-07-18 18:54:11 +00002733 // Create the macro instantiation object and add to the current macro
2734 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002735 MacroInstantiation *MI = new MacroInstantiation(
2736 NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Daniel Dunbar43235712010-07-18 18:54:11 +00002737 ActiveMacros.push_back(MI);
2738
Toma Tabacu217116e2015-04-27 10:50:29 +00002739 ++NumOfMacroInstantiations;
2740
Daniel Dunbar43235712010-07-18 18:54:11 +00002741 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00002742 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00002743 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar43235712010-07-18 18:54:11 +00002744 Lex();
2745
2746 return false;
2747}
2748
Jim Grosbach4b905842013-09-20 23:08:21 +00002749void AsmParser::handleMacroExit() {
Daniel Dunbar43235712010-07-18 18:54:11 +00002750 // Jump to the EndOfStatement we should return to, and consume it.
Jim Grosbach4b905842013-09-20 23:08:21 +00002751 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
Daniel Dunbar43235712010-07-18 18:54:11 +00002752 Lex();
2753
2754 // Pop the instantiation entry.
2755 delete ActiveMacros.back();
2756 ActiveMacros.pop_back();
2757}
2758
Jim Grosbach4b905842013-09-20 23:08:21 +00002759bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
Nirav Dave05b58912018-06-05 15:13:39 +00002760 bool NoDeadStrip, bool AllowExtendedExpr) {
Pete Cooper80d21cb2015-06-22 19:35:57 +00002761 MCSymbol *Sym;
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002762 const MCExpr *Value;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002763 if (MCParserUtils::parseAssignmentExpression(Name, allow_redef, *this, Sym,
Nirav Dave05b58912018-06-05 15:13:39 +00002764 Value, AllowExtendedExpr))
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002765 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002766
Pete Cooper80d21cb2015-06-22 19:35:57 +00002767 if (!Sym) {
2768 // In the case where we parse an expression starting with a '.', we will
2769 // not generate an error, nor will we create a symbol. In this case we
2770 // should just return out.
Anders Waldenborg84809572014-02-17 20:48:32 +00002771 return false;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002772 }
David Majnemer58cb80c2014-12-24 10:27:50 +00002773
Daniel Dunbarae7ac012009-06-29 23:43:14 +00002774 // Do the assignment.
Daniel Dunbarb7b20972009-08-31 08:09:09 +00002775 Out.EmitAssignment(Sym, Value);
Jim Grosbachb7b750d2012-09-13 23:11:31 +00002776 if (NoDeadStrip)
2777 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2778
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002779 return false;
2780}
2781
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002782/// parseIdentifier:
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002783/// ::= identifier
2784/// ::= string
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002785bool AsmParser::parseIdentifier(StringRef &Res) {
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002786 // The assembler has relaxed rules for accepting identifiers, in particular we
Hans Wennborgce69d772013-10-18 20:46:28 +00002787 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2788 // separate tokens. At this level, we have already lexed so we cannot (currently)
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002789 // handle this as a context dependent token, instead we detect adjacent tokens
2790 // and return the combined identifier.
Hans Wennborgce69d772013-10-18 20:46:28 +00002791 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2792 SMLoc PrefixLoc = getLexer().getLoc();
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002793
Hans Wennborgce69d772013-10-18 20:46:28 +00002794 // Consume the prefix character, and check for a following identifier.
Nirav Daved0463322016-10-12 13:58:07 +00002795
2796 AsmToken Buf[1];
2797 Lexer.peekTokens(Buf, false);
2798
2799 if (Buf[0].isNot(AsmToken::Identifier))
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002800 return true;
2801
Hans Wennborgce69d772013-10-18 20:46:28 +00002802 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
Nirav Daved0463322016-10-12 13:58:07 +00002803 if (PrefixLoc.getPointer() + 1 != Buf[0].getLoc().getPointer())
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002804 return true;
2805
Nirav Daved0463322016-10-12 13:58:07 +00002806 // eat $ or @
2807 Lexer.Lex(); // Lexer's Lex guarantees consecutive token.
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002808 // Construct the joined identifier and consume the token.
Jim Grosbach4b905842013-09-20 23:08:21 +00002809 Res =
Hans Wennborgce69d772013-10-18 20:46:28 +00002810 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
Nirav Davefd910412016-06-17 16:06:17 +00002811 Lex(); // Parser Lex to maintain invariants.
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002812 return false;
2813 }
2814
Jim Grosbach4b905842013-09-20 23:08:21 +00002815 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002816 return true;
2817
Sean Callanan936b0d32010-01-19 21:44:56 +00002818 Res = getTok().getIdentifier();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002819
Sean Callanan686ed8d2010-01-19 20:22:31 +00002820 Lex(); // Consume the identifier token.
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002821
2822 return false;
2823}
2824
Jim Grosbach4b905842013-09-20 23:08:21 +00002825/// parseDirectiveSet:
Nico Weber4ada0d92011-01-28 03:04:41 +00002826/// ::= .equ identifier ',' expression
2827/// ::= .equiv identifier ',' expression
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002828/// ::= .set identifier ',' expression
Jim Grosbach4b905842013-09-20 23:08:21 +00002829bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002830 StringRef Name;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002831 if (check(parseIdentifier(Name), "expected identifier") ||
2832 parseToken(AsmToken::Comma) || parseAssignment(Name, allow_redef, true))
2833 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
2834 return false;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002835}
2836
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002837bool AsmParser::parseEscapedString(std::string &Data) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00002838 if (check(getTok().isNot(AsmToken::String), "expected string"))
2839 return true;
Daniel Dunbaref668c12009-08-14 18:19:52 +00002840
2841 Data = "";
Sean Callanan936b0d32010-01-19 21:44:56 +00002842 StringRef Str = getTok().getStringContents();
Daniel Dunbaref668c12009-08-14 18:19:52 +00002843 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2844 if (Str[i] != '\\') {
2845 Data += Str[i];
2846 continue;
2847 }
2848
2849 // Recognize escaped characters. Note that this escape semantics currently
2850 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2851 ++i;
2852 if (i == e)
2853 return TokError("unexpected backslash at end of string");
2854
2855 // Recognize octal sequences.
Jim Grosbach4b905842013-09-20 23:08:21 +00002856 if ((unsigned)(Str[i] - '0') <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002857 // Consume up to three octal characters.
2858 unsigned Value = Str[i] - '0';
2859
Jim Grosbach4b905842013-09-20 23:08:21 +00002860 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002861 ++i;
2862 Value = Value * 8 + (Str[i] - '0');
2863
Jim Grosbach4b905842013-09-20 23:08:21 +00002864 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002865 ++i;
2866 Value = Value * 8 + (Str[i] - '0');
2867 }
2868 }
2869
2870 if (Value > 255)
2871 return TokError("invalid octal escape sequence (out of range)");
2872
Jim Grosbach4b905842013-09-20 23:08:21 +00002873 Data += (unsigned char)Value;
Daniel Dunbaref668c12009-08-14 18:19:52 +00002874 continue;
2875 }
2876
2877 // Otherwise recognize individual escapes.
2878 switch (Str[i]) {
2879 default:
2880 // Just reject invalid escape sequences for now.
2881 return TokError("invalid escape sequence (unrecognized character)");
2882
2883 case 'b': Data += '\b'; break;
2884 case 'f': Data += '\f'; break;
2885 case 'n': Data += '\n'; break;
2886 case 'r': Data += '\r'; break;
2887 case 't': Data += '\t'; break;
2888 case '"': Data += '"'; break;
2889 case '\\': Data += '\\'; break;
2890 }
2891 }
2892
Nirav Davea645433c2016-07-18 15:24:03 +00002893 Lex();
Daniel Dunbaref668c12009-08-14 18:19:52 +00002894 return false;
2895}
2896
Jim Grosbach4b905842013-09-20 23:08:21 +00002897/// parseDirectiveAscii:
Rafael Espindola63760ba2010-10-28 20:02:27 +00002898/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002899bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00002900 auto parseOp = [&]() -> bool {
2901 std::string Data;
2902 if (checkForValidSection() || parseEscapedString(Data))
Nirav Davef43cc9f2016-10-10 15:24:54 +00002903 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002904 getStreamer().EmitBytes(Data);
2905 if (ZeroTerminated)
2906 getStreamer().EmitBytes(StringRef("\0", 1));
2907 return false;
2908 };
Daniel Dunbare5444a82010-09-09 22:42:59 +00002909
Nirav Dave1a9044b2016-10-24 14:35:29 +00002910 if (parseMany(parseOp))
2911 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbara10e5192009-06-24 23:30:00 +00002912 return false;
2913}
2914
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002915/// parseDirectiveReloc
2916/// ::= .reloc expression , identifier [ , expression ]
2917bool AsmParser::parseDirectiveReloc(SMLoc DirectiveLoc) {
2918 const MCExpr *Offset;
2919 const MCExpr *Expr = nullptr;
2920
2921 SMLoc OffsetLoc = Lexer.getTok().getLoc();
Nirav Dave1a9044b2016-10-24 14:35:29 +00002922 int64_t OffsetValue;
2923 // We can only deal with constant expressions at the moment.
2924
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002925 if (parseExpression(Offset))
2926 return true;
2927
Nirav Dave6c0665e2018-04-30 19:22:40 +00002928 if (check(!Offset->evaluateAsAbsolute(OffsetValue,
2929 getStreamer().getAssemblerPtr()),
2930 OffsetLoc, "expression is not a constant value") ||
Nirav Davea645433c2016-07-18 15:24:03 +00002931 check(OffsetValue < 0, OffsetLoc, "expression is negative") ||
2932 parseToken(AsmToken::Comma, "expected comma") ||
2933 check(getTok().isNot(AsmToken::Identifier), "expected relocation name"))
2934 return true;
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002935
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002936 SMLoc NameLoc = Lexer.getTok().getLoc();
2937 StringRef Name = Lexer.getTok().getIdentifier();
Nirav Davefd910412016-06-17 16:06:17 +00002938 Lex();
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002939
2940 if (Lexer.is(AsmToken::Comma)) {
Nirav Davefd910412016-06-17 16:06:17 +00002941 Lex();
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002942 SMLoc ExprLoc = Lexer.getLoc();
2943 if (parseExpression(Expr))
2944 return true;
2945
2946 MCValue Value;
2947 if (!Expr->evaluateAsRelocatable(Value, nullptr, nullptr))
2948 return Error(ExprLoc, "expression must be relocatable");
2949 }
2950
Nirav Davea645433c2016-07-18 15:24:03 +00002951 if (parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00002952 "unexpected token in .reloc directive"))
2953 return true;
2954
Peter Smith57f661b2018-06-06 09:40:06 +00002955 const MCTargetAsmParser &MCT = getTargetParser();
2956 const MCSubtargetInfo &STI = MCT.getSTI();
2957 if (getStreamer().EmitRelocDirective(*Offset, Name, Expr, DirectiveLoc, STI))
Nirav Dave1ab71992016-07-18 19:35:21 +00002958 return Error(NameLoc, "unknown relocation name");
2959
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002960 return false;
2961}
2962
Jim Grosbach4b905842013-09-20 23:08:21 +00002963/// parseDirectiveValue
Daniel Dunbara10e5192009-06-24 23:30:00 +00002964/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00002965bool AsmParser::parseDirectiveValue(StringRef IDVal, unsigned Size) {
2966 auto parseOp = [&]() -> bool {
2967 const MCExpr *Value;
2968 SMLoc ExprLoc = getLexer().getLoc();
2969 if (checkForValidSection() || parseExpression(Value))
Nirav Davef43cc9f2016-10-10 15:24:54 +00002970 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002971 // Special case constant expressions to match code generator.
2972 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2973 assert(Size <= 8 && "Invalid size");
2974 uint64_t IntValue = MCE->getValue();
2975 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2976 return Error(ExprLoc, "out of range literal value");
2977 getStreamer().EmitIntValue(IntValue, Size);
2978 } else
2979 getStreamer().EmitValue(Value, Size, ExprLoc);
2980 return false;
2981 };
Daniel Dunbare5444a82010-09-09 22:42:59 +00002982
Nirav Dave1a9044b2016-10-24 14:35:29 +00002983 if (parseMany(parseOp))
2984 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbara10e5192009-06-24 23:30:00 +00002985 return false;
2986}
2987
Paul Robinson01954692018-04-11 15:14:05 +00002988static bool parseHexOcta(AsmParser &Asm, uint64_t &hi, uint64_t &lo) {
2989 if (Asm.getTok().isNot(AsmToken::Integer) &&
2990 Asm.getTok().isNot(AsmToken::BigNum))
2991 return Asm.TokError("unknown token in expression");
2992 SMLoc ExprLoc = Asm.getTok().getLoc();
2993 APInt IntValue = Asm.getTok().getAPIntVal();
2994 Asm.Lex();
2995 if (!IntValue.isIntN(128))
2996 return Asm.Error(ExprLoc, "out of range literal value");
2997 if (!IntValue.isIntN(64)) {
2998 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
2999 lo = IntValue.getLoBits(64).getZExtValue();
3000 } else {
3001 hi = 0;
3002 lo = IntValue.getZExtValue();
3003 }
3004 return false;
3005}
3006
David Woodhoused6de0d92014-02-01 16:20:59 +00003007/// ParseDirectiveOctaValue
3008/// ::= .octa [ hexconstant (, hexconstant)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00003009
3010bool AsmParser::parseDirectiveOctaValue(StringRef IDVal) {
3011 auto parseOp = [&]() -> bool {
Nirav Davef43cc9f2016-10-10 15:24:54 +00003012 if (checkForValidSection())
3013 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003014 uint64_t hi, lo;
Paul Robinson01954692018-04-11 15:14:05 +00003015 if (parseHexOcta(*this, hi, lo))
3016 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003017 if (MAI.isLittleEndian()) {
3018 getStreamer().EmitIntValue(lo, 8);
3019 getStreamer().EmitIntValue(hi, 8);
3020 } else {
3021 getStreamer().EmitIntValue(hi, 8);
3022 getStreamer().EmitIntValue(lo, 8);
3023 }
3024 return false;
3025 };
David Woodhoused6de0d92014-02-01 16:20:59 +00003026
Nirav Dave1a9044b2016-10-24 14:35:29 +00003027 if (parseMany(parseOp))
3028 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
David Woodhoused6de0d92014-02-01 16:20:59 +00003029 return false;
3030}
3031
Petr Hosek4cb08ce2016-09-23 19:25:15 +00003032bool AsmParser::parseRealValue(const fltSemantics &Semantics, APInt &Res) {
3033 // We don't truly support arithmetic on floating point expressions, so we
3034 // have to manually parse unary prefixes.
3035 bool IsNeg = false;
3036 if (getLexer().is(AsmToken::Minus)) {
3037 Lexer.Lex();
3038 IsNeg = true;
3039 } else if (getLexer().is(AsmToken::Plus))
3040 Lexer.Lex();
3041
3042 if (Lexer.is(AsmToken::Error))
3043 return TokError(Lexer.getErr());
3044 if (Lexer.isNot(AsmToken::Integer) && Lexer.isNot(AsmToken::Real) &&
3045 Lexer.isNot(AsmToken::Identifier))
3046 return TokError("unexpected token in directive");
3047
3048 // Convert to an APFloat.
3049 APFloat Value(Semantics);
3050 StringRef IDVal = getTok().getString();
3051 if (getLexer().is(AsmToken::Identifier)) {
3052 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
3053 Value = APFloat::getInf(Semantics);
3054 else if (!IDVal.compare_lower("nan"))
3055 Value = APFloat::getNaN(Semantics, false, ~0);
3056 else
3057 return TokError("invalid floating point literal");
3058 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
3059 APFloat::opInvalidOp)
3060 return TokError("invalid floating point literal");
3061 if (IsNeg)
3062 Value.changeSign();
3063
3064 // Consume the numeric token.
3065 Lex();
3066
3067 Res = Value.bitcastToAPInt();
3068
3069 return false;
3070}
3071
Jim Grosbach4b905842013-09-20 23:08:21 +00003072/// parseDirectiveRealValue
Daniel Dunbar2af16532010-09-24 01:59:56 +00003073/// ::= (.single | .double) [ expression (, expression)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00003074bool AsmParser::parseDirectiveRealValue(StringRef IDVal,
3075 const fltSemantics &Semantics) {
3076 auto parseOp = [&]() -> bool {
3077 APInt AsInt;
3078 if (checkForValidSection() || parseRealValue(Semantics, AsInt))
Nirav Davef43cc9f2016-10-10 15:24:54 +00003079 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003080 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
3081 AsInt.getBitWidth() / 8);
3082 return false;
3083 };
Daniel Dunbar2af16532010-09-24 01:59:56 +00003084
Nirav Dave1a9044b2016-10-24 14:35:29 +00003085 if (parseMany(parseOp))
3086 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbar2af16532010-09-24 01:59:56 +00003087 return false;
3088}
3089
Jim Grosbach4b905842013-09-20 23:08:21 +00003090/// parseDirectiveZero
Rafael Espindola922e3f42010-09-16 15:03:59 +00003091/// ::= .zero expression
Jim Grosbach4b905842013-09-20 23:08:21 +00003092bool AsmParser::parseDirectiveZero() {
Petr Hosek67a94a72016-05-28 05:57:48 +00003093 SMLoc NumBytesLoc = Lexer.getLoc();
3094 const MCExpr *NumBytes;
Nirav Davef43cc9f2016-10-10 15:24:54 +00003095 if (checkForValidSection() || parseExpression(NumBytes))
Rafael Espindola922e3f42010-09-16 15:03:59 +00003096 return true;
3097
Rafael Espindolab91bac62010-10-05 19:42:57 +00003098 int64_t Val = 0;
3099 if (getLexer().is(AsmToken::Comma)) {
3100 Lex();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003101 if (parseAbsoluteExpression(Val))
Rafael Espindolab91bac62010-10-05 19:42:57 +00003102 return true;
3103 }
3104
Nirav Davea645433c2016-07-18 15:24:03 +00003105 if (parseToken(AsmToken::EndOfStatement,
3106 "unexpected token in '.zero' directive"))
3107 return true;
Petr Hosek67a94a72016-05-28 05:57:48 +00003108 getStreamer().emitFill(*NumBytes, Val, NumBytesLoc);
Rafael Espindola922e3f42010-09-16 15:03:59 +00003109
3110 return false;
3111}
3112
Jim Grosbach4b905842013-09-20 23:08:21 +00003113/// parseDirectiveFill
Roman Divackye33098f2013-09-24 17:44:41 +00003114/// ::= .fill expression [ , expression [ , expression ] ]
Jim Grosbach4b905842013-09-20 23:08:21 +00003115bool AsmParser::parseDirectiveFill() {
Petr Hosek67a94a72016-05-28 05:57:48 +00003116 SMLoc NumValuesLoc = Lexer.getLoc();
3117 const MCExpr *NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00003118 if (checkForValidSection() || parseExpression(NumValues))
Daniel Dunbara10e5192009-06-24 23:30:00 +00003119 return true;
3120
Roman Divackye33098f2013-09-24 17:44:41 +00003121 int64_t FillSize = 1;
3122 int64_t FillExpr = 0;
Michael J. Spencer530ce852010-10-09 11:00:50 +00003123
David Majnemer522d3db2014-02-01 07:19:38 +00003124 SMLoc SizeLoc, ExprLoc;
Daniel Dunbara10e5192009-06-24 23:30:00 +00003125
Nirav Dave1a9044b2016-10-24 14:35:29 +00003126 if (parseOptionalToken(AsmToken::Comma)) {
3127 SizeLoc = getTok().getLoc();
3128 if (parseAbsoluteExpression(FillSize))
Roman Divackye33098f2013-09-24 17:44:41 +00003129 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003130 if (parseOptionalToken(AsmToken::Comma)) {
3131 ExprLoc = getTok().getLoc();
3132 if (parseAbsoluteExpression(FillExpr))
Roman Divackye33098f2013-09-24 17:44:41 +00003133 return true;
Roman Divackye33098f2013-09-24 17:44:41 +00003134 }
3135 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003136 if (parseToken(AsmToken::EndOfStatement,
3137 "unexpected token in '.fill' directive"))
3138 return true;
Daniel Dunbara10e5192009-06-24 23:30:00 +00003139
David Majnemer522d3db2014-02-01 07:19:38 +00003140 if (FillSize < 0) {
3141 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
Petr Hosek6abd38b2016-05-28 08:20:08 +00003142 return false;
David Majnemer522d3db2014-02-01 07:19:38 +00003143 }
3144 if (FillSize > 8) {
3145 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
3146 FillSize = 8;
3147 }
Daniel Dunbara10e5192009-06-24 23:30:00 +00003148
David Majnemer522d3db2014-02-01 07:19:38 +00003149 if (!isUInt<32>(FillExpr) && FillSize > 4)
3150 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
3151
Petr Hosek67a94a72016-05-28 05:57:48 +00003152 getStreamer().emitFill(*NumValues, FillSize, FillExpr, NumValuesLoc);
Daniel Dunbara10e5192009-06-24 23:30:00 +00003153
3154 return false;
3155}
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00003156
Jim Grosbach4b905842013-09-20 23:08:21 +00003157/// parseDirectiveOrg
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00003158/// ::= .org expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00003159bool AsmParser::parseDirectiveOrg() {
Daniel Dunbar897ffad2009-08-31 08:09:28 +00003160 const MCExpr *Offset;
Oliver Stannard268f42f2016-12-14 10:43:58 +00003161 SMLoc OffsetLoc = Lexer.getLoc();
Nirav Davef43cc9f2016-10-10 15:24:54 +00003162 if (checkForValidSection() || parseExpression(Offset))
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00003163 return true;
3164
3165 // Parse optional fill expression.
3166 int64_t FillExpr = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003167 if (parseOptionalToken(AsmToken::Comma))
3168 if (parseAbsoluteExpression(FillExpr))
3169 return addErrorSuffix(" in '.org' directive");
3170 if (parseToken(AsmToken::EndOfStatement))
3171 return addErrorSuffix(" in '.org' directive");
Nirav Davea645433c2016-07-18 15:24:03 +00003172
Oliver Stannard268f42f2016-12-14 10:43:58 +00003173 getStreamer().emitValueToOffset(Offset, FillExpr, OffsetLoc);
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00003174 return false;
3175}
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003176
Jim Grosbach4b905842013-09-20 23:08:21 +00003177/// parseDirectiveAlign
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003178/// ::= {.align, ...} expression [ , expression [ , expression ]]
Jim Grosbach4b905842013-09-20 23:08:21 +00003179bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003180 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003181 int64_t Alignment;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003182 SMLoc MaxBytesLoc;
3183 bool HasFillExpr = false;
3184 int64_t FillExpr = 0;
3185 int64_t MaxBytesToFill = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003186
3187 auto parseAlign = [&]() -> bool {
Coby Tayreed483a102017-08-02 17:36:10 +00003188 if (parseAbsoluteExpression(Alignment))
Nirav Davea645433c2016-07-18 15:24:03 +00003189 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003190 if (parseOptionalToken(AsmToken::Comma)) {
3191 // The fill expression can be omitted while specifying a maximum number of
3192 // alignment bytes, e.g:
3193 // .align 3,,4
3194 if (getTok().isNot(AsmToken::Comma)) {
3195 HasFillExpr = true;
3196 if (parseAbsoluteExpression(FillExpr))
3197 return true;
3198 }
3199 if (parseOptionalToken(AsmToken::Comma))
3200 if (parseTokenLoc(MaxBytesLoc) ||
3201 parseAbsoluteExpression(MaxBytesToFill))
3202 return true;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003203 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003204 return parseToken(AsmToken::EndOfStatement);
3205 };
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003206
Coby Tayreed483a102017-08-02 17:36:10 +00003207 if (checkForValidSection())
3208 return addErrorSuffix(" in directive");
3209 // Ignore empty '.p2align' directives for GNU-as compatibility
3210 if (IsPow2 && (ValueSize == 1) && getTok().is(AsmToken::EndOfStatement)) {
3211 Warning(AlignmentLoc, "p2align directive with no operand(s) is ignored");
3212 return parseToken(AsmToken::EndOfStatement);
3213 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003214 if (parseAlign())
3215 return addErrorSuffix(" in directive");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003216
Nirav Dave2364748a2016-09-16 18:30:20 +00003217 // Always emit an alignment here even if we thrown an error.
3218 bool ReturnVal = false;
3219
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003220 // Compute alignment in bytes.
3221 if (IsPow2) {
3222 // FIXME: Diagnose overflow.
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003223 if (Alignment >= 32) {
Nirav Dave2364748a2016-09-16 18:30:20 +00003224 ReturnVal |= Error(AlignmentLoc, "invalid alignment value");
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003225 Alignment = 31;
3226 }
3227
Benjamin Kramer63951ad2009-09-06 09:35:10 +00003228 Alignment = 1ULL << Alignment;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00003229 } else {
Davide Italianocb2da712015-09-08 18:59:47 +00003230 // Reject alignments that aren't either a power of two or zero,
3231 // for gas compatibility. Alignment of zero is silently rounded
3232 // up to one.
3233 if (Alignment == 0)
3234 Alignment = 1;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00003235 if (!isPowerOf2_64(Alignment))
Nirav Dave2364748a2016-09-16 18:30:20 +00003236 ReturnVal |= Error(AlignmentLoc, "alignment must be a power of 2");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003237 }
3238
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003239 // Diagnose non-sensical max bytes to align.
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003240 if (MaxBytesLoc.isValid()) {
3241 if (MaxBytesToFill < 1) {
Nirav Dave2364748a2016-09-16 18:30:20 +00003242 ReturnVal |= Error(MaxBytesLoc,
3243 "alignment directive can never be satisfied in this "
Jim Grosbach4b905842013-09-20 23:08:21 +00003244 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar4abcccb2009-08-21 23:01:53 +00003245 MaxBytesToFill = 0;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003246 }
3247
3248 if (MaxBytesToFill >= Alignment) {
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +00003249 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
Jim Grosbach4b905842013-09-20 23:08:21 +00003250 "has no effect");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003251 MaxBytesToFill = 0;
3252 }
3253 }
3254
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003255 // Check whether we should use optimal code alignment for this .align
3256 // directive.
Eric Christopher445c9522016-10-14 05:47:37 +00003257 const MCSection *Section = getStreamer().getCurrentSectionOnly();
Saleem Abdulrasool7f2f9f42014-03-21 05:13:23 +00003258 assert(Section && "must have section to emit alignment");
3259 bool UseCodeAlign = Section->UseCodeAlign();
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003260 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
3261 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003262 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003263 } else {
Kevin Enderby7f993022010-02-25 18:46:04 +00003264 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnerc2b36752010-07-15 21:19:31 +00003265 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
3266 MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003267 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003268
Nirav Dave2364748a2016-09-16 18:30:20 +00003269 return ReturnVal;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003270}
3271
Jim Grosbach4b905842013-09-20 23:08:21 +00003272/// parseDirectiveFile
Paul Robinson29f5f982018-01-09 23:31:48 +00003273/// ::= .file filename
Scott Linder16c7bda2018-02-23 23:01:06 +00003274/// ::= .file number [directory] filename [md5 checksum] [source source-text]
Jim Grosbach4b905842013-09-20 23:08:21 +00003275bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003276 // FIXME: I'm not sure what this is.
3277 int64_t FileNumber = -1;
Eli Bendersky17233942013-01-15 22:59:42 +00003278 if (getLexer().is(AsmToken::Integer)) {
3279 FileNumber = getTok().getIntVal();
3280 Lex();
3281
Paul Robinsonb271f312018-03-29 17:16:41 +00003282 if (FileNumber < 0)
3283 return TokError("negative file number");
Eli Bendersky17233942013-01-15 22:59:42 +00003284 }
3285
Paul Robinson37fbb922018-06-20 16:12:03 +00003286 std::string Path;
Eli Bendersky17233942013-01-15 22:59:42 +00003287
3288 // Usually the directory and filename together, otherwise just the directory.
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003289 // Allow the strings to have escaped octal character sequence.
Nirav Davea645433c2016-07-18 15:24:03 +00003290 if (check(getTok().isNot(AsmToken::String),
3291 "unexpected token in '.file' directive") ||
3292 parseEscapedString(Path))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003293 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003294
3295 StringRef Directory;
3296 StringRef Filename;
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003297 std::string FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00003298 if (getLexer().is(AsmToken::String)) {
Nirav Davea645433c2016-07-18 15:24:03 +00003299 if (check(FileNumber == -1,
3300 "explicit path specified, but no file number") ||
3301 parseEscapedString(FilenameData))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003302 return true;
3303 Filename = FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00003304 Directory = Path;
Eli Bendersky17233942013-01-15 22:59:42 +00003305 } else {
3306 Filename = Path;
3307 }
3308
Paul Robinson01954692018-04-11 15:14:05 +00003309 uint64_t MD5Hi, MD5Lo;
3310 bool HasMD5 = false;
Scott Linder16c7bda2018-02-23 23:01:06 +00003311
3312 Optional<StringRef> Source;
3313 bool HasSource = false;
3314 std::string SourceString;
3315
3316 while (!parseOptionalToken(AsmToken::EndOfStatement)) {
Paul Robinson29f5f982018-01-09 23:31:48 +00003317 StringRef Keyword;
3318 if (check(getTok().isNot(AsmToken::Identifier),
3319 "unexpected token in '.file' directive") ||
Scott Linder16c7bda2018-02-23 23:01:06 +00003320 parseIdentifier(Keyword))
Paul Robinson29f5f982018-01-09 23:31:48 +00003321 return true;
Scott Linder16c7bda2018-02-23 23:01:06 +00003322 if (Keyword == "md5") {
Paul Robinson01954692018-04-11 15:14:05 +00003323 HasMD5 = true;
Scott Linder16c7bda2018-02-23 23:01:06 +00003324 if (check(FileNumber == -1,
3325 "MD5 checksum specified, but no file number") ||
Paul Robinson01954692018-04-11 15:14:05 +00003326 parseHexOcta(*this, MD5Hi, MD5Lo))
Scott Linder16c7bda2018-02-23 23:01:06 +00003327 return true;
3328 } else if (Keyword == "source") {
3329 HasSource = true;
3330 if (check(FileNumber == -1,
3331 "source specified, but no file number") ||
3332 check(getTok().isNot(AsmToken::String),
3333 "unexpected token in '.file' directive") ||
3334 parseEscapedString(SourceString))
3335 return true;
3336 } else {
3337 return TokError("unexpected token in '.file' directive");
3338 }
Paul Robinson29f5f982018-01-09 23:31:48 +00003339 }
Eli Bendersky17233942013-01-15 22:59:42 +00003340
Paul Robinson938d9a02018-03-22 15:48:01 +00003341 // In case there is a -g option as well as debug info from directive .file,
3342 // we turn off the -g option, directly use the existing debug info instead.
Paul Robinsoncc7344a2018-06-14 13:38:20 +00003343 // Also reset any implicit ".file 0" for the assembler source.
3344 if (Ctx.getGenDwarfForAssembly()) {
3345 Ctx.getMCDwarfLineTable(0).resetRootFile();
3346 Ctx.setGenDwarfForAssembly(false);
3347 }
Paul Robinson938d9a02018-03-22 15:48:01 +00003348
Eli Bendersky17233942013-01-15 22:59:42 +00003349 if (FileNumber == -1)
3350 getStreamer().EmitFileDirective(Filename);
3351 else {
Paul Robinson29f5f982018-01-09 23:31:48 +00003352 MD5::MD5Result *CKMem = nullptr;
Paul Robinson01954692018-04-11 15:14:05 +00003353 if (HasMD5) {
Paul Robinson29f5f982018-01-09 23:31:48 +00003354 CKMem = (MD5::MD5Result *)Ctx.allocate(sizeof(MD5::MD5Result), 1);
Paul Robinson01954692018-04-11 15:14:05 +00003355 for (unsigned i = 0; i != 8; ++i) {
3356 CKMem->Bytes[i] = uint8_t(MD5Hi >> ((7 - i) * 8));
3357 CKMem->Bytes[i + 8] = uint8_t(MD5Lo >> ((7 - i) * 8));
3358 }
Paul Robinson29f5f982018-01-09 23:31:48 +00003359 }
Scott Linder16c7bda2018-02-23 23:01:06 +00003360 if (HasSource) {
3361 char *SourceBuf = static_cast<char *>(Ctx.allocate(SourceString.size()));
3362 memcpy(SourceBuf, SourceString.data(), SourceString.size());
3363 Source = StringRef(SourceBuf, SourceString.size());
3364 }
Paul Robinsonb271f312018-03-29 17:16:41 +00003365 if (FileNumber == 0)
3366 getStreamer().emitDwarfFile0Directive(Directory, Filename, CKMem, Source);
3367 else {
3368 Expected<unsigned> FileNumOrErr = getStreamer().tryEmitDwarfFileDirective(
3369 FileNumber, Directory, Filename, CKMem, Source);
3370 if (!FileNumOrErr)
3371 return Error(DirectiveLoc, toString(FileNumOrErr.takeError()));
3372 FileNumber = FileNumOrErr.get();
3373 }
Paul Robinsoncc7344a2018-06-14 13:38:20 +00003374 // Alert the user if there are some .file directives with MD5 and some not.
3375 // But only do that once.
3376 if (!ReportedInconsistentMD5 && !Ctx.isDwarfMD5UsageConsistent(0)) {
3377 ReportedInconsistentMD5 = true;
3378 return Warning(DirectiveLoc, "inconsistent use of MD5 checksums");
3379 }
Eli Bendersky17233942013-01-15 22:59:42 +00003380 }
3381
3382 return false;
3383}
3384
Jim Grosbach4b905842013-09-20 23:08:21 +00003385/// parseDirectiveLine
Eli Bendersky17233942013-01-15 22:59:42 +00003386/// ::= .line [number]
Jim Grosbach4b905842013-09-20 23:08:21 +00003387bool AsmParser::parseDirectiveLine() {
Nirav Davea645433c2016-07-18 15:24:03 +00003388 int64_t LineNumber;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003389 if (getLexer().is(AsmToken::Integer)) {
Nirav Davea645433c2016-07-18 15:24:03 +00003390 if (parseIntToken(LineNumber, "unexpected token in '.line' directive"))
3391 return true;
Jim Grosbach4b905842013-09-20 23:08:21 +00003392 (void)LineNumber;
Eli Bendersky17233942013-01-15 22:59:42 +00003393 // FIXME: Do something with the .line.
3394 }
Nirav Davea645433c2016-07-18 15:24:03 +00003395 if (parseToken(AsmToken::EndOfStatement,
3396 "unexpected token in '.line' directive"))
3397 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003398
3399 return false;
3400}
3401
Jim Grosbach4b905842013-09-20 23:08:21 +00003402/// parseDirectiveLoc
Eli Bendersky17233942013-01-15 22:59:42 +00003403/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
3404/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
3405/// The first number is a file number, must have been previously assigned with
3406/// a .file directive, the second number is the line number and optionally the
3407/// third number is a column position (zero if not specified). The remaining
3408/// optional items are .loc sub-directives.
Jim Grosbach4b905842013-09-20 23:08:21 +00003409bool AsmParser::parseDirectiveLoc() {
Nirav Davea645433c2016-07-18 15:24:03 +00003410 int64_t FileNumber = 0, LineNumber = 0;
3411 SMLoc Loc = getTok().getLoc();
3412 if (parseIntToken(FileNumber, "unexpected token in '.loc' directive") ||
3413 check(FileNumber < 1, Loc,
3414 "file number less than one in '.loc' directive") ||
3415 check(!getContext().isValidDwarfFileNumber(FileNumber), Loc,
3416 "unassigned file number in '.loc' directive"))
3417 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003418
Nirav Davea645433c2016-07-18 15:24:03 +00003419 // optional
Eli Bendersky17233942013-01-15 22:59:42 +00003420 if (getLexer().is(AsmToken::Integer)) {
3421 LineNumber = getTok().getIntVal();
Adrian Prantl6ac40032013-09-26 23:37:11 +00003422 if (LineNumber < 0)
3423 return TokError("line number less than zero in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003424 Lex();
3425 }
3426
3427 int64_t ColumnPos = 0;
3428 if (getLexer().is(AsmToken::Integer)) {
3429 ColumnPos = getTok().getIntVal();
3430 if (ColumnPos < 0)
3431 return TokError("column position less than zero in '.loc' directive");
3432 Lex();
3433 }
3434
3435 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
3436 unsigned Isa = 0;
3437 int64_t Discriminator = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003438
Nirav Dave1a9044b2016-10-24 14:35:29 +00003439 auto parseLocOp = [&]() -> bool {
3440 StringRef Name;
3441 SMLoc Loc = getTok().getLoc();
3442 if (parseIdentifier(Name))
3443 return TokError("unexpected token in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003444
Nirav Dave1a9044b2016-10-24 14:35:29 +00003445 if (Name == "basic_block")
3446 Flags |= DWARF2_FLAG_BASIC_BLOCK;
3447 else if (Name == "prologue_end")
3448 Flags |= DWARF2_FLAG_PROLOGUE_END;
3449 else if (Name == "epilogue_begin")
3450 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
3451 else if (Name == "is_stmt") {
3452 Loc = getTok().getLoc();
3453 const MCExpr *Value;
3454 if (parseExpression(Value))
3455 return true;
3456 // The expression must be the constant 0 or 1.
3457 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3458 int Value = MCE->getValue();
3459 if (Value == 0)
3460 Flags &= ~DWARF2_FLAG_IS_STMT;
3461 else if (Value == 1)
3462 Flags |= DWARF2_FLAG_IS_STMT;
3463 else
3464 return Error(Loc, "is_stmt value not 0 or 1");
Craig Topperf15655b2013-04-22 04:22:40 +00003465 } else {
Nirav Dave1a9044b2016-10-24 14:35:29 +00003466 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
Eli Bendersky17233942013-01-15 22:59:42 +00003467 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003468 } else if (Name == "isa") {
3469 Loc = getTok().getLoc();
3470 const MCExpr *Value;
3471 if (parseExpression(Value))
3472 return true;
3473 // The expression must be a constant greater or equal to 0.
3474 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3475 int Value = MCE->getValue();
3476 if (Value < 0)
3477 return Error(Loc, "isa number less than zero");
3478 Isa = Value;
3479 } else {
3480 return Error(Loc, "isa number not a constant value");
3481 }
3482 } else if (Name == "discriminator") {
3483 if (parseAbsoluteExpression(Discriminator))
3484 return true;
3485 } else {
3486 return Error(Loc, "unknown sub-directive in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003487 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003488 return false;
3489 };
3490
Nirav Davee2369aa2016-10-26 17:28:58 +00003491 if (parseMany(parseLocOp, false /*hasComma*/))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003492 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003493
3494 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
3495 Isa, Discriminator, StringRef());
3496
3497 return false;
3498}
3499
Jim Grosbach4b905842013-09-20 23:08:21 +00003500/// parseDirectiveStabs
Eli Bendersky17233942013-01-15 22:59:42 +00003501/// ::= .stabs string, number, number, number
Jim Grosbach4b905842013-09-20 23:08:21 +00003502bool AsmParser::parseDirectiveStabs() {
Eli Bendersky17233942013-01-15 22:59:42 +00003503 return TokError("unsupported directive '.stabs'");
3504}
3505
Reid Kleckner2214ed82016-01-29 00:49:42 +00003506/// parseDirectiveCVFile
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003507/// ::= .cv_file number filename [checksum] [checksumkind]
Reid Kleckner2214ed82016-01-29 00:49:42 +00003508bool AsmParser::parseDirectiveCVFile() {
Nirav Davea645433c2016-07-18 15:24:03 +00003509 SMLoc FileNumberLoc = getTok().getLoc();
3510 int64_t FileNumber;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003511 std::string Filename;
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003512 std::string Checksum;
3513 int64_t ChecksumKind = 0;
Nirav Davea645433c2016-07-18 15:24:03 +00003514
3515 if (parseIntToken(FileNumber,
3516 "expected file number in '.cv_file' directive") ||
3517 check(FileNumber < 1, FileNumberLoc, "file number less than one") ||
3518 check(getTok().isNot(AsmToken::String),
3519 "unexpected token in '.cv_file' directive") ||
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003520 parseEscapedString(Filename))
Reid Klecknera5b1eef2016-08-26 17:58:37 +00003521 return true;
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003522 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
3523 if (check(getTok().isNot(AsmToken::String),
3524 "unexpected token in '.cv_file' directive") ||
3525 parseEscapedString(Checksum) ||
3526 parseIntToken(ChecksumKind,
3527 "expected checksum kind in '.cv_file' directive") ||
3528 parseToken(AsmToken::EndOfStatement,
3529 "unexpected token in '.cv_file' directive"))
3530 return true;
3531 }
Nirav Dave1ab71992016-07-18 19:35:21 +00003532
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003533 Checksum = fromHex(Checksum);
3534 void *CKMem = Ctx.allocate(Checksum.size(), 1);
3535 memcpy(CKMem, Checksum.data(), Checksum.size());
3536 ArrayRef<uint8_t> ChecksumAsBytes(reinterpret_cast<const uint8_t *>(CKMem),
3537 Checksum.size());
3538
3539 if (!getStreamer().EmitCVFileDirective(FileNumber, Filename, ChecksumAsBytes,
3540 static_cast<uint8_t>(ChecksumKind)))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003541 return Error(FileNumberLoc, "file number already allocated");
Reid Kleckner2214ed82016-01-29 00:49:42 +00003542
3543 return false;
3544}
3545
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003546bool AsmParser::parseCVFunctionId(int64_t &FunctionId,
3547 StringRef DirectiveName) {
3548 SMLoc Loc;
3549 return parseTokenLoc(Loc) ||
3550 parseIntToken(FunctionId, "expected function id in '" + DirectiveName +
3551 "' directive") ||
3552 check(FunctionId < 0 || FunctionId >= UINT_MAX, Loc,
3553 "expected function id within range [0, UINT_MAX)");
3554}
3555
3556bool AsmParser::parseCVFileId(int64_t &FileNumber, StringRef DirectiveName) {
3557 SMLoc Loc;
3558 return parseTokenLoc(Loc) ||
3559 parseIntToken(FileNumber, "expected integer in '" + DirectiveName +
3560 "' directive") ||
3561 check(FileNumber < 1, Loc, "file number less than one in '" +
3562 DirectiveName + "' directive") ||
3563 check(!getCVContext().isValidFileNumber(FileNumber), Loc,
3564 "unassigned file number in '" + DirectiveName + "' directive");
3565}
3566
3567/// parseDirectiveCVFuncId
3568/// ::= .cv_func_id FunctionId
3569///
3570/// Introduces a function ID that can be used with .cv_loc.
3571bool AsmParser::parseDirectiveCVFuncId() {
3572 SMLoc FunctionIdLoc = getTok().getLoc();
3573 int64_t FunctionId;
3574
3575 if (parseCVFunctionId(FunctionId, ".cv_func_id") ||
3576 parseToken(AsmToken::EndOfStatement,
3577 "unexpected token in '.cv_func_id' directive"))
3578 return true;
3579
3580 if (!getStreamer().EmitCVFuncIdDirective(FunctionId))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003581 return Error(FunctionIdLoc, "function id already allocated");
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003582
3583 return false;
3584}
3585
3586/// parseDirectiveCVInlineSiteId
3587/// ::= .cv_inline_site_id FunctionId
3588/// "within" IAFunc
3589/// "inlined_at" IAFile IALine [IACol]
3590///
3591/// Introduces a function ID that can be used with .cv_loc. Includes "inlined
3592/// at" source location information for use in the line table of the caller,
3593/// whether the caller is a real function or another inlined call site.
3594bool AsmParser::parseDirectiveCVInlineSiteId() {
3595 SMLoc FunctionIdLoc = getTok().getLoc();
3596 int64_t FunctionId;
3597 int64_t IAFunc;
3598 int64_t IAFile;
3599 int64_t IALine;
3600 int64_t IACol = 0;
3601
3602 // FunctionId
3603 if (parseCVFunctionId(FunctionId, ".cv_inline_site_id"))
3604 return true;
3605
3606 // "within"
3607 if (check((getLexer().isNot(AsmToken::Identifier) ||
3608 getTok().getIdentifier() != "within"),
3609 "expected 'within' identifier in '.cv_inline_site_id' directive"))
3610 return true;
3611 Lex();
3612
3613 // IAFunc
3614 if (parseCVFunctionId(IAFunc, ".cv_inline_site_id"))
3615 return true;
3616
3617 // "inlined_at"
3618 if (check((getLexer().isNot(AsmToken::Identifier) ||
3619 getTok().getIdentifier() != "inlined_at"),
3620 "expected 'inlined_at' identifier in '.cv_inline_site_id' "
3621 "directive") )
3622 return true;
3623 Lex();
3624
3625 // IAFile IALine
3626 if (parseCVFileId(IAFile, ".cv_inline_site_id") ||
3627 parseIntToken(IALine, "expected line number after 'inlined_at'"))
3628 return true;
3629
3630 // [IACol]
3631 if (getLexer().is(AsmToken::Integer)) {
3632 IACol = getTok().getIntVal();
3633 Lex();
3634 }
3635
3636 if (parseToken(AsmToken::EndOfStatement,
3637 "unexpected token in '.cv_inline_site_id' directive"))
3638 return true;
3639
3640 if (!getStreamer().EmitCVInlineSiteIdDirective(FunctionId, IAFunc, IAFile,
3641 IALine, IACol, FunctionIdLoc))
Nirav Dave2364748a2016-09-16 18:30:20 +00003642 return Error(FunctionIdLoc, "function id already allocated");
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003643
3644 return false;
3645}
3646
Reid Kleckner2214ed82016-01-29 00:49:42 +00003647/// parseDirectiveCVLoc
3648/// ::= .cv_loc FunctionId FileNumber [LineNumber] [ColumnPos] [prologue_end]
3649/// [is_stmt VALUE]
3650/// The first number is a file number, must have been previously assigned with
3651/// a .file directive, the second number is the line number and optionally the
3652/// third number is a column position (zero if not specified). The remaining
3653/// optional items are .loc sub-directives.
3654bool AsmParser::parseDirectiveCVLoc() {
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003655 SMLoc DirectiveLoc = getTok().getLoc();
Nirav Davea645433c2016-07-18 15:24:03 +00003656 int64_t FunctionId, FileNumber;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003657 if (parseCVFunctionId(FunctionId, ".cv_loc") ||
3658 parseCVFileId(FileNumber, ".cv_loc"))
Nirav Davea645433c2016-07-18 15:24:03 +00003659 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003660
3661 int64_t LineNumber = 0;
3662 if (getLexer().is(AsmToken::Integer)) {
3663 LineNumber = getTok().getIntVal();
3664 if (LineNumber < 0)
3665 return TokError("line number less than zero in '.cv_loc' directive");
3666 Lex();
3667 }
3668
3669 int64_t ColumnPos = 0;
3670 if (getLexer().is(AsmToken::Integer)) {
3671 ColumnPos = getTok().getIntVal();
3672 if (ColumnPos < 0)
3673 return TokError("column position less than zero in '.cv_loc' directive");
3674 Lex();
3675 }
3676
3677 bool PrologueEnd = false;
3678 uint64_t IsStmt = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003679
3680 auto parseOp = [&]() -> bool {
Reid Kleckner2214ed82016-01-29 00:49:42 +00003681 StringRef Name;
3682 SMLoc Loc = getTok().getLoc();
3683 if (parseIdentifier(Name))
3684 return TokError("unexpected token in '.cv_loc' directive");
Reid Kleckner2214ed82016-01-29 00:49:42 +00003685 if (Name == "prologue_end")
3686 PrologueEnd = true;
3687 else if (Name == "is_stmt") {
3688 Loc = getTok().getLoc();
3689 const MCExpr *Value;
3690 if (parseExpression(Value))
3691 return true;
3692 // The expression must be the constant 0 or 1.
3693 IsStmt = ~0ULL;
3694 if (const auto *MCE = dyn_cast<MCConstantExpr>(Value))
3695 IsStmt = MCE->getValue();
3696
3697 if (IsStmt > 1)
3698 return Error(Loc, "is_stmt value not 0 or 1");
3699 } else {
3700 return Error(Loc, "unknown sub-directive in '.cv_loc' directive");
3701 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003702 return false;
3703 };
3704
3705 if (parseMany(parseOp, false /*hasComma*/))
3706 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003707
3708 getStreamer().EmitCVLocDirective(FunctionId, FileNumber, LineNumber,
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003709 ColumnPos, PrologueEnd, IsStmt, StringRef(),
3710 DirectiveLoc);
Reid Kleckner2214ed82016-01-29 00:49:42 +00003711 return false;
3712}
3713
3714/// parseDirectiveCVLinetable
3715/// ::= .cv_linetable FunctionId, FnStart, FnEnd
3716bool AsmParser::parseDirectiveCVLinetable() {
Nirav Davea645433c2016-07-18 15:24:03 +00003717 int64_t FunctionId;
3718 StringRef FnStartName, FnEndName;
3719 SMLoc Loc = getTok().getLoc();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003720 if (parseCVFunctionId(FunctionId, ".cv_linetable") ||
Nirav Davea645433c2016-07-18 15:24:03 +00003721 parseToken(AsmToken::Comma,
3722 "unexpected token in '.cv_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003723 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3724 "expected identifier in directive") ||
Nirav Davea645433c2016-07-18 15:24:03 +00003725 parseToken(AsmToken::Comma,
3726 "unexpected token in '.cv_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003727 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3728 "expected identifier in directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00003729 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003730
3731 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3732 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
3733
3734 getStreamer().EmitCVLinetableDirective(FunctionId, FnStartSym, FnEndSym);
3735 return false;
3736}
3737
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003738/// parseDirectiveCVInlineLinetable
David Majnemerc9911f22016-02-02 19:22:34 +00003739/// ::= .cv_inline_linetable PrimaryFunctionId FileId LineNum FnStart FnEnd
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003740bool AsmParser::parseDirectiveCVInlineLinetable() {
Nirav Davea645433c2016-07-18 15:24:03 +00003741 int64_t PrimaryFunctionId, SourceFileId, SourceLineNum;
3742 StringRef FnStartName, FnEndName;
3743 SMLoc Loc = getTok().getLoc();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003744 if (parseCVFunctionId(PrimaryFunctionId, ".cv_inline_linetable") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003745 parseTokenLoc(Loc) ||
Nirav Davea645433c2016-07-18 15:24:03 +00003746 parseIntToken(
3747 SourceFileId,
3748 "expected SourceField in '.cv_inline_linetable' directive") ||
3749 check(SourceFileId <= 0, Loc,
3750 "File id less than zero in '.cv_inline_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003751 parseTokenLoc(Loc) ||
Nirav Davea645433c2016-07-18 15:24:03 +00003752 parseIntToken(
3753 SourceLineNum,
3754 "expected SourceLineNum in '.cv_inline_linetable' directive") ||
3755 check(SourceLineNum < 0, Loc,
3756 "Line number less than zero in '.cv_inline_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003757 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3758 "expected identifier in directive") ||
3759 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3760 "expected identifier in directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00003761 return true;
David Majnemerc9911f22016-02-02 19:22:34 +00003762
Nirav Davea645433c2016-07-18 15:24:03 +00003763 if (parseToken(AsmToken::EndOfStatement, "Expected End of Statement"))
3764 return true;
3765
3766 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3767 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
Reid Kleckner1fcd6102016-02-02 17:41:18 +00003768 getStreamer().EmitCVInlineLinetableDirective(PrimaryFunctionId, SourceFileId,
3769 SourceLineNum, FnStartSym,
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003770 FnEndSym);
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003771 return false;
3772}
3773
David Majnemer408b5e62016-02-05 01:55:49 +00003774/// parseDirectiveCVDefRange
3775/// ::= .cv_def_range RangeStart RangeEnd (GapStart GapEnd)*, bytes*
3776bool AsmParser::parseDirectiveCVDefRange() {
3777 SMLoc Loc;
3778 std::vector<std::pair<const MCSymbol *, const MCSymbol *>> Ranges;
3779 while (getLexer().is(AsmToken::Identifier)) {
3780 Loc = getLexer().getLoc();
3781 StringRef GapStartName;
3782 if (parseIdentifier(GapStartName))
3783 return Error(Loc, "expected identifier in directive");
3784 MCSymbol *GapStartSym = getContext().getOrCreateSymbol(GapStartName);
3785
3786 Loc = getLexer().getLoc();
3787 StringRef GapEndName;
3788 if (parseIdentifier(GapEndName))
3789 return Error(Loc, "expected identifier in directive");
3790 MCSymbol *GapEndSym = getContext().getOrCreateSymbol(GapEndName);
3791
3792 Ranges.push_back({GapStartSym, GapEndSym});
3793 }
3794
David Majnemer408b5e62016-02-05 01:55:49 +00003795 std::string FixedSizePortion;
Nirav Davea645433c2016-07-18 15:24:03 +00003796 if (parseToken(AsmToken::Comma, "unexpected token in directive") ||
3797 parseEscapedString(FixedSizePortion))
David Majnemer408b5e62016-02-05 01:55:49 +00003798 return true;
David Majnemer408b5e62016-02-05 01:55:49 +00003799
3800 getStreamer().EmitCVDefRangeDirective(Ranges, FixedSizePortion);
3801 return false;
3802}
3803
Reid Kleckner2214ed82016-01-29 00:49:42 +00003804/// parseDirectiveCVStringTable
3805/// ::= .cv_stringtable
3806bool AsmParser::parseDirectiveCVStringTable() {
3807 getStreamer().EmitCVStringTableDirective();
3808 return false;
3809}
3810
3811/// parseDirectiveCVFileChecksums
3812/// ::= .cv_filechecksums
3813bool AsmParser::parseDirectiveCVFileChecksums() {
3814 getStreamer().EmitCVFileChecksumsDirective();
3815 return false;
3816}
3817
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003818/// parseDirectiveCVFileChecksumOffset
3819/// ::= .cv_filechecksumoffset fileno
3820bool AsmParser::parseDirectiveCVFileChecksumOffset() {
3821 int64_t FileNo;
3822 if (parseIntToken(FileNo, "expected identifier in directive"))
3823 return true;
3824 if (parseToken(AsmToken::EndOfStatement, "Expected End of Statement"))
3825 return true;
3826 getStreamer().EmitCVFileChecksumOffsetDirective(FileNo);
3827 return false;
3828}
3829
Reid Kleckner9cdd4df2017-10-11 21:24:33 +00003830/// parseDirectiveCVFPOData
3831/// ::= .cv_fpo_data procsym
3832bool AsmParser::parseDirectiveCVFPOData() {
3833 SMLoc DirLoc = getLexer().getLoc();
3834 StringRef ProcName;
3835 if (parseIdentifier(ProcName))
3836 return TokError("expected symbol name");
3837 if (parseEOL("unexpected tokens"))
3838 return addErrorSuffix(" in '.cv_fpo_data' directive");
3839 MCSymbol *ProcSym = getContext().getOrCreateSymbol(ProcName);
3840 getStreamer().EmitCVFPOData(ProcSym, DirLoc);
3841 return false;
3842}
3843
Jim Grosbach4b905842013-09-20 23:08:21 +00003844/// parseDirectiveCFISections
Eli Bendersky17233942013-01-15 22:59:42 +00003845/// ::= .cfi_sections section [, section]
Jim Grosbach4b905842013-09-20 23:08:21 +00003846bool AsmParser::parseDirectiveCFISections() {
Eli Bendersky17233942013-01-15 22:59:42 +00003847 StringRef Name;
3848 bool EH = false;
3849 bool Debug = false;
3850
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003851 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003852 return TokError("Expected an identifier");
3853
3854 if (Name == ".eh_frame")
3855 EH = true;
3856 else if (Name == ".debug_frame")
3857 Debug = true;
3858
3859 if (getLexer().is(AsmToken::Comma)) {
3860 Lex();
3861
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003862 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003863 return TokError("Expected an identifier");
3864
3865 if (Name == ".eh_frame")
3866 EH = true;
3867 else if (Name == ".debug_frame")
3868 Debug = true;
3869 }
3870
3871 getStreamer().EmitCFISections(EH, Debug);
3872 return false;
3873}
3874
Jim Grosbach4b905842013-09-20 23:08:21 +00003875/// parseDirectiveCFIStartProc
David Majnemere035cf92014-01-27 17:20:25 +00003876/// ::= .cfi_startproc [simple]
Jim Grosbach4b905842013-09-20 23:08:21 +00003877bool AsmParser::parseDirectiveCFIStartProc() {
David Majnemere035cf92014-01-27 17:20:25 +00003878 StringRef Simple;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003879 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
3880 if (check(parseIdentifier(Simple) || Simple != "simple",
3881 "unexpected token") ||
3882 parseToken(AsmToken::EndOfStatement))
3883 return addErrorSuffix(" in '.cfi_startproc' directive");
3884 }
Nirav Davea645433c2016-07-18 15:24:03 +00003885
Oliver Stannardcf6bfb12014-11-03 12:19:03 +00003886 getStreamer().EmitCFIStartProc(!Simple.empty());
Eli Bendersky17233942013-01-15 22:59:42 +00003887 return false;
3888}
3889
Jim Grosbach4b905842013-09-20 23:08:21 +00003890/// parseDirectiveCFIEndProc
Eli Bendersky17233942013-01-15 22:59:42 +00003891/// ::= .cfi_endproc
Jim Grosbach4b905842013-09-20 23:08:21 +00003892bool AsmParser::parseDirectiveCFIEndProc() {
Eli Bendersky17233942013-01-15 22:59:42 +00003893 getStreamer().EmitCFIEndProc();
3894 return false;
3895}
3896
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003897/// parse register name or number.
Jim Grosbach4b905842013-09-20 23:08:21 +00003898bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
Eli Bendersky17233942013-01-15 22:59:42 +00003899 SMLoc DirectiveLoc) {
3900 unsigned RegNo;
3901
3902 if (getLexer().isNot(AsmToken::Integer)) {
3903 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
3904 return true;
Bill Wendlingbc07a892013-06-18 07:20:20 +00003905 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
Eli Bendersky17233942013-01-15 22:59:42 +00003906 } else
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003907 return parseAbsoluteExpression(Register);
Eli Bendersky17233942013-01-15 22:59:42 +00003908
3909 return false;
3910}
3911
Jim Grosbach4b905842013-09-20 23:08:21 +00003912/// parseDirectiveCFIDefCfa
Eli Bendersky17233942013-01-15 22:59:42 +00003913/// ::= .cfi_def_cfa register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003914bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003915 int64_t Register = 0, Offset = 0;
3916 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3917 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3918 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003919 return true;
3920
3921 getStreamer().EmitCFIDefCfa(Register, Offset);
3922 return false;
3923}
3924
Jim Grosbach4b905842013-09-20 23:08:21 +00003925/// parseDirectiveCFIDefCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003926/// ::= .cfi_def_cfa_offset offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003927bool AsmParser::parseDirectiveCFIDefCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00003928 int64_t Offset = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003929 if (parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003930 return true;
3931
3932 getStreamer().EmitCFIDefCfaOffset(Offset);
3933 return false;
3934}
3935
Jim Grosbach4b905842013-09-20 23:08:21 +00003936/// parseDirectiveCFIRegister
Eli Bendersky17233942013-01-15 22:59:42 +00003937/// ::= .cfi_register register, register
Jim Grosbach4b905842013-09-20 23:08:21 +00003938bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003939 int64_t Register1 = 0, Register2 = 0;
3940 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc) ||
3941 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3942 parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003943 return true;
3944
3945 getStreamer().EmitCFIRegister(Register1, Register2);
3946 return false;
3947}
3948
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00003949/// parseDirectiveCFIWindowSave
3950/// ::= .cfi_window_save
3951bool AsmParser::parseDirectiveCFIWindowSave() {
3952 getStreamer().EmitCFIWindowSave();
3953 return false;
3954}
3955
Jim Grosbach4b905842013-09-20 23:08:21 +00003956/// parseDirectiveCFIAdjustCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003957/// ::= .cfi_adjust_cfa_offset adjustment
Jim Grosbach4b905842013-09-20 23:08:21 +00003958bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00003959 int64_t Adjustment = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003960 if (parseAbsoluteExpression(Adjustment))
Eli Bendersky17233942013-01-15 22:59:42 +00003961 return true;
3962
3963 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3964 return false;
3965}
3966
Jim Grosbach4b905842013-09-20 23:08:21 +00003967/// parseDirectiveCFIDefCfaRegister
Eli Bendersky17233942013-01-15 22:59:42 +00003968/// ::= .cfi_def_cfa_register register
Jim Grosbach4b905842013-09-20 23:08:21 +00003969bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003970 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003971 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003972 return true;
3973
3974 getStreamer().EmitCFIDefCfaRegister(Register);
3975 return false;
3976}
3977
Jim Grosbach4b905842013-09-20 23:08:21 +00003978/// parseDirectiveCFIOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003979/// ::= .cfi_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003980bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003981 int64_t Register = 0;
3982 int64_t Offset = 0;
3983
Nirav Davea645433c2016-07-18 15:24:03 +00003984 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3985 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3986 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003987 return true;
3988
3989 getStreamer().EmitCFIOffset(Register, Offset);
3990 return false;
3991}
3992
Jim Grosbach4b905842013-09-20 23:08:21 +00003993/// parseDirectiveCFIRelOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003994/// ::= .cfi_rel_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003995bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003996 int64_t Register = 0, Offset = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003997
Nirav Davea645433c2016-07-18 15:24:03 +00003998 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3999 parseToken(AsmToken::Comma, "unexpected token in directive") ||
4000 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00004001 return true;
4002
4003 getStreamer().EmitCFIRelOffset(Register, Offset);
4004 return false;
4005}
4006
4007static bool isValidEncoding(int64_t Encoding) {
4008 if (Encoding & ~0xff)
4009 return false;
4010
4011 if (Encoding == dwarf::DW_EH_PE_omit)
4012 return true;
4013
4014 const unsigned Format = Encoding & 0xf;
4015 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
4016 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
4017 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
4018 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
4019 return false;
4020
4021 const unsigned Application = Encoding & 0x70;
4022 if (Application != dwarf::DW_EH_PE_absptr &&
4023 Application != dwarf::DW_EH_PE_pcrel)
4024 return false;
4025
4026 return true;
4027}
4028
Jim Grosbach4b905842013-09-20 23:08:21 +00004029/// parseDirectiveCFIPersonalityOrLsda
Eli Bendersky17233942013-01-15 22:59:42 +00004030/// IsPersonality true for cfi_personality, false for cfi_lsda
4031/// ::= .cfi_personality encoding, [symbol_name]
4032/// ::= .cfi_lsda encoding, [symbol_name]
Jim Grosbach4b905842013-09-20 23:08:21 +00004033bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
Eli Bendersky17233942013-01-15 22:59:42 +00004034 int64_t Encoding = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004035 if (parseAbsoluteExpression(Encoding))
Eli Bendersky17233942013-01-15 22:59:42 +00004036 return true;
4037 if (Encoding == dwarf::DW_EH_PE_omit)
4038 return false;
4039
Eli Bendersky17233942013-01-15 22:59:42 +00004040 StringRef Name;
Nirav Davea645433c2016-07-18 15:24:03 +00004041 if (check(!isValidEncoding(Encoding), "unsupported encoding.") ||
4042 parseToken(AsmToken::Comma, "unexpected token in directive") ||
4043 check(parseIdentifier(Name), "expected identifier in directive"))
4044 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004045
Jim Grosbach6f482002015-05-18 18:43:14 +00004046 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Eli Bendersky17233942013-01-15 22:59:42 +00004047
4048 if (IsPersonality)
4049 getStreamer().EmitCFIPersonality(Sym, Encoding);
4050 else
4051 getStreamer().EmitCFILsda(Sym, Encoding);
4052 return false;
4053}
4054
Jim Grosbach4b905842013-09-20 23:08:21 +00004055/// parseDirectiveCFIRememberState
Eli Bendersky17233942013-01-15 22:59:42 +00004056/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00004057bool AsmParser::parseDirectiveCFIRememberState() {
Eli Bendersky17233942013-01-15 22:59:42 +00004058 getStreamer().EmitCFIRememberState();
4059 return false;
4060}
4061
Jim Grosbach4b905842013-09-20 23:08:21 +00004062/// parseDirectiveCFIRestoreState
Eli Bendersky17233942013-01-15 22:59:42 +00004063/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00004064bool AsmParser::parseDirectiveCFIRestoreState() {
Eli Bendersky17233942013-01-15 22:59:42 +00004065 getStreamer().EmitCFIRestoreState();
4066 return false;
4067}
4068
Jim Grosbach4b905842013-09-20 23:08:21 +00004069/// parseDirectiveCFISameValue
Eli Bendersky17233942013-01-15 22:59:42 +00004070/// ::= .cfi_same_value register
Jim Grosbach4b905842013-09-20 23:08:21 +00004071bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004072 int64_t Register = 0;
4073
Jim Grosbach4b905842013-09-20 23:08:21 +00004074 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00004075 return true;
4076
4077 getStreamer().EmitCFISameValue(Register);
4078 return false;
4079}
4080
Jim Grosbach4b905842013-09-20 23:08:21 +00004081/// parseDirectiveCFIRestore
Eli Bendersky17233942013-01-15 22:59:42 +00004082/// ::= .cfi_restore register
Jim Grosbach4b905842013-09-20 23:08:21 +00004083bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004084 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00004085 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00004086 return true;
4087
4088 getStreamer().EmitCFIRestore(Register);
4089 return false;
4090}
4091
Jim Grosbach4b905842013-09-20 23:08:21 +00004092/// parseDirectiveCFIEscape
Eli Bendersky17233942013-01-15 22:59:42 +00004093/// ::= .cfi_escape expression[,...]
Jim Grosbach4b905842013-09-20 23:08:21 +00004094bool AsmParser::parseDirectiveCFIEscape() {
Eli Bendersky17233942013-01-15 22:59:42 +00004095 std::string Values;
4096 int64_t CurrValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004097 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00004098 return true;
4099
4100 Values.push_back((uint8_t)CurrValue);
4101
4102 while (getLexer().is(AsmToken::Comma)) {
4103 Lex();
4104
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004105 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00004106 return true;
4107
4108 Values.push_back((uint8_t)CurrValue);
4109 }
4110
4111 getStreamer().EmitCFIEscape(Values);
4112 return false;
4113}
4114
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +00004115/// parseDirectiveCFIReturnColumn
4116/// ::= .cfi_return_column register
4117bool AsmParser::parseDirectiveCFIReturnColumn(SMLoc DirectiveLoc) {
4118 int64_t Register = 0;
4119 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
4120 return true;
4121 getStreamer().EmitCFIReturnColumn(Register);
4122 return false;
4123}
4124
Jim Grosbach4b905842013-09-20 23:08:21 +00004125/// parseDirectiveCFISignalFrame
Eli Bendersky17233942013-01-15 22:59:42 +00004126/// ::= .cfi_signal_frame
Jim Grosbach4b905842013-09-20 23:08:21 +00004127bool AsmParser::parseDirectiveCFISignalFrame() {
Nirav Davea645433c2016-07-18 15:24:03 +00004128 if (parseToken(AsmToken::EndOfStatement,
4129 "unexpected token in '.cfi_signal_frame'"))
4130 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004131
4132 getStreamer().EmitCFISignalFrame();
4133 return false;
4134}
4135
Jim Grosbach4b905842013-09-20 23:08:21 +00004136/// parseDirectiveCFIUndefined
Eli Bendersky17233942013-01-15 22:59:42 +00004137/// ::= .cfi_undefined register
Jim Grosbach4b905842013-09-20 23:08:21 +00004138bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004139 int64_t Register = 0;
4140
Jim Grosbach4b905842013-09-20 23:08:21 +00004141 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00004142 return true;
4143
4144 getStreamer().EmitCFIUndefined(Register);
4145 return false;
4146}
4147
Michael Zuckerman56704612017-05-01 13:20:12 +00004148/// parseDirectiveAltmacro
4149/// ::= .altmacro
4150/// ::= .noaltmacro
4151bool AsmParser::parseDirectiveAltmacro(StringRef Directive) {
4152 if (getLexer().isNot(AsmToken::EndOfStatement))
4153 return TokError("unexpected token in '" + Directive + "' directive");
4154 if (Directive == ".altmacro")
4155 getLexer().SetAltMacroMode(true);
4156 else
4157 getLexer().SetAltMacroMode(false);
4158 return false;
4159}
4160
Jim Grosbach4b905842013-09-20 23:08:21 +00004161/// parseDirectiveMacrosOnOff
Eli Bendersky17233942013-01-15 22:59:42 +00004162/// ::= .macros_on
4163/// ::= .macros_off
Jim Grosbach4b905842013-09-20 23:08:21 +00004164bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
Nirav Davea645433c2016-07-18 15:24:03 +00004165 if (parseToken(AsmToken::EndOfStatement,
4166 "unexpected token in '" + Directive + "' directive"))
4167 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004168
Jim Grosbach4b905842013-09-20 23:08:21 +00004169 setMacrosEnabled(Directive == ".macros_on");
Eli Bendersky17233942013-01-15 22:59:42 +00004170 return false;
4171}
4172
Jim Grosbach4b905842013-09-20 23:08:21 +00004173/// parseDirectiveMacro
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00004174/// ::= .macro name[,] [parameters]
Jim Grosbach4b905842013-09-20 23:08:21 +00004175bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004176 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004177 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00004178 return TokError("expected identifier in '.macro' directive");
4179
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00004180 if (getLexer().is(AsmToken::Comma))
4181 Lex();
4182
Eli Bendersky17233942013-01-15 22:59:42 +00004183 MCAsmMacroParameters Parameters;
David Majnemer91fc4c22014-01-29 18:57:46 +00004184 while (getLexer().isNot(AsmToken::EndOfStatement)) {
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00004185
Alexander Kornienko8c0809c2015-01-15 11:41:30 +00004186 if (!Parameters.empty() && Parameters.back().Vararg)
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00004187 return Error(Lexer.getLoc(),
4188 "Vararg parameter '" + Parameters.back().Name +
4189 "' should be last one in the list of parameters.");
4190
David Majnemer91fc4c22014-01-29 18:57:46 +00004191 MCAsmMacroParameter Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00004192 if (parseIdentifier(Parameter.Name))
David Majnemer91fc4c22014-01-29 18:57:46 +00004193 return TokError("expected identifier in '.macro' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00004194
Coby Tayreebedaae02017-04-08 20:29:03 +00004195 // Emit an error if two (or more) named parameters share the same name
4196 for (const MCAsmMacroParameter& CurrParam : Parameters)
4197 if (CurrParam.Name.equals(Parameter.Name))
4198 return TokError("macro '" + Name + "' has multiple parameters"
4199 " named '" + Parameter.Name + "'");
4200
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00004201 if (Lexer.is(AsmToken::Colon)) {
4202 Lex(); // consume ':'
4203
4204 SMLoc QualLoc;
4205 StringRef Qualifier;
4206
4207 QualLoc = Lexer.getLoc();
4208 if (parseIdentifier(Qualifier))
4209 return Error(QualLoc, "missing parameter qualifier for "
4210 "'" + Parameter.Name + "' in macro '" + Name + "'");
4211
4212 if (Qualifier == "req")
4213 Parameter.Required = true;
Kevin Enderbye3c13462014-08-04 23:14:37 +00004214 else if (Qualifier == "vararg")
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00004215 Parameter.Vararg = true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00004216 else
4217 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
4218 "for '" + Parameter.Name + "' in macro '" + Name + "'");
4219 }
4220
David Majnemer91fc4c22014-01-29 18:57:46 +00004221 if (getLexer().is(AsmToken::Equal)) {
4222 Lex();
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00004223
4224 SMLoc ParamLoc;
4225
4226 ParamLoc = Lexer.getLoc();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00004227 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
David Majnemer91fc4c22014-01-29 18:57:46 +00004228 return true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00004229
4230 if (Parameter.Required)
4231 Warning(ParamLoc, "pointless default value for required parameter "
4232 "'" + Parameter.Name + "' in macro '" + Name + "'");
Eli Bendersky17233942013-01-15 22:59:42 +00004233 }
David Majnemer91fc4c22014-01-29 18:57:46 +00004234
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00004235 Parameters.push_back(std::move(Parameter));
David Majnemer91fc4c22014-01-29 18:57:46 +00004236
4237 if (getLexer().is(AsmToken::Comma))
4238 Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00004239 }
4240
Nirav Dave1180e6892016-06-02 17:15:05 +00004241 // Eat just the end of statement.
4242 Lexer.Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00004243
Nirav Dave1180e6892016-06-02 17:15:05 +00004244 // Consuming deferred text, so use Lexer.Lex to ignore Lexing Errors
Eli Bendersky17233942013-01-15 22:59:42 +00004245 AsmToken EndToken, StartToken = getTok();
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00004246 unsigned MacroDepth = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00004247 // Lex the macro definition.
Eugene Zelenko33d7b762016-08-23 17:14:32 +00004248 while (true) {
Nirav Dave1180e6892016-06-02 17:15:05 +00004249 // Ignore Lexing errors in macros.
4250 while (Lexer.is(AsmToken::Error)) {
4251 Lexer.Lex();
4252 }
4253
Eli Bendersky17233942013-01-15 22:59:42 +00004254 // Check whether we have reached the end of the file.
4255 if (getLexer().is(AsmToken::Eof))
4256 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
4257
4258 // Otherwise, check whether we have reach the .endmacro.
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00004259 if (getLexer().is(AsmToken::Identifier)) {
4260 if (getTok().getIdentifier() == ".endm" ||
4261 getTok().getIdentifier() == ".endmacro") {
4262 if (MacroDepth == 0) { // Outermost macro.
4263 EndToken = getTok();
Nirav Dave1180e6892016-06-02 17:15:05 +00004264 Lexer.Lex();
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00004265 if (getLexer().isNot(AsmToken::EndOfStatement))
4266 return TokError("unexpected token in '" + EndToken.getIdentifier() +
4267 "' directive");
4268 break;
4269 } else {
4270 // Otherwise we just found the end of an inner macro.
4271 --MacroDepth;
4272 }
4273 } else if (getTok().getIdentifier() == ".macro") {
4274 // We allow nested macros. Those aren't instantiated until the outermost
4275 // macro is expanded so just ignore them for now.
4276 ++MacroDepth;
4277 }
Eli Bendersky17233942013-01-15 22:59:42 +00004278 }
4279
4280 // Otherwise, scan til the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004281 eatToEndOfStatement();
Eli Bendersky17233942013-01-15 22:59:42 +00004282 }
4283
Rafael Espindola22c38a02018-02-14 16:34:27 +00004284 if (getContext().lookupMacro(Name)) {
Eli Bendersky17233942013-01-15 22:59:42 +00004285 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
4286 }
4287
4288 const char *BodyStart = StartToken.getLoc().getPointer();
4289 const char *BodyEnd = EndToken.getLoc().getPointer();
4290 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Jim Grosbach4b905842013-09-20 23:08:21 +00004291 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
Oliver Stannardc3e7c6d2018-03-06 15:32:34 +00004292 MCAsmMacro Macro(Name, Body, std::move(Parameters));
4293 DEBUG_WITH_TYPE("asm-macros", dbgs() << "Defining new macro:\n";
4294 Macro.dump());
4295 getContext().defineMacro(Name, std::move(Macro));
Eli Bendersky17233942013-01-15 22:59:42 +00004296 return false;
4297}
4298
Jim Grosbach4b905842013-09-20 23:08:21 +00004299/// checkForBadMacro
Kevin Enderby81c944c2013-01-22 21:44:53 +00004300///
4301/// With the support added for named parameters there may be code out there that
4302/// is transitioning from positional parameters. In versions of gas that did
Alp Tokercb402912014-01-24 17:20:08 +00004303/// not support named parameters they would be ignored on the macro definition.
Kevin Enderby81c944c2013-01-22 21:44:53 +00004304/// But to support both styles of parameters this is not possible so if a macro
Alp Tokercb402912014-01-24 17:20:08 +00004305/// definition has named parameters but does not use them and has what appears
Kevin Enderby81c944c2013-01-22 21:44:53 +00004306/// to be positional parameters, strings like $1, $2, ... and $n, then issue a
4307/// warning that the positional parameter found in body which have no effect.
4308/// Hoping the developer will either remove the named parameters from the macro
Alp Tokercb402912014-01-24 17:20:08 +00004309/// definition so the positional parameters get used if that was what was
Kevin Enderby81c944c2013-01-22 21:44:53 +00004310/// intended or change the macro to use the named parameters. It is possible
4311/// this warning will trigger when the none of the named parameters are used
4312/// and the strings like $1 are infact to simply to be passed trough unchanged.
Jim Grosbach4b905842013-09-20 23:08:21 +00004313void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
Kevin Enderby81c944c2013-01-22 21:44:53 +00004314 StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00004315 ArrayRef<MCAsmMacroParameter> Parameters) {
Kevin Enderby81c944c2013-01-22 21:44:53 +00004316 // If this macro is not defined with named parameters the warning we are
4317 // checking for here doesn't apply.
4318 unsigned NParameters = Parameters.size();
4319 if (NParameters == 0)
4320 return;
4321
4322 bool NamedParametersFound = false;
4323 bool PositionalParametersFound = false;
4324
4325 // Look at the body of the macro for use of both the named parameters and what
4326 // are likely to be positional parameters. This is what expandMacro() is
4327 // doing when it finds the parameters in the body.
4328 while (!Body.empty()) {
4329 // Scan for the next possible parameter.
4330 std::size_t End = Body.size(), Pos = 0;
4331 for (; Pos != End; ++Pos) {
4332 // Check for a substitution or escape.
4333 // This macro is defined with parameters, look for \foo, \bar, etc.
4334 if (Body[Pos] == '\\' && Pos + 1 != End)
4335 break;
4336
4337 // This macro should have parameters, but look for $0, $1, ..., $n too.
4338 if (Body[Pos] != '$' || Pos + 1 == End)
4339 continue;
4340 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00004341 if (Next == '$' || Next == 'n' ||
4342 isdigit(static_cast<unsigned char>(Next)))
Kevin Enderby81c944c2013-01-22 21:44:53 +00004343 break;
4344 }
4345
4346 // Check if we reached the end.
4347 if (Pos == End)
4348 break;
4349
4350 if (Body[Pos] == '$') {
Jim Grosbach4b905842013-09-20 23:08:21 +00004351 switch (Body[Pos + 1]) {
4352 // $$ => $
Kevin Enderby81c944c2013-01-22 21:44:53 +00004353 case '$':
4354 break;
4355
Jim Grosbach4b905842013-09-20 23:08:21 +00004356 // $n => number of arguments
Kevin Enderby81c944c2013-01-22 21:44:53 +00004357 case 'n':
4358 PositionalParametersFound = true;
4359 break;
4360
Jim Grosbach4b905842013-09-20 23:08:21 +00004361 // $[0-9] => argument
Kevin Enderby81c944c2013-01-22 21:44:53 +00004362 default: {
4363 PositionalParametersFound = true;
4364 break;
Jim Grosbach4b905842013-09-20 23:08:21 +00004365 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00004366 }
4367 Pos += 2;
4368 } else {
4369 unsigned I = Pos + 1;
4370 while (isIdentifierChar(Body[I]) && I + 1 != End)
4371 ++I;
4372
Jim Grosbach4b905842013-09-20 23:08:21 +00004373 const char *Begin = Body.data() + Pos + 1;
4374 StringRef Argument(Begin, I - (Pos + 1));
Kevin Enderby81c944c2013-01-22 21:44:53 +00004375 unsigned Index = 0;
4376 for (; Index < NParameters; ++Index)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00004377 if (Parameters[Index].Name == Argument)
Kevin Enderby81c944c2013-01-22 21:44:53 +00004378 break;
4379
4380 if (Index == NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00004381 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
4382 Pos += 3;
4383 else {
4384 Pos = I;
4385 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00004386 } else {
4387 NamedParametersFound = true;
4388 Pos += 1 + Argument.size();
4389 }
4390 }
4391 // Update the scan point.
4392 Body = Body.substr(Pos);
4393 }
4394
4395 if (!NamedParametersFound && PositionalParametersFound)
4396 Warning(DirectiveLoc, "macro defined with named parameters which are not "
4397 "used in macro body, possible positional parameter "
4398 "found in body which will have no effect");
4399}
4400
Nico Weber155dccd12014-07-24 17:08:39 +00004401/// parseDirectiveExitMacro
4402/// ::= .exitm
4403bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
Nirav Davea645433c2016-07-18 15:24:03 +00004404 if (parseToken(AsmToken::EndOfStatement,
4405 "unexpected token in '" + Directive + "' directive"))
4406 return true;
Nico Weber155dccd12014-07-24 17:08:39 +00004407
4408 if (!isInsideMacroInstantiation())
4409 return TokError("unexpected '" + Directive + "' in file, "
4410 "no current macro definition");
4411
4412 // Exit all conditionals that are active in the current macro.
4413 while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
4414 TheCondState = TheCondStack.back();
4415 TheCondStack.pop_back();
4416 }
4417
4418 handleMacroExit();
4419 return false;
4420}
4421
Jim Grosbach4b905842013-09-20 23:08:21 +00004422/// parseDirectiveEndMacro
Eli Bendersky17233942013-01-15 22:59:42 +00004423/// ::= .endm
4424/// ::= .endmacro
Jim Grosbach4b905842013-09-20 23:08:21 +00004425bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
Eli Bendersky17233942013-01-15 22:59:42 +00004426 if (getLexer().isNot(AsmToken::EndOfStatement))
4427 return TokError("unexpected token in '" + Directive + "' directive");
4428
4429 // If we are inside a macro instantiation, terminate the current
4430 // instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00004431 if (isInsideMacroInstantiation()) {
4432 handleMacroExit();
Eli Bendersky17233942013-01-15 22:59:42 +00004433 return false;
4434 }
4435
4436 // Otherwise, this .endmacro is a stray entry in the file; well formed
4437 // .endmacro directives are handled during the macro definition parsing.
4438 return TokError("unexpected '" + Directive + "' in file, "
Jim Grosbach4b905842013-09-20 23:08:21 +00004439 "no current macro definition");
Eli Bendersky17233942013-01-15 22:59:42 +00004440}
4441
Jim Grosbach4b905842013-09-20 23:08:21 +00004442/// parseDirectivePurgeMacro
Eli Bendersky17233942013-01-15 22:59:42 +00004443/// ::= .purgem
Jim Grosbach4b905842013-09-20 23:08:21 +00004444bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004445 StringRef Name;
Nirav Davea645433c2016-07-18 15:24:03 +00004446 SMLoc Loc;
Nirav Daved8858ca2016-08-30 14:15:43 +00004447 if (parseTokenLoc(Loc) ||
4448 check(parseIdentifier(Name), Loc,
4449 "expected identifier in '.purgem' directive") ||
Nirav Davea645433c2016-07-18 15:24:03 +00004450 parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00004451 "unexpected token in '.purgem' directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00004452 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004453
Rafael Espindola22c38a02018-02-14 16:34:27 +00004454 if (!getContext().lookupMacro(Name))
Nirav Dave1ab71992016-07-18 19:35:21 +00004455 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
4456
Rafael Espindola22c38a02018-02-14 16:34:27 +00004457 getContext().undefineMacro(Name);
Oliver Stannardc3e7c6d2018-03-06 15:32:34 +00004458 DEBUG_WITH_TYPE("asm-macros", dbgs()
4459 << "Un-defining macro: " << Name << "\n");
Eli Bendersky17233942013-01-15 22:59:42 +00004460 return false;
4461}
Eli Benderskyf483ff92012-12-20 19:05:53 +00004462
Jim Grosbach4b905842013-09-20 23:08:21 +00004463/// parseDirectiveBundleAlignMode
Eli Benderskyf483ff92012-12-20 19:05:53 +00004464/// ::= {.bundle_align_mode} expression
Jim Grosbach4b905842013-09-20 23:08:21 +00004465bool AsmParser::parseDirectiveBundleAlignMode() {
Eli Benderskyf483ff92012-12-20 19:05:53 +00004466 // Expect a single argument: an expression that evaluates to a constant
4467 // in the inclusive range 0-30.
4468 SMLoc ExprLoc = getLexer().getLoc();
4469 int64_t AlignSizePow2;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004470 if (checkForValidSection() || parseAbsoluteExpression(AlignSizePow2) ||
Nirav Davea645433c2016-07-18 15:24:03 +00004471 parseToken(AsmToken::EndOfStatement, "unexpected token after expression "
4472 "in '.bundle_align_mode' "
4473 "directive") ||
4474 check(AlignSizePow2 < 0 || AlignSizePow2 > 30, ExprLoc,
4475 "invalid bundle alignment size (expected between 0 and 30)"))
Eli Benderskyf483ff92012-12-20 19:05:53 +00004476 return true;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004477
4478 // Because of AlignSizePow2's verified range we can safely truncate it to
4479 // unsigned.
4480 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
4481 return false;
4482}
4483
Jim Grosbach4b905842013-09-20 23:08:21 +00004484/// parseDirectiveBundleLock
Eli Bendersky802b6282013-01-07 21:51:08 +00004485/// ::= {.bundle_lock} [align_to_end]
Jim Grosbach4b905842013-09-20 23:08:21 +00004486bool AsmParser::parseDirectiveBundleLock() {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004487 if (checkForValidSection())
4488 return true;
Eli Bendersky802b6282013-01-07 21:51:08 +00004489 bool AlignToEnd = false;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004490
Nirav Dave1a9044b2016-10-24 14:35:29 +00004491 StringRef Option;
4492 SMLoc Loc = getTok().getLoc();
4493 const char *kInvalidOptionError =
4494 "invalid option for '.bundle_lock' directive";
Eli Bendersky802b6282013-01-07 21:51:08 +00004495
Nirav Dave1a9044b2016-10-24 14:35:29 +00004496 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
Nirav Davea645433c2016-07-18 15:24:03 +00004497 if (check(parseIdentifier(Option), Loc, kInvalidOptionError) ||
4498 check(Option != "align_to_end", Loc, kInvalidOptionError) ||
Nirav Dave1a9044b2016-10-24 14:35:29 +00004499 parseToken(AsmToken::EndOfStatement,
4500 "unexpected token after '.bundle_lock' directive option"))
Nirav Davea645433c2016-07-18 15:24:03 +00004501 return true;
Eli Bendersky802b6282013-01-07 21:51:08 +00004502 AlignToEnd = true;
4503 }
4504
Eli Bendersky802b6282013-01-07 21:51:08 +00004505 getStreamer().EmitBundleLock(AlignToEnd);
Eli Benderskyf483ff92012-12-20 19:05:53 +00004506 return false;
4507}
4508
Jim Grosbach4b905842013-09-20 23:08:21 +00004509/// parseDirectiveBundleLock
Eli Benderskyf483ff92012-12-20 19:05:53 +00004510/// ::= {.bundle_lock}
Jim Grosbach4b905842013-09-20 23:08:21 +00004511bool AsmParser::parseDirectiveBundleUnlock() {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004512 if (checkForValidSection() ||
4513 parseToken(AsmToken::EndOfStatement,
Nirav Davea645433c2016-07-18 15:24:03 +00004514 "unexpected token in '.bundle_unlock' directive"))
4515 return true;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004516
4517 getStreamer().EmitBundleUnlock();
4518 return false;
4519}
4520
Jim Grosbach4b905842013-09-20 23:08:21 +00004521/// parseDirectiveSpace
Eli Bendersky17233942013-01-15 22:59:42 +00004522/// ::= (.skip | .space) expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004523bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
Petr Hosek67a94a72016-05-28 05:57:48 +00004524 SMLoc NumBytesLoc = Lexer.getLoc();
4525 const MCExpr *NumBytes;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004526 if (checkForValidSection() || parseExpression(NumBytes))
Eli Bendersky17233942013-01-15 22:59:42 +00004527 return true;
4528
4529 int64_t FillExpr = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00004530 if (parseOptionalToken(AsmToken::Comma))
4531 if (parseAbsoluteExpression(FillExpr))
4532 return addErrorSuffix("in '" + Twine(IDVal) + "' directive");
4533 if (parseToken(AsmToken::EndOfStatement))
4534 return addErrorSuffix("in '" + Twine(IDVal) + "' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00004535
Eli Bendersky17233942013-01-15 22:59:42 +00004536 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
Petr Hosek67a94a72016-05-28 05:57:48 +00004537 getStreamer().emitFill(*NumBytes, FillExpr, NumBytesLoc);
Eli Bendersky17233942013-01-15 22:59:42 +00004538
4539 return false;
4540}
4541
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004542/// parseDirectiveDCB
4543/// ::= .dcb.{b, l, w} expression, expression
4544bool AsmParser::parseDirectiveDCB(StringRef IDVal, unsigned Size) {
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004545 SMLoc NumValuesLoc = Lexer.getLoc();
4546 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004547 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004548 return true;
4549
4550 if (NumValues < 0) {
4551 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4552 return false;
4553 }
4554
4555 if (parseToken(AsmToken::Comma,
4556 "unexpected token in '" + Twine(IDVal) + "' directive"))
4557 return true;
4558
4559 const MCExpr *Value;
4560 SMLoc ExprLoc = getLexer().getLoc();
4561 if (parseExpression(Value))
4562 return true;
4563
4564 // Special case constant expressions to match code generator.
4565 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
4566 assert(Size <= 8 && "Invalid size");
4567 uint64_t IntValue = MCE->getValue();
4568 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
4569 return Error(ExprLoc, "literal value out of range for directive");
4570 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4571 getStreamer().EmitIntValue(IntValue, Size);
4572 } else {
4573 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4574 getStreamer().EmitValue(Value, Size, ExprLoc);
4575 }
4576
4577 if (parseToken(AsmToken::EndOfStatement,
4578 "unexpected token in '" + Twine(IDVal) + "' directive"))
4579 return true;
4580
4581 return false;
4582}
4583
4584/// parseDirectiveRealDCB
4585/// ::= .dcb.{d, s} expression, expression
4586bool AsmParser::parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &Semantics) {
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004587 SMLoc NumValuesLoc = Lexer.getLoc();
4588 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004589 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004590 return true;
4591
4592 if (NumValues < 0) {
4593 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4594 return false;
4595 }
4596
4597 if (parseToken(AsmToken::Comma,
4598 "unexpected token in '" + Twine(IDVal) + "' directive"))
4599 return true;
4600
4601 APInt AsInt;
4602 if (parseRealValue(Semantics, AsInt))
4603 return true;
4604
4605 if (parseToken(AsmToken::EndOfStatement,
4606 "unexpected token in '" + Twine(IDVal) + "' directive"))
4607 return true;
4608
4609 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4610 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
4611 AsInt.getBitWidth() / 8);
4612
4613 return false;
4614}
4615
Petr Hosek85b2f672016-09-23 21:53:36 +00004616/// parseDirectiveDS
4617/// ::= .ds.{b, d, l, p, s, w, x} expression
4618bool AsmParser::parseDirectiveDS(StringRef IDVal, unsigned Size) {
Petr Hosek85b2f672016-09-23 21:53:36 +00004619 SMLoc NumValuesLoc = Lexer.getLoc();
4620 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004621 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek85b2f672016-09-23 21:53:36 +00004622 return true;
4623
4624 if (NumValues < 0) {
4625 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4626 return false;
4627 }
4628
4629 if (parseToken(AsmToken::EndOfStatement,
4630 "unexpected token in '" + Twine(IDVal) + "' directive"))
4631 return true;
4632
4633 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4634 getStreamer().emitFill(Size, 0);
4635
4636 return false;
4637}
4638
Jim Grosbach4b905842013-09-20 23:08:21 +00004639/// parseDirectiveLEB128
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004640/// ::= (.sleb128 | .uleb128) [ expression (, expression)* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004641bool AsmParser::parseDirectiveLEB128(bool Signed) {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004642 if (checkForValidSection())
4643 return true;
4644
Nirav Dave1a9044b2016-10-24 14:35:29 +00004645 auto parseOp = [&]() -> bool {
4646 const MCExpr *Value;
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004647 if (parseExpression(Value))
4648 return true;
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004649 if (Signed)
4650 getStreamer().EmitSLEB128Value(Value);
4651 else
4652 getStreamer().EmitULEB128Value(Value);
Nirav Dave1a9044b2016-10-24 14:35:29 +00004653 return false;
4654 };
Eli Bendersky17233942013-01-15 22:59:42 +00004655
Nirav Dave1a9044b2016-10-24 14:35:29 +00004656 if (parseMany(parseOp))
4657 return addErrorSuffix(" in directive");
Eli Bendersky17233942013-01-15 22:59:42 +00004658
4659 return false;
4660}
4661
Jim Grosbach4b905842013-09-20 23:08:21 +00004662/// parseDirectiveSymbolAttribute
Daniel Dunbara5508c82009-06-30 00:33:19 +00004663/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004664bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00004665 auto parseOp = [&]() -> bool {
4666 StringRef Name;
4667 SMLoc Loc = getTok().getLoc();
4668 if (parseIdentifier(Name))
4669 return Error(Loc, "expected identifier");
4670 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004671
Nirav Dave1a9044b2016-10-24 14:35:29 +00004672 // Assembler local symbols don't make any sense here. Complain loudly.
4673 if (Sym->isTemporary())
4674 return Error(Loc, "non-local symbol required");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004675
Nirav Dave1a9044b2016-10-24 14:35:29 +00004676 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
4677 return Error(Loc, "unable to emit symbol attribute");
4678 return false;
4679 };
Daniel Dunbara5508c82009-06-30 00:33:19 +00004680
Nirav Dave1a9044b2016-10-24 14:35:29 +00004681 if (parseMany(parseOp))
4682 return addErrorSuffix(" in directive");
Jan Wen Voungc7682872010-09-30 01:09:20 +00004683 return false;
Daniel Dunbara5508c82009-06-30 00:33:19 +00004684}
Chris Lattnera1e11f52009-07-07 20:30:46 +00004685
Jim Grosbach4b905842013-09-20 23:08:21 +00004686/// parseDirectiveComm
Chris Lattner28ad7542009-07-09 17:25:12 +00004687/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004688bool AsmParser::parseDirectiveComm(bool IsLocal) {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004689 if (checkForValidSection())
4690 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00004691
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004692 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004693 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004694 if (parseIdentifier(Name))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004695 return TokError("expected identifier in directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004696
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +00004697 // Handle the identifier as the key symbol.
Jim Grosbach6f482002015-05-18 18:43:14 +00004698 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Chris Lattnera1e11f52009-07-07 20:30:46 +00004699
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004700 if (getLexer().isNot(AsmToken::Comma))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004701 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00004702 Lex();
Chris Lattnera1e11f52009-07-07 20:30:46 +00004703
4704 int64_t Size;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004705 SMLoc SizeLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004706 if (parseAbsoluteExpression(Size))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004707 return true;
4708
4709 int64_t Pow2Alignment = 0;
4710 SMLoc Pow2AlignmentLoc;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004711 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan686ed8d2010-01-19 20:22:31 +00004712 Lex();
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004713 Pow2AlignmentLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004714 if (parseAbsoluteExpression(Pow2Alignment))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004715 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00004716
Benjamin Kramer68b9f052012-09-07 21:08:01 +00004717 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
4718 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00004719 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
4720
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00004721 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramer68b9f052012-09-07 21:08:01 +00004722 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
4723 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00004724 if (!isPowerOf2_64(Pow2Alignment))
4725 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
4726 Pow2Alignment = Log2_64(Pow2Alignment);
4727 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00004728 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00004729
Nirav Dave1a9044b2016-10-24 14:35:29 +00004730 if (parseToken(AsmToken::EndOfStatement,
4731 "unexpected token in '.comm' or '.lcomm' directive"))
4732 return true;
Chris Lattnera1e11f52009-07-07 20:30:46 +00004733
Chris Lattner28ad7542009-07-09 17:25:12 +00004734 // NOTE: a size of zero for a .comm should create a undefined symbol
4735 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattnera1e11f52009-07-07 20:30:46 +00004736 if (Size < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00004737 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
Jim Grosbach4b905842013-09-20 23:08:21 +00004738 "be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00004739
Eric Christopherbc818852010-05-14 01:38:54 +00004740 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattnera1e11f52009-07-07 20:30:46 +00004741 // may internally end up wanting an alignment in bytes.
4742 // FIXME: Diagnose overflow.
4743 if (Pow2Alignment < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00004744 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
Jim Grosbach4b905842013-09-20 23:08:21 +00004745 "alignment, can't be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00004746
Rafael Espindola13a79bb2017-02-02 21:26:06 +00004747 Sym->redefineIfPossible();
Daniel Dunbar6860ac72009-08-22 07:22:36 +00004748 if (!Sym->isUndefined())
Chris Lattnera1e11f52009-07-07 20:30:46 +00004749 return Error(IDLoc, "invalid symbol redefinition");
4750
Chris Lattner28ad7542009-07-09 17:25:12 +00004751 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00004752 if (IsLocal) {
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00004753 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00004754 return false;
4755 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00004756
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004757 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattnera1e11f52009-07-07 20:30:46 +00004758 return false;
4759}
Chris Lattner07cadaf2009-07-10 22:20:30 +00004760
Jim Grosbach4b905842013-09-20 23:08:21 +00004761/// parseDirectiveAbort
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004762/// ::= .abort [... message ...]
Jim Grosbach4b905842013-09-20 23:08:21 +00004763bool AsmParser::parseDirectiveAbort() {
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004764 // FIXME: Use loc from directive.
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004765 SMLoc Loc = getLexer().getLoc();
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004766
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004767 StringRef Str = parseStringToEndOfStatement();
Nirav Davea645433c2016-07-18 15:24:03 +00004768 if (parseToken(AsmToken::EndOfStatement,
4769 "unexpected token in '.abort' directive"))
4770 return true;
Kevin Enderby56523ce2009-07-13 23:15:14 +00004771
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004772 if (Str.empty())
Nirav Dave2364748a2016-09-16 18:30:20 +00004773 return Error(Loc, ".abort detected. Assembly stopping.");
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004774 else
Nirav Dave2364748a2016-09-16 18:30:20 +00004775 return Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004776 // FIXME: Actually abort assembly here.
Kevin Enderby56523ce2009-07-13 23:15:14 +00004777
4778 return false;
4779}
Kevin Enderbycbe475d2009-07-14 21:35:03 +00004780
Jim Grosbach4b905842013-09-20 23:08:21 +00004781/// parseDirectiveInclude
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004782/// ::= .include "filename"
Jim Grosbach4b905842013-09-20 23:08:21 +00004783bool AsmParser::parseDirectiveInclude() {
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004784 // Allow the strings to have escaped octal character sequence.
4785 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00004786 SMLoc IncludeLoc = getTok().getLoc();
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004787
Nirav Davea645433c2016-07-18 15:24:03 +00004788 if (check(getTok().isNot(AsmToken::String),
4789 "expected string in '.include' directive") ||
4790 parseEscapedString(Filename) ||
4791 check(getTok().isNot(AsmToken::EndOfStatement),
4792 "unexpected token in '.include' directive") ||
4793 // Attempt to switch the lexer to the included file before consuming the
4794 // end of statement to avoid losing it when we switch.
4795 check(enterIncludeFile(Filename), IncludeLoc,
4796 "Could not find include file '" + Filename + "'"))
Chris Lattner693fbb82009-07-16 06:14:39 +00004797 return true;
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004798
4799 return false;
4800}
Kevin Enderby09ea5702009-07-15 15:30:11 +00004801
Jim Grosbach4b905842013-09-20 23:08:21 +00004802/// parseDirectiveIncbin
Petr Hosek2f4ac442016-09-23 00:41:06 +00004803/// ::= .incbin "filename" [ , skip [ , count ] ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004804bool AsmParser::parseDirectiveIncbin() {
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004805 // Allow the strings to have escaped octal character sequence.
4806 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00004807 SMLoc IncbinLoc = getTok().getLoc();
4808 if (check(getTok().isNot(AsmToken::String),
4809 "expected string in '.incbin' directive") ||
Petr Hosek2f4ac442016-09-23 00:41:06 +00004810 parseEscapedString(Filename))
4811 return true;
4812
4813 int64_t Skip = 0;
4814 const MCExpr *Count = nullptr;
4815 SMLoc SkipLoc, CountLoc;
Nirav Dave1a9044b2016-10-24 14:35:29 +00004816 if (parseOptionalToken(AsmToken::Comma)) {
Petr Hosek2f4ac442016-09-23 00:41:06 +00004817 // The skip expression can be omitted while specifying the count, e.g:
4818 // .incbin "filename",,4
4819 if (getTok().isNot(AsmToken::Comma)) {
4820 if (parseTokenLoc(SkipLoc) || parseAbsoluteExpression(Skip))
4821 return true;
4822 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00004823 if (parseOptionalToken(AsmToken::Comma)) {
4824 CountLoc = getTok().getLoc();
4825 if (parseExpression(Count))
Petr Hosek2f4ac442016-09-23 00:41:06 +00004826 return true;
4827 }
4828 }
4829
4830 if (parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00004831 "unexpected token in '.incbin' directive"))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004832 return true;
Nirav Dave1ab71992016-07-18 19:35:21 +00004833
Petr Hosek2f4ac442016-09-23 00:41:06 +00004834 if (check(Skip < 0, SkipLoc, "skip is negative"))
4835 return true;
4836
Nirav Dave1ab71992016-07-18 19:35:21 +00004837 // Attempt to process the included file.
Petr Hosek2f4ac442016-09-23 00:41:06 +00004838 if (processIncbinFile(Filename, Skip, Count, CountLoc))
Nirav Dave1ab71992016-07-18 19:35:21 +00004839 return Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
Kevin Enderby109f25c2011-12-14 21:47:48 +00004840 return false;
4841}
4842
Jim Grosbach4b905842013-09-20 23:08:21 +00004843/// parseDirectiveIf
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004844/// ::= .if{,eq,ge,gt,le,lt,ne} expression
4845bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004846 TheCondStack.push_back(TheCondState);
4847 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004848 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004849 eatToEndOfStatement();
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004850 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004851 int64_t ExprValue;
Nirav Davea645433c2016-07-18 15:24:03 +00004852 if (parseAbsoluteExpression(ExprValue) ||
4853 parseToken(AsmToken::EndOfStatement,
4854 "unexpected token in '.if' directive"))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004855 return true;
4856
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004857 switch (DirKind) {
4858 default:
4859 llvm_unreachable("unsupported directive");
4860 case DK_IF:
4861 case DK_IFNE:
4862 break;
4863 case DK_IFEQ:
4864 ExprValue = ExprValue == 0;
4865 break;
4866 case DK_IFGE:
4867 ExprValue = ExprValue >= 0;
4868 break;
4869 case DK_IFGT:
4870 ExprValue = ExprValue > 0;
4871 break;
4872 case DK_IFLE:
4873 ExprValue = ExprValue <= 0;
4874 break;
4875 case DK_IFLT:
4876 ExprValue = ExprValue < 0;
4877 break;
4878 }
4879
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004880 TheCondState.CondMet = ExprValue;
4881 TheCondState.Ignore = !TheCondState.CondMet;
4882 }
4883
4884 return false;
4885}
4886
Jim Grosbach4b905842013-09-20 23:08:21 +00004887/// parseDirectiveIfb
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004888/// ::= .ifb string
Jim Grosbach4b905842013-09-20 23:08:21 +00004889bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004890 TheCondStack.push_back(TheCondState);
4891 TheCondState.TheCond = AsmCond::IfCond;
4892
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004893 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004894 eatToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004895 } else {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004896 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004897
Nirav Davea645433c2016-07-18 15:24:03 +00004898 if (parseToken(AsmToken::EndOfStatement,
4899 "unexpected token in '.ifb' directive"))
4900 return true;
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004901
4902 TheCondState.CondMet = ExpectBlank == Str.empty();
4903 TheCondState.Ignore = !TheCondState.CondMet;
4904 }
4905
4906 return false;
4907}
4908
Jim Grosbach4b905842013-09-20 23:08:21 +00004909/// parseDirectiveIfc
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004910/// ::= .ifc string1, string2
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00004911/// ::= .ifnc string1, string2
Jim Grosbach4b905842013-09-20 23:08:21 +00004912bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004913 TheCondStack.push_back(TheCondState);
4914 TheCondState.TheCond = AsmCond::IfCond;
4915
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004916 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004917 eatToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004918 } else {
Jim Grosbach4b905842013-09-20 23:08:21 +00004919 StringRef Str1 = parseStringToComma();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004920
Nirav Davea645433c2016-07-18 15:24:03 +00004921 if (parseToken(AsmToken::Comma, "unexpected token in '.ifc' directive"))
4922 return true;
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004923
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004924 StringRef Str2 = parseStringToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004925
Nirav Davea645433c2016-07-18 15:24:03 +00004926 if (parseToken(AsmToken::EndOfStatement,
4927 "unexpected token in '.ifc' directive"))
4928 return true;
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004929
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00004930 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004931 TheCondState.Ignore = !TheCondState.CondMet;
4932 }
4933
4934 return false;
4935}
4936
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004937/// parseDirectiveIfeqs
4938/// ::= .ifeqs string1, string2
Sid Manning51c35602015-03-18 14:20:54 +00004939bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual) {
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004940 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00004941 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00004942 return TokError("expected string parameter for '.ifeqs' directive");
4943 return TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004944 }
4945
4946 StringRef String1 = getTok().getStringContents();
4947 Lex();
4948
4949 if (Lexer.isNot(AsmToken::Comma)) {
Sid Manning51c35602015-03-18 14:20:54 +00004950 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00004951 return TokError(
4952 "expected comma after first string for '.ifeqs' directive");
4953 return TokError("expected comma after first string for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004954 }
4955
4956 Lex();
4957
4958 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00004959 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00004960 return TokError("expected string parameter for '.ifeqs' directive");
4961 return TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004962 }
4963
4964 StringRef String2 = getTok().getStringContents();
4965 Lex();
4966
4967 TheCondStack.push_back(TheCondState);
4968 TheCondState.TheCond = AsmCond::IfCond;
Sid Manning51c35602015-03-18 14:20:54 +00004969 TheCondState.CondMet = ExpectEqual == (String1 == String2);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004970 TheCondState.Ignore = !TheCondState.CondMet;
4971
4972 return false;
4973}
4974
Jim Grosbach4b905842013-09-20 23:08:21 +00004975/// parseDirectiveIfdef
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004976/// ::= .ifdef symbol
Jim Grosbach4b905842013-09-20 23:08:21 +00004977bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004978 StringRef Name;
4979 TheCondStack.push_back(TheCondState);
4980 TheCondState.TheCond = AsmCond::IfCond;
4981
4982 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004983 eatToEndOfStatement();
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004984 } else {
Nirav Davea645433c2016-07-18 15:24:03 +00004985 if (check(parseIdentifier(Name), "expected identifier after '.ifdef'") ||
4986 parseToken(AsmToken::EndOfStatement, "unexpected token in '.ifdef'"))
4987 return true;
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004988
Jim Grosbach6f482002015-05-18 18:43:14 +00004989 MCSymbol *Sym = getContext().lookupSymbol(Name);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004990
4991 if (expect_defined)
Craig Topper353eda42014-04-24 06:44:33 +00004992 TheCondState.CondMet = (Sym && !Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004993 else
Craig Topper353eda42014-04-24 06:44:33 +00004994 TheCondState.CondMet = (!Sym || Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004995 TheCondState.Ignore = !TheCondState.CondMet;
4996 }
4997
4998 return false;
4999}
5000
Jim Grosbach4b905842013-09-20 23:08:21 +00005001/// parseDirectiveElseIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005002/// ::= .elseif expression
Jim Grosbach4b905842013-09-20 23:08:21 +00005003bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005004 if (TheCondState.TheCond != AsmCond::IfCond &&
5005 TheCondState.TheCond != AsmCond::ElseIfCond)
Nirav Dave2364748a2016-09-16 18:30:20 +00005006 return Error(DirectiveLoc, "Encountered a .elseif that doesn't follow an"
5007 " .if or an .elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005008 TheCondState.TheCond = AsmCond::ElseIfCond;
5009
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005010 bool LastIgnoreState = false;
5011 if (!TheCondStack.empty())
Craig Topper2172ad62013-04-22 04:24:02 +00005012 LastIgnoreState = TheCondStack.back().Ignore;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005013 if (LastIgnoreState || TheCondState.CondMet) {
5014 TheCondState.Ignore = true;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005015 eatToEndOfStatement();
Craig Topperf15655b2013-04-22 04:22:40 +00005016 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005017 int64_t ExprValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005018 if (parseAbsoluteExpression(ExprValue))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005019 return true;
5020
Nirav Dave1a9044b2016-10-24 14:35:29 +00005021 if (parseToken(AsmToken::EndOfStatement,
5022 "unexpected token in '.elseif' directive"))
5023 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00005024
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005025 TheCondState.CondMet = ExprValue;
5026 TheCondState.Ignore = !TheCondState.CondMet;
5027 }
5028
5029 return false;
5030}
5031
Jim Grosbach4b905842013-09-20 23:08:21 +00005032/// parseDirectiveElse
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005033/// ::= .else
Jim Grosbach4b905842013-09-20 23:08:21 +00005034bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00005035 if (parseToken(AsmToken::EndOfStatement,
5036 "unexpected token in '.else' directive"))
5037 return true;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005038
5039 if (TheCondState.TheCond != AsmCond::IfCond &&
5040 TheCondState.TheCond != AsmCond::ElseIfCond)
Nirav Dave2364748a2016-09-16 18:30:20 +00005041 return Error(DirectiveLoc, "Encountered a .else that doesn't follow "
5042 " an .if or an .elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005043 TheCondState.TheCond = AsmCond::ElseCond;
5044 bool LastIgnoreState = false;
5045 if (!TheCondStack.empty())
5046 LastIgnoreState = TheCondStack.back().Ignore;
5047 if (LastIgnoreState || TheCondState.CondMet)
5048 TheCondState.Ignore = true;
5049 else
5050 TheCondState.Ignore = false;
5051
5052 return false;
5053}
5054
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00005055/// parseDirectiveEnd
5056/// ::= .end
5057bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00005058 if (parseToken(AsmToken::EndOfStatement,
5059 "unexpected token in '.end' directive"))
5060 return true;
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00005061
5062 while (Lexer.isNot(AsmToken::Eof))
Nirav Dave1a9044b2016-10-24 14:35:29 +00005063 Lexer.Lex();
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00005064
5065 return false;
5066}
5067
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00005068/// parseDirectiveError
5069/// ::= .err
5070/// ::= .error [string]
5071bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
5072 if (!TheCondStack.empty()) {
5073 if (TheCondStack.back().Ignore) {
5074 eatToEndOfStatement();
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00005075 return false;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00005076 }
5077 }
5078
5079 if (!WithMessage)
5080 return Error(L, ".err encountered");
5081
5082 StringRef Message = ".error directive invoked in source file";
5083 if (Lexer.isNot(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00005084 if (Lexer.isNot(AsmToken::String))
5085 return TokError(".error argument must be a string");
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00005086
5087 Message = getTok().getStringContents();
5088 Lex();
5089 }
5090
Nirav Dave2364748a2016-09-16 18:30:20 +00005091 return Error(L, Message);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00005092}
5093
Nico Weber404012b2014-07-24 16:26:06 +00005094/// parseDirectiveWarning
5095/// ::= .warning [string]
5096bool AsmParser::parseDirectiveWarning(SMLoc L) {
5097 if (!TheCondStack.empty()) {
5098 if (TheCondStack.back().Ignore) {
5099 eatToEndOfStatement();
5100 return false;
5101 }
5102 }
5103
5104 StringRef Message = ".warning directive invoked in source file";
Nirav Dave1a9044b2016-10-24 14:35:29 +00005105
5106 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00005107 if (Lexer.isNot(AsmToken::String))
5108 return TokError(".warning argument must be a string");
Nico Weber404012b2014-07-24 16:26:06 +00005109
5110 Message = getTok().getStringContents();
5111 Lex();
Nirav Dave1a9044b2016-10-24 14:35:29 +00005112 if (parseToken(AsmToken::EndOfStatement,
5113 "expected end of statement in '.warning' directive"))
5114 return true;
Nico Weber404012b2014-07-24 16:26:06 +00005115 }
5116
Nirav Dave2364748a2016-09-16 18:30:20 +00005117 return Warning(L, Message);
Nico Weber404012b2014-07-24 16:26:06 +00005118}
5119
Jim Grosbach4b905842013-09-20 23:08:21 +00005120/// parseDirectiveEndIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005121/// ::= .endif
Jim Grosbach4b905842013-09-20 23:08:21 +00005122bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00005123 if (parseToken(AsmToken::EndOfStatement,
5124 "unexpected token in '.endif' directive"))
5125 return true;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005126
Jim Grosbach4b905842013-09-20 23:08:21 +00005127 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
Nirav Dave2364748a2016-09-16 18:30:20 +00005128 return Error(DirectiveLoc, "Encountered a .endif that doesn't follow "
5129 "an .if or .else");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005130 if (!TheCondStack.empty()) {
5131 TheCondState = TheCondStack.back();
5132 TheCondStack.pop_back();
5133 }
5134
5135 return false;
5136}
Daniel Dunbara4b069c2009-08-11 04:24:50 +00005137
Eli Bendersky17233942013-01-15 22:59:42 +00005138void AsmParser::initializeDirectiveKindMap() {
5139 DirectiveKindMap[".set"] = DK_SET;
5140 DirectiveKindMap[".equ"] = DK_EQU;
5141 DirectiveKindMap[".equiv"] = DK_EQUIV;
5142 DirectiveKindMap[".ascii"] = DK_ASCII;
5143 DirectiveKindMap[".asciz"] = DK_ASCIZ;
5144 DirectiveKindMap[".string"] = DK_STRING;
5145 DirectiveKindMap[".byte"] = DK_BYTE;
5146 DirectiveKindMap[".short"] = DK_SHORT;
5147 DirectiveKindMap[".value"] = DK_VALUE;
5148 DirectiveKindMap[".2byte"] = DK_2BYTE;
5149 DirectiveKindMap[".long"] = DK_LONG;
5150 DirectiveKindMap[".int"] = DK_INT;
5151 DirectiveKindMap[".4byte"] = DK_4BYTE;
5152 DirectiveKindMap[".quad"] = DK_QUAD;
5153 DirectiveKindMap[".8byte"] = DK_8BYTE;
David Woodhoused6de0d92014-02-01 16:20:59 +00005154 DirectiveKindMap[".octa"] = DK_OCTA;
Eli Bendersky17233942013-01-15 22:59:42 +00005155 DirectiveKindMap[".single"] = DK_SINGLE;
5156 DirectiveKindMap[".float"] = DK_FLOAT;
5157 DirectiveKindMap[".double"] = DK_DOUBLE;
5158 DirectiveKindMap[".align"] = DK_ALIGN;
5159 DirectiveKindMap[".align32"] = DK_ALIGN32;
5160 DirectiveKindMap[".balign"] = DK_BALIGN;
5161 DirectiveKindMap[".balignw"] = DK_BALIGNW;
5162 DirectiveKindMap[".balignl"] = DK_BALIGNL;
5163 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
5164 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
5165 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
5166 DirectiveKindMap[".org"] = DK_ORG;
5167 DirectiveKindMap[".fill"] = DK_FILL;
5168 DirectiveKindMap[".zero"] = DK_ZERO;
5169 DirectiveKindMap[".extern"] = DK_EXTERN;
5170 DirectiveKindMap[".globl"] = DK_GLOBL;
5171 DirectiveKindMap[".global"] = DK_GLOBAL;
Eli Bendersky17233942013-01-15 22:59:42 +00005172 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
5173 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
5174 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
5175 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
5176 DirectiveKindMap[".reference"] = DK_REFERENCE;
5177 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
5178 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
5179 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
5180 DirectiveKindMap[".comm"] = DK_COMM;
5181 DirectiveKindMap[".common"] = DK_COMMON;
5182 DirectiveKindMap[".lcomm"] = DK_LCOMM;
5183 DirectiveKindMap[".abort"] = DK_ABORT;
5184 DirectiveKindMap[".include"] = DK_INCLUDE;
5185 DirectiveKindMap[".incbin"] = DK_INCBIN;
5186 DirectiveKindMap[".code16"] = DK_CODE16;
5187 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
5188 DirectiveKindMap[".rept"] = DK_REPT;
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00005189 DirectiveKindMap[".rep"] = DK_REPT;
Eli Bendersky17233942013-01-15 22:59:42 +00005190 DirectiveKindMap[".irp"] = DK_IRP;
5191 DirectiveKindMap[".irpc"] = DK_IRPC;
5192 DirectiveKindMap[".endr"] = DK_ENDR;
5193 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
5194 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
5195 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
5196 DirectiveKindMap[".if"] = DK_IF;
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00005197 DirectiveKindMap[".ifeq"] = DK_IFEQ;
5198 DirectiveKindMap[".ifge"] = DK_IFGE;
5199 DirectiveKindMap[".ifgt"] = DK_IFGT;
5200 DirectiveKindMap[".ifle"] = DK_IFLE;
5201 DirectiveKindMap[".iflt"] = DK_IFLT;
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00005202 DirectiveKindMap[".ifne"] = DK_IFNE;
Eli Bendersky17233942013-01-15 22:59:42 +00005203 DirectiveKindMap[".ifb"] = DK_IFB;
5204 DirectiveKindMap[".ifnb"] = DK_IFNB;
5205 DirectiveKindMap[".ifc"] = DK_IFC;
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00005206 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
Eli Bendersky17233942013-01-15 22:59:42 +00005207 DirectiveKindMap[".ifnc"] = DK_IFNC;
Sid Manning51c35602015-03-18 14:20:54 +00005208 DirectiveKindMap[".ifnes"] = DK_IFNES;
Eli Bendersky17233942013-01-15 22:59:42 +00005209 DirectiveKindMap[".ifdef"] = DK_IFDEF;
5210 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
5211 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
5212 DirectiveKindMap[".elseif"] = DK_ELSEIF;
5213 DirectiveKindMap[".else"] = DK_ELSE;
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00005214 DirectiveKindMap[".end"] = DK_END;
Eli Bendersky17233942013-01-15 22:59:42 +00005215 DirectiveKindMap[".endif"] = DK_ENDIF;
5216 DirectiveKindMap[".skip"] = DK_SKIP;
5217 DirectiveKindMap[".space"] = DK_SPACE;
5218 DirectiveKindMap[".file"] = DK_FILE;
5219 DirectiveKindMap[".line"] = DK_LINE;
5220 DirectiveKindMap[".loc"] = DK_LOC;
5221 DirectiveKindMap[".stabs"] = DK_STABS;
Reid Kleckner2214ed82016-01-29 00:49:42 +00005222 DirectiveKindMap[".cv_file"] = DK_CV_FILE;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00005223 DirectiveKindMap[".cv_func_id"] = DK_CV_FUNC_ID;
Reid Kleckner2214ed82016-01-29 00:49:42 +00005224 DirectiveKindMap[".cv_loc"] = DK_CV_LOC;
5225 DirectiveKindMap[".cv_linetable"] = DK_CV_LINETABLE;
David Majnemer6fcbd7e2016-01-29 19:24:12 +00005226 DirectiveKindMap[".cv_inline_linetable"] = DK_CV_INLINE_LINETABLE;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00005227 DirectiveKindMap[".cv_inline_site_id"] = DK_CV_INLINE_SITE_ID;
David Majnemer408b5e62016-02-05 01:55:49 +00005228 DirectiveKindMap[".cv_def_range"] = DK_CV_DEF_RANGE;
Reid Kleckner2214ed82016-01-29 00:49:42 +00005229 DirectiveKindMap[".cv_stringtable"] = DK_CV_STRINGTABLE;
5230 DirectiveKindMap[".cv_filechecksums"] = DK_CV_FILECHECKSUMS;
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00005231 DirectiveKindMap[".cv_filechecksumoffset"] = DK_CV_FILECHECKSUM_OFFSET;
Reid Kleckner9cdd4df2017-10-11 21:24:33 +00005232 DirectiveKindMap[".cv_fpo_data"] = DK_CV_FPO_DATA;
Eli Bendersky17233942013-01-15 22:59:42 +00005233 DirectiveKindMap[".sleb128"] = DK_SLEB128;
5234 DirectiveKindMap[".uleb128"] = DK_ULEB128;
5235 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
5236 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
5237 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
5238 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
5239 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
5240 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
5241 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
5242 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
5243 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
5244 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
5245 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
5246 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
5247 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
5248 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
5249 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
5250 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +00005251 DirectiveKindMap[".cfi_return_column"] = DK_CFI_RETURN_COLUMN;
Eli Bendersky17233942013-01-15 22:59:42 +00005252 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
5253 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
5254 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00005255 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
Eli Bendersky17233942013-01-15 22:59:42 +00005256 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
5257 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
5258 DirectiveKindMap[".macro"] = DK_MACRO;
Nico Weber155dccd12014-07-24 17:08:39 +00005259 DirectiveKindMap[".exitm"] = DK_EXITM;
Eli Bendersky17233942013-01-15 22:59:42 +00005260 DirectiveKindMap[".endm"] = DK_ENDM;
5261 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
5262 DirectiveKindMap[".purgem"] = DK_PURGEM;
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00005263 DirectiveKindMap[".err"] = DK_ERR;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00005264 DirectiveKindMap[".error"] = DK_ERROR;
Nico Weber404012b2014-07-24 16:26:06 +00005265 DirectiveKindMap[".warning"] = DK_WARNING;
Michael Zuckerman56704612017-05-01 13:20:12 +00005266 DirectiveKindMap[".altmacro"] = DK_ALTMACRO;
5267 DirectiveKindMap[".noaltmacro"] = DK_NOALTMACRO;
Daniel Sanders9f6ad492015-11-12 13:33:00 +00005268 DirectiveKindMap[".reloc"] = DK_RELOC;
Petr Hosek731bb9c2016-08-23 21:34:53 +00005269 DirectiveKindMap[".dc"] = DK_DC;
5270 DirectiveKindMap[".dc.a"] = DK_DC_A;
5271 DirectiveKindMap[".dc.b"] = DK_DC_B;
5272 DirectiveKindMap[".dc.d"] = DK_DC_D;
5273 DirectiveKindMap[".dc.l"] = DK_DC_L;
5274 DirectiveKindMap[".dc.s"] = DK_DC_S;
5275 DirectiveKindMap[".dc.w"] = DK_DC_W;
5276 DirectiveKindMap[".dc.x"] = DK_DC_X;
Petr Hosek4cb08ce2016-09-23 19:25:15 +00005277 DirectiveKindMap[".dcb"] = DK_DCB;
5278 DirectiveKindMap[".dcb.b"] = DK_DCB_B;
5279 DirectiveKindMap[".dcb.d"] = DK_DCB_D;
5280 DirectiveKindMap[".dcb.l"] = DK_DCB_L;
5281 DirectiveKindMap[".dcb.s"] = DK_DCB_S;
5282 DirectiveKindMap[".dcb.w"] = DK_DCB_W;
5283 DirectiveKindMap[".dcb.x"] = DK_DCB_X;
Petr Hosek85b2f672016-09-23 21:53:36 +00005284 DirectiveKindMap[".ds"] = DK_DS;
5285 DirectiveKindMap[".ds.b"] = DK_DS_B;
5286 DirectiveKindMap[".ds.d"] = DK_DS_D;
5287 DirectiveKindMap[".ds.l"] = DK_DS_L;
5288 DirectiveKindMap[".ds.p"] = DK_DS_P;
5289 DirectiveKindMap[".ds.s"] = DK_DS_S;
5290 DirectiveKindMap[".ds.w"] = DK_DS_W;
5291 DirectiveKindMap[".ds.x"] = DK_DS_X;
Coby Tayree01e53202017-10-02 14:36:31 +00005292 DirectiveKindMap[".print"] = DK_PRINT;
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00005293}
5294
Jim Grosbach4b905842013-09-20 23:08:21 +00005295MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005296 AsmToken EndToken, StartToken = getTok();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005297
Rafael Espindola34b9c512012-06-03 23:57:14 +00005298 unsigned NestLevel = 0;
Eugene Zelenko33d7b762016-08-23 17:14:32 +00005299 while (true) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005300 // Check whether we have reached the end of the file.
Rafael Espindola34b9c512012-06-03 23:57:14 +00005301 if (getLexer().is(AsmToken::Eof)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00005302 printError(DirectiveLoc, "no matching '.endr' in definition");
Craig Topper353eda42014-04-24 06:44:33 +00005303 return nullptr;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005304 }
5305
Rafael Espindola34b9c512012-06-03 23:57:14 +00005306 if (Lexer.is(AsmToken::Identifier) &&
Nikolay Haustov95b4fcd2016-03-01 08:18:28 +00005307 (getTok().getIdentifier() == ".rept" ||
5308 getTok().getIdentifier() == ".irp" ||
5309 getTok().getIdentifier() == ".irpc")) {
Rafael Espindola34b9c512012-06-03 23:57:14 +00005310 ++NestLevel;
5311 }
5312
5313 // Otherwise, check whether we have reached the .endr.
Jim Grosbach4b905842013-09-20 23:08:21 +00005314 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
Rafael Espindola34b9c512012-06-03 23:57:14 +00005315 if (NestLevel == 0) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005316 EndToken = getTok();
5317 Lex();
Rafael Espindola34b9c512012-06-03 23:57:14 +00005318 if (Lexer.isNot(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00005319 printError(getTok().getLoc(),
5320 "unexpected token in '.endr' directive");
Craig Topper353eda42014-04-24 06:44:33 +00005321 return nullptr;
Rafael Espindola34b9c512012-06-03 23:57:14 +00005322 }
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005323 break;
5324 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00005325 --NestLevel;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005326 }
5327
Rafael Espindola34b9c512012-06-03 23:57:14 +00005328 // Otherwise, scan till the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005329 eatToEndOfStatement();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005330 }
5331
5332 const char *BodyStart = StartToken.getLoc().getPointer();
5333 const char *BodyEnd = EndToken.getLoc().getPointer();
5334 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
5335
Rafael Espindola34b9c512012-06-03 23:57:14 +00005336 // We Are Anonymous.
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00005337 MacroLikeBodies.emplace_back(StringRef(), Body, MCAsmMacroParameters());
Benjamin Kramer1df3a1f2013-08-04 09:06:29 +00005338 return &MacroLikeBodies.back();
Rafael Espindola34b9c512012-06-03 23:57:14 +00005339}
5340
Jim Grosbach4b905842013-09-20 23:08:21 +00005341void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +00005342 raw_svector_ostream &OS) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005343 OS << ".endr\n";
5344
Rafael Espindola3560ff22014-08-27 20:03:13 +00005345 std::unique_ptr<MemoryBuffer> Instantiation =
5346 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005347
Rafael Espindola34b9c512012-06-03 23:57:14 +00005348 // Create the macro instantiation object and add to the current macro
5349 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00005350 MacroInstantiation *MI = new MacroInstantiation(
5351 DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Rafael Espindola34b9c512012-06-03 23:57:14 +00005352 ActiveMacros.push_back(MI);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005353
Rafael Espindola34b9c512012-06-03 23:57:14 +00005354 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00005355 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00005356 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Rafael Espindola34b9c512012-06-03 23:57:14 +00005357 Lex();
5358}
5359
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00005360/// parseDirectiveRept
5361/// ::= .rep | .rept count
5362bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00005363 const MCExpr *CountExpr;
5364 SMLoc CountLoc = getTok().getLoc();
5365 if (parseExpression(CountExpr))
5366 return true;
5367
Rafael Espindola34b9c512012-06-03 23:57:14 +00005368 int64_t Count;
Nirav Dave6c0665e2018-04-30 19:22:40 +00005369 if (!CountExpr->evaluateAsAbsolute(Count, getStreamer().getAssemblerPtr())) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00005370 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
5371 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00005372
Nirav Davea645433c2016-07-18 15:24:03 +00005373 if (check(Count < 0, CountLoc, "Count is negative") ||
5374 parseToken(AsmToken::EndOfStatement,
5375 "unexpected token in '" + Dir + "' directive"))
5376 return true;
Rafael Espindola34b9c512012-06-03 23:57:14 +00005377
5378 // Lex the rept definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005379 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola34b9c512012-06-03 23:57:14 +00005380 if (!M)
5381 return true;
5382
5383 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5384 // to hold the macro body with substitutions.
5385 SmallString<256> Buf;
Rafael Espindola34b9c512012-06-03 23:57:14 +00005386 raw_svector_ostream OS(Buf);
5387 while (Count--) {
Toma Tabacu217116e2015-04-27 10:50:29 +00005388 // Note that the AtPseudoVariable is disabled for instantiations of .rep(t).
5389 if (expandMacro(OS, M->Body, None, None, false, getTok().getLoc()))
Rafael Espindola34b9c512012-06-03 23:57:14 +00005390 return true;
5391 }
Jim Grosbach4b905842013-09-20 23:08:21 +00005392 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005393
5394 return false;
5395}
5396
Jim Grosbach4b905842013-09-20 23:08:21 +00005397/// parseDirectiveIrp
Rafael Espindola768b41c2012-06-15 14:02:34 +00005398/// ::= .irp symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00005399bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00005400 MCAsmMacroParameter Parameter;
Eli Bendersky38274122013-01-14 23:22:36 +00005401 MCAsmMacroArguments A;
Nirav Davea645433c2016-07-18 15:24:03 +00005402 if (check(parseIdentifier(Parameter.Name),
5403 "expected identifier in '.irp' directive") ||
5404 parseToken(AsmToken::Comma, "expected comma in '.irp' directive") ||
5405 parseMacroArguments(nullptr, A) ||
5406 parseToken(AsmToken::EndOfStatement, "expected End of Statement"))
Rafael Espindola768b41c2012-06-15 14:02:34 +00005407 return true;
5408
Rafael Espindola768b41c2012-06-15 14:02:34 +00005409 // Lex the irp definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005410 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola768b41c2012-06-15 14:02:34 +00005411 if (!M)
5412 return true;
5413
5414 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5415 // to hold the macro body with substitutions.
5416 SmallString<256> Buf;
5417 raw_svector_ostream OS(Buf);
5418
Craig Topper84008482015-10-10 05:38:14 +00005419 for (const MCAsmMacroArgument &Arg : A) {
Toma Tabacu217116e2015-04-27 10:50:29 +00005420 // Note that the AtPseudoVariable is enabled for instantiations of .irp.
5421 // This is undocumented, but GAS seems to support it.
Craig Topper84008482015-10-10 05:38:14 +00005422 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindola768b41c2012-06-15 14:02:34 +00005423 return true;
5424 }
5425
Jim Grosbach4b905842013-09-20 23:08:21 +00005426 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola768b41c2012-06-15 14:02:34 +00005427
5428 return false;
5429}
5430
Jim Grosbach4b905842013-09-20 23:08:21 +00005431/// parseDirectiveIrpc
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005432/// ::= .irpc symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00005433bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00005434 MCAsmMacroParameter Parameter;
Eli Bendersky38274122013-01-14 23:22:36 +00005435 MCAsmMacroArguments A;
Nirav Davea645433c2016-07-18 15:24:03 +00005436
5437 if (check(parseIdentifier(Parameter.Name),
5438 "expected identifier in '.irpc' directive") ||
5439 parseToken(AsmToken::Comma, "expected comma in '.irpc' directive") ||
5440 parseMacroArguments(nullptr, A))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005441 return true;
5442
5443 if (A.size() != 1 || A.front().size() != 1)
5444 return TokError("unexpected token in '.irpc' directive");
5445
5446 // Eat the end of statement.
Nirav Davea645433c2016-07-18 15:24:03 +00005447 if (parseToken(AsmToken::EndOfStatement, "expected end of statement"))
5448 return true;
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005449
5450 // Lex the irpc definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005451 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005452 if (!M)
5453 return true;
5454
5455 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5456 // to hold the macro body with substitutions.
5457 SmallString<256> Buf;
5458 raw_svector_ostream OS(Buf);
5459
5460 StringRef Values = A.front().front().getString();
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00005461 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
Eli Benderskya7b905e2013-01-14 19:00:26 +00005462 MCAsmMacroArgument Arg;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00005463 Arg.emplace_back(AsmToken::Identifier, Values.slice(I, I + 1));
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005464
Toma Tabacu217116e2015-04-27 10:50:29 +00005465 // Note that the AtPseudoVariable is enabled for instantiations of .irpc.
5466 // This is undocumented, but GAS seems to support it.
5467 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005468 return true;
5469 }
5470
Jim Grosbach4b905842013-09-20 23:08:21 +00005471 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005472
5473 return false;
5474}
5475
Jim Grosbach4b905842013-09-20 23:08:21 +00005476bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
Rafael Espindola34b9c512012-06-03 23:57:14 +00005477 if (ActiveMacros.empty())
Preston Gurdeb3ebf12012-09-19 20:23:43 +00005478 return TokError("unmatched '.endr' directive");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005479
5480 // The only .repl that should get here are the ones created by
Jim Grosbach4b905842013-09-20 23:08:21 +00005481 // instantiateMacroLikeBody.
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005482 assert(getLexer().is(AsmToken::EndOfStatement));
5483
Jim Grosbach4b905842013-09-20 23:08:21 +00005484 handleMacroExit();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005485 return false;
5486}
Rafael Espindola12d73d12010-09-11 16:45:15 +00005487
Jim Grosbach4b905842013-09-20 23:08:21 +00005488bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
Benjamin Kramer1a136112013-02-15 20:37:21 +00005489 size_t Len) {
Eli Friedman0f4871d2012-10-22 23:58:19 +00005490 const MCExpr *Value;
5491 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005492 if (parseExpression(Value))
Eli Friedman0f4871d2012-10-22 23:58:19 +00005493 return true;
5494 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5495 if (!MCE)
5496 return Error(ExprLoc, "unexpected expression in _emit");
5497 uint64_t IntValue = MCE->getValue();
Craig Topper55b1f292015-10-10 20:17:07 +00005498 if (!isUInt<8>(IntValue) && !isInt<8>(IntValue))
Eli Friedman0f4871d2012-10-22 23:58:19 +00005499 return Error(ExprLoc, "literal value out of range for directive");
5500
Craig Topper7d5b2312015-10-10 05:25:02 +00005501 Info.AsmRewrites->emplace_back(AOK_Emit, IDLoc, Len);
Chad Rosierc7f552c2013-02-12 21:33:51 +00005502 return false;
5503}
5504
Jim Grosbach4b905842013-09-20 23:08:21 +00005505bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
Chad Rosierc7f552c2013-02-12 21:33:51 +00005506 const MCExpr *Value;
5507 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005508 if (parseExpression(Value))
Chad Rosierc7f552c2013-02-12 21:33:51 +00005509 return true;
5510 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5511 if (!MCE)
5512 return Error(ExprLoc, "unexpected expression in align");
5513 uint64_t IntValue = MCE->getValue();
5514 if (!isPowerOf2_64(IntValue))
5515 return Error(ExprLoc, "literal value not a power of two greater then zero");
5516
Craig Topper7d5b2312015-10-10 05:25:02 +00005517 Info.AsmRewrites->emplace_back(AOK_Align, IDLoc, 5, Log2_64(IntValue));
Eli Friedman0f4871d2012-10-22 23:58:19 +00005518 return false;
5519}
5520
Coby Tayree01e53202017-10-02 14:36:31 +00005521bool AsmParser::parseDirectivePrint(SMLoc DirectiveLoc) {
5522 const AsmToken StrTok = getTok();
5523 Lex();
5524 if (StrTok.isNot(AsmToken::String) || StrTok.getString().front() != '"')
5525 return Error(DirectiveLoc, "expected double quoted string after .print");
5526 if (parseToken(AsmToken::EndOfStatement, "expected end of statement"))
5527 return true;
5528 llvm::outs() << StrTok.getStringContents() << '\n';
5529 return false;
5530}
5531
Chad Rosierf43fcf52013-02-13 21:27:17 +00005532// We are comparing pointers, but the pointers are relative to a single string.
5533// Thus, this should always be deterministic.
Benjamin Kramer8817cca2013-09-22 14:09:50 +00005534static int rewritesSort(const AsmRewrite *AsmRewriteA,
5535 const AsmRewrite *AsmRewriteB) {
Chad Rosiereb5c1682013-02-13 18:38:58 +00005536 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
5537 return -1;
5538 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
5539 return 1;
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005540
Chad Rosierfce4fab2013-04-08 17:43:47 +00005541 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
5542 // rewrite to the same location. Make sure the SizeDirective rewrite is
5543 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
5544 // ensures the sort algorithm is stable.
Jim Grosbach4b905842013-09-20 23:08:21 +00005545 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
5546 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005547 return -1;
Chad Rosierfce4fab2013-04-08 17:43:47 +00005548
Jim Grosbach4b905842013-09-20 23:08:21 +00005549 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
5550 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005551 return 1;
Jim Grosbach4b905842013-09-20 23:08:21 +00005552 llvm_unreachable("Unstable rewrite sort.");
Chad Rosierb2144ce2013-02-13 01:03:13 +00005553}
5554
Jim Grosbach4b905842013-09-20 23:08:21 +00005555bool AsmParser::parseMSInlineAsm(
5556 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00005557 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool>> &OpDecls,
Jim Grosbach4b905842013-09-20 23:08:21 +00005558 SmallVectorImpl<std::string> &Constraints,
5559 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
5560 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
Chad Rosier37e755c2012-10-23 17:43:43 +00005561 SmallVector<void *, 4> InputDecls;
5562 SmallVector<void *, 4> OutputDecls;
Chad Rosiera4bc9432013-01-10 22:10:27 +00005563 SmallVector<bool, 4> InputDeclsAddressOf;
5564 SmallVector<bool, 4> OutputDeclsAddressOf;
Chad Rosier8bce6642012-10-18 15:49:34 +00005565 SmallVector<std::string, 4> InputConstraints;
5566 SmallVector<std::string, 4> OutputConstraints;
Benjamin Kramer1a136112013-02-15 20:37:21 +00005567 SmallVector<unsigned, 4> ClobberRegs;
Chad Rosier8bce6642012-10-18 15:49:34 +00005568
Benjamin Kramer1a136112013-02-15 20:37:21 +00005569 SmallVector<AsmRewrite, 4> AsmStrRewrites;
Chad Rosier8bce6642012-10-18 15:49:34 +00005570
5571 // Prime the lexer.
5572 Lex();
5573
5574 // While we have input, parse each statement.
5575 unsigned InputIdx = 0;
5576 unsigned OutputIdx = 0;
5577 while (getLexer().isNot(AsmToken::Eof)) {
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00005578 // Parse curly braces marking block start/end
5579 if (parseCurlyBlockScope(AsmStrRewrites))
5580 continue;
5581
Eli Friedman0f4871d2012-10-22 23:58:19 +00005582 ParseStatementInfo Info(&AsmStrRewrites);
Nirav Dave2364748a2016-09-16 18:30:20 +00005583 bool StatementErr = parseStatement(Info, &SI);
Nirav Dave9fa8af22016-09-13 13:55:06 +00005584
Nirav Dave2364748a2016-09-16 18:30:20 +00005585 if (StatementErr || Info.ParseError) {
5586 // Emit pending errors if any exist.
5587 printPendingErrors();
Nico Webere204c482016-09-13 18:17:00 +00005588 return true;
Nirav Dave2364748a2016-09-16 18:30:20 +00005589 }
5590
5591 // No pending error should exist here.
5592 assert(!hasPendingError() && "unexpected error from parseStatement");
Chad Rosier149e8e02012-12-12 22:45:52 +00005593
Benjamin Kramer1a136112013-02-15 20:37:21 +00005594 if (Info.Opcode == ~0U)
5595 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00005596
Benjamin Kramer1a136112013-02-15 20:37:21 +00005597 const MCInstrDesc &Desc = MII->get(Info.Opcode);
Chad Rosier8bce6642012-10-18 15:49:34 +00005598
Benjamin Kramer1a136112013-02-15 20:37:21 +00005599 // Build the list of clobbers, outputs and inputs.
5600 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
David Blaikie960ea3f2014-06-08 16:18:35 +00005601 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005602
Benjamin Kramer1a136112013-02-15 20:37:21 +00005603 // Immediate.
David Blaikie960ea3f2014-06-08 16:18:35 +00005604 if (Operand.isImm())
Benjamin Kramer1a136112013-02-15 20:37:21 +00005605 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00005606
Benjamin Kramer1a136112013-02-15 20:37:21 +00005607 // Register operand.
Nico Weber42f79db2014-07-17 20:24:55 +00005608 if (Operand.isReg() && !Operand.needAddressOf() &&
5609 !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
Benjamin Kramer1a136112013-02-15 20:37:21 +00005610 unsigned NumDefs = Desc.getNumDefs();
5611 // Clobber.
David Blaikie960ea3f2014-06-08 16:18:35 +00005612 if (NumDefs && Operand.getMCOperandNum() < NumDefs)
5613 ClobberRegs.push_back(Operand.getReg());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005614 continue;
5615 }
5616
5617 // Expr/Input or Output.
David Blaikie960ea3f2014-06-08 16:18:35 +00005618 StringRef SymName = Operand.getSymName();
Chad Rosiere81309b2013-04-09 17:53:49 +00005619 if (SymName.empty())
5620 continue;
5621
David Blaikie960ea3f2014-06-08 16:18:35 +00005622 void *OpDecl = Operand.getOpDecl();
Benjamin Kramer1a136112013-02-15 20:37:21 +00005623 if (!OpDecl)
5624 continue;
5625
5626 bool isOutput = (i == 1) && Desc.mayStore();
Chad Rosiere81309b2013-04-09 17:53:49 +00005627 SMLoc Start = SMLoc::getFromPointer(SymName.data());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005628 if (isOutput) {
5629 ++InputIdx;
5630 OutputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00005631 OutputDeclsAddressOf.push_back(Operand.needAddressOf());
Yaron Keren075759a2015-03-30 15:42:36 +00005632 OutputConstraints.push_back(("=" + Operand.getConstraint()).str());
Craig Topper7d5b2312015-10-10 05:25:02 +00005633 AsmStrRewrites.emplace_back(AOK_Output, Start, SymName.size());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005634 } else {
5635 InputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00005636 InputDeclsAddressOf.push_back(Operand.needAddressOf());
5637 InputConstraints.push_back(Operand.getConstraint().str());
Craig Topper7d5b2312015-10-10 05:25:02 +00005638 AsmStrRewrites.emplace_back(AOK_Input, Start, SymName.size());
Chad Rosier8bce6642012-10-18 15:49:34 +00005639 }
Chad Rosier8bce6642012-10-18 15:49:34 +00005640 }
Reid Kleckneree088972013-12-10 18:27:32 +00005641
5642 // Consider implicit defs to be clobbers. Think of cpuid and push.
Craig Toppere5e035a32015-12-05 07:13:35 +00005643 ArrayRef<MCPhysReg> ImpDefs(Desc.getImplicitDefs(),
5644 Desc.getNumImplicitDefs());
David Majnemer8114c1a2014-06-23 02:17:16 +00005645 ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end());
Chad Rosier8bce6642012-10-18 15:49:34 +00005646 }
5647
5648 // Set the number of Outputs and Inputs.
Chad Rosierf641baa2012-10-18 19:39:30 +00005649 NumOutputs = OutputDecls.size();
5650 NumInputs = InputDecls.size();
Chad Rosier8bce6642012-10-18 15:49:34 +00005651
5652 // Set the unique clobbers.
Benjamin Kramer1a136112013-02-15 20:37:21 +00005653 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
5654 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
5655 ClobberRegs.end());
5656 Clobbers.assign(ClobberRegs.size(), std::string());
5657 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
5658 raw_string_ostream OS(Clobbers[I]);
5659 IP->printRegName(OS, ClobberRegs[I]);
5660 }
Chad Rosier8bce6642012-10-18 15:49:34 +00005661
5662 // Merge the various outputs and inputs. Output are expected first.
5663 if (NumOutputs || NumInputs) {
5664 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierf641baa2012-10-18 19:39:30 +00005665 OpDecls.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00005666 Constraints.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00005667 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00005668 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00005669 Constraints[i] = OutputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005670 }
5671 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00005672 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00005673 Constraints[j] = InputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005674 }
5675 }
5676
5677 // Build the IR assembly string.
Alp Tokere69170a2014-06-26 22:52:05 +00005678 std::string AsmStringIR;
5679 raw_string_ostream OS(AsmStringIR);
Alp Tokera55b95b2014-07-06 10:33:31 +00005680 StringRef ASMString =
5681 SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
5682 const char *AsmStart = ASMString.begin();
5683 const char *AsmEnd = ASMString.end();
Jim Grosbach4b905842013-09-20 23:08:21 +00005684 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
David Majnemer8114c1a2014-06-23 02:17:16 +00005685 for (const AsmRewrite &AR : AsmStrRewrites) {
5686 AsmRewriteKind Kind = AR.Kind;
Chad Rosierff10ed12013-04-12 16:26:42 +00005687
David Majnemer8114c1a2014-06-23 02:17:16 +00005688 const char *Loc = AR.Loc.getPointer();
Chad Rosier17d37992013-03-19 21:12:14 +00005689 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
Chad Rosier0f48c552012-10-19 20:57:14 +00005690
Chad Rosier120eefd2013-03-19 17:32:17 +00005691 // Emit everything up to the immediate/expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00005692 if (unsigned Len = Loc - AsmStart)
Chad Rosier17d37992013-03-19 21:12:14 +00005693 OS << StringRef(AsmStart, Len);
Chad Rosier0f48c552012-10-19 20:57:14 +00005694
Chad Rosier37e755c2012-10-23 17:43:43 +00005695 // Skip the original expression.
5696 if (Kind == AOK_Skip) {
David Majnemer8114c1a2014-06-23 02:17:16 +00005697 AsmStart = Loc + AR.Len;
Chad Rosier37e755c2012-10-23 17:43:43 +00005698 continue;
5699 }
5700
Chad Rosierff10ed12013-04-12 16:26:42 +00005701 unsigned AdditionalSkip = 0;
Chad Rosier8bce6642012-10-18 15:49:34 +00005702 // Rewrite expressions in $N notation.
Chad Rosier0f48c552012-10-19 20:57:14 +00005703 switch (Kind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00005704 default:
5705 break;
Coby Tayreed8912892017-08-24 08:46:25 +00005706 case AOK_IntelExpr:
5707 assert(AR.IntelExp.isValid() && "cannot write invalid intel expression");
5708 if (AR.IntelExp.NeedBracs)
5709 OS << "[";
5710 if (AR.IntelExp.hasBaseReg())
5711 OS << AR.IntelExp.BaseReg;
5712 if (AR.IntelExp.hasIndexReg())
5713 OS << (AR.IntelExp.hasBaseReg() ? " + " : "")
5714 << AR.IntelExp.IndexReg;
5715 if (AR.IntelExp.Scale > 1)
5716 OS << " * $$" << AR.IntelExp.Scale;
5717 if (AR.IntelExp.Imm || !AR.IntelExp.hasRegs())
5718 OS << (AR.IntelExp.hasRegs() ? " + $$" : "$$") << AR.IntelExp.Imm;
5719 if (AR.IntelExp.NeedBracs)
5720 OS << "]";
Chad Rosier8bce6642012-10-18 15:49:34 +00005721 break;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005722 case AOK_Label:
Matt Arsenault4e273432014-12-04 00:06:57 +00005723 OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005724 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005725 case AOK_Input:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005726 OS << '$' << InputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00005727 break;
5728 case AOK_Output:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005729 OS << '$' << OutputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00005730 break;
Chad Rosier0f48c552012-10-19 20:57:14 +00005731 case AOK_SizeDirective:
David Majnemer8114c1a2014-06-23 02:17:16 +00005732 switch (AR.Val) {
Chad Rosier0f48c552012-10-19 20:57:14 +00005733 default: break;
5734 case 8: OS << "byte ptr "; break;
5735 case 16: OS << "word ptr "; break;
5736 case 32: OS << "dword ptr "; break;
5737 case 64: OS << "qword ptr "; break;
5738 case 80: OS << "xword ptr "; break;
5739 case 128: OS << "xmmword ptr "; break;
5740 case 256: OS << "ymmword ptr "; break;
5741 }
Eli Friedman0f4871d2012-10-22 23:58:19 +00005742 break;
5743 case AOK_Emit:
5744 OS << ".byte";
5745 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00005746 case AOK_Align: {
Reid Klecknerfb1c1c72015-10-27 17:32:48 +00005747 // MS alignment directives are measured in bytes. If the native assembler
5748 // measures alignment in bytes, we can pass it straight through.
5749 OS << ".align";
5750 if (getContext().getAsmInfo()->getAlignmentIsInBytes())
5751 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00005752
Reid Klecknerfb1c1c72015-10-27 17:32:48 +00005753 // Alignment is in log2 form, so print that instead and skip the original
5754 // immediate.
5755 unsigned Val = AR.Val;
5756 OS << ' ' << Val;
Benjamin Kramer1a136112013-02-15 20:37:21 +00005757 assert(Val < 10 && "Expected alignment less then 2^10.");
Chad Rosierc7f552c2013-02-12 21:33:51 +00005758 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
5759 break;
5760 }
Michael Zuckerman02ecd432015-12-13 17:07:23 +00005761 case AOK_EVEN:
5762 OS << ".even";
5763 break;
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00005764 case AOK_EndOfStatement:
5765 OS << "\n\t";
5766 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005767 }
Chad Rosier0f48c552012-10-19 20:57:14 +00005768
Chad Rosier8bce6642012-10-18 15:49:34 +00005769 // Skip the original expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00005770 AsmStart = Loc + AR.Len + AdditionalSkip;
Chad Rosier8bce6642012-10-18 15:49:34 +00005771 }
5772
5773 // Emit the remainder of the asm string.
Chad Rosier17d37992013-03-19 21:12:14 +00005774 if (AsmStart != AsmEnd)
5775 OS << StringRef(AsmStart, AsmEnd - AsmStart);
Chad Rosier8bce6642012-10-18 15:49:34 +00005776
5777 AsmString = OS.str();
5778 return false;
5779}
5780
Pete Cooper80d21cb2015-06-22 19:35:57 +00005781namespace llvm {
5782namespace MCParserUtils {
5783
5784/// Returns whether the given symbol is used anywhere in the given expression,
5785/// or subexpressions.
5786static bool isSymbolUsedInExpression(const MCSymbol *Sym, const MCExpr *Value) {
5787 switch (Value->getKind()) {
5788 case MCExpr::Binary: {
5789 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
5790 return isSymbolUsedInExpression(Sym, BE->getLHS()) ||
5791 isSymbolUsedInExpression(Sym, BE->getRHS());
5792 }
5793 case MCExpr::Target:
5794 case MCExpr::Constant:
5795 return false;
5796 case MCExpr::SymbolRef: {
5797 const MCSymbol &S =
5798 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
5799 if (S.isVariable())
5800 return isSymbolUsedInExpression(Sym, S.getVariableValue());
5801 return &S == Sym;
5802 }
5803 case MCExpr::Unary:
5804 return isSymbolUsedInExpression(
5805 Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
5806 }
5807
5808 llvm_unreachable("Unknown expr kind!");
5809}
5810
5811bool parseAssignmentExpression(StringRef Name, bool allow_redef,
5812 MCAsmParser &Parser, MCSymbol *&Sym,
Nirav Dave05b58912018-06-05 15:13:39 +00005813 const MCExpr *&Value, bool AllowExtendedExpr) {
Pete Cooper80d21cb2015-06-22 19:35:57 +00005814
5815 // FIXME: Use better location, we should use proper tokens.
Nirav Davefd910412016-06-17 16:06:17 +00005816 SMLoc EqualLoc = Parser.getTok().getLoc();
Nirav Dave05b58912018-06-05 15:13:39 +00005817 SMLoc EndLoc;
5818 if (AllowExtendedExpr) {
5819 if (Parser.getTargetParser().parseAssignmentExpression(Value, EndLoc)) {
5820 return Parser.TokError("missing expression");
5821 }
5822 } else if (Parser.parseExpression(Value, EndLoc))
5823 return Parser.TokError("missing expression");
Pete Cooper80d21cb2015-06-22 19:35:57 +00005824
5825 // Note: we don't count b as used in "a = b". This is to allow
5826 // a = b
5827 // b = c
5828
Nirav Dave1a9044b2016-10-24 14:35:29 +00005829 if (Parser.parseToken(AsmToken::EndOfStatement))
5830 return true;
Pete Cooper80d21cb2015-06-22 19:35:57 +00005831
5832 // Validate that the LHS is allowed to be a variable (either it has not been
5833 // used as a symbol, or it is an absolute symbol).
5834 Sym = Parser.getContext().lookupSymbol(Name);
5835 if (Sym) {
5836 // Diagnose assignment to a label.
5837 //
5838 // FIXME: Diagnostics. Note the location of the definition as a label.
5839 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
5840 if (isSymbolUsedInExpression(Sym, Value))
5841 return Parser.Error(EqualLoc, "Recursive use of '" + Name + "'");
Vedant Kumar86dbd922015-08-31 17:44:53 +00005842 else if (Sym->isUndefined(/*SetUsed*/ false) && !Sym->isUsed() &&
5843 !Sym->isVariable())
Pete Cooper80d21cb2015-06-22 19:35:57 +00005844 ; // Allow redefinitions of undefined symbols only used in directives.
5845 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
5846 ; // Allow redefinitions of variables that haven't yet been used.
5847 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
5848 return Parser.Error(EqualLoc, "redefinition of '" + Name + "'");
5849 else if (!Sym->isVariable())
5850 return Parser.Error(EqualLoc, "invalid assignment to '" + Name + "'");
5851 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
5852 return Parser.Error(EqualLoc,
5853 "invalid reassignment of non-absolute variable '" +
5854 Name + "'");
Pete Cooper80d21cb2015-06-22 19:35:57 +00005855 } else if (Name == ".") {
Oliver Stannard268f42f2016-12-14 10:43:58 +00005856 Parser.getStreamer().emitValueToOffset(Value, 0, EqualLoc);
Pete Cooper80d21cb2015-06-22 19:35:57 +00005857 return false;
5858 } else
5859 Sym = Parser.getContext().getOrCreateSymbol(Name);
5860
5861 Sym->setRedefinable(allow_redef);
5862
5863 return false;
5864}
5865
Eugene Zelenko33d7b762016-08-23 17:14:32 +00005866} // end namespace MCParserUtils
5867} // end namespace llvm
Pete Cooper80d21cb2015-06-22 19:35:57 +00005868
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00005869/// Create an MCAsmParser instance.
Jim Grosbach4b905842013-09-20 23:08:21 +00005870MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
Sanne Wouda29338752017-02-08 14:48:05 +00005871 MCStreamer &Out, const MCAsmInfo &MAI,
5872 unsigned CB) {
5873 return new AsmParser(SM, C, Out, MAI, CB);
Daniel Dunbar01e36072010-07-17 02:26:10 +00005874}