blob: 72225ef6039f4918dfac18899d12e2c44b5f0861 [file] [log] [blame]
Chris Lattnerb0133452009-06-21 20:16:42 +00001//===- AsmParser.cpp - Parser for Assembly Files --------------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattnerb0133452009-06-21 20:16:42 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This class implements the parser for assembly files.
10//
11//===----------------------------------------------------------------------===//
12
Daniel Dunbar2af16532010-09-24 01:59:56 +000013#include "llvm/ADT/APFloat.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000014#include "llvm/ADT/APInt.h"
15#include "llvm/ADT/ArrayRef.h"
16#include "llvm/ADT/None.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000017#include "llvm/ADT/STLExtras.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000018#include "llvm/ADT/SmallString.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000019#include "llvm/ADT/SmallVector.h"
Reid Kleckner26fa1bf2017-09-19 18:14:45 +000020#include "llvm/ADT/StringExtras.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000021#include "llvm/ADT/StringMap.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000022#include "llvm/ADT/StringRef.h"
Daniel Dunbareb6bb322009-07-27 23:20:52 +000023#include "llvm/ADT/Twine.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000024#include "llvm/BinaryFormat/Dwarf.h"
Reid Kleckner7bbe7112019-10-19 01:44:09 +000025#include "llvm/DebugInfo/CodeView/SymbolRecord.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;
Serge Guelton836aa272019-01-20 23:06:45 +0000162 int64_t LineNumber;
Tim Northoverc0bef992016-04-13 19:46:54 +0000163 SMLoc Loc;
Serge Guelton836aa272019-01-20 23:06:45 +0000164 unsigned Buf;
165 CppHashInfoTy() : Filename(), LineNumber(0), Loc(), Buf(0) {}
Tim Northoverc0bef992016-04-13 19:46:54 +0000166 };
167 CppHashInfoTy CppHashInfo;
168
Paul Robinson9c563262019-05-21 11:59:03 +0000169 /// The filename from the first cpp hash file line comment, if any.
170 StringRef FirstCppHashFilename;
171
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000172 /// List of forward directional labels for diagnosis at the end.
Tim Northoverc0bef992016-04-13 19:46:54 +0000173 SmallVector<std::tuple<SMLoc, CppHashInfoTy, MCSymbol *>, 4> DirLabels;
174
Devang Patela173ee52012-01-31 18:14:05 +0000175 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000176 unsigned AssemblerDialect = ~0U;
Devang Patela173ee52012-01-31 18:14:05 +0000177
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000178 /// is Darwin compatibility enabled?
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000179 bool IsDarwin = false;
Preston Gurd05500642012-09-19 20:36:12 +0000180
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000181 /// Are we parsing ms-style inline assembly?
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000182 bool ParsingInlineAsm = false;
Chad Rosier49963552012-10-13 00:26:04 +0000183
Paul Robinsoncc7344a2018-06-14 13:38:20 +0000184 /// Did we already inform the user about inconsistent MD5 usage?
185 bool ReportedInconsistentMD5 = false;
186
Craig Topperc81aff72018-09-25 20:55:55 +0000187 // Is alt macro mode enabled.
188 bool AltMacroMode = false;
189
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000190public:
Jim Grosbach345768c2011-08-16 18:33:49 +0000191 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Sanne Wouda29338752017-02-08 14:48:05 +0000192 const MCAsmInfo &MAI, unsigned CB);
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000193 AsmParser(const AsmParser &) = delete;
194 AsmParser &operator=(const AsmParser &) = delete;
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000195 ~AsmParser() override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000196
Craig Topper59be68f2014-03-08 07:14:16 +0000197 bool Run(bool NoInitialTextSection, bool NoFinalize = false) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000198
Craig Topper59be68f2014-03-08 07:14:16 +0000199 void addDirectiveHandler(StringRef Directive,
200 ExtensionDirectiveHandler Handler) override {
Eli Bendersky29b9f472013-01-16 00:50:52 +0000201 ExtensionDirectiveMap[Directive] = Handler;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000202 }
203
Toma Tabacu11e14a92015-04-21 11:50:52 +0000204 void addAliasForDirective(StringRef Directive, StringRef Alias) override {
205 DirectiveKindMap[Directive] = DirectiveKindMap[Alias];
206 }
207
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000208 /// @name MCAsmParser Interface
209 /// {
210
Craig Topper59be68f2014-03-08 07:14:16 +0000211 SourceMgr &getSourceManager() override { return SrcMgr; }
212 MCAsmLexer &getLexer() override { return Lexer; }
213 MCContext &getContext() override { return Ctx; }
214 MCStreamer &getStreamer() override { return Out; }
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000215
Reid Klecknera5b1eef2016-08-26 17:58:37 +0000216 CodeViewContext &getCVContext() { return Ctx.getCVContext(); }
217
Craig Topper59be68f2014-03-08 07:14:16 +0000218 unsigned getAssemblerDialect() override {
Devang Patela173ee52012-01-31 18:14:05 +0000219 if (AssemblerDialect == ~0U)
Eric Christophera7c32732012-12-18 00:30:54 +0000220 return MAI.getAssemblerDialect();
Devang Patela173ee52012-01-31 18:14:05 +0000221 else
222 return AssemblerDialect;
223 }
Craig Topper59be68f2014-03-08 07:14:16 +0000224 void setAssemblerDialect(unsigned i) override {
Devang Patela173ee52012-01-31 18:14:05 +0000225 AssemblerDialect = i;
226 }
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000227
Nirav Dave2364748a2016-09-16 18:30:20 +0000228 void Note(SMLoc L, const Twine &Msg, SMRange Range = None) override;
229 bool Warning(SMLoc L, const Twine &Msg, SMRange Range = None) override;
230 bool printError(SMLoc L, const Twine &Msg, SMRange Range = None) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000231
Craig Topper59be68f2014-03-08 07:14:16 +0000232 const AsmToken &Lex() override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000233
Yunzhong Gao27ea29b2016-09-02 23:15:29 +0000234 void setParsingInlineAsm(bool V) override {
235 ParsingInlineAsm = V;
Reid Kleckner953bdce2018-10-24 20:23:57 +0000236 // When parsing MS inline asm, we must lex 0b1101 and 0ABCH as binary and
237 // hex integer literals.
238 Lexer.setLexMasmIntegers(V);
Yunzhong Gao27ea29b2016-09-02 23:15:29 +0000239 }
Craig Topper59be68f2014-03-08 07:14:16 +0000240 bool isParsingInlineAsm() override { return ParsingInlineAsm; }
Chad Rosier8bce6642012-10-18 15:49:34 +0000241
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000242 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
Chad Rosier8bce6642012-10-18 15:49:34 +0000243 unsigned &NumOutputs, unsigned &NumInputs,
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000244 SmallVectorImpl<std::pair<void *,bool>> &OpDecls,
Chad Rosier8bce6642012-10-18 15:49:34 +0000245 SmallVectorImpl<std::string> &Constraints,
Chad Rosier8bce6642012-10-18 15:49:34 +0000246 SmallVectorImpl<std::string> &Clobbers,
Craig Topper59be68f2014-03-08 07:14:16 +0000247 const MCInstrInfo *MII, const MCInstPrinter *IP,
248 MCAsmParserSemaCallback &SI) override;
Chad Rosier49963552012-10-13 00:26:04 +0000249
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000250 bool parseExpression(const MCExpr *&Res);
Craig Topper59be68f2014-03-08 07:14:16 +0000251 bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
252 bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) override;
253 bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
Toma Tabacu7bc44dc2015-06-25 09:52:02 +0000254 bool parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
255 SMLoc &EndLoc) override;
Craig Topper59be68f2014-03-08 07:14:16 +0000256 bool parseAbsoluteExpression(int64_t &Res) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000257
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000258 /// Parse a floating point expression using the float \p Semantics
Petr Hosek4cb08ce2016-09-23 19:25:15 +0000259 /// and set \p Res to the value.
260 bool parseRealValue(const fltSemantics &Semantics, APInt &Res);
261
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000262 /// Parse an identifier or string (as a quoted identifier)
Eli Bendersky0cf0cb92013-01-12 00:05:00 +0000263 /// and set \p Res to the identifier contents.
Craig Topper59be68f2014-03-08 07:14:16 +0000264 bool parseIdentifier(StringRef &Res) override;
265 void eatToEndOfStatement() override;
Eli Bendersky0cf0cb92013-01-12 00:05:00 +0000266
Nirav Davef43cc9f2016-10-10 15:24:54 +0000267 bool checkForValidSection() override;
Nirav Davea645433c2016-07-18 15:24:03 +0000268
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000269 /// }
270
271private:
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +0000272 bool parseStatement(ParseStatementInfo &Info,
273 MCAsmParserSemaCallback *SI);
Marina Yatsina5f5de9f2016-03-07 18:11:16 +0000274 bool parseCurlyBlockScope(SmallVectorImpl<AsmRewrite>& AsmStrRewrites);
Craig Topper3c76c522015-09-20 23:35:59 +0000275 bool parseCppHashLineFilenameComment(SMLoc L);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000276
Jim Grosbach4b905842013-09-20 23:08:21 +0000277 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +0000278 ArrayRef<MCAsmMacroParameter> Parameters);
Rafael Espindola34b9c512012-06-03 23:57:14 +0000279 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +0000280 ArrayRef<MCAsmMacroParameter> Parameters,
Toma Tabacu217116e2015-04-27 10:50:29 +0000281 ArrayRef<MCAsmMacroArgument> A, bool EnableAtPseudoVariable,
Craig Topper3c76c522015-09-20 23:35:59 +0000282 SMLoc L);
Daniel Dunbar43235712010-07-18 18:54:11 +0000283
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000284 /// Are macros enabled in the parser?
Jim Grosbach4b905842013-09-20 23:08:21 +0000285 bool areMacrosEnabled() {return MacrosEnabledFlag;}
Eli Benderskya313ae62013-01-16 18:56:50 +0000286
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000287 /// Control a flag in the parser that enables or disables macros.
Jim Grosbach4b905842013-09-20 23:08:21 +0000288 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
Eli Benderskya313ae62013-01-16 18:56:50 +0000289
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000290 /// Are we inside a macro instantiation?
Jim Grosbach4b905842013-09-20 23:08:21 +0000291 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
Eli Benderskya313ae62013-01-16 18:56:50 +0000292
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000293 /// Handle entry to macro instantiation.
Eli Benderskya313ae62013-01-16 18:56:50 +0000294 ///
295 /// \param M The macro.
296 /// \param NameLoc Instantiation location.
Jim Grosbach4b905842013-09-20 23:08:21 +0000297 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
Eli Benderskya313ae62013-01-16 18:56:50 +0000298
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000299 /// Handle exit from macro instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +0000300 void handleMacroExit();
Eli Benderskya313ae62013-01-16 18:56:50 +0000301
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000302 /// Extract AsmTokens for a macro argument.
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +0000303 bool parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg);
Eli Benderskya313ae62013-01-16 18:56:50 +0000304
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000305 /// Parse all macro arguments for a given macro.
Jim Grosbach4b905842013-09-20 23:08:21 +0000306 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
Eli Benderskya313ae62013-01-16 18:56:50 +0000307
Jim Grosbach4b905842013-09-20 23:08:21 +0000308 void printMacroInstantiations();
309 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
Nirav Dave2364748a2016-09-16 18:30:20 +0000310 SMRange Range = None) const {
311 ArrayRef<SMRange> Ranges(Range);
Chris Lattner72845262011-10-16 05:47:55 +0000312 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
Benjamin Kramerc7583112010-09-27 17:42:11 +0000313 }
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000314 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
Benjamin Kramerc7583112010-09-27 17:42:11 +0000315
Paul Robinson938d9a02018-03-22 15:48:01 +0000316 /// Should we emit DWARF describing this assembler source? (Returns false if
317 /// the source has .file directives, which means we don't want to generate
318 /// info describing the assembler source itself.)
319 bool enabledGenDwarfForAssembly();
320
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000321 /// Enter the specified file. This returns true on failure.
Jim Grosbach4b905842013-09-20 23:08:21 +0000322 bool enterIncludeFile(const std::string &Filename);
323
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000324 /// Process the specified file for the .incbin directive.
Kevin Enderby109f25c2011-12-14 21:47:48 +0000325 /// This returns true on failure.
Petr Hosek2f4ac442016-09-23 00:41:06 +0000326 bool processIncbinFile(const std::string &Filename, int64_t Skip = 0,
327 const MCExpr *Count = nullptr, SMLoc Loc = SMLoc());
Daniel Dunbar43235712010-07-18 18:54:11 +0000328
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000329 /// Reset the current lexer position to that given by \p Loc. The
Daniel Dunbar43235712010-07-18 18:54:11 +0000330 /// current token is not set; clients should ensure Lex() is called
331 /// subsequently.
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000332 ///
Alp Tokera55b95b2014-07-06 10:33:31 +0000333 /// \param InBuffer If not 0, should be the known buffer id that contains the
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000334 /// location.
Alp Tokera55b95b2014-07-06 10:33:31 +0000335 void jumpToLoc(SMLoc Loc, unsigned InBuffer = 0);
Daniel Dunbar43235712010-07-18 18:54:11 +0000336
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000337 /// Parse up to the end of statement and a return the contents from the
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000338 /// current token until the end of the statement; the current token on exit
339 /// will be either the EndOfStatement or EOF.
Craig Topper59be68f2014-03-08 07:14:16 +0000340 StringRef parseStringToEndOfStatement() override;
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000341
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000342 /// Parse until the end of a statement or a comma is encountered,
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000343 /// return the contents from the current token up to the end or comma.
Jim Grosbach4b905842013-09-20 23:08:21 +0000344 StringRef parseStringToComma();
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000345
Jim Grosbach4b905842013-09-20 23:08:21 +0000346 bool parseAssignment(StringRef Name, bool allow_redef,
Nirav Dave7fd992a2018-08-16 16:31:14 +0000347 bool NoDeadStrip = false);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000348
Ahmed Bougacha457852f2015-04-28 00:17:39 +0000349 unsigned getBinOpPrecedence(AsmToken::TokenKind K,
350 MCBinaryExpr::Opcode &Kind);
351
Jim Grosbach4b905842013-09-20 23:08:21 +0000352 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
353 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
354 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000355
Jim Grosbach4b905842013-09-20 23:08:21 +0000356 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
Rafael Espindola63760ba2010-10-28 20:02:27 +0000357
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000358 bool parseCVFunctionId(int64_t &FunctionId, StringRef DirectiveName);
359 bool parseCVFileId(int64_t &FileId, StringRef DirectiveName);
360
Eli Bendersky17233942013-01-15 22:59:42 +0000361 // Generic (target and platform independent) directive parsing.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000362 enum DirectiveKind {
Eli Bendersky4d21fa02013-01-10 23:40:56 +0000363 DK_NO_DIRECTIVE, // Placeholder
Saleem Abdulrasoolb3c70c02017-07-28 03:39:18 +0000364 DK_SET,
365 DK_EQU,
366 DK_EQUIV,
367 DK_ASCII,
368 DK_ASCIZ,
369 DK_STRING,
370 DK_BYTE,
371 DK_SHORT,
Daniel Sanders9f6ad492015-11-12 13:33:00 +0000372 DK_RELOC,
Saleem Abdulrasoolb3c70c02017-07-28 03:39:18 +0000373 DK_VALUE,
374 DK_2BYTE,
375 DK_LONG,
376 DK_INT,
377 DK_4BYTE,
378 DK_QUAD,
379 DK_8BYTE,
380 DK_OCTA,
381 DK_DC,
382 DK_DC_A,
383 DK_DC_B,
384 DK_DC_D,
385 DK_DC_L,
386 DK_DC_S,
387 DK_DC_W,
388 DK_DC_X,
389 DK_DCB,
390 DK_DCB_B,
391 DK_DCB_D,
392 DK_DCB_L,
393 DK_DCB_S,
394 DK_DCB_W,
395 DK_DCB_X,
396 DK_DS,
397 DK_DS_B,
398 DK_DS_D,
399 DK_DS_L,
400 DK_DS_P,
401 DK_DS_S,
402 DK_DS_W,
403 DK_DS_X,
404 DK_SINGLE,
405 DK_FLOAT,
406 DK_DOUBLE,
407 DK_ALIGN,
408 DK_ALIGN32,
409 DK_BALIGN,
410 DK_BALIGNW,
411 DK_BALIGNL,
412 DK_P2ALIGN,
413 DK_P2ALIGNW,
414 DK_P2ALIGNL,
415 DK_ORG,
416 DK_FILL,
417 DK_ENDR,
418 DK_BUNDLE_ALIGN_MODE,
419 DK_BUNDLE_LOCK,
420 DK_BUNDLE_UNLOCK,
421 DK_ZERO,
422 DK_EXTERN,
423 DK_GLOBL,
424 DK_GLOBAL,
425 DK_LAZY_REFERENCE,
426 DK_NO_DEAD_STRIP,
427 DK_SYMBOL_RESOLVER,
428 DK_PRIVATE_EXTERN,
429 DK_REFERENCE,
430 DK_WEAK_DEFINITION,
431 DK_WEAK_REFERENCE,
432 DK_WEAK_DEF_CAN_BE_HIDDEN,
Vedant Kumar13ef84f2019-01-25 18:30:22 +0000433 DK_COLD,
Saleem Abdulrasoolb3c70c02017-07-28 03:39:18 +0000434 DK_COMM,
435 DK_COMMON,
436 DK_LCOMM,
437 DK_ABORT,
438 DK_INCLUDE,
439 DK_INCBIN,
440 DK_CODE16,
441 DK_CODE16GCC,
442 DK_REPT,
443 DK_IRP,
444 DK_IRPC,
445 DK_IF,
446 DK_IFEQ,
447 DK_IFGE,
448 DK_IFGT,
449 DK_IFLE,
450 DK_IFLT,
451 DK_IFNE,
452 DK_IFB,
453 DK_IFNB,
454 DK_IFC,
455 DK_IFEQS,
456 DK_IFNC,
457 DK_IFNES,
458 DK_IFDEF,
459 DK_IFNDEF,
460 DK_IFNOTDEF,
461 DK_ELSEIF,
462 DK_ELSE,
463 DK_ENDIF,
464 DK_SPACE,
465 DK_SKIP,
466 DK_FILE,
467 DK_LINE,
468 DK_LOC,
469 DK_STABS,
470 DK_CV_FILE,
471 DK_CV_FUNC_ID,
472 DK_CV_INLINE_SITE_ID,
473 DK_CV_LOC,
474 DK_CV_LINETABLE,
475 DK_CV_INLINE_LINETABLE,
476 DK_CV_DEF_RANGE,
477 DK_CV_STRINGTABLE,
Reid Kleckner06d02d02018-09-07 21:30:52 +0000478 DK_CV_STRING,
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000479 DK_CV_FILECHECKSUMS,
Reid Kleckner26fa1bf2017-09-19 18:14:45 +0000480 DK_CV_FILECHECKSUM_OFFSET,
Reid Kleckner9cdd4df2017-10-11 21:24:33 +0000481 DK_CV_FPO_DATA,
Saleem Abdulrasoolb3c70c02017-07-28 03:39:18 +0000482 DK_CFI_SECTIONS,
483 DK_CFI_STARTPROC,
484 DK_CFI_ENDPROC,
485 DK_CFI_DEF_CFA,
486 DK_CFI_DEF_CFA_OFFSET,
487 DK_CFI_ADJUST_CFA_OFFSET,
488 DK_CFI_DEF_CFA_REGISTER,
489 DK_CFI_OFFSET,
490 DK_CFI_REL_OFFSET,
491 DK_CFI_PERSONALITY,
492 DK_CFI_LSDA,
493 DK_CFI_REMEMBER_STATE,
494 DK_CFI_RESTORE_STATE,
495 DK_CFI_SAME_VALUE,
496 DK_CFI_RESTORE,
497 DK_CFI_ESCAPE,
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +0000498 DK_CFI_RETURN_COLUMN,
Saleem Abdulrasoolb3c70c02017-07-28 03:39:18 +0000499 DK_CFI_SIGNAL_FRAME,
500 DK_CFI_UNDEFINED,
501 DK_CFI_REGISTER,
502 DK_CFI_WINDOW_SAVE,
Luke Cheeseman41a9e532018-12-21 10:45:08 +0000503 DK_CFI_B_KEY_FRAME,
Saleem Abdulrasoolb3c70c02017-07-28 03:39:18 +0000504 DK_MACROS_ON,
505 DK_MACROS_OFF,
506 DK_ALTMACRO,
507 DK_NOALTMACRO,
508 DK_MACRO,
509 DK_EXITM,
510 DK_ENDM,
511 DK_ENDMACRO,
512 DK_PURGEM,
513 DK_SLEB128,
514 DK_ULEB128,
515 DK_ERR,
516 DK_ERROR,
517 DK_WARNING,
Coby Tayree01e53202017-10-02 14:36:31 +0000518 DK_PRINT,
Peter Collingbourne3e227332018-07-17 22:17:18 +0000519 DK_ADDRSIG,
520 DK_ADDRSIG_SYM,
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000521 DK_END
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000522 };
523
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000524 /// Maps directive name --> DirectiveKind enum, for
Eli Bendersky17233942013-01-15 22:59:42 +0000525 /// directives parsed by this class.
526 StringMap<DirectiveKind> DirectiveKindMap;
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000527
Nilanjana Basuda60fc82019-08-05 14:16:58 +0000528 // Codeview def_range type parsing.
529 enum CVDefRangeType {
530 CVDR_DEFRANGE = 0, // Placeholder
531 CVDR_DEFRANGE_REGISTER,
532 CVDR_DEFRANGE_FRAMEPOINTER_REL,
533 CVDR_DEFRANGE_SUBFIELD_REGISTER,
534 CVDR_DEFRANGE_REGISTER_REL
535 };
536
537 /// Maps Codeview def_range types --> CVDefRangeType enum, for
538 /// Codeview def_range types parsed by this class.
539 StringMap<CVDefRangeType> CVDefRangeTypeMap;
540
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000541 // ".ascii", ".asciz", ".string"
Jim Grosbach4b905842013-09-20 23:08:21 +0000542 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
Daniel Sanders9f6ad492015-11-12 13:33:00 +0000543 bool parseDirectiveReloc(SMLoc DirectiveLoc); // ".reloc"
Nirav Dave1a9044b2016-10-24 14:35:29 +0000544 bool parseDirectiveValue(StringRef IDVal,
545 unsigned Size); // ".byte", ".long", ...
546 bool parseDirectiveOctaValue(StringRef IDVal); // ".octa", ...
547 bool parseDirectiveRealValue(StringRef IDVal,
548 const fltSemantics &); // ".single", ...
Jim Grosbach4b905842013-09-20 23:08:21 +0000549 bool parseDirectiveFill(); // ".fill"
550 bool parseDirectiveZero(); // ".zero"
Eric Christophera7c32732012-12-18 00:30:54 +0000551 // ".set", ".equ", ".equiv"
Jim Grosbach4b905842013-09-20 23:08:21 +0000552 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
553 bool parseDirectiveOrg(); // ".org"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000554 // ".align{,32}", ".p2align{,w,l}"
Jim Grosbach4b905842013-09-20 23:08:21 +0000555 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000556
Eli Bendersky17233942013-01-15 22:59:42 +0000557 // ".file", ".line", ".loc", ".stabs"
Jim Grosbach4b905842013-09-20 23:08:21 +0000558 bool parseDirectiveFile(SMLoc DirectiveLoc);
559 bool parseDirectiveLine();
560 bool parseDirectiveLoc();
561 bool parseDirectiveStabs();
Eli Bendersky17233942013-01-15 22:59:42 +0000562
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000563 // ".cv_file", ".cv_func_id", ".cv_inline_site_id", ".cv_loc", ".cv_linetable",
Reid Kleckner06d02d02018-09-07 21:30:52 +0000564 // ".cv_inline_linetable", ".cv_def_range", ".cv_string"
Reid Kleckner2214ed82016-01-29 00:49:42 +0000565 bool parseDirectiveCVFile();
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000566 bool parseDirectiveCVFuncId();
567 bool parseDirectiveCVInlineSiteId();
Reid Kleckner2214ed82016-01-29 00:49:42 +0000568 bool parseDirectiveCVLoc();
569 bool parseDirectiveCVLinetable();
David Majnemer6fcbd7e2016-01-29 19:24:12 +0000570 bool parseDirectiveCVInlineLinetable();
David Majnemer408b5e62016-02-05 01:55:49 +0000571 bool parseDirectiveCVDefRange();
Reid Kleckner06d02d02018-09-07 21:30:52 +0000572 bool parseDirectiveCVString();
Reid Kleckner2214ed82016-01-29 00:49:42 +0000573 bool parseDirectiveCVStringTable();
574 bool parseDirectiveCVFileChecksums();
Reid Kleckner26fa1bf2017-09-19 18:14:45 +0000575 bool parseDirectiveCVFileChecksumOffset();
Reid Kleckner9cdd4df2017-10-11 21:24:33 +0000576 bool parseDirectiveCVFPOData();
Reid Kleckner2214ed82016-01-29 00:49:42 +0000577
Eli Bendersky17233942013-01-15 22:59:42 +0000578 // .cfi directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000579 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +0000580 bool parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +0000581 bool parseDirectiveCFISections();
582 bool parseDirectiveCFIStartProc();
583 bool parseDirectiveCFIEndProc();
584 bool parseDirectiveCFIDefCfaOffset();
585 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
586 bool parseDirectiveCFIAdjustCfaOffset();
587 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
588 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
589 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
590 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
591 bool parseDirectiveCFIRememberState();
592 bool parseDirectiveCFIRestoreState();
593 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
594 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
595 bool parseDirectiveCFIEscape();
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +0000596 bool parseDirectiveCFIReturnColumn(SMLoc DirectiveLoc);
Jim Grosbach4b905842013-09-20 23:08:21 +0000597 bool parseDirectiveCFISignalFrame();
598 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
Eli Bendersky17233942013-01-15 22:59:42 +0000599
600 // macro directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000601 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
Nico Weber155dccd12014-07-24 17:08:39 +0000602 bool parseDirectiveExitMacro(StringRef Directive);
Jim Grosbach4b905842013-09-20 23:08:21 +0000603 bool parseDirectiveEndMacro(StringRef Directive);
604 bool parseDirectiveMacro(SMLoc DirectiveLoc);
605 bool parseDirectiveMacrosOnOff(StringRef Directive);
Michael Zuckerman56704612017-05-01 13:20:12 +0000606 // alternate macro mode directives
607 bool parseDirectiveAltmacro(StringRef Directive);
Eli Benderskyf483ff92012-12-20 19:05:53 +0000608 // ".bundle_align_mode"
Jim Grosbach4b905842013-09-20 23:08:21 +0000609 bool parseDirectiveBundleAlignMode();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000610 // ".bundle_lock"
Jim Grosbach4b905842013-09-20 23:08:21 +0000611 bool parseDirectiveBundleLock();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000612 // ".bundle_unlock"
Jim Grosbach4b905842013-09-20 23:08:21 +0000613 bool parseDirectiveBundleUnlock();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000614
Eli Bendersky17233942013-01-15 22:59:42 +0000615 // ".space", ".skip"
Jim Grosbach4b905842013-09-20 23:08:21 +0000616 bool parseDirectiveSpace(StringRef IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +0000617
Petr Hosek4cb08ce2016-09-23 19:25:15 +0000618 // ".dcb"
619 bool parseDirectiveDCB(StringRef IDVal, unsigned Size);
620 bool parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &);
Petr Hosek85b2f672016-09-23 21:53:36 +0000621 // ".ds"
622 bool parseDirectiveDS(StringRef IDVal, unsigned Size);
Petr Hosek4cb08ce2016-09-23 19:25:15 +0000623
Eli Bendersky17233942013-01-15 22:59:42 +0000624 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
Jim Grosbach4b905842013-09-20 23:08:21 +0000625 bool parseDirectiveLEB128(bool Signed);
Eli Bendersky17233942013-01-15 22:59:42 +0000626
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000627 /// Parse a directive like ".globl" which
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000628 /// accepts a single symbol (which should be a label or an external).
Jim Grosbach4b905842013-09-20 23:08:21 +0000629 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000630
Jim Grosbach4b905842013-09-20 23:08:21 +0000631 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000632
Jim Grosbach4b905842013-09-20 23:08:21 +0000633 bool parseDirectiveAbort(); // ".abort"
634 bool parseDirectiveInclude(); // ".include"
635 bool parseDirectiveIncbin(); // ".incbin"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000636
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +0000637 // ".if", ".ifeq", ".ifge", ".ifgt" , ".ifle", ".iflt" or ".ifne"
638 bool parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind);
Benjamin Kramer62c18b02012-05-12 11:18:42 +0000639 // ".ifb" or ".ifnb", depending on ExpectBlank.
Jim Grosbach4b905842013-09-20 23:08:21 +0000640 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000641 // ".ifc" or ".ifnc", depending on ExpectEqual.
Jim Grosbach4b905842013-09-20 23:08:21 +0000642 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
Sid Manning51c35602015-03-18 14:20:54 +0000643 // ".ifeqs" or ".ifnes", depending on ExpectEqual.
644 bool parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +0000645 // ".ifdef" or ".ifndef", depending on expect_defined
Jim Grosbach4b905842013-09-20 23:08:21 +0000646 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
647 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
648 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
649 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
Craig Topper59be68f2014-03-08 07:14:16 +0000650 bool parseEscapedString(std::string &Data) override;
Daniel Dunbar55f16672010-09-17 02:47:07 +0000651
Jim Grosbach4b905842013-09-20 23:08:21 +0000652 const MCExpr *applyModifierToExpr(const MCExpr *E,
Daniel Dunbar55f16672010-09-17 02:47:07 +0000653 MCSymbolRefExpr::VariantKind Variant);
Rafael Espindola47b7dac2012-05-12 16:31:10 +0000654
Rafael Espindola34b9c512012-06-03 23:57:14 +0000655 // Macro-like directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000656 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
657 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +0000658 raw_svector_ostream &OS);
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +0000659 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
Jim Grosbach4b905842013-09-20 23:08:21 +0000660 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
661 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
662 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
Chad Rosier8bce6642012-10-18 15:49:34 +0000663
Chad Rosierc7f552c2013-02-12 21:33:51 +0000664 // "_emit" or "__emit"
Jim Grosbach4b905842013-09-20 23:08:21 +0000665 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
Chad Rosierc7f552c2013-02-12 21:33:51 +0000666 size_t Len);
667
668 // "align"
Jim Grosbach4b905842013-09-20 23:08:21 +0000669 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000670
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000671 // "end"
672 bool parseDirectiveEnd(SMLoc DirectiveLoc);
673
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +0000674 // ".err" or ".error"
675 bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +0000676
Nico Weber404012b2014-07-24 16:26:06 +0000677 // ".warning"
678 bool parseDirectiveWarning(SMLoc DirectiveLoc);
679
Coby Tayree01e53202017-10-02 14:36:31 +0000680 // .print <double-quotes-string>
681 bool parseDirectivePrint(SMLoc DirectiveLoc);
682
Peter Collingbourne3e227332018-07-17 22:17:18 +0000683 // Directives to support address-significance tables.
684 bool parseDirectiveAddrsig();
685 bool parseDirectiveAddrsigSym();
686
Eli Bendersky17233942013-01-15 22:59:42 +0000687 void initializeDirectiveKindMap();
Nilanjana Basuda60fc82019-08-05 14:16:58 +0000688 void initializeCVDefRangeTypeMap();
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000689};
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000690
691} // end anonymous namespace
Daniel Dunbar86033402010-07-12 17:54:38 +0000692
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000693namespace llvm {
694
695extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbarab058b82010-07-12 21:23:32 +0000696extern MCAsmParserExtension *createELFAsmParser();
Michael J. Spencerc8dbdfd2010-10-09 11:01:07 +0000697extern MCAsmParserExtension *createCOFFAsmParser();
Wouter van Oortmerssencc75e772018-11-12 20:15:01 +0000698extern MCAsmParserExtension *createWasmAsmParser();
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000699
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000700} // end namespace llvm
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000701
Chris Lattnerc35681b2010-01-19 19:46:13 +0000702enum { DEFAULT_ADDRSPACE = 0 };
703
David Blaikie9f380a32015-03-16 18:06:57 +0000704AsmParser::AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Sanne Wouda29338752017-02-08 14:48:05 +0000705 const MCAsmInfo &MAI, unsigned CB = 0)
David Blaikie9f380a32015-03-16 18:06:57 +0000706 : Lexer(MAI), Ctx(Ctx), Out(Out), MAI(MAI), SrcMgr(SM),
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000707 CurBuffer(CB ? CB : SM.getMainFileID()), MacrosEnabledFlag(true) {
Nirav Dave2364748a2016-09-16 18:30:20 +0000708 HadError = false;
Benjamin Kramer47f5e302011-10-16 10:48:29 +0000709 // Save the old handler.
710 SavedDiagHandler = SrcMgr.getDiagHandler();
711 SavedDiagContext = SrcMgr.getDiagContext();
712 // Set our own handler which calls the saved handler.
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000713 SrcMgr.setDiagHandler(DiagHandler, this);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000714 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar86033402010-07-12 17:54:38 +0000715
Daniel Dunbarc5011082010-07-12 18:12:02 +0000716 // Initialize the platform / file format parser.
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000717 switch (Ctx.getObjectFileInfo()->getObjectFileType()) {
718 case MCObjectFileInfo::IsCOFF:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000719 PlatformParser.reset(createCOFFAsmParser());
720 break;
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000721 case MCObjectFileInfo::IsMachO:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000722 PlatformParser.reset(createDarwinAsmParser());
723 IsDarwin = true;
724 break;
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000725 case MCObjectFileInfo::IsELF:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000726 PlatformParser.reset(createELFAsmParser());
727 break;
Dan Gohman18eafb62017-02-22 01:23:18 +0000728 case MCObjectFileInfo::IsWasm:
Wouter van Oortmerssencc75e772018-11-12 20:15:01 +0000729 PlatformParser.reset(createWasmAsmParser());
Dan Gohman18eafb62017-02-22 01:23:18 +0000730 break;
Jason Liua03ae732019-03-12 22:01:10 +0000731 case MCObjectFileInfo::IsXCOFF:
Hubert Tongfc34a532019-08-06 15:05:20 +0000732 report_fatal_error(
733 "Need to implement createXCOFFAsmParser for XCOFF format.");
Jason Liua03ae732019-03-12 22:01:10 +0000734 break;
Daniel Dunbarc5011082010-07-12 18:12:02 +0000735 }
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000736
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000737 PlatformParser->Initialize(*this);
Eli Bendersky17233942013-01-15 22:59:42 +0000738 initializeDirectiveKindMap();
Nilanjana Basuda60fc82019-08-05 14:16:58 +0000739 initializeCVDefRangeTypeMap();
Toma Tabacu217116e2015-04-27 10:50:29 +0000740
741 NumOfMacroInstantiations = 0;
Chris Lattner351a7ef2009-09-27 21:16:52 +0000742}
743
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000744AsmParser::~AsmParser() {
Saleem Abdulrasool6eae1e62014-05-21 17:53:18 +0000745 assert((HadError || ActiveMacros.empty()) &&
746 "Unexpected active macro instantiation!");
Sanne Wouda29338752017-02-08 14:48:05 +0000747
748 // Restore the saved diagnostics handler and context for use during
749 // finalization.
750 SrcMgr.setDiagHandler(SavedDiagHandler, SavedDiagContext);
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000751}
752
Jim Grosbach4b905842013-09-20 23:08:21 +0000753void AsmParser::printMacroInstantiations() {
Daniel Dunbar43235712010-07-18 18:54:11 +0000754 // Print the active macro instantiation stack.
Jim Grosbach4b905842013-09-20 23:08:21 +0000755 for (std::vector<MacroInstantiation *>::const_reverse_iterator
756 it = ActiveMacros.rbegin(),
757 ie = ActiveMacros.rend();
758 it != ie; ++it)
759 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
Chris Lattner03b80a42011-10-16 05:43:57 +0000760 "while in macro instantiation");
Daniel Dunbar43235712010-07-18 18:54:11 +0000761}
762
Nirav Dave2364748a2016-09-16 18:30:20 +0000763void AsmParser::Note(SMLoc L, const Twine &Msg, SMRange Range) {
764 printPendingErrors();
765 printMessage(L, SourceMgr::DK_Note, Msg, Range);
Saleem Abdulrasool69c7caf2014-01-07 02:28:31 +0000766 printMacroInstantiations();
767}
768
Nirav Dave2364748a2016-09-16 18:30:20 +0000769bool AsmParser::Warning(SMLoc L, const Twine &Msg, SMRange Range) {
Colin LeMahieufe36f832015-07-27 22:39:14 +0000770 if(getTargetParser().getTargetOptions().MCNoWarn)
771 return false;
Joerg Sonnenberger29815912014-08-26 18:39:50 +0000772 if (getTargetParser().getTargetOptions().MCFatalWarnings)
Nirav Dave2364748a2016-09-16 18:30:20 +0000773 return Error(L, Msg, Range);
774 printMessage(L, SourceMgr::DK_Warning, Msg, Range);
Jim Grosbach4b905842013-09-20 23:08:21 +0000775 printMacroInstantiations();
Joerg Sonnenberger74ba2622011-05-19 18:00:13 +0000776 return false;
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +0000777}
778
Nirav Dave2364748a2016-09-16 18:30:20 +0000779bool AsmParser::printError(SMLoc L, const Twine &Msg, SMRange Range) {
Daniel Dunbar43325c42010-09-09 22:42:56 +0000780 HadError = true;
Nirav Dave2364748a2016-09-16 18:30:20 +0000781 printMessage(L, SourceMgr::DK_Error, Msg, Range);
Jim Grosbach4b905842013-09-20 23:08:21 +0000782 printMacroInstantiations();
Chris Lattner2adc9e72009-06-21 21:22:11 +0000783 return true;
784}
785
Jim Grosbach4b905842013-09-20 23:08:21 +0000786bool AsmParser::enterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergeraf5f23e2011-06-01 13:10:15 +0000787 std::string IncludedFile;
Alp Tokera55b95b2014-07-06 10:33:31 +0000788 unsigned NewBuf =
789 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
790 if (!NewBuf)
Sean Callanan7a77eae2010-01-21 00:19:58 +0000791 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +0000792
Sean Callanan7a77eae2010-01-21 00:19:58 +0000793 CurBuffer = NewBuf;
Rafael Espindola8026bd02014-07-06 14:17:29 +0000794 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Sean Callanan7a77eae2010-01-21 00:19:58 +0000795 return false;
796}
Daniel Dunbar43235712010-07-18 18:54:11 +0000797
Sylvestre Ledru149e2812013-05-14 23:36:24 +0000798/// Process the specified .incbin file by searching for it in the include paths
Benjamin Kramerbde91762012-06-02 10:20:22 +0000799/// then just emitting the byte contents of the file to the streamer. This
Kevin Enderby109f25c2011-12-14 21:47:48 +0000800/// returns true on failure.
Petr Hosek2f4ac442016-09-23 00:41:06 +0000801bool AsmParser::processIncbinFile(const std::string &Filename, int64_t Skip,
802 const MCExpr *Count, SMLoc Loc) {
Kevin Enderby109f25c2011-12-14 21:47:48 +0000803 std::string IncludedFile;
Alp Tokera55b95b2014-07-06 10:33:31 +0000804 unsigned NewBuf =
805 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
806 if (!NewBuf)
Kevin Enderby109f25c2011-12-14 21:47:48 +0000807 return true;
808
Kevin Enderbyad41ab52011-12-14 22:34:45 +0000809 // Pick up the bytes from the file and emit them.
Petr Hosek2f4ac442016-09-23 00:41:06 +0000810 StringRef Bytes = SrcMgr.getMemoryBuffer(NewBuf)->getBuffer();
811 Bytes = Bytes.drop_front(Skip);
812 if (Count) {
813 int64_t Res;
Nirav Dave6c0665e2018-04-30 19:22:40 +0000814 if (!Count->evaluateAsAbsolute(Res, getStreamer().getAssemblerPtr()))
Petr Hosek2f4ac442016-09-23 00:41:06 +0000815 return Error(Loc, "expected absolute expression");
816 if (Res < 0)
817 return Warning(Loc, "negative count has no effect");
818 Bytes = Bytes.take_front(Res);
819 }
820 getStreamer().EmitBytes(Bytes);
Kevin Enderby109f25c2011-12-14 21:47:48 +0000821 return false;
822}
823
Alp Tokera55b95b2014-07-06 10:33:31 +0000824void AsmParser::jumpToLoc(SMLoc Loc, unsigned InBuffer) {
825 CurBuffer = InBuffer ? InBuffer : SrcMgr.FindBufferContainingLoc(Loc);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000826 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(),
827 Loc.getPointer());
Daniel Dunbar43235712010-07-18 18:54:11 +0000828}
829
Sean Callanan7a77eae2010-01-21 00:19:58 +0000830const AsmToken &AsmParser::Lex() {
Nirav Dave1180e6892016-06-02 17:15:05 +0000831 if (Lexer.getTok().is(AsmToken::Error))
832 Error(Lexer.getErrLoc(), Lexer.getErr());
833
Nirav Dave53a72f42016-07-11 12:42:14 +0000834 // if it's a end of statement with a comment in it
835 if (getTok().is(AsmToken::EndOfStatement)) {
836 // if this is a line comment output it.
Nirav Dave670109d2017-06-09 14:04:03 +0000837 if (!getTok().getString().empty() && getTok().getString().front() != '\n' &&
Nirav Dave53a72f42016-07-11 12:42:14 +0000838 getTok().getString().front() != '\r' && MAI.preserveAsmComments())
839 Out.addExplicitComment(Twine(getTok().getString()));
840 }
841
Sean Callanan7a77eae2010-01-21 00:19:58 +0000842 const AsmToken *tok = &Lexer.Lex();
Nirav Dave53a72f42016-07-11 12:42:14 +0000843
844 // Parse comments here to be deferred until end of next statement.
Nirav Davefd910412016-06-17 16:06:17 +0000845 while (tok->is(AsmToken::Comment)) {
Nirav Dave53a72f42016-07-11 12:42:14 +0000846 if (MAI.preserveAsmComments())
847 Out.addExplicitComment(Twine(tok->getString()));
Nirav Davefd910412016-06-17 16:06:17 +0000848 tok = &Lexer.Lex();
849 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000850
Sean Callanan7a77eae2010-01-21 00:19:58 +0000851 if (tok->is(AsmToken::Eof)) {
852 // If this is the end of an included file, pop the parent file off the
853 // include stack.
854 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
855 if (ParentIncludeLoc != SMLoc()) {
Jim Grosbach4b905842013-09-20 23:08:21 +0000856 jumpToLoc(ParentIncludeLoc);
Nirav Davefd910412016-06-17 16:06:17 +0000857 return Lex();
Sean Callanan7a77eae2010-01-21 00:19:58 +0000858 }
859 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000860
Sean Callanan7a77eae2010-01-21 00:19:58 +0000861 return *tok;
Sean Callanan686ed8d2010-01-19 20:22:31 +0000862}
863
Paul Robinson938d9a02018-03-22 15:48:01 +0000864bool AsmParser::enabledGenDwarfForAssembly() {
865 // Check whether the user specified -g.
866 if (!getContext().getGenDwarfForAssembly())
867 return false;
868 // If we haven't encountered any .file directives (which would imply that
869 // the assembler source was produced with debug info already) then emit one
870 // describing the assembler source file itself.
Paul Robinson1ca25762019-03-01 20:58:04 +0000871 if (getContext().getGenDwarfFileNumber() == 0) {
Paul Robinson9c563262019-05-21 11:59:03 +0000872 // Use the first #line directive for this, if any. It's preprocessed, so
873 // there is no checksum, and of course no source directive.
874 if (!FirstCppHashFilename.empty())
875 getContext().setMCLineTableRootFile(/*CUID=*/0,
876 getContext().getCompilationDir(),
877 FirstCppHashFilename,
878 /*Cksum=*/None, /*Source=*/None);
Paul Robinson1ca25762019-03-01 20:58:04 +0000879 const MCDwarfFile &RootFile =
880 getContext().getMCDwarfLineTable(/*CUID=*/0).getRootFile();
Paul Robinson938d9a02018-03-22 15:48:01 +0000881 getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective(
Paul Robinson1ca25762019-03-01 20:58:04 +0000882 /*CUID=*/0, getContext().getCompilationDir(), RootFile.Name,
883 RootFile.Checksum, RootFile.Source));
884 }
Paul Robinson938d9a02018-03-22 15:48:01 +0000885 return true;
886}
887
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000888bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar322fec62010-03-13 02:20:57 +0000889 // Create the initial section, if requested.
Daniel Dunbar322fec62010-03-13 02:20:57 +0000890 if (!NoInitialTextSection)
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000891 Out.InitSections(false);
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000892
Chris Lattner36e02122009-06-21 20:54:55 +0000893 // Prime the lexer.
Sean Callanan686ed8d2010-01-19 20:22:31 +0000894 Lex();
Daniel Dunbar43325c42010-09-09 22:42:56 +0000895
896 HadError = false;
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000897 AsmCond StartingCondState = TheCondState;
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +0000898 SmallVector<AsmRewrite, 4> AsmStrRewrites;
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000899
Kevin Enderby6469fc22011-11-01 22:27:22 +0000900 // If we are generating dwarf for assembly source files save the initial text
Paul Robinson938d9a02018-03-22 15:48:01 +0000901 // section. (Don't use enabledGenDwarfForAssembly() here, as we aren't
902 // emitting any actual debug info yet and haven't had a chance to parse any
903 // embedded .file directives.)
Kevin Enderby6469fc22011-11-01 22:27:22 +0000904 if (getContext().getGenDwarfForAssembly()) {
Eric Christopher445c9522016-10-14 05:47:37 +0000905 MCSection *Sec = getStreamer().getCurrentSectionOnly();
Rafael Espindola2f9bdd82015-05-27 20:52:32 +0000906 if (!Sec->getBeginSymbol()) {
907 MCSymbol *SectionStartSym = getContext().createTempSymbol();
908 getStreamer().EmitLabel(SectionStartSym);
909 Sec->setBeginSymbol(SectionStartSym);
910 }
Rafael Espindolae0746792015-05-21 16:52:32 +0000911 bool InsertResult = getContext().addGenDwarfSection(Sec);
912 assert(InsertResult && ".text section should not have debug info yet");
Rafael Espindolafa160c72015-05-21 17:09:22 +0000913 (void)InsertResult;
Kevin Enderby6469fc22011-11-01 22:27:22 +0000914 }
915
Chris Lattner73f36112009-07-02 21:53:43 +0000916 // While we have input, parse each statement.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000917 while (Lexer.isNot(AsmToken::Eof)) {
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +0000918 ParseStatementInfo Info(&AsmStrRewrites);
Joerg Sonnenberger60b403e2019-10-23 15:39:10 +0200919 bool Parsed = parseStatement(Info, nullptr);
Michael J. Spencer530ce852010-10-09 11:00:50 +0000920
Nirav Dave2364748a2016-09-16 18:30:20 +0000921 // If we have a Lexer Error we are on an Error Token. Load in Lexer Error
922 // for printing ErrMsg via Lex() only if no (presumably better) parser error
923 // exists.
Joerg Sonnenberger60b403e2019-10-23 15:39:10 +0200924 if (Parsed && !hasPendingError() && Lexer.getTok().is(AsmToken::Error)) {
Nirav Dave1180e6892016-06-02 17:15:05 +0000925 Lex();
926 }
927
Nirav Dave2364748a2016-09-16 18:30:20 +0000928 // parseStatement returned true so may need to emit an error.
929 printPendingErrors();
930
931 // Skipping to the next line if needed.
Joerg Sonnenberger60b403e2019-10-23 15:39:10 +0200932 if (Parsed && !getLexer().isAtStartOfStatement())
Nirav Dave2364748a2016-09-16 18:30:20 +0000933 eatToEndOfStatement();
Chris Lattner73f36112009-07-02 21:53:43 +0000934 }
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000935
Wouter van Oortmerssen29c6ce52018-12-26 22:46:18 +0000936 getTargetParser().onEndOfFile();
937 printPendingErrors();
938
Nirav Dave2364748a2016-09-16 18:30:20 +0000939 // All errors should have been emitted.
940 assert(!hasPendingError() && "unexpected error from parseStatement");
941
Oliver Stannard21718282016-07-26 14:19:47 +0000942 getTargetParser().flushPendingInstructions(getStreamer());
943
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000944 if (TheCondState.TheCond != StartingCondState.TheCond ||
945 TheCondState.Ignore != StartingCondState.Ignore)
Nirav Dave2364748a2016-09-16 18:30:20 +0000946 printError(getTok().getLoc(), "unmatched .ifs or .elses");
Kevin Enderbye5930f12010-07-28 20:55:35 +0000947 // Check to see there are no empty DwarfFile slots.
David Blaikie8bf66c42014-04-01 07:35:52 +0000948 const auto &LineTables = getContext().getMCDwarfLineTables();
949 if (!LineTables.empty()) {
950 unsigned Index = 0;
951 for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) {
952 if (File.Name.empty() && Index != 0)
Nirav Dave2364748a2016-09-16 18:30:20 +0000953 printError(getTok().getLoc(), "unassigned file number: " +
954 Twine(Index) +
955 " for .file directives");
David Blaikie8bf66c42014-04-01 07:35:52 +0000956 ++Index;
957 }
Kevin Enderbye5930f12010-07-28 20:55:35 +0000958 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000959
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000960 // Check to see that all assembler local symbols were actually defined.
961 // Targets that don't do subsections via symbols may not want this, though,
962 // so conservatively exclude them. Only do this if we're finalizing, though,
963 // as otherwise we won't necessarilly have seen everything yet.
Tim Northover6b3169b2016-04-11 19:50:46 +0000964 if (!NoFinalize) {
965 if (MAI.hasSubsectionsViaSymbols()) {
966 for (const auto &TableEntry : getContext().getSymbols()) {
967 MCSymbol *Sym = TableEntry.getValue();
968 // Variable symbols may not be marked as defined, so check those
969 // explicitly. If we know it's a variable, we have a definition for
970 // the purposes of this check.
971 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
972 // FIXME: We would really like to refer back to where the symbol was
973 // first referenced for a source location. We need to add something
974 // to track that. Currently, we just point to the end of the file.
Nirav Dave2364748a2016-09-16 18:30:20 +0000975 printError(getTok().getLoc(), "assembler local symbol '" +
976 Sym->getName() + "' not defined");
Tim Northover6b3169b2016-04-11 19:50:46 +0000977 }
978 }
979
980 // Temporary symbols like the ones for directional jumps don't go in the
981 // symbol table. They also need to be diagnosed in all (final) cases.
Tim Northoverc0bef992016-04-13 19:46:54 +0000982 for (std::tuple<SMLoc, CppHashInfoTy, MCSymbol *> &LocSym : DirLabels) {
983 if (std::get<2>(LocSym)->isUndefined()) {
984 // Reset the state of any "# line file" directives we've seen to the
985 // context as it was at the diagnostic site.
986 CppHashInfo = std::get<1>(LocSym);
Nirav Dave2364748a2016-09-16 18:30:20 +0000987 printError(std::get<0>(LocSym), "directional label undefined");
Tim Northoverc0bef992016-04-13 19:46:54 +0000988 }
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000989 }
990 }
991
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000992 // Finalize the output stream if there are no errors and if the client wants
993 // us to.
Jack Carter13d5f752013-10-04 22:52:31 +0000994 if (!HadError && !NoFinalize)
Daniel Dunbar9df5f332009-08-21 08:34:18 +0000995 Out.Finish();
996
Oliver Stannard07b43d32015-11-17 09:58:07 +0000997 return HadError || getContext().hadError();
Chris Lattner36e02122009-06-21 20:54:55 +0000998}
999
Nirav Davef43cc9f2016-10-10 15:24:54 +00001000bool AsmParser::checkForValidSection() {
Eric Christopher445c9522016-10-14 05:47:37 +00001001 if (!ParsingInlineAsm && !getStreamer().getCurrentSectionOnly()) {
Rafael Espindola7b61ddf2014-10-15 16:12:52 +00001002 Out.InitSections(false);
Nirav Davef43cc9f2016-10-10 15:24:54 +00001003 return Error(getTok().getLoc(),
1004 "expected section directive before assembly directive");
Daniel Dunbare5444a82010-09-09 22:42:59 +00001005 }
Nirav Davef43cc9f2016-10-10 15:24:54 +00001006 return false;
Daniel Dunbare5444a82010-09-09 22:42:59 +00001007}
1008
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001009/// Throw away the rest of the line for testing purposes.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001010void AsmParser::eatToEndOfStatement() {
Jim Grosbach4b905842013-09-20 23:08:21 +00001011 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Nirav Dave1180e6892016-06-02 17:15:05 +00001012 Lexer.Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +00001013
Chris Lattnere5074c42009-06-22 01:29:09 +00001014 // Eat EOL.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001015 if (Lexer.is(AsmToken::EndOfStatement))
Nirav Dave1180e6892016-06-02 17:15:05 +00001016 Lexer.Lex();
Chris Lattnere5074c42009-06-22 01:29:09 +00001017}
1018
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001019StringRef AsmParser::parseStringToEndOfStatement() {
Daniel Dunbar40a564f2010-07-18 20:15:59 +00001020 const char *Start = getTok().getLoc().getPointer();
1021
Jim Grosbach4b905842013-09-20 23:08:21 +00001022 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Nirav Davefd910412016-06-17 16:06:17 +00001023 Lexer.Lex();
Daniel Dunbar40a564f2010-07-18 20:15:59 +00001024
1025 const char *End = getTok().getLoc().getPointer();
1026 return StringRef(Start, End - Start);
1027}
Chris Lattner78db3622009-06-22 05:51:26 +00001028
Jim Grosbach4b905842013-09-20 23:08:21 +00001029StringRef AsmParser::parseStringToComma() {
Benjamin Kramere297b9f2012-05-12 11:18:51 +00001030 const char *Start = getTok().getLoc().getPointer();
1031
1032 while (Lexer.isNot(AsmToken::EndOfStatement) &&
Jim Grosbach4b905842013-09-20 23:08:21 +00001033 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
Nirav Davefd910412016-06-17 16:06:17 +00001034 Lexer.Lex();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00001035
1036 const char *End = getTok().getLoc().getPointer();
1037 return StringRef(Start, End - Start);
1038}
1039
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001040/// Parse a paren expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +00001041/// NOTE: This assumes the leading '(' has already been consumed.
1042///
1043/// parenexpr ::= expr)
1044///
Jim Grosbach4b905842013-09-20 23:08:21 +00001045bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
1046 if (parseExpression(Res))
1047 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001048 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner7fdbce72009-06-22 06:32:03 +00001049 return TokError("expected ')' in parentheses expression");
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001050 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001051 Lex();
Chris Lattner7fdbce72009-06-22 06:32:03 +00001052 return false;
1053}
Chris Lattner78db3622009-06-22 05:51:26 +00001054
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001055/// Parse a bracket expression and return it.
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +00001056/// NOTE: This assumes the leading '[' has already been consumed.
1057///
1058/// bracketexpr ::= expr]
1059///
Jim Grosbach4b905842013-09-20 23:08:21 +00001060bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
1061 if (parseExpression(Res))
1062 return true;
Nirav Davea645433c2016-07-18 15:24:03 +00001063 EndLoc = getTok().getEndLoc();
1064 if (parseToken(AsmToken::RBrac, "expected ']' in brackets expression"))
1065 return true;
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +00001066 return false;
1067}
1068
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001069/// Parse a primary expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +00001070/// primaryexpr ::= (parenexpr
1071/// primaryexpr ::= symbol
1072/// primaryexpr ::= number
Chris Lattner6b55cb92010-04-14 04:40:28 +00001073/// primaryexpr ::= '.'
Chris Lattner7fdbce72009-06-22 06:32:03 +00001074/// primaryexpr ::= ~,+,- primaryexpr
Jim Grosbach4b905842013-09-20 23:08:21 +00001075bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Kevin Enderby0017d8a2013-01-22 21:09:20 +00001076 SMLoc FirstTokenLoc = getLexer().getLoc();
1077 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
1078 switch (FirstTokenKind) {
Chris Lattner78db3622009-06-22 05:51:26 +00001079 default:
1080 return TokError("unknown token in expression");
Eric Christopher104af062011-04-12 00:03:13 +00001081 // If we have an error assume that we've already handled it.
1082 case AsmToken::Error:
1083 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001084 case AsmToken::Exclaim:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001085 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001086 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001087 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +00001088 Res = MCUnaryExpr::createLNot(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001089 return false;
Daniel Dunbar24764322010-08-24 19:13:42 +00001090 case AsmToken::Dollar:
Hans Wennborgce69d772013-10-18 20:46:28 +00001091 case AsmToken::At:
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +00001092 case AsmToken::String:
Daniel Dunbard20cda02009-10-16 01:34:54 +00001093 case AsmToken::Identifier: {
Daniel Dunbar24764322010-08-24 19:13:42 +00001094 StringRef Identifier;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001095 if (parseIdentifier(Identifier)) {
Nirav Daved0463322016-10-12 13:58:07 +00001096 // We may have failed but $ may be a valid token.
1097 if (getTok().is(AsmToken::Dollar)) {
David Majnemer0c58bc62013-09-25 10:47:21 +00001098 if (Lexer.getMAI().getDollarIsPC()) {
Nirav Daved0463322016-10-12 13:58:07 +00001099 Lex();
David Majnemer0c58bc62013-09-25 10:47:21 +00001100 // This is a '$' reference, which references the current PC. Emit a
1101 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +00001102 MCSymbol *Sym = Ctx.createTempSymbol();
David Majnemer0c58bc62013-09-25 10:47:21 +00001103 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +00001104 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None,
Jack Carter721726a2013-10-04 21:26:15 +00001105 getContext());
David Majnemer0c58bc62013-09-25 10:47:21 +00001106 EndLoc = FirstTokenLoc;
1107 return false;
Ted Kremenek297febe2014-03-06 22:13:17 +00001108 }
1109 return Error(FirstTokenLoc, "invalid token in expression");
David Majnemer0c58bc62013-09-25 10:47:21 +00001110 }
Kevin Enderby0017d8a2013-01-22 21:09:20 +00001111 }
David Peixotto8ad70b32013-12-04 22:43:20 +00001112 // Parse symbol variant
1113 std::pair<StringRef, StringRef> Split;
1114 if (!MAI.useParensForSymbolVariant()) {
David Majnemer6a5b8122014-06-19 01:25:43 +00001115 if (FirstTokenKind == AsmToken::String) {
1116 if (Lexer.is(AsmToken::At)) {
Nirav Davefd910412016-06-17 16:06:17 +00001117 Lex(); // eat @
David Majnemer6a5b8122014-06-19 01:25:43 +00001118 SMLoc AtLoc = getLexer().getLoc();
1119 StringRef VName;
1120 if (parseIdentifier(VName))
1121 return Error(AtLoc, "expected symbol variant after '@'");
1122
1123 Split = std::make_pair(Identifier, VName);
1124 }
1125 } else {
1126 Split = Identifier.split('@');
1127 }
David Peixotto8ad70b32013-12-04 22:43:20 +00001128 } else if (Lexer.is(AsmToken::LParen)) {
Nirav Davefd910412016-06-17 16:06:17 +00001129 Lex(); // eat '('.
David Peixotto8ad70b32013-12-04 22:43:20 +00001130 StringRef VName;
1131 parseIdentifier(VName);
Nirav Davea645433c2016-07-18 15:24:03 +00001132 // eat ')'.
1133 if (parseToken(AsmToken::RParen,
1134 "unexpected token in variant, expected ')'"))
1135 return true;
David Peixotto8ad70b32013-12-04 22:43:20 +00001136 Split = std::make_pair(Identifier, VName);
1137 }
Daniel Dunbar24764322010-08-24 19:13:42 +00001138
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001139 EndLoc = SMLoc::getFromPointer(Identifier.end());
1140
Daniel Dunbard20cda02009-10-16 01:34:54 +00001141 // This is a symbol reference.
Hans Wennborgce69d772013-10-18 20:46:28 +00001142 StringRef SymbolName = Identifier;
Weiming Zhaocf26d562016-12-01 18:00:36 +00001143 if (SymbolName.empty())
Francis Visoiu Mistrih627d1462018-10-08 10:28:11 +00001144 return Error(getLexer().getLoc(), "expected a symbol reference");
Weiming Zhaocf26d562016-12-01 18:00:36 +00001145
Hans Wennborgce69d772013-10-18 20:46:28 +00001146 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Hans Wennborg69918bc2013-10-17 01:13:02 +00001147
Hans Wennborg7ddcdc82013-10-18 02:14:40 +00001148 // Lookup the symbol variant if used.
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00001149 if (!Split.second.empty()) {
Hans Wennborg7ddcdc82013-10-18 02:14:40 +00001150 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Hans Wennborgce69d772013-10-18 20:46:28 +00001151 if (Variant != MCSymbolRefExpr::VK_Invalid) {
1152 SymbolName = Split.first;
David Peixotto8ad70b32013-12-04 22:43:20 +00001153 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
Hans Wennborgce69d772013-10-18 20:46:28 +00001154 Variant = MCSymbolRefExpr::VK_None;
1155 } else {
Saleem Abdulrasoola25e1e42014-01-26 22:29:43 +00001156 return Error(SMLoc::getFromPointer(Split.second.begin()),
1157 "invalid variant '" + Split.second + "'");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001158 }
1159 }
Daniel Dunbar55992562010-03-15 23:51:06 +00001160
Bill Wendling1b104382019-08-09 20:16:31 +00001161 MCSymbol *Sym = getContext().getInlineAsmLabel(SymbolName);
1162 if (!Sym)
1163 Sym = getContext().getOrCreateSymbol(SymbolName);
Hans Wennborgce69d772013-10-18 20:46:28 +00001164
Daniel Dunbard20cda02009-10-16 01:34:54 +00001165 // If this is an absolute variable reference, substitute it now to preserve
1166 // semantics in the face of reassignment.
Nirav Dave05b58912018-06-05 15:13:39 +00001167 if (Sym->isVariable()) {
1168 auto V = Sym->getVariableValue(/*SetUsed*/ false);
Nirav Daveb1f9e4d2018-09-17 20:34:26 +00001169 bool DoInline = isa<MCConstantExpr>(V) && !Variant;
Nirav Dave05b58912018-06-05 15:13:39 +00001170 if (auto TV = dyn_cast<MCTargetExpr>(V))
1171 DoInline = TV->inlineAssignedExpr();
1172 if (DoInline) {
1173 if (Variant)
1174 return Error(EndLoc, "unexpected modifier on variable reference");
1175 Res = Sym->getVariableValue(/*SetUsed*/ false);
1176 return false;
1177 }
Daniel Dunbard20cda02009-10-16 01:34:54 +00001178 }
1179
1180 // Otherwise create a symbol ref.
Chad Rosier9245e122017-01-19 20:06:32 +00001181 Res = MCSymbolRefExpr::create(Sym, Variant, getContext(), FirstTokenLoc);
Chris Lattner78db3622009-06-22 05:51:26 +00001182 return false;
Daniel Dunbard20cda02009-10-16 01:34:54 +00001183 }
David Woodhousef42a6662014-02-01 16:20:54 +00001184 case AsmToken::BigNum:
1185 return TokError("literal value out of range for directive");
Kevin Enderby0510b482010-05-17 23:08:19 +00001186 case AsmToken::Integer: {
1187 SMLoc Loc = getTok().getLoc();
1188 int64_t IntVal = getTok().getIntVal();
Jim Grosbach13760bd2015-05-30 01:25:56 +00001189 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001190 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001191 Lex(); // Eat token.
Kevin Enderby0510b482010-05-17 23:08:19 +00001192 // Look for 'b' or 'f' following an Integer as a directional label
1193 if (Lexer.getKind() == AsmToken::Identifier) {
1194 StringRef IDVal = getTok().getString();
Ulrich Weigandd4120982013-06-20 16:24:17 +00001195 // Lookup the symbol variant if used.
1196 std::pair<StringRef, StringRef> Split = IDVal.split('@');
1197 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
1198 if (Split.first.size() != IDVal.size()) {
1199 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Arnaud A. de Grandmaisonc97727a2014-03-21 21:54:46 +00001200 if (Variant == MCSymbolRefExpr::VK_Invalid)
Ulrich Weigandd4120982013-06-20 16:24:17 +00001201 return TokError("invalid variant '" + Split.second + "'");
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001202 IDVal = Split.first;
Ulrich Weigandd4120982013-06-20 16:24:17 +00001203 }
Jim Grosbach4b905842013-09-20 23:08:21 +00001204 if (IDVal == "f" || IDVal == "b") {
1205 MCSymbol *Sym =
Jim Grosbach6f482002015-05-18 18:43:14 +00001206 Ctx.getDirectionalLocalSymbol(IntVal, IDVal == "b");
Jim Grosbach13760bd2015-05-30 01:25:56 +00001207 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00001208 if (IDVal == "b" && Sym->isUndefined())
Tim Northover6b3169b2016-04-11 19:50:46 +00001209 return Error(Loc, "directional label undefined");
Tim Northoverc0bef992016-04-13 19:46:54 +00001210 DirLabels.push_back(std::make_tuple(Loc, CppHashInfo, Sym));
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001211 EndLoc = Lexer.getTok().getEndLoc();
Kevin Enderby0510b482010-05-17 23:08:19 +00001212 Lex(); // Eat identifier.
1213 }
1214 }
Chris Lattner78db3622009-06-22 05:51:26 +00001215 return false;
Kevin Enderby0510b482010-05-17 23:08:19 +00001216 }
Bill Wendlingcdbf17b2011-01-25 21:26:41 +00001217 case AsmToken::Real: {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001218 APFloat RealVal(APFloat::IEEEdouble(), getTok().getString());
Bob Wilson813bdf62011-02-03 23:17:47 +00001219 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Jim Grosbach13760bd2015-05-30 01:25:56 +00001220 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001221 EndLoc = Lexer.getTok().getEndLoc();
Bill Wendlingcdbf17b2011-01-25 21:26:41 +00001222 Lex(); // Eat token.
1223 return false;
1224 }
Chris Lattner6b55cb92010-04-14 04:40:28 +00001225 case AsmToken::Dot: {
1226 // This is a '.' reference, which references the current PC. Emit a
1227 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +00001228 MCSymbol *Sym = Ctx.createTempSymbol();
Chris Lattner6b55cb92010-04-14 04:40:28 +00001229 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +00001230 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001231 EndLoc = Lexer.getTok().getEndLoc();
Chris Lattner6b55cb92010-04-14 04:40:28 +00001232 Lex(); // Eat identifier.
1233 return false;
1234 }
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001235 case AsmToken::LParen:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001236 Lex(); // Eat the '('.
Jim Grosbach4b905842013-09-20 23:08:21 +00001237 return parseParenExpr(Res, EndLoc);
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +00001238 case AsmToken::LBrac:
1239 if (!PlatformParser->HasBracketExpressions())
1240 return TokError("brackets expression not supported on this target");
1241 Lex(); // Eat the '['.
Jim Grosbach4b905842013-09-20 23:08:21 +00001242 return parseBracketExpr(Res, EndLoc);
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001243 case AsmToken::Minus:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001244 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001245 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001246 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +00001247 Res = MCUnaryExpr::createMinus(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001248 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001249 case AsmToken::Plus:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001250 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001251 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001252 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +00001253 Res = MCUnaryExpr::createPlus(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001254 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001255 case AsmToken::Tilde:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001256 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001257 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001258 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +00001259 Res = MCUnaryExpr::createNot(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001260 return false;
Daniel Sanders3feeb9c2016-08-08 11:50:25 +00001261 // MIPS unary expression operators. The lexer won't generate these tokens if
1262 // MCAsmInfo::HasMipsExpressions is false for the target.
1263 case AsmToken::PercentCall16:
1264 case AsmToken::PercentCall_Hi:
1265 case AsmToken::PercentCall_Lo:
1266 case AsmToken::PercentDtprel_Hi:
1267 case AsmToken::PercentDtprel_Lo:
1268 case AsmToken::PercentGot:
1269 case AsmToken::PercentGot_Disp:
1270 case AsmToken::PercentGot_Hi:
1271 case AsmToken::PercentGot_Lo:
1272 case AsmToken::PercentGot_Ofst:
1273 case AsmToken::PercentGot_Page:
1274 case AsmToken::PercentGottprel:
1275 case AsmToken::PercentGp_Rel:
1276 case AsmToken::PercentHi:
1277 case AsmToken::PercentHigher:
1278 case AsmToken::PercentHighest:
1279 case AsmToken::PercentLo:
1280 case AsmToken::PercentNeg:
1281 case AsmToken::PercentPcrel_Hi:
1282 case AsmToken::PercentPcrel_Lo:
1283 case AsmToken::PercentTlsgd:
1284 case AsmToken::PercentTlsldm:
1285 case AsmToken::PercentTprel_Hi:
1286 case AsmToken::PercentTprel_Lo:
1287 Lex(); // Eat the operator.
1288 if (Lexer.isNot(AsmToken::LParen))
1289 return TokError("expected '(' after operator");
1290 Lex(); // Eat the operator.
1291 if (parseExpression(Res, EndLoc))
1292 return true;
1293 if (Lexer.isNot(AsmToken::RParen))
1294 return TokError("expected ')'");
1295 Lex(); // Eat the operator.
1296 Res = getTargetParser().createTargetUnaryExpr(Res, FirstTokenKind, Ctx);
1297 return !Res;
Chris Lattner78db3622009-06-22 05:51:26 +00001298 }
1299}
Chris Lattner7fdbce72009-06-22 06:32:03 +00001300
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001301bool AsmParser::parseExpression(const MCExpr *&Res) {
Chris Lattnere17df0b2010-01-15 19:39:23 +00001302 SMLoc EndLoc;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001303 return parseExpression(Res, EndLoc);
Chris Lattner528d00b2010-01-15 19:28:38 +00001304}
1305
Daniel Dunbar55f16672010-09-17 02:47:07 +00001306const MCExpr *
Jim Grosbach4b905842013-09-20 23:08:21 +00001307AsmParser::applyModifierToExpr(const MCExpr *E,
Daniel Dunbar55f16672010-09-17 02:47:07 +00001308 MCSymbolRefExpr::VariantKind Variant) {
Joerg Sonnenbergerb822af42013-08-27 20:23:19 +00001309 // Ask the target implementation about this expression first.
1310 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
1311 if (NewE)
1312 return NewE;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001313 // Recurse over the given expression, rebuilding it to apply the given variant
1314 // if there is exactly one symbol.
1315 switch (E->getKind()) {
1316 case MCExpr::Target:
1317 case MCExpr::Constant:
Craig Topper353eda42014-04-24 06:44:33 +00001318 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001319
1320 case MCExpr::SymbolRef: {
1321 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
1322
1323 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001324 TokError("invalid variant on expression '" + getTok().getIdentifier() +
1325 "' (already modified)");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001326 return E;
1327 }
1328
Jim Grosbach13760bd2015-05-30 01:25:56 +00001329 return MCSymbolRefExpr::create(&SRE->getSymbol(), Variant, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001330 }
1331
1332 case MCExpr::Unary: {
1333 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +00001334 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001335 if (!Sub)
Craig Topper353eda42014-04-24 06:44:33 +00001336 return nullptr;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001337 return MCUnaryExpr::create(UE->getOpcode(), Sub, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001338 }
1339
1340 case MCExpr::Binary: {
1341 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +00001342 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
1343 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001344
1345 if (!LHS && !RHS)
Craig Topper353eda42014-04-24 06:44:33 +00001346 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001347
Jim Grosbach4b905842013-09-20 23:08:21 +00001348 if (!LHS)
1349 LHS = BE->getLHS();
1350 if (!RHS)
1351 RHS = BE->getRHS();
Daniel Dunbar55f16672010-09-17 02:47:07 +00001352
Jim Grosbach13760bd2015-05-30 01:25:56 +00001353 return MCBinaryExpr::create(BE->getOpcode(), LHS, RHS, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001354 }
1355 }
Daniel Dunbarbaad46c2010-09-17 16:34:24 +00001356
Craig Toppera2886c22012-02-07 05:05:23 +00001357 llvm_unreachable("Invalid expression kind!");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001358}
1359
Michael Zuckerman763e60e2017-05-04 10:37:00 +00001360/// This function checks if the next token is <string> type or arithmetic.
1361/// string that begin with character '<' must end with character '>'.
1362/// otherwise it is arithmetics.
1363/// If the function returns a 'true' value,
1364/// the End argument will be filled with the last location pointed to the '>'
1365/// character.
1366
Craig Topper3da977b2018-09-25 19:37:35 +00001367/// There is a gap between the AltMacro's documentation and the single quote
1368/// implementation. GCC does not fully support this feature and so we will not
1369/// support it.
Michael Zuckerman763e60e2017-05-04 10:37:00 +00001370/// TODO: Adding single quote as a string.
Craig Topperd2aab832018-09-25 20:13:55 +00001371static bool isAltmacroString(SMLoc &StrLoc, SMLoc &EndLoc) {
Craig Topperc06ee832018-09-25 18:33:00 +00001372 assert((StrLoc.getPointer() != nullptr) &&
Michael Zuckerman763e60e2017-05-04 10:37:00 +00001373 "Argument to the function cannot be a NULL value");
1374 const char *CharPtr = StrLoc.getPointer();
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00001375 while ((*CharPtr != '>') && (*CharPtr != '\n') && (*CharPtr != '\r') &&
1376 (*CharPtr != '\0')) {
1377 if (*CharPtr == '!')
1378 CharPtr++;
Michael Zuckerman763e60e2017-05-04 10:37:00 +00001379 CharPtr++;
1380 }
1381 if (*CharPtr == '>') {
1382 EndLoc = StrLoc.getFromPointer(CharPtr + 1);
1383 return true;
1384 }
1385 return false;
1386}
1387
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001388/// creating a string without the escape characters '!'.
Craig Topperd2aab832018-09-25 20:13:55 +00001389static std::string altMacroString(StringRef AltMacroStr) {
1390 std::string Res;
Michael Zuckermanff298792017-05-10 14:00:57 +00001391 for (size_t Pos = 0; Pos < AltMacroStr.size(); Pos++) {
Michael Zuckerman1f1a9122017-05-10 13:08:11 +00001392 if (AltMacroStr[Pos] == '!')
1393 Pos++;
1394 Res += AltMacroStr[Pos];
1395 }
Craig Topperd2aab832018-09-25 20:13:55 +00001396 return Res;
Michael Zuckerman1f1a9122017-05-10 13:08:11 +00001397}
1398
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001399/// Parse an expression and return it.
Michael J. Spencer530ce852010-10-09 11:00:50 +00001400///
Jim Grosbachbd164242011-08-20 16:24:13 +00001401/// expr ::= expr &&,|| expr -> lowest.
1402/// expr ::= expr |,^,&,! expr
1403/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1404/// expr ::= expr <<,>> expr
1405/// expr ::= expr +,- expr
1406/// expr ::= expr *,/,% expr -> highest.
Chris Lattner7fdbce72009-06-22 06:32:03 +00001407/// expr ::= primaryexpr
1408///
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001409bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001410 // Parse the expression.
Craig Topper353eda42014-04-24 06:44:33 +00001411 Res = nullptr;
Nirav Dave7fd992a2018-08-16 16:31:14 +00001412 if (getTargetParser().parsePrimaryExpr(Res, EndLoc) ||
1413 parseBinOpRHS(1, Res, EndLoc))
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001414 return true;
1415
Daniel Dunbar55f16672010-09-17 02:47:07 +00001416 // As a special case, we support 'a op b @ modifier' by rewriting the
1417 // expression to include the modifier. This is inefficient, but in general we
1418 // expect users to use 'a@modifier op b'.
1419 if (Lexer.getKind() == AsmToken::At) {
1420 Lex();
1421
1422 if (Lexer.isNot(AsmToken::Identifier))
1423 return TokError("unexpected symbol modifier following '@'");
1424
1425 MCSymbolRefExpr::VariantKind Variant =
Jim Grosbach4b905842013-09-20 23:08:21 +00001426 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001427 if (Variant == MCSymbolRefExpr::VK_Invalid)
1428 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1429
Jim Grosbach4b905842013-09-20 23:08:21 +00001430 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001431 if (!ModifiedRes) {
1432 return TokError("invalid modifier '" + getTok().getIdentifier() +
1433 "' (no symbols present)");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001434 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001435
Daniel Dunbar55f16672010-09-17 02:47:07 +00001436 Res = ModifiedRes;
1437 Lex();
1438 }
1439
Nirav Dave6c0665e2018-04-30 19:22:40 +00001440 // Try to constant fold it up front, if possible. Do not exploit
1441 // assembler here.
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001442 int64_t Value;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001443 if (Res->evaluateAsAbsolute(Value))
1444 Res = MCConstantExpr::create(Value, getContext());
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001445
1446 return false;
Chris Lattner7fdbce72009-06-22 06:32:03 +00001447}
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001448
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001449bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Craig Topper353eda42014-04-24 06:44:33 +00001450 Res = nullptr;
Jim Grosbach4b905842013-09-20 23:08:21 +00001451 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
Daniel Dunbar7c82d562009-08-31 08:08:17 +00001452}
1453
Toma Tabacu7bc44dc2015-06-25 09:52:02 +00001454bool AsmParser::parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
1455 SMLoc &EndLoc) {
1456 if (parseParenExpr(Res, EndLoc))
1457 return true;
1458
1459 for (; ParenDepth > 0; --ParenDepth) {
1460 if (parseBinOpRHS(1, Res, EndLoc))
1461 return true;
1462
1463 // We don't Lex() the last RParen.
1464 // This is the same behavior as parseParenExpression().
1465 if (ParenDepth - 1 > 0) {
Nirav Davea645433c2016-07-18 15:24:03 +00001466 EndLoc = getTok().getEndLoc();
1467 if (parseToken(AsmToken::RParen,
1468 "expected ')' in parentheses expression"))
1469 return true;
Toma Tabacu7bc44dc2015-06-25 09:52:02 +00001470 }
1471 }
1472 return false;
1473}
1474
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001475bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
Daniel Dunbarf3636452009-08-31 08:07:22 +00001476 const MCExpr *Expr;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001477
Daniel Dunbar75630b32009-06-30 02:10:03 +00001478 SMLoc StartLoc = Lexer.getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001479 if (parseExpression(Expr))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001480 return true;
1481
Nirav Dave6c0665e2018-04-30 19:22:40 +00001482 if (!Expr->evaluateAsAbsolute(Res, getStreamer().getAssemblerPtr()))
Daniel Dunbar75630b32009-06-30 02:10:03 +00001483 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001484
1485 return false;
1486}
1487
David Majnemer0993e0b2015-10-26 03:15:34 +00001488static unsigned getDarwinBinOpPrecedence(AsmToken::TokenKind K,
1489 MCBinaryExpr::Opcode &Kind,
1490 bool ShouldUseLogicalShr) {
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001491 switch (K) {
Daniel Dunbar940cda22009-08-31 08:07:44 +00001492 default:
Jim Grosbach4b905842013-09-20 23:08:21 +00001493 return 0; // not a binop.
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001494
Jim Grosbach4b905842013-09-20 23:08:21 +00001495 // Lowest Precedence: &&, ||
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001496 case AsmToken::AmpAmp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001497 Kind = MCBinaryExpr::LAnd;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001498 return 1;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001499 case AsmToken::PipePipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001500 Kind = MCBinaryExpr::LOr;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001501 return 1;
1502
Jim Grosbach4b905842013-09-20 23:08:21 +00001503 // Low Precedence: |, &, ^
1504 //
1505 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001506 case AsmToken::Pipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001507 Kind = MCBinaryExpr::Or;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001508 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001509 case AsmToken::Caret:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001510 Kind = MCBinaryExpr::Xor;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001511 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001512 case AsmToken::Amp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001513 Kind = MCBinaryExpr::And;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001514 return 2;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001515
Jim Grosbach4b905842013-09-20 23:08:21 +00001516 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001517 case AsmToken::EqualEqual:
1518 Kind = MCBinaryExpr::EQ;
1519 return 3;
1520 case AsmToken::ExclaimEqual:
1521 case AsmToken::LessGreater:
1522 Kind = MCBinaryExpr::NE;
1523 return 3;
1524 case AsmToken::Less:
1525 Kind = MCBinaryExpr::LT;
1526 return 3;
1527 case AsmToken::LessEqual:
1528 Kind = MCBinaryExpr::LTE;
1529 return 3;
1530 case AsmToken::Greater:
1531 Kind = MCBinaryExpr::GT;
1532 return 3;
1533 case AsmToken::GreaterEqual:
1534 Kind = MCBinaryExpr::GTE;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001535 return 3;
1536
Jim Grosbach4b905842013-09-20 23:08:21 +00001537 // Intermediate Precedence: <<, >>
Jim Grosbachbd164242011-08-20 16:24:13 +00001538 case AsmToken::LessLess:
1539 Kind = MCBinaryExpr::Shl;
1540 return 4;
1541 case AsmToken::GreaterGreater:
David Majnemer0993e0b2015-10-26 03:15:34 +00001542 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
Jim Grosbachbd164242011-08-20 16:24:13 +00001543 return 4;
1544
Jim Grosbach4b905842013-09-20 23:08:21 +00001545 // High Intermediate Precedence: +, -
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001546 case AsmToken::Plus:
1547 Kind = MCBinaryExpr::Add;
Jim Grosbachbd164242011-08-20 16:24:13 +00001548 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001549 case AsmToken::Minus:
1550 Kind = MCBinaryExpr::Sub;
Jim Grosbachbd164242011-08-20 16:24:13 +00001551 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001552
Jim Grosbach4b905842013-09-20 23:08:21 +00001553 // Highest Precedence: *, /, %
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001554 case AsmToken::Star:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001555 Kind = MCBinaryExpr::Mul;
Jim Grosbachbd164242011-08-20 16:24:13 +00001556 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001557 case AsmToken::Slash:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001558 Kind = MCBinaryExpr::Div;
Jim Grosbachbd164242011-08-20 16:24:13 +00001559 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001560 case AsmToken::Percent:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001561 Kind = MCBinaryExpr::Mod;
Jim Grosbachbd164242011-08-20 16:24:13 +00001562 return 6;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001563 }
1564}
1565
David Majnemer0993e0b2015-10-26 03:15:34 +00001566static unsigned getGNUBinOpPrecedence(AsmToken::TokenKind K,
1567 MCBinaryExpr::Opcode &Kind,
1568 bool ShouldUseLogicalShr) {
1569 switch (K) {
1570 default:
1571 return 0; // not a binop.
1572
1573 // Lowest Precedence: &&, ||
1574 case AsmToken::AmpAmp:
1575 Kind = MCBinaryExpr::LAnd;
1576 return 2;
1577 case AsmToken::PipePipe:
1578 Kind = MCBinaryExpr::LOr;
1579 return 1;
1580
1581 // Low Precedence: ==, !=, <>, <, <=, >, >=
1582 case AsmToken::EqualEqual:
1583 Kind = MCBinaryExpr::EQ;
1584 return 3;
1585 case AsmToken::ExclaimEqual:
1586 case AsmToken::LessGreater:
1587 Kind = MCBinaryExpr::NE;
1588 return 3;
1589 case AsmToken::Less:
1590 Kind = MCBinaryExpr::LT;
1591 return 3;
1592 case AsmToken::LessEqual:
1593 Kind = MCBinaryExpr::LTE;
1594 return 3;
1595 case AsmToken::Greater:
1596 Kind = MCBinaryExpr::GT;
1597 return 3;
1598 case AsmToken::GreaterEqual:
1599 Kind = MCBinaryExpr::GTE;
1600 return 3;
1601
1602 // Low Intermediate Precedence: +, -
1603 case AsmToken::Plus:
1604 Kind = MCBinaryExpr::Add;
1605 return 4;
1606 case AsmToken::Minus:
1607 Kind = MCBinaryExpr::Sub;
1608 return 4;
1609
1610 // High Intermediate Precedence: |, &, ^
1611 //
1612 // FIXME: gas seems to support '!' as an infix operator?
1613 case AsmToken::Pipe:
1614 Kind = MCBinaryExpr::Or;
1615 return 5;
1616 case AsmToken::Caret:
1617 Kind = MCBinaryExpr::Xor;
1618 return 5;
1619 case AsmToken::Amp:
1620 Kind = MCBinaryExpr::And;
1621 return 5;
1622
1623 // Highest Precedence: *, /, %, <<, >>
1624 case AsmToken::Star:
1625 Kind = MCBinaryExpr::Mul;
1626 return 6;
1627 case AsmToken::Slash:
1628 Kind = MCBinaryExpr::Div;
1629 return 6;
1630 case AsmToken::Percent:
1631 Kind = MCBinaryExpr::Mod;
1632 return 6;
1633 case AsmToken::LessLess:
1634 Kind = MCBinaryExpr::Shl;
1635 return 6;
1636 case AsmToken::GreaterGreater:
1637 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1638 return 6;
1639 }
1640}
1641
1642unsigned AsmParser::getBinOpPrecedence(AsmToken::TokenKind K,
1643 MCBinaryExpr::Opcode &Kind) {
1644 bool ShouldUseLogicalShr = MAI.shouldUseLogicalShr();
1645 return IsDarwin ? getDarwinBinOpPrecedence(K, Kind, ShouldUseLogicalShr)
1646 : getGNUBinOpPrecedence(K, Kind, ShouldUseLogicalShr);
1647}
1648
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001649/// Parse all binary operators with precedence >= 'Precedence'.
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001650/// Res contains the LHS of the expression on input.
Jim Grosbach4b905842013-09-20 23:08:21 +00001651bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
Chris Lattner528d00b2010-01-15 19:28:38 +00001652 SMLoc &EndLoc) {
Chad Rosier9245e122017-01-19 20:06:32 +00001653 SMLoc StartLoc = Lexer.getLoc();
Eugene Zelenko33d7b762016-08-23 17:14:32 +00001654 while (true) {
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001655 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001656 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001657
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001658 // If the next token is lower precedence than we are allowed to eat, return
1659 // successfully with what we ate already.
1660 if (TokPrec < Precedence)
1661 return false;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001662
Sean Callanan686ed8d2010-01-19 20:22:31 +00001663 Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +00001664
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001665 // Eat the next primary expression.
Daniel Dunbarf3636452009-08-31 08:07:22 +00001666 const MCExpr *RHS;
Nirav Dave7fd992a2018-08-16 16:31:14 +00001667 if (getTargetParser().parsePrimaryExpr(RHS, EndLoc))
Jim Grosbach4b905842013-09-20 23:08:21 +00001668 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001669
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001670 // If BinOp binds less tightly with RHS than the operator after RHS, let
1671 // the pending operator take RHS as its LHS.
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001672 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001673 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Jim Grosbach4b905842013-09-20 23:08:21 +00001674 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1675 return true;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001676
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001677 // Merge LHS and RHS according to operator.
Chad Rosier9245e122017-01-19 20:06:32 +00001678 Res = MCBinaryExpr::create(Kind, Res, RHS, getContext(), StartLoc);
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001679 }
1680}
1681
Chris Lattner36e02122009-06-21 20:54:55 +00001682/// ParseStatement:
1683/// ::= EndOfStatement
Chris Lattnere5074c42009-06-22 01:29:09 +00001684/// ::= Label* Directive ...Operands... EndOfStatement
1685/// ::= Label* Identifier OperandList* EndOfStatement
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001686bool AsmParser::parseStatement(ParseStatementInfo &Info,
1687 MCAsmParserSemaCallback *SI) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001688 assert(!hasPendingError() && "parseStatement started with pending error");
Nirav Davefd910412016-06-17 16:06:17 +00001689 // Eat initial spaces and comments
1690 while (Lexer.is(AsmToken::Space))
1691 Lex();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001692 if (Lexer.is(AsmToken::EndOfStatement)) {
Nirav Davefd910412016-06-17 16:06:17 +00001693 // if this is a line comment we can drop it safely
Nirav Dave670109d2017-06-09 14:04:03 +00001694 if (getTok().getString().empty() || getTok().getString().front() == '\r' ||
Nirav Davefd910412016-06-17 16:06:17 +00001695 getTok().getString().front() == '\n')
1696 Out.AddBlankLine();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001697 Lex();
Chris Lattner36e02122009-06-21 20:54:55 +00001698 return false;
Chris Lattner36e02122009-06-21 20:54:55 +00001699 }
Nirav Davefd910412016-06-17 16:06:17 +00001700 // Statements always start with an identifier.
Sean Callanan936b0d32010-01-19 21:44:56 +00001701 AsmToken ID = getTok();
Daniel Dunbaree4465c2009-07-28 16:38:40 +00001702 SMLoc IDLoc = ID.getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001703 StringRef IDVal;
Kevin Enderby0510b482010-05-17 23:08:19 +00001704 int64_t LocalLabelVal = -1;
Nirav Davefd910412016-06-17 16:06:17 +00001705 if (Lexer.is(AsmToken::HashDirective))
Jim Grosbach4b905842013-09-20 23:08:21 +00001706 return parseCppHashLineFilenameComment(IDLoc);
Kevin Enderbyfa3c6f12010-12-24 00:12:02 +00001707 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderby0510b482010-05-17 23:08:19 +00001708 if (Lexer.is(AsmToken::Integer)) {
1709 LocalLabelVal = getTok().getIntVal();
1710 if (LocalLabelVal < 0) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001711 if (!TheCondState.Ignore) {
1712 Lex(); // always eat a token
1713 return Error(IDLoc, "unexpected token at start of statement");
1714 }
Kevin Enderby0510b482010-05-17 23:08:19 +00001715 IDVal = "";
Eli Bendersky88024712013-01-16 19:32:36 +00001716 } else {
Kevin Enderby0510b482010-05-17 23:08:19 +00001717 IDVal = getTok().getString();
1718 Lex(); // Consume the integer token to be used as an identifier token.
1719 if (Lexer.getKind() != AsmToken::Colon) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001720 if (!TheCondState.Ignore) {
1721 Lex(); // always eat a token
1722 return Error(IDLoc, "unexpected token at start of statement");
1723 }
Kevin Enderby0510b482010-05-17 23:08:19 +00001724 }
1725 }
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001726 } else if (Lexer.is(AsmToken::Dot)) {
1727 // Treat '.' as a valid identifier in this context.
1728 Lex();
1729 IDVal = ".";
Colin LeMahieu8a0453e2015-11-09 00:31:07 +00001730 } else if (Lexer.is(AsmToken::LCurly)) {
1731 // Treat '{' as a valid identifier in this context.
1732 Lex();
1733 IDVal = "{";
1734
1735 } else if (Lexer.is(AsmToken::RCurly)) {
1736 // Treat '}' as a valid identifier in this context.
1737 Lex();
1738 IDVal = "}";
Yonghong Song06ff6552017-09-12 17:55:23 +00001739 } else if (Lexer.is(AsmToken::Star) &&
1740 getTargetParser().starIsStartOfStatement()) {
1741 // Accept '*' as a valid start of statement.
1742 Lex();
1743 IDVal = "*";
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001744 } else if (parseIdentifier(IDVal)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001745 if (!TheCondState.Ignore) {
1746 Lex(); // always eat a token
1747 return Error(IDLoc, "unexpected token at start of statement");
1748 }
Chris Lattner926885c2010-04-17 18:14:27 +00001749 IDVal = "";
1750 }
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001751
Chris Lattner926885c2010-04-17 18:14:27 +00001752 // Handle conditional assembly here before checking for skipping. We
1753 // have to do this so that .endif isn't skipped in a ".if 0" block for
1754 // example.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001755 StringMap<DirectiveKind>::const_iterator DirKindIt =
Jim Grosbach4b905842013-09-20 23:08:21 +00001756 DirectiveKindMap.find(IDVal);
1757 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
Nilanjana Basuda60fc82019-08-05 14:16:58 +00001758
Jim Grosbach4b905842013-09-20 23:08:21 +00001759 ? DK_NO_DIRECTIVE
1760 : DirKindIt->getValue();
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001761 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001762 default:
1763 break;
1764 case DK_IF:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001765 case DK_IFEQ:
1766 case DK_IFGE:
1767 case DK_IFGT:
1768 case DK_IFLE:
1769 case DK_IFLT:
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00001770 case DK_IFNE:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001771 return parseDirectiveIf(IDLoc, DirKind);
Jim Grosbach4b905842013-09-20 23:08:21 +00001772 case DK_IFB:
1773 return parseDirectiveIfb(IDLoc, true);
1774 case DK_IFNB:
1775 return parseDirectiveIfb(IDLoc, false);
1776 case DK_IFC:
1777 return parseDirectiveIfc(IDLoc, true);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00001778 case DK_IFEQS:
Sid Manning51c35602015-03-18 14:20:54 +00001779 return parseDirectiveIfeqs(IDLoc, true);
Jim Grosbach4b905842013-09-20 23:08:21 +00001780 case DK_IFNC:
1781 return parseDirectiveIfc(IDLoc, false);
Sid Manning51c35602015-03-18 14:20:54 +00001782 case DK_IFNES:
1783 return parseDirectiveIfeqs(IDLoc, false);
Jim Grosbach4b905842013-09-20 23:08:21 +00001784 case DK_IFDEF:
1785 return parseDirectiveIfdef(IDLoc, true);
1786 case DK_IFNDEF:
1787 case DK_IFNOTDEF:
1788 return parseDirectiveIfdef(IDLoc, false);
1789 case DK_ELSEIF:
1790 return parseDirectiveElseIf(IDLoc);
1791 case DK_ELSE:
1792 return parseDirectiveElse(IDLoc);
1793 case DK_ENDIF:
1794 return parseDirectiveEndIf(IDLoc);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001795 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001796
Eli Bendersky88024712013-01-16 19:32:36 +00001797 // Ignore the statement if in the middle of inactive conditional
1798 // (e.g. ".if 0").
Chad Rosiereda70b32012-10-20 00:47:08 +00001799 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001800 eatToEndOfStatement();
Chris Lattner926885c2010-04-17 18:14:27 +00001801 return false;
1802 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001803
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001804 // FIXME: Recurse on local labels?
1805
1806 // See what kind of statement we have.
1807 switch (Lexer.getKind()) {
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001808 case AsmToken::Colon: {
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001809 if (!getTargetParser().isLabel(ID))
1810 break;
Nirav Davef43cc9f2016-10-10 15:24:54 +00001811 if (checkForValidSection())
1812 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00001813
Chris Lattner36e02122009-06-21 20:54:55 +00001814 // identifier ':' -> Label.
Sean Callanan686ed8d2010-01-19 20:22:31 +00001815 Lex();
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001816
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001817 // Diagnose attempt to use '.' as a label.
1818 if (IDVal == ".")
1819 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1820
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001821 // Diagnose attempt to use a variable as a label.
1822 //
1823 // FIXME: Diagnostics. Note the location of the definition as a label.
1824 // FIXME: This doesn't diagnose assignment to a symbol which has been
1825 // implicitly marked as external.
Kevin Enderby0510b482010-05-17 23:08:19 +00001826 MCSymbol *Sym;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001827 if (LocalLabelVal == -1) {
1828 if (ParsingInlineAsm && SI) {
Nico Weber67e715f2015-06-19 23:43:47 +00001829 StringRef RewrittenLabel =
1830 SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true);
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00001831 assert(!RewrittenLabel.empty() &&
Nico Weber67e715f2015-06-19 23:43:47 +00001832 "We should have an internal name here.");
Craig Topper7d5b2312015-10-10 05:25:02 +00001833 Info.AsmRewrites->emplace_back(AOK_Label, IDLoc, IDVal.size(),
1834 RewrittenLabel);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001835 IDVal = RewrittenLabel;
1836 }
Jim Grosbach6f482002015-05-18 18:43:14 +00001837 Sym = getContext().getOrCreateSymbol(IDVal);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001838 } else
Jim Grosbach6f482002015-05-18 18:43:14 +00001839 Sym = Ctx.createDirectionalLocalSymbol(LocalLabelVal);
Nirav Dave9263ae32016-08-02 19:17:54 +00001840 // End of Labels should be treated as end of line for lexing
1841 // purposes but that information is not available to the Lexer who
1842 // does not understand Labels. This may cause us to see a Hash
1843 // here instead of a preprocessor line comment.
1844 if (getTok().is(AsmToken::Hash)) {
1845 StringRef CommentStr = parseStringToEndOfStatement();
1846 Lexer.Lex();
1847 Lexer.UnLex(AsmToken(AsmToken::EndOfStatement, CommentStr));
1848 }
1849
Nirav Dave8ea792d2016-07-13 14:03:12 +00001850 // Consume any end of statement token, if present, to avoid spurious
1851 // AddBlankLine calls().
1852 if (getTok().is(AsmToken::EndOfStatement)) {
1853 Lex();
1854 }
1855
Maya Madhavanec1efe42018-09-20 05:11:42 +00001856 getTargetParser().doBeforeLabelEmit(Sym);
1857
Daniel Dunbare73b2672009-08-26 22:13:22 +00001858 // Emit the label.
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +00001859 if (!getTargetParser().isParsingInlineAsm())
Rafael Espindolabe991572017-02-10 15:13:12 +00001860 Out.EmitLabel(Sym, IDLoc);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001861
Kevin Enderbye7739d42011-12-09 18:09:40 +00001862 // If we are generating dwarf for assembly source files then gather the
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001863 // info to make a dwarf label entry for this label if needed.
Paul Robinson938d9a02018-03-22 15:48:01 +00001864 if (enabledGenDwarfForAssembly())
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001865 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1866 IDLoc);
Kevin Enderbye7739d42011-12-09 18:09:40 +00001867
Tim Northover1744d0a2013-10-25 12:49:50 +00001868 getTargetParser().onLabelParsed(Sym);
1869
Eli Friedman0f4871d2012-10-22 23:58:19 +00001870 return false;
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001871 }
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001872
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001873 case AsmToken::Equal:
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001874 if (!getTargetParser().equalIsAsmAssignment())
1875 break;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001876 // identifier '=' ... -> assignment statement
Sean Callanan686ed8d2010-01-19 20:22:31 +00001877 Lex();
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001878
Nirav Dave7fd992a2018-08-16 16:31:14 +00001879 return parseAssignment(IDVal, true);
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001880
1881 default: // Normal instruction or directive.
1882 break;
Chris Lattner36e02122009-06-21 20:54:55 +00001883 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001884
1885 // If macros are enabled, check to see if this is a macro instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00001886 if (areMacrosEnabled())
Rafael Espindola22c38a02018-02-14 16:34:27 +00001887 if (const MCAsmMacro *M = getContext().lookupMacro(IDVal)) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001888 return handleMacroEntry(M, IDLoc);
Eli Bendersky38274122013-01-14 23:22:36 +00001889 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001890
Michael J. Spencer530ce852010-10-09 11:00:50 +00001891 // Otherwise, we have a normal instruction or directive.
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001892
Eli Bendersky17233942013-01-15 22:59:42 +00001893 // Directives start with "."
Ana Pazos353f67a2018-08-25 01:34:32 +00001894 if (IDVal.startswith(".") && IDVal != ".") {
Eli Bendersky17233942013-01-15 22:59:42 +00001895 // There are several entities interested in parsing directives:
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001896 //
Eli Bendersky17233942013-01-15 22:59:42 +00001897 // 1. The target-specific assembly parser. Some directives are target
1898 // specific or may potentially behave differently on certain targets.
1899 // 2. Asm parser extensions. For example, platform-specific parsers
1900 // (like the ELF parser) register themselves as extensions.
1901 // 3. The generic directive parser implemented by this class. These are
1902 // all the directives that behave in a target and platform independent
1903 // manner, or at least have a default behavior that's shared between
1904 // all targets and platforms.
Akira Hatanakad3590752012-07-05 19:09:33 +00001905
Oliver Stannard21718282016-07-26 14:19:47 +00001906 getTargetParser().flushPendingInstructions(getStreamer());
1907
Nirav Dave2364748a2016-09-16 18:30:20 +00001908 SMLoc StartTokLoc = getTok().getLoc();
1909 bool TPDirectiveReturn = getTargetParser().ParseDirective(ID);
1910
1911 if (hasPendingError())
1912 return true;
1913 // Currently the return value should be true if we are
1914 // uninterested but as this is at odds with the standard parsing
1915 // convention (return true = error) we have instances of a parsed
1916 // directive that fails returning true as an error. Catch these
1917 // cases as best as possible errors here.
1918 if (TPDirectiveReturn && StartTokLoc != getTok().getLoc())
1919 return true;
1920 // Return if we did some parsing or believe we succeeded.
1921 if (!TPDirectiveReturn || StartTokLoc != getTok().getLoc())
Akira Hatanakad3590752012-07-05 19:09:33 +00001922 return false;
1923
Alp Tokercb402912014-01-24 17:20:08 +00001924 // Next, check the extension directive map to see if any extension has
Eli Bendersky17233942013-01-15 22:59:42 +00001925 // registered itself to parse this directive.
Jim Grosbach4b905842013-09-20 23:08:21 +00001926 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1927 ExtensionDirectiveMap.lookup(IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +00001928 if (Handler.first)
1929 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1930
1931 // Finally, if no one else is interested in this directive, it must be
1932 // generic and familiar to this class.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001933 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001934 default:
1935 break;
1936 case DK_SET:
1937 case DK_EQU:
1938 return parseDirectiveSet(IDVal, true);
1939 case DK_EQUIV:
1940 return parseDirectiveSet(IDVal, false);
1941 case DK_ASCII:
1942 return parseDirectiveAscii(IDVal, false);
1943 case DK_ASCIZ:
1944 case DK_STRING:
1945 return parseDirectiveAscii(IDVal, true);
1946 case DK_BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001947 case DK_DC_B:
1948 return parseDirectiveValue(IDVal, 1);
1949 case DK_DC:
1950 case DK_DC_W:
Jim Grosbach4b905842013-09-20 23:08:21 +00001951 case DK_SHORT:
1952 case DK_VALUE:
1953 case DK_2BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001954 return parseDirectiveValue(IDVal, 2);
Jim Grosbach4b905842013-09-20 23:08:21 +00001955 case DK_LONG:
1956 case DK_INT:
1957 case DK_4BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001958 case DK_DC_L:
1959 return parseDirectiveValue(IDVal, 4);
Jim Grosbach4b905842013-09-20 23:08:21 +00001960 case DK_QUAD:
1961 case DK_8BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001962 return parseDirectiveValue(IDVal, 8);
1963 case DK_DC_A:
Konstantin Zhuravlyovdc77b2e2017-04-17 17:41:25 +00001964 return parseDirectiveValue(
1965 IDVal, getContext().getAsmInfo()->getCodePointerSize());
David Woodhoused6de0d92014-02-01 16:20:59 +00001966 case DK_OCTA:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001967 return parseDirectiveOctaValue(IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001968 case DK_SINGLE:
1969 case DK_FLOAT:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001970 case DK_DC_S:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001971 return parseDirectiveRealValue(IDVal, APFloat::IEEEsingle());
Jim Grosbach4b905842013-09-20 23:08:21 +00001972 case DK_DOUBLE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001973 case DK_DC_D:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001974 return parseDirectiveRealValue(IDVal, APFloat::IEEEdouble());
Jim Grosbach4b905842013-09-20 23:08:21 +00001975 case DK_ALIGN: {
1976 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1977 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1978 }
1979 case DK_ALIGN32: {
1980 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1981 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1982 }
1983 case DK_BALIGN:
1984 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1985 case DK_BALIGNW:
1986 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1987 case DK_BALIGNL:
1988 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1989 case DK_P2ALIGN:
1990 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1991 case DK_P2ALIGNW:
1992 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1993 case DK_P2ALIGNL:
1994 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1995 case DK_ORG:
1996 return parseDirectiveOrg();
1997 case DK_FILL:
1998 return parseDirectiveFill();
1999 case DK_ZERO:
2000 return parseDirectiveZero();
2001 case DK_EXTERN:
2002 eatToEndOfStatement(); // .extern is the default, ignore it.
2003 return false;
2004 case DK_GLOBL:
2005 case DK_GLOBAL:
2006 return parseDirectiveSymbolAttribute(MCSA_Global);
2007 case DK_LAZY_REFERENCE:
2008 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
2009 case DK_NO_DEAD_STRIP:
2010 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
2011 case DK_SYMBOL_RESOLVER:
2012 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
2013 case DK_PRIVATE_EXTERN:
2014 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
2015 case DK_REFERENCE:
2016 return parseDirectiveSymbolAttribute(MCSA_Reference);
2017 case DK_WEAK_DEFINITION:
2018 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
2019 case DK_WEAK_REFERENCE:
2020 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
2021 case DK_WEAK_DEF_CAN_BE_HIDDEN:
2022 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
Vedant Kumar13ef84f2019-01-25 18:30:22 +00002023 case DK_COLD:
2024 return parseDirectiveSymbolAttribute(MCSA_Cold);
Jim Grosbach4b905842013-09-20 23:08:21 +00002025 case DK_COMM:
2026 case DK_COMMON:
2027 return parseDirectiveComm(/*IsLocal=*/false);
2028 case DK_LCOMM:
2029 return parseDirectiveComm(/*IsLocal=*/true);
2030 case DK_ABORT:
2031 return parseDirectiveAbort();
2032 case DK_INCLUDE:
2033 return parseDirectiveInclude();
2034 case DK_INCBIN:
2035 return parseDirectiveIncbin();
2036 case DK_CODE16:
2037 case DK_CODE16GCC:
Nirav Davefd910412016-06-17 16:06:17 +00002038 return TokError(Twine(IDVal) +
2039 " not currently supported for this target");
Jim Grosbach4b905842013-09-20 23:08:21 +00002040 case DK_REPT:
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00002041 return parseDirectiveRept(IDLoc, IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00002042 case DK_IRP:
2043 return parseDirectiveIrp(IDLoc);
2044 case DK_IRPC:
2045 return parseDirectiveIrpc(IDLoc);
2046 case DK_ENDR:
2047 return parseDirectiveEndr(IDLoc);
2048 case DK_BUNDLE_ALIGN_MODE:
2049 return parseDirectiveBundleAlignMode();
2050 case DK_BUNDLE_LOCK:
2051 return parseDirectiveBundleLock();
2052 case DK_BUNDLE_UNLOCK:
2053 return parseDirectiveBundleUnlock();
2054 case DK_SLEB128:
2055 return parseDirectiveLEB128(true);
2056 case DK_ULEB128:
2057 return parseDirectiveLEB128(false);
2058 case DK_SPACE:
2059 case DK_SKIP:
2060 return parseDirectiveSpace(IDVal);
2061 case DK_FILE:
2062 return parseDirectiveFile(IDLoc);
2063 case DK_LINE:
2064 return parseDirectiveLine();
2065 case DK_LOC:
2066 return parseDirectiveLoc();
2067 case DK_STABS:
2068 return parseDirectiveStabs();
Reid Kleckner2214ed82016-01-29 00:49:42 +00002069 case DK_CV_FILE:
2070 return parseDirectiveCVFile();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00002071 case DK_CV_FUNC_ID:
2072 return parseDirectiveCVFuncId();
2073 case DK_CV_INLINE_SITE_ID:
2074 return parseDirectiveCVInlineSiteId();
Reid Kleckner2214ed82016-01-29 00:49:42 +00002075 case DK_CV_LOC:
2076 return parseDirectiveCVLoc();
2077 case DK_CV_LINETABLE:
2078 return parseDirectiveCVLinetable();
David Majnemer6fcbd7e2016-01-29 19:24:12 +00002079 case DK_CV_INLINE_LINETABLE:
2080 return parseDirectiveCVInlineLinetable();
David Majnemer408b5e62016-02-05 01:55:49 +00002081 case DK_CV_DEF_RANGE:
2082 return parseDirectiveCVDefRange();
Reid Kleckner06d02d02018-09-07 21:30:52 +00002083 case DK_CV_STRING:
2084 return parseDirectiveCVString();
Reid Kleckner2214ed82016-01-29 00:49:42 +00002085 case DK_CV_STRINGTABLE:
2086 return parseDirectiveCVStringTable();
2087 case DK_CV_FILECHECKSUMS:
2088 return parseDirectiveCVFileChecksums();
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00002089 case DK_CV_FILECHECKSUM_OFFSET:
2090 return parseDirectiveCVFileChecksumOffset();
Reid Kleckner9cdd4df2017-10-11 21:24:33 +00002091 case DK_CV_FPO_DATA:
2092 return parseDirectiveCVFPOData();
Jim Grosbach4b905842013-09-20 23:08:21 +00002093 case DK_CFI_SECTIONS:
2094 return parseDirectiveCFISections();
2095 case DK_CFI_STARTPROC:
2096 return parseDirectiveCFIStartProc();
2097 case DK_CFI_ENDPROC:
2098 return parseDirectiveCFIEndProc();
2099 case DK_CFI_DEF_CFA:
2100 return parseDirectiveCFIDefCfa(IDLoc);
2101 case DK_CFI_DEF_CFA_OFFSET:
2102 return parseDirectiveCFIDefCfaOffset();
2103 case DK_CFI_ADJUST_CFA_OFFSET:
2104 return parseDirectiveCFIAdjustCfaOffset();
2105 case DK_CFI_DEF_CFA_REGISTER:
2106 return parseDirectiveCFIDefCfaRegister(IDLoc);
2107 case DK_CFI_OFFSET:
2108 return parseDirectiveCFIOffset(IDLoc);
2109 case DK_CFI_REL_OFFSET:
2110 return parseDirectiveCFIRelOffset(IDLoc);
2111 case DK_CFI_PERSONALITY:
2112 return parseDirectiveCFIPersonalityOrLsda(true);
2113 case DK_CFI_LSDA:
2114 return parseDirectiveCFIPersonalityOrLsda(false);
2115 case DK_CFI_REMEMBER_STATE:
2116 return parseDirectiveCFIRememberState();
2117 case DK_CFI_RESTORE_STATE:
2118 return parseDirectiveCFIRestoreState();
2119 case DK_CFI_SAME_VALUE:
2120 return parseDirectiveCFISameValue(IDLoc);
2121 case DK_CFI_RESTORE:
2122 return parseDirectiveCFIRestore(IDLoc);
2123 case DK_CFI_ESCAPE:
2124 return parseDirectiveCFIEscape();
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +00002125 case DK_CFI_RETURN_COLUMN:
2126 return parseDirectiveCFIReturnColumn(IDLoc);
Jim Grosbach4b905842013-09-20 23:08:21 +00002127 case DK_CFI_SIGNAL_FRAME:
2128 return parseDirectiveCFISignalFrame();
2129 case DK_CFI_UNDEFINED:
2130 return parseDirectiveCFIUndefined(IDLoc);
2131 case DK_CFI_REGISTER:
2132 return parseDirectiveCFIRegister(IDLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00002133 case DK_CFI_WINDOW_SAVE:
2134 return parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +00002135 case DK_MACROS_ON:
2136 case DK_MACROS_OFF:
2137 return parseDirectiveMacrosOnOff(IDVal);
2138 case DK_MACRO:
2139 return parseDirectiveMacro(IDLoc);
Michael Zuckerman56704612017-05-01 13:20:12 +00002140 case DK_ALTMACRO:
2141 case DK_NOALTMACRO:
2142 return parseDirectiveAltmacro(IDVal);
Nico Weber155dccd12014-07-24 17:08:39 +00002143 case DK_EXITM:
2144 return parseDirectiveExitMacro(IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00002145 case DK_ENDM:
2146 case DK_ENDMACRO:
2147 return parseDirectiveEndMacro(IDVal);
2148 case DK_PURGEM:
2149 return parseDirectivePurgeMacro(IDLoc);
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00002150 case DK_END:
2151 return parseDirectiveEnd(IDLoc);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00002152 case DK_ERR:
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00002153 return parseDirectiveError(IDLoc, false);
2154 case DK_ERROR:
2155 return parseDirectiveError(IDLoc, true);
Nico Weber404012b2014-07-24 16:26:06 +00002156 case DK_WARNING:
2157 return parseDirectiveWarning(IDLoc);
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002158 case DK_RELOC:
2159 return parseDirectiveReloc(IDLoc);
Petr Hosek4cb08ce2016-09-23 19:25:15 +00002160 case DK_DCB:
2161 case DK_DCB_W:
2162 return parseDirectiveDCB(IDVal, 2);
2163 case DK_DCB_B:
2164 return parseDirectiveDCB(IDVal, 1);
2165 case DK_DCB_D:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002166 return parseDirectiveRealDCB(IDVal, APFloat::IEEEdouble());
Petr Hosek4cb08ce2016-09-23 19:25:15 +00002167 case DK_DCB_L:
2168 return parseDirectiveDCB(IDVal, 4);
2169 case DK_DCB_S:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002170 return parseDirectiveRealDCB(IDVal, APFloat::IEEEsingle());
Petr Hosek731bb9c2016-08-23 21:34:53 +00002171 case DK_DC_X:
Petr Hosek4cb08ce2016-09-23 19:25:15 +00002172 case DK_DCB_X:
Petr Hosek731bb9c2016-08-23 21:34:53 +00002173 return TokError(Twine(IDVal) +
2174 " not currently supported for this target");
Petr Hosek85b2f672016-09-23 21:53:36 +00002175 case DK_DS:
2176 case DK_DS_W:
2177 return parseDirectiveDS(IDVal, 2);
2178 case DK_DS_B:
2179 return parseDirectiveDS(IDVal, 1);
2180 case DK_DS_D:
2181 return parseDirectiveDS(IDVal, 8);
2182 case DK_DS_L:
2183 case DK_DS_S:
2184 return parseDirectiveDS(IDVal, 4);
2185 case DK_DS_P:
2186 case DK_DS_X:
2187 return parseDirectiveDS(IDVal, 12);
Coby Tayree01e53202017-10-02 14:36:31 +00002188 case DK_PRINT:
2189 return parseDirectivePrint(IDLoc);
Peter Collingbourne3e227332018-07-17 22:17:18 +00002190 case DK_ADDRSIG:
2191 return parseDirectiveAddrsig();
2192 case DK_ADDRSIG_SYM:
2193 return parseDirectiveAddrsigSym();
Eli Friedman20b02642010-07-19 04:17:25 +00002194 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002195
Jim Grosbach758e0cc2012-05-01 18:38:27 +00002196 return Error(IDLoc, "unknown directive");
Chris Lattnere5074c42009-06-22 01:29:09 +00002197 }
Chris Lattner36e02122009-06-21 20:54:55 +00002198
Chad Rosierc7f552c2013-02-12 21:33:51 +00002199 // __asm _emit or __asm __emit
2200 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
2201 IDVal == "_EMIT" || IDVal == "__EMIT"))
Jim Grosbach4b905842013-09-20 23:08:21 +00002202 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
Chad Rosierc7f552c2013-02-12 21:33:51 +00002203
2204 // __asm align
2205 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
Jim Grosbach4b905842013-09-20 23:08:21 +00002206 return parseDirectiveMSAlign(IDLoc, Info);
Eli Friedman0f4871d2012-10-22 23:58:19 +00002207
Coby Tayree3847be92017-04-04 17:57:23 +00002208 if (ParsingInlineAsm && (IDVal == "even" || IDVal == "EVEN"))
Michael Zuckerman02ecd432015-12-13 17:07:23 +00002209 Info.AsmRewrites->emplace_back(AOK_EVEN, IDLoc, 4);
Nirav Davef43cc9f2016-10-10 15:24:54 +00002210 if (checkForValidSection())
2211 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00002212
Chris Lattner7cbfa442010-05-19 23:34:33 +00002213 // Canonicalize the opcode to lower case.
Eli Bendersky88024712013-01-16 19:32:36 +00002214 std::string OpcodeStr = IDVal.lower();
Chad Rosierf0e87202012-10-25 20:41:34 +00002215 ParseInstructionInfo IInfo(Info.AsmRewrites);
Nirav Dave2364748a2016-09-16 18:30:20 +00002216 bool ParseHadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, ID,
2217 Info.ParsedOperands);
2218 Info.ParseError = ParseHadError;
Chris Lattnere5074c42009-06-22 01:29:09 +00002219
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002220 // Dump the parsed representation, if requested.
2221 if (getShowParsedOperands()) {
2222 SmallString<256> Str;
2223 raw_svector_ostream OS(Str);
2224 OS << "parsed instruction: [";
Eli Friedman0f4871d2012-10-22 23:58:19 +00002225 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002226 if (i != 0)
2227 OS << ", ";
Eli Friedman0f4871d2012-10-22 23:58:19 +00002228 Info.ParsedOperands[i]->print(OS);
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002229 }
2230 OS << "]";
2231
Jim Grosbach4b905842013-09-20 23:08:21 +00002232 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002233 }
2234
Nirav Dave2364748a2016-09-16 18:30:20 +00002235 // Fail even if ParseInstruction erroneously returns false.
2236 if (hasPendingError() || ParseHadError)
2237 return true;
2238
Oliver Stannard8b273082014-06-19 15:52:37 +00002239 // If we are generating dwarf for the current section then generate a .loc
2240 // directive for the instruction.
Paul Robinson938d9a02018-03-22 15:48:01 +00002241 if (!ParseHadError && enabledGenDwarfForAssembly() &&
Oliver Stannard8b273082014-06-19 15:52:37 +00002242 getContext().getGenDwarfSectionSyms().count(
Eric Christopher445c9522016-10-14 05:47:37 +00002243 getStreamer().getCurrentSectionOnly())) {
Saleem Abdulrasool4d6ed7c2014-12-24 06:32:43 +00002244 unsigned Line;
2245 if (ActiveMacros.empty())
2246 Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
2247 else
Frederic Riss16238d92015-06-25 21:57:33 +00002248 Line = SrcMgr.FindLineNumber(ActiveMacros.front()->InstantiationLoc,
2249 ActiveMacros.front()->ExitBuffer);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002250
Eli Bendersky88024712013-01-16 19:32:36 +00002251 // If we previously parsed a cpp hash file line comment then make sure the
2252 // current Dwarf File is for the CppHashFilename if not then emit the
2253 // Dwarf File table for it and adjust the line number for the .loc.
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00002254 if (!CppHashInfo.Filename.empty()) {
David Blaikiec714ef42014-03-17 01:52:11 +00002255 unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
Tim Northoverc0bef992016-04-13 19:46:54 +00002256 0, StringRef(), CppHashInfo.Filename);
David Blaikiec714ef42014-03-17 01:52:11 +00002257 getContext().setGenDwarfFileNumber(FileNumber);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002258
Graydon Hoare54fe2082018-04-07 00:44:02 +00002259 unsigned CppHashLocLineNo =
2260 SrcMgr.FindLineNumber(CppHashInfo.Loc, CppHashInfo.Buf);
Tim Northoverc0bef992016-04-13 19:46:54 +00002261 Line = CppHashInfo.LineNumber - 1 + (Line - CppHashLocLineNo);
Eli Bendersky88024712013-01-16 19:32:36 +00002262 }
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002263
Jim Grosbach4b905842013-09-20 23:08:21 +00002264 getStreamer().EmitDwarfLocDirective(
2265 getContext().getGenDwarfFileNumber(), Line, 0,
2266 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
2267 StringRef());
Kevin Enderby6469fc22011-11-01 22:27:22 +00002268 }
2269
Daniel Dunbarce0c1e12010-05-04 00:33:07 +00002270 // If parsing succeeded, match the instruction.
Nirav Dave2364748a2016-09-16 18:30:20 +00002271 if (!ParseHadError) {
Tim Northover26bb14e2014-08-18 11:49:42 +00002272 uint64_t ErrorInfo;
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +00002273 if (getTargetParser().MatchAndEmitInstruction(
2274 IDLoc, Info.Opcode, Info.ParsedOperands, Out, ErrorInfo,
2275 getTargetParser().isParsingInlineAsm()))
Nirav Dave2364748a2016-09-16 18:30:20 +00002276 return true;
Chad Rosier49963552012-10-13 00:26:04 +00002277 }
Chris Lattnera2a9d162010-09-11 16:18:25 +00002278 return false;
Chris Lattnerb0133452009-06-21 20:16:42 +00002279}
Chris Lattnerbedf6c22009-06-24 04:43:34 +00002280
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00002281// Parse and erase curly braces marking block start/end
Sam Cleggf009da22018-04-19 22:00:53 +00002282bool
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00002283AsmParser::parseCurlyBlockScope(SmallVectorImpl<AsmRewrite> &AsmStrRewrites) {
2284 // Identify curly brace marking block start/end
2285 if (Lexer.isNot(AsmToken::LCurly) && Lexer.isNot(AsmToken::RCurly))
2286 return false;
2287
2288 SMLoc StartLoc = Lexer.getLoc();
2289 Lex(); // Eat the brace
2290 if (Lexer.is(AsmToken::EndOfStatement))
2291 Lex(); // Eat EndOfStatement following the brace
2292
2293 // Erase the block start/end brace from the output asm string
2294 AsmStrRewrites.emplace_back(AOK_Skip, StartLoc, Lexer.getLoc().getPointer() -
2295 StartLoc.getPointer());
2296 return true;
2297}
2298
Jim Grosbach4b905842013-09-20 23:08:21 +00002299/// parseCppHashLineFilenameComment as this:
Kevin Enderby72553612011-09-13 23:45:18 +00002300/// ::= # number "filename"
Craig Topper3c76c522015-09-20 23:35:59 +00002301bool AsmParser::parseCppHashLineFilenameComment(SMLoc L) {
Kevin Enderby72553612011-09-13 23:45:18 +00002302 Lex(); // Eat the hash token.
Nirav Davefd910412016-06-17 16:06:17 +00002303 // Lexer only ever emits HashDirective if it fully formed if it's
2304 // done the checking already so this is an internal error.
2305 assert(getTok().is(AsmToken::Integer) &&
2306 "Lexing Cpp line comment: Expected Integer");
Kevin Enderby72553612011-09-13 23:45:18 +00002307 int64_t LineNumber = getTok().getIntVal();
Kevin Enderby72553612011-09-13 23:45:18 +00002308 Lex();
Nirav Davefd910412016-06-17 16:06:17 +00002309 assert(getTok().is(AsmToken::String) &&
2310 "Lexing Cpp line comment: Expected String");
Kevin Enderby72553612011-09-13 23:45:18 +00002311 StringRef Filename = getTok().getString();
Nirav Davefd910412016-06-17 16:06:17 +00002312 Lex();
Nirav Dave2364748a2016-09-16 18:30:20 +00002313
Kevin Enderby72553612011-09-13 23:45:18 +00002314 // Get rid of the enclosing quotes.
Jim Grosbach4b905842013-09-20 23:08:21 +00002315 Filename = Filename.substr(1, Filename.size() - 2);
Kevin Enderby72553612011-09-13 23:45:18 +00002316
Paul Robinson9c563262019-05-21 11:59:03 +00002317 // Save the SMLoc, Filename and LineNumber for later use by diagnostics
2318 // and possibly DWARF file info.
Tim Northoverc0bef992016-04-13 19:46:54 +00002319 CppHashInfo.Loc = L;
2320 CppHashInfo.Filename = Filename;
2321 CppHashInfo.LineNumber = LineNumber;
2322 CppHashInfo.Buf = CurBuffer;
Paul Robinson9c563262019-05-21 11:59:03 +00002323 if (FirstCppHashFilename.empty())
2324 FirstCppHashFilename = Filename;
Kevin Enderby72553612011-09-13 23:45:18 +00002325 return false;
2326}
2327
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002328/// will use the last parsed cpp hash line filename comment
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002329/// for the Filename and LineNo if any in the diagnostic.
2330void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002331 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002332 raw_ostream &OS = errs();
2333
2334 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
Craig Topper3c76c522015-09-20 23:35:59 +00002335 SMLoc DiagLoc = Diag.getLoc();
Alp Tokera55b95b2014-07-06 10:33:31 +00002336 unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2337 unsigned CppHashBuf =
Tim Northoverc0bef992016-04-13 19:46:54 +00002338 Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashInfo.Loc);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002339
Jim Grosbach4b905842013-09-20 23:08:21 +00002340 // Like SourceMgr::printMessage() we need to print the include stack if any
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002341 // before printing the message.
Alp Tokera55b95b2014-07-06 10:33:31 +00002342 unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2343 if (!Parser->SavedDiagHandler && DiagCurBuffer &&
2344 DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002345 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
2346 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002347 }
2348
Eric Christophera7c32732012-12-18 00:30:54 +00002349 // If we have not parsed a cpp hash line filename comment or the source
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002350 // manager changed or buffer changed (like in a nested include) then just
2351 // print the normal diagnostic using its Filename and LineNo.
Tim Northoverc0bef992016-04-13 19:46:54 +00002352 if (!Parser->CppHashInfo.LineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002353 DiagBuf != CppHashBuf) {
Benjamin Kramer47f5e302011-10-16 10:48:29 +00002354 if (Parser->SavedDiagHandler)
2355 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
2356 else
Craig Topper353eda42014-04-24 06:44:33 +00002357 Diag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002358 return;
2359 }
2360
Eric Christophera7c32732012-12-18 00:30:54 +00002361 // Use the CppHashFilename and calculate a line number based on the
Tim Northoverc0bef992016-04-13 19:46:54 +00002362 // CppHashInfo.Loc and CppHashInfo.LineNumber relative to this Diag's SMLoc
2363 // for the diagnostic.
2364 const std::string &Filename = Parser->CppHashInfo.Filename;
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002365
2366 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
2367 int CppHashLocLineNo =
Tim Northoverc0bef992016-04-13 19:46:54 +00002368 Parser->SrcMgr.FindLineNumber(Parser->CppHashInfo.Loc, CppHashBuf);
Jim Grosbach4b905842013-09-20 23:08:21 +00002369 int LineNo =
Tim Northoverc0bef992016-04-13 19:46:54 +00002370 Parser->CppHashInfo.LineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002371
Jim Grosbach4b905842013-09-20 23:08:21 +00002372 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
2373 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
Chris Lattner72845262011-10-16 05:47:55 +00002374 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002375
Benjamin Kramer47f5e302011-10-16 10:48:29 +00002376 if (Parser->SavedDiagHandler)
2377 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
2378 else
Craig Topper353eda42014-04-24 06:44:33 +00002379 NewDiag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002380}
2381
Rafael Espindola2c064482012-08-21 18:29:30 +00002382// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
2383// difference being that that function accepts '@' as part of identifiers and
2384// we can't do that. AsmLexer.cpp should probably be changed to handle
2385// '@' as a special case when needed.
2386static bool isIdentifierChar(char c) {
Guy Benyei83c74e92013-02-12 21:21:59 +00002387 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
2388 c == '.';
Rafael Espindola2c064482012-08-21 18:29:30 +00002389}
2390
Rafael Espindola34b9c512012-06-03 23:57:14 +00002391bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00002392 ArrayRef<MCAsmMacroParameter> Parameters,
Toma Tabacu217116e2015-04-27 10:50:29 +00002393 ArrayRef<MCAsmMacroArgument> A,
Craig Topper3c76c522015-09-20 23:35:59 +00002394 bool EnableAtPseudoVariable, SMLoc L) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00002395 unsigned NParameters = Parameters.size();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002396 bool HasVararg = NParameters ? Parameters.back().Vararg : false;
Benjamin Kramer513e7442014-02-20 13:36:32 +00002397 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
Rafael Espindola1134ab232011-06-05 02:43:45 +00002398 return Error(L, "Wrong number of arguments");
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002399
Preston Gurd05500642012-09-19 20:36:12 +00002400 // A macro without parameters is handled differently on Darwin:
2401 // gas accepts no arguments and does no substitutions
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002402 while (!Body.empty()) {
2403 // Scan for the next substitution.
2404 std::size_t End = Body.size(), Pos = 0;
2405 for (; Pos != End; ++Pos) {
2406 // Check for a substitution or escape.
Benjamin Kramer513e7442014-02-20 13:36:32 +00002407 if (IsDarwin && !NParameters) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00002408 // This macro has no parameters, look for $0, $1, etc.
2409 if (Body[Pos] != '$' || Pos + 1 == End)
2410 continue;
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002411
Rafael Espindola1134ab232011-06-05 02:43:45 +00002412 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00002413 if (Next == '$' || Next == 'n' ||
2414 isdigit(static_cast<unsigned char>(Next)))
Rafael Espindola1134ab232011-06-05 02:43:45 +00002415 break;
2416 } else {
2417 // This macro has parameters, look for \foo, \bar, etc.
2418 if (Body[Pos] == '\\' && Pos + 1 != End)
2419 break;
2420 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002421 }
2422
2423 // Add the prefix.
2424 OS << Body.slice(0, Pos);
2425
2426 // Check if we reached the end.
2427 if (Pos == End)
2428 break;
2429
Benjamin Kramer513e7442014-02-20 13:36:32 +00002430 if (IsDarwin && !NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002431 switch (Body[Pos + 1]) {
2432 // $$ => $
Rafael Espindola1134ab232011-06-05 02:43:45 +00002433 case '$':
2434 OS << '$';
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002435 break;
2436
Jim Grosbach4b905842013-09-20 23:08:21 +00002437 // $n => number of arguments
Rafael Espindola1134ab232011-06-05 02:43:45 +00002438 case 'n':
2439 OS << A.size();
2440 break;
2441
Jim Grosbach4b905842013-09-20 23:08:21 +00002442 // $[0-9] => argument
Rafael Espindola1134ab232011-06-05 02:43:45 +00002443 default: {
2444 // Missing arguments are ignored.
Jim Grosbach4b905842013-09-20 23:08:21 +00002445 unsigned Index = Body[Pos + 1] - '0';
Rafael Espindola1134ab232011-06-05 02:43:45 +00002446 if (Index >= A.size())
2447 break;
2448
2449 // Otherwise substitute with the token values, with spaces eliminated.
Craig Topper84008482015-10-10 05:38:14 +00002450 for (const AsmToken &Token : A[Index])
2451 OS << Token.getString();
Rafael Espindola1134ab232011-06-05 02:43:45 +00002452 break;
2453 }
2454 }
2455 Pos += 2;
2456 } else {
2457 unsigned I = Pos + 1;
Toma Tabacu217116e2015-04-27 10:50:29 +00002458
2459 // Check for the \@ pseudo-variable.
2460 if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End)
Rafael Espindola1134ab232011-06-05 02:43:45 +00002461 ++I;
Toma Tabacu217116e2015-04-27 10:50:29 +00002462 else
2463 while (isIdentifierChar(Body[I]) && I + 1 != End)
2464 ++I;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002465
Jim Grosbach4b905842013-09-20 23:08:21 +00002466 const char *Begin = Body.data() + Pos + 1;
2467 StringRef Argument(Begin, I - (Pos + 1));
Rafael Espindola1134ab232011-06-05 02:43:45 +00002468 unsigned Index = 0;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002469
Toma Tabacu217116e2015-04-27 10:50:29 +00002470 if (Argument == "@") {
2471 OS << NumOfMacroInstantiations;
2472 Pos += 2;
Preston Gurd05500642012-09-19 20:36:12 +00002473 } else {
Toma Tabacu217116e2015-04-27 10:50:29 +00002474 for (; Index < NParameters; ++Index)
2475 if (Parameters[Index].Name == Argument)
2476 break;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002477
Toma Tabacu217116e2015-04-27 10:50:29 +00002478 if (Index == NParameters) {
2479 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
2480 Pos += 3;
2481 else {
2482 OS << '\\' << Argument;
2483 Pos = I;
2484 }
2485 } else {
2486 bool VarargParameter = HasVararg && Index == (NParameters - 1);
Craig Topper84008482015-10-10 05:38:14 +00002487 for (const AsmToken &Token : A[Index])
Michael Zuckerman56704612017-05-01 13:20:12 +00002488 // For altmacro mode, you can write '%expr'.
2489 // The prefix '%' evaluates the expression 'expr'
Craig Topper3da977b2018-09-25 19:37:35 +00002490 // and uses the result as a string (e.g. replace %(1+2) with the
2491 // string "3").
Michael Zuckerman56704612017-05-01 13:20:12 +00002492 // Here, we identify the integer token which is the result of the
Craig Topper3da977b2018-09-25 19:37:35 +00002493 // absolute expression evaluation and replace it with its string
2494 // representation.
Craig Topperc81aff72018-09-25 20:55:55 +00002495 if (AltMacroMode && Token.getString().front() == '%' &&
Craig Topper3da977b2018-09-25 19:37:35 +00002496 Token.is(AsmToken::Integer))
Michael Zuckerman56704612017-05-01 13:20:12 +00002497 // Emit an integer value to the buffer.
2498 OS << Token.getIntVal();
Michael Zuckerman1f1a9122017-05-10 13:08:11 +00002499 // Only Token that was validated as a string and begins with '<'
2500 // is considered altMacroString!!!
Craig Topperc81aff72018-09-25 20:55:55 +00002501 else if (AltMacroMode && Token.getString().front() == '<' &&
Michael Zuckerman1f1a9122017-05-10 13:08:11 +00002502 Token.is(AsmToken::String)) {
Craig Topperd2aab832018-09-25 20:13:55 +00002503 OS << altMacroString(Token.getStringContents());
Michael Zuckerman1f1a9122017-05-10 13:08:11 +00002504 }
Toma Tabacu217116e2015-04-27 10:50:29 +00002505 // We expect no quotes around the string's contents when
2506 // parsing for varargs.
Michael Zuckerman56704612017-05-01 13:20:12 +00002507 else if (Token.isNot(AsmToken::String) || VarargParameter)
Craig Topper84008482015-10-10 05:38:14 +00002508 OS << Token.getString();
Toma Tabacu217116e2015-04-27 10:50:29 +00002509 else
Craig Topper84008482015-10-10 05:38:14 +00002510 OS << Token.getStringContents();
Toma Tabacu217116e2015-04-27 10:50:29 +00002511
2512 Pos += 1 + Argument.size();
2513 }
Preston Gurd05500642012-09-19 20:36:12 +00002514 }
Rafael Espindola1134ab232011-06-05 02:43:45 +00002515 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002516 // Update the scan point.
Rafael Espindola1134ab232011-06-05 02:43:45 +00002517 Body = Body.substr(Pos);
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002518 }
Daniel Dunbar43235712010-07-18 18:54:11 +00002519
Rafael Espindola1134ab232011-06-05 02:43:45 +00002520 return false;
2521}
Daniel Dunbar43235712010-07-18 18:54:11 +00002522
Nico Weber2a8f9222014-07-24 16:29:04 +00002523MacroInstantiation::MacroInstantiation(SMLoc IL, int EB, SMLoc EL,
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002524 size_t CondStackDepth)
Rafael Espindolaf43a94e2014-08-17 22:48:55 +00002525 : InstantiationLoc(IL), ExitBuffer(EB), ExitLoc(EL),
Nico Weber155dccd12014-07-24 17:08:39 +00002526 CondStackDepth(CondStackDepth) {}
Daniel Dunbar43235712010-07-18 18:54:11 +00002527
Jim Grosbach4b905842013-09-20 23:08:21 +00002528static bool isOperator(AsmToken::TokenKind kind) {
2529 switch (kind) {
2530 default:
2531 return false;
2532 case AsmToken::Plus:
2533 case AsmToken::Minus:
2534 case AsmToken::Tilde:
2535 case AsmToken::Slash:
2536 case AsmToken::Star:
2537 case AsmToken::Dot:
2538 case AsmToken::Equal:
2539 case AsmToken::EqualEqual:
2540 case AsmToken::Pipe:
2541 case AsmToken::PipePipe:
2542 case AsmToken::Caret:
2543 case AsmToken::Amp:
2544 case AsmToken::AmpAmp:
2545 case AsmToken::Exclaim:
2546 case AsmToken::ExclaimEqual:
Jim Grosbach4b905842013-09-20 23:08:21 +00002547 case AsmToken::Less:
2548 case AsmToken::LessEqual:
2549 case AsmToken::LessLess:
2550 case AsmToken::LessGreater:
2551 case AsmToken::Greater:
2552 case AsmToken::GreaterEqual:
2553 case AsmToken::GreaterGreater:
2554 return true;
Preston Gurd05500642012-09-19 20:36:12 +00002555 }
2556}
2557
David Majnemer16252452014-01-29 00:07:39 +00002558namespace {
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002559
David Majnemer16252452014-01-29 00:07:39 +00002560class AsmLexerSkipSpaceRAII {
2561public:
2562 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
2563 Lexer.setSkipSpace(SkipSpace);
2564 }
2565
2566 ~AsmLexerSkipSpaceRAII() {
2567 Lexer.setSkipSpace(true);
2568 }
2569
2570private:
2571 AsmLexer &Lexer;
2572};
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002573
2574} // end anonymous namespace
David Majnemer16252452014-01-29 00:07:39 +00002575
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002576bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
2577
2578 if (Vararg) {
2579 if (Lexer.isNot(AsmToken::EndOfStatement)) {
2580 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002581 MA.emplace_back(AsmToken::String, Str);
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002582 }
2583 return false;
2584 }
2585
Rafael Espindola768b41c2012-06-15 14:02:34 +00002586 unsigned ParenLevel = 0;
Preston Gurd05500642012-09-19 20:36:12 +00002587
David Majnemer16252452014-01-29 00:07:39 +00002588 // Darwin doesn't use spaces to delmit arguments.
2589 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
Rafael Espindola768b41c2012-06-15 14:02:34 +00002590
Scott Egertona1fa68a2016-02-11 13:48:49 +00002591 bool SpaceEaten;
2592
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002593 while (true) {
Scott Egertona1fa68a2016-02-11 13:48:49 +00002594 SpaceEaten = false;
David Majnemer16252452014-01-29 00:07:39 +00002595 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002596 return TokError("unexpected token in macro instantiation");
Preston Gurd05500642012-09-19 20:36:12 +00002597
Scott Egertona1fa68a2016-02-11 13:48:49 +00002598 if (ParenLevel == 0) {
Preston Gurd05500642012-09-19 20:36:12 +00002599
Scott Egertona1fa68a2016-02-11 13:48:49 +00002600 if (Lexer.is(AsmToken::Comma))
2601 break;
2602
2603 if (Lexer.is(AsmToken::Space)) {
2604 SpaceEaten = true;
Nirav Dave1180e6892016-06-02 17:15:05 +00002605 Lexer.Lex(); // Eat spaces
Scott Egertona1fa68a2016-02-11 13:48:49 +00002606 }
Preston Gurd05500642012-09-19 20:36:12 +00002607
2608 // Spaces can delimit parameters, but could also be part an expression.
2609 // If the token after a space is an operator, add the token and the next
2610 // one into this argument
David Majnemer91fc4c22014-01-29 18:57:46 +00002611 if (!IsDarwin) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002612 if (isOperator(Lexer.getKind())) {
Scott Egertona1fa68a2016-02-11 13:48:49 +00002613 MA.push_back(getTok());
Nirav Dave1180e6892016-06-02 17:15:05 +00002614 Lexer.Lex();
Preston Gurd05500642012-09-19 20:36:12 +00002615
Scott Egertona1fa68a2016-02-11 13:48:49 +00002616 // Whitespace after an operator can be ignored.
2617 if (Lexer.is(AsmToken::Space))
Nirav Dave1180e6892016-06-02 17:15:05 +00002618 Lexer.Lex();
Scott Egertona1fa68a2016-02-11 13:48:49 +00002619
2620 continue;
Preston Gurd05500642012-09-19 20:36:12 +00002621 }
2622 }
Scott Egertona1fa68a2016-02-11 13:48:49 +00002623 if (SpaceEaten)
2624 break;
Preston Gurd05500642012-09-19 20:36:12 +00002625 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002626
Jim Grosbach4b905842013-09-20 23:08:21 +00002627 // handleMacroEntry relies on not advancing the lexer here
Rafael Espindola768b41c2012-06-15 14:02:34 +00002628 // to be able to fill in the remaining default parameter values
2629 if (Lexer.is(AsmToken::EndOfStatement))
2630 break;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002631
2632 // Adjust the current parentheses level.
2633 if (Lexer.is(AsmToken::LParen))
2634 ++ParenLevel;
2635 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
2636 --ParenLevel;
2637
2638 // Append the token to the current argument list.
2639 MA.push_back(getTok());
Nirav Dave1180e6892016-06-02 17:15:05 +00002640 Lexer.Lex();
Rafael Espindola768b41c2012-06-15 14:02:34 +00002641 }
Preston Gurd05500642012-09-19 20:36:12 +00002642
Rafael Espindola768b41c2012-06-15 14:02:34 +00002643 if (ParenLevel != 0)
Rafael Espindola3e5eb422012-08-21 15:55:04 +00002644 return TokError("unbalanced parentheses in macro argument");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002645 return false;
2646}
2647
2648// Parse the macro instantiation arguments.
Jim Grosbach4b905842013-09-20 23:08:21 +00002649bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
Vladimir Medic9bad0d332013-08-20 13:33:18 +00002650 MCAsmMacroArguments &A) {
Rafael Espindola768b41c2012-06-15 14:02:34 +00002651 const unsigned NParameters = M ? M->Parameters.size() : 0;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002652 bool NamedParametersFound = false;
2653 SmallVector<SMLoc, 4> FALocs;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002654
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002655 A.resize(NParameters);
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002656 FALocs.resize(NParameters);
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002657
Rafael Espindola768b41c2012-06-15 14:02:34 +00002658 // Parse two kinds of macro invocations:
2659 // - macros defined without any parameters accept an arbitrary number of them
2660 // - macros defined with parameters accept at most that many of them
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002661 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002662 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
2663 ++Parameter) {
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002664 SMLoc IDLoc = Lexer.getLoc();
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002665 MCAsmMacroParameter FA;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002666
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002667 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00002668 if (parseIdentifier(FA.Name))
2669 return Error(IDLoc, "invalid argument identifier for formal argument");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002670
Nirav Dave2364748a2016-09-16 18:30:20 +00002671 if (Lexer.isNot(AsmToken::Equal))
2672 return TokError("expected '=' after formal parameter identifier");
2673
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002674 Lex();
2675
2676 NamedParametersFound = true;
2677 }
Michael Zuckerman56704612017-05-01 13:20:12 +00002678 bool Vararg = HasVararg && Parameter == (NParameters - 1);
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002679
Nirav Dave2364748a2016-09-16 18:30:20 +00002680 if (NamedParametersFound && FA.Name.empty())
2681 return Error(IDLoc, "cannot mix positional and keyword arguments");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002682
Michael Zuckerman763e60e2017-05-04 10:37:00 +00002683 SMLoc StrLoc = Lexer.getLoc();
2684 SMLoc EndLoc;
Craig Topperc81aff72018-09-25 20:55:55 +00002685 if (AltMacroMode && Lexer.is(AsmToken::Percent)) {
Craig Topper3da977b2018-09-25 19:37:35 +00002686 const MCExpr *AbsoluteExp;
2687 int64_t Value;
2688 /// Eat '%'
2689 Lex();
2690 if (parseExpression(AbsoluteExp, EndLoc))
2691 return false;
2692 if (!AbsoluteExp->evaluateAsAbsolute(Value,
2693 getStreamer().getAssemblerPtr()))
2694 return Error(StrLoc, "expected absolute expression");
2695 const char *StrChar = StrLoc.getPointer();
2696 const char *EndChar = EndLoc.getPointer();
2697 AsmToken newToken(AsmToken::Integer,
2698 StringRef(StrChar, EndChar - StrChar), Value);
2699 FA.Value.push_back(newToken);
Craig Topperc81aff72018-09-25 20:55:55 +00002700 } else if (AltMacroMode && Lexer.is(AsmToken::Less) &&
Michael Zuckerman763e60e2017-05-04 10:37:00 +00002701 isAltmacroString(StrLoc, EndLoc)) {
Craig Topper3da977b2018-09-25 19:37:35 +00002702 const char *StrChar = StrLoc.getPointer();
2703 const char *EndChar = EndLoc.getPointer();
2704 jumpToLoc(EndLoc, CurBuffer);
2705 /// Eat from '<' to '>'
2706 Lex();
2707 AsmToken newToken(AsmToken::String,
2708 StringRef(StrChar, EndChar - StrChar));
2709 FA.Value.push_back(newToken);
Michael Zuckerman763e60e2017-05-04 10:37:00 +00002710 } else if(parseMacroArgument(FA.Value, Vararg))
Craig Topper3da977b2018-09-25 19:37:35 +00002711 return true;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002712
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002713 unsigned PI = Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002714 if (!FA.Name.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002715 unsigned FAI = 0;
2716 for (FAI = 0; FAI < NParameters; ++FAI)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002717 if (M->Parameters[FAI].Name == FA.Name)
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002718 break;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002719
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002720 if (FAI >= NParameters) {
Nirav Davefd910412016-06-17 16:06:17 +00002721 assert(M && "expected macro to be defined");
Nirav Dave2364748a2016-09-16 18:30:20 +00002722 return Error(IDLoc, "parameter named '" + FA.Name +
2723 "' does not exist for macro '" + M->Name + "'");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002724 }
2725 PI = FAI;
2726 }
2727
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002728 if (!FA.Value.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002729 if (A.size() <= PI)
2730 A.resize(PI + 1);
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002731 A[PI] = FA.Value;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002732
2733 if (FALocs.size() <= PI)
2734 FALocs.resize(PI + 1);
2735
2736 FALocs[PI] = Lexer.getLoc();
Preston Gurd242ed3152012-09-19 20:29:04 +00002737 }
Jim Grosbach206661622012-07-30 22:44:17 +00002738
Preston Gurd242ed3152012-09-19 20:29:04 +00002739 // At the end of the statement, fill in remaining arguments that have
2740 // default values. If there aren't any, then the next argument is
2741 // required but missing
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002742 if (Lexer.is(AsmToken::EndOfStatement)) {
2743 bool Failure = false;
2744 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2745 if (A[FAI].empty()) {
2746 if (M->Parameters[FAI].Required) {
2747 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2748 "missing value for required parameter "
2749 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2750 Failure = true;
2751 }
2752
2753 if (!M->Parameters[FAI].Value.empty())
2754 A[FAI] = M->Parameters[FAI].Value;
2755 }
2756 }
2757 return Failure;
2758 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002759
2760 if (Lexer.is(AsmToken::Comma))
2761 Lex();
2762 }
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002763
2764 return TokError("too many positional arguments");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002765}
2766
Jim Grosbach4b905842013-09-20 23:08:21 +00002767bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
Davide Italiano7c9fc732016-07-27 05:51:56 +00002768 // Arbitrarily limit macro nesting depth (default matches 'as'). We can
2769 // eliminate this, although we should protect against infinite loops.
2770 unsigned MaxNestingDepth = AsmMacroMaxNestingDepth;
2771 if (ActiveMacros.size() == MaxNestingDepth) {
2772 std::ostringstream MaxNestingDepthError;
2773 MaxNestingDepthError << "macros cannot be nested more than "
2774 << MaxNestingDepth << " levels deep."
2775 << " Use -asm-macro-max-nesting-depth to increase "
2776 "this limit.";
2777 return TokError(MaxNestingDepthError.str());
2778 }
Daniel Dunbar43235712010-07-18 18:54:11 +00002779
Eli Bendersky38274122013-01-14 23:22:36 +00002780 MCAsmMacroArguments A;
Jim Grosbach4b905842013-09-20 23:08:21 +00002781 if (parseMacroArguments(M, A))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002782 return true;
Daniel Dunbar43235712010-07-18 18:54:11 +00002783
Rafael Espindola1134ab232011-06-05 02:43:45 +00002784 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2785 // to hold the macro body with substitutions.
2786 SmallString<256> Buf;
2787 StringRef Body = M->Body;
Rafael Espindola34b9c512012-06-03 23:57:14 +00002788 raw_svector_ostream OS(Buf);
Rafael Espindola1134ab232011-06-05 02:43:45 +00002789
Toma Tabacu217116e2015-04-27 10:50:29 +00002790 if (expandMacro(OS, Body, M->Parameters, A, true, getTok().getLoc()))
Rafael Espindola1134ab232011-06-05 02:43:45 +00002791 return true;
2792
Eli Bendersky38274122013-01-14 23:22:36 +00002793 // We include the .endmacro in the buffer as our cue to exit the macro
Rafael Espindola34b9c512012-06-03 23:57:14 +00002794 // instantiation.
2795 OS << ".endmacro\n";
2796
Rafael Espindola3560ff22014-08-27 20:03:13 +00002797 std::unique_ptr<MemoryBuffer> Instantiation =
2798 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola1134ab232011-06-05 02:43:45 +00002799
Daniel Dunbar43235712010-07-18 18:54:11 +00002800 // Create the macro instantiation object and add to the current macro
2801 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002802 MacroInstantiation *MI = new MacroInstantiation(
2803 NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Daniel Dunbar43235712010-07-18 18:54:11 +00002804 ActiveMacros.push_back(MI);
2805
Toma Tabacu217116e2015-04-27 10:50:29 +00002806 ++NumOfMacroInstantiations;
2807
Daniel Dunbar43235712010-07-18 18:54:11 +00002808 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00002809 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00002810 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar43235712010-07-18 18:54:11 +00002811 Lex();
2812
2813 return false;
2814}
2815
Jim Grosbach4b905842013-09-20 23:08:21 +00002816void AsmParser::handleMacroExit() {
Daniel Dunbar43235712010-07-18 18:54:11 +00002817 // Jump to the EndOfStatement we should return to, and consume it.
Jim Grosbach4b905842013-09-20 23:08:21 +00002818 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
Daniel Dunbar43235712010-07-18 18:54:11 +00002819 Lex();
2820
2821 // Pop the instantiation entry.
2822 delete ActiveMacros.back();
2823 ActiveMacros.pop_back();
2824}
2825
Jim Grosbach4b905842013-09-20 23:08:21 +00002826bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
Nirav Dave7fd992a2018-08-16 16:31:14 +00002827 bool NoDeadStrip) {
Pete Cooper80d21cb2015-06-22 19:35:57 +00002828 MCSymbol *Sym;
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002829 const MCExpr *Value;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002830 if (MCParserUtils::parseAssignmentExpression(Name, allow_redef, *this, Sym,
Nirav Dave7fd992a2018-08-16 16:31:14 +00002831 Value))
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002832 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002833
Pete Cooper80d21cb2015-06-22 19:35:57 +00002834 if (!Sym) {
2835 // In the case where we parse an expression starting with a '.', we will
2836 // not generate an error, nor will we create a symbol. In this case we
2837 // should just return out.
Anders Waldenborg84809572014-02-17 20:48:32 +00002838 return false;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002839 }
David Majnemer58cb80c2014-12-24 10:27:50 +00002840
Daniel Dunbarae7ac012009-06-29 23:43:14 +00002841 // Do the assignment.
Daniel Dunbarb7b20972009-08-31 08:09:09 +00002842 Out.EmitAssignment(Sym, Value);
Jim Grosbachb7b750d2012-09-13 23:11:31 +00002843 if (NoDeadStrip)
2844 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2845
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002846 return false;
2847}
2848
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002849/// parseIdentifier:
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002850/// ::= identifier
2851/// ::= string
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002852bool AsmParser::parseIdentifier(StringRef &Res) {
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002853 // The assembler has relaxed rules for accepting identifiers, in particular we
Hans Wennborgce69d772013-10-18 20:46:28 +00002854 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2855 // separate tokens. At this level, we have already lexed so we cannot (currently)
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002856 // handle this as a context dependent token, instead we detect adjacent tokens
2857 // and return the combined identifier.
Hans Wennborgce69d772013-10-18 20:46:28 +00002858 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2859 SMLoc PrefixLoc = getLexer().getLoc();
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002860
Hans Wennborgce69d772013-10-18 20:46:28 +00002861 // Consume the prefix character, and check for a following identifier.
Nirav Daved0463322016-10-12 13:58:07 +00002862
2863 AsmToken Buf[1];
2864 Lexer.peekTokens(Buf, false);
2865
2866 if (Buf[0].isNot(AsmToken::Identifier))
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002867 return true;
2868
Hans Wennborgce69d772013-10-18 20:46:28 +00002869 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
Nirav Daved0463322016-10-12 13:58:07 +00002870 if (PrefixLoc.getPointer() + 1 != Buf[0].getLoc().getPointer())
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002871 return true;
2872
Nirav Daved0463322016-10-12 13:58:07 +00002873 // eat $ or @
2874 Lexer.Lex(); // Lexer's Lex guarantees consecutive token.
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002875 // Construct the joined identifier and consume the token.
Jim Grosbach4b905842013-09-20 23:08:21 +00002876 Res =
Hans Wennborgce69d772013-10-18 20:46:28 +00002877 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
Nirav Davefd910412016-06-17 16:06:17 +00002878 Lex(); // Parser Lex to maintain invariants.
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002879 return false;
2880 }
2881
Jim Grosbach4b905842013-09-20 23:08:21 +00002882 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002883 return true;
2884
Sean Callanan936b0d32010-01-19 21:44:56 +00002885 Res = getTok().getIdentifier();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002886
Sean Callanan686ed8d2010-01-19 20:22:31 +00002887 Lex(); // Consume the identifier token.
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002888
2889 return false;
2890}
2891
Jim Grosbach4b905842013-09-20 23:08:21 +00002892/// parseDirectiveSet:
Nico Weber4ada0d92011-01-28 03:04:41 +00002893/// ::= .equ identifier ',' expression
2894/// ::= .equiv identifier ',' expression
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002895/// ::= .set identifier ',' expression
Jim Grosbach4b905842013-09-20 23:08:21 +00002896bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002897 StringRef Name;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002898 if (check(parseIdentifier(Name), "expected identifier") ||
2899 parseToken(AsmToken::Comma) || parseAssignment(Name, allow_redef, true))
2900 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
2901 return false;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002902}
2903
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002904bool AsmParser::parseEscapedString(std::string &Data) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00002905 if (check(getTok().isNot(AsmToken::String), "expected string"))
2906 return true;
Daniel Dunbaref668c12009-08-14 18:19:52 +00002907
2908 Data = "";
Sean Callanan936b0d32010-01-19 21:44:56 +00002909 StringRef Str = getTok().getStringContents();
Daniel Dunbaref668c12009-08-14 18:19:52 +00002910 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2911 if (Str[i] != '\\') {
2912 Data += Str[i];
2913 continue;
2914 }
2915
2916 // Recognize escaped characters. Note that this escape semantics currently
Bill Wendling411f1882019-10-08 04:39:52 +00002917 // loosely follows Darwin 'as'.
Daniel Dunbaref668c12009-08-14 18:19:52 +00002918 ++i;
2919 if (i == e)
2920 return TokError("unexpected backslash at end of string");
2921
Bill Wendling411f1882019-10-08 04:39:52 +00002922 // Recognize hex sequences similarly to GNU 'as'.
2923 if (Str[i] == 'x' || Str[i] == 'X') {
2924 size_t length = Str.size();
2925 if (i + 1 >= length || !isHexDigit(Str[i + 1]))
2926 return TokError("invalid hexadecimal escape sequence");
2927
2928 // Consume hex characters. GNU 'as' reads all hexadecimal characters and
2929 // then truncates to the lower 16 bits. Seems reasonable.
2930 unsigned Value = 0;
2931 while (i + 1 < length && isHexDigit(Str[i + 1]))
2932 Value = Value * 16 + hexDigitValue(Str[++i]);
2933
2934 Data += (unsigned char)(Value & 0xFF);
2935 continue;
2936 }
2937
Daniel Dunbaref668c12009-08-14 18:19:52 +00002938 // Recognize octal sequences.
Jim Grosbach4b905842013-09-20 23:08:21 +00002939 if ((unsigned)(Str[i] - '0') <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002940 // Consume up to three octal characters.
2941 unsigned Value = Str[i] - '0';
2942
Jim Grosbach4b905842013-09-20 23:08:21 +00002943 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002944 ++i;
2945 Value = Value * 8 + (Str[i] - '0');
2946
Jim Grosbach4b905842013-09-20 23:08:21 +00002947 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002948 ++i;
2949 Value = Value * 8 + (Str[i] - '0');
2950 }
2951 }
2952
2953 if (Value > 255)
2954 return TokError("invalid octal escape sequence (out of range)");
2955
Jim Grosbach4b905842013-09-20 23:08:21 +00002956 Data += (unsigned char)Value;
Daniel Dunbaref668c12009-08-14 18:19:52 +00002957 continue;
2958 }
2959
2960 // Otherwise recognize individual escapes.
2961 switch (Str[i]) {
2962 default:
2963 // Just reject invalid escape sequences for now.
2964 return TokError("invalid escape sequence (unrecognized character)");
2965
2966 case 'b': Data += '\b'; break;
2967 case 'f': Data += '\f'; break;
2968 case 'n': Data += '\n'; break;
2969 case 'r': Data += '\r'; break;
2970 case 't': Data += '\t'; break;
2971 case '"': Data += '"'; break;
2972 case '\\': Data += '\\'; break;
2973 }
2974 }
2975
Nirav Davea645433c2016-07-18 15:24:03 +00002976 Lex();
Daniel Dunbaref668c12009-08-14 18:19:52 +00002977 return false;
2978}
2979
Jim Grosbach4b905842013-09-20 23:08:21 +00002980/// parseDirectiveAscii:
Rafael Espindola63760ba2010-10-28 20:02:27 +00002981/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002982bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00002983 auto parseOp = [&]() -> bool {
2984 std::string Data;
2985 if (checkForValidSection() || parseEscapedString(Data))
Nirav Davef43cc9f2016-10-10 15:24:54 +00002986 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002987 getStreamer().EmitBytes(Data);
2988 if (ZeroTerminated)
2989 getStreamer().EmitBytes(StringRef("\0", 1));
2990 return false;
2991 };
Daniel Dunbare5444a82010-09-09 22:42:59 +00002992
Nirav Dave1a9044b2016-10-24 14:35:29 +00002993 if (parseMany(parseOp))
2994 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbara10e5192009-06-24 23:30:00 +00002995 return false;
2996}
2997
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002998/// parseDirectiveReloc
2999/// ::= .reloc expression , identifier [ , expression ]
3000bool AsmParser::parseDirectiveReloc(SMLoc DirectiveLoc) {
3001 const MCExpr *Offset;
3002 const MCExpr *Expr = nullptr;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003003 int64_t OffsetValue;
Vladimir Stefanovic1d2714b2018-11-21 16:28:39 +00003004 SMLoc OffsetLoc = Lexer.getTok().getLoc();
Nirav Dave1a9044b2016-10-24 14:35:29 +00003005
Daniel Sanders9f6ad492015-11-12 13:33:00 +00003006 if (parseExpression(Offset))
3007 return true;
3008
Vladimir Stefanovic1d2714b2018-11-21 16:28:39 +00003009 if ((Offset->evaluateAsAbsolute(OffsetValue,
3010 getStreamer().getAssemblerPtr()) &&
3011 check(OffsetValue < 0, OffsetLoc, "expression is negative")) ||
3012 (check(Offset->getKind() != llvm::MCExpr::Constant &&
3013 Offset->getKind() != llvm::MCExpr::SymbolRef,
3014 OffsetLoc, "expected non-negative number or a label")) ||
3015 (parseToken(AsmToken::Comma, "expected comma") ||
3016 check(getTok().isNot(AsmToken::Identifier), "expected relocation name")))
Nirav Davea645433c2016-07-18 15:24:03 +00003017 return true;
Daniel Sanders9f6ad492015-11-12 13:33:00 +00003018
Daniel Sanders9f6ad492015-11-12 13:33:00 +00003019 SMLoc NameLoc = Lexer.getTok().getLoc();
3020 StringRef Name = Lexer.getTok().getIdentifier();
Nirav Davefd910412016-06-17 16:06:17 +00003021 Lex();
Daniel Sanders9f6ad492015-11-12 13:33:00 +00003022
3023 if (Lexer.is(AsmToken::Comma)) {
Nirav Davefd910412016-06-17 16:06:17 +00003024 Lex();
Daniel Sanders9f6ad492015-11-12 13:33:00 +00003025 SMLoc ExprLoc = Lexer.getLoc();
3026 if (parseExpression(Expr))
3027 return true;
3028
3029 MCValue Value;
3030 if (!Expr->evaluateAsRelocatable(Value, nullptr, nullptr))
3031 return Error(ExprLoc, "expression must be relocatable");
3032 }
3033
Nirav Davea645433c2016-07-18 15:24:03 +00003034 if (parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00003035 "unexpected token in .reloc directive"))
3036 return true;
3037
Peter Smith57f661b2018-06-06 09:40:06 +00003038 const MCTargetAsmParser &MCT = getTargetParser();
3039 const MCSubtargetInfo &STI = MCT.getSTI();
3040 if (getStreamer().EmitRelocDirective(*Offset, Name, Expr, DirectiveLoc, STI))
Nirav Dave1ab71992016-07-18 19:35:21 +00003041 return Error(NameLoc, "unknown relocation name");
3042
Daniel Sanders9f6ad492015-11-12 13:33:00 +00003043 return false;
3044}
3045
Jim Grosbach4b905842013-09-20 23:08:21 +00003046/// parseDirectiveValue
Daniel Dunbara10e5192009-06-24 23:30:00 +00003047/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00003048bool AsmParser::parseDirectiveValue(StringRef IDVal, unsigned Size) {
3049 auto parseOp = [&]() -> bool {
3050 const MCExpr *Value;
3051 SMLoc ExprLoc = getLexer().getLoc();
3052 if (checkForValidSection() || parseExpression(Value))
Nirav Davef43cc9f2016-10-10 15:24:54 +00003053 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003054 // Special case constant expressions to match code generator.
3055 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3056 assert(Size <= 8 && "Invalid size");
3057 uint64_t IntValue = MCE->getValue();
3058 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
3059 return Error(ExprLoc, "out of range literal value");
3060 getStreamer().EmitIntValue(IntValue, Size);
3061 } else
3062 getStreamer().EmitValue(Value, Size, ExprLoc);
3063 return false;
3064 };
Daniel Dunbare5444a82010-09-09 22:42:59 +00003065
Nirav Dave1a9044b2016-10-24 14:35:29 +00003066 if (parseMany(parseOp))
3067 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbara10e5192009-06-24 23:30:00 +00003068 return false;
3069}
3070
Paul Robinson01954692018-04-11 15:14:05 +00003071static bool parseHexOcta(AsmParser &Asm, uint64_t &hi, uint64_t &lo) {
3072 if (Asm.getTok().isNot(AsmToken::Integer) &&
3073 Asm.getTok().isNot(AsmToken::BigNum))
3074 return Asm.TokError("unknown token in expression");
3075 SMLoc ExprLoc = Asm.getTok().getLoc();
3076 APInt IntValue = Asm.getTok().getAPIntVal();
3077 Asm.Lex();
3078 if (!IntValue.isIntN(128))
3079 return Asm.Error(ExprLoc, "out of range literal value");
3080 if (!IntValue.isIntN(64)) {
3081 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
3082 lo = IntValue.getLoBits(64).getZExtValue();
3083 } else {
3084 hi = 0;
3085 lo = IntValue.getZExtValue();
3086 }
3087 return false;
3088}
3089
David Woodhoused6de0d92014-02-01 16:20:59 +00003090/// ParseDirectiveOctaValue
3091/// ::= .octa [ hexconstant (, hexconstant)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00003092
3093bool AsmParser::parseDirectiveOctaValue(StringRef IDVal) {
3094 auto parseOp = [&]() -> bool {
Nirav Davef43cc9f2016-10-10 15:24:54 +00003095 if (checkForValidSection())
3096 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003097 uint64_t hi, lo;
Paul Robinson01954692018-04-11 15:14:05 +00003098 if (parseHexOcta(*this, hi, lo))
3099 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003100 if (MAI.isLittleEndian()) {
3101 getStreamer().EmitIntValue(lo, 8);
3102 getStreamer().EmitIntValue(hi, 8);
3103 } else {
3104 getStreamer().EmitIntValue(hi, 8);
3105 getStreamer().EmitIntValue(lo, 8);
3106 }
3107 return false;
3108 };
David Woodhoused6de0d92014-02-01 16:20:59 +00003109
Nirav Dave1a9044b2016-10-24 14:35:29 +00003110 if (parseMany(parseOp))
3111 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
David Woodhoused6de0d92014-02-01 16:20:59 +00003112 return false;
3113}
3114
Petr Hosek4cb08ce2016-09-23 19:25:15 +00003115bool AsmParser::parseRealValue(const fltSemantics &Semantics, APInt &Res) {
3116 // We don't truly support arithmetic on floating point expressions, so we
3117 // have to manually parse unary prefixes.
3118 bool IsNeg = false;
3119 if (getLexer().is(AsmToken::Minus)) {
3120 Lexer.Lex();
3121 IsNeg = true;
3122 } else if (getLexer().is(AsmToken::Plus))
3123 Lexer.Lex();
3124
3125 if (Lexer.is(AsmToken::Error))
3126 return TokError(Lexer.getErr());
3127 if (Lexer.isNot(AsmToken::Integer) && Lexer.isNot(AsmToken::Real) &&
3128 Lexer.isNot(AsmToken::Identifier))
3129 return TokError("unexpected token in directive");
3130
3131 // Convert to an APFloat.
3132 APFloat Value(Semantics);
3133 StringRef IDVal = getTok().getString();
3134 if (getLexer().is(AsmToken::Identifier)) {
3135 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
3136 Value = APFloat::getInf(Semantics);
3137 else if (!IDVal.compare_lower("nan"))
3138 Value = APFloat::getNaN(Semantics, false, ~0);
3139 else
3140 return TokError("invalid floating point literal");
3141 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
3142 APFloat::opInvalidOp)
3143 return TokError("invalid floating point literal");
3144 if (IsNeg)
3145 Value.changeSign();
3146
3147 // Consume the numeric token.
3148 Lex();
3149
3150 Res = Value.bitcastToAPInt();
3151
3152 return false;
3153}
3154
Jim Grosbach4b905842013-09-20 23:08:21 +00003155/// parseDirectiveRealValue
Daniel Dunbar2af16532010-09-24 01:59:56 +00003156/// ::= (.single | .double) [ expression (, expression)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00003157bool AsmParser::parseDirectiveRealValue(StringRef IDVal,
3158 const fltSemantics &Semantics) {
3159 auto parseOp = [&]() -> bool {
3160 APInt AsInt;
3161 if (checkForValidSection() || parseRealValue(Semantics, AsInt))
Nirav Davef43cc9f2016-10-10 15:24:54 +00003162 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003163 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
3164 AsInt.getBitWidth() / 8);
3165 return false;
3166 };
Daniel Dunbar2af16532010-09-24 01:59:56 +00003167
Nirav Dave1a9044b2016-10-24 14:35:29 +00003168 if (parseMany(parseOp))
3169 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbar2af16532010-09-24 01:59:56 +00003170 return false;
3171}
3172
Jim Grosbach4b905842013-09-20 23:08:21 +00003173/// parseDirectiveZero
Rafael Espindola922e3f42010-09-16 15:03:59 +00003174/// ::= .zero expression
Jim Grosbach4b905842013-09-20 23:08:21 +00003175bool AsmParser::parseDirectiveZero() {
Petr Hosek67a94a72016-05-28 05:57:48 +00003176 SMLoc NumBytesLoc = Lexer.getLoc();
3177 const MCExpr *NumBytes;
Nirav Davef43cc9f2016-10-10 15:24:54 +00003178 if (checkForValidSection() || parseExpression(NumBytes))
Rafael Espindola922e3f42010-09-16 15:03:59 +00003179 return true;
3180
Rafael Espindolab91bac62010-10-05 19:42:57 +00003181 int64_t Val = 0;
3182 if (getLexer().is(AsmToken::Comma)) {
3183 Lex();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003184 if (parseAbsoluteExpression(Val))
Rafael Espindolab91bac62010-10-05 19:42:57 +00003185 return true;
3186 }
3187
Nirav Davea645433c2016-07-18 15:24:03 +00003188 if (parseToken(AsmToken::EndOfStatement,
3189 "unexpected token in '.zero' directive"))
3190 return true;
Petr Hosek67a94a72016-05-28 05:57:48 +00003191 getStreamer().emitFill(*NumBytes, Val, NumBytesLoc);
Rafael Espindola922e3f42010-09-16 15:03:59 +00003192
3193 return false;
3194}
3195
Jim Grosbach4b905842013-09-20 23:08:21 +00003196/// parseDirectiveFill
Roman Divackye33098f2013-09-24 17:44:41 +00003197/// ::= .fill expression [ , expression [ , expression ] ]
Jim Grosbach4b905842013-09-20 23:08:21 +00003198bool AsmParser::parseDirectiveFill() {
Petr Hosek67a94a72016-05-28 05:57:48 +00003199 SMLoc NumValuesLoc = Lexer.getLoc();
3200 const MCExpr *NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00003201 if (checkForValidSection() || parseExpression(NumValues))
Daniel Dunbara10e5192009-06-24 23:30:00 +00003202 return true;
3203
Roman Divackye33098f2013-09-24 17:44:41 +00003204 int64_t FillSize = 1;
3205 int64_t FillExpr = 0;
Michael J. Spencer530ce852010-10-09 11:00:50 +00003206
David Majnemer522d3db2014-02-01 07:19:38 +00003207 SMLoc SizeLoc, ExprLoc;
Daniel Dunbara10e5192009-06-24 23:30:00 +00003208
Nirav Dave1a9044b2016-10-24 14:35:29 +00003209 if (parseOptionalToken(AsmToken::Comma)) {
3210 SizeLoc = getTok().getLoc();
3211 if (parseAbsoluteExpression(FillSize))
Roman Divackye33098f2013-09-24 17:44:41 +00003212 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003213 if (parseOptionalToken(AsmToken::Comma)) {
3214 ExprLoc = getTok().getLoc();
3215 if (parseAbsoluteExpression(FillExpr))
Roman Divackye33098f2013-09-24 17:44:41 +00003216 return true;
Roman Divackye33098f2013-09-24 17:44:41 +00003217 }
3218 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003219 if (parseToken(AsmToken::EndOfStatement,
3220 "unexpected token in '.fill' directive"))
3221 return true;
Daniel Dunbara10e5192009-06-24 23:30:00 +00003222
David Majnemer522d3db2014-02-01 07:19:38 +00003223 if (FillSize < 0) {
3224 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
Petr Hosek6abd38b2016-05-28 08:20:08 +00003225 return false;
David Majnemer522d3db2014-02-01 07:19:38 +00003226 }
3227 if (FillSize > 8) {
3228 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
3229 FillSize = 8;
3230 }
Daniel Dunbara10e5192009-06-24 23:30:00 +00003231
David Majnemer522d3db2014-02-01 07:19:38 +00003232 if (!isUInt<32>(FillExpr) && FillSize > 4)
3233 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
3234
Petr Hosek67a94a72016-05-28 05:57:48 +00003235 getStreamer().emitFill(*NumValues, FillSize, FillExpr, NumValuesLoc);
Daniel Dunbara10e5192009-06-24 23:30:00 +00003236
3237 return false;
3238}
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00003239
Jim Grosbach4b905842013-09-20 23:08:21 +00003240/// parseDirectiveOrg
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00003241/// ::= .org expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00003242bool AsmParser::parseDirectiveOrg() {
Daniel Dunbar897ffad2009-08-31 08:09:28 +00003243 const MCExpr *Offset;
Oliver Stannard268f42f2016-12-14 10:43:58 +00003244 SMLoc OffsetLoc = Lexer.getLoc();
Nirav Davef43cc9f2016-10-10 15:24:54 +00003245 if (checkForValidSection() || parseExpression(Offset))
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00003246 return true;
3247
3248 // Parse optional fill expression.
3249 int64_t FillExpr = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003250 if (parseOptionalToken(AsmToken::Comma))
3251 if (parseAbsoluteExpression(FillExpr))
3252 return addErrorSuffix(" in '.org' directive");
3253 if (parseToken(AsmToken::EndOfStatement))
3254 return addErrorSuffix(" in '.org' directive");
Nirav Davea645433c2016-07-18 15:24:03 +00003255
Oliver Stannard268f42f2016-12-14 10:43:58 +00003256 getStreamer().emitValueToOffset(Offset, FillExpr, OffsetLoc);
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00003257 return false;
3258}
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003259
Jim Grosbach4b905842013-09-20 23:08:21 +00003260/// parseDirectiveAlign
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003261/// ::= {.align, ...} expression [ , expression [ , expression ]]
Jim Grosbach4b905842013-09-20 23:08:21 +00003262bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003263 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003264 int64_t Alignment;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003265 SMLoc MaxBytesLoc;
3266 bool HasFillExpr = false;
3267 int64_t FillExpr = 0;
3268 int64_t MaxBytesToFill = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003269
3270 auto parseAlign = [&]() -> bool {
Coby Tayreed483a102017-08-02 17:36:10 +00003271 if (parseAbsoluteExpression(Alignment))
Nirav Davea645433c2016-07-18 15:24:03 +00003272 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003273 if (parseOptionalToken(AsmToken::Comma)) {
3274 // The fill expression can be omitted while specifying a maximum number of
3275 // alignment bytes, e.g:
3276 // .align 3,,4
3277 if (getTok().isNot(AsmToken::Comma)) {
3278 HasFillExpr = true;
3279 if (parseAbsoluteExpression(FillExpr))
3280 return true;
3281 }
3282 if (parseOptionalToken(AsmToken::Comma))
3283 if (parseTokenLoc(MaxBytesLoc) ||
3284 parseAbsoluteExpression(MaxBytesToFill))
3285 return true;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003286 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003287 return parseToken(AsmToken::EndOfStatement);
3288 };
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003289
Coby Tayreed483a102017-08-02 17:36:10 +00003290 if (checkForValidSection())
3291 return addErrorSuffix(" in directive");
3292 // Ignore empty '.p2align' directives for GNU-as compatibility
3293 if (IsPow2 && (ValueSize == 1) && getTok().is(AsmToken::EndOfStatement)) {
3294 Warning(AlignmentLoc, "p2align directive with no operand(s) is ignored");
3295 return parseToken(AsmToken::EndOfStatement);
3296 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003297 if (parseAlign())
3298 return addErrorSuffix(" in directive");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003299
Nirav Dave2364748a2016-09-16 18:30:20 +00003300 // Always emit an alignment here even if we thrown an error.
3301 bool ReturnVal = false;
3302
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003303 // Compute alignment in bytes.
3304 if (IsPow2) {
3305 // FIXME: Diagnose overflow.
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003306 if (Alignment >= 32) {
Nirav Dave2364748a2016-09-16 18:30:20 +00003307 ReturnVal |= Error(AlignmentLoc, "invalid alignment value");
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003308 Alignment = 31;
3309 }
3310
Benjamin Kramer63951ad2009-09-06 09:35:10 +00003311 Alignment = 1ULL << Alignment;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00003312 } else {
Davide Italianocb2da712015-09-08 18:59:47 +00003313 // Reject alignments that aren't either a power of two or zero,
3314 // for gas compatibility. Alignment of zero is silently rounded
3315 // up to one.
3316 if (Alignment == 0)
3317 Alignment = 1;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00003318 if (!isPowerOf2_64(Alignment))
Nirav Dave2364748a2016-09-16 18:30:20 +00003319 ReturnVal |= Error(AlignmentLoc, "alignment must be a power of 2");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003320 }
3321
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003322 // Diagnose non-sensical max bytes to align.
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003323 if (MaxBytesLoc.isValid()) {
3324 if (MaxBytesToFill < 1) {
Nirav Dave2364748a2016-09-16 18:30:20 +00003325 ReturnVal |= Error(MaxBytesLoc,
3326 "alignment directive can never be satisfied in this "
Jim Grosbach4b905842013-09-20 23:08:21 +00003327 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar4abcccb2009-08-21 23:01:53 +00003328 MaxBytesToFill = 0;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003329 }
3330
3331 if (MaxBytesToFill >= Alignment) {
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +00003332 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
Jim Grosbach4b905842013-09-20 23:08:21 +00003333 "has no effect");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003334 MaxBytesToFill = 0;
3335 }
3336 }
3337
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003338 // Check whether we should use optimal code alignment for this .align
3339 // directive.
Eric Christopher445c9522016-10-14 05:47:37 +00003340 const MCSection *Section = getStreamer().getCurrentSectionOnly();
Saleem Abdulrasool7f2f9f42014-03-21 05:13:23 +00003341 assert(Section && "must have section to emit alignment");
3342 bool UseCodeAlign = Section->UseCodeAlign();
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003343 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
3344 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003345 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003346 } else {
Kevin Enderby7f993022010-02-25 18:46:04 +00003347 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnerc2b36752010-07-15 21:19:31 +00003348 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
3349 MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003350 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003351
Nirav Dave2364748a2016-09-16 18:30:20 +00003352 return ReturnVal;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003353}
3354
Jim Grosbach4b905842013-09-20 23:08:21 +00003355/// parseDirectiveFile
Paul Robinson29f5f982018-01-09 23:31:48 +00003356/// ::= .file filename
Scott Linder16c7bda2018-02-23 23:01:06 +00003357/// ::= .file number [directory] filename [md5 checksum] [source source-text]
Jim Grosbach4b905842013-09-20 23:08:21 +00003358bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003359 // FIXME: I'm not sure what this is.
3360 int64_t FileNumber = -1;
Eli Bendersky17233942013-01-15 22:59:42 +00003361 if (getLexer().is(AsmToken::Integer)) {
3362 FileNumber = getTok().getIntVal();
3363 Lex();
3364
Paul Robinsonb271f312018-03-29 17:16:41 +00003365 if (FileNumber < 0)
3366 return TokError("negative file number");
Eli Bendersky17233942013-01-15 22:59:42 +00003367 }
3368
Paul Robinson37fbb922018-06-20 16:12:03 +00003369 std::string Path;
Eli Bendersky17233942013-01-15 22:59:42 +00003370
3371 // Usually the directory and filename together, otherwise just the directory.
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003372 // Allow the strings to have escaped octal character sequence.
Nirav Davea645433c2016-07-18 15:24:03 +00003373 if (check(getTok().isNot(AsmToken::String),
3374 "unexpected token in '.file' directive") ||
3375 parseEscapedString(Path))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003376 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003377
3378 StringRef Directory;
3379 StringRef Filename;
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003380 std::string FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00003381 if (getLexer().is(AsmToken::String)) {
Nirav Davea645433c2016-07-18 15:24:03 +00003382 if (check(FileNumber == -1,
3383 "explicit path specified, but no file number") ||
3384 parseEscapedString(FilenameData))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003385 return true;
3386 Filename = FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00003387 Directory = Path;
Eli Bendersky17233942013-01-15 22:59:42 +00003388 } else {
3389 Filename = Path;
3390 }
3391
Paul Robinson01954692018-04-11 15:14:05 +00003392 uint64_t MD5Hi, MD5Lo;
3393 bool HasMD5 = false;
Scott Linder16c7bda2018-02-23 23:01:06 +00003394
3395 Optional<StringRef> Source;
3396 bool HasSource = false;
3397 std::string SourceString;
3398
3399 while (!parseOptionalToken(AsmToken::EndOfStatement)) {
Paul Robinson29f5f982018-01-09 23:31:48 +00003400 StringRef Keyword;
3401 if (check(getTok().isNot(AsmToken::Identifier),
3402 "unexpected token in '.file' directive") ||
Scott Linder16c7bda2018-02-23 23:01:06 +00003403 parseIdentifier(Keyword))
Paul Robinson29f5f982018-01-09 23:31:48 +00003404 return true;
Scott Linder16c7bda2018-02-23 23:01:06 +00003405 if (Keyword == "md5") {
Paul Robinson01954692018-04-11 15:14:05 +00003406 HasMD5 = true;
Scott Linder16c7bda2018-02-23 23:01:06 +00003407 if (check(FileNumber == -1,
3408 "MD5 checksum specified, but no file number") ||
Paul Robinson01954692018-04-11 15:14:05 +00003409 parseHexOcta(*this, MD5Hi, MD5Lo))
Scott Linder16c7bda2018-02-23 23:01:06 +00003410 return true;
3411 } else if (Keyword == "source") {
3412 HasSource = true;
3413 if (check(FileNumber == -1,
3414 "source specified, but no file number") ||
3415 check(getTok().isNot(AsmToken::String),
3416 "unexpected token in '.file' directive") ||
3417 parseEscapedString(SourceString))
3418 return true;
3419 } else {
3420 return TokError("unexpected token in '.file' directive");
3421 }
Paul Robinson29f5f982018-01-09 23:31:48 +00003422 }
Eli Bendersky17233942013-01-15 22:59:42 +00003423
Reid Kleckner98bbd072018-12-21 23:35:48 +00003424 if (FileNumber == -1) {
Reid Klecknerf38bc4f2019-02-05 21:14:09 +00003425 // Ignore the directive if there is no number and the target doesn't support
3426 // numberless .file directives. This allows some portability of assembler
3427 // between different object file formats.
3428 if (getContext().getAsmInfo()->hasSingleParameterDotFile())
3429 getStreamer().EmitFileDirective(Filename);
Reid Kleckner98bbd072018-12-21 23:35:48 +00003430 } else {
Brian Cain3e0ca572018-08-28 16:23:39 +00003431 // In case there is a -g option as well as debug info from directive .file,
3432 // we turn off the -g option, directly use the existing debug info instead.
Paul Robinson26cc5bc2019-06-21 13:10:19 +00003433 // Throw away any implicit file table for the assembler source.
Brian Cain3e0ca572018-08-28 16:23:39 +00003434 if (Ctx.getGenDwarfForAssembly()) {
Paul Robinson26cc5bc2019-06-21 13:10:19 +00003435 Ctx.getMCDwarfLineTable(0).resetFileTable();
Brian Cain3e0ca572018-08-28 16:23:39 +00003436 Ctx.setGenDwarfForAssembly(false);
3437 }
3438
Eric Christopher798e83b2019-04-04 23:34:38 +00003439 Optional<MD5::MD5Result> CKMem;
Paul Robinson01954692018-04-11 15:14:05 +00003440 if (HasMD5) {
Eric Christopher798e83b2019-04-04 23:34:38 +00003441 MD5::MD5Result Sum;
Paul Robinson01954692018-04-11 15:14:05 +00003442 for (unsigned i = 0; i != 8; ++i) {
Eric Christopher798e83b2019-04-04 23:34:38 +00003443 Sum.Bytes[i] = uint8_t(MD5Hi >> ((7 - i) * 8));
3444 Sum.Bytes[i + 8] = uint8_t(MD5Lo >> ((7 - i) * 8));
Paul Robinson01954692018-04-11 15:14:05 +00003445 }
Eric Christopher798e83b2019-04-04 23:34:38 +00003446 CKMem = Sum;
Paul Robinson29f5f982018-01-09 23:31:48 +00003447 }
Scott Linder16c7bda2018-02-23 23:01:06 +00003448 if (HasSource) {
3449 char *SourceBuf = static_cast<char *>(Ctx.allocate(SourceString.size()));
3450 memcpy(SourceBuf, SourceString.data(), SourceString.size());
3451 Source = StringRef(SourceBuf, SourceString.size());
3452 }
Paul Robinson547adca2018-06-21 16:42:03 +00003453 if (FileNumber == 0) {
3454 if (Ctx.getDwarfVersion() < 5)
3455 return Warning(DirectiveLoc, "file 0 not supported prior to DWARF-5");
Paul Robinsonb271f312018-03-29 17:16:41 +00003456 getStreamer().emitDwarfFile0Directive(Directory, Filename, CKMem, Source);
Paul Robinson547adca2018-06-21 16:42:03 +00003457 } else {
Paul Robinsonb271f312018-03-29 17:16:41 +00003458 Expected<unsigned> FileNumOrErr = getStreamer().tryEmitDwarfFileDirective(
3459 FileNumber, Directory, Filename, CKMem, Source);
3460 if (!FileNumOrErr)
3461 return Error(DirectiveLoc, toString(FileNumOrErr.takeError()));
Paul Robinsonb271f312018-03-29 17:16:41 +00003462 }
Paul Robinsoncc7344a2018-06-14 13:38:20 +00003463 // Alert the user if there are some .file directives with MD5 and some not.
3464 // But only do that once.
3465 if (!ReportedInconsistentMD5 && !Ctx.isDwarfMD5UsageConsistent(0)) {
3466 ReportedInconsistentMD5 = true;
3467 return Warning(DirectiveLoc, "inconsistent use of MD5 checksums");
3468 }
Eli Bendersky17233942013-01-15 22:59:42 +00003469 }
3470
3471 return false;
3472}
3473
Jim Grosbach4b905842013-09-20 23:08:21 +00003474/// parseDirectiveLine
Eli Bendersky17233942013-01-15 22:59:42 +00003475/// ::= .line [number]
Jim Grosbach4b905842013-09-20 23:08:21 +00003476bool AsmParser::parseDirectiveLine() {
Nirav Davea645433c2016-07-18 15:24:03 +00003477 int64_t LineNumber;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003478 if (getLexer().is(AsmToken::Integer)) {
Nirav Davea645433c2016-07-18 15:24:03 +00003479 if (parseIntToken(LineNumber, "unexpected token in '.line' directive"))
3480 return true;
Jim Grosbach4b905842013-09-20 23:08:21 +00003481 (void)LineNumber;
Eli Bendersky17233942013-01-15 22:59:42 +00003482 // FIXME: Do something with the .line.
3483 }
Nirav Davea645433c2016-07-18 15:24:03 +00003484 if (parseToken(AsmToken::EndOfStatement,
3485 "unexpected token in '.line' directive"))
3486 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003487
3488 return false;
3489}
3490
Jim Grosbach4b905842013-09-20 23:08:21 +00003491/// parseDirectiveLoc
Eli Bendersky17233942013-01-15 22:59:42 +00003492/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
3493/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
3494/// The first number is a file number, must have been previously assigned with
3495/// a .file directive, the second number is the line number and optionally the
3496/// third number is a column position (zero if not specified). The remaining
3497/// optional items are .loc sub-directives.
Jim Grosbach4b905842013-09-20 23:08:21 +00003498bool AsmParser::parseDirectiveLoc() {
Nirav Davea645433c2016-07-18 15:24:03 +00003499 int64_t FileNumber = 0, LineNumber = 0;
3500 SMLoc Loc = getTok().getLoc();
3501 if (parseIntToken(FileNumber, "unexpected token in '.loc' directive") ||
Paul Robinson11539b02018-06-22 14:16:11 +00003502 check(FileNumber < 1 && Ctx.getDwarfVersion() < 5, Loc,
Nirav Davea645433c2016-07-18 15:24:03 +00003503 "file number less than one in '.loc' directive") ||
3504 check(!getContext().isValidDwarfFileNumber(FileNumber), Loc,
3505 "unassigned file number in '.loc' directive"))
3506 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003507
Nirav Davea645433c2016-07-18 15:24:03 +00003508 // optional
Eli Bendersky17233942013-01-15 22:59:42 +00003509 if (getLexer().is(AsmToken::Integer)) {
3510 LineNumber = getTok().getIntVal();
Adrian Prantl6ac40032013-09-26 23:37:11 +00003511 if (LineNumber < 0)
3512 return TokError("line number less than zero in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003513 Lex();
3514 }
3515
3516 int64_t ColumnPos = 0;
3517 if (getLexer().is(AsmToken::Integer)) {
3518 ColumnPos = getTok().getIntVal();
3519 if (ColumnPos < 0)
3520 return TokError("column position less than zero in '.loc' directive");
3521 Lex();
3522 }
3523
3524 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
3525 unsigned Isa = 0;
3526 int64_t Discriminator = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003527
Nirav Dave1a9044b2016-10-24 14:35:29 +00003528 auto parseLocOp = [&]() -> bool {
3529 StringRef Name;
3530 SMLoc Loc = getTok().getLoc();
3531 if (parseIdentifier(Name))
3532 return TokError("unexpected token in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003533
Nirav Dave1a9044b2016-10-24 14:35:29 +00003534 if (Name == "basic_block")
3535 Flags |= DWARF2_FLAG_BASIC_BLOCK;
3536 else if (Name == "prologue_end")
3537 Flags |= DWARF2_FLAG_PROLOGUE_END;
3538 else if (Name == "epilogue_begin")
3539 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
3540 else if (Name == "is_stmt") {
3541 Loc = getTok().getLoc();
3542 const MCExpr *Value;
3543 if (parseExpression(Value))
3544 return true;
3545 // The expression must be the constant 0 or 1.
3546 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3547 int Value = MCE->getValue();
3548 if (Value == 0)
3549 Flags &= ~DWARF2_FLAG_IS_STMT;
3550 else if (Value == 1)
3551 Flags |= DWARF2_FLAG_IS_STMT;
3552 else
3553 return Error(Loc, "is_stmt value not 0 or 1");
Craig Topperf15655b2013-04-22 04:22:40 +00003554 } else {
Nirav Dave1a9044b2016-10-24 14:35:29 +00003555 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
Eli Bendersky17233942013-01-15 22:59:42 +00003556 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003557 } else if (Name == "isa") {
3558 Loc = getTok().getLoc();
3559 const MCExpr *Value;
3560 if (parseExpression(Value))
3561 return true;
3562 // The expression must be a constant greater or equal to 0.
3563 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3564 int Value = MCE->getValue();
3565 if (Value < 0)
3566 return Error(Loc, "isa number less than zero");
3567 Isa = Value;
3568 } else {
3569 return Error(Loc, "isa number not a constant value");
3570 }
3571 } else if (Name == "discriminator") {
3572 if (parseAbsoluteExpression(Discriminator))
3573 return true;
3574 } else {
3575 return Error(Loc, "unknown sub-directive in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003576 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003577 return false;
3578 };
3579
Nirav Davee2369aa2016-10-26 17:28:58 +00003580 if (parseMany(parseLocOp, false /*hasComma*/))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003581 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003582
3583 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
3584 Isa, Discriminator, StringRef());
3585
3586 return false;
3587}
3588
Jim Grosbach4b905842013-09-20 23:08:21 +00003589/// parseDirectiveStabs
Eli Bendersky17233942013-01-15 22:59:42 +00003590/// ::= .stabs string, number, number, number
Jim Grosbach4b905842013-09-20 23:08:21 +00003591bool AsmParser::parseDirectiveStabs() {
Eli Bendersky17233942013-01-15 22:59:42 +00003592 return TokError("unsupported directive '.stabs'");
3593}
3594
Reid Kleckner2214ed82016-01-29 00:49:42 +00003595/// parseDirectiveCVFile
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003596/// ::= .cv_file number filename [checksum] [checksumkind]
Reid Kleckner2214ed82016-01-29 00:49:42 +00003597bool AsmParser::parseDirectiveCVFile() {
Nirav Davea645433c2016-07-18 15:24:03 +00003598 SMLoc FileNumberLoc = getTok().getLoc();
3599 int64_t FileNumber;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003600 std::string Filename;
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003601 std::string Checksum;
3602 int64_t ChecksumKind = 0;
Nirav Davea645433c2016-07-18 15:24:03 +00003603
3604 if (parseIntToken(FileNumber,
3605 "expected file number in '.cv_file' directive") ||
3606 check(FileNumber < 1, FileNumberLoc, "file number less than one") ||
3607 check(getTok().isNot(AsmToken::String),
3608 "unexpected token in '.cv_file' directive") ||
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003609 parseEscapedString(Filename))
Reid Klecknera5b1eef2016-08-26 17:58:37 +00003610 return true;
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003611 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
3612 if (check(getTok().isNot(AsmToken::String),
3613 "unexpected token in '.cv_file' directive") ||
3614 parseEscapedString(Checksum) ||
3615 parseIntToken(ChecksumKind,
3616 "expected checksum kind in '.cv_file' directive") ||
3617 parseToken(AsmToken::EndOfStatement,
3618 "unexpected token in '.cv_file' directive"))
3619 return true;
3620 }
Nirav Dave1ab71992016-07-18 19:35:21 +00003621
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003622 Checksum = fromHex(Checksum);
3623 void *CKMem = Ctx.allocate(Checksum.size(), 1);
3624 memcpy(CKMem, Checksum.data(), Checksum.size());
3625 ArrayRef<uint8_t> ChecksumAsBytes(reinterpret_cast<const uint8_t *>(CKMem),
3626 Checksum.size());
3627
3628 if (!getStreamer().EmitCVFileDirective(FileNumber, Filename, ChecksumAsBytes,
3629 static_cast<uint8_t>(ChecksumKind)))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003630 return Error(FileNumberLoc, "file number already allocated");
Reid Kleckner2214ed82016-01-29 00:49:42 +00003631
3632 return false;
3633}
3634
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003635bool AsmParser::parseCVFunctionId(int64_t &FunctionId,
3636 StringRef DirectiveName) {
3637 SMLoc Loc;
3638 return parseTokenLoc(Loc) ||
3639 parseIntToken(FunctionId, "expected function id in '" + DirectiveName +
3640 "' directive") ||
3641 check(FunctionId < 0 || FunctionId >= UINT_MAX, Loc,
3642 "expected function id within range [0, UINT_MAX)");
3643}
3644
3645bool AsmParser::parseCVFileId(int64_t &FileNumber, StringRef DirectiveName) {
3646 SMLoc Loc;
3647 return parseTokenLoc(Loc) ||
3648 parseIntToken(FileNumber, "expected integer in '" + DirectiveName +
3649 "' directive") ||
3650 check(FileNumber < 1, Loc, "file number less than one in '" +
3651 DirectiveName + "' directive") ||
3652 check(!getCVContext().isValidFileNumber(FileNumber), Loc,
3653 "unassigned file number in '" + DirectiveName + "' directive");
3654}
3655
3656/// parseDirectiveCVFuncId
3657/// ::= .cv_func_id FunctionId
3658///
3659/// Introduces a function ID that can be used with .cv_loc.
3660bool AsmParser::parseDirectiveCVFuncId() {
3661 SMLoc FunctionIdLoc = getTok().getLoc();
3662 int64_t FunctionId;
3663
3664 if (parseCVFunctionId(FunctionId, ".cv_func_id") ||
3665 parseToken(AsmToken::EndOfStatement,
3666 "unexpected token in '.cv_func_id' directive"))
3667 return true;
3668
3669 if (!getStreamer().EmitCVFuncIdDirective(FunctionId))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003670 return Error(FunctionIdLoc, "function id already allocated");
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003671
3672 return false;
3673}
3674
3675/// parseDirectiveCVInlineSiteId
3676/// ::= .cv_inline_site_id FunctionId
3677/// "within" IAFunc
3678/// "inlined_at" IAFile IALine [IACol]
3679///
3680/// Introduces a function ID that can be used with .cv_loc. Includes "inlined
3681/// at" source location information for use in the line table of the caller,
3682/// whether the caller is a real function or another inlined call site.
3683bool AsmParser::parseDirectiveCVInlineSiteId() {
3684 SMLoc FunctionIdLoc = getTok().getLoc();
3685 int64_t FunctionId;
3686 int64_t IAFunc;
3687 int64_t IAFile;
3688 int64_t IALine;
3689 int64_t IACol = 0;
3690
3691 // FunctionId
3692 if (parseCVFunctionId(FunctionId, ".cv_inline_site_id"))
3693 return true;
3694
3695 // "within"
3696 if (check((getLexer().isNot(AsmToken::Identifier) ||
3697 getTok().getIdentifier() != "within"),
3698 "expected 'within' identifier in '.cv_inline_site_id' directive"))
3699 return true;
3700 Lex();
3701
3702 // IAFunc
3703 if (parseCVFunctionId(IAFunc, ".cv_inline_site_id"))
3704 return true;
3705
3706 // "inlined_at"
3707 if (check((getLexer().isNot(AsmToken::Identifier) ||
3708 getTok().getIdentifier() != "inlined_at"),
3709 "expected 'inlined_at' identifier in '.cv_inline_site_id' "
3710 "directive") )
3711 return true;
3712 Lex();
3713
3714 // IAFile IALine
3715 if (parseCVFileId(IAFile, ".cv_inline_site_id") ||
3716 parseIntToken(IALine, "expected line number after 'inlined_at'"))
3717 return true;
3718
3719 // [IACol]
3720 if (getLexer().is(AsmToken::Integer)) {
3721 IACol = getTok().getIntVal();
3722 Lex();
3723 }
3724
3725 if (parseToken(AsmToken::EndOfStatement,
3726 "unexpected token in '.cv_inline_site_id' directive"))
3727 return true;
3728
3729 if (!getStreamer().EmitCVInlineSiteIdDirective(FunctionId, IAFunc, IAFile,
3730 IALine, IACol, FunctionIdLoc))
Nirav Dave2364748a2016-09-16 18:30:20 +00003731 return Error(FunctionIdLoc, "function id already allocated");
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003732
3733 return false;
3734}
3735
Reid Kleckner2214ed82016-01-29 00:49:42 +00003736/// parseDirectiveCVLoc
3737/// ::= .cv_loc FunctionId FileNumber [LineNumber] [ColumnPos] [prologue_end]
3738/// [is_stmt VALUE]
3739/// The first number is a file number, must have been previously assigned with
3740/// a .file directive, the second number is the line number and optionally the
3741/// third number is a column position (zero if not specified). The remaining
3742/// optional items are .loc sub-directives.
3743bool AsmParser::parseDirectiveCVLoc() {
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003744 SMLoc DirectiveLoc = getTok().getLoc();
Nirav Davea645433c2016-07-18 15:24:03 +00003745 int64_t FunctionId, FileNumber;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003746 if (parseCVFunctionId(FunctionId, ".cv_loc") ||
3747 parseCVFileId(FileNumber, ".cv_loc"))
Nirav Davea645433c2016-07-18 15:24:03 +00003748 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003749
3750 int64_t LineNumber = 0;
3751 if (getLexer().is(AsmToken::Integer)) {
3752 LineNumber = getTok().getIntVal();
3753 if (LineNumber < 0)
3754 return TokError("line number less than zero in '.cv_loc' directive");
3755 Lex();
3756 }
3757
3758 int64_t ColumnPos = 0;
3759 if (getLexer().is(AsmToken::Integer)) {
3760 ColumnPos = getTok().getIntVal();
3761 if (ColumnPos < 0)
3762 return TokError("column position less than zero in '.cv_loc' directive");
3763 Lex();
3764 }
3765
3766 bool PrologueEnd = false;
3767 uint64_t IsStmt = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003768
3769 auto parseOp = [&]() -> bool {
Reid Kleckner2214ed82016-01-29 00:49:42 +00003770 StringRef Name;
3771 SMLoc Loc = getTok().getLoc();
3772 if (parseIdentifier(Name))
3773 return TokError("unexpected token in '.cv_loc' directive");
Reid Kleckner2214ed82016-01-29 00:49:42 +00003774 if (Name == "prologue_end")
3775 PrologueEnd = true;
3776 else if (Name == "is_stmt") {
3777 Loc = getTok().getLoc();
3778 const MCExpr *Value;
3779 if (parseExpression(Value))
3780 return true;
3781 // The expression must be the constant 0 or 1.
3782 IsStmt = ~0ULL;
3783 if (const auto *MCE = dyn_cast<MCConstantExpr>(Value))
3784 IsStmt = MCE->getValue();
3785
3786 if (IsStmt > 1)
3787 return Error(Loc, "is_stmt value not 0 or 1");
3788 } else {
3789 return Error(Loc, "unknown sub-directive in '.cv_loc' directive");
3790 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003791 return false;
3792 };
3793
3794 if (parseMany(parseOp, false /*hasComma*/))
3795 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003796
3797 getStreamer().EmitCVLocDirective(FunctionId, FileNumber, LineNumber,
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003798 ColumnPos, PrologueEnd, IsStmt, StringRef(),
3799 DirectiveLoc);
Reid Kleckner2214ed82016-01-29 00:49:42 +00003800 return false;
3801}
3802
3803/// parseDirectiveCVLinetable
3804/// ::= .cv_linetable FunctionId, FnStart, FnEnd
3805bool AsmParser::parseDirectiveCVLinetable() {
Nirav Davea645433c2016-07-18 15:24:03 +00003806 int64_t FunctionId;
3807 StringRef FnStartName, FnEndName;
3808 SMLoc Loc = getTok().getLoc();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003809 if (parseCVFunctionId(FunctionId, ".cv_linetable") ||
Nirav Davea645433c2016-07-18 15:24:03 +00003810 parseToken(AsmToken::Comma,
3811 "unexpected token in '.cv_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003812 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3813 "expected identifier in directive") ||
Nirav Davea645433c2016-07-18 15:24:03 +00003814 parseToken(AsmToken::Comma,
3815 "unexpected token in '.cv_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003816 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3817 "expected identifier in directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00003818 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003819
3820 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3821 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
3822
3823 getStreamer().EmitCVLinetableDirective(FunctionId, FnStartSym, FnEndSym);
3824 return false;
3825}
3826
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003827/// parseDirectiveCVInlineLinetable
David Majnemerc9911f22016-02-02 19:22:34 +00003828/// ::= .cv_inline_linetable PrimaryFunctionId FileId LineNum FnStart FnEnd
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003829bool AsmParser::parseDirectiveCVInlineLinetable() {
Nirav Davea645433c2016-07-18 15:24:03 +00003830 int64_t PrimaryFunctionId, SourceFileId, SourceLineNum;
3831 StringRef FnStartName, FnEndName;
3832 SMLoc Loc = getTok().getLoc();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003833 if (parseCVFunctionId(PrimaryFunctionId, ".cv_inline_linetable") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003834 parseTokenLoc(Loc) ||
Nirav Davea645433c2016-07-18 15:24:03 +00003835 parseIntToken(
3836 SourceFileId,
3837 "expected SourceField in '.cv_inline_linetable' directive") ||
3838 check(SourceFileId <= 0, Loc,
3839 "File id less than zero in '.cv_inline_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003840 parseTokenLoc(Loc) ||
Nirav Davea645433c2016-07-18 15:24:03 +00003841 parseIntToken(
3842 SourceLineNum,
3843 "expected SourceLineNum in '.cv_inline_linetable' directive") ||
3844 check(SourceLineNum < 0, Loc,
3845 "Line number less than zero in '.cv_inline_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003846 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3847 "expected identifier in directive") ||
3848 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3849 "expected identifier in directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00003850 return true;
David Majnemerc9911f22016-02-02 19:22:34 +00003851
Nirav Davea645433c2016-07-18 15:24:03 +00003852 if (parseToken(AsmToken::EndOfStatement, "Expected End of Statement"))
3853 return true;
3854
3855 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3856 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
Reid Kleckner1fcd6102016-02-02 17:41:18 +00003857 getStreamer().EmitCVInlineLinetableDirective(PrimaryFunctionId, SourceFileId,
3858 SourceLineNum, FnStartSym,
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003859 FnEndSym);
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003860 return false;
3861}
3862
Nilanjana Basuda60fc82019-08-05 14:16:58 +00003863void AsmParser::initializeCVDefRangeTypeMap() {
3864 CVDefRangeTypeMap["reg"] = CVDR_DEFRANGE_REGISTER;
3865 CVDefRangeTypeMap["frame_ptr_rel"] = CVDR_DEFRANGE_FRAMEPOINTER_REL;
3866 CVDefRangeTypeMap["subfield_reg"] = CVDR_DEFRANGE_SUBFIELD_REGISTER;
3867 CVDefRangeTypeMap["reg_rel"] = CVDR_DEFRANGE_REGISTER_REL;
3868}
3869
David Majnemer408b5e62016-02-05 01:55:49 +00003870/// parseDirectiveCVDefRange
3871/// ::= .cv_def_range RangeStart RangeEnd (GapStart GapEnd)*, bytes*
3872bool AsmParser::parseDirectiveCVDefRange() {
3873 SMLoc Loc;
3874 std::vector<std::pair<const MCSymbol *, const MCSymbol *>> Ranges;
3875 while (getLexer().is(AsmToken::Identifier)) {
3876 Loc = getLexer().getLoc();
3877 StringRef GapStartName;
3878 if (parseIdentifier(GapStartName))
3879 return Error(Loc, "expected identifier in directive");
3880 MCSymbol *GapStartSym = getContext().getOrCreateSymbol(GapStartName);
3881
3882 Loc = getLexer().getLoc();
3883 StringRef GapEndName;
3884 if (parseIdentifier(GapEndName))
3885 return Error(Loc, "expected identifier in directive");
3886 MCSymbol *GapEndSym = getContext().getOrCreateSymbol(GapEndName);
3887
3888 Ranges.push_back({GapStartSym, GapEndSym});
3889 }
3890
Nilanjana Basuda60fc82019-08-05 14:16:58 +00003891 StringRef CVDefRangeTypeStr;
3892 if (parseToken(
3893 AsmToken::Comma,
3894 "expected comma before def_range type in .cv_def_range directive") ||
3895 parseIdentifier(CVDefRangeTypeStr))
3896 return Error(Loc, "expected def_range type in directive");
David Majnemer408b5e62016-02-05 01:55:49 +00003897
Nilanjana Basuda60fc82019-08-05 14:16:58 +00003898 StringMap<CVDefRangeType>::const_iterator CVTypeIt =
3899 CVDefRangeTypeMap.find(CVDefRangeTypeStr);
3900 CVDefRangeType CVDRType = (CVTypeIt == CVDefRangeTypeMap.end())
3901 ? CVDR_DEFRANGE
3902 : CVTypeIt->getValue();
3903 switch (CVDRType) {
3904 case CVDR_DEFRANGE_REGISTER: {
3905 int64_t DRRegister;
3906 if (parseToken(AsmToken::Comma, "expected comma before register number in "
3907 ".cv_def_range directive") ||
3908 parseAbsoluteExpression(DRRegister))
3909 return Error(Loc, "expected register number");
3910
Reid Kleckner7bbe7112019-10-19 01:44:09 +00003911 codeview::DefRangeRegisterHeader DRHdr;
Nilanjana Basuda60fc82019-08-05 14:16:58 +00003912 DRHdr.Register = DRRegister;
3913 DRHdr.MayHaveNoName = 0;
3914 getStreamer().EmitCVDefRangeDirective(Ranges, DRHdr);
3915 break;
3916 }
3917 case CVDR_DEFRANGE_FRAMEPOINTER_REL: {
3918 int64_t DROffset;
3919 if (parseToken(AsmToken::Comma,
3920 "expected comma before offset in .cv_def_range directive") ||
3921 parseAbsoluteExpression(DROffset))
3922 return Error(Loc, "expected offset value");
3923
Reid Kleckner7bbe7112019-10-19 01:44:09 +00003924 codeview::DefRangeFramePointerRelHeader DRHdr;
Nilanjana Basuda60fc82019-08-05 14:16:58 +00003925 DRHdr.Offset = DROffset;
3926 getStreamer().EmitCVDefRangeDirective(Ranges, DRHdr);
3927 break;
3928 }
3929 case CVDR_DEFRANGE_SUBFIELD_REGISTER: {
3930 int64_t DRRegister;
3931 int64_t DROffsetInParent;
3932 if (parseToken(AsmToken::Comma, "expected comma before register number in "
3933 ".cv_def_range directive") ||
3934 parseAbsoluteExpression(DRRegister))
3935 return Error(Loc, "expected register number");
3936 if (parseToken(AsmToken::Comma,
3937 "expected comma before offset in .cv_def_range directive") ||
3938 parseAbsoluteExpression(DROffsetInParent))
3939 return Error(Loc, "expected offset value");
3940
Reid Kleckner7bbe7112019-10-19 01:44:09 +00003941 codeview::DefRangeSubfieldRegisterHeader DRHdr;
Nilanjana Basuda60fc82019-08-05 14:16:58 +00003942 DRHdr.Register = DRRegister;
3943 DRHdr.MayHaveNoName = 0;
3944 DRHdr.OffsetInParent = DROffsetInParent;
3945 getStreamer().EmitCVDefRangeDirective(Ranges, DRHdr);
3946 break;
3947 }
3948 case CVDR_DEFRANGE_REGISTER_REL: {
3949 int64_t DRRegister;
3950 int64_t DRFlags;
3951 int64_t DRBasePointerOffset;
3952 if (parseToken(AsmToken::Comma, "expected comma before register number in "
3953 ".cv_def_range directive") ||
3954 parseAbsoluteExpression(DRRegister))
3955 return Error(Loc, "expected register value");
3956 if (parseToken(
3957 AsmToken::Comma,
3958 "expected comma before flag value in .cv_def_range directive") ||
3959 parseAbsoluteExpression(DRFlags))
3960 return Error(Loc, "expected flag value");
3961 if (parseToken(AsmToken::Comma, "expected comma before base pointer offset "
3962 "in .cv_def_range directive") ||
3963 parseAbsoluteExpression(DRBasePointerOffset))
3964 return Error(Loc, "expected base pointer offset value");
3965
Reid Kleckner7bbe7112019-10-19 01:44:09 +00003966 codeview::DefRangeRegisterRelHeader DRHdr;
Nilanjana Basuda60fc82019-08-05 14:16:58 +00003967 DRHdr.Register = DRRegister;
3968 DRHdr.Flags = DRFlags;
3969 DRHdr.BasePointerOffset = DRBasePointerOffset;
3970 getStreamer().EmitCVDefRangeDirective(Ranges, DRHdr);
3971 break;
3972 }
3973 default:
3974 return Error(Loc, "unexpected def_range type in .cv_def_range directive");
3975 }
3976 return true;
David Majnemer408b5e62016-02-05 01:55:49 +00003977}
3978
Reid Kleckner06d02d02018-09-07 21:30:52 +00003979/// parseDirectiveCVString
3980/// ::= .cv_stringtable "string"
3981bool AsmParser::parseDirectiveCVString() {
3982 std::string Data;
3983 if (checkForValidSection() || parseEscapedString(Data))
3984 return addErrorSuffix(" in '.cv_string' directive");
3985
3986 // Put the string in the table and emit the offset.
3987 std::pair<StringRef, unsigned> Insertion =
3988 getCVContext().addToStringTable(Data);
3989 getStreamer().EmitIntValue(Insertion.second, 4);
3990 return false;
3991}
3992
Reid Kleckner2214ed82016-01-29 00:49:42 +00003993/// parseDirectiveCVStringTable
3994/// ::= .cv_stringtable
3995bool AsmParser::parseDirectiveCVStringTable() {
3996 getStreamer().EmitCVStringTableDirective();
3997 return false;
3998}
3999
4000/// parseDirectiveCVFileChecksums
4001/// ::= .cv_filechecksums
4002bool AsmParser::parseDirectiveCVFileChecksums() {
4003 getStreamer().EmitCVFileChecksumsDirective();
4004 return false;
4005}
4006
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00004007/// parseDirectiveCVFileChecksumOffset
4008/// ::= .cv_filechecksumoffset fileno
4009bool AsmParser::parseDirectiveCVFileChecksumOffset() {
4010 int64_t FileNo;
4011 if (parseIntToken(FileNo, "expected identifier in directive"))
4012 return true;
4013 if (parseToken(AsmToken::EndOfStatement, "Expected End of Statement"))
4014 return true;
4015 getStreamer().EmitCVFileChecksumOffsetDirective(FileNo);
4016 return false;
4017}
4018
Reid Kleckner9cdd4df2017-10-11 21:24:33 +00004019/// parseDirectiveCVFPOData
4020/// ::= .cv_fpo_data procsym
4021bool AsmParser::parseDirectiveCVFPOData() {
4022 SMLoc DirLoc = getLexer().getLoc();
4023 StringRef ProcName;
4024 if (parseIdentifier(ProcName))
4025 return TokError("expected symbol name");
4026 if (parseEOL("unexpected tokens"))
4027 return addErrorSuffix(" in '.cv_fpo_data' directive");
4028 MCSymbol *ProcSym = getContext().getOrCreateSymbol(ProcName);
4029 getStreamer().EmitCVFPOData(ProcSym, DirLoc);
4030 return false;
4031}
4032
Jim Grosbach4b905842013-09-20 23:08:21 +00004033/// parseDirectiveCFISections
Eli Bendersky17233942013-01-15 22:59:42 +00004034/// ::= .cfi_sections section [, section]
Jim Grosbach4b905842013-09-20 23:08:21 +00004035bool AsmParser::parseDirectiveCFISections() {
Eli Bendersky17233942013-01-15 22:59:42 +00004036 StringRef Name;
4037 bool EH = false;
4038 bool Debug = false;
4039
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004040 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00004041 return TokError("Expected an identifier");
4042
4043 if (Name == ".eh_frame")
4044 EH = true;
4045 else if (Name == ".debug_frame")
4046 Debug = true;
4047
4048 if (getLexer().is(AsmToken::Comma)) {
4049 Lex();
4050
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004051 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00004052 return TokError("Expected an identifier");
4053
4054 if (Name == ".eh_frame")
4055 EH = true;
4056 else if (Name == ".debug_frame")
4057 Debug = true;
4058 }
4059
4060 getStreamer().EmitCFISections(EH, Debug);
4061 return false;
4062}
4063
Jim Grosbach4b905842013-09-20 23:08:21 +00004064/// parseDirectiveCFIStartProc
David Majnemere035cf92014-01-27 17:20:25 +00004065/// ::= .cfi_startproc [simple]
Jim Grosbach4b905842013-09-20 23:08:21 +00004066bool AsmParser::parseDirectiveCFIStartProc() {
David Majnemere035cf92014-01-27 17:20:25 +00004067 StringRef Simple;
Nirav Dave1a9044b2016-10-24 14:35:29 +00004068 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
4069 if (check(parseIdentifier(Simple) || Simple != "simple",
4070 "unexpected token") ||
4071 parseToken(AsmToken::EndOfStatement))
4072 return addErrorSuffix(" in '.cfi_startproc' directive");
4073 }
Wouter van Oortmerssencc75e772018-11-12 20:15:01 +00004074
Kristina Brooks1a41a112018-10-19 12:14:30 +00004075 // TODO(kristina): Deal with a corner case of incorrect diagnostic context
4076 // being produced if this directive is emitted as part of preprocessor macro
4077 // expansion which can *ONLY* happen if Clang's cc1as is the API consumer.
4078 // Tools like llvm-mc on the other hand are not affected by it, and report
4079 // correct context information.
4080 getStreamer().EmitCFIStartProc(!Simple.empty(), Lexer.getLoc());
Eli Bendersky17233942013-01-15 22:59:42 +00004081 return false;
4082}
4083
Jim Grosbach4b905842013-09-20 23:08:21 +00004084/// parseDirectiveCFIEndProc
Eli Bendersky17233942013-01-15 22:59:42 +00004085/// ::= .cfi_endproc
Jim Grosbach4b905842013-09-20 23:08:21 +00004086bool AsmParser::parseDirectiveCFIEndProc() {
Eli Bendersky17233942013-01-15 22:59:42 +00004087 getStreamer().EmitCFIEndProc();
4088 return false;
4089}
4090
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00004091/// parse register name or number.
Jim Grosbach4b905842013-09-20 23:08:21 +00004092bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
Eli Bendersky17233942013-01-15 22:59:42 +00004093 SMLoc DirectiveLoc) {
4094 unsigned RegNo;
4095
4096 if (getLexer().isNot(AsmToken::Integer)) {
4097 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
4098 return true;
Bill Wendlingbc07a892013-06-18 07:20:20 +00004099 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
Eli Bendersky17233942013-01-15 22:59:42 +00004100 } else
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004101 return parseAbsoluteExpression(Register);
Eli Bendersky17233942013-01-15 22:59:42 +00004102
4103 return false;
4104}
4105
Jim Grosbach4b905842013-09-20 23:08:21 +00004106/// parseDirectiveCFIDefCfa
Eli Bendersky17233942013-01-15 22:59:42 +00004107/// ::= .cfi_def_cfa register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00004108bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00004109 int64_t Register = 0, Offset = 0;
4110 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
4111 parseToken(AsmToken::Comma, "unexpected token in directive") ||
4112 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00004113 return true;
4114
4115 getStreamer().EmitCFIDefCfa(Register, Offset);
4116 return false;
4117}
4118
Jim Grosbach4b905842013-09-20 23:08:21 +00004119/// parseDirectiveCFIDefCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00004120/// ::= .cfi_def_cfa_offset offset
Jim Grosbach4b905842013-09-20 23:08:21 +00004121bool AsmParser::parseDirectiveCFIDefCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00004122 int64_t Offset = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004123 if (parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00004124 return true;
4125
4126 getStreamer().EmitCFIDefCfaOffset(Offset);
4127 return false;
4128}
4129
Jim Grosbach4b905842013-09-20 23:08:21 +00004130/// parseDirectiveCFIRegister
Eli Bendersky17233942013-01-15 22:59:42 +00004131/// ::= .cfi_register register, register
Jim Grosbach4b905842013-09-20 23:08:21 +00004132bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00004133 int64_t Register1 = 0, Register2 = 0;
4134 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc) ||
4135 parseToken(AsmToken::Comma, "unexpected token in directive") ||
4136 parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00004137 return true;
4138
4139 getStreamer().EmitCFIRegister(Register1, Register2);
4140 return false;
4141}
4142
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00004143/// parseDirectiveCFIWindowSave
4144/// ::= .cfi_window_save
4145bool AsmParser::parseDirectiveCFIWindowSave() {
4146 getStreamer().EmitCFIWindowSave();
4147 return false;
4148}
4149
Jim Grosbach4b905842013-09-20 23:08:21 +00004150/// parseDirectiveCFIAdjustCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00004151/// ::= .cfi_adjust_cfa_offset adjustment
Jim Grosbach4b905842013-09-20 23:08:21 +00004152bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00004153 int64_t Adjustment = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004154 if (parseAbsoluteExpression(Adjustment))
Eli Bendersky17233942013-01-15 22:59:42 +00004155 return true;
4156
4157 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
4158 return false;
4159}
4160
Jim Grosbach4b905842013-09-20 23:08:21 +00004161/// parseDirectiveCFIDefCfaRegister
Eli Bendersky17233942013-01-15 22:59:42 +00004162/// ::= .cfi_def_cfa_register register
Jim Grosbach4b905842013-09-20 23:08:21 +00004163bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004164 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00004165 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00004166 return true;
4167
4168 getStreamer().EmitCFIDefCfaRegister(Register);
4169 return false;
4170}
4171
Jim Grosbach4b905842013-09-20 23:08:21 +00004172/// parseDirectiveCFIOffset
Eli Bendersky17233942013-01-15 22:59:42 +00004173/// ::= .cfi_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00004174bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004175 int64_t Register = 0;
4176 int64_t Offset = 0;
4177
Nirav Davea645433c2016-07-18 15:24:03 +00004178 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
4179 parseToken(AsmToken::Comma, "unexpected token in directive") ||
4180 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00004181 return true;
4182
4183 getStreamer().EmitCFIOffset(Register, Offset);
4184 return false;
4185}
4186
Jim Grosbach4b905842013-09-20 23:08:21 +00004187/// parseDirectiveCFIRelOffset
Eli Bendersky17233942013-01-15 22:59:42 +00004188/// ::= .cfi_rel_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00004189bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00004190 int64_t Register = 0, Offset = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00004191
Nirav Davea645433c2016-07-18 15:24:03 +00004192 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
4193 parseToken(AsmToken::Comma, "unexpected token in directive") ||
4194 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00004195 return true;
4196
4197 getStreamer().EmitCFIRelOffset(Register, Offset);
4198 return false;
4199}
4200
4201static bool isValidEncoding(int64_t Encoding) {
4202 if (Encoding & ~0xff)
4203 return false;
4204
4205 if (Encoding == dwarf::DW_EH_PE_omit)
4206 return true;
4207
4208 const unsigned Format = Encoding & 0xf;
4209 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
4210 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
4211 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
4212 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
4213 return false;
4214
4215 const unsigned Application = Encoding & 0x70;
4216 if (Application != dwarf::DW_EH_PE_absptr &&
4217 Application != dwarf::DW_EH_PE_pcrel)
4218 return false;
4219
4220 return true;
4221}
4222
Jim Grosbach4b905842013-09-20 23:08:21 +00004223/// parseDirectiveCFIPersonalityOrLsda
Eli Bendersky17233942013-01-15 22:59:42 +00004224/// IsPersonality true for cfi_personality, false for cfi_lsda
4225/// ::= .cfi_personality encoding, [symbol_name]
4226/// ::= .cfi_lsda encoding, [symbol_name]
Jim Grosbach4b905842013-09-20 23:08:21 +00004227bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
Eli Bendersky17233942013-01-15 22:59:42 +00004228 int64_t Encoding = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004229 if (parseAbsoluteExpression(Encoding))
Eli Bendersky17233942013-01-15 22:59:42 +00004230 return true;
4231 if (Encoding == dwarf::DW_EH_PE_omit)
4232 return false;
4233
Eli Bendersky17233942013-01-15 22:59:42 +00004234 StringRef Name;
Nirav Davea645433c2016-07-18 15:24:03 +00004235 if (check(!isValidEncoding(Encoding), "unsupported encoding.") ||
4236 parseToken(AsmToken::Comma, "unexpected token in directive") ||
4237 check(parseIdentifier(Name), "expected identifier in directive"))
4238 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004239
Jim Grosbach6f482002015-05-18 18:43:14 +00004240 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Eli Bendersky17233942013-01-15 22:59:42 +00004241
4242 if (IsPersonality)
4243 getStreamer().EmitCFIPersonality(Sym, Encoding);
4244 else
4245 getStreamer().EmitCFILsda(Sym, Encoding);
4246 return false;
4247}
4248
Jim Grosbach4b905842013-09-20 23:08:21 +00004249/// parseDirectiveCFIRememberState
Eli Bendersky17233942013-01-15 22:59:42 +00004250/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00004251bool AsmParser::parseDirectiveCFIRememberState() {
Eli Bendersky17233942013-01-15 22:59:42 +00004252 getStreamer().EmitCFIRememberState();
4253 return false;
4254}
4255
Jim Grosbach4b905842013-09-20 23:08:21 +00004256/// parseDirectiveCFIRestoreState
Eli Bendersky17233942013-01-15 22:59:42 +00004257/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00004258bool AsmParser::parseDirectiveCFIRestoreState() {
Eli Bendersky17233942013-01-15 22:59:42 +00004259 getStreamer().EmitCFIRestoreState();
4260 return false;
4261}
4262
Jim Grosbach4b905842013-09-20 23:08:21 +00004263/// parseDirectiveCFISameValue
Eli Bendersky17233942013-01-15 22:59:42 +00004264/// ::= .cfi_same_value register
Jim Grosbach4b905842013-09-20 23:08:21 +00004265bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004266 int64_t Register = 0;
4267
Jim Grosbach4b905842013-09-20 23:08:21 +00004268 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00004269 return true;
4270
4271 getStreamer().EmitCFISameValue(Register);
4272 return false;
4273}
4274
Jim Grosbach4b905842013-09-20 23:08:21 +00004275/// parseDirectiveCFIRestore
Eli Bendersky17233942013-01-15 22:59:42 +00004276/// ::= .cfi_restore register
Jim Grosbach4b905842013-09-20 23:08:21 +00004277bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004278 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00004279 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00004280 return true;
4281
4282 getStreamer().EmitCFIRestore(Register);
4283 return false;
4284}
4285
Jim Grosbach4b905842013-09-20 23:08:21 +00004286/// parseDirectiveCFIEscape
Eli Bendersky17233942013-01-15 22:59:42 +00004287/// ::= .cfi_escape expression[,...]
Jim Grosbach4b905842013-09-20 23:08:21 +00004288bool AsmParser::parseDirectiveCFIEscape() {
Eli Bendersky17233942013-01-15 22:59:42 +00004289 std::string Values;
4290 int64_t CurrValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004291 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00004292 return true;
4293
4294 Values.push_back((uint8_t)CurrValue);
4295
4296 while (getLexer().is(AsmToken::Comma)) {
4297 Lex();
4298
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004299 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00004300 return true;
4301
4302 Values.push_back((uint8_t)CurrValue);
4303 }
4304
4305 getStreamer().EmitCFIEscape(Values);
4306 return false;
4307}
4308
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +00004309/// parseDirectiveCFIReturnColumn
4310/// ::= .cfi_return_column register
4311bool AsmParser::parseDirectiveCFIReturnColumn(SMLoc DirectiveLoc) {
4312 int64_t Register = 0;
4313 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
4314 return true;
4315 getStreamer().EmitCFIReturnColumn(Register);
4316 return false;
4317}
4318
Jim Grosbach4b905842013-09-20 23:08:21 +00004319/// parseDirectiveCFISignalFrame
Eli Bendersky17233942013-01-15 22:59:42 +00004320/// ::= .cfi_signal_frame
Jim Grosbach4b905842013-09-20 23:08:21 +00004321bool AsmParser::parseDirectiveCFISignalFrame() {
Nirav Davea645433c2016-07-18 15:24:03 +00004322 if (parseToken(AsmToken::EndOfStatement,
4323 "unexpected token in '.cfi_signal_frame'"))
4324 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004325
4326 getStreamer().EmitCFISignalFrame();
4327 return false;
4328}
4329
Jim Grosbach4b905842013-09-20 23:08:21 +00004330/// parseDirectiveCFIUndefined
Eli Bendersky17233942013-01-15 22:59:42 +00004331/// ::= .cfi_undefined register
Jim Grosbach4b905842013-09-20 23:08:21 +00004332bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004333 int64_t Register = 0;
4334
Jim Grosbach4b905842013-09-20 23:08:21 +00004335 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00004336 return true;
4337
4338 getStreamer().EmitCFIUndefined(Register);
4339 return false;
4340}
4341
Michael Zuckerman56704612017-05-01 13:20:12 +00004342/// parseDirectiveAltmacro
4343/// ::= .altmacro
4344/// ::= .noaltmacro
4345bool AsmParser::parseDirectiveAltmacro(StringRef Directive) {
4346 if (getLexer().isNot(AsmToken::EndOfStatement))
4347 return TokError("unexpected token in '" + Directive + "' directive");
Craig Topperc81aff72018-09-25 20:55:55 +00004348 AltMacroMode = (Directive == ".altmacro");
Michael Zuckerman56704612017-05-01 13:20:12 +00004349 return false;
4350}
4351
Jim Grosbach4b905842013-09-20 23:08:21 +00004352/// parseDirectiveMacrosOnOff
Eli Bendersky17233942013-01-15 22:59:42 +00004353/// ::= .macros_on
4354/// ::= .macros_off
Jim Grosbach4b905842013-09-20 23:08:21 +00004355bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
Nirav Davea645433c2016-07-18 15:24:03 +00004356 if (parseToken(AsmToken::EndOfStatement,
4357 "unexpected token in '" + Directive + "' directive"))
4358 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004359
Jim Grosbach4b905842013-09-20 23:08:21 +00004360 setMacrosEnabled(Directive == ".macros_on");
Eli Bendersky17233942013-01-15 22:59:42 +00004361 return false;
4362}
4363
Jim Grosbach4b905842013-09-20 23:08:21 +00004364/// parseDirectiveMacro
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00004365/// ::= .macro name[,] [parameters]
Jim Grosbach4b905842013-09-20 23:08:21 +00004366bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004367 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004368 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00004369 return TokError("expected identifier in '.macro' directive");
4370
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00004371 if (getLexer().is(AsmToken::Comma))
4372 Lex();
4373
Eli Bendersky17233942013-01-15 22:59:42 +00004374 MCAsmMacroParameters Parameters;
David Majnemer91fc4c22014-01-29 18:57:46 +00004375 while (getLexer().isNot(AsmToken::EndOfStatement)) {
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00004376
Alexander Kornienko8c0809c2015-01-15 11:41:30 +00004377 if (!Parameters.empty() && Parameters.back().Vararg)
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00004378 return Error(Lexer.getLoc(),
4379 "Vararg parameter '" + Parameters.back().Name +
4380 "' should be last one in the list of parameters.");
4381
David Majnemer91fc4c22014-01-29 18:57:46 +00004382 MCAsmMacroParameter Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00004383 if (parseIdentifier(Parameter.Name))
David Majnemer91fc4c22014-01-29 18:57:46 +00004384 return TokError("expected identifier in '.macro' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00004385
Coby Tayreebedaae02017-04-08 20:29:03 +00004386 // Emit an error if two (or more) named parameters share the same name
4387 for (const MCAsmMacroParameter& CurrParam : Parameters)
4388 if (CurrParam.Name.equals(Parameter.Name))
4389 return TokError("macro '" + Name + "' has multiple parameters"
4390 " named '" + Parameter.Name + "'");
4391
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00004392 if (Lexer.is(AsmToken::Colon)) {
4393 Lex(); // consume ':'
4394
4395 SMLoc QualLoc;
4396 StringRef Qualifier;
4397
4398 QualLoc = Lexer.getLoc();
4399 if (parseIdentifier(Qualifier))
4400 return Error(QualLoc, "missing parameter qualifier for "
4401 "'" + Parameter.Name + "' in macro '" + Name + "'");
4402
4403 if (Qualifier == "req")
4404 Parameter.Required = true;
Kevin Enderbye3c13462014-08-04 23:14:37 +00004405 else if (Qualifier == "vararg")
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00004406 Parameter.Vararg = true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00004407 else
4408 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
4409 "for '" + Parameter.Name + "' in macro '" + Name + "'");
4410 }
4411
David Majnemer91fc4c22014-01-29 18:57:46 +00004412 if (getLexer().is(AsmToken::Equal)) {
4413 Lex();
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00004414
4415 SMLoc ParamLoc;
4416
4417 ParamLoc = Lexer.getLoc();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00004418 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
David Majnemer91fc4c22014-01-29 18:57:46 +00004419 return true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00004420
4421 if (Parameter.Required)
4422 Warning(ParamLoc, "pointless default value for required parameter "
4423 "'" + Parameter.Name + "' in macro '" + Name + "'");
Eli Bendersky17233942013-01-15 22:59:42 +00004424 }
David Majnemer91fc4c22014-01-29 18:57:46 +00004425
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00004426 Parameters.push_back(std::move(Parameter));
David Majnemer91fc4c22014-01-29 18:57:46 +00004427
4428 if (getLexer().is(AsmToken::Comma))
4429 Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00004430 }
4431
Nirav Dave1180e6892016-06-02 17:15:05 +00004432 // Eat just the end of statement.
4433 Lexer.Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00004434
Nirav Dave1180e6892016-06-02 17:15:05 +00004435 // Consuming deferred text, so use Lexer.Lex to ignore Lexing Errors
Eli Bendersky17233942013-01-15 22:59:42 +00004436 AsmToken EndToken, StartToken = getTok();
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00004437 unsigned MacroDepth = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00004438 // Lex the macro definition.
Eugene Zelenko33d7b762016-08-23 17:14:32 +00004439 while (true) {
Nirav Dave1180e6892016-06-02 17:15:05 +00004440 // Ignore Lexing errors in macros.
4441 while (Lexer.is(AsmToken::Error)) {
4442 Lexer.Lex();
4443 }
4444
Eli Bendersky17233942013-01-15 22:59:42 +00004445 // Check whether we have reached the end of the file.
4446 if (getLexer().is(AsmToken::Eof))
4447 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
4448
4449 // Otherwise, check whether we have reach the .endmacro.
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00004450 if (getLexer().is(AsmToken::Identifier)) {
4451 if (getTok().getIdentifier() == ".endm" ||
4452 getTok().getIdentifier() == ".endmacro") {
4453 if (MacroDepth == 0) { // Outermost macro.
4454 EndToken = getTok();
Nirav Dave1180e6892016-06-02 17:15:05 +00004455 Lexer.Lex();
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00004456 if (getLexer().isNot(AsmToken::EndOfStatement))
4457 return TokError("unexpected token in '" + EndToken.getIdentifier() +
4458 "' directive");
4459 break;
4460 } else {
4461 // Otherwise we just found the end of an inner macro.
4462 --MacroDepth;
4463 }
4464 } else if (getTok().getIdentifier() == ".macro") {
4465 // We allow nested macros. Those aren't instantiated until the outermost
4466 // macro is expanded so just ignore them for now.
4467 ++MacroDepth;
4468 }
Eli Bendersky17233942013-01-15 22:59:42 +00004469 }
4470
4471 // Otherwise, scan til the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004472 eatToEndOfStatement();
Eli Bendersky17233942013-01-15 22:59:42 +00004473 }
4474
Rafael Espindola22c38a02018-02-14 16:34:27 +00004475 if (getContext().lookupMacro(Name)) {
Eli Bendersky17233942013-01-15 22:59:42 +00004476 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
4477 }
4478
4479 const char *BodyStart = StartToken.getLoc().getPointer();
4480 const char *BodyEnd = EndToken.getLoc().getPointer();
4481 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Jim Grosbach4b905842013-09-20 23:08:21 +00004482 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
Oliver Stannardc3e7c6d2018-03-06 15:32:34 +00004483 MCAsmMacro Macro(Name, Body, std::move(Parameters));
4484 DEBUG_WITH_TYPE("asm-macros", dbgs() << "Defining new macro:\n";
4485 Macro.dump());
4486 getContext().defineMacro(Name, std::move(Macro));
Eli Bendersky17233942013-01-15 22:59:42 +00004487 return false;
4488}
4489
Jim Grosbach4b905842013-09-20 23:08:21 +00004490/// checkForBadMacro
Kevin Enderby81c944c2013-01-22 21:44:53 +00004491///
4492/// With the support added for named parameters there may be code out there that
4493/// is transitioning from positional parameters. In versions of gas that did
Alp Tokercb402912014-01-24 17:20:08 +00004494/// not support named parameters they would be ignored on the macro definition.
Kevin Enderby81c944c2013-01-22 21:44:53 +00004495/// But to support both styles of parameters this is not possible so if a macro
Alp Tokercb402912014-01-24 17:20:08 +00004496/// definition has named parameters but does not use them and has what appears
Kevin Enderby81c944c2013-01-22 21:44:53 +00004497/// to be positional parameters, strings like $1, $2, ... and $n, then issue a
4498/// warning that the positional parameter found in body which have no effect.
4499/// Hoping the developer will either remove the named parameters from the macro
Alp Tokercb402912014-01-24 17:20:08 +00004500/// definition so the positional parameters get used if that was what was
Kevin Enderby81c944c2013-01-22 21:44:53 +00004501/// intended or change the macro to use the named parameters. It is possible
4502/// this warning will trigger when the none of the named parameters are used
4503/// and the strings like $1 are infact to simply to be passed trough unchanged.
Jim Grosbach4b905842013-09-20 23:08:21 +00004504void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
Kevin Enderby81c944c2013-01-22 21:44:53 +00004505 StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00004506 ArrayRef<MCAsmMacroParameter> Parameters) {
Kevin Enderby81c944c2013-01-22 21:44:53 +00004507 // If this macro is not defined with named parameters the warning we are
4508 // checking for here doesn't apply.
4509 unsigned NParameters = Parameters.size();
4510 if (NParameters == 0)
4511 return;
4512
4513 bool NamedParametersFound = false;
4514 bool PositionalParametersFound = false;
4515
4516 // Look at the body of the macro for use of both the named parameters and what
4517 // are likely to be positional parameters. This is what expandMacro() is
4518 // doing when it finds the parameters in the body.
4519 while (!Body.empty()) {
4520 // Scan for the next possible parameter.
4521 std::size_t End = Body.size(), Pos = 0;
4522 for (; Pos != End; ++Pos) {
4523 // Check for a substitution or escape.
4524 // This macro is defined with parameters, look for \foo, \bar, etc.
4525 if (Body[Pos] == '\\' && Pos + 1 != End)
4526 break;
4527
4528 // This macro should have parameters, but look for $0, $1, ..., $n too.
4529 if (Body[Pos] != '$' || Pos + 1 == End)
4530 continue;
4531 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00004532 if (Next == '$' || Next == 'n' ||
4533 isdigit(static_cast<unsigned char>(Next)))
Kevin Enderby81c944c2013-01-22 21:44:53 +00004534 break;
4535 }
4536
4537 // Check if we reached the end.
4538 if (Pos == End)
4539 break;
4540
4541 if (Body[Pos] == '$') {
Jim Grosbach4b905842013-09-20 23:08:21 +00004542 switch (Body[Pos + 1]) {
4543 // $$ => $
Kevin Enderby81c944c2013-01-22 21:44:53 +00004544 case '$':
4545 break;
4546
Jim Grosbach4b905842013-09-20 23:08:21 +00004547 // $n => number of arguments
Kevin Enderby81c944c2013-01-22 21:44:53 +00004548 case 'n':
4549 PositionalParametersFound = true;
4550 break;
4551
Jim Grosbach4b905842013-09-20 23:08:21 +00004552 // $[0-9] => argument
Kevin Enderby81c944c2013-01-22 21:44:53 +00004553 default: {
4554 PositionalParametersFound = true;
4555 break;
Jim Grosbach4b905842013-09-20 23:08:21 +00004556 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00004557 }
4558 Pos += 2;
4559 } else {
4560 unsigned I = Pos + 1;
4561 while (isIdentifierChar(Body[I]) && I + 1 != End)
4562 ++I;
4563
Jim Grosbach4b905842013-09-20 23:08:21 +00004564 const char *Begin = Body.data() + Pos + 1;
4565 StringRef Argument(Begin, I - (Pos + 1));
Kevin Enderby81c944c2013-01-22 21:44:53 +00004566 unsigned Index = 0;
4567 for (; Index < NParameters; ++Index)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00004568 if (Parameters[Index].Name == Argument)
Kevin Enderby81c944c2013-01-22 21:44:53 +00004569 break;
4570
4571 if (Index == NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00004572 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
4573 Pos += 3;
4574 else {
4575 Pos = I;
4576 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00004577 } else {
4578 NamedParametersFound = true;
4579 Pos += 1 + Argument.size();
4580 }
4581 }
4582 // Update the scan point.
4583 Body = Body.substr(Pos);
4584 }
4585
4586 if (!NamedParametersFound && PositionalParametersFound)
4587 Warning(DirectiveLoc, "macro defined with named parameters which are not "
4588 "used in macro body, possible positional parameter "
4589 "found in body which will have no effect");
4590}
4591
Nico Weber155dccd12014-07-24 17:08:39 +00004592/// parseDirectiveExitMacro
4593/// ::= .exitm
4594bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
Nirav Davea645433c2016-07-18 15:24:03 +00004595 if (parseToken(AsmToken::EndOfStatement,
4596 "unexpected token in '" + Directive + "' directive"))
4597 return true;
Nico Weber155dccd12014-07-24 17:08:39 +00004598
4599 if (!isInsideMacroInstantiation())
4600 return TokError("unexpected '" + Directive + "' in file, "
4601 "no current macro definition");
4602
4603 // Exit all conditionals that are active in the current macro.
4604 while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
4605 TheCondState = TheCondStack.back();
4606 TheCondStack.pop_back();
4607 }
4608
4609 handleMacroExit();
4610 return false;
4611}
4612
Jim Grosbach4b905842013-09-20 23:08:21 +00004613/// parseDirectiveEndMacro
Eli Bendersky17233942013-01-15 22:59:42 +00004614/// ::= .endm
4615/// ::= .endmacro
Jim Grosbach4b905842013-09-20 23:08:21 +00004616bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
Eli Bendersky17233942013-01-15 22:59:42 +00004617 if (getLexer().isNot(AsmToken::EndOfStatement))
4618 return TokError("unexpected token in '" + Directive + "' directive");
4619
4620 // If we are inside a macro instantiation, terminate the current
4621 // instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00004622 if (isInsideMacroInstantiation()) {
4623 handleMacroExit();
Eli Bendersky17233942013-01-15 22:59:42 +00004624 return false;
4625 }
4626
4627 // Otherwise, this .endmacro is a stray entry in the file; well formed
4628 // .endmacro directives are handled during the macro definition parsing.
4629 return TokError("unexpected '" + Directive + "' in file, "
Jim Grosbach4b905842013-09-20 23:08:21 +00004630 "no current macro definition");
Eli Bendersky17233942013-01-15 22:59:42 +00004631}
4632
Jim Grosbach4b905842013-09-20 23:08:21 +00004633/// parseDirectivePurgeMacro
Eli Bendersky17233942013-01-15 22:59:42 +00004634/// ::= .purgem
Jim Grosbach4b905842013-09-20 23:08:21 +00004635bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004636 StringRef Name;
Nirav Davea645433c2016-07-18 15:24:03 +00004637 SMLoc Loc;
Nirav Daved8858ca2016-08-30 14:15:43 +00004638 if (parseTokenLoc(Loc) ||
4639 check(parseIdentifier(Name), Loc,
4640 "expected identifier in '.purgem' directive") ||
Nirav Davea645433c2016-07-18 15:24:03 +00004641 parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00004642 "unexpected token in '.purgem' directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00004643 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004644
Rafael Espindola22c38a02018-02-14 16:34:27 +00004645 if (!getContext().lookupMacro(Name))
Nirav Dave1ab71992016-07-18 19:35:21 +00004646 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
4647
Rafael Espindola22c38a02018-02-14 16:34:27 +00004648 getContext().undefineMacro(Name);
Oliver Stannardc3e7c6d2018-03-06 15:32:34 +00004649 DEBUG_WITH_TYPE("asm-macros", dbgs()
4650 << "Un-defining macro: " << Name << "\n");
Eli Bendersky17233942013-01-15 22:59:42 +00004651 return false;
4652}
Eli Benderskyf483ff92012-12-20 19:05:53 +00004653
Jim Grosbach4b905842013-09-20 23:08:21 +00004654/// parseDirectiveBundleAlignMode
Eli Benderskyf483ff92012-12-20 19:05:53 +00004655/// ::= {.bundle_align_mode} expression
Jim Grosbach4b905842013-09-20 23:08:21 +00004656bool AsmParser::parseDirectiveBundleAlignMode() {
Eli Benderskyf483ff92012-12-20 19:05:53 +00004657 // Expect a single argument: an expression that evaluates to a constant
4658 // in the inclusive range 0-30.
4659 SMLoc ExprLoc = getLexer().getLoc();
4660 int64_t AlignSizePow2;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004661 if (checkForValidSection() || parseAbsoluteExpression(AlignSizePow2) ||
Nirav Davea645433c2016-07-18 15:24:03 +00004662 parseToken(AsmToken::EndOfStatement, "unexpected token after expression "
4663 "in '.bundle_align_mode' "
4664 "directive") ||
4665 check(AlignSizePow2 < 0 || AlignSizePow2 > 30, ExprLoc,
4666 "invalid bundle alignment size (expected between 0 and 30)"))
Eli Benderskyf483ff92012-12-20 19:05:53 +00004667 return true;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004668
4669 // Because of AlignSizePow2's verified range we can safely truncate it to
4670 // unsigned.
4671 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
4672 return false;
4673}
4674
Jim Grosbach4b905842013-09-20 23:08:21 +00004675/// parseDirectiveBundleLock
Eli Bendersky802b6282013-01-07 21:51:08 +00004676/// ::= {.bundle_lock} [align_to_end]
Jim Grosbach4b905842013-09-20 23:08:21 +00004677bool AsmParser::parseDirectiveBundleLock() {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004678 if (checkForValidSection())
4679 return true;
Eli Bendersky802b6282013-01-07 21:51:08 +00004680 bool AlignToEnd = false;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004681
Nirav Dave1a9044b2016-10-24 14:35:29 +00004682 StringRef Option;
4683 SMLoc Loc = getTok().getLoc();
4684 const char *kInvalidOptionError =
4685 "invalid option for '.bundle_lock' directive";
Eli Bendersky802b6282013-01-07 21:51:08 +00004686
Nirav Dave1a9044b2016-10-24 14:35:29 +00004687 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
Nirav Davea645433c2016-07-18 15:24:03 +00004688 if (check(parseIdentifier(Option), Loc, kInvalidOptionError) ||
4689 check(Option != "align_to_end", Loc, kInvalidOptionError) ||
Nirav Dave1a9044b2016-10-24 14:35:29 +00004690 parseToken(AsmToken::EndOfStatement,
4691 "unexpected token after '.bundle_lock' directive option"))
Nirav Davea645433c2016-07-18 15:24:03 +00004692 return true;
Eli Bendersky802b6282013-01-07 21:51:08 +00004693 AlignToEnd = true;
4694 }
4695
Eli Bendersky802b6282013-01-07 21:51:08 +00004696 getStreamer().EmitBundleLock(AlignToEnd);
Eli Benderskyf483ff92012-12-20 19:05:53 +00004697 return false;
4698}
4699
Jim Grosbach4b905842013-09-20 23:08:21 +00004700/// parseDirectiveBundleLock
Eli Benderskyf483ff92012-12-20 19:05:53 +00004701/// ::= {.bundle_lock}
Jim Grosbach4b905842013-09-20 23:08:21 +00004702bool AsmParser::parseDirectiveBundleUnlock() {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004703 if (checkForValidSection() ||
4704 parseToken(AsmToken::EndOfStatement,
Nirav Davea645433c2016-07-18 15:24:03 +00004705 "unexpected token in '.bundle_unlock' directive"))
4706 return true;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004707
4708 getStreamer().EmitBundleUnlock();
4709 return false;
4710}
4711
Jim Grosbach4b905842013-09-20 23:08:21 +00004712/// parseDirectiveSpace
Eli Bendersky17233942013-01-15 22:59:42 +00004713/// ::= (.skip | .space) expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004714bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
Petr Hosek67a94a72016-05-28 05:57:48 +00004715 SMLoc NumBytesLoc = Lexer.getLoc();
4716 const MCExpr *NumBytes;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004717 if (checkForValidSection() || parseExpression(NumBytes))
Eli Bendersky17233942013-01-15 22:59:42 +00004718 return true;
4719
4720 int64_t FillExpr = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00004721 if (parseOptionalToken(AsmToken::Comma))
4722 if (parseAbsoluteExpression(FillExpr))
4723 return addErrorSuffix("in '" + Twine(IDVal) + "' directive");
4724 if (parseToken(AsmToken::EndOfStatement))
4725 return addErrorSuffix("in '" + Twine(IDVal) + "' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00004726
Eli Bendersky17233942013-01-15 22:59:42 +00004727 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
Petr Hosek67a94a72016-05-28 05:57:48 +00004728 getStreamer().emitFill(*NumBytes, FillExpr, NumBytesLoc);
Eli Bendersky17233942013-01-15 22:59:42 +00004729
4730 return false;
4731}
4732
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004733/// parseDirectiveDCB
4734/// ::= .dcb.{b, l, w} expression, expression
4735bool AsmParser::parseDirectiveDCB(StringRef IDVal, unsigned Size) {
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004736 SMLoc NumValuesLoc = Lexer.getLoc();
4737 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004738 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004739 return true;
4740
4741 if (NumValues < 0) {
4742 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4743 return false;
4744 }
4745
4746 if (parseToken(AsmToken::Comma,
4747 "unexpected token in '" + Twine(IDVal) + "' directive"))
4748 return true;
4749
4750 const MCExpr *Value;
4751 SMLoc ExprLoc = getLexer().getLoc();
4752 if (parseExpression(Value))
4753 return true;
4754
4755 // Special case constant expressions to match code generator.
4756 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
4757 assert(Size <= 8 && "Invalid size");
4758 uint64_t IntValue = MCE->getValue();
4759 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
4760 return Error(ExprLoc, "literal value out of range for directive");
4761 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4762 getStreamer().EmitIntValue(IntValue, Size);
4763 } else {
4764 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4765 getStreamer().EmitValue(Value, Size, ExprLoc);
4766 }
4767
4768 if (parseToken(AsmToken::EndOfStatement,
4769 "unexpected token in '" + Twine(IDVal) + "' directive"))
4770 return true;
4771
4772 return false;
4773}
4774
4775/// parseDirectiveRealDCB
4776/// ::= .dcb.{d, s} expression, expression
4777bool AsmParser::parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &Semantics) {
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004778 SMLoc NumValuesLoc = Lexer.getLoc();
4779 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004780 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004781 return true;
4782
4783 if (NumValues < 0) {
4784 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4785 return false;
4786 }
4787
4788 if (parseToken(AsmToken::Comma,
4789 "unexpected token in '" + Twine(IDVal) + "' directive"))
4790 return true;
4791
4792 APInt AsInt;
4793 if (parseRealValue(Semantics, AsInt))
4794 return true;
4795
4796 if (parseToken(AsmToken::EndOfStatement,
4797 "unexpected token in '" + Twine(IDVal) + "' directive"))
4798 return true;
4799
4800 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4801 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
4802 AsInt.getBitWidth() / 8);
4803
4804 return false;
4805}
4806
Petr Hosek85b2f672016-09-23 21:53:36 +00004807/// parseDirectiveDS
4808/// ::= .ds.{b, d, l, p, s, w, x} expression
4809bool AsmParser::parseDirectiveDS(StringRef IDVal, unsigned Size) {
Petr Hosek85b2f672016-09-23 21:53:36 +00004810 SMLoc NumValuesLoc = Lexer.getLoc();
4811 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004812 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek85b2f672016-09-23 21:53:36 +00004813 return true;
4814
4815 if (NumValues < 0) {
4816 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4817 return false;
4818 }
4819
4820 if (parseToken(AsmToken::EndOfStatement,
4821 "unexpected token in '" + Twine(IDVal) + "' directive"))
4822 return true;
4823
4824 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4825 getStreamer().emitFill(Size, 0);
4826
4827 return false;
4828}
4829
Jim Grosbach4b905842013-09-20 23:08:21 +00004830/// parseDirectiveLEB128
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004831/// ::= (.sleb128 | .uleb128) [ expression (, expression)* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004832bool AsmParser::parseDirectiveLEB128(bool Signed) {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004833 if (checkForValidSection())
4834 return true;
4835
Nirav Dave1a9044b2016-10-24 14:35:29 +00004836 auto parseOp = [&]() -> bool {
4837 const MCExpr *Value;
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004838 if (parseExpression(Value))
4839 return true;
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004840 if (Signed)
4841 getStreamer().EmitSLEB128Value(Value);
4842 else
4843 getStreamer().EmitULEB128Value(Value);
Nirav Dave1a9044b2016-10-24 14:35:29 +00004844 return false;
4845 };
Eli Bendersky17233942013-01-15 22:59:42 +00004846
Nirav Dave1a9044b2016-10-24 14:35:29 +00004847 if (parseMany(parseOp))
4848 return addErrorSuffix(" in directive");
Eli Bendersky17233942013-01-15 22:59:42 +00004849
4850 return false;
4851}
4852
Jim Grosbach4b905842013-09-20 23:08:21 +00004853/// parseDirectiveSymbolAttribute
Daniel Dunbara5508c82009-06-30 00:33:19 +00004854/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004855bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00004856 auto parseOp = [&]() -> bool {
4857 StringRef Name;
4858 SMLoc Loc = getTok().getLoc();
4859 if (parseIdentifier(Name))
4860 return Error(Loc, "expected identifier");
4861 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004862
Nirav Dave1a9044b2016-10-24 14:35:29 +00004863 // Assembler local symbols don't make any sense here. Complain loudly.
4864 if (Sym->isTemporary())
4865 return Error(Loc, "non-local symbol required");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004866
Nirav Dave1a9044b2016-10-24 14:35:29 +00004867 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
4868 return Error(Loc, "unable to emit symbol attribute");
4869 return false;
4870 };
Daniel Dunbara5508c82009-06-30 00:33:19 +00004871
Nirav Dave1a9044b2016-10-24 14:35:29 +00004872 if (parseMany(parseOp))
4873 return addErrorSuffix(" in directive");
Jan Wen Voungc7682872010-09-30 01:09:20 +00004874 return false;
Daniel Dunbara5508c82009-06-30 00:33:19 +00004875}
Chris Lattnera1e11f52009-07-07 20:30:46 +00004876
Jim Grosbach4b905842013-09-20 23:08:21 +00004877/// parseDirectiveComm
Chris Lattner28ad7542009-07-09 17:25:12 +00004878/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004879bool AsmParser::parseDirectiveComm(bool IsLocal) {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004880 if (checkForValidSection())
4881 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00004882
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004883 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004884 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004885 if (parseIdentifier(Name))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004886 return TokError("expected identifier in directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004887
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +00004888 // Handle the identifier as the key symbol.
Jim Grosbach6f482002015-05-18 18:43:14 +00004889 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Chris Lattnera1e11f52009-07-07 20:30:46 +00004890
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004891 if (getLexer().isNot(AsmToken::Comma))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004892 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00004893 Lex();
Chris Lattnera1e11f52009-07-07 20:30:46 +00004894
4895 int64_t Size;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004896 SMLoc SizeLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004897 if (parseAbsoluteExpression(Size))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004898 return true;
4899
4900 int64_t Pow2Alignment = 0;
4901 SMLoc Pow2AlignmentLoc;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004902 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan686ed8d2010-01-19 20:22:31 +00004903 Lex();
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004904 Pow2AlignmentLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004905 if (parseAbsoluteExpression(Pow2Alignment))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004906 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00004907
Benjamin Kramer68b9f052012-09-07 21:08:01 +00004908 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
4909 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00004910 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
4911
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00004912 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramer68b9f052012-09-07 21:08:01 +00004913 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
4914 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00004915 if (!isPowerOf2_64(Pow2Alignment))
4916 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
4917 Pow2Alignment = Log2_64(Pow2Alignment);
4918 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00004919 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00004920
Nirav Dave1a9044b2016-10-24 14:35:29 +00004921 if (parseToken(AsmToken::EndOfStatement,
4922 "unexpected token in '.comm' or '.lcomm' directive"))
4923 return true;
Chris Lattnera1e11f52009-07-07 20:30:46 +00004924
Chris Lattner28ad7542009-07-09 17:25:12 +00004925 // NOTE: a size of zero for a .comm should create a undefined symbol
4926 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattnera1e11f52009-07-07 20:30:46 +00004927 if (Size < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00004928 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
Jim Grosbach4b905842013-09-20 23:08:21 +00004929 "be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00004930
Eric Christopherbc818852010-05-14 01:38:54 +00004931 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattnera1e11f52009-07-07 20:30:46 +00004932 // may internally end up wanting an alignment in bytes.
4933 // FIXME: Diagnose overflow.
4934 if (Pow2Alignment < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00004935 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
Jim Grosbach4b905842013-09-20 23:08:21 +00004936 "alignment, can't be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00004937
Rafael Espindola13a79bb2017-02-02 21:26:06 +00004938 Sym->redefineIfPossible();
Daniel Dunbar6860ac72009-08-22 07:22:36 +00004939 if (!Sym->isUndefined())
Chris Lattnera1e11f52009-07-07 20:30:46 +00004940 return Error(IDLoc, "invalid symbol redefinition");
4941
Chris Lattner28ad7542009-07-09 17:25:12 +00004942 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00004943 if (IsLocal) {
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00004944 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00004945 return false;
4946 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00004947
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004948 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattnera1e11f52009-07-07 20:30:46 +00004949 return false;
4950}
Chris Lattner07cadaf2009-07-10 22:20:30 +00004951
Jim Grosbach4b905842013-09-20 23:08:21 +00004952/// parseDirectiveAbort
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004953/// ::= .abort [... message ...]
Jim Grosbach4b905842013-09-20 23:08:21 +00004954bool AsmParser::parseDirectiveAbort() {
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004955 // FIXME: Use loc from directive.
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004956 SMLoc Loc = getLexer().getLoc();
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004957
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004958 StringRef Str = parseStringToEndOfStatement();
Nirav Davea645433c2016-07-18 15:24:03 +00004959 if (parseToken(AsmToken::EndOfStatement,
4960 "unexpected token in '.abort' directive"))
4961 return true;
Kevin Enderby56523ce2009-07-13 23:15:14 +00004962
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004963 if (Str.empty())
Nirav Dave2364748a2016-09-16 18:30:20 +00004964 return Error(Loc, ".abort detected. Assembly stopping.");
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004965 else
Nirav Dave2364748a2016-09-16 18:30:20 +00004966 return Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004967 // FIXME: Actually abort assembly here.
Kevin Enderby56523ce2009-07-13 23:15:14 +00004968
4969 return false;
4970}
Kevin Enderbycbe475d2009-07-14 21:35:03 +00004971
Jim Grosbach4b905842013-09-20 23:08:21 +00004972/// parseDirectiveInclude
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004973/// ::= .include "filename"
Jim Grosbach4b905842013-09-20 23:08:21 +00004974bool AsmParser::parseDirectiveInclude() {
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004975 // Allow the strings to have escaped octal character sequence.
4976 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00004977 SMLoc IncludeLoc = getTok().getLoc();
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004978
Nirav Davea645433c2016-07-18 15:24:03 +00004979 if (check(getTok().isNot(AsmToken::String),
4980 "expected string in '.include' directive") ||
4981 parseEscapedString(Filename) ||
4982 check(getTok().isNot(AsmToken::EndOfStatement),
4983 "unexpected token in '.include' directive") ||
4984 // Attempt to switch the lexer to the included file before consuming the
4985 // end of statement to avoid losing it when we switch.
4986 check(enterIncludeFile(Filename), IncludeLoc,
4987 "Could not find include file '" + Filename + "'"))
Chris Lattner693fbb82009-07-16 06:14:39 +00004988 return true;
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004989
4990 return false;
4991}
Kevin Enderby09ea5702009-07-15 15:30:11 +00004992
Jim Grosbach4b905842013-09-20 23:08:21 +00004993/// parseDirectiveIncbin
Petr Hosek2f4ac442016-09-23 00:41:06 +00004994/// ::= .incbin "filename" [ , skip [ , count ] ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004995bool AsmParser::parseDirectiveIncbin() {
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004996 // Allow the strings to have escaped octal character sequence.
4997 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00004998 SMLoc IncbinLoc = getTok().getLoc();
4999 if (check(getTok().isNot(AsmToken::String),
5000 "expected string in '.incbin' directive") ||
Petr Hosek2f4ac442016-09-23 00:41:06 +00005001 parseEscapedString(Filename))
5002 return true;
5003
5004 int64_t Skip = 0;
5005 const MCExpr *Count = nullptr;
5006 SMLoc SkipLoc, CountLoc;
Nirav Dave1a9044b2016-10-24 14:35:29 +00005007 if (parseOptionalToken(AsmToken::Comma)) {
Petr Hosek2f4ac442016-09-23 00:41:06 +00005008 // The skip expression can be omitted while specifying the count, e.g:
5009 // .incbin "filename",,4
5010 if (getTok().isNot(AsmToken::Comma)) {
5011 if (parseTokenLoc(SkipLoc) || parseAbsoluteExpression(Skip))
5012 return true;
5013 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00005014 if (parseOptionalToken(AsmToken::Comma)) {
5015 CountLoc = getTok().getLoc();
5016 if (parseExpression(Count))
Petr Hosek2f4ac442016-09-23 00:41:06 +00005017 return true;
5018 }
5019 }
5020
5021 if (parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00005022 "unexpected token in '.incbin' directive"))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00005023 return true;
Nirav Dave1ab71992016-07-18 19:35:21 +00005024
Petr Hosek2f4ac442016-09-23 00:41:06 +00005025 if (check(Skip < 0, SkipLoc, "skip is negative"))
5026 return true;
5027
Nirav Dave1ab71992016-07-18 19:35:21 +00005028 // Attempt to process the included file.
Petr Hosek2f4ac442016-09-23 00:41:06 +00005029 if (processIncbinFile(Filename, Skip, Count, CountLoc))
Nirav Dave1ab71992016-07-18 19:35:21 +00005030 return Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
Kevin Enderby109f25c2011-12-14 21:47:48 +00005031 return false;
5032}
5033
Jim Grosbach4b905842013-09-20 23:08:21 +00005034/// parseDirectiveIf
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00005035/// ::= .if{,eq,ge,gt,le,lt,ne} expression
5036bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005037 TheCondStack.push_back(TheCondState);
5038 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00005039 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005040 eatToEndOfStatement();
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00005041 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005042 int64_t ExprValue;
Nirav Davea645433c2016-07-18 15:24:03 +00005043 if (parseAbsoluteExpression(ExprValue) ||
5044 parseToken(AsmToken::EndOfStatement,
5045 "unexpected token in '.if' directive"))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005046 return true;
5047
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00005048 switch (DirKind) {
5049 default:
5050 llvm_unreachable("unsupported directive");
5051 case DK_IF:
5052 case DK_IFNE:
5053 break;
5054 case DK_IFEQ:
5055 ExprValue = ExprValue == 0;
5056 break;
5057 case DK_IFGE:
5058 ExprValue = ExprValue >= 0;
5059 break;
5060 case DK_IFGT:
5061 ExprValue = ExprValue > 0;
5062 break;
5063 case DK_IFLE:
5064 ExprValue = ExprValue <= 0;
5065 break;
5066 case DK_IFLT:
5067 ExprValue = ExprValue < 0;
5068 break;
5069 }
5070
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005071 TheCondState.CondMet = ExprValue;
5072 TheCondState.Ignore = !TheCondState.CondMet;
5073 }
5074
5075 return false;
5076}
5077
Jim Grosbach4b905842013-09-20 23:08:21 +00005078/// parseDirectiveIfb
Benjamin Kramer62c18b02012-05-12 11:18:42 +00005079/// ::= .ifb string
Jim Grosbach4b905842013-09-20 23:08:21 +00005080bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
Benjamin Kramer62c18b02012-05-12 11:18:42 +00005081 TheCondStack.push_back(TheCondState);
5082 TheCondState.TheCond = AsmCond::IfCond;
5083
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00005084 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005085 eatToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00005086 } else {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005087 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00005088
Nirav Davea645433c2016-07-18 15:24:03 +00005089 if (parseToken(AsmToken::EndOfStatement,
5090 "unexpected token in '.ifb' directive"))
5091 return true;
Benjamin Kramer62c18b02012-05-12 11:18:42 +00005092
5093 TheCondState.CondMet = ExpectBlank == Str.empty();
5094 TheCondState.Ignore = !TheCondState.CondMet;
5095 }
5096
5097 return false;
5098}
5099
Jim Grosbach4b905842013-09-20 23:08:21 +00005100/// parseDirectiveIfc
Benjamin Kramere297b9f2012-05-12 11:18:51 +00005101/// ::= .ifc string1, string2
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00005102/// ::= .ifnc string1, string2
Jim Grosbach4b905842013-09-20 23:08:21 +00005103bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
Benjamin Kramere297b9f2012-05-12 11:18:51 +00005104 TheCondStack.push_back(TheCondState);
5105 TheCondState.TheCond = AsmCond::IfCond;
5106
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00005107 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005108 eatToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00005109 } else {
Jim Grosbach4b905842013-09-20 23:08:21 +00005110 StringRef Str1 = parseStringToComma();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00005111
Nirav Davea645433c2016-07-18 15:24:03 +00005112 if (parseToken(AsmToken::Comma, "unexpected token in '.ifc' directive"))
5113 return true;
Benjamin Kramere297b9f2012-05-12 11:18:51 +00005114
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005115 StringRef Str2 = parseStringToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00005116
Nirav Davea645433c2016-07-18 15:24:03 +00005117 if (parseToken(AsmToken::EndOfStatement,
5118 "unexpected token in '.ifc' directive"))
5119 return true;
Benjamin Kramere297b9f2012-05-12 11:18:51 +00005120
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00005121 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
Benjamin Kramere297b9f2012-05-12 11:18:51 +00005122 TheCondState.Ignore = !TheCondState.CondMet;
5123 }
5124
5125 return false;
5126}
5127
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00005128/// parseDirectiveIfeqs
5129/// ::= .ifeqs string1, string2
Sid Manning51c35602015-03-18 14:20:54 +00005130bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual) {
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00005131 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00005132 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00005133 return TokError("expected string parameter for '.ifeqs' directive");
5134 return TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00005135 }
5136
5137 StringRef String1 = getTok().getStringContents();
5138 Lex();
5139
5140 if (Lexer.isNot(AsmToken::Comma)) {
Sid Manning51c35602015-03-18 14:20:54 +00005141 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00005142 return TokError(
5143 "expected comma after first string for '.ifeqs' directive");
5144 return TokError("expected comma after first string for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00005145 }
5146
5147 Lex();
5148
5149 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00005150 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00005151 return TokError("expected string parameter for '.ifeqs' directive");
5152 return TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00005153 }
5154
5155 StringRef String2 = getTok().getStringContents();
5156 Lex();
5157
5158 TheCondStack.push_back(TheCondState);
5159 TheCondState.TheCond = AsmCond::IfCond;
Sid Manning51c35602015-03-18 14:20:54 +00005160 TheCondState.CondMet = ExpectEqual == (String1 == String2);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00005161 TheCondState.Ignore = !TheCondState.CondMet;
5162
5163 return false;
5164}
5165
Jim Grosbach4b905842013-09-20 23:08:21 +00005166/// parseDirectiveIfdef
Benjamin Kramere297b9f2012-05-12 11:18:51 +00005167/// ::= .ifdef symbol
Jim Grosbach4b905842013-09-20 23:08:21 +00005168bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00005169 StringRef Name;
5170 TheCondStack.push_back(TheCondState);
5171 TheCondState.TheCond = AsmCond::IfCond;
5172
5173 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005174 eatToEndOfStatement();
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00005175 } else {
Nirav Davea645433c2016-07-18 15:24:03 +00005176 if (check(parseIdentifier(Name), "expected identifier after '.ifdef'") ||
5177 parseToken(AsmToken::EndOfStatement, "unexpected token in '.ifdef'"))
5178 return true;
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00005179
Jim Grosbach6f482002015-05-18 18:43:14 +00005180 MCSymbol *Sym = getContext().lookupSymbol(Name);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00005181
5182 if (expect_defined)
Scott Linderb5d62922019-01-28 19:32:08 +00005183 TheCondState.CondMet = (Sym && !Sym->isUndefined(false));
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00005184 else
Scott Linderb5d62922019-01-28 19:32:08 +00005185 TheCondState.CondMet = (!Sym || Sym->isUndefined(false));
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00005186 TheCondState.Ignore = !TheCondState.CondMet;
5187 }
5188
5189 return false;
5190}
5191
Jim Grosbach4b905842013-09-20 23:08:21 +00005192/// parseDirectiveElseIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005193/// ::= .elseif expression
Jim Grosbach4b905842013-09-20 23:08:21 +00005194bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005195 if (TheCondState.TheCond != AsmCond::IfCond &&
5196 TheCondState.TheCond != AsmCond::ElseIfCond)
Nirav Dave2364748a2016-09-16 18:30:20 +00005197 return Error(DirectiveLoc, "Encountered a .elseif that doesn't follow an"
5198 " .if or an .elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005199 TheCondState.TheCond = AsmCond::ElseIfCond;
5200
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005201 bool LastIgnoreState = false;
5202 if (!TheCondStack.empty())
Craig Topper2172ad62013-04-22 04:24:02 +00005203 LastIgnoreState = TheCondStack.back().Ignore;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005204 if (LastIgnoreState || TheCondState.CondMet) {
5205 TheCondState.Ignore = true;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005206 eatToEndOfStatement();
Craig Topperf15655b2013-04-22 04:22:40 +00005207 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005208 int64_t ExprValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005209 if (parseAbsoluteExpression(ExprValue))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005210 return true;
5211
Nirav Dave1a9044b2016-10-24 14:35:29 +00005212 if (parseToken(AsmToken::EndOfStatement,
5213 "unexpected token in '.elseif' directive"))
5214 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00005215
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005216 TheCondState.CondMet = ExprValue;
5217 TheCondState.Ignore = !TheCondState.CondMet;
5218 }
5219
5220 return false;
5221}
5222
Jim Grosbach4b905842013-09-20 23:08:21 +00005223/// parseDirectiveElse
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005224/// ::= .else
Jim Grosbach4b905842013-09-20 23:08:21 +00005225bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00005226 if (parseToken(AsmToken::EndOfStatement,
5227 "unexpected token in '.else' directive"))
5228 return true;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005229
5230 if (TheCondState.TheCond != AsmCond::IfCond &&
5231 TheCondState.TheCond != AsmCond::ElseIfCond)
Nirav Dave2364748a2016-09-16 18:30:20 +00005232 return Error(DirectiveLoc, "Encountered a .else that doesn't follow "
5233 " an .if or an .elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005234 TheCondState.TheCond = AsmCond::ElseCond;
5235 bool LastIgnoreState = false;
5236 if (!TheCondStack.empty())
5237 LastIgnoreState = TheCondStack.back().Ignore;
5238 if (LastIgnoreState || TheCondState.CondMet)
5239 TheCondState.Ignore = true;
5240 else
5241 TheCondState.Ignore = false;
5242
5243 return false;
5244}
5245
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00005246/// parseDirectiveEnd
5247/// ::= .end
5248bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00005249 if (parseToken(AsmToken::EndOfStatement,
5250 "unexpected token in '.end' directive"))
5251 return true;
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00005252
5253 while (Lexer.isNot(AsmToken::Eof))
Nirav Dave1a9044b2016-10-24 14:35:29 +00005254 Lexer.Lex();
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00005255
5256 return false;
5257}
5258
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00005259/// parseDirectiveError
5260/// ::= .err
5261/// ::= .error [string]
5262bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
5263 if (!TheCondStack.empty()) {
5264 if (TheCondStack.back().Ignore) {
5265 eatToEndOfStatement();
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00005266 return false;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00005267 }
5268 }
5269
5270 if (!WithMessage)
5271 return Error(L, ".err encountered");
5272
5273 StringRef Message = ".error directive invoked in source file";
5274 if (Lexer.isNot(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00005275 if (Lexer.isNot(AsmToken::String))
5276 return TokError(".error argument must be a string");
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00005277
5278 Message = getTok().getStringContents();
5279 Lex();
5280 }
5281
Nirav Dave2364748a2016-09-16 18:30:20 +00005282 return Error(L, Message);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00005283}
5284
Nico Weber404012b2014-07-24 16:26:06 +00005285/// parseDirectiveWarning
5286/// ::= .warning [string]
5287bool AsmParser::parseDirectiveWarning(SMLoc L) {
5288 if (!TheCondStack.empty()) {
5289 if (TheCondStack.back().Ignore) {
5290 eatToEndOfStatement();
5291 return false;
5292 }
5293 }
5294
5295 StringRef Message = ".warning directive invoked in source file";
Nirav Dave1a9044b2016-10-24 14:35:29 +00005296
5297 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00005298 if (Lexer.isNot(AsmToken::String))
5299 return TokError(".warning argument must be a string");
Nico Weber404012b2014-07-24 16:26:06 +00005300
5301 Message = getTok().getStringContents();
5302 Lex();
Nirav Dave1a9044b2016-10-24 14:35:29 +00005303 if (parseToken(AsmToken::EndOfStatement,
5304 "expected end of statement in '.warning' directive"))
5305 return true;
Nico Weber404012b2014-07-24 16:26:06 +00005306 }
5307
Nirav Dave2364748a2016-09-16 18:30:20 +00005308 return Warning(L, Message);
Nico Weber404012b2014-07-24 16:26:06 +00005309}
5310
Jim Grosbach4b905842013-09-20 23:08:21 +00005311/// parseDirectiveEndIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005312/// ::= .endif
Jim Grosbach4b905842013-09-20 23:08:21 +00005313bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00005314 if (parseToken(AsmToken::EndOfStatement,
5315 "unexpected token in '.endif' directive"))
5316 return true;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005317
Jim Grosbach4b905842013-09-20 23:08:21 +00005318 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
Nirav Dave2364748a2016-09-16 18:30:20 +00005319 return Error(DirectiveLoc, "Encountered a .endif that doesn't follow "
5320 "an .if or .else");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005321 if (!TheCondStack.empty()) {
5322 TheCondState = TheCondStack.back();
5323 TheCondStack.pop_back();
5324 }
5325
5326 return false;
5327}
Daniel Dunbara4b069c2009-08-11 04:24:50 +00005328
Eli Bendersky17233942013-01-15 22:59:42 +00005329void AsmParser::initializeDirectiveKindMap() {
5330 DirectiveKindMap[".set"] = DK_SET;
5331 DirectiveKindMap[".equ"] = DK_EQU;
5332 DirectiveKindMap[".equiv"] = DK_EQUIV;
5333 DirectiveKindMap[".ascii"] = DK_ASCII;
5334 DirectiveKindMap[".asciz"] = DK_ASCIZ;
5335 DirectiveKindMap[".string"] = DK_STRING;
5336 DirectiveKindMap[".byte"] = DK_BYTE;
5337 DirectiveKindMap[".short"] = DK_SHORT;
5338 DirectiveKindMap[".value"] = DK_VALUE;
5339 DirectiveKindMap[".2byte"] = DK_2BYTE;
5340 DirectiveKindMap[".long"] = DK_LONG;
5341 DirectiveKindMap[".int"] = DK_INT;
5342 DirectiveKindMap[".4byte"] = DK_4BYTE;
5343 DirectiveKindMap[".quad"] = DK_QUAD;
5344 DirectiveKindMap[".8byte"] = DK_8BYTE;
David Woodhoused6de0d92014-02-01 16:20:59 +00005345 DirectiveKindMap[".octa"] = DK_OCTA;
Eli Bendersky17233942013-01-15 22:59:42 +00005346 DirectiveKindMap[".single"] = DK_SINGLE;
5347 DirectiveKindMap[".float"] = DK_FLOAT;
5348 DirectiveKindMap[".double"] = DK_DOUBLE;
5349 DirectiveKindMap[".align"] = DK_ALIGN;
5350 DirectiveKindMap[".align32"] = DK_ALIGN32;
5351 DirectiveKindMap[".balign"] = DK_BALIGN;
5352 DirectiveKindMap[".balignw"] = DK_BALIGNW;
5353 DirectiveKindMap[".balignl"] = DK_BALIGNL;
5354 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
5355 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
5356 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
5357 DirectiveKindMap[".org"] = DK_ORG;
5358 DirectiveKindMap[".fill"] = DK_FILL;
5359 DirectiveKindMap[".zero"] = DK_ZERO;
5360 DirectiveKindMap[".extern"] = DK_EXTERN;
5361 DirectiveKindMap[".globl"] = DK_GLOBL;
5362 DirectiveKindMap[".global"] = DK_GLOBAL;
Eli Bendersky17233942013-01-15 22:59:42 +00005363 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
5364 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
5365 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
5366 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
5367 DirectiveKindMap[".reference"] = DK_REFERENCE;
5368 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
5369 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
5370 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
Vedant Kumar13ef84f2019-01-25 18:30:22 +00005371 DirectiveKindMap[".cold"] = DK_COLD;
Eli Bendersky17233942013-01-15 22:59:42 +00005372 DirectiveKindMap[".comm"] = DK_COMM;
5373 DirectiveKindMap[".common"] = DK_COMMON;
5374 DirectiveKindMap[".lcomm"] = DK_LCOMM;
5375 DirectiveKindMap[".abort"] = DK_ABORT;
5376 DirectiveKindMap[".include"] = DK_INCLUDE;
5377 DirectiveKindMap[".incbin"] = DK_INCBIN;
5378 DirectiveKindMap[".code16"] = DK_CODE16;
5379 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
5380 DirectiveKindMap[".rept"] = DK_REPT;
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00005381 DirectiveKindMap[".rep"] = DK_REPT;
Eli Bendersky17233942013-01-15 22:59:42 +00005382 DirectiveKindMap[".irp"] = DK_IRP;
5383 DirectiveKindMap[".irpc"] = DK_IRPC;
5384 DirectiveKindMap[".endr"] = DK_ENDR;
5385 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
5386 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
5387 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
5388 DirectiveKindMap[".if"] = DK_IF;
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00005389 DirectiveKindMap[".ifeq"] = DK_IFEQ;
5390 DirectiveKindMap[".ifge"] = DK_IFGE;
5391 DirectiveKindMap[".ifgt"] = DK_IFGT;
5392 DirectiveKindMap[".ifle"] = DK_IFLE;
5393 DirectiveKindMap[".iflt"] = DK_IFLT;
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00005394 DirectiveKindMap[".ifne"] = DK_IFNE;
Eli Bendersky17233942013-01-15 22:59:42 +00005395 DirectiveKindMap[".ifb"] = DK_IFB;
5396 DirectiveKindMap[".ifnb"] = DK_IFNB;
5397 DirectiveKindMap[".ifc"] = DK_IFC;
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00005398 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
Eli Bendersky17233942013-01-15 22:59:42 +00005399 DirectiveKindMap[".ifnc"] = DK_IFNC;
Sid Manning51c35602015-03-18 14:20:54 +00005400 DirectiveKindMap[".ifnes"] = DK_IFNES;
Eli Bendersky17233942013-01-15 22:59:42 +00005401 DirectiveKindMap[".ifdef"] = DK_IFDEF;
5402 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
5403 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
5404 DirectiveKindMap[".elseif"] = DK_ELSEIF;
5405 DirectiveKindMap[".else"] = DK_ELSE;
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00005406 DirectiveKindMap[".end"] = DK_END;
Eli Bendersky17233942013-01-15 22:59:42 +00005407 DirectiveKindMap[".endif"] = DK_ENDIF;
5408 DirectiveKindMap[".skip"] = DK_SKIP;
5409 DirectiveKindMap[".space"] = DK_SPACE;
5410 DirectiveKindMap[".file"] = DK_FILE;
5411 DirectiveKindMap[".line"] = DK_LINE;
5412 DirectiveKindMap[".loc"] = DK_LOC;
5413 DirectiveKindMap[".stabs"] = DK_STABS;
Reid Kleckner2214ed82016-01-29 00:49:42 +00005414 DirectiveKindMap[".cv_file"] = DK_CV_FILE;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00005415 DirectiveKindMap[".cv_func_id"] = DK_CV_FUNC_ID;
Reid Kleckner2214ed82016-01-29 00:49:42 +00005416 DirectiveKindMap[".cv_loc"] = DK_CV_LOC;
5417 DirectiveKindMap[".cv_linetable"] = DK_CV_LINETABLE;
David Majnemer6fcbd7e2016-01-29 19:24:12 +00005418 DirectiveKindMap[".cv_inline_linetable"] = DK_CV_INLINE_LINETABLE;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00005419 DirectiveKindMap[".cv_inline_site_id"] = DK_CV_INLINE_SITE_ID;
David Majnemer408b5e62016-02-05 01:55:49 +00005420 DirectiveKindMap[".cv_def_range"] = DK_CV_DEF_RANGE;
Reid Kleckner06d02d02018-09-07 21:30:52 +00005421 DirectiveKindMap[".cv_string"] = DK_CV_STRING;
Reid Kleckner2214ed82016-01-29 00:49:42 +00005422 DirectiveKindMap[".cv_stringtable"] = DK_CV_STRINGTABLE;
5423 DirectiveKindMap[".cv_filechecksums"] = DK_CV_FILECHECKSUMS;
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00005424 DirectiveKindMap[".cv_filechecksumoffset"] = DK_CV_FILECHECKSUM_OFFSET;
Reid Kleckner9cdd4df2017-10-11 21:24:33 +00005425 DirectiveKindMap[".cv_fpo_data"] = DK_CV_FPO_DATA;
Eli Bendersky17233942013-01-15 22:59:42 +00005426 DirectiveKindMap[".sleb128"] = DK_SLEB128;
5427 DirectiveKindMap[".uleb128"] = DK_ULEB128;
5428 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
5429 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
5430 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
5431 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
5432 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
5433 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
5434 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
5435 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
5436 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
5437 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
5438 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
5439 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
5440 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
5441 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
5442 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
5443 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +00005444 DirectiveKindMap[".cfi_return_column"] = DK_CFI_RETURN_COLUMN;
Eli Bendersky17233942013-01-15 22:59:42 +00005445 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
5446 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
5447 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00005448 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
Luke Cheeseman41a9e532018-12-21 10:45:08 +00005449 DirectiveKindMap[".cfi_b_key_frame"] = DK_CFI_B_KEY_FRAME;
Eli Bendersky17233942013-01-15 22:59:42 +00005450 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
5451 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
5452 DirectiveKindMap[".macro"] = DK_MACRO;
Nico Weber155dccd12014-07-24 17:08:39 +00005453 DirectiveKindMap[".exitm"] = DK_EXITM;
Eli Bendersky17233942013-01-15 22:59:42 +00005454 DirectiveKindMap[".endm"] = DK_ENDM;
5455 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
5456 DirectiveKindMap[".purgem"] = DK_PURGEM;
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00005457 DirectiveKindMap[".err"] = DK_ERR;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00005458 DirectiveKindMap[".error"] = DK_ERROR;
Nico Weber404012b2014-07-24 16:26:06 +00005459 DirectiveKindMap[".warning"] = DK_WARNING;
Michael Zuckerman56704612017-05-01 13:20:12 +00005460 DirectiveKindMap[".altmacro"] = DK_ALTMACRO;
5461 DirectiveKindMap[".noaltmacro"] = DK_NOALTMACRO;
Daniel Sanders9f6ad492015-11-12 13:33:00 +00005462 DirectiveKindMap[".reloc"] = DK_RELOC;
Petr Hosek731bb9c2016-08-23 21:34:53 +00005463 DirectiveKindMap[".dc"] = DK_DC;
5464 DirectiveKindMap[".dc.a"] = DK_DC_A;
5465 DirectiveKindMap[".dc.b"] = DK_DC_B;
5466 DirectiveKindMap[".dc.d"] = DK_DC_D;
5467 DirectiveKindMap[".dc.l"] = DK_DC_L;
5468 DirectiveKindMap[".dc.s"] = DK_DC_S;
5469 DirectiveKindMap[".dc.w"] = DK_DC_W;
5470 DirectiveKindMap[".dc.x"] = DK_DC_X;
Petr Hosek4cb08ce2016-09-23 19:25:15 +00005471 DirectiveKindMap[".dcb"] = DK_DCB;
5472 DirectiveKindMap[".dcb.b"] = DK_DCB_B;
5473 DirectiveKindMap[".dcb.d"] = DK_DCB_D;
5474 DirectiveKindMap[".dcb.l"] = DK_DCB_L;
5475 DirectiveKindMap[".dcb.s"] = DK_DCB_S;
5476 DirectiveKindMap[".dcb.w"] = DK_DCB_W;
5477 DirectiveKindMap[".dcb.x"] = DK_DCB_X;
Petr Hosek85b2f672016-09-23 21:53:36 +00005478 DirectiveKindMap[".ds"] = DK_DS;
5479 DirectiveKindMap[".ds.b"] = DK_DS_B;
5480 DirectiveKindMap[".ds.d"] = DK_DS_D;
5481 DirectiveKindMap[".ds.l"] = DK_DS_L;
5482 DirectiveKindMap[".ds.p"] = DK_DS_P;
5483 DirectiveKindMap[".ds.s"] = DK_DS_S;
5484 DirectiveKindMap[".ds.w"] = DK_DS_W;
5485 DirectiveKindMap[".ds.x"] = DK_DS_X;
Coby Tayree01e53202017-10-02 14:36:31 +00005486 DirectiveKindMap[".print"] = DK_PRINT;
Peter Collingbourne3e227332018-07-17 22:17:18 +00005487 DirectiveKindMap[".addrsig"] = DK_ADDRSIG;
5488 DirectiveKindMap[".addrsig_sym"] = DK_ADDRSIG_SYM;
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00005489}
5490
Jim Grosbach4b905842013-09-20 23:08:21 +00005491MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005492 AsmToken EndToken, StartToken = getTok();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005493
Rafael Espindola34b9c512012-06-03 23:57:14 +00005494 unsigned NestLevel = 0;
Eugene Zelenko33d7b762016-08-23 17:14:32 +00005495 while (true) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005496 // Check whether we have reached the end of the file.
Rafael Espindola34b9c512012-06-03 23:57:14 +00005497 if (getLexer().is(AsmToken::Eof)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00005498 printError(DirectiveLoc, "no matching '.endr' in definition");
Craig Topper353eda42014-04-24 06:44:33 +00005499 return nullptr;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005500 }
5501
Rafael Espindola34b9c512012-06-03 23:57:14 +00005502 if (Lexer.is(AsmToken::Identifier) &&
Nirav Davee24fcd52018-07-18 16:17:03 +00005503 (getTok().getIdentifier() == ".rep" ||
5504 getTok().getIdentifier() == ".rept" ||
Nikolay Haustov95b4fcd2016-03-01 08:18:28 +00005505 getTok().getIdentifier() == ".irp" ||
5506 getTok().getIdentifier() == ".irpc")) {
Rafael Espindola34b9c512012-06-03 23:57:14 +00005507 ++NestLevel;
5508 }
5509
5510 // Otherwise, check whether we have reached the .endr.
Jim Grosbach4b905842013-09-20 23:08:21 +00005511 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
Rafael Espindola34b9c512012-06-03 23:57:14 +00005512 if (NestLevel == 0) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005513 EndToken = getTok();
5514 Lex();
Rafael Espindola34b9c512012-06-03 23:57:14 +00005515 if (Lexer.isNot(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00005516 printError(getTok().getLoc(),
5517 "unexpected token in '.endr' directive");
Craig Topper353eda42014-04-24 06:44:33 +00005518 return nullptr;
Rafael Espindola34b9c512012-06-03 23:57:14 +00005519 }
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005520 break;
5521 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00005522 --NestLevel;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005523 }
5524
Rafael Espindola34b9c512012-06-03 23:57:14 +00005525 // Otherwise, scan till the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005526 eatToEndOfStatement();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005527 }
5528
5529 const char *BodyStart = StartToken.getLoc().getPointer();
5530 const char *BodyEnd = EndToken.getLoc().getPointer();
5531 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
5532
Rafael Espindola34b9c512012-06-03 23:57:14 +00005533 // We Are Anonymous.
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00005534 MacroLikeBodies.emplace_back(StringRef(), Body, MCAsmMacroParameters());
Benjamin Kramer1df3a1f2013-08-04 09:06:29 +00005535 return &MacroLikeBodies.back();
Rafael Espindola34b9c512012-06-03 23:57:14 +00005536}
5537
Jim Grosbach4b905842013-09-20 23:08:21 +00005538void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +00005539 raw_svector_ostream &OS) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005540 OS << ".endr\n";
5541
Rafael Espindola3560ff22014-08-27 20:03:13 +00005542 std::unique_ptr<MemoryBuffer> Instantiation =
5543 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005544
Rafael Espindola34b9c512012-06-03 23:57:14 +00005545 // Create the macro instantiation object and add to the current macro
5546 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00005547 MacroInstantiation *MI = new MacroInstantiation(
5548 DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Rafael Espindola34b9c512012-06-03 23:57:14 +00005549 ActiveMacros.push_back(MI);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005550
Rafael Espindola34b9c512012-06-03 23:57:14 +00005551 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00005552 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00005553 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Rafael Espindola34b9c512012-06-03 23:57:14 +00005554 Lex();
5555}
5556
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00005557/// parseDirectiveRept
5558/// ::= .rep | .rept count
5559bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00005560 const MCExpr *CountExpr;
5561 SMLoc CountLoc = getTok().getLoc();
5562 if (parseExpression(CountExpr))
5563 return true;
5564
Rafael Espindola34b9c512012-06-03 23:57:14 +00005565 int64_t Count;
Nirav Dave6c0665e2018-04-30 19:22:40 +00005566 if (!CountExpr->evaluateAsAbsolute(Count, getStreamer().getAssemblerPtr())) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00005567 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
5568 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00005569
Nirav Davea645433c2016-07-18 15:24:03 +00005570 if (check(Count < 0, CountLoc, "Count is negative") ||
5571 parseToken(AsmToken::EndOfStatement,
5572 "unexpected token in '" + Dir + "' directive"))
5573 return true;
Rafael Espindola34b9c512012-06-03 23:57:14 +00005574
5575 // Lex the rept definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005576 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola34b9c512012-06-03 23:57:14 +00005577 if (!M)
5578 return true;
5579
5580 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5581 // to hold the macro body with substitutions.
5582 SmallString<256> Buf;
Rafael Espindola34b9c512012-06-03 23:57:14 +00005583 raw_svector_ostream OS(Buf);
5584 while (Count--) {
Toma Tabacu217116e2015-04-27 10:50:29 +00005585 // Note that the AtPseudoVariable is disabled for instantiations of .rep(t).
5586 if (expandMacro(OS, M->Body, None, None, false, getTok().getLoc()))
Rafael Espindola34b9c512012-06-03 23:57:14 +00005587 return true;
5588 }
Jim Grosbach4b905842013-09-20 23:08:21 +00005589 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005590
5591 return false;
5592}
5593
Jim Grosbach4b905842013-09-20 23:08:21 +00005594/// parseDirectiveIrp
Rafael Espindola768b41c2012-06-15 14:02:34 +00005595/// ::= .irp symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00005596bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00005597 MCAsmMacroParameter Parameter;
Eli Bendersky38274122013-01-14 23:22:36 +00005598 MCAsmMacroArguments A;
Nirav Davea645433c2016-07-18 15:24:03 +00005599 if (check(parseIdentifier(Parameter.Name),
5600 "expected identifier in '.irp' directive") ||
5601 parseToken(AsmToken::Comma, "expected comma in '.irp' directive") ||
5602 parseMacroArguments(nullptr, A) ||
5603 parseToken(AsmToken::EndOfStatement, "expected End of Statement"))
Rafael Espindola768b41c2012-06-15 14:02:34 +00005604 return true;
5605
Rafael Espindola768b41c2012-06-15 14:02:34 +00005606 // Lex the irp definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005607 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola768b41c2012-06-15 14:02:34 +00005608 if (!M)
5609 return true;
5610
5611 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5612 // to hold the macro body with substitutions.
5613 SmallString<256> Buf;
5614 raw_svector_ostream OS(Buf);
5615
Craig Topper84008482015-10-10 05:38:14 +00005616 for (const MCAsmMacroArgument &Arg : A) {
Toma Tabacu217116e2015-04-27 10:50:29 +00005617 // Note that the AtPseudoVariable is enabled for instantiations of .irp.
5618 // This is undocumented, but GAS seems to support it.
Craig Topper84008482015-10-10 05:38:14 +00005619 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindola768b41c2012-06-15 14:02:34 +00005620 return true;
5621 }
5622
Jim Grosbach4b905842013-09-20 23:08:21 +00005623 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola768b41c2012-06-15 14:02:34 +00005624
5625 return false;
5626}
5627
Jim Grosbach4b905842013-09-20 23:08:21 +00005628/// parseDirectiveIrpc
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005629/// ::= .irpc symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00005630bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00005631 MCAsmMacroParameter Parameter;
Eli Bendersky38274122013-01-14 23:22:36 +00005632 MCAsmMacroArguments A;
Nirav Davea645433c2016-07-18 15:24:03 +00005633
5634 if (check(parseIdentifier(Parameter.Name),
5635 "expected identifier in '.irpc' directive") ||
5636 parseToken(AsmToken::Comma, "expected comma in '.irpc' directive") ||
5637 parseMacroArguments(nullptr, A))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005638 return true;
5639
5640 if (A.size() != 1 || A.front().size() != 1)
5641 return TokError("unexpected token in '.irpc' directive");
5642
5643 // Eat the end of statement.
Nirav Davea645433c2016-07-18 15:24:03 +00005644 if (parseToken(AsmToken::EndOfStatement, "expected end of statement"))
5645 return true;
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005646
5647 // Lex the irpc definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005648 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005649 if (!M)
5650 return true;
5651
5652 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5653 // to hold the macro body with substitutions.
5654 SmallString<256> Buf;
5655 raw_svector_ostream OS(Buf);
5656
5657 StringRef Values = A.front().front().getString();
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00005658 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
Eli Benderskya7b905e2013-01-14 19:00:26 +00005659 MCAsmMacroArgument Arg;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00005660 Arg.emplace_back(AsmToken::Identifier, Values.slice(I, I + 1));
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005661
Toma Tabacu217116e2015-04-27 10:50:29 +00005662 // Note that the AtPseudoVariable is enabled for instantiations of .irpc.
5663 // This is undocumented, but GAS seems to support it.
5664 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005665 return true;
5666 }
5667
Jim Grosbach4b905842013-09-20 23:08:21 +00005668 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005669
5670 return false;
5671}
5672
Jim Grosbach4b905842013-09-20 23:08:21 +00005673bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
Rafael Espindola34b9c512012-06-03 23:57:14 +00005674 if (ActiveMacros.empty())
Preston Gurdeb3ebf12012-09-19 20:23:43 +00005675 return TokError("unmatched '.endr' directive");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005676
5677 // The only .repl that should get here are the ones created by
Jim Grosbach4b905842013-09-20 23:08:21 +00005678 // instantiateMacroLikeBody.
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005679 assert(getLexer().is(AsmToken::EndOfStatement));
5680
Jim Grosbach4b905842013-09-20 23:08:21 +00005681 handleMacroExit();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005682 return false;
5683}
Rafael Espindola12d73d12010-09-11 16:45:15 +00005684
Jim Grosbach4b905842013-09-20 23:08:21 +00005685bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
Benjamin Kramer1a136112013-02-15 20:37:21 +00005686 size_t Len) {
Eli Friedman0f4871d2012-10-22 23:58:19 +00005687 const MCExpr *Value;
5688 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005689 if (parseExpression(Value))
Eli Friedman0f4871d2012-10-22 23:58:19 +00005690 return true;
5691 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5692 if (!MCE)
5693 return Error(ExprLoc, "unexpected expression in _emit");
5694 uint64_t IntValue = MCE->getValue();
Craig Topper55b1f292015-10-10 20:17:07 +00005695 if (!isUInt<8>(IntValue) && !isInt<8>(IntValue))
Eli Friedman0f4871d2012-10-22 23:58:19 +00005696 return Error(ExprLoc, "literal value out of range for directive");
5697
Craig Topper7d5b2312015-10-10 05:25:02 +00005698 Info.AsmRewrites->emplace_back(AOK_Emit, IDLoc, Len);
Chad Rosierc7f552c2013-02-12 21:33:51 +00005699 return false;
5700}
5701
Jim Grosbach4b905842013-09-20 23:08:21 +00005702bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
Chad Rosierc7f552c2013-02-12 21:33:51 +00005703 const MCExpr *Value;
5704 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005705 if (parseExpression(Value))
Chad Rosierc7f552c2013-02-12 21:33:51 +00005706 return true;
5707 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5708 if (!MCE)
5709 return Error(ExprLoc, "unexpected expression in align");
5710 uint64_t IntValue = MCE->getValue();
5711 if (!isPowerOf2_64(IntValue))
5712 return Error(ExprLoc, "literal value not a power of two greater then zero");
5713
Craig Topper7d5b2312015-10-10 05:25:02 +00005714 Info.AsmRewrites->emplace_back(AOK_Align, IDLoc, 5, Log2_64(IntValue));
Eli Friedman0f4871d2012-10-22 23:58:19 +00005715 return false;
5716}
5717
Coby Tayree01e53202017-10-02 14:36:31 +00005718bool AsmParser::parseDirectivePrint(SMLoc DirectiveLoc) {
5719 const AsmToken StrTok = getTok();
5720 Lex();
5721 if (StrTok.isNot(AsmToken::String) || StrTok.getString().front() != '"')
5722 return Error(DirectiveLoc, "expected double quoted string after .print");
5723 if (parseToken(AsmToken::EndOfStatement, "expected end of statement"))
5724 return true;
5725 llvm::outs() << StrTok.getStringContents() << '\n';
5726 return false;
5727}
5728
Peter Collingbourne3e227332018-07-17 22:17:18 +00005729bool AsmParser::parseDirectiveAddrsig() {
5730 getStreamer().EmitAddrsig();
5731 return false;
5732}
5733
5734bool AsmParser::parseDirectiveAddrsigSym() {
5735 StringRef Name;
5736 if (check(parseIdentifier(Name),
5737 "expected identifier in '.addrsig_sym' directive"))
5738 return true;
5739 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
5740 getStreamer().EmitAddrsigSym(Sym);
5741 return false;
5742}
5743
Chad Rosierf43fcf52013-02-13 21:27:17 +00005744// We are comparing pointers, but the pointers are relative to a single string.
5745// Thus, this should always be deterministic.
Benjamin Kramer8817cca2013-09-22 14:09:50 +00005746static int rewritesSort(const AsmRewrite *AsmRewriteA,
5747 const AsmRewrite *AsmRewriteB) {
Chad Rosiereb5c1682013-02-13 18:38:58 +00005748 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
5749 return -1;
5750 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
5751 return 1;
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005752
Chad Rosierfce4fab2013-04-08 17:43:47 +00005753 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
5754 // rewrite to the same location. Make sure the SizeDirective rewrite is
5755 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
5756 // ensures the sort algorithm is stable.
Jim Grosbach4b905842013-09-20 23:08:21 +00005757 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
5758 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005759 return -1;
Chad Rosierfce4fab2013-04-08 17:43:47 +00005760
Jim Grosbach4b905842013-09-20 23:08:21 +00005761 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
5762 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005763 return 1;
Jim Grosbach4b905842013-09-20 23:08:21 +00005764 llvm_unreachable("Unstable rewrite sort.");
Chad Rosierb2144ce2013-02-13 01:03:13 +00005765}
5766
Jim Grosbach4b905842013-09-20 23:08:21 +00005767bool AsmParser::parseMSInlineAsm(
5768 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00005769 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool>> &OpDecls,
Jim Grosbach4b905842013-09-20 23:08:21 +00005770 SmallVectorImpl<std::string> &Constraints,
5771 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
5772 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
Chad Rosier37e755c2012-10-23 17:43:43 +00005773 SmallVector<void *, 4> InputDecls;
5774 SmallVector<void *, 4> OutputDecls;
Chad Rosiera4bc9432013-01-10 22:10:27 +00005775 SmallVector<bool, 4> InputDeclsAddressOf;
5776 SmallVector<bool, 4> OutputDeclsAddressOf;
Chad Rosier8bce6642012-10-18 15:49:34 +00005777 SmallVector<std::string, 4> InputConstraints;
5778 SmallVector<std::string, 4> OutputConstraints;
Benjamin Kramer1a136112013-02-15 20:37:21 +00005779 SmallVector<unsigned, 4> ClobberRegs;
Chad Rosier8bce6642012-10-18 15:49:34 +00005780
Benjamin Kramer1a136112013-02-15 20:37:21 +00005781 SmallVector<AsmRewrite, 4> AsmStrRewrites;
Chad Rosier8bce6642012-10-18 15:49:34 +00005782
5783 // Prime the lexer.
5784 Lex();
5785
5786 // While we have input, parse each statement.
5787 unsigned InputIdx = 0;
5788 unsigned OutputIdx = 0;
5789 while (getLexer().isNot(AsmToken::Eof)) {
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00005790 // Parse curly braces marking block start/end
5791 if (parseCurlyBlockScope(AsmStrRewrites))
5792 continue;
5793
Eli Friedman0f4871d2012-10-22 23:58:19 +00005794 ParseStatementInfo Info(&AsmStrRewrites);
Nirav Dave2364748a2016-09-16 18:30:20 +00005795 bool StatementErr = parseStatement(Info, &SI);
Nirav Dave9fa8af22016-09-13 13:55:06 +00005796
Nirav Dave2364748a2016-09-16 18:30:20 +00005797 if (StatementErr || Info.ParseError) {
5798 // Emit pending errors if any exist.
5799 printPendingErrors();
Nico Webere204c482016-09-13 18:17:00 +00005800 return true;
Nirav Dave2364748a2016-09-16 18:30:20 +00005801 }
5802
5803 // No pending error should exist here.
5804 assert(!hasPendingError() && "unexpected error from parseStatement");
Chad Rosier149e8e02012-12-12 22:45:52 +00005805
Benjamin Kramer1a136112013-02-15 20:37:21 +00005806 if (Info.Opcode == ~0U)
5807 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00005808
Benjamin Kramer1a136112013-02-15 20:37:21 +00005809 const MCInstrDesc &Desc = MII->get(Info.Opcode);
Chad Rosier8bce6642012-10-18 15:49:34 +00005810
Benjamin Kramer1a136112013-02-15 20:37:21 +00005811 // Build the list of clobbers, outputs and inputs.
5812 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
David Blaikie960ea3f2014-06-08 16:18:35 +00005813 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005814
Benjamin Kramer1a136112013-02-15 20:37:21 +00005815 // Immediate.
David Blaikie960ea3f2014-06-08 16:18:35 +00005816 if (Operand.isImm())
Benjamin Kramer1a136112013-02-15 20:37:21 +00005817 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00005818
Benjamin Kramer1a136112013-02-15 20:37:21 +00005819 // Register operand.
Nico Weber42f79db2014-07-17 20:24:55 +00005820 if (Operand.isReg() && !Operand.needAddressOf() &&
5821 !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
Benjamin Kramer1a136112013-02-15 20:37:21 +00005822 unsigned NumDefs = Desc.getNumDefs();
5823 // Clobber.
David Blaikie960ea3f2014-06-08 16:18:35 +00005824 if (NumDefs && Operand.getMCOperandNum() < NumDefs)
5825 ClobberRegs.push_back(Operand.getReg());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005826 continue;
5827 }
5828
5829 // Expr/Input or Output.
David Blaikie960ea3f2014-06-08 16:18:35 +00005830 StringRef SymName = Operand.getSymName();
Chad Rosiere81309b2013-04-09 17:53:49 +00005831 if (SymName.empty())
5832 continue;
5833
David Blaikie960ea3f2014-06-08 16:18:35 +00005834 void *OpDecl = Operand.getOpDecl();
Benjamin Kramer1a136112013-02-15 20:37:21 +00005835 if (!OpDecl)
5836 continue;
5837
5838 bool isOutput = (i == 1) && Desc.mayStore();
Chad Rosiere81309b2013-04-09 17:53:49 +00005839 SMLoc Start = SMLoc::getFromPointer(SymName.data());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005840 if (isOutput) {
5841 ++InputIdx;
5842 OutputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00005843 OutputDeclsAddressOf.push_back(Operand.needAddressOf());
Yaron Keren075759a2015-03-30 15:42:36 +00005844 OutputConstraints.push_back(("=" + Operand.getConstraint()).str());
Craig Topper7d5b2312015-10-10 05:25:02 +00005845 AsmStrRewrites.emplace_back(AOK_Output, Start, SymName.size());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005846 } else {
5847 InputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00005848 InputDeclsAddressOf.push_back(Operand.needAddressOf());
5849 InputConstraints.push_back(Operand.getConstraint().str());
Craig Topper7d5b2312015-10-10 05:25:02 +00005850 AsmStrRewrites.emplace_back(AOK_Input, Start, SymName.size());
Chad Rosier8bce6642012-10-18 15:49:34 +00005851 }
Chad Rosier8bce6642012-10-18 15:49:34 +00005852 }
Reid Kleckneree088972013-12-10 18:27:32 +00005853
5854 // Consider implicit defs to be clobbers. Think of cpuid and push.
Craig Toppere5e035a32015-12-05 07:13:35 +00005855 ArrayRef<MCPhysReg> ImpDefs(Desc.getImplicitDefs(),
5856 Desc.getNumImplicitDefs());
David Majnemer8114c1a2014-06-23 02:17:16 +00005857 ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end());
Chad Rosier8bce6642012-10-18 15:49:34 +00005858 }
5859
5860 // Set the number of Outputs and Inputs.
Chad Rosierf641baa2012-10-18 19:39:30 +00005861 NumOutputs = OutputDecls.size();
5862 NumInputs = InputDecls.size();
Chad Rosier8bce6642012-10-18 15:49:34 +00005863
5864 // Set the unique clobbers.
Benjamin Kramer1a136112013-02-15 20:37:21 +00005865 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
5866 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
5867 ClobberRegs.end());
5868 Clobbers.assign(ClobberRegs.size(), std::string());
5869 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
5870 raw_string_ostream OS(Clobbers[I]);
5871 IP->printRegName(OS, ClobberRegs[I]);
5872 }
Chad Rosier8bce6642012-10-18 15:49:34 +00005873
5874 // Merge the various outputs and inputs. Output are expected first.
5875 if (NumOutputs || NumInputs) {
5876 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierf641baa2012-10-18 19:39:30 +00005877 OpDecls.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00005878 Constraints.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00005879 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00005880 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00005881 Constraints[i] = OutputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005882 }
5883 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00005884 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00005885 Constraints[j] = InputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005886 }
5887 }
5888
5889 // Build the IR assembly string.
Alp Tokere69170a2014-06-26 22:52:05 +00005890 std::string AsmStringIR;
5891 raw_string_ostream OS(AsmStringIR);
Alp Tokera55b95b2014-07-06 10:33:31 +00005892 StringRef ASMString =
5893 SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
5894 const char *AsmStart = ASMString.begin();
5895 const char *AsmEnd = ASMString.end();
Jim Grosbach4b905842013-09-20 23:08:21 +00005896 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
David Majnemer8114c1a2014-06-23 02:17:16 +00005897 for (const AsmRewrite &AR : AsmStrRewrites) {
5898 AsmRewriteKind Kind = AR.Kind;
Chad Rosierff10ed12013-04-12 16:26:42 +00005899
David Majnemer8114c1a2014-06-23 02:17:16 +00005900 const char *Loc = AR.Loc.getPointer();
Chad Rosier17d37992013-03-19 21:12:14 +00005901 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
Chad Rosier0f48c552012-10-19 20:57:14 +00005902
Chad Rosier120eefd2013-03-19 17:32:17 +00005903 // Emit everything up to the immediate/expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00005904 if (unsigned Len = Loc - AsmStart)
Chad Rosier17d37992013-03-19 21:12:14 +00005905 OS << StringRef(AsmStart, Len);
Chad Rosier0f48c552012-10-19 20:57:14 +00005906
Chad Rosier37e755c2012-10-23 17:43:43 +00005907 // Skip the original expression.
5908 if (Kind == AOK_Skip) {
David Majnemer8114c1a2014-06-23 02:17:16 +00005909 AsmStart = Loc + AR.Len;
Chad Rosier37e755c2012-10-23 17:43:43 +00005910 continue;
5911 }
5912
Chad Rosierff10ed12013-04-12 16:26:42 +00005913 unsigned AdditionalSkip = 0;
Chad Rosier8bce6642012-10-18 15:49:34 +00005914 // Rewrite expressions in $N notation.
Chad Rosier0f48c552012-10-19 20:57:14 +00005915 switch (Kind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00005916 default:
5917 break;
Coby Tayreed8912892017-08-24 08:46:25 +00005918 case AOK_IntelExpr:
5919 assert(AR.IntelExp.isValid() && "cannot write invalid intel expression");
5920 if (AR.IntelExp.NeedBracs)
5921 OS << "[";
5922 if (AR.IntelExp.hasBaseReg())
5923 OS << AR.IntelExp.BaseReg;
5924 if (AR.IntelExp.hasIndexReg())
5925 OS << (AR.IntelExp.hasBaseReg() ? " + " : "")
5926 << AR.IntelExp.IndexReg;
5927 if (AR.IntelExp.Scale > 1)
5928 OS << " * $$" << AR.IntelExp.Scale;
5929 if (AR.IntelExp.Imm || !AR.IntelExp.hasRegs())
5930 OS << (AR.IntelExp.hasRegs() ? " + $$" : "$$") << AR.IntelExp.Imm;
5931 if (AR.IntelExp.NeedBracs)
5932 OS << "]";
Chad Rosier8bce6642012-10-18 15:49:34 +00005933 break;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005934 case AOK_Label:
Matt Arsenault4e273432014-12-04 00:06:57 +00005935 OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005936 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005937 case AOK_Input:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005938 OS << '$' << InputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00005939 break;
5940 case AOK_Output:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005941 OS << '$' << OutputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00005942 break;
Chad Rosier0f48c552012-10-19 20:57:14 +00005943 case AOK_SizeDirective:
David Majnemer8114c1a2014-06-23 02:17:16 +00005944 switch (AR.Val) {
Chad Rosier0f48c552012-10-19 20:57:14 +00005945 default: break;
5946 case 8: OS << "byte ptr "; break;
5947 case 16: OS << "word ptr "; break;
5948 case 32: OS << "dword ptr "; break;
5949 case 64: OS << "qword ptr "; break;
5950 case 80: OS << "xword ptr "; break;
5951 case 128: OS << "xmmword ptr "; break;
5952 case 256: OS << "ymmword ptr "; break;
5953 }
Eli Friedman0f4871d2012-10-22 23:58:19 +00005954 break;
5955 case AOK_Emit:
5956 OS << ".byte";
5957 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00005958 case AOK_Align: {
Reid Klecknerfb1c1c72015-10-27 17:32:48 +00005959 // MS alignment directives are measured in bytes. If the native assembler
5960 // measures alignment in bytes, we can pass it straight through.
5961 OS << ".align";
5962 if (getContext().getAsmInfo()->getAlignmentIsInBytes())
5963 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00005964
Reid Klecknerfb1c1c72015-10-27 17:32:48 +00005965 // Alignment is in log2 form, so print that instead and skip the original
5966 // immediate.
5967 unsigned Val = AR.Val;
5968 OS << ' ' << Val;
Benjamin Kramer1a136112013-02-15 20:37:21 +00005969 assert(Val < 10 && "Expected alignment less then 2^10.");
Chad Rosierc7f552c2013-02-12 21:33:51 +00005970 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
5971 break;
5972 }
Michael Zuckerman02ecd432015-12-13 17:07:23 +00005973 case AOK_EVEN:
5974 OS << ".even";
5975 break;
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00005976 case AOK_EndOfStatement:
5977 OS << "\n\t";
5978 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005979 }
Chad Rosier0f48c552012-10-19 20:57:14 +00005980
Chad Rosier8bce6642012-10-18 15:49:34 +00005981 // Skip the original expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00005982 AsmStart = Loc + AR.Len + AdditionalSkip;
Chad Rosier8bce6642012-10-18 15:49:34 +00005983 }
5984
5985 // Emit the remainder of the asm string.
Chad Rosier17d37992013-03-19 21:12:14 +00005986 if (AsmStart != AsmEnd)
5987 OS << StringRef(AsmStart, AsmEnd - AsmStart);
Chad Rosier8bce6642012-10-18 15:49:34 +00005988
5989 AsmString = OS.str();
5990 return false;
5991}
5992
Pete Cooper80d21cb2015-06-22 19:35:57 +00005993namespace llvm {
5994namespace MCParserUtils {
5995
5996/// Returns whether the given symbol is used anywhere in the given expression,
5997/// or subexpressions.
5998static bool isSymbolUsedInExpression(const MCSymbol *Sym, const MCExpr *Value) {
5999 switch (Value->getKind()) {
6000 case MCExpr::Binary: {
6001 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
6002 return isSymbolUsedInExpression(Sym, BE->getLHS()) ||
6003 isSymbolUsedInExpression(Sym, BE->getRHS());
6004 }
6005 case MCExpr::Target:
6006 case MCExpr::Constant:
6007 return false;
6008 case MCExpr::SymbolRef: {
6009 const MCSymbol &S =
6010 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
6011 if (S.isVariable())
6012 return isSymbolUsedInExpression(Sym, S.getVariableValue());
6013 return &S == Sym;
6014 }
6015 case MCExpr::Unary:
6016 return isSymbolUsedInExpression(
6017 Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
6018 }
6019
6020 llvm_unreachable("Unknown expr kind!");
6021}
6022
6023bool parseAssignmentExpression(StringRef Name, bool allow_redef,
6024 MCAsmParser &Parser, MCSymbol *&Sym,
Nirav Dave7fd992a2018-08-16 16:31:14 +00006025 const MCExpr *&Value) {
Pete Cooper80d21cb2015-06-22 19:35:57 +00006026
6027 // FIXME: Use better location, we should use proper tokens.
Nirav Davefd910412016-06-17 16:06:17 +00006028 SMLoc EqualLoc = Parser.getTok().getLoc();
Nirav Dave7fd992a2018-08-16 16:31:14 +00006029 if (Parser.parseExpression(Value))
6030 return Parser.TokError("missing expression");
Pete Cooper80d21cb2015-06-22 19:35:57 +00006031
6032 // Note: we don't count b as used in "a = b". This is to allow
6033 // a = b
6034 // b = c
6035
Nirav Dave1a9044b2016-10-24 14:35:29 +00006036 if (Parser.parseToken(AsmToken::EndOfStatement))
6037 return true;
Pete Cooper80d21cb2015-06-22 19:35:57 +00006038
6039 // Validate that the LHS is allowed to be a variable (either it has not been
6040 // used as a symbol, or it is an absolute symbol).
6041 Sym = Parser.getContext().lookupSymbol(Name);
6042 if (Sym) {
6043 // Diagnose assignment to a label.
6044 //
6045 // FIXME: Diagnostics. Note the location of the definition as a label.
6046 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
6047 if (isSymbolUsedInExpression(Sym, Value))
6048 return Parser.Error(EqualLoc, "Recursive use of '" + Name + "'");
Vedant Kumar86dbd922015-08-31 17:44:53 +00006049 else if (Sym->isUndefined(/*SetUsed*/ false) && !Sym->isUsed() &&
6050 !Sym->isVariable())
Pete Cooper80d21cb2015-06-22 19:35:57 +00006051 ; // Allow redefinitions of undefined symbols only used in directives.
6052 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
6053 ; // Allow redefinitions of variables that haven't yet been used.
6054 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
6055 return Parser.Error(EqualLoc, "redefinition of '" + Name + "'");
6056 else if (!Sym->isVariable())
6057 return Parser.Error(EqualLoc, "invalid assignment to '" + Name + "'");
6058 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
6059 return Parser.Error(EqualLoc,
6060 "invalid reassignment of non-absolute variable '" +
6061 Name + "'");
Pete Cooper80d21cb2015-06-22 19:35:57 +00006062 } else if (Name == ".") {
Oliver Stannard268f42f2016-12-14 10:43:58 +00006063 Parser.getStreamer().emitValueToOffset(Value, 0, EqualLoc);
Pete Cooper80d21cb2015-06-22 19:35:57 +00006064 return false;
6065 } else
6066 Sym = Parser.getContext().getOrCreateSymbol(Name);
6067
6068 Sym->setRedefinable(allow_redef);
6069
6070 return false;
6071}
6072
Eugene Zelenko33d7b762016-08-23 17:14:32 +00006073} // end namespace MCParserUtils
6074} // end namespace llvm
Pete Cooper80d21cb2015-06-22 19:35:57 +00006075
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006076/// Create an MCAsmParser instance.
Jim Grosbach4b905842013-09-20 23:08:21 +00006077MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
Sanne Wouda29338752017-02-08 14:48:05 +00006078 MCStreamer &Out, const MCAsmInfo &MAI,
6079 unsigned CB) {
6080 return new AsmParser(SM, C, Out, MAI, CB);
Daniel Dunbar01e36072010-07-17 02:26:10 +00006081}