blob: faa29f3f63c9f25b4fa541dd6ddf508713cc519d [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"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000025#include "llvm/MC/MCAsmInfo.h"
Reid Klecknera5b1eef2016-08-26 17:58:37 +000026#include "llvm/MC/MCCodeView.h"
Daniel Dunbarca29e4d2009-06-23 22:01:43 +000027#include "llvm/MC/MCContext.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000028#include "llvm/MC/MCDirectives.h"
Evan Cheng11424442011-07-26 00:24:13 +000029#include "llvm/MC/MCDwarf.h"
Daniel Dunbar115e4d62009-08-31 08:06:59 +000030#include "llvm/MC/MCExpr.h"
Chad Rosier8bce6642012-10-18 15:49:34 +000031#include "llvm/MC/MCInstPrinter.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000032#include "llvm/MC/MCInstrDesc.h"
Chad Rosier8bce6642012-10-18 15:49:34 +000033#include "llvm/MC/MCInstrInfo.h"
Rafael Espindolae28610d2013-12-09 20:26:40 +000034#include "llvm/MC/MCObjectFileInfo.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000035#include "llvm/MC/MCParser/AsmCond.h"
36#include "llvm/MC/MCParser/AsmLexer.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000037#include "llvm/MC/MCParser/MCAsmLexer.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000038#include "llvm/MC/MCParser/MCAsmParser.h"
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +000039#include "llvm/MC/MCParser/MCAsmParserExtension.h"
Pete Cooper80d21cb2015-06-22 19:35:57 +000040#include "llvm/MC/MCParser/MCAsmParserUtils.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000041#include "llvm/MC/MCParser/MCParsedAsmOperand.h"
Benjamin Kramerb3e8a6d2016-01-27 10:01:28 +000042#include "llvm/MC/MCParser/MCTargetAsmParser.h"
Evan Cheng76792992011-07-20 05:58:47 +000043#include "llvm/MC/MCRegisterInfo.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000044#include "llvm/MC/MCSection.h"
Daniel Dunbarca29e4d2009-06-23 22:01:43 +000045#include "llvm/MC/MCStreamer.h"
Daniel Dunbarae7ac012009-06-29 23:43:14 +000046#include "llvm/MC/MCSymbol.h"
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +000047#include "llvm/MC/MCTargetOptions.h"
Daniel Sanders9f6ad492015-11-12 13:33:00 +000048#include "llvm/MC/MCValue.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000049#include "llvm/Support/Casting.h"
Davide Italiano7c9fc732016-07-27 05:51:56 +000050#include "llvm/Support/CommandLine.h"
Benjamin Kramer4efe5062012-01-28 15:28:41 +000051#include "llvm/Support/ErrorHandling.h"
Paul Robinson29f5f982018-01-09 23:31:48 +000052#include "llvm/Support/MD5.h"
Jim Grosbach76346c32011-06-29 16:05:14 +000053#include "llvm/Support/MathExtras.h"
Kevin Enderbye233dda2010-06-28 21:45:58 +000054#include "llvm/Support/MemoryBuffer.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000055#include "llvm/Support/SMLoc.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000056#include "llvm/Support/SourceMgr.h"
Chris Lattner36e02122009-06-21 20:54:55 +000057#include "llvm/Support/raw_ostream.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000058#include <algorithm>
59#include <cassert>
Nick Lewycky0de20af2010-12-19 20:43:38 +000060#include <cctype>
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +000061#include <climits>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000062#include <cstddef>
63#include <cstdint>
Benjamin Kramerd59664f2014-04-29 23:26:49 +000064#include <deque>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000065#include <memory>
Davide Italiano7c9fc732016-07-27 05:51:56 +000066#include <sstream>
Chad Rosier8bce6642012-10-18 15:49:34 +000067#include <string>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000068#include <tuple>
69#include <utility>
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000070#include <vector>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000071
Chris Lattnerb0133452009-06-21 20:16:42 +000072using namespace llvm;
73
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +000074MCAsmParserSemaCallback::~MCAsmParserSemaCallback() = default;
Nick Lewyckyac612272012-10-19 07:00:09 +000075
Davide Italiano7c9fc732016-07-27 05:51:56 +000076static cl::opt<unsigned> AsmMacroMaxNestingDepth(
77 "asm-macro-max-nesting-depth", cl::init(20), cl::Hidden,
78 cl::desc("The maximum nesting depth allowed for assembly macros."));
79
Daniel Dunbar86033402010-07-12 17:54:38 +000080namespace {
Eugene Zelenko33d7b762016-08-23 17:14:32 +000081
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000082/// Helper types for tracking macro definitions.
Eli Benderskya313ae62013-01-16 18:56:50 +000083typedef std::vector<AsmToken> MCAsmMacroArgument;
84typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +000085
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000086/// Helper class for storing information about an active macro
Daniel Dunbar43235712010-07-18 18:54:11 +000087/// instantiation.
88struct MacroInstantiation {
Daniel Dunbar43235712010-07-18 18:54:11 +000089 /// The location of the instantiation.
90 SMLoc InstantiationLoc;
91
Daniel Dunbar40f1d852012-12-01 01:38:48 +000092 /// The buffer where parsing should resume upon instantiation completion.
93 int ExitBuffer;
94
Daniel Dunbar43235712010-07-18 18:54:11 +000095 /// The location where parsing should resume upon instantiation completion.
96 SMLoc ExitLoc;
97
Nico Weber155dccd12014-07-24 17:08:39 +000098 /// The depth of TheCondStack at the start of the instantiation.
99 size_t CondStackDepth;
100
Daniel Dunbar43235712010-07-18 18:54:11 +0000101public:
Rafael Espindola9eef18c2014-08-27 19:49:03 +0000102 MacroInstantiation(SMLoc IL, int EB, SMLoc EL, size_t CondStackDepth);
Daniel Dunbar43235712010-07-18 18:54:11 +0000103};
104
Eli Friedman0f4871d2012-10-22 23:58:19 +0000105struct ParseStatementInfo {
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000106 /// The parsed operands from the last parsed statement.
David Blaikie960ea3f2014-06-08 16:18:35 +0000107 SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> ParsedOperands;
Eli Friedman0f4871d2012-10-22 23:58:19 +0000108
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000109 /// The opcode from the last parsed instruction.
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000110 unsigned Opcode = ~0U;
Eli Friedman0f4871d2012-10-22 23:58:19 +0000111
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000112 /// Was there an error parsing the inline assembly?
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000113 bool ParseError = false;
Chad Rosier149e8e02012-12-12 22:45:52 +0000114
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000115 SmallVectorImpl<AsmRewrite> *AsmRewrites = nullptr;
Eli Friedman0f4871d2012-10-22 23:58:19 +0000116
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +0000117 ParseStatementInfo() = delete;
Eli Friedman0f4871d2012-10-22 23:58:19 +0000118 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000119 : AsmRewrites(rewrites) {}
Eli Friedman0f4871d2012-10-22 23:58:19 +0000120};
121
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000122/// The concrete assembly parser instance.
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000123class AsmParser : public MCAsmParser {
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000124private:
125 AsmLexer Lexer;
126 MCContext &Ctx;
127 MCStreamer &Out;
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000128 const MCAsmInfo &MAI;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000129 SourceMgr &SrcMgr;
Benjamin Kramer47f5e302011-10-16 10:48:29 +0000130 SourceMgr::DiagHandlerTy SavedDiagHandler;
131 void *SavedDiagContext;
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000132 std::unique_ptr<MCAsmParserExtension> PlatformParser;
Rafael Espindola82065cb2011-04-11 21:49:50 +0000133
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000134 /// This is the current buffer index we're lexing from as managed by the
135 /// SourceMgr object.
Alp Tokera55b95b2014-07-06 10:33:31 +0000136 unsigned CurBuffer;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000137
138 AsmCond TheCondState;
139 std::vector<AsmCond> TheCondStack;
140
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000141 /// maps directive names to handler methods in parser
Eli Bendersky17233942013-01-15 22:59:42 +0000142 /// extensions. Extensions register themselves in this map by calling
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000143 /// addDirectiveHandler.
Eli Bendersky17233942013-01-15 22:59:42 +0000144 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
Daniel Dunbar828984f2010-07-18 18:38:02 +0000145
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000146 /// Stack of active macro instantiations.
Daniel Dunbar43235712010-07-18 18:54:11 +0000147 std::vector<MacroInstantiation*> ActiveMacros;
148
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000149 /// List of bodies of anonymous macros.
Benjamin Kramer1df3a1f2013-08-04 09:06:29 +0000150 std::deque<MCAsmMacro> MacroLikeBodies;
151
Daniel Dunbar828984f2010-07-18 18:38:02 +0000152 /// Boolean tracking whether macro substitution is enabled.
Eli Benderskyc2f6f922013-01-14 18:08:41 +0000153 unsigned MacrosEnabledFlag : 1;
Daniel Dunbar828984f2010-07-18 18:38:02 +0000154
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000155 /// Keeps track of how many .macro's have been instantiated.
Toma Tabacu217116e2015-04-27 10:50:29 +0000156 unsigned NumOfMacroInstantiations;
157
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000158 /// The values from the last parsed cpp hash file line comment if any.
Tim Northoverc0bef992016-04-13 19:46:54 +0000159 struct CppHashInfoTy {
160 StringRef Filename;
Andrew Kaylorca196472016-04-21 20:09:35 +0000161 int64_t LineNumber = 0;
Tim Northoverc0bef992016-04-13 19:46:54 +0000162 SMLoc Loc;
Andrew Kaylorca196472016-04-21 20:09:35 +0000163 unsigned Buf = 0;
Tim Northoverc0bef992016-04-13 19:46:54 +0000164 };
165 CppHashInfoTy CppHashInfo;
166
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000167 /// List of forward directional labels for diagnosis at the end.
Tim Northoverc0bef992016-04-13 19:46:54 +0000168 SmallVector<std::tuple<SMLoc, CppHashInfoTy, MCSymbol *>, 4> DirLabels;
169
Devang Patela173ee52012-01-31 18:14:05 +0000170 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000171 unsigned AssemblerDialect = ~0U;
Devang Patela173ee52012-01-31 18:14:05 +0000172
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000173 /// is Darwin compatibility enabled?
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000174 bool IsDarwin = false;
Preston Gurd05500642012-09-19 20:36:12 +0000175
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000176 /// Are we parsing ms-style inline assembly?
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000177 bool ParsingInlineAsm = false;
Chad Rosier49963552012-10-13 00:26:04 +0000178
Paul Robinsoncc7344a2018-06-14 13:38:20 +0000179 /// Did we already inform the user about inconsistent MD5 usage?
180 bool ReportedInconsistentMD5 = false;
181
Craig Topperc81aff72018-09-25 20:55:55 +0000182 // Is alt macro mode enabled.
183 bool AltMacroMode = false;
184
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000185public:
Jim Grosbach345768c2011-08-16 18:33:49 +0000186 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Sanne Wouda29338752017-02-08 14:48:05 +0000187 const MCAsmInfo &MAI, unsigned CB);
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000188 AsmParser(const AsmParser &) = delete;
189 AsmParser &operator=(const AsmParser &) = delete;
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000190 ~AsmParser() override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000191
Craig Topper59be68f2014-03-08 07:14:16 +0000192 bool Run(bool NoInitialTextSection, bool NoFinalize = false) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000193
Craig Topper59be68f2014-03-08 07:14:16 +0000194 void addDirectiveHandler(StringRef Directive,
195 ExtensionDirectiveHandler Handler) override {
Eli Bendersky29b9f472013-01-16 00:50:52 +0000196 ExtensionDirectiveMap[Directive] = Handler;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000197 }
198
Toma Tabacu11e14a92015-04-21 11:50:52 +0000199 void addAliasForDirective(StringRef Directive, StringRef Alias) override {
200 DirectiveKindMap[Directive] = DirectiveKindMap[Alias];
201 }
202
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000203 /// @name MCAsmParser Interface
204 /// {
205
Craig Topper59be68f2014-03-08 07:14:16 +0000206 SourceMgr &getSourceManager() override { return SrcMgr; }
207 MCAsmLexer &getLexer() override { return Lexer; }
208 MCContext &getContext() override { return Ctx; }
209 MCStreamer &getStreamer() override { return Out; }
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000210
Reid Klecknera5b1eef2016-08-26 17:58:37 +0000211 CodeViewContext &getCVContext() { return Ctx.getCVContext(); }
212
Craig Topper59be68f2014-03-08 07:14:16 +0000213 unsigned getAssemblerDialect() override {
Devang Patela173ee52012-01-31 18:14:05 +0000214 if (AssemblerDialect == ~0U)
Eric Christophera7c32732012-12-18 00:30:54 +0000215 return MAI.getAssemblerDialect();
Devang Patela173ee52012-01-31 18:14:05 +0000216 else
217 return AssemblerDialect;
218 }
Craig Topper59be68f2014-03-08 07:14:16 +0000219 void setAssemblerDialect(unsigned i) override {
Devang Patela173ee52012-01-31 18:14:05 +0000220 AssemblerDialect = i;
221 }
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000222
Nirav Dave2364748a2016-09-16 18:30:20 +0000223 void Note(SMLoc L, const Twine &Msg, SMRange Range = None) override;
224 bool Warning(SMLoc L, const Twine &Msg, SMRange Range = None) override;
225 bool printError(SMLoc L, const Twine &Msg, SMRange Range = None) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000226
Craig Topper59be68f2014-03-08 07:14:16 +0000227 const AsmToken &Lex() override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000228
Yunzhong Gao27ea29b2016-09-02 23:15:29 +0000229 void setParsingInlineAsm(bool V) override {
230 ParsingInlineAsm = V;
Reid Kleckner953bdce2018-10-24 20:23:57 +0000231 // When parsing MS inline asm, we must lex 0b1101 and 0ABCH as binary and
232 // hex integer literals.
233 Lexer.setLexMasmIntegers(V);
Yunzhong Gao27ea29b2016-09-02 23:15:29 +0000234 }
Craig Topper59be68f2014-03-08 07:14:16 +0000235 bool isParsingInlineAsm() override { return ParsingInlineAsm; }
Chad Rosier8bce6642012-10-18 15:49:34 +0000236
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000237 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
Chad Rosier8bce6642012-10-18 15:49:34 +0000238 unsigned &NumOutputs, unsigned &NumInputs,
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000239 SmallVectorImpl<std::pair<void *,bool>> &OpDecls,
Chad Rosier8bce6642012-10-18 15:49:34 +0000240 SmallVectorImpl<std::string> &Constraints,
Chad Rosier8bce6642012-10-18 15:49:34 +0000241 SmallVectorImpl<std::string> &Clobbers,
Craig Topper59be68f2014-03-08 07:14:16 +0000242 const MCInstrInfo *MII, const MCInstPrinter *IP,
243 MCAsmParserSemaCallback &SI) override;
Chad Rosier49963552012-10-13 00:26:04 +0000244
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000245 bool parseExpression(const MCExpr *&Res);
Craig Topper59be68f2014-03-08 07:14:16 +0000246 bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
247 bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) override;
248 bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
Toma Tabacu7bc44dc2015-06-25 09:52:02 +0000249 bool parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
250 SMLoc &EndLoc) override;
Craig Topper59be68f2014-03-08 07:14:16 +0000251 bool parseAbsoluteExpression(int64_t &Res) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000252
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000253 /// Parse a floating point expression using the float \p Semantics
Petr Hosek4cb08ce2016-09-23 19:25:15 +0000254 /// and set \p Res to the value.
255 bool parseRealValue(const fltSemantics &Semantics, APInt &Res);
256
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000257 /// Parse an identifier or string (as a quoted identifier)
Eli Bendersky0cf0cb92013-01-12 00:05:00 +0000258 /// and set \p Res to the identifier contents.
Craig Topper59be68f2014-03-08 07:14:16 +0000259 bool parseIdentifier(StringRef &Res) override;
260 void eatToEndOfStatement() override;
Eli Bendersky0cf0cb92013-01-12 00:05:00 +0000261
Nirav Davef43cc9f2016-10-10 15:24:54 +0000262 bool checkForValidSection() override;
Nirav Davea645433c2016-07-18 15:24:03 +0000263
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000264 /// }
265
266private:
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +0000267 bool parseStatement(ParseStatementInfo &Info,
268 MCAsmParserSemaCallback *SI);
Marina Yatsina5f5de9f2016-03-07 18:11:16 +0000269 bool parseCurlyBlockScope(SmallVectorImpl<AsmRewrite>& AsmStrRewrites);
Craig Topper3c76c522015-09-20 23:35:59 +0000270 bool parseCppHashLineFilenameComment(SMLoc L);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000271
Jim Grosbach4b905842013-09-20 23:08:21 +0000272 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +0000273 ArrayRef<MCAsmMacroParameter> Parameters);
Rafael Espindola34b9c512012-06-03 23:57:14 +0000274 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +0000275 ArrayRef<MCAsmMacroParameter> Parameters,
Toma Tabacu217116e2015-04-27 10:50:29 +0000276 ArrayRef<MCAsmMacroArgument> A, bool EnableAtPseudoVariable,
Craig Topper3c76c522015-09-20 23:35:59 +0000277 SMLoc L);
Daniel Dunbar43235712010-07-18 18:54:11 +0000278
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000279 /// Are macros enabled in the parser?
Jim Grosbach4b905842013-09-20 23:08:21 +0000280 bool areMacrosEnabled() {return MacrosEnabledFlag;}
Eli Benderskya313ae62013-01-16 18:56:50 +0000281
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000282 /// Control a flag in the parser that enables or disables macros.
Jim Grosbach4b905842013-09-20 23:08:21 +0000283 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
Eli Benderskya313ae62013-01-16 18:56:50 +0000284
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000285 /// Are we inside a macro instantiation?
Jim Grosbach4b905842013-09-20 23:08:21 +0000286 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
Eli Benderskya313ae62013-01-16 18:56:50 +0000287
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000288 /// Handle entry to macro instantiation.
Eli Benderskya313ae62013-01-16 18:56:50 +0000289 ///
290 /// \param M The macro.
291 /// \param NameLoc Instantiation location.
Jim Grosbach4b905842013-09-20 23:08:21 +0000292 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
Eli Benderskya313ae62013-01-16 18:56:50 +0000293
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000294 /// Handle exit from macro instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +0000295 void handleMacroExit();
Eli Benderskya313ae62013-01-16 18:56:50 +0000296
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000297 /// Extract AsmTokens for a macro argument.
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +0000298 bool parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg);
Eli Benderskya313ae62013-01-16 18:56:50 +0000299
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000300 /// Parse all macro arguments for a given macro.
Jim Grosbach4b905842013-09-20 23:08:21 +0000301 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
Eli Benderskya313ae62013-01-16 18:56:50 +0000302
Jim Grosbach4b905842013-09-20 23:08:21 +0000303 void printMacroInstantiations();
304 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
Nirav Dave2364748a2016-09-16 18:30:20 +0000305 SMRange Range = None) const {
306 ArrayRef<SMRange> Ranges(Range);
Chris Lattner72845262011-10-16 05:47:55 +0000307 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
Benjamin Kramerc7583112010-09-27 17:42:11 +0000308 }
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000309 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
Benjamin Kramerc7583112010-09-27 17:42:11 +0000310
Paul Robinson938d9a02018-03-22 15:48:01 +0000311 /// Should we emit DWARF describing this assembler source? (Returns false if
312 /// the source has .file directives, which means we don't want to generate
313 /// info describing the assembler source itself.)
314 bool enabledGenDwarfForAssembly();
315
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000316 /// Enter the specified file. This returns true on failure.
Jim Grosbach4b905842013-09-20 23:08:21 +0000317 bool enterIncludeFile(const std::string &Filename);
318
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000319 /// Process the specified file for the .incbin directive.
Kevin Enderby109f25c2011-12-14 21:47:48 +0000320 /// This returns true on failure.
Petr Hosek2f4ac442016-09-23 00:41:06 +0000321 bool processIncbinFile(const std::string &Filename, int64_t Skip = 0,
322 const MCExpr *Count = nullptr, SMLoc Loc = SMLoc());
Daniel Dunbar43235712010-07-18 18:54:11 +0000323
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000324 /// Reset the current lexer position to that given by \p Loc. The
Daniel Dunbar43235712010-07-18 18:54:11 +0000325 /// current token is not set; clients should ensure Lex() is called
326 /// subsequently.
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000327 ///
Alp Tokera55b95b2014-07-06 10:33:31 +0000328 /// \param InBuffer If not 0, should be the known buffer id that contains the
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000329 /// location.
Alp Tokera55b95b2014-07-06 10:33:31 +0000330 void jumpToLoc(SMLoc Loc, unsigned InBuffer = 0);
Daniel Dunbar43235712010-07-18 18:54:11 +0000331
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000332 /// Parse up to the end of statement and a return the contents from the
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000333 /// current token until the end of the statement; the current token on exit
334 /// will be either the EndOfStatement or EOF.
Craig Topper59be68f2014-03-08 07:14:16 +0000335 StringRef parseStringToEndOfStatement() override;
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000336
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000337 /// Parse until the end of a statement or a comma is encountered,
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000338 /// return the contents from the current token up to the end or comma.
Jim Grosbach4b905842013-09-20 23:08:21 +0000339 StringRef parseStringToComma();
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000340
Jim Grosbach4b905842013-09-20 23:08:21 +0000341 bool parseAssignment(StringRef Name, bool allow_redef,
Nirav Dave7fd992a2018-08-16 16:31:14 +0000342 bool NoDeadStrip = false);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000343
Ahmed Bougacha457852f2015-04-28 00:17:39 +0000344 unsigned getBinOpPrecedence(AsmToken::TokenKind K,
345 MCBinaryExpr::Opcode &Kind);
346
Jim Grosbach4b905842013-09-20 23:08:21 +0000347 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
348 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
349 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000350
Jim Grosbach4b905842013-09-20 23:08:21 +0000351 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
Rafael Espindola63760ba2010-10-28 20:02:27 +0000352
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000353 bool parseCVFunctionId(int64_t &FunctionId, StringRef DirectiveName);
354 bool parseCVFileId(int64_t &FileId, StringRef DirectiveName);
355
Eli Bendersky17233942013-01-15 22:59:42 +0000356 // Generic (target and platform independent) directive parsing.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000357 enum DirectiveKind {
Eli Bendersky4d21fa02013-01-10 23:40:56 +0000358 DK_NO_DIRECTIVE, // Placeholder
Saleem Abdulrasoolb3c70c02017-07-28 03:39:18 +0000359 DK_SET,
360 DK_EQU,
361 DK_EQUIV,
362 DK_ASCII,
363 DK_ASCIZ,
364 DK_STRING,
365 DK_BYTE,
366 DK_SHORT,
Daniel Sanders9f6ad492015-11-12 13:33:00 +0000367 DK_RELOC,
Saleem Abdulrasoolb3c70c02017-07-28 03:39:18 +0000368 DK_VALUE,
369 DK_2BYTE,
370 DK_LONG,
371 DK_INT,
372 DK_4BYTE,
373 DK_QUAD,
374 DK_8BYTE,
375 DK_OCTA,
376 DK_DC,
377 DK_DC_A,
378 DK_DC_B,
379 DK_DC_D,
380 DK_DC_L,
381 DK_DC_S,
382 DK_DC_W,
383 DK_DC_X,
384 DK_DCB,
385 DK_DCB_B,
386 DK_DCB_D,
387 DK_DCB_L,
388 DK_DCB_S,
389 DK_DCB_W,
390 DK_DCB_X,
391 DK_DS,
392 DK_DS_B,
393 DK_DS_D,
394 DK_DS_L,
395 DK_DS_P,
396 DK_DS_S,
397 DK_DS_W,
398 DK_DS_X,
399 DK_SINGLE,
400 DK_FLOAT,
401 DK_DOUBLE,
402 DK_ALIGN,
403 DK_ALIGN32,
404 DK_BALIGN,
405 DK_BALIGNW,
406 DK_BALIGNL,
407 DK_P2ALIGN,
408 DK_P2ALIGNW,
409 DK_P2ALIGNL,
410 DK_ORG,
411 DK_FILL,
412 DK_ENDR,
413 DK_BUNDLE_ALIGN_MODE,
414 DK_BUNDLE_LOCK,
415 DK_BUNDLE_UNLOCK,
416 DK_ZERO,
417 DK_EXTERN,
418 DK_GLOBL,
419 DK_GLOBAL,
420 DK_LAZY_REFERENCE,
421 DK_NO_DEAD_STRIP,
422 DK_SYMBOL_RESOLVER,
423 DK_PRIVATE_EXTERN,
424 DK_REFERENCE,
425 DK_WEAK_DEFINITION,
426 DK_WEAK_REFERENCE,
427 DK_WEAK_DEF_CAN_BE_HIDDEN,
428 DK_COMM,
429 DK_COMMON,
430 DK_LCOMM,
431 DK_ABORT,
432 DK_INCLUDE,
433 DK_INCBIN,
434 DK_CODE16,
435 DK_CODE16GCC,
436 DK_REPT,
437 DK_IRP,
438 DK_IRPC,
439 DK_IF,
440 DK_IFEQ,
441 DK_IFGE,
442 DK_IFGT,
443 DK_IFLE,
444 DK_IFLT,
445 DK_IFNE,
446 DK_IFB,
447 DK_IFNB,
448 DK_IFC,
449 DK_IFEQS,
450 DK_IFNC,
451 DK_IFNES,
452 DK_IFDEF,
453 DK_IFNDEF,
454 DK_IFNOTDEF,
455 DK_ELSEIF,
456 DK_ELSE,
457 DK_ENDIF,
458 DK_SPACE,
459 DK_SKIP,
460 DK_FILE,
461 DK_LINE,
462 DK_LOC,
463 DK_STABS,
464 DK_CV_FILE,
465 DK_CV_FUNC_ID,
466 DK_CV_INLINE_SITE_ID,
467 DK_CV_LOC,
468 DK_CV_LINETABLE,
469 DK_CV_INLINE_LINETABLE,
470 DK_CV_DEF_RANGE,
471 DK_CV_STRINGTABLE,
Reid Kleckner06d02d02018-09-07 21:30:52 +0000472 DK_CV_STRING,
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000473 DK_CV_FILECHECKSUMS,
Reid Kleckner26fa1bf2017-09-19 18:14:45 +0000474 DK_CV_FILECHECKSUM_OFFSET,
Reid Kleckner9cdd4df2017-10-11 21:24:33 +0000475 DK_CV_FPO_DATA,
Saleem Abdulrasoolb3c70c02017-07-28 03:39:18 +0000476 DK_CFI_SECTIONS,
477 DK_CFI_STARTPROC,
478 DK_CFI_ENDPROC,
479 DK_CFI_DEF_CFA,
480 DK_CFI_DEF_CFA_OFFSET,
481 DK_CFI_ADJUST_CFA_OFFSET,
482 DK_CFI_DEF_CFA_REGISTER,
483 DK_CFI_OFFSET,
484 DK_CFI_REL_OFFSET,
485 DK_CFI_PERSONALITY,
486 DK_CFI_LSDA,
487 DK_CFI_REMEMBER_STATE,
488 DK_CFI_RESTORE_STATE,
489 DK_CFI_SAME_VALUE,
490 DK_CFI_RESTORE,
491 DK_CFI_ESCAPE,
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +0000492 DK_CFI_RETURN_COLUMN,
Saleem Abdulrasoolb3c70c02017-07-28 03:39:18 +0000493 DK_CFI_SIGNAL_FRAME,
494 DK_CFI_UNDEFINED,
495 DK_CFI_REGISTER,
496 DK_CFI_WINDOW_SAVE,
Luke Cheeseman41a9e532018-12-21 10:45:08 +0000497 DK_CFI_B_KEY_FRAME,
Saleem Abdulrasoolb3c70c02017-07-28 03:39:18 +0000498 DK_MACROS_ON,
499 DK_MACROS_OFF,
500 DK_ALTMACRO,
501 DK_NOALTMACRO,
502 DK_MACRO,
503 DK_EXITM,
504 DK_ENDM,
505 DK_ENDMACRO,
506 DK_PURGEM,
507 DK_SLEB128,
508 DK_ULEB128,
509 DK_ERR,
510 DK_ERROR,
511 DK_WARNING,
Coby Tayree01e53202017-10-02 14:36:31 +0000512 DK_PRINT,
Peter Collingbourne3e227332018-07-17 22:17:18 +0000513 DK_ADDRSIG,
514 DK_ADDRSIG_SYM,
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000515 DK_END
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000516 };
517
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000518 /// Maps directive name --> DirectiveKind enum, for
Eli Bendersky17233942013-01-15 22:59:42 +0000519 /// directives parsed by this class.
520 StringMap<DirectiveKind> DirectiveKindMap;
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000521
522 // ".ascii", ".asciz", ".string"
Jim Grosbach4b905842013-09-20 23:08:21 +0000523 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
Daniel Sanders9f6ad492015-11-12 13:33:00 +0000524 bool parseDirectiveReloc(SMLoc DirectiveLoc); // ".reloc"
Nirav Dave1a9044b2016-10-24 14:35:29 +0000525 bool parseDirectiveValue(StringRef IDVal,
526 unsigned Size); // ".byte", ".long", ...
527 bool parseDirectiveOctaValue(StringRef IDVal); // ".octa", ...
528 bool parseDirectiveRealValue(StringRef IDVal,
529 const fltSemantics &); // ".single", ...
Jim Grosbach4b905842013-09-20 23:08:21 +0000530 bool parseDirectiveFill(); // ".fill"
531 bool parseDirectiveZero(); // ".zero"
Eric Christophera7c32732012-12-18 00:30:54 +0000532 // ".set", ".equ", ".equiv"
Jim Grosbach4b905842013-09-20 23:08:21 +0000533 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
534 bool parseDirectiveOrg(); // ".org"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000535 // ".align{,32}", ".p2align{,w,l}"
Jim Grosbach4b905842013-09-20 23:08:21 +0000536 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000537
Eli Bendersky17233942013-01-15 22:59:42 +0000538 // ".file", ".line", ".loc", ".stabs"
Jim Grosbach4b905842013-09-20 23:08:21 +0000539 bool parseDirectiveFile(SMLoc DirectiveLoc);
540 bool parseDirectiveLine();
541 bool parseDirectiveLoc();
542 bool parseDirectiveStabs();
Eli Bendersky17233942013-01-15 22:59:42 +0000543
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000544 // ".cv_file", ".cv_func_id", ".cv_inline_site_id", ".cv_loc", ".cv_linetable",
Reid Kleckner06d02d02018-09-07 21:30:52 +0000545 // ".cv_inline_linetable", ".cv_def_range", ".cv_string"
Reid Kleckner2214ed82016-01-29 00:49:42 +0000546 bool parseDirectiveCVFile();
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000547 bool parseDirectiveCVFuncId();
548 bool parseDirectiveCVInlineSiteId();
Reid Kleckner2214ed82016-01-29 00:49:42 +0000549 bool parseDirectiveCVLoc();
550 bool parseDirectiveCVLinetable();
David Majnemer6fcbd7e2016-01-29 19:24:12 +0000551 bool parseDirectiveCVInlineLinetable();
David Majnemer408b5e62016-02-05 01:55:49 +0000552 bool parseDirectiveCVDefRange();
Reid Kleckner06d02d02018-09-07 21:30:52 +0000553 bool parseDirectiveCVString();
Reid Kleckner2214ed82016-01-29 00:49:42 +0000554 bool parseDirectiveCVStringTable();
555 bool parseDirectiveCVFileChecksums();
Reid Kleckner26fa1bf2017-09-19 18:14:45 +0000556 bool parseDirectiveCVFileChecksumOffset();
Reid Kleckner9cdd4df2017-10-11 21:24:33 +0000557 bool parseDirectiveCVFPOData();
Reid Kleckner2214ed82016-01-29 00:49:42 +0000558
Eli Bendersky17233942013-01-15 22:59:42 +0000559 // .cfi directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000560 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +0000561 bool parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +0000562 bool parseDirectiveCFISections();
563 bool parseDirectiveCFIStartProc();
564 bool parseDirectiveCFIEndProc();
565 bool parseDirectiveCFIDefCfaOffset();
566 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
567 bool parseDirectiveCFIAdjustCfaOffset();
568 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
569 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
570 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
571 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
572 bool parseDirectiveCFIRememberState();
573 bool parseDirectiveCFIRestoreState();
574 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
575 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
576 bool parseDirectiveCFIEscape();
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +0000577 bool parseDirectiveCFIReturnColumn(SMLoc DirectiveLoc);
Jim Grosbach4b905842013-09-20 23:08:21 +0000578 bool parseDirectiveCFISignalFrame();
579 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
Eli Bendersky17233942013-01-15 22:59:42 +0000580
581 // macro directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000582 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
Nico Weber155dccd12014-07-24 17:08:39 +0000583 bool parseDirectiveExitMacro(StringRef Directive);
Jim Grosbach4b905842013-09-20 23:08:21 +0000584 bool parseDirectiveEndMacro(StringRef Directive);
585 bool parseDirectiveMacro(SMLoc DirectiveLoc);
586 bool parseDirectiveMacrosOnOff(StringRef Directive);
Michael Zuckerman56704612017-05-01 13:20:12 +0000587 // alternate macro mode directives
588 bool parseDirectiveAltmacro(StringRef Directive);
Eli Benderskyf483ff92012-12-20 19:05:53 +0000589 // ".bundle_align_mode"
Jim Grosbach4b905842013-09-20 23:08:21 +0000590 bool parseDirectiveBundleAlignMode();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000591 // ".bundle_lock"
Jim Grosbach4b905842013-09-20 23:08:21 +0000592 bool parseDirectiveBundleLock();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000593 // ".bundle_unlock"
Jim Grosbach4b905842013-09-20 23:08:21 +0000594 bool parseDirectiveBundleUnlock();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000595
Eli Bendersky17233942013-01-15 22:59:42 +0000596 // ".space", ".skip"
Jim Grosbach4b905842013-09-20 23:08:21 +0000597 bool parseDirectiveSpace(StringRef IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +0000598
Petr Hosek4cb08ce2016-09-23 19:25:15 +0000599 // ".dcb"
600 bool parseDirectiveDCB(StringRef IDVal, unsigned Size);
601 bool parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &);
Petr Hosek85b2f672016-09-23 21:53:36 +0000602 // ".ds"
603 bool parseDirectiveDS(StringRef IDVal, unsigned Size);
Petr Hosek4cb08ce2016-09-23 19:25:15 +0000604
Eli Bendersky17233942013-01-15 22:59:42 +0000605 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
Jim Grosbach4b905842013-09-20 23:08:21 +0000606 bool parseDirectiveLEB128(bool Signed);
Eli Bendersky17233942013-01-15 22:59:42 +0000607
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000608 /// Parse a directive like ".globl" which
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000609 /// accepts a single symbol (which should be a label or an external).
Jim Grosbach4b905842013-09-20 23:08:21 +0000610 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000611
Jim Grosbach4b905842013-09-20 23:08:21 +0000612 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000613
Jim Grosbach4b905842013-09-20 23:08:21 +0000614 bool parseDirectiveAbort(); // ".abort"
615 bool parseDirectiveInclude(); // ".include"
616 bool parseDirectiveIncbin(); // ".incbin"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000617
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +0000618 // ".if", ".ifeq", ".ifge", ".ifgt" , ".ifle", ".iflt" or ".ifne"
619 bool parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind);
Benjamin Kramer62c18b02012-05-12 11:18:42 +0000620 // ".ifb" or ".ifnb", depending on ExpectBlank.
Jim Grosbach4b905842013-09-20 23:08:21 +0000621 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000622 // ".ifc" or ".ifnc", depending on ExpectEqual.
Jim Grosbach4b905842013-09-20 23:08:21 +0000623 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
Sid Manning51c35602015-03-18 14:20:54 +0000624 // ".ifeqs" or ".ifnes", depending on ExpectEqual.
625 bool parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +0000626 // ".ifdef" or ".ifndef", depending on expect_defined
Jim Grosbach4b905842013-09-20 23:08:21 +0000627 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
628 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
629 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
630 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
Craig Topper59be68f2014-03-08 07:14:16 +0000631 bool parseEscapedString(std::string &Data) override;
Daniel Dunbar55f16672010-09-17 02:47:07 +0000632
Jim Grosbach4b905842013-09-20 23:08:21 +0000633 const MCExpr *applyModifierToExpr(const MCExpr *E,
Daniel Dunbar55f16672010-09-17 02:47:07 +0000634 MCSymbolRefExpr::VariantKind Variant);
Rafael Espindola47b7dac2012-05-12 16:31:10 +0000635
Rafael Espindola34b9c512012-06-03 23:57:14 +0000636 // Macro-like directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000637 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
638 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +0000639 raw_svector_ostream &OS);
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +0000640 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
Jim Grosbach4b905842013-09-20 23:08:21 +0000641 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
642 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
643 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
Chad Rosier8bce6642012-10-18 15:49:34 +0000644
Chad Rosierc7f552c2013-02-12 21:33:51 +0000645 // "_emit" or "__emit"
Jim Grosbach4b905842013-09-20 23:08:21 +0000646 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
Chad Rosierc7f552c2013-02-12 21:33:51 +0000647 size_t Len);
648
649 // "align"
Jim Grosbach4b905842013-09-20 23:08:21 +0000650 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000651
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000652 // "end"
653 bool parseDirectiveEnd(SMLoc DirectiveLoc);
654
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +0000655 // ".err" or ".error"
656 bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +0000657
Nico Weber404012b2014-07-24 16:26:06 +0000658 // ".warning"
659 bool parseDirectiveWarning(SMLoc DirectiveLoc);
660
Coby Tayree01e53202017-10-02 14:36:31 +0000661 // .print <double-quotes-string>
662 bool parseDirectivePrint(SMLoc DirectiveLoc);
663
Peter Collingbourne3e227332018-07-17 22:17:18 +0000664 // Directives to support address-significance tables.
665 bool parseDirectiveAddrsig();
666 bool parseDirectiveAddrsigSym();
667
Eli Bendersky17233942013-01-15 22:59:42 +0000668 void initializeDirectiveKindMap();
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000669};
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000670
671} // end anonymous namespace
Daniel Dunbar86033402010-07-12 17:54:38 +0000672
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000673namespace llvm {
674
675extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbarab058b82010-07-12 21:23:32 +0000676extern MCAsmParserExtension *createELFAsmParser();
Michael J. Spencerc8dbdfd2010-10-09 11:01:07 +0000677extern MCAsmParserExtension *createCOFFAsmParser();
Wouter van Oortmerssencc75e772018-11-12 20:15:01 +0000678extern MCAsmParserExtension *createWasmAsmParser();
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000679
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000680} // end namespace llvm
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000681
Chris Lattnerc35681b2010-01-19 19:46:13 +0000682enum { DEFAULT_ADDRSPACE = 0 };
683
David Blaikie9f380a32015-03-16 18:06:57 +0000684AsmParser::AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Sanne Wouda29338752017-02-08 14:48:05 +0000685 const MCAsmInfo &MAI, unsigned CB = 0)
David Blaikie9f380a32015-03-16 18:06:57 +0000686 : Lexer(MAI), Ctx(Ctx), Out(Out), MAI(MAI), SrcMgr(SM),
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000687 CurBuffer(CB ? CB : SM.getMainFileID()), MacrosEnabledFlag(true) {
Nirav Dave2364748a2016-09-16 18:30:20 +0000688 HadError = false;
Benjamin Kramer47f5e302011-10-16 10:48:29 +0000689 // Save the old handler.
690 SavedDiagHandler = SrcMgr.getDiagHandler();
691 SavedDiagContext = SrcMgr.getDiagContext();
692 // Set our own handler which calls the saved handler.
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000693 SrcMgr.setDiagHandler(DiagHandler, this);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000694 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar86033402010-07-12 17:54:38 +0000695
Daniel Dunbarc5011082010-07-12 18:12:02 +0000696 // Initialize the platform / file format parser.
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000697 switch (Ctx.getObjectFileInfo()->getObjectFileType()) {
698 case MCObjectFileInfo::IsCOFF:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000699 PlatformParser.reset(createCOFFAsmParser());
700 break;
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000701 case MCObjectFileInfo::IsMachO:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000702 PlatformParser.reset(createDarwinAsmParser());
703 IsDarwin = true;
704 break;
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000705 case MCObjectFileInfo::IsELF:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000706 PlatformParser.reset(createELFAsmParser());
707 break;
Dan Gohman18eafb62017-02-22 01:23:18 +0000708 case MCObjectFileInfo::IsWasm:
Wouter van Oortmerssencc75e772018-11-12 20:15:01 +0000709 PlatformParser.reset(createWasmAsmParser());
Dan Gohman18eafb62017-02-22 01:23:18 +0000710 break;
Daniel Dunbarc5011082010-07-12 18:12:02 +0000711 }
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000712
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000713 PlatformParser->Initialize(*this);
Eli Bendersky17233942013-01-15 22:59:42 +0000714 initializeDirectiveKindMap();
Toma Tabacu217116e2015-04-27 10:50:29 +0000715
716 NumOfMacroInstantiations = 0;
Chris Lattner351a7ef2009-09-27 21:16:52 +0000717}
718
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000719AsmParser::~AsmParser() {
Saleem Abdulrasool6eae1e62014-05-21 17:53:18 +0000720 assert((HadError || ActiveMacros.empty()) &&
721 "Unexpected active macro instantiation!");
Sanne Wouda29338752017-02-08 14:48:05 +0000722
723 // Restore the saved diagnostics handler and context for use during
724 // finalization.
725 SrcMgr.setDiagHandler(SavedDiagHandler, SavedDiagContext);
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000726}
727
Jim Grosbach4b905842013-09-20 23:08:21 +0000728void AsmParser::printMacroInstantiations() {
Daniel Dunbar43235712010-07-18 18:54:11 +0000729 // Print the active macro instantiation stack.
Jim Grosbach4b905842013-09-20 23:08:21 +0000730 for (std::vector<MacroInstantiation *>::const_reverse_iterator
731 it = ActiveMacros.rbegin(),
732 ie = ActiveMacros.rend();
733 it != ie; ++it)
734 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
Chris Lattner03b80a42011-10-16 05:43:57 +0000735 "while in macro instantiation");
Daniel Dunbar43235712010-07-18 18:54:11 +0000736}
737
Nirav Dave2364748a2016-09-16 18:30:20 +0000738void AsmParser::Note(SMLoc L, const Twine &Msg, SMRange Range) {
739 printPendingErrors();
740 printMessage(L, SourceMgr::DK_Note, Msg, Range);
Saleem Abdulrasool69c7caf2014-01-07 02:28:31 +0000741 printMacroInstantiations();
742}
743
Nirav Dave2364748a2016-09-16 18:30:20 +0000744bool AsmParser::Warning(SMLoc L, const Twine &Msg, SMRange Range) {
Colin LeMahieufe36f832015-07-27 22:39:14 +0000745 if(getTargetParser().getTargetOptions().MCNoWarn)
746 return false;
Joerg Sonnenberger29815912014-08-26 18:39:50 +0000747 if (getTargetParser().getTargetOptions().MCFatalWarnings)
Nirav Dave2364748a2016-09-16 18:30:20 +0000748 return Error(L, Msg, Range);
749 printMessage(L, SourceMgr::DK_Warning, Msg, Range);
Jim Grosbach4b905842013-09-20 23:08:21 +0000750 printMacroInstantiations();
Joerg Sonnenberger74ba2622011-05-19 18:00:13 +0000751 return false;
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +0000752}
753
Nirav Dave2364748a2016-09-16 18:30:20 +0000754bool AsmParser::printError(SMLoc L, const Twine &Msg, SMRange Range) {
Daniel Dunbar43325c42010-09-09 22:42:56 +0000755 HadError = true;
Nirav Dave2364748a2016-09-16 18:30:20 +0000756 printMessage(L, SourceMgr::DK_Error, Msg, Range);
Jim Grosbach4b905842013-09-20 23:08:21 +0000757 printMacroInstantiations();
Chris Lattner2adc9e72009-06-21 21:22:11 +0000758 return true;
759}
760
Jim Grosbach4b905842013-09-20 23:08:21 +0000761bool AsmParser::enterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergeraf5f23e2011-06-01 13:10:15 +0000762 std::string IncludedFile;
Alp Tokera55b95b2014-07-06 10:33:31 +0000763 unsigned NewBuf =
764 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
765 if (!NewBuf)
Sean Callanan7a77eae2010-01-21 00:19:58 +0000766 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +0000767
Sean Callanan7a77eae2010-01-21 00:19:58 +0000768 CurBuffer = NewBuf;
Rafael Espindola8026bd02014-07-06 14:17:29 +0000769 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Sean Callanan7a77eae2010-01-21 00:19:58 +0000770 return false;
771}
Daniel Dunbar43235712010-07-18 18:54:11 +0000772
Sylvestre Ledru149e2812013-05-14 23:36:24 +0000773/// Process the specified .incbin file by searching for it in the include paths
Benjamin Kramerbde91762012-06-02 10:20:22 +0000774/// then just emitting the byte contents of the file to the streamer. This
Kevin Enderby109f25c2011-12-14 21:47:48 +0000775/// returns true on failure.
Petr Hosek2f4ac442016-09-23 00:41:06 +0000776bool AsmParser::processIncbinFile(const std::string &Filename, int64_t Skip,
777 const MCExpr *Count, SMLoc Loc) {
Kevin Enderby109f25c2011-12-14 21:47:48 +0000778 std::string IncludedFile;
Alp Tokera55b95b2014-07-06 10:33:31 +0000779 unsigned NewBuf =
780 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
781 if (!NewBuf)
Kevin Enderby109f25c2011-12-14 21:47:48 +0000782 return true;
783
Kevin Enderbyad41ab52011-12-14 22:34:45 +0000784 // Pick up the bytes from the file and emit them.
Petr Hosek2f4ac442016-09-23 00:41:06 +0000785 StringRef Bytes = SrcMgr.getMemoryBuffer(NewBuf)->getBuffer();
786 Bytes = Bytes.drop_front(Skip);
787 if (Count) {
788 int64_t Res;
Nirav Dave6c0665e2018-04-30 19:22:40 +0000789 if (!Count->evaluateAsAbsolute(Res, getStreamer().getAssemblerPtr()))
Petr Hosek2f4ac442016-09-23 00:41:06 +0000790 return Error(Loc, "expected absolute expression");
791 if (Res < 0)
792 return Warning(Loc, "negative count has no effect");
793 Bytes = Bytes.take_front(Res);
794 }
795 getStreamer().EmitBytes(Bytes);
Kevin Enderby109f25c2011-12-14 21:47:48 +0000796 return false;
797}
798
Alp Tokera55b95b2014-07-06 10:33:31 +0000799void AsmParser::jumpToLoc(SMLoc Loc, unsigned InBuffer) {
800 CurBuffer = InBuffer ? InBuffer : SrcMgr.FindBufferContainingLoc(Loc);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000801 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(),
802 Loc.getPointer());
Daniel Dunbar43235712010-07-18 18:54:11 +0000803}
804
Sean Callanan7a77eae2010-01-21 00:19:58 +0000805const AsmToken &AsmParser::Lex() {
Nirav Dave1180e6892016-06-02 17:15:05 +0000806 if (Lexer.getTok().is(AsmToken::Error))
807 Error(Lexer.getErrLoc(), Lexer.getErr());
808
Nirav Dave53a72f42016-07-11 12:42:14 +0000809 // if it's a end of statement with a comment in it
810 if (getTok().is(AsmToken::EndOfStatement)) {
811 // if this is a line comment output it.
Nirav Dave670109d2017-06-09 14:04:03 +0000812 if (!getTok().getString().empty() && getTok().getString().front() != '\n' &&
Nirav Dave53a72f42016-07-11 12:42:14 +0000813 getTok().getString().front() != '\r' && MAI.preserveAsmComments())
814 Out.addExplicitComment(Twine(getTok().getString()));
815 }
816
Sean Callanan7a77eae2010-01-21 00:19:58 +0000817 const AsmToken *tok = &Lexer.Lex();
Nirav Dave53a72f42016-07-11 12:42:14 +0000818
819 // Parse comments here to be deferred until end of next statement.
Nirav Davefd910412016-06-17 16:06:17 +0000820 while (tok->is(AsmToken::Comment)) {
Nirav Dave53a72f42016-07-11 12:42:14 +0000821 if (MAI.preserveAsmComments())
822 Out.addExplicitComment(Twine(tok->getString()));
Nirav Davefd910412016-06-17 16:06:17 +0000823 tok = &Lexer.Lex();
824 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000825
Sean Callanan7a77eae2010-01-21 00:19:58 +0000826 if (tok->is(AsmToken::Eof)) {
827 // If this is the end of an included file, pop the parent file off the
828 // include stack.
829 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
830 if (ParentIncludeLoc != SMLoc()) {
Jim Grosbach4b905842013-09-20 23:08:21 +0000831 jumpToLoc(ParentIncludeLoc);
Nirav Davefd910412016-06-17 16:06:17 +0000832 return Lex();
Sean Callanan7a77eae2010-01-21 00:19:58 +0000833 }
834 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000835
Sean Callanan7a77eae2010-01-21 00:19:58 +0000836 return *tok;
Sean Callanan686ed8d2010-01-19 20:22:31 +0000837}
838
Paul Robinson938d9a02018-03-22 15:48:01 +0000839bool AsmParser::enabledGenDwarfForAssembly() {
840 // Check whether the user specified -g.
841 if (!getContext().getGenDwarfForAssembly())
842 return false;
843 // If we haven't encountered any .file directives (which would imply that
844 // the assembler source was produced with debug info already) then emit one
845 // describing the assembler source file itself.
846 if (getContext().getGenDwarfFileNumber() == 0)
847 getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective(
848 0, StringRef(), getContext().getMainFileName()));
849 return true;
850}
851
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000852bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar322fec62010-03-13 02:20:57 +0000853 // Create the initial section, if requested.
Daniel Dunbar322fec62010-03-13 02:20:57 +0000854 if (!NoInitialTextSection)
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000855 Out.InitSections(false);
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000856
Chris Lattner36e02122009-06-21 20:54:55 +0000857 // Prime the lexer.
Sean Callanan686ed8d2010-01-19 20:22:31 +0000858 Lex();
Daniel Dunbar43325c42010-09-09 22:42:56 +0000859
860 HadError = false;
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000861 AsmCond StartingCondState = TheCondState;
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +0000862 SmallVector<AsmRewrite, 4> AsmStrRewrites;
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000863
Kevin Enderby6469fc22011-11-01 22:27:22 +0000864 // If we are generating dwarf for assembly source files save the initial text
Paul Robinson938d9a02018-03-22 15:48:01 +0000865 // section. (Don't use enabledGenDwarfForAssembly() here, as we aren't
866 // emitting any actual debug info yet and haven't had a chance to parse any
867 // embedded .file directives.)
Kevin Enderby6469fc22011-11-01 22:27:22 +0000868 if (getContext().getGenDwarfForAssembly()) {
Eric Christopher445c9522016-10-14 05:47:37 +0000869 MCSection *Sec = getStreamer().getCurrentSectionOnly();
Rafael Espindola2f9bdd82015-05-27 20:52:32 +0000870 if (!Sec->getBeginSymbol()) {
871 MCSymbol *SectionStartSym = getContext().createTempSymbol();
872 getStreamer().EmitLabel(SectionStartSym);
873 Sec->setBeginSymbol(SectionStartSym);
874 }
Rafael Espindolae0746792015-05-21 16:52:32 +0000875 bool InsertResult = getContext().addGenDwarfSection(Sec);
876 assert(InsertResult && ".text section should not have debug info yet");
Rafael Espindolafa160c72015-05-21 17:09:22 +0000877 (void)InsertResult;
Kevin Enderby6469fc22011-11-01 22:27:22 +0000878 }
879
Chris Lattner73f36112009-07-02 21:53:43 +0000880 // While we have input, parse each statement.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000881 while (Lexer.isNot(AsmToken::Eof)) {
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +0000882 ParseStatementInfo Info(&AsmStrRewrites);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +0000883 if (!parseStatement(Info, nullptr))
Jim Grosbach4b905842013-09-20 23:08:21 +0000884 continue;
Michael J. Spencer530ce852010-10-09 11:00:50 +0000885
Nirav Dave2364748a2016-09-16 18:30:20 +0000886 // If we have a Lexer Error we are on an Error Token. Load in Lexer Error
887 // for printing ErrMsg via Lex() only if no (presumably better) parser error
888 // exists.
889 if (!hasPendingError() && Lexer.getTok().is(AsmToken::Error)) {
Nirav Dave1180e6892016-06-02 17:15:05 +0000890 Lex();
891 }
892
Nirav Dave2364748a2016-09-16 18:30:20 +0000893 // parseStatement returned true so may need to emit an error.
894 printPendingErrors();
895
896 // Skipping to the next line if needed.
897 if (!getLexer().isAtStartOfStatement())
898 eatToEndOfStatement();
Chris Lattner73f36112009-07-02 21:53:43 +0000899 }
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000900
Wouter van Oortmerssen29c6ce52018-12-26 22:46:18 +0000901 getTargetParser().onEndOfFile();
902 printPendingErrors();
903
Nirav Dave2364748a2016-09-16 18:30:20 +0000904 // All errors should have been emitted.
905 assert(!hasPendingError() && "unexpected error from parseStatement");
906
Oliver Stannard21718282016-07-26 14:19:47 +0000907 getTargetParser().flushPendingInstructions(getStreamer());
908
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000909 if (TheCondState.TheCond != StartingCondState.TheCond ||
910 TheCondState.Ignore != StartingCondState.Ignore)
Nirav Dave2364748a2016-09-16 18:30:20 +0000911 printError(getTok().getLoc(), "unmatched .ifs or .elses");
Kevin Enderbye5930f12010-07-28 20:55:35 +0000912 // Check to see there are no empty DwarfFile slots.
David Blaikie8bf66c42014-04-01 07:35:52 +0000913 const auto &LineTables = getContext().getMCDwarfLineTables();
914 if (!LineTables.empty()) {
915 unsigned Index = 0;
916 for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) {
917 if (File.Name.empty() && Index != 0)
Nirav Dave2364748a2016-09-16 18:30:20 +0000918 printError(getTok().getLoc(), "unassigned file number: " +
919 Twine(Index) +
920 " for .file directives");
David Blaikie8bf66c42014-04-01 07:35:52 +0000921 ++Index;
922 }
Kevin Enderbye5930f12010-07-28 20:55:35 +0000923 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000924
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000925 // Check to see that all assembler local symbols were actually defined.
926 // Targets that don't do subsections via symbols may not want this, though,
927 // so conservatively exclude them. Only do this if we're finalizing, though,
928 // as otherwise we won't necessarilly have seen everything yet.
Tim Northover6b3169b2016-04-11 19:50:46 +0000929 if (!NoFinalize) {
930 if (MAI.hasSubsectionsViaSymbols()) {
931 for (const auto &TableEntry : getContext().getSymbols()) {
932 MCSymbol *Sym = TableEntry.getValue();
933 // Variable symbols may not be marked as defined, so check those
934 // explicitly. If we know it's a variable, we have a definition for
935 // the purposes of this check.
936 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
937 // FIXME: We would really like to refer back to where the symbol was
938 // first referenced for a source location. We need to add something
939 // to track that. Currently, we just point to the end of the file.
Nirav Dave2364748a2016-09-16 18:30:20 +0000940 printError(getTok().getLoc(), "assembler local symbol '" +
941 Sym->getName() + "' not defined");
Tim Northover6b3169b2016-04-11 19:50:46 +0000942 }
943 }
944
945 // Temporary symbols like the ones for directional jumps don't go in the
946 // symbol table. They also need to be diagnosed in all (final) cases.
Tim Northoverc0bef992016-04-13 19:46:54 +0000947 for (std::tuple<SMLoc, CppHashInfoTy, MCSymbol *> &LocSym : DirLabels) {
948 if (std::get<2>(LocSym)->isUndefined()) {
949 // Reset the state of any "# line file" directives we've seen to the
950 // context as it was at the diagnostic site.
951 CppHashInfo = std::get<1>(LocSym);
Nirav Dave2364748a2016-09-16 18:30:20 +0000952 printError(std::get<0>(LocSym), "directional label undefined");
Tim Northoverc0bef992016-04-13 19:46:54 +0000953 }
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000954 }
955 }
956
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000957 // Finalize the output stream if there are no errors and if the client wants
958 // us to.
Jack Carter13d5f752013-10-04 22:52:31 +0000959 if (!HadError && !NoFinalize)
Daniel Dunbar9df5f332009-08-21 08:34:18 +0000960 Out.Finish();
961
Oliver Stannard07b43d32015-11-17 09:58:07 +0000962 return HadError || getContext().hadError();
Chris Lattner36e02122009-06-21 20:54:55 +0000963}
964
Nirav Davef43cc9f2016-10-10 15:24:54 +0000965bool AsmParser::checkForValidSection() {
Eric Christopher445c9522016-10-14 05:47:37 +0000966 if (!ParsingInlineAsm && !getStreamer().getCurrentSectionOnly()) {
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000967 Out.InitSections(false);
Nirav Davef43cc9f2016-10-10 15:24:54 +0000968 return Error(getTok().getLoc(),
969 "expected section directive before assembly directive");
Daniel Dunbare5444a82010-09-09 22:42:59 +0000970 }
Nirav Davef43cc9f2016-10-10 15:24:54 +0000971 return false;
Daniel Dunbare5444a82010-09-09 22:42:59 +0000972}
973
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000974/// Throw away the rest of the line for testing purposes.
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000975void AsmParser::eatToEndOfStatement() {
Jim Grosbach4b905842013-09-20 23:08:21 +0000976 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Nirav Dave1180e6892016-06-02 17:15:05 +0000977 Lexer.Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +0000978
Chris Lattnere5074c42009-06-22 01:29:09 +0000979 // Eat EOL.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000980 if (Lexer.is(AsmToken::EndOfStatement))
Nirav Dave1180e6892016-06-02 17:15:05 +0000981 Lexer.Lex();
Chris Lattnere5074c42009-06-22 01:29:09 +0000982}
983
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000984StringRef AsmParser::parseStringToEndOfStatement() {
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000985 const char *Start = getTok().getLoc().getPointer();
986
Jim Grosbach4b905842013-09-20 23:08:21 +0000987 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Nirav Davefd910412016-06-17 16:06:17 +0000988 Lexer.Lex();
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000989
990 const char *End = getTok().getLoc().getPointer();
991 return StringRef(Start, End - Start);
992}
Chris Lattner78db3622009-06-22 05:51:26 +0000993
Jim Grosbach4b905842013-09-20 23:08:21 +0000994StringRef AsmParser::parseStringToComma() {
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000995 const char *Start = getTok().getLoc().getPointer();
996
997 while (Lexer.isNot(AsmToken::EndOfStatement) &&
Jim Grosbach4b905842013-09-20 23:08:21 +0000998 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
Nirav Davefd910412016-06-17 16:06:17 +0000999 Lexer.Lex();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00001000
1001 const char *End = getTok().getLoc().getPointer();
1002 return StringRef(Start, End - Start);
1003}
1004
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001005/// Parse a paren expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +00001006/// NOTE: This assumes the leading '(' has already been consumed.
1007///
1008/// parenexpr ::= expr)
1009///
Jim Grosbach4b905842013-09-20 23:08:21 +00001010bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
1011 if (parseExpression(Res))
1012 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001013 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner7fdbce72009-06-22 06:32:03 +00001014 return TokError("expected ')' in parentheses expression");
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001015 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001016 Lex();
Chris Lattner7fdbce72009-06-22 06:32:03 +00001017 return false;
1018}
Chris Lattner78db3622009-06-22 05:51:26 +00001019
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001020/// Parse a bracket expression and return it.
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +00001021/// NOTE: This assumes the leading '[' has already been consumed.
1022///
1023/// bracketexpr ::= expr]
1024///
Jim Grosbach4b905842013-09-20 23:08:21 +00001025bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
1026 if (parseExpression(Res))
1027 return true;
Nirav Davea645433c2016-07-18 15:24:03 +00001028 EndLoc = getTok().getEndLoc();
1029 if (parseToken(AsmToken::RBrac, "expected ']' in brackets expression"))
1030 return true;
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +00001031 return false;
1032}
1033
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001034/// Parse a primary expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +00001035/// primaryexpr ::= (parenexpr
1036/// primaryexpr ::= symbol
1037/// primaryexpr ::= number
Chris Lattner6b55cb92010-04-14 04:40:28 +00001038/// primaryexpr ::= '.'
Chris Lattner7fdbce72009-06-22 06:32:03 +00001039/// primaryexpr ::= ~,+,- primaryexpr
Jim Grosbach4b905842013-09-20 23:08:21 +00001040bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Kevin Enderby0017d8a2013-01-22 21:09:20 +00001041 SMLoc FirstTokenLoc = getLexer().getLoc();
1042 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
1043 switch (FirstTokenKind) {
Chris Lattner78db3622009-06-22 05:51:26 +00001044 default:
1045 return TokError("unknown token in expression");
Eric Christopher104af062011-04-12 00:03:13 +00001046 // If we have an error assume that we've already handled it.
1047 case AsmToken::Error:
1048 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001049 case AsmToken::Exclaim:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001050 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001051 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001052 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +00001053 Res = MCUnaryExpr::createLNot(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001054 return false;
Daniel Dunbar24764322010-08-24 19:13:42 +00001055 case AsmToken::Dollar:
Hans Wennborgce69d772013-10-18 20:46:28 +00001056 case AsmToken::At:
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +00001057 case AsmToken::String:
Daniel Dunbard20cda02009-10-16 01:34:54 +00001058 case AsmToken::Identifier: {
Daniel Dunbar24764322010-08-24 19:13:42 +00001059 StringRef Identifier;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001060 if (parseIdentifier(Identifier)) {
Nirav Daved0463322016-10-12 13:58:07 +00001061 // We may have failed but $ may be a valid token.
1062 if (getTok().is(AsmToken::Dollar)) {
David Majnemer0c58bc62013-09-25 10:47:21 +00001063 if (Lexer.getMAI().getDollarIsPC()) {
Nirav Daved0463322016-10-12 13:58:07 +00001064 Lex();
David Majnemer0c58bc62013-09-25 10:47:21 +00001065 // This is a '$' reference, which references the current PC. Emit a
1066 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +00001067 MCSymbol *Sym = Ctx.createTempSymbol();
David Majnemer0c58bc62013-09-25 10:47:21 +00001068 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +00001069 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None,
Jack Carter721726a2013-10-04 21:26:15 +00001070 getContext());
David Majnemer0c58bc62013-09-25 10:47:21 +00001071 EndLoc = FirstTokenLoc;
1072 return false;
Ted Kremenek297febe2014-03-06 22:13:17 +00001073 }
1074 return Error(FirstTokenLoc, "invalid token in expression");
David Majnemer0c58bc62013-09-25 10:47:21 +00001075 }
Kevin Enderby0017d8a2013-01-22 21:09:20 +00001076 }
David Peixotto8ad70b32013-12-04 22:43:20 +00001077 // Parse symbol variant
1078 std::pair<StringRef, StringRef> Split;
1079 if (!MAI.useParensForSymbolVariant()) {
David Majnemer6a5b8122014-06-19 01:25:43 +00001080 if (FirstTokenKind == AsmToken::String) {
1081 if (Lexer.is(AsmToken::At)) {
Nirav Davefd910412016-06-17 16:06:17 +00001082 Lex(); // eat @
David Majnemer6a5b8122014-06-19 01:25:43 +00001083 SMLoc AtLoc = getLexer().getLoc();
1084 StringRef VName;
1085 if (parseIdentifier(VName))
1086 return Error(AtLoc, "expected symbol variant after '@'");
1087
1088 Split = std::make_pair(Identifier, VName);
1089 }
1090 } else {
1091 Split = Identifier.split('@');
1092 }
David Peixotto8ad70b32013-12-04 22:43:20 +00001093 } else if (Lexer.is(AsmToken::LParen)) {
Nirav Davefd910412016-06-17 16:06:17 +00001094 Lex(); // eat '('.
David Peixotto8ad70b32013-12-04 22:43:20 +00001095 StringRef VName;
1096 parseIdentifier(VName);
Nirav Davea645433c2016-07-18 15:24:03 +00001097 // eat ')'.
1098 if (parseToken(AsmToken::RParen,
1099 "unexpected token in variant, expected ')'"))
1100 return true;
David Peixotto8ad70b32013-12-04 22:43:20 +00001101 Split = std::make_pair(Identifier, VName);
1102 }
Daniel Dunbar24764322010-08-24 19:13:42 +00001103
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001104 EndLoc = SMLoc::getFromPointer(Identifier.end());
1105
Daniel Dunbard20cda02009-10-16 01:34:54 +00001106 // This is a symbol reference.
Hans Wennborgce69d772013-10-18 20:46:28 +00001107 StringRef SymbolName = Identifier;
Weiming Zhaocf26d562016-12-01 18:00:36 +00001108 if (SymbolName.empty())
Francis Visoiu Mistrih627d1462018-10-08 10:28:11 +00001109 return Error(getLexer().getLoc(), "expected a symbol reference");
Weiming Zhaocf26d562016-12-01 18:00:36 +00001110
Hans Wennborgce69d772013-10-18 20:46:28 +00001111 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Hans Wennborg69918bc2013-10-17 01:13:02 +00001112
Hans Wennborg7ddcdc82013-10-18 02:14:40 +00001113 // Lookup the symbol variant if used.
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00001114 if (!Split.second.empty()) {
Hans Wennborg7ddcdc82013-10-18 02:14:40 +00001115 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Hans Wennborgce69d772013-10-18 20:46:28 +00001116 if (Variant != MCSymbolRefExpr::VK_Invalid) {
1117 SymbolName = Split.first;
David Peixotto8ad70b32013-12-04 22:43:20 +00001118 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
Hans Wennborgce69d772013-10-18 20:46:28 +00001119 Variant = MCSymbolRefExpr::VK_None;
1120 } else {
Saleem Abdulrasoola25e1e42014-01-26 22:29:43 +00001121 return Error(SMLoc::getFromPointer(Split.second.begin()),
1122 "invalid variant '" + Split.second + "'");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001123 }
1124 }
Daniel Dunbar55992562010-03-15 23:51:06 +00001125
Jim Grosbach6f482002015-05-18 18:43:14 +00001126 MCSymbol *Sym = getContext().getOrCreateSymbol(SymbolName);
Hans Wennborgce69d772013-10-18 20:46:28 +00001127
Daniel Dunbard20cda02009-10-16 01:34:54 +00001128 // If this is an absolute variable reference, substitute it now to preserve
1129 // semantics in the face of reassignment.
Nirav Dave05b58912018-06-05 15:13:39 +00001130 if (Sym->isVariable()) {
1131 auto V = Sym->getVariableValue(/*SetUsed*/ false);
Nirav Daveb1f9e4d2018-09-17 20:34:26 +00001132 bool DoInline = isa<MCConstantExpr>(V) && !Variant;
Nirav Dave05b58912018-06-05 15:13:39 +00001133 if (auto TV = dyn_cast<MCTargetExpr>(V))
1134 DoInline = TV->inlineAssignedExpr();
1135 if (DoInline) {
1136 if (Variant)
1137 return Error(EndLoc, "unexpected modifier on variable reference");
1138 Res = Sym->getVariableValue(/*SetUsed*/ false);
1139 return false;
1140 }
Daniel Dunbard20cda02009-10-16 01:34:54 +00001141 }
1142
1143 // Otherwise create a symbol ref.
Chad Rosier9245e122017-01-19 20:06:32 +00001144 Res = MCSymbolRefExpr::create(Sym, Variant, getContext(), FirstTokenLoc);
Chris Lattner78db3622009-06-22 05:51:26 +00001145 return false;
Daniel Dunbard20cda02009-10-16 01:34:54 +00001146 }
David Woodhousef42a6662014-02-01 16:20:54 +00001147 case AsmToken::BigNum:
1148 return TokError("literal value out of range for directive");
Kevin Enderby0510b482010-05-17 23:08:19 +00001149 case AsmToken::Integer: {
1150 SMLoc Loc = getTok().getLoc();
1151 int64_t IntVal = getTok().getIntVal();
Jim Grosbach13760bd2015-05-30 01:25:56 +00001152 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001153 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001154 Lex(); // Eat token.
Kevin Enderby0510b482010-05-17 23:08:19 +00001155 // Look for 'b' or 'f' following an Integer as a directional label
1156 if (Lexer.getKind() == AsmToken::Identifier) {
1157 StringRef IDVal = getTok().getString();
Ulrich Weigandd4120982013-06-20 16:24:17 +00001158 // Lookup the symbol variant if used.
1159 std::pair<StringRef, StringRef> Split = IDVal.split('@');
1160 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
1161 if (Split.first.size() != IDVal.size()) {
1162 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Arnaud A. de Grandmaisonc97727a2014-03-21 21:54:46 +00001163 if (Variant == MCSymbolRefExpr::VK_Invalid)
Ulrich Weigandd4120982013-06-20 16:24:17 +00001164 return TokError("invalid variant '" + Split.second + "'");
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001165 IDVal = Split.first;
Ulrich Weigandd4120982013-06-20 16:24:17 +00001166 }
Jim Grosbach4b905842013-09-20 23:08:21 +00001167 if (IDVal == "f" || IDVal == "b") {
1168 MCSymbol *Sym =
Jim Grosbach6f482002015-05-18 18:43:14 +00001169 Ctx.getDirectionalLocalSymbol(IntVal, IDVal == "b");
Jim Grosbach13760bd2015-05-30 01:25:56 +00001170 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00001171 if (IDVal == "b" && Sym->isUndefined())
Tim Northover6b3169b2016-04-11 19:50:46 +00001172 return Error(Loc, "directional label undefined");
Tim Northoverc0bef992016-04-13 19:46:54 +00001173 DirLabels.push_back(std::make_tuple(Loc, CppHashInfo, Sym));
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001174 EndLoc = Lexer.getTok().getEndLoc();
Kevin Enderby0510b482010-05-17 23:08:19 +00001175 Lex(); // Eat identifier.
1176 }
1177 }
Chris Lattner78db3622009-06-22 05:51:26 +00001178 return false;
Kevin Enderby0510b482010-05-17 23:08:19 +00001179 }
Bill Wendlingcdbf17b2011-01-25 21:26:41 +00001180 case AsmToken::Real: {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001181 APFloat RealVal(APFloat::IEEEdouble(), getTok().getString());
Bob Wilson813bdf62011-02-03 23:17:47 +00001182 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Jim Grosbach13760bd2015-05-30 01:25:56 +00001183 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001184 EndLoc = Lexer.getTok().getEndLoc();
Bill Wendlingcdbf17b2011-01-25 21:26:41 +00001185 Lex(); // Eat token.
1186 return false;
1187 }
Chris Lattner6b55cb92010-04-14 04:40:28 +00001188 case AsmToken::Dot: {
1189 // This is a '.' reference, which references the current PC. Emit a
1190 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +00001191 MCSymbol *Sym = Ctx.createTempSymbol();
Chris Lattner6b55cb92010-04-14 04:40:28 +00001192 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +00001193 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001194 EndLoc = Lexer.getTok().getEndLoc();
Chris Lattner6b55cb92010-04-14 04:40:28 +00001195 Lex(); // Eat identifier.
1196 return false;
1197 }
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001198 case AsmToken::LParen:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001199 Lex(); // Eat the '('.
Jim Grosbach4b905842013-09-20 23:08:21 +00001200 return parseParenExpr(Res, EndLoc);
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +00001201 case AsmToken::LBrac:
1202 if (!PlatformParser->HasBracketExpressions())
1203 return TokError("brackets expression not supported on this target");
1204 Lex(); // Eat the '['.
Jim Grosbach4b905842013-09-20 23:08:21 +00001205 return parseBracketExpr(Res, EndLoc);
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001206 case AsmToken::Minus:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001207 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001208 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001209 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +00001210 Res = MCUnaryExpr::createMinus(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001211 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001212 case AsmToken::Plus:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001213 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001214 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001215 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +00001216 Res = MCUnaryExpr::createPlus(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001217 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001218 case AsmToken::Tilde:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001219 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001220 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001221 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +00001222 Res = MCUnaryExpr::createNot(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001223 return false;
Daniel Sanders3feeb9c2016-08-08 11:50:25 +00001224 // MIPS unary expression operators. The lexer won't generate these tokens if
1225 // MCAsmInfo::HasMipsExpressions is false for the target.
1226 case AsmToken::PercentCall16:
1227 case AsmToken::PercentCall_Hi:
1228 case AsmToken::PercentCall_Lo:
1229 case AsmToken::PercentDtprel_Hi:
1230 case AsmToken::PercentDtprel_Lo:
1231 case AsmToken::PercentGot:
1232 case AsmToken::PercentGot_Disp:
1233 case AsmToken::PercentGot_Hi:
1234 case AsmToken::PercentGot_Lo:
1235 case AsmToken::PercentGot_Ofst:
1236 case AsmToken::PercentGot_Page:
1237 case AsmToken::PercentGottprel:
1238 case AsmToken::PercentGp_Rel:
1239 case AsmToken::PercentHi:
1240 case AsmToken::PercentHigher:
1241 case AsmToken::PercentHighest:
1242 case AsmToken::PercentLo:
1243 case AsmToken::PercentNeg:
1244 case AsmToken::PercentPcrel_Hi:
1245 case AsmToken::PercentPcrel_Lo:
1246 case AsmToken::PercentTlsgd:
1247 case AsmToken::PercentTlsldm:
1248 case AsmToken::PercentTprel_Hi:
1249 case AsmToken::PercentTprel_Lo:
1250 Lex(); // Eat the operator.
1251 if (Lexer.isNot(AsmToken::LParen))
1252 return TokError("expected '(' after operator");
1253 Lex(); // Eat the operator.
1254 if (parseExpression(Res, EndLoc))
1255 return true;
1256 if (Lexer.isNot(AsmToken::RParen))
1257 return TokError("expected ')'");
1258 Lex(); // Eat the operator.
1259 Res = getTargetParser().createTargetUnaryExpr(Res, FirstTokenKind, Ctx);
1260 return !Res;
Chris Lattner78db3622009-06-22 05:51:26 +00001261 }
1262}
Chris Lattner7fdbce72009-06-22 06:32:03 +00001263
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001264bool AsmParser::parseExpression(const MCExpr *&Res) {
Chris Lattnere17df0b2010-01-15 19:39:23 +00001265 SMLoc EndLoc;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001266 return parseExpression(Res, EndLoc);
Chris Lattner528d00b2010-01-15 19:28:38 +00001267}
1268
Daniel Dunbar55f16672010-09-17 02:47:07 +00001269const MCExpr *
Jim Grosbach4b905842013-09-20 23:08:21 +00001270AsmParser::applyModifierToExpr(const MCExpr *E,
Daniel Dunbar55f16672010-09-17 02:47:07 +00001271 MCSymbolRefExpr::VariantKind Variant) {
Joerg Sonnenbergerb822af42013-08-27 20:23:19 +00001272 // Ask the target implementation about this expression first.
1273 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
1274 if (NewE)
1275 return NewE;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001276 // Recurse over the given expression, rebuilding it to apply the given variant
1277 // if there is exactly one symbol.
1278 switch (E->getKind()) {
1279 case MCExpr::Target:
1280 case MCExpr::Constant:
Craig Topper353eda42014-04-24 06:44:33 +00001281 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001282
1283 case MCExpr::SymbolRef: {
1284 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
1285
1286 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001287 TokError("invalid variant on expression '" + getTok().getIdentifier() +
1288 "' (already modified)");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001289 return E;
1290 }
1291
Jim Grosbach13760bd2015-05-30 01:25:56 +00001292 return MCSymbolRefExpr::create(&SRE->getSymbol(), Variant, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001293 }
1294
1295 case MCExpr::Unary: {
1296 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +00001297 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001298 if (!Sub)
Craig Topper353eda42014-04-24 06:44:33 +00001299 return nullptr;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001300 return MCUnaryExpr::create(UE->getOpcode(), Sub, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001301 }
1302
1303 case MCExpr::Binary: {
1304 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +00001305 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
1306 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001307
1308 if (!LHS && !RHS)
Craig Topper353eda42014-04-24 06:44:33 +00001309 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001310
Jim Grosbach4b905842013-09-20 23:08:21 +00001311 if (!LHS)
1312 LHS = BE->getLHS();
1313 if (!RHS)
1314 RHS = BE->getRHS();
Daniel Dunbar55f16672010-09-17 02:47:07 +00001315
Jim Grosbach13760bd2015-05-30 01:25:56 +00001316 return MCBinaryExpr::create(BE->getOpcode(), LHS, RHS, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001317 }
1318 }
Daniel Dunbarbaad46c2010-09-17 16:34:24 +00001319
Craig Toppera2886c22012-02-07 05:05:23 +00001320 llvm_unreachable("Invalid expression kind!");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001321}
1322
Michael Zuckerman763e60e2017-05-04 10:37:00 +00001323/// This function checks if the next token is <string> type or arithmetic.
1324/// string that begin with character '<' must end with character '>'.
1325/// otherwise it is arithmetics.
1326/// If the function returns a 'true' value,
1327/// the End argument will be filled with the last location pointed to the '>'
1328/// character.
1329
Craig Topper3da977b2018-09-25 19:37:35 +00001330/// There is a gap between the AltMacro's documentation and the single quote
1331/// implementation. GCC does not fully support this feature and so we will not
1332/// support it.
Michael Zuckerman763e60e2017-05-04 10:37:00 +00001333/// TODO: Adding single quote as a string.
Craig Topperd2aab832018-09-25 20:13:55 +00001334static bool isAltmacroString(SMLoc &StrLoc, SMLoc &EndLoc) {
Craig Topperc06ee832018-09-25 18:33:00 +00001335 assert((StrLoc.getPointer() != nullptr) &&
Michael Zuckerman763e60e2017-05-04 10:37:00 +00001336 "Argument to the function cannot be a NULL value");
1337 const char *CharPtr = StrLoc.getPointer();
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00001338 while ((*CharPtr != '>') && (*CharPtr != '\n') && (*CharPtr != '\r') &&
1339 (*CharPtr != '\0')) {
1340 if (*CharPtr == '!')
1341 CharPtr++;
Michael Zuckerman763e60e2017-05-04 10:37:00 +00001342 CharPtr++;
1343 }
1344 if (*CharPtr == '>') {
1345 EndLoc = StrLoc.getFromPointer(CharPtr + 1);
1346 return true;
1347 }
1348 return false;
1349}
1350
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001351/// creating a string without the escape characters '!'.
Craig Topperd2aab832018-09-25 20:13:55 +00001352static std::string altMacroString(StringRef AltMacroStr) {
1353 std::string Res;
Michael Zuckermanff298792017-05-10 14:00:57 +00001354 for (size_t Pos = 0; Pos < AltMacroStr.size(); Pos++) {
Michael Zuckerman1f1a9122017-05-10 13:08:11 +00001355 if (AltMacroStr[Pos] == '!')
1356 Pos++;
1357 Res += AltMacroStr[Pos];
1358 }
Craig Topperd2aab832018-09-25 20:13:55 +00001359 return Res;
Michael Zuckerman1f1a9122017-05-10 13:08:11 +00001360}
1361
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001362/// Parse an expression and return it.
Michael J. Spencer530ce852010-10-09 11:00:50 +00001363///
Jim Grosbachbd164242011-08-20 16:24:13 +00001364/// expr ::= expr &&,|| expr -> lowest.
1365/// expr ::= expr |,^,&,! expr
1366/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1367/// expr ::= expr <<,>> expr
1368/// expr ::= expr +,- expr
1369/// expr ::= expr *,/,% expr -> highest.
Chris Lattner7fdbce72009-06-22 06:32:03 +00001370/// expr ::= primaryexpr
1371///
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001372bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001373 // Parse the expression.
Craig Topper353eda42014-04-24 06:44:33 +00001374 Res = nullptr;
Nirav Dave7fd992a2018-08-16 16:31:14 +00001375 if (getTargetParser().parsePrimaryExpr(Res, EndLoc) ||
1376 parseBinOpRHS(1, Res, EndLoc))
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001377 return true;
1378
Daniel Dunbar55f16672010-09-17 02:47:07 +00001379 // As a special case, we support 'a op b @ modifier' by rewriting the
1380 // expression to include the modifier. This is inefficient, but in general we
1381 // expect users to use 'a@modifier op b'.
1382 if (Lexer.getKind() == AsmToken::At) {
1383 Lex();
1384
1385 if (Lexer.isNot(AsmToken::Identifier))
1386 return TokError("unexpected symbol modifier following '@'");
1387
1388 MCSymbolRefExpr::VariantKind Variant =
Jim Grosbach4b905842013-09-20 23:08:21 +00001389 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001390 if (Variant == MCSymbolRefExpr::VK_Invalid)
1391 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1392
Jim Grosbach4b905842013-09-20 23:08:21 +00001393 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001394 if (!ModifiedRes) {
1395 return TokError("invalid modifier '" + getTok().getIdentifier() +
1396 "' (no symbols present)");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001397 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001398
Daniel Dunbar55f16672010-09-17 02:47:07 +00001399 Res = ModifiedRes;
1400 Lex();
1401 }
1402
Nirav Dave6c0665e2018-04-30 19:22:40 +00001403 // Try to constant fold it up front, if possible. Do not exploit
1404 // assembler here.
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001405 int64_t Value;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001406 if (Res->evaluateAsAbsolute(Value))
1407 Res = MCConstantExpr::create(Value, getContext());
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001408
1409 return false;
Chris Lattner7fdbce72009-06-22 06:32:03 +00001410}
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001411
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001412bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Craig Topper353eda42014-04-24 06:44:33 +00001413 Res = nullptr;
Jim Grosbach4b905842013-09-20 23:08:21 +00001414 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
Daniel Dunbar7c82d562009-08-31 08:08:17 +00001415}
1416
Toma Tabacu7bc44dc2015-06-25 09:52:02 +00001417bool AsmParser::parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
1418 SMLoc &EndLoc) {
1419 if (parseParenExpr(Res, EndLoc))
1420 return true;
1421
1422 for (; ParenDepth > 0; --ParenDepth) {
1423 if (parseBinOpRHS(1, Res, EndLoc))
1424 return true;
1425
1426 // We don't Lex() the last RParen.
1427 // This is the same behavior as parseParenExpression().
1428 if (ParenDepth - 1 > 0) {
Nirav Davea645433c2016-07-18 15:24:03 +00001429 EndLoc = getTok().getEndLoc();
1430 if (parseToken(AsmToken::RParen,
1431 "expected ')' in parentheses expression"))
1432 return true;
Toma Tabacu7bc44dc2015-06-25 09:52:02 +00001433 }
1434 }
1435 return false;
1436}
1437
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001438bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
Daniel Dunbarf3636452009-08-31 08:07:22 +00001439 const MCExpr *Expr;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001440
Daniel Dunbar75630b32009-06-30 02:10:03 +00001441 SMLoc StartLoc = Lexer.getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001442 if (parseExpression(Expr))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001443 return true;
1444
Nirav Dave6c0665e2018-04-30 19:22:40 +00001445 if (!Expr->evaluateAsAbsolute(Res, getStreamer().getAssemblerPtr()))
Daniel Dunbar75630b32009-06-30 02:10:03 +00001446 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001447
1448 return false;
1449}
1450
David Majnemer0993e0b2015-10-26 03:15:34 +00001451static unsigned getDarwinBinOpPrecedence(AsmToken::TokenKind K,
1452 MCBinaryExpr::Opcode &Kind,
1453 bool ShouldUseLogicalShr) {
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001454 switch (K) {
Daniel Dunbar940cda22009-08-31 08:07:44 +00001455 default:
Jim Grosbach4b905842013-09-20 23:08:21 +00001456 return 0; // not a binop.
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001457
Jim Grosbach4b905842013-09-20 23:08:21 +00001458 // Lowest Precedence: &&, ||
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001459 case AsmToken::AmpAmp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001460 Kind = MCBinaryExpr::LAnd;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001461 return 1;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001462 case AsmToken::PipePipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001463 Kind = MCBinaryExpr::LOr;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001464 return 1;
1465
Jim Grosbach4b905842013-09-20 23:08:21 +00001466 // Low Precedence: |, &, ^
1467 //
1468 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001469 case AsmToken::Pipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001470 Kind = MCBinaryExpr::Or;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001471 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001472 case AsmToken::Caret:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001473 Kind = MCBinaryExpr::Xor;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001474 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001475 case AsmToken::Amp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001476 Kind = MCBinaryExpr::And;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001477 return 2;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001478
Jim Grosbach4b905842013-09-20 23:08:21 +00001479 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001480 case AsmToken::EqualEqual:
1481 Kind = MCBinaryExpr::EQ;
1482 return 3;
1483 case AsmToken::ExclaimEqual:
1484 case AsmToken::LessGreater:
1485 Kind = MCBinaryExpr::NE;
1486 return 3;
1487 case AsmToken::Less:
1488 Kind = MCBinaryExpr::LT;
1489 return 3;
1490 case AsmToken::LessEqual:
1491 Kind = MCBinaryExpr::LTE;
1492 return 3;
1493 case AsmToken::Greater:
1494 Kind = MCBinaryExpr::GT;
1495 return 3;
1496 case AsmToken::GreaterEqual:
1497 Kind = MCBinaryExpr::GTE;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001498 return 3;
1499
Jim Grosbach4b905842013-09-20 23:08:21 +00001500 // Intermediate Precedence: <<, >>
Jim Grosbachbd164242011-08-20 16:24:13 +00001501 case AsmToken::LessLess:
1502 Kind = MCBinaryExpr::Shl;
1503 return 4;
1504 case AsmToken::GreaterGreater:
David Majnemer0993e0b2015-10-26 03:15:34 +00001505 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
Jim Grosbachbd164242011-08-20 16:24:13 +00001506 return 4;
1507
Jim Grosbach4b905842013-09-20 23:08:21 +00001508 // High Intermediate Precedence: +, -
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001509 case AsmToken::Plus:
1510 Kind = MCBinaryExpr::Add;
Jim Grosbachbd164242011-08-20 16:24:13 +00001511 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001512 case AsmToken::Minus:
1513 Kind = MCBinaryExpr::Sub;
Jim Grosbachbd164242011-08-20 16:24:13 +00001514 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001515
Jim Grosbach4b905842013-09-20 23:08:21 +00001516 // Highest Precedence: *, /, %
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001517 case AsmToken::Star:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001518 Kind = MCBinaryExpr::Mul;
Jim Grosbachbd164242011-08-20 16:24:13 +00001519 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001520 case AsmToken::Slash:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001521 Kind = MCBinaryExpr::Div;
Jim Grosbachbd164242011-08-20 16:24:13 +00001522 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001523 case AsmToken::Percent:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001524 Kind = MCBinaryExpr::Mod;
Jim Grosbachbd164242011-08-20 16:24:13 +00001525 return 6;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001526 }
1527}
1528
David Majnemer0993e0b2015-10-26 03:15:34 +00001529static unsigned getGNUBinOpPrecedence(AsmToken::TokenKind K,
1530 MCBinaryExpr::Opcode &Kind,
1531 bool ShouldUseLogicalShr) {
1532 switch (K) {
1533 default:
1534 return 0; // not a binop.
1535
1536 // Lowest Precedence: &&, ||
1537 case AsmToken::AmpAmp:
1538 Kind = MCBinaryExpr::LAnd;
1539 return 2;
1540 case AsmToken::PipePipe:
1541 Kind = MCBinaryExpr::LOr;
1542 return 1;
1543
1544 // Low Precedence: ==, !=, <>, <, <=, >, >=
1545 case AsmToken::EqualEqual:
1546 Kind = MCBinaryExpr::EQ;
1547 return 3;
1548 case AsmToken::ExclaimEqual:
1549 case AsmToken::LessGreater:
1550 Kind = MCBinaryExpr::NE;
1551 return 3;
1552 case AsmToken::Less:
1553 Kind = MCBinaryExpr::LT;
1554 return 3;
1555 case AsmToken::LessEqual:
1556 Kind = MCBinaryExpr::LTE;
1557 return 3;
1558 case AsmToken::Greater:
1559 Kind = MCBinaryExpr::GT;
1560 return 3;
1561 case AsmToken::GreaterEqual:
1562 Kind = MCBinaryExpr::GTE;
1563 return 3;
1564
1565 // Low Intermediate Precedence: +, -
1566 case AsmToken::Plus:
1567 Kind = MCBinaryExpr::Add;
1568 return 4;
1569 case AsmToken::Minus:
1570 Kind = MCBinaryExpr::Sub;
1571 return 4;
1572
1573 // High Intermediate Precedence: |, &, ^
1574 //
1575 // FIXME: gas seems to support '!' as an infix operator?
1576 case AsmToken::Pipe:
1577 Kind = MCBinaryExpr::Or;
1578 return 5;
1579 case AsmToken::Caret:
1580 Kind = MCBinaryExpr::Xor;
1581 return 5;
1582 case AsmToken::Amp:
1583 Kind = MCBinaryExpr::And;
1584 return 5;
1585
1586 // Highest Precedence: *, /, %, <<, >>
1587 case AsmToken::Star:
1588 Kind = MCBinaryExpr::Mul;
1589 return 6;
1590 case AsmToken::Slash:
1591 Kind = MCBinaryExpr::Div;
1592 return 6;
1593 case AsmToken::Percent:
1594 Kind = MCBinaryExpr::Mod;
1595 return 6;
1596 case AsmToken::LessLess:
1597 Kind = MCBinaryExpr::Shl;
1598 return 6;
1599 case AsmToken::GreaterGreater:
1600 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1601 return 6;
1602 }
1603}
1604
1605unsigned AsmParser::getBinOpPrecedence(AsmToken::TokenKind K,
1606 MCBinaryExpr::Opcode &Kind) {
1607 bool ShouldUseLogicalShr = MAI.shouldUseLogicalShr();
1608 return IsDarwin ? getDarwinBinOpPrecedence(K, Kind, ShouldUseLogicalShr)
1609 : getGNUBinOpPrecedence(K, Kind, ShouldUseLogicalShr);
1610}
1611
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001612/// Parse all binary operators with precedence >= 'Precedence'.
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001613/// Res contains the LHS of the expression on input.
Jim Grosbach4b905842013-09-20 23:08:21 +00001614bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
Chris Lattner528d00b2010-01-15 19:28:38 +00001615 SMLoc &EndLoc) {
Chad Rosier9245e122017-01-19 20:06:32 +00001616 SMLoc StartLoc = Lexer.getLoc();
Eugene Zelenko33d7b762016-08-23 17:14:32 +00001617 while (true) {
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001618 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001619 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001620
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001621 // If the next token is lower precedence than we are allowed to eat, return
1622 // successfully with what we ate already.
1623 if (TokPrec < Precedence)
1624 return false;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001625
Sean Callanan686ed8d2010-01-19 20:22:31 +00001626 Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +00001627
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001628 // Eat the next primary expression.
Daniel Dunbarf3636452009-08-31 08:07:22 +00001629 const MCExpr *RHS;
Nirav Dave7fd992a2018-08-16 16:31:14 +00001630 if (getTargetParser().parsePrimaryExpr(RHS, EndLoc))
Jim Grosbach4b905842013-09-20 23:08:21 +00001631 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001632
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001633 // If BinOp binds less tightly with RHS than the operator after RHS, let
1634 // the pending operator take RHS as its LHS.
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001635 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001636 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Jim Grosbach4b905842013-09-20 23:08:21 +00001637 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1638 return true;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001639
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001640 // Merge LHS and RHS according to operator.
Chad Rosier9245e122017-01-19 20:06:32 +00001641 Res = MCBinaryExpr::create(Kind, Res, RHS, getContext(), StartLoc);
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001642 }
1643}
1644
Chris Lattner36e02122009-06-21 20:54:55 +00001645/// ParseStatement:
1646/// ::= EndOfStatement
Chris Lattnere5074c42009-06-22 01:29:09 +00001647/// ::= Label* Directive ...Operands... EndOfStatement
1648/// ::= Label* Identifier OperandList* EndOfStatement
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001649bool AsmParser::parseStatement(ParseStatementInfo &Info,
1650 MCAsmParserSemaCallback *SI) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001651 assert(!hasPendingError() && "parseStatement started with pending error");
Nirav Davefd910412016-06-17 16:06:17 +00001652 // Eat initial spaces and comments
1653 while (Lexer.is(AsmToken::Space))
1654 Lex();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001655 if (Lexer.is(AsmToken::EndOfStatement)) {
Nirav Davefd910412016-06-17 16:06:17 +00001656 // if this is a line comment we can drop it safely
Nirav Dave670109d2017-06-09 14:04:03 +00001657 if (getTok().getString().empty() || getTok().getString().front() == '\r' ||
Nirav Davefd910412016-06-17 16:06:17 +00001658 getTok().getString().front() == '\n')
1659 Out.AddBlankLine();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001660 Lex();
Chris Lattner36e02122009-06-21 20:54:55 +00001661 return false;
Chris Lattner36e02122009-06-21 20:54:55 +00001662 }
Nirav Davefd910412016-06-17 16:06:17 +00001663 // Statements always start with an identifier.
Sean Callanan936b0d32010-01-19 21:44:56 +00001664 AsmToken ID = getTok();
Daniel Dunbaree4465c2009-07-28 16:38:40 +00001665 SMLoc IDLoc = ID.getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001666 StringRef IDVal;
Kevin Enderby0510b482010-05-17 23:08:19 +00001667 int64_t LocalLabelVal = -1;
Nirav Davefd910412016-06-17 16:06:17 +00001668 if (Lexer.is(AsmToken::HashDirective))
Jim Grosbach4b905842013-09-20 23:08:21 +00001669 return parseCppHashLineFilenameComment(IDLoc);
Kevin Enderbyfa3c6f12010-12-24 00:12:02 +00001670 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderby0510b482010-05-17 23:08:19 +00001671 if (Lexer.is(AsmToken::Integer)) {
1672 LocalLabelVal = getTok().getIntVal();
1673 if (LocalLabelVal < 0) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001674 if (!TheCondState.Ignore) {
1675 Lex(); // always eat a token
1676 return Error(IDLoc, "unexpected token at start of statement");
1677 }
Kevin Enderby0510b482010-05-17 23:08:19 +00001678 IDVal = "";
Eli Bendersky88024712013-01-16 19:32:36 +00001679 } else {
Kevin Enderby0510b482010-05-17 23:08:19 +00001680 IDVal = getTok().getString();
1681 Lex(); // Consume the integer token to be used as an identifier token.
1682 if (Lexer.getKind() != AsmToken::Colon) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001683 if (!TheCondState.Ignore) {
1684 Lex(); // always eat a token
1685 return Error(IDLoc, "unexpected token at start of statement");
1686 }
Kevin Enderby0510b482010-05-17 23:08:19 +00001687 }
1688 }
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001689 } else if (Lexer.is(AsmToken::Dot)) {
1690 // Treat '.' as a valid identifier in this context.
1691 Lex();
1692 IDVal = ".";
Colin LeMahieu8a0453e2015-11-09 00:31:07 +00001693 } else if (Lexer.is(AsmToken::LCurly)) {
1694 // Treat '{' as a valid identifier in this context.
1695 Lex();
1696 IDVal = "{";
1697
1698 } else if (Lexer.is(AsmToken::RCurly)) {
1699 // Treat '}' as a valid identifier in this context.
1700 Lex();
1701 IDVal = "}";
Yonghong Song06ff6552017-09-12 17:55:23 +00001702 } else if (Lexer.is(AsmToken::Star) &&
1703 getTargetParser().starIsStartOfStatement()) {
1704 // Accept '*' as a valid start of statement.
1705 Lex();
1706 IDVal = "*";
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001707 } else if (parseIdentifier(IDVal)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001708 if (!TheCondState.Ignore) {
1709 Lex(); // always eat a token
1710 return Error(IDLoc, "unexpected token at start of statement");
1711 }
Chris Lattner926885c2010-04-17 18:14:27 +00001712 IDVal = "";
1713 }
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001714
Chris Lattner926885c2010-04-17 18:14:27 +00001715 // Handle conditional assembly here before checking for skipping. We
1716 // have to do this so that .endif isn't skipped in a ".if 0" block for
1717 // example.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001718 StringMap<DirectiveKind>::const_iterator DirKindIt =
Jim Grosbach4b905842013-09-20 23:08:21 +00001719 DirectiveKindMap.find(IDVal);
1720 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1721 ? DK_NO_DIRECTIVE
1722 : DirKindIt->getValue();
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001723 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001724 default:
1725 break;
1726 case DK_IF:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001727 case DK_IFEQ:
1728 case DK_IFGE:
1729 case DK_IFGT:
1730 case DK_IFLE:
1731 case DK_IFLT:
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00001732 case DK_IFNE:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001733 return parseDirectiveIf(IDLoc, DirKind);
Jim Grosbach4b905842013-09-20 23:08:21 +00001734 case DK_IFB:
1735 return parseDirectiveIfb(IDLoc, true);
1736 case DK_IFNB:
1737 return parseDirectiveIfb(IDLoc, false);
1738 case DK_IFC:
1739 return parseDirectiveIfc(IDLoc, true);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00001740 case DK_IFEQS:
Sid Manning51c35602015-03-18 14:20:54 +00001741 return parseDirectiveIfeqs(IDLoc, true);
Jim Grosbach4b905842013-09-20 23:08:21 +00001742 case DK_IFNC:
1743 return parseDirectiveIfc(IDLoc, false);
Sid Manning51c35602015-03-18 14:20:54 +00001744 case DK_IFNES:
1745 return parseDirectiveIfeqs(IDLoc, false);
Jim Grosbach4b905842013-09-20 23:08:21 +00001746 case DK_IFDEF:
1747 return parseDirectiveIfdef(IDLoc, true);
1748 case DK_IFNDEF:
1749 case DK_IFNOTDEF:
1750 return parseDirectiveIfdef(IDLoc, false);
1751 case DK_ELSEIF:
1752 return parseDirectiveElseIf(IDLoc);
1753 case DK_ELSE:
1754 return parseDirectiveElse(IDLoc);
1755 case DK_ENDIF:
1756 return parseDirectiveEndIf(IDLoc);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001757 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001758
Eli Bendersky88024712013-01-16 19:32:36 +00001759 // Ignore the statement if in the middle of inactive conditional
1760 // (e.g. ".if 0").
Chad Rosiereda70b32012-10-20 00:47:08 +00001761 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001762 eatToEndOfStatement();
Chris Lattner926885c2010-04-17 18:14:27 +00001763 return false;
1764 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001765
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001766 // FIXME: Recurse on local labels?
1767
1768 // See what kind of statement we have.
1769 switch (Lexer.getKind()) {
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001770 case AsmToken::Colon: {
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001771 if (!getTargetParser().isLabel(ID))
1772 break;
Nirav Davef43cc9f2016-10-10 15:24:54 +00001773 if (checkForValidSection())
1774 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00001775
Chris Lattner36e02122009-06-21 20:54:55 +00001776 // identifier ':' -> Label.
Sean Callanan686ed8d2010-01-19 20:22:31 +00001777 Lex();
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001778
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001779 // Diagnose attempt to use '.' as a label.
1780 if (IDVal == ".")
1781 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1782
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001783 // Diagnose attempt to use a variable as a label.
1784 //
1785 // FIXME: Diagnostics. Note the location of the definition as a label.
1786 // FIXME: This doesn't diagnose assignment to a symbol which has been
1787 // implicitly marked as external.
Kevin Enderby0510b482010-05-17 23:08:19 +00001788 MCSymbol *Sym;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001789 if (LocalLabelVal == -1) {
1790 if (ParsingInlineAsm && SI) {
Nico Weber67e715f2015-06-19 23:43:47 +00001791 StringRef RewrittenLabel =
1792 SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true);
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00001793 assert(!RewrittenLabel.empty() &&
Nico Weber67e715f2015-06-19 23:43:47 +00001794 "We should have an internal name here.");
Craig Topper7d5b2312015-10-10 05:25:02 +00001795 Info.AsmRewrites->emplace_back(AOK_Label, IDLoc, IDVal.size(),
1796 RewrittenLabel);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001797 IDVal = RewrittenLabel;
1798 }
Jim Grosbach6f482002015-05-18 18:43:14 +00001799 Sym = getContext().getOrCreateSymbol(IDVal);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001800 } else
Jim Grosbach6f482002015-05-18 18:43:14 +00001801 Sym = Ctx.createDirectionalLocalSymbol(LocalLabelVal);
Nirav Dave9263ae32016-08-02 19:17:54 +00001802 // End of Labels should be treated as end of line for lexing
1803 // purposes but that information is not available to the Lexer who
1804 // does not understand Labels. This may cause us to see a Hash
1805 // here instead of a preprocessor line comment.
1806 if (getTok().is(AsmToken::Hash)) {
1807 StringRef CommentStr = parseStringToEndOfStatement();
1808 Lexer.Lex();
1809 Lexer.UnLex(AsmToken(AsmToken::EndOfStatement, CommentStr));
1810 }
1811
Nirav Dave8ea792d2016-07-13 14:03:12 +00001812 // Consume any end of statement token, if present, to avoid spurious
1813 // AddBlankLine calls().
1814 if (getTok().is(AsmToken::EndOfStatement)) {
1815 Lex();
1816 }
1817
Maya Madhavanec1efe42018-09-20 05:11:42 +00001818 getTargetParser().doBeforeLabelEmit(Sym);
1819
Daniel Dunbare73b2672009-08-26 22:13:22 +00001820 // Emit the label.
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +00001821 if (!getTargetParser().isParsingInlineAsm())
Rafael Espindolabe991572017-02-10 15:13:12 +00001822 Out.EmitLabel(Sym, IDLoc);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001823
Kevin Enderbye7739d42011-12-09 18:09:40 +00001824 // If we are generating dwarf for assembly source files then gather the
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001825 // info to make a dwarf label entry for this label if needed.
Paul Robinson938d9a02018-03-22 15:48:01 +00001826 if (enabledGenDwarfForAssembly())
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001827 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1828 IDLoc);
Kevin Enderbye7739d42011-12-09 18:09:40 +00001829
Tim Northover1744d0a2013-10-25 12:49:50 +00001830 getTargetParser().onLabelParsed(Sym);
1831
Eli Friedman0f4871d2012-10-22 23:58:19 +00001832 return false;
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001833 }
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001834
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001835 case AsmToken::Equal:
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001836 if (!getTargetParser().equalIsAsmAssignment())
1837 break;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001838 // identifier '=' ... -> assignment statement
Sean Callanan686ed8d2010-01-19 20:22:31 +00001839 Lex();
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001840
Nirav Dave7fd992a2018-08-16 16:31:14 +00001841 return parseAssignment(IDVal, true);
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001842
1843 default: // Normal instruction or directive.
1844 break;
Chris Lattner36e02122009-06-21 20:54:55 +00001845 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001846
1847 // If macros are enabled, check to see if this is a macro instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00001848 if (areMacrosEnabled())
Rafael Espindola22c38a02018-02-14 16:34:27 +00001849 if (const MCAsmMacro *M = getContext().lookupMacro(IDVal)) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001850 return handleMacroEntry(M, IDLoc);
Eli Bendersky38274122013-01-14 23:22:36 +00001851 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001852
Michael J. Spencer530ce852010-10-09 11:00:50 +00001853 // Otherwise, we have a normal instruction or directive.
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001854
Eli Bendersky17233942013-01-15 22:59:42 +00001855 // Directives start with "."
Ana Pazos353f67a2018-08-25 01:34:32 +00001856 if (IDVal.startswith(".") && IDVal != ".") {
Eli Bendersky17233942013-01-15 22:59:42 +00001857 // There are several entities interested in parsing directives:
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001858 //
Eli Bendersky17233942013-01-15 22:59:42 +00001859 // 1. The target-specific assembly parser. Some directives are target
1860 // specific or may potentially behave differently on certain targets.
1861 // 2. Asm parser extensions. For example, platform-specific parsers
1862 // (like the ELF parser) register themselves as extensions.
1863 // 3. The generic directive parser implemented by this class. These are
1864 // all the directives that behave in a target and platform independent
1865 // manner, or at least have a default behavior that's shared between
1866 // all targets and platforms.
Akira Hatanakad3590752012-07-05 19:09:33 +00001867
Oliver Stannard21718282016-07-26 14:19:47 +00001868 getTargetParser().flushPendingInstructions(getStreamer());
1869
Nirav Dave2364748a2016-09-16 18:30:20 +00001870 SMLoc StartTokLoc = getTok().getLoc();
1871 bool TPDirectiveReturn = getTargetParser().ParseDirective(ID);
1872
1873 if (hasPendingError())
1874 return true;
1875 // Currently the return value should be true if we are
1876 // uninterested but as this is at odds with the standard parsing
1877 // convention (return true = error) we have instances of a parsed
1878 // directive that fails returning true as an error. Catch these
1879 // cases as best as possible errors here.
1880 if (TPDirectiveReturn && StartTokLoc != getTok().getLoc())
1881 return true;
1882 // Return if we did some parsing or believe we succeeded.
1883 if (!TPDirectiveReturn || StartTokLoc != getTok().getLoc())
Akira Hatanakad3590752012-07-05 19:09:33 +00001884 return false;
1885
Alp Tokercb402912014-01-24 17:20:08 +00001886 // Next, check the extension directive map to see if any extension has
Eli Bendersky17233942013-01-15 22:59:42 +00001887 // registered itself to parse this directive.
Jim Grosbach4b905842013-09-20 23:08:21 +00001888 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1889 ExtensionDirectiveMap.lookup(IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +00001890 if (Handler.first)
1891 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1892
1893 // Finally, if no one else is interested in this directive, it must be
1894 // generic and familiar to this class.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001895 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001896 default:
1897 break;
1898 case DK_SET:
1899 case DK_EQU:
1900 return parseDirectiveSet(IDVal, true);
1901 case DK_EQUIV:
1902 return parseDirectiveSet(IDVal, false);
1903 case DK_ASCII:
1904 return parseDirectiveAscii(IDVal, false);
1905 case DK_ASCIZ:
1906 case DK_STRING:
1907 return parseDirectiveAscii(IDVal, true);
1908 case DK_BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001909 case DK_DC_B:
1910 return parseDirectiveValue(IDVal, 1);
1911 case DK_DC:
1912 case DK_DC_W:
Jim Grosbach4b905842013-09-20 23:08:21 +00001913 case DK_SHORT:
1914 case DK_VALUE:
1915 case DK_2BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001916 return parseDirectiveValue(IDVal, 2);
Jim Grosbach4b905842013-09-20 23:08:21 +00001917 case DK_LONG:
1918 case DK_INT:
1919 case DK_4BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001920 case DK_DC_L:
1921 return parseDirectiveValue(IDVal, 4);
Jim Grosbach4b905842013-09-20 23:08:21 +00001922 case DK_QUAD:
1923 case DK_8BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001924 return parseDirectiveValue(IDVal, 8);
1925 case DK_DC_A:
Konstantin Zhuravlyovdc77b2e2017-04-17 17:41:25 +00001926 return parseDirectiveValue(
1927 IDVal, getContext().getAsmInfo()->getCodePointerSize());
David Woodhoused6de0d92014-02-01 16:20:59 +00001928 case DK_OCTA:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001929 return parseDirectiveOctaValue(IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001930 case DK_SINGLE:
1931 case DK_FLOAT:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001932 case DK_DC_S:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001933 return parseDirectiveRealValue(IDVal, APFloat::IEEEsingle());
Jim Grosbach4b905842013-09-20 23:08:21 +00001934 case DK_DOUBLE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001935 case DK_DC_D:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001936 return parseDirectiveRealValue(IDVal, APFloat::IEEEdouble());
Jim Grosbach4b905842013-09-20 23:08:21 +00001937 case DK_ALIGN: {
1938 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1939 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1940 }
1941 case DK_ALIGN32: {
1942 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1943 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1944 }
1945 case DK_BALIGN:
1946 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1947 case DK_BALIGNW:
1948 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1949 case DK_BALIGNL:
1950 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1951 case DK_P2ALIGN:
1952 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1953 case DK_P2ALIGNW:
1954 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1955 case DK_P2ALIGNL:
1956 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1957 case DK_ORG:
1958 return parseDirectiveOrg();
1959 case DK_FILL:
1960 return parseDirectiveFill();
1961 case DK_ZERO:
1962 return parseDirectiveZero();
1963 case DK_EXTERN:
1964 eatToEndOfStatement(); // .extern is the default, ignore it.
1965 return false;
1966 case DK_GLOBL:
1967 case DK_GLOBAL:
1968 return parseDirectiveSymbolAttribute(MCSA_Global);
1969 case DK_LAZY_REFERENCE:
1970 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1971 case DK_NO_DEAD_STRIP:
1972 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1973 case DK_SYMBOL_RESOLVER:
1974 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1975 case DK_PRIVATE_EXTERN:
1976 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1977 case DK_REFERENCE:
1978 return parseDirectiveSymbolAttribute(MCSA_Reference);
1979 case DK_WEAK_DEFINITION:
1980 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1981 case DK_WEAK_REFERENCE:
1982 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1983 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1984 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1985 case DK_COMM:
1986 case DK_COMMON:
1987 return parseDirectiveComm(/*IsLocal=*/false);
1988 case DK_LCOMM:
1989 return parseDirectiveComm(/*IsLocal=*/true);
1990 case DK_ABORT:
1991 return parseDirectiveAbort();
1992 case DK_INCLUDE:
1993 return parseDirectiveInclude();
1994 case DK_INCBIN:
1995 return parseDirectiveIncbin();
1996 case DK_CODE16:
1997 case DK_CODE16GCC:
Nirav Davefd910412016-06-17 16:06:17 +00001998 return TokError(Twine(IDVal) +
1999 " not currently supported for this target");
Jim Grosbach4b905842013-09-20 23:08:21 +00002000 case DK_REPT:
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00002001 return parseDirectiveRept(IDLoc, IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00002002 case DK_IRP:
2003 return parseDirectiveIrp(IDLoc);
2004 case DK_IRPC:
2005 return parseDirectiveIrpc(IDLoc);
2006 case DK_ENDR:
2007 return parseDirectiveEndr(IDLoc);
2008 case DK_BUNDLE_ALIGN_MODE:
2009 return parseDirectiveBundleAlignMode();
2010 case DK_BUNDLE_LOCK:
2011 return parseDirectiveBundleLock();
2012 case DK_BUNDLE_UNLOCK:
2013 return parseDirectiveBundleUnlock();
2014 case DK_SLEB128:
2015 return parseDirectiveLEB128(true);
2016 case DK_ULEB128:
2017 return parseDirectiveLEB128(false);
2018 case DK_SPACE:
2019 case DK_SKIP:
2020 return parseDirectiveSpace(IDVal);
2021 case DK_FILE:
2022 return parseDirectiveFile(IDLoc);
2023 case DK_LINE:
2024 return parseDirectiveLine();
2025 case DK_LOC:
2026 return parseDirectiveLoc();
2027 case DK_STABS:
2028 return parseDirectiveStabs();
Reid Kleckner2214ed82016-01-29 00:49:42 +00002029 case DK_CV_FILE:
2030 return parseDirectiveCVFile();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00002031 case DK_CV_FUNC_ID:
2032 return parseDirectiveCVFuncId();
2033 case DK_CV_INLINE_SITE_ID:
2034 return parseDirectiveCVInlineSiteId();
Reid Kleckner2214ed82016-01-29 00:49:42 +00002035 case DK_CV_LOC:
2036 return parseDirectiveCVLoc();
2037 case DK_CV_LINETABLE:
2038 return parseDirectiveCVLinetable();
David Majnemer6fcbd7e2016-01-29 19:24:12 +00002039 case DK_CV_INLINE_LINETABLE:
2040 return parseDirectiveCVInlineLinetable();
David Majnemer408b5e62016-02-05 01:55:49 +00002041 case DK_CV_DEF_RANGE:
2042 return parseDirectiveCVDefRange();
Reid Kleckner06d02d02018-09-07 21:30:52 +00002043 case DK_CV_STRING:
2044 return parseDirectiveCVString();
Reid Kleckner2214ed82016-01-29 00:49:42 +00002045 case DK_CV_STRINGTABLE:
2046 return parseDirectiveCVStringTable();
2047 case DK_CV_FILECHECKSUMS:
2048 return parseDirectiveCVFileChecksums();
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00002049 case DK_CV_FILECHECKSUM_OFFSET:
2050 return parseDirectiveCVFileChecksumOffset();
Reid Kleckner9cdd4df2017-10-11 21:24:33 +00002051 case DK_CV_FPO_DATA:
2052 return parseDirectiveCVFPOData();
Jim Grosbach4b905842013-09-20 23:08:21 +00002053 case DK_CFI_SECTIONS:
2054 return parseDirectiveCFISections();
2055 case DK_CFI_STARTPROC:
2056 return parseDirectiveCFIStartProc();
2057 case DK_CFI_ENDPROC:
2058 return parseDirectiveCFIEndProc();
2059 case DK_CFI_DEF_CFA:
2060 return parseDirectiveCFIDefCfa(IDLoc);
2061 case DK_CFI_DEF_CFA_OFFSET:
2062 return parseDirectiveCFIDefCfaOffset();
2063 case DK_CFI_ADJUST_CFA_OFFSET:
2064 return parseDirectiveCFIAdjustCfaOffset();
2065 case DK_CFI_DEF_CFA_REGISTER:
2066 return parseDirectiveCFIDefCfaRegister(IDLoc);
2067 case DK_CFI_OFFSET:
2068 return parseDirectiveCFIOffset(IDLoc);
2069 case DK_CFI_REL_OFFSET:
2070 return parseDirectiveCFIRelOffset(IDLoc);
2071 case DK_CFI_PERSONALITY:
2072 return parseDirectiveCFIPersonalityOrLsda(true);
2073 case DK_CFI_LSDA:
2074 return parseDirectiveCFIPersonalityOrLsda(false);
2075 case DK_CFI_REMEMBER_STATE:
2076 return parseDirectiveCFIRememberState();
2077 case DK_CFI_RESTORE_STATE:
2078 return parseDirectiveCFIRestoreState();
2079 case DK_CFI_SAME_VALUE:
2080 return parseDirectiveCFISameValue(IDLoc);
2081 case DK_CFI_RESTORE:
2082 return parseDirectiveCFIRestore(IDLoc);
2083 case DK_CFI_ESCAPE:
2084 return parseDirectiveCFIEscape();
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +00002085 case DK_CFI_RETURN_COLUMN:
2086 return parseDirectiveCFIReturnColumn(IDLoc);
Jim Grosbach4b905842013-09-20 23:08:21 +00002087 case DK_CFI_SIGNAL_FRAME:
2088 return parseDirectiveCFISignalFrame();
2089 case DK_CFI_UNDEFINED:
2090 return parseDirectiveCFIUndefined(IDLoc);
2091 case DK_CFI_REGISTER:
2092 return parseDirectiveCFIRegister(IDLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00002093 case DK_CFI_WINDOW_SAVE:
2094 return parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +00002095 case DK_MACROS_ON:
2096 case DK_MACROS_OFF:
2097 return parseDirectiveMacrosOnOff(IDVal);
2098 case DK_MACRO:
2099 return parseDirectiveMacro(IDLoc);
Michael Zuckerman56704612017-05-01 13:20:12 +00002100 case DK_ALTMACRO:
2101 case DK_NOALTMACRO:
2102 return parseDirectiveAltmacro(IDVal);
Nico Weber155dccd12014-07-24 17:08:39 +00002103 case DK_EXITM:
2104 return parseDirectiveExitMacro(IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00002105 case DK_ENDM:
2106 case DK_ENDMACRO:
2107 return parseDirectiveEndMacro(IDVal);
2108 case DK_PURGEM:
2109 return parseDirectivePurgeMacro(IDLoc);
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00002110 case DK_END:
2111 return parseDirectiveEnd(IDLoc);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00002112 case DK_ERR:
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00002113 return parseDirectiveError(IDLoc, false);
2114 case DK_ERROR:
2115 return parseDirectiveError(IDLoc, true);
Nico Weber404012b2014-07-24 16:26:06 +00002116 case DK_WARNING:
2117 return parseDirectiveWarning(IDLoc);
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002118 case DK_RELOC:
2119 return parseDirectiveReloc(IDLoc);
Petr Hosek4cb08ce2016-09-23 19:25:15 +00002120 case DK_DCB:
2121 case DK_DCB_W:
2122 return parseDirectiveDCB(IDVal, 2);
2123 case DK_DCB_B:
2124 return parseDirectiveDCB(IDVal, 1);
2125 case DK_DCB_D:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002126 return parseDirectiveRealDCB(IDVal, APFloat::IEEEdouble());
Petr Hosek4cb08ce2016-09-23 19:25:15 +00002127 case DK_DCB_L:
2128 return parseDirectiveDCB(IDVal, 4);
2129 case DK_DCB_S:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002130 return parseDirectiveRealDCB(IDVal, APFloat::IEEEsingle());
Petr Hosek731bb9c2016-08-23 21:34:53 +00002131 case DK_DC_X:
Petr Hosek4cb08ce2016-09-23 19:25:15 +00002132 case DK_DCB_X:
Petr Hosek731bb9c2016-08-23 21:34:53 +00002133 return TokError(Twine(IDVal) +
2134 " not currently supported for this target");
Petr Hosek85b2f672016-09-23 21:53:36 +00002135 case DK_DS:
2136 case DK_DS_W:
2137 return parseDirectiveDS(IDVal, 2);
2138 case DK_DS_B:
2139 return parseDirectiveDS(IDVal, 1);
2140 case DK_DS_D:
2141 return parseDirectiveDS(IDVal, 8);
2142 case DK_DS_L:
2143 case DK_DS_S:
2144 return parseDirectiveDS(IDVal, 4);
2145 case DK_DS_P:
2146 case DK_DS_X:
2147 return parseDirectiveDS(IDVal, 12);
Coby Tayree01e53202017-10-02 14:36:31 +00002148 case DK_PRINT:
2149 return parseDirectivePrint(IDLoc);
Peter Collingbourne3e227332018-07-17 22:17:18 +00002150 case DK_ADDRSIG:
2151 return parseDirectiveAddrsig();
2152 case DK_ADDRSIG_SYM:
2153 return parseDirectiveAddrsigSym();
Eli Friedman20b02642010-07-19 04:17:25 +00002154 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002155
Jim Grosbach758e0cc2012-05-01 18:38:27 +00002156 return Error(IDLoc, "unknown directive");
Chris Lattnere5074c42009-06-22 01:29:09 +00002157 }
Chris Lattner36e02122009-06-21 20:54:55 +00002158
Chad Rosierc7f552c2013-02-12 21:33:51 +00002159 // __asm _emit or __asm __emit
2160 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
2161 IDVal == "_EMIT" || IDVal == "__EMIT"))
Jim Grosbach4b905842013-09-20 23:08:21 +00002162 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
Chad Rosierc7f552c2013-02-12 21:33:51 +00002163
2164 // __asm align
2165 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
Jim Grosbach4b905842013-09-20 23:08:21 +00002166 return parseDirectiveMSAlign(IDLoc, Info);
Eli Friedman0f4871d2012-10-22 23:58:19 +00002167
Coby Tayree3847be92017-04-04 17:57:23 +00002168 if (ParsingInlineAsm && (IDVal == "even" || IDVal == "EVEN"))
Michael Zuckerman02ecd432015-12-13 17:07:23 +00002169 Info.AsmRewrites->emplace_back(AOK_EVEN, IDLoc, 4);
Nirav Davef43cc9f2016-10-10 15:24:54 +00002170 if (checkForValidSection())
2171 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00002172
Chris Lattner7cbfa442010-05-19 23:34:33 +00002173 // Canonicalize the opcode to lower case.
Eli Bendersky88024712013-01-16 19:32:36 +00002174 std::string OpcodeStr = IDVal.lower();
Chad Rosierf0e87202012-10-25 20:41:34 +00002175 ParseInstructionInfo IInfo(Info.AsmRewrites);
Nirav Dave2364748a2016-09-16 18:30:20 +00002176 bool ParseHadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, ID,
2177 Info.ParsedOperands);
2178 Info.ParseError = ParseHadError;
Chris Lattnere5074c42009-06-22 01:29:09 +00002179
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002180 // Dump the parsed representation, if requested.
2181 if (getShowParsedOperands()) {
2182 SmallString<256> Str;
2183 raw_svector_ostream OS(Str);
2184 OS << "parsed instruction: [";
Eli Friedman0f4871d2012-10-22 23:58:19 +00002185 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002186 if (i != 0)
2187 OS << ", ";
Eli Friedman0f4871d2012-10-22 23:58:19 +00002188 Info.ParsedOperands[i]->print(OS);
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002189 }
2190 OS << "]";
2191
Jim Grosbach4b905842013-09-20 23:08:21 +00002192 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002193 }
2194
Nirav Dave2364748a2016-09-16 18:30:20 +00002195 // Fail even if ParseInstruction erroneously returns false.
2196 if (hasPendingError() || ParseHadError)
2197 return true;
2198
Oliver Stannard8b273082014-06-19 15:52:37 +00002199 // If we are generating dwarf for the current section then generate a .loc
2200 // directive for the instruction.
Paul Robinson938d9a02018-03-22 15:48:01 +00002201 if (!ParseHadError && enabledGenDwarfForAssembly() &&
Oliver Stannard8b273082014-06-19 15:52:37 +00002202 getContext().getGenDwarfSectionSyms().count(
Eric Christopher445c9522016-10-14 05:47:37 +00002203 getStreamer().getCurrentSectionOnly())) {
Saleem Abdulrasool4d6ed7c2014-12-24 06:32:43 +00002204 unsigned Line;
2205 if (ActiveMacros.empty())
2206 Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
2207 else
Frederic Riss16238d92015-06-25 21:57:33 +00002208 Line = SrcMgr.FindLineNumber(ActiveMacros.front()->InstantiationLoc,
2209 ActiveMacros.front()->ExitBuffer);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002210
Eli Bendersky88024712013-01-16 19:32:36 +00002211 // If we previously parsed a cpp hash file line comment then make sure the
2212 // current Dwarf File is for the CppHashFilename if not then emit the
2213 // Dwarf File table for it and adjust the line number for the .loc.
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00002214 if (!CppHashInfo.Filename.empty()) {
David Blaikiec714ef42014-03-17 01:52:11 +00002215 unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
Tim Northoverc0bef992016-04-13 19:46:54 +00002216 0, StringRef(), CppHashInfo.Filename);
David Blaikiec714ef42014-03-17 01:52:11 +00002217 getContext().setGenDwarfFileNumber(FileNumber);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002218
Graydon Hoare54fe2082018-04-07 00:44:02 +00002219 unsigned CppHashLocLineNo =
2220 SrcMgr.FindLineNumber(CppHashInfo.Loc, CppHashInfo.Buf);
Tim Northoverc0bef992016-04-13 19:46:54 +00002221 Line = CppHashInfo.LineNumber - 1 + (Line - CppHashLocLineNo);
Eli Bendersky88024712013-01-16 19:32:36 +00002222 }
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002223
Jim Grosbach4b905842013-09-20 23:08:21 +00002224 getStreamer().EmitDwarfLocDirective(
2225 getContext().getGenDwarfFileNumber(), Line, 0,
2226 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
2227 StringRef());
Kevin Enderby6469fc22011-11-01 22:27:22 +00002228 }
2229
Daniel Dunbarce0c1e12010-05-04 00:33:07 +00002230 // If parsing succeeded, match the instruction.
Nirav Dave2364748a2016-09-16 18:30:20 +00002231 if (!ParseHadError) {
Tim Northover26bb14e2014-08-18 11:49:42 +00002232 uint64_t ErrorInfo;
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +00002233 if (getTargetParser().MatchAndEmitInstruction(
2234 IDLoc, Info.Opcode, Info.ParsedOperands, Out, ErrorInfo,
2235 getTargetParser().isParsingInlineAsm()))
Nirav Dave2364748a2016-09-16 18:30:20 +00002236 return true;
Chad Rosier49963552012-10-13 00:26:04 +00002237 }
Chris Lattnera2a9d162010-09-11 16:18:25 +00002238 return false;
Chris Lattnerb0133452009-06-21 20:16:42 +00002239}
Chris Lattnerbedf6c22009-06-24 04:43:34 +00002240
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00002241// Parse and erase curly braces marking block start/end
Sam Cleggf009da22018-04-19 22:00:53 +00002242bool
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00002243AsmParser::parseCurlyBlockScope(SmallVectorImpl<AsmRewrite> &AsmStrRewrites) {
2244 // Identify curly brace marking block start/end
2245 if (Lexer.isNot(AsmToken::LCurly) && Lexer.isNot(AsmToken::RCurly))
2246 return false;
2247
2248 SMLoc StartLoc = Lexer.getLoc();
2249 Lex(); // Eat the brace
2250 if (Lexer.is(AsmToken::EndOfStatement))
2251 Lex(); // Eat EndOfStatement following the brace
2252
2253 // Erase the block start/end brace from the output asm string
2254 AsmStrRewrites.emplace_back(AOK_Skip, StartLoc, Lexer.getLoc().getPointer() -
2255 StartLoc.getPointer());
2256 return true;
2257}
2258
Jim Grosbach4b905842013-09-20 23:08:21 +00002259/// parseCppHashLineFilenameComment as this:
Kevin Enderby72553612011-09-13 23:45:18 +00002260/// ::= # number "filename"
Craig Topper3c76c522015-09-20 23:35:59 +00002261bool AsmParser::parseCppHashLineFilenameComment(SMLoc L) {
Kevin Enderby72553612011-09-13 23:45:18 +00002262 Lex(); // Eat the hash token.
Nirav Davefd910412016-06-17 16:06:17 +00002263 // Lexer only ever emits HashDirective if it fully formed if it's
2264 // done the checking already so this is an internal error.
2265 assert(getTok().is(AsmToken::Integer) &&
2266 "Lexing Cpp line comment: Expected Integer");
Kevin Enderby72553612011-09-13 23:45:18 +00002267 int64_t LineNumber = getTok().getIntVal();
Kevin Enderby72553612011-09-13 23:45:18 +00002268 Lex();
Nirav Davefd910412016-06-17 16:06:17 +00002269 assert(getTok().is(AsmToken::String) &&
2270 "Lexing Cpp line comment: Expected String");
Kevin Enderby72553612011-09-13 23:45:18 +00002271 StringRef Filename = getTok().getString();
Nirav Davefd910412016-06-17 16:06:17 +00002272 Lex();
Nirav Dave2364748a2016-09-16 18:30:20 +00002273
Kevin Enderby72553612011-09-13 23:45:18 +00002274 // Get rid of the enclosing quotes.
Jim Grosbach4b905842013-09-20 23:08:21 +00002275 Filename = Filename.substr(1, Filename.size() - 2);
Kevin Enderby72553612011-09-13 23:45:18 +00002276
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002277 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
Tim Northoverc0bef992016-04-13 19:46:54 +00002278 CppHashInfo.Loc = L;
2279 CppHashInfo.Filename = Filename;
2280 CppHashInfo.LineNumber = LineNumber;
2281 CppHashInfo.Buf = CurBuffer;
Kevin Enderby72553612011-09-13 23:45:18 +00002282 return false;
2283}
2284
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002285/// will use the last parsed cpp hash line filename comment
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002286/// for the Filename and LineNo if any in the diagnostic.
2287void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002288 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002289 raw_ostream &OS = errs();
2290
2291 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
Craig Topper3c76c522015-09-20 23:35:59 +00002292 SMLoc DiagLoc = Diag.getLoc();
Alp Tokera55b95b2014-07-06 10:33:31 +00002293 unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2294 unsigned CppHashBuf =
Tim Northoverc0bef992016-04-13 19:46:54 +00002295 Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashInfo.Loc);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002296
Jim Grosbach4b905842013-09-20 23:08:21 +00002297 // Like SourceMgr::printMessage() we need to print the include stack if any
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002298 // before printing the message.
Alp Tokera55b95b2014-07-06 10:33:31 +00002299 unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2300 if (!Parser->SavedDiagHandler && DiagCurBuffer &&
2301 DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002302 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
2303 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002304 }
2305
Eric Christophera7c32732012-12-18 00:30:54 +00002306 // If we have not parsed a cpp hash line filename comment or the source
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002307 // manager changed or buffer changed (like in a nested include) then just
2308 // print the normal diagnostic using its Filename and LineNo.
Tim Northoverc0bef992016-04-13 19:46:54 +00002309 if (!Parser->CppHashInfo.LineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002310 DiagBuf != CppHashBuf) {
Benjamin Kramer47f5e302011-10-16 10:48:29 +00002311 if (Parser->SavedDiagHandler)
2312 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
2313 else
Craig Topper353eda42014-04-24 06:44:33 +00002314 Diag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002315 return;
2316 }
2317
Eric Christophera7c32732012-12-18 00:30:54 +00002318 // Use the CppHashFilename and calculate a line number based on the
Tim Northoverc0bef992016-04-13 19:46:54 +00002319 // CppHashInfo.Loc and CppHashInfo.LineNumber relative to this Diag's SMLoc
2320 // for the diagnostic.
2321 const std::string &Filename = Parser->CppHashInfo.Filename;
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002322
2323 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
2324 int CppHashLocLineNo =
Tim Northoverc0bef992016-04-13 19:46:54 +00002325 Parser->SrcMgr.FindLineNumber(Parser->CppHashInfo.Loc, CppHashBuf);
Jim Grosbach4b905842013-09-20 23:08:21 +00002326 int LineNo =
Tim Northoverc0bef992016-04-13 19:46:54 +00002327 Parser->CppHashInfo.LineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002328
Jim Grosbach4b905842013-09-20 23:08:21 +00002329 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
2330 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
Chris Lattner72845262011-10-16 05:47:55 +00002331 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002332
Benjamin Kramer47f5e302011-10-16 10:48:29 +00002333 if (Parser->SavedDiagHandler)
2334 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
2335 else
Craig Topper353eda42014-04-24 06:44:33 +00002336 NewDiag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002337}
2338
Rafael Espindola2c064482012-08-21 18:29:30 +00002339// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
2340// difference being that that function accepts '@' as part of identifiers and
2341// we can't do that. AsmLexer.cpp should probably be changed to handle
2342// '@' as a special case when needed.
2343static bool isIdentifierChar(char c) {
Guy Benyei83c74e92013-02-12 21:21:59 +00002344 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
2345 c == '.';
Rafael Espindola2c064482012-08-21 18:29:30 +00002346}
2347
Rafael Espindola34b9c512012-06-03 23:57:14 +00002348bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00002349 ArrayRef<MCAsmMacroParameter> Parameters,
Toma Tabacu217116e2015-04-27 10:50:29 +00002350 ArrayRef<MCAsmMacroArgument> A,
Craig Topper3c76c522015-09-20 23:35:59 +00002351 bool EnableAtPseudoVariable, SMLoc L) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00002352 unsigned NParameters = Parameters.size();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002353 bool HasVararg = NParameters ? Parameters.back().Vararg : false;
Benjamin Kramer513e7442014-02-20 13:36:32 +00002354 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
Rafael Espindola1134ab232011-06-05 02:43:45 +00002355 return Error(L, "Wrong number of arguments");
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002356
Preston Gurd05500642012-09-19 20:36:12 +00002357 // A macro without parameters is handled differently on Darwin:
2358 // gas accepts no arguments and does no substitutions
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002359 while (!Body.empty()) {
2360 // Scan for the next substitution.
2361 std::size_t End = Body.size(), Pos = 0;
2362 for (; Pos != End; ++Pos) {
2363 // Check for a substitution or escape.
Benjamin Kramer513e7442014-02-20 13:36:32 +00002364 if (IsDarwin && !NParameters) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00002365 // This macro has no parameters, look for $0, $1, etc.
2366 if (Body[Pos] != '$' || Pos + 1 == End)
2367 continue;
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002368
Rafael Espindola1134ab232011-06-05 02:43:45 +00002369 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00002370 if (Next == '$' || Next == 'n' ||
2371 isdigit(static_cast<unsigned char>(Next)))
Rafael Espindola1134ab232011-06-05 02:43:45 +00002372 break;
2373 } else {
2374 // This macro has parameters, look for \foo, \bar, etc.
2375 if (Body[Pos] == '\\' && Pos + 1 != End)
2376 break;
2377 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002378 }
2379
2380 // Add the prefix.
2381 OS << Body.slice(0, Pos);
2382
2383 // Check if we reached the end.
2384 if (Pos == End)
2385 break;
2386
Benjamin Kramer513e7442014-02-20 13:36:32 +00002387 if (IsDarwin && !NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002388 switch (Body[Pos + 1]) {
2389 // $$ => $
Rafael Espindola1134ab232011-06-05 02:43:45 +00002390 case '$':
2391 OS << '$';
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002392 break;
2393
Jim Grosbach4b905842013-09-20 23:08:21 +00002394 // $n => number of arguments
Rafael Espindola1134ab232011-06-05 02:43:45 +00002395 case 'n':
2396 OS << A.size();
2397 break;
2398
Jim Grosbach4b905842013-09-20 23:08:21 +00002399 // $[0-9] => argument
Rafael Espindola1134ab232011-06-05 02:43:45 +00002400 default: {
2401 // Missing arguments are ignored.
Jim Grosbach4b905842013-09-20 23:08:21 +00002402 unsigned Index = Body[Pos + 1] - '0';
Rafael Espindola1134ab232011-06-05 02:43:45 +00002403 if (Index >= A.size())
2404 break;
2405
2406 // Otherwise substitute with the token values, with spaces eliminated.
Craig Topper84008482015-10-10 05:38:14 +00002407 for (const AsmToken &Token : A[Index])
2408 OS << Token.getString();
Rafael Espindola1134ab232011-06-05 02:43:45 +00002409 break;
2410 }
2411 }
2412 Pos += 2;
2413 } else {
2414 unsigned I = Pos + 1;
Toma Tabacu217116e2015-04-27 10:50:29 +00002415
2416 // Check for the \@ pseudo-variable.
2417 if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End)
Rafael Espindola1134ab232011-06-05 02:43:45 +00002418 ++I;
Toma Tabacu217116e2015-04-27 10:50:29 +00002419 else
2420 while (isIdentifierChar(Body[I]) && I + 1 != End)
2421 ++I;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002422
Jim Grosbach4b905842013-09-20 23:08:21 +00002423 const char *Begin = Body.data() + Pos + 1;
2424 StringRef Argument(Begin, I - (Pos + 1));
Rafael Espindola1134ab232011-06-05 02:43:45 +00002425 unsigned Index = 0;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002426
Toma Tabacu217116e2015-04-27 10:50:29 +00002427 if (Argument == "@") {
2428 OS << NumOfMacroInstantiations;
2429 Pos += 2;
Preston Gurd05500642012-09-19 20:36:12 +00002430 } else {
Toma Tabacu217116e2015-04-27 10:50:29 +00002431 for (; Index < NParameters; ++Index)
2432 if (Parameters[Index].Name == Argument)
2433 break;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002434
Toma Tabacu217116e2015-04-27 10:50:29 +00002435 if (Index == NParameters) {
2436 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
2437 Pos += 3;
2438 else {
2439 OS << '\\' << Argument;
2440 Pos = I;
2441 }
2442 } else {
2443 bool VarargParameter = HasVararg && Index == (NParameters - 1);
Craig Topper84008482015-10-10 05:38:14 +00002444 for (const AsmToken &Token : A[Index])
Michael Zuckerman56704612017-05-01 13:20:12 +00002445 // For altmacro mode, you can write '%expr'.
2446 // The prefix '%' evaluates the expression 'expr'
Craig Topper3da977b2018-09-25 19:37:35 +00002447 // and uses the result as a string (e.g. replace %(1+2) with the
2448 // string "3").
Michael Zuckerman56704612017-05-01 13:20:12 +00002449 // Here, we identify the integer token which is the result of the
Craig Topper3da977b2018-09-25 19:37:35 +00002450 // absolute expression evaluation and replace it with its string
2451 // representation.
Craig Topperc81aff72018-09-25 20:55:55 +00002452 if (AltMacroMode && Token.getString().front() == '%' &&
Craig Topper3da977b2018-09-25 19:37:35 +00002453 Token.is(AsmToken::Integer))
Michael Zuckerman56704612017-05-01 13:20:12 +00002454 // Emit an integer value to the buffer.
2455 OS << Token.getIntVal();
Michael Zuckerman1f1a9122017-05-10 13:08:11 +00002456 // Only Token that was validated as a string and begins with '<'
2457 // is considered altMacroString!!!
Craig Topperc81aff72018-09-25 20:55:55 +00002458 else if (AltMacroMode && Token.getString().front() == '<' &&
Michael Zuckerman1f1a9122017-05-10 13:08:11 +00002459 Token.is(AsmToken::String)) {
Craig Topperd2aab832018-09-25 20:13:55 +00002460 OS << altMacroString(Token.getStringContents());
Michael Zuckerman1f1a9122017-05-10 13:08:11 +00002461 }
Toma Tabacu217116e2015-04-27 10:50:29 +00002462 // We expect no quotes around the string's contents when
2463 // parsing for varargs.
Michael Zuckerman56704612017-05-01 13:20:12 +00002464 else if (Token.isNot(AsmToken::String) || VarargParameter)
Craig Topper84008482015-10-10 05:38:14 +00002465 OS << Token.getString();
Toma Tabacu217116e2015-04-27 10:50:29 +00002466 else
Craig Topper84008482015-10-10 05:38:14 +00002467 OS << Token.getStringContents();
Toma Tabacu217116e2015-04-27 10:50:29 +00002468
2469 Pos += 1 + Argument.size();
2470 }
Preston Gurd05500642012-09-19 20:36:12 +00002471 }
Rafael Espindola1134ab232011-06-05 02:43:45 +00002472 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002473 // Update the scan point.
Rafael Espindola1134ab232011-06-05 02:43:45 +00002474 Body = Body.substr(Pos);
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002475 }
Daniel Dunbar43235712010-07-18 18:54:11 +00002476
Rafael Espindola1134ab232011-06-05 02:43:45 +00002477 return false;
2478}
Daniel Dunbar43235712010-07-18 18:54:11 +00002479
Nico Weber2a8f9222014-07-24 16:29:04 +00002480MacroInstantiation::MacroInstantiation(SMLoc IL, int EB, SMLoc EL,
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002481 size_t CondStackDepth)
Rafael Espindolaf43a94e2014-08-17 22:48:55 +00002482 : InstantiationLoc(IL), ExitBuffer(EB), ExitLoc(EL),
Nico Weber155dccd12014-07-24 17:08:39 +00002483 CondStackDepth(CondStackDepth) {}
Daniel Dunbar43235712010-07-18 18:54:11 +00002484
Jim Grosbach4b905842013-09-20 23:08:21 +00002485static bool isOperator(AsmToken::TokenKind kind) {
2486 switch (kind) {
2487 default:
2488 return false;
2489 case AsmToken::Plus:
2490 case AsmToken::Minus:
2491 case AsmToken::Tilde:
2492 case AsmToken::Slash:
2493 case AsmToken::Star:
2494 case AsmToken::Dot:
2495 case AsmToken::Equal:
2496 case AsmToken::EqualEqual:
2497 case AsmToken::Pipe:
2498 case AsmToken::PipePipe:
2499 case AsmToken::Caret:
2500 case AsmToken::Amp:
2501 case AsmToken::AmpAmp:
2502 case AsmToken::Exclaim:
2503 case AsmToken::ExclaimEqual:
Jim Grosbach4b905842013-09-20 23:08:21 +00002504 case AsmToken::Less:
2505 case AsmToken::LessEqual:
2506 case AsmToken::LessLess:
2507 case AsmToken::LessGreater:
2508 case AsmToken::Greater:
2509 case AsmToken::GreaterEqual:
2510 case AsmToken::GreaterGreater:
2511 return true;
Preston Gurd05500642012-09-19 20:36:12 +00002512 }
2513}
2514
David Majnemer16252452014-01-29 00:07:39 +00002515namespace {
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002516
David Majnemer16252452014-01-29 00:07:39 +00002517class AsmLexerSkipSpaceRAII {
2518public:
2519 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
2520 Lexer.setSkipSpace(SkipSpace);
2521 }
2522
2523 ~AsmLexerSkipSpaceRAII() {
2524 Lexer.setSkipSpace(true);
2525 }
2526
2527private:
2528 AsmLexer &Lexer;
2529};
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002530
2531} // end anonymous namespace
David Majnemer16252452014-01-29 00:07:39 +00002532
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002533bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
2534
2535 if (Vararg) {
2536 if (Lexer.isNot(AsmToken::EndOfStatement)) {
2537 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002538 MA.emplace_back(AsmToken::String, Str);
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002539 }
2540 return false;
2541 }
2542
Rafael Espindola768b41c2012-06-15 14:02:34 +00002543 unsigned ParenLevel = 0;
Preston Gurd05500642012-09-19 20:36:12 +00002544
David Majnemer16252452014-01-29 00:07:39 +00002545 // Darwin doesn't use spaces to delmit arguments.
2546 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
Rafael Espindola768b41c2012-06-15 14:02:34 +00002547
Scott Egertona1fa68a2016-02-11 13:48:49 +00002548 bool SpaceEaten;
2549
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002550 while (true) {
Scott Egertona1fa68a2016-02-11 13:48:49 +00002551 SpaceEaten = false;
David Majnemer16252452014-01-29 00:07:39 +00002552 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002553 return TokError("unexpected token in macro instantiation");
Preston Gurd05500642012-09-19 20:36:12 +00002554
Scott Egertona1fa68a2016-02-11 13:48:49 +00002555 if (ParenLevel == 0) {
Preston Gurd05500642012-09-19 20:36:12 +00002556
Scott Egertona1fa68a2016-02-11 13:48:49 +00002557 if (Lexer.is(AsmToken::Comma))
2558 break;
2559
2560 if (Lexer.is(AsmToken::Space)) {
2561 SpaceEaten = true;
Nirav Dave1180e6892016-06-02 17:15:05 +00002562 Lexer.Lex(); // Eat spaces
Scott Egertona1fa68a2016-02-11 13:48:49 +00002563 }
Preston Gurd05500642012-09-19 20:36:12 +00002564
2565 // Spaces can delimit parameters, but could also be part an expression.
2566 // If the token after a space is an operator, add the token and the next
2567 // one into this argument
David Majnemer91fc4c22014-01-29 18:57:46 +00002568 if (!IsDarwin) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002569 if (isOperator(Lexer.getKind())) {
Scott Egertona1fa68a2016-02-11 13:48:49 +00002570 MA.push_back(getTok());
Nirav Dave1180e6892016-06-02 17:15:05 +00002571 Lexer.Lex();
Preston Gurd05500642012-09-19 20:36:12 +00002572
Scott Egertona1fa68a2016-02-11 13:48:49 +00002573 // Whitespace after an operator can be ignored.
2574 if (Lexer.is(AsmToken::Space))
Nirav Dave1180e6892016-06-02 17:15:05 +00002575 Lexer.Lex();
Scott Egertona1fa68a2016-02-11 13:48:49 +00002576
2577 continue;
Preston Gurd05500642012-09-19 20:36:12 +00002578 }
2579 }
Scott Egertona1fa68a2016-02-11 13:48:49 +00002580 if (SpaceEaten)
2581 break;
Preston Gurd05500642012-09-19 20:36:12 +00002582 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002583
Jim Grosbach4b905842013-09-20 23:08:21 +00002584 // handleMacroEntry relies on not advancing the lexer here
Rafael Espindola768b41c2012-06-15 14:02:34 +00002585 // to be able to fill in the remaining default parameter values
2586 if (Lexer.is(AsmToken::EndOfStatement))
2587 break;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002588
2589 // Adjust the current parentheses level.
2590 if (Lexer.is(AsmToken::LParen))
2591 ++ParenLevel;
2592 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
2593 --ParenLevel;
2594
2595 // Append the token to the current argument list.
2596 MA.push_back(getTok());
Nirav Dave1180e6892016-06-02 17:15:05 +00002597 Lexer.Lex();
Rafael Espindola768b41c2012-06-15 14:02:34 +00002598 }
Preston Gurd05500642012-09-19 20:36:12 +00002599
Rafael Espindola768b41c2012-06-15 14:02:34 +00002600 if (ParenLevel != 0)
Rafael Espindola3e5eb422012-08-21 15:55:04 +00002601 return TokError("unbalanced parentheses in macro argument");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002602 return false;
2603}
2604
2605// Parse the macro instantiation arguments.
Jim Grosbach4b905842013-09-20 23:08:21 +00002606bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
Vladimir Medic9bad0d332013-08-20 13:33:18 +00002607 MCAsmMacroArguments &A) {
Rafael Espindola768b41c2012-06-15 14:02:34 +00002608 const unsigned NParameters = M ? M->Parameters.size() : 0;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002609 bool NamedParametersFound = false;
2610 SmallVector<SMLoc, 4> FALocs;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002611
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002612 A.resize(NParameters);
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002613 FALocs.resize(NParameters);
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002614
Rafael Espindola768b41c2012-06-15 14:02:34 +00002615 // Parse two kinds of macro invocations:
2616 // - macros defined without any parameters accept an arbitrary number of them
2617 // - macros defined with parameters accept at most that many of them
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002618 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002619 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
2620 ++Parameter) {
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002621 SMLoc IDLoc = Lexer.getLoc();
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002622 MCAsmMacroParameter FA;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002623
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002624 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00002625 if (parseIdentifier(FA.Name))
2626 return Error(IDLoc, "invalid argument identifier for formal argument");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002627
Nirav Dave2364748a2016-09-16 18:30:20 +00002628 if (Lexer.isNot(AsmToken::Equal))
2629 return TokError("expected '=' after formal parameter identifier");
2630
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002631 Lex();
2632
2633 NamedParametersFound = true;
2634 }
Michael Zuckerman56704612017-05-01 13:20:12 +00002635 bool Vararg = HasVararg && Parameter == (NParameters - 1);
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002636
Nirav Dave2364748a2016-09-16 18:30:20 +00002637 if (NamedParametersFound && FA.Name.empty())
2638 return Error(IDLoc, "cannot mix positional and keyword arguments");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002639
Michael Zuckerman763e60e2017-05-04 10:37:00 +00002640 SMLoc StrLoc = Lexer.getLoc();
2641 SMLoc EndLoc;
Craig Topperc81aff72018-09-25 20:55:55 +00002642 if (AltMacroMode && Lexer.is(AsmToken::Percent)) {
Craig Topper3da977b2018-09-25 19:37:35 +00002643 const MCExpr *AbsoluteExp;
2644 int64_t Value;
2645 /// Eat '%'
2646 Lex();
2647 if (parseExpression(AbsoluteExp, EndLoc))
2648 return false;
2649 if (!AbsoluteExp->evaluateAsAbsolute(Value,
2650 getStreamer().getAssemblerPtr()))
2651 return Error(StrLoc, "expected absolute expression");
2652 const char *StrChar = StrLoc.getPointer();
2653 const char *EndChar = EndLoc.getPointer();
2654 AsmToken newToken(AsmToken::Integer,
2655 StringRef(StrChar, EndChar - StrChar), Value);
2656 FA.Value.push_back(newToken);
Craig Topperc81aff72018-09-25 20:55:55 +00002657 } else if (AltMacroMode && Lexer.is(AsmToken::Less) &&
Michael Zuckerman763e60e2017-05-04 10:37:00 +00002658 isAltmacroString(StrLoc, EndLoc)) {
Craig Topper3da977b2018-09-25 19:37:35 +00002659 const char *StrChar = StrLoc.getPointer();
2660 const char *EndChar = EndLoc.getPointer();
2661 jumpToLoc(EndLoc, CurBuffer);
2662 /// Eat from '<' to '>'
2663 Lex();
2664 AsmToken newToken(AsmToken::String,
2665 StringRef(StrChar, EndChar - StrChar));
2666 FA.Value.push_back(newToken);
Michael Zuckerman763e60e2017-05-04 10:37:00 +00002667 } else if(parseMacroArgument(FA.Value, Vararg))
Craig Topper3da977b2018-09-25 19:37:35 +00002668 return true;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002669
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002670 unsigned PI = Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002671 if (!FA.Name.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002672 unsigned FAI = 0;
2673 for (FAI = 0; FAI < NParameters; ++FAI)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002674 if (M->Parameters[FAI].Name == FA.Name)
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002675 break;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002676
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002677 if (FAI >= NParameters) {
Nirav Davefd910412016-06-17 16:06:17 +00002678 assert(M && "expected macro to be defined");
Nirav Dave2364748a2016-09-16 18:30:20 +00002679 return Error(IDLoc, "parameter named '" + FA.Name +
2680 "' does not exist for macro '" + M->Name + "'");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002681 }
2682 PI = FAI;
2683 }
2684
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002685 if (!FA.Value.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002686 if (A.size() <= PI)
2687 A.resize(PI + 1);
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002688 A[PI] = FA.Value;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002689
2690 if (FALocs.size() <= PI)
2691 FALocs.resize(PI + 1);
2692
2693 FALocs[PI] = Lexer.getLoc();
Preston Gurd242ed3152012-09-19 20:29:04 +00002694 }
Jim Grosbach206661622012-07-30 22:44:17 +00002695
Preston Gurd242ed3152012-09-19 20:29:04 +00002696 // At the end of the statement, fill in remaining arguments that have
2697 // default values. If there aren't any, then the next argument is
2698 // required but missing
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002699 if (Lexer.is(AsmToken::EndOfStatement)) {
2700 bool Failure = false;
2701 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2702 if (A[FAI].empty()) {
2703 if (M->Parameters[FAI].Required) {
2704 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2705 "missing value for required parameter "
2706 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2707 Failure = true;
2708 }
2709
2710 if (!M->Parameters[FAI].Value.empty())
2711 A[FAI] = M->Parameters[FAI].Value;
2712 }
2713 }
2714 return Failure;
2715 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002716
2717 if (Lexer.is(AsmToken::Comma))
2718 Lex();
2719 }
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002720
2721 return TokError("too many positional arguments");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002722}
2723
Jim Grosbach4b905842013-09-20 23:08:21 +00002724bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
Davide Italiano7c9fc732016-07-27 05:51:56 +00002725 // Arbitrarily limit macro nesting depth (default matches 'as'). We can
2726 // eliminate this, although we should protect against infinite loops.
2727 unsigned MaxNestingDepth = AsmMacroMaxNestingDepth;
2728 if (ActiveMacros.size() == MaxNestingDepth) {
2729 std::ostringstream MaxNestingDepthError;
2730 MaxNestingDepthError << "macros cannot be nested more than "
2731 << MaxNestingDepth << " levels deep."
2732 << " Use -asm-macro-max-nesting-depth to increase "
2733 "this limit.";
2734 return TokError(MaxNestingDepthError.str());
2735 }
Daniel Dunbar43235712010-07-18 18:54:11 +00002736
Eli Bendersky38274122013-01-14 23:22:36 +00002737 MCAsmMacroArguments A;
Jim Grosbach4b905842013-09-20 23:08:21 +00002738 if (parseMacroArguments(M, A))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002739 return true;
Daniel Dunbar43235712010-07-18 18:54:11 +00002740
Rafael Espindola1134ab232011-06-05 02:43:45 +00002741 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2742 // to hold the macro body with substitutions.
2743 SmallString<256> Buf;
2744 StringRef Body = M->Body;
Rafael Espindola34b9c512012-06-03 23:57:14 +00002745 raw_svector_ostream OS(Buf);
Rafael Espindola1134ab232011-06-05 02:43:45 +00002746
Toma Tabacu217116e2015-04-27 10:50:29 +00002747 if (expandMacro(OS, Body, M->Parameters, A, true, getTok().getLoc()))
Rafael Espindola1134ab232011-06-05 02:43:45 +00002748 return true;
2749
Eli Bendersky38274122013-01-14 23:22:36 +00002750 // We include the .endmacro in the buffer as our cue to exit the macro
Rafael Espindola34b9c512012-06-03 23:57:14 +00002751 // instantiation.
2752 OS << ".endmacro\n";
2753
Rafael Espindola3560ff22014-08-27 20:03:13 +00002754 std::unique_ptr<MemoryBuffer> Instantiation =
2755 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola1134ab232011-06-05 02:43:45 +00002756
Daniel Dunbar43235712010-07-18 18:54:11 +00002757 // Create the macro instantiation object and add to the current macro
2758 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002759 MacroInstantiation *MI = new MacroInstantiation(
2760 NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Daniel Dunbar43235712010-07-18 18:54:11 +00002761 ActiveMacros.push_back(MI);
2762
Toma Tabacu217116e2015-04-27 10:50:29 +00002763 ++NumOfMacroInstantiations;
2764
Daniel Dunbar43235712010-07-18 18:54:11 +00002765 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00002766 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00002767 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar43235712010-07-18 18:54:11 +00002768 Lex();
2769
2770 return false;
2771}
2772
Jim Grosbach4b905842013-09-20 23:08:21 +00002773void AsmParser::handleMacroExit() {
Daniel Dunbar43235712010-07-18 18:54:11 +00002774 // Jump to the EndOfStatement we should return to, and consume it.
Jim Grosbach4b905842013-09-20 23:08:21 +00002775 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
Daniel Dunbar43235712010-07-18 18:54:11 +00002776 Lex();
2777
2778 // Pop the instantiation entry.
2779 delete ActiveMacros.back();
2780 ActiveMacros.pop_back();
2781}
2782
Jim Grosbach4b905842013-09-20 23:08:21 +00002783bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
Nirav Dave7fd992a2018-08-16 16:31:14 +00002784 bool NoDeadStrip) {
Pete Cooper80d21cb2015-06-22 19:35:57 +00002785 MCSymbol *Sym;
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002786 const MCExpr *Value;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002787 if (MCParserUtils::parseAssignmentExpression(Name, allow_redef, *this, Sym,
Nirav Dave7fd992a2018-08-16 16:31:14 +00002788 Value))
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002789 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002790
Pete Cooper80d21cb2015-06-22 19:35:57 +00002791 if (!Sym) {
2792 // In the case where we parse an expression starting with a '.', we will
2793 // not generate an error, nor will we create a symbol. In this case we
2794 // should just return out.
Anders Waldenborg84809572014-02-17 20:48:32 +00002795 return false;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002796 }
David Majnemer58cb80c2014-12-24 10:27:50 +00002797
Daniel Dunbarae7ac012009-06-29 23:43:14 +00002798 // Do the assignment.
Daniel Dunbarb7b20972009-08-31 08:09:09 +00002799 Out.EmitAssignment(Sym, Value);
Jim Grosbachb7b750d2012-09-13 23:11:31 +00002800 if (NoDeadStrip)
2801 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2802
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002803 return false;
2804}
2805
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002806/// parseIdentifier:
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002807/// ::= identifier
2808/// ::= string
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002809bool AsmParser::parseIdentifier(StringRef &Res) {
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002810 // The assembler has relaxed rules for accepting identifiers, in particular we
Hans Wennborgce69d772013-10-18 20:46:28 +00002811 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2812 // separate tokens. At this level, we have already lexed so we cannot (currently)
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002813 // handle this as a context dependent token, instead we detect adjacent tokens
2814 // and return the combined identifier.
Hans Wennborgce69d772013-10-18 20:46:28 +00002815 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2816 SMLoc PrefixLoc = getLexer().getLoc();
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002817
Hans Wennborgce69d772013-10-18 20:46:28 +00002818 // Consume the prefix character, and check for a following identifier.
Nirav Daved0463322016-10-12 13:58:07 +00002819
2820 AsmToken Buf[1];
2821 Lexer.peekTokens(Buf, false);
2822
2823 if (Buf[0].isNot(AsmToken::Identifier))
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002824 return true;
2825
Hans Wennborgce69d772013-10-18 20:46:28 +00002826 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
Nirav Daved0463322016-10-12 13:58:07 +00002827 if (PrefixLoc.getPointer() + 1 != Buf[0].getLoc().getPointer())
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002828 return true;
2829
Nirav Daved0463322016-10-12 13:58:07 +00002830 // eat $ or @
2831 Lexer.Lex(); // Lexer's Lex guarantees consecutive token.
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002832 // Construct the joined identifier and consume the token.
Jim Grosbach4b905842013-09-20 23:08:21 +00002833 Res =
Hans Wennborgce69d772013-10-18 20:46:28 +00002834 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
Nirav Davefd910412016-06-17 16:06:17 +00002835 Lex(); // Parser Lex to maintain invariants.
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002836 return false;
2837 }
2838
Jim Grosbach4b905842013-09-20 23:08:21 +00002839 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002840 return true;
2841
Sean Callanan936b0d32010-01-19 21:44:56 +00002842 Res = getTok().getIdentifier();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002843
Sean Callanan686ed8d2010-01-19 20:22:31 +00002844 Lex(); // Consume the identifier token.
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002845
2846 return false;
2847}
2848
Jim Grosbach4b905842013-09-20 23:08:21 +00002849/// parseDirectiveSet:
Nico Weber4ada0d92011-01-28 03:04:41 +00002850/// ::= .equ identifier ',' expression
2851/// ::= .equiv identifier ',' expression
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002852/// ::= .set identifier ',' expression
Jim Grosbach4b905842013-09-20 23:08:21 +00002853bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002854 StringRef Name;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002855 if (check(parseIdentifier(Name), "expected identifier") ||
2856 parseToken(AsmToken::Comma) || parseAssignment(Name, allow_redef, true))
2857 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
2858 return false;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002859}
2860
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002861bool AsmParser::parseEscapedString(std::string &Data) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00002862 if (check(getTok().isNot(AsmToken::String), "expected string"))
2863 return true;
Daniel Dunbaref668c12009-08-14 18:19:52 +00002864
2865 Data = "";
Sean Callanan936b0d32010-01-19 21:44:56 +00002866 StringRef Str = getTok().getStringContents();
Daniel Dunbaref668c12009-08-14 18:19:52 +00002867 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2868 if (Str[i] != '\\') {
2869 Data += Str[i];
2870 continue;
2871 }
2872
2873 // Recognize escaped characters. Note that this escape semantics currently
2874 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2875 ++i;
2876 if (i == e)
2877 return TokError("unexpected backslash at end of string");
2878
2879 // Recognize octal sequences.
Jim Grosbach4b905842013-09-20 23:08:21 +00002880 if ((unsigned)(Str[i] - '0') <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002881 // Consume up to three octal characters.
2882 unsigned Value = Str[i] - '0';
2883
Jim Grosbach4b905842013-09-20 23:08:21 +00002884 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002885 ++i;
2886 Value = Value * 8 + (Str[i] - '0');
2887
Jim Grosbach4b905842013-09-20 23:08:21 +00002888 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002889 ++i;
2890 Value = Value * 8 + (Str[i] - '0');
2891 }
2892 }
2893
2894 if (Value > 255)
2895 return TokError("invalid octal escape sequence (out of range)");
2896
Jim Grosbach4b905842013-09-20 23:08:21 +00002897 Data += (unsigned char)Value;
Daniel Dunbaref668c12009-08-14 18:19:52 +00002898 continue;
2899 }
2900
2901 // Otherwise recognize individual escapes.
2902 switch (Str[i]) {
2903 default:
2904 // Just reject invalid escape sequences for now.
2905 return TokError("invalid escape sequence (unrecognized character)");
2906
2907 case 'b': Data += '\b'; break;
2908 case 'f': Data += '\f'; break;
2909 case 'n': Data += '\n'; break;
2910 case 'r': Data += '\r'; break;
2911 case 't': Data += '\t'; break;
2912 case '"': Data += '"'; break;
2913 case '\\': Data += '\\'; break;
2914 }
2915 }
2916
Nirav Davea645433c2016-07-18 15:24:03 +00002917 Lex();
Daniel Dunbaref668c12009-08-14 18:19:52 +00002918 return false;
2919}
2920
Jim Grosbach4b905842013-09-20 23:08:21 +00002921/// parseDirectiveAscii:
Rafael Espindola63760ba2010-10-28 20:02:27 +00002922/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002923bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00002924 auto parseOp = [&]() -> bool {
2925 std::string Data;
2926 if (checkForValidSection() || parseEscapedString(Data))
Nirav Davef43cc9f2016-10-10 15:24:54 +00002927 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002928 getStreamer().EmitBytes(Data);
2929 if (ZeroTerminated)
2930 getStreamer().EmitBytes(StringRef("\0", 1));
2931 return false;
2932 };
Daniel Dunbare5444a82010-09-09 22:42:59 +00002933
Nirav Dave1a9044b2016-10-24 14:35:29 +00002934 if (parseMany(parseOp))
2935 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbara10e5192009-06-24 23:30:00 +00002936 return false;
2937}
2938
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002939/// parseDirectiveReloc
2940/// ::= .reloc expression , identifier [ , expression ]
2941bool AsmParser::parseDirectiveReloc(SMLoc DirectiveLoc) {
2942 const MCExpr *Offset;
2943 const MCExpr *Expr = nullptr;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002944 int64_t OffsetValue;
Vladimir Stefanovic1d2714b2018-11-21 16:28:39 +00002945 SMLoc OffsetLoc = Lexer.getTok().getLoc();
Nirav Dave1a9044b2016-10-24 14:35:29 +00002946
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002947 if (parseExpression(Offset))
2948 return true;
2949
Vladimir Stefanovic1d2714b2018-11-21 16:28:39 +00002950 if ((Offset->evaluateAsAbsolute(OffsetValue,
2951 getStreamer().getAssemblerPtr()) &&
2952 check(OffsetValue < 0, OffsetLoc, "expression is negative")) ||
2953 (check(Offset->getKind() != llvm::MCExpr::Constant &&
2954 Offset->getKind() != llvm::MCExpr::SymbolRef,
2955 OffsetLoc, "expected non-negative number or a label")) ||
2956 (parseToken(AsmToken::Comma, "expected comma") ||
2957 check(getTok().isNot(AsmToken::Identifier), "expected relocation name")))
Nirav Davea645433c2016-07-18 15:24:03 +00002958 return true;
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002959
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002960 SMLoc NameLoc = Lexer.getTok().getLoc();
2961 StringRef Name = Lexer.getTok().getIdentifier();
Nirav Davefd910412016-06-17 16:06:17 +00002962 Lex();
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002963
2964 if (Lexer.is(AsmToken::Comma)) {
Nirav Davefd910412016-06-17 16:06:17 +00002965 Lex();
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002966 SMLoc ExprLoc = Lexer.getLoc();
2967 if (parseExpression(Expr))
2968 return true;
2969
2970 MCValue Value;
2971 if (!Expr->evaluateAsRelocatable(Value, nullptr, nullptr))
2972 return Error(ExprLoc, "expression must be relocatable");
2973 }
2974
Nirav Davea645433c2016-07-18 15:24:03 +00002975 if (parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00002976 "unexpected token in .reloc directive"))
2977 return true;
2978
Peter Smith57f661b2018-06-06 09:40:06 +00002979 const MCTargetAsmParser &MCT = getTargetParser();
2980 const MCSubtargetInfo &STI = MCT.getSTI();
2981 if (getStreamer().EmitRelocDirective(*Offset, Name, Expr, DirectiveLoc, STI))
Nirav Dave1ab71992016-07-18 19:35:21 +00002982 return Error(NameLoc, "unknown relocation name");
2983
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002984 return false;
2985}
2986
Jim Grosbach4b905842013-09-20 23:08:21 +00002987/// parseDirectiveValue
Daniel Dunbara10e5192009-06-24 23:30:00 +00002988/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00002989bool AsmParser::parseDirectiveValue(StringRef IDVal, unsigned Size) {
2990 auto parseOp = [&]() -> bool {
2991 const MCExpr *Value;
2992 SMLoc ExprLoc = getLexer().getLoc();
2993 if (checkForValidSection() || parseExpression(Value))
Nirav Davef43cc9f2016-10-10 15:24:54 +00002994 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002995 // Special case constant expressions to match code generator.
2996 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2997 assert(Size <= 8 && "Invalid size");
2998 uint64_t IntValue = MCE->getValue();
2999 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
3000 return Error(ExprLoc, "out of range literal value");
3001 getStreamer().EmitIntValue(IntValue, Size);
3002 } else
3003 getStreamer().EmitValue(Value, Size, ExprLoc);
3004 return false;
3005 };
Daniel Dunbare5444a82010-09-09 22:42:59 +00003006
Nirav Dave1a9044b2016-10-24 14:35:29 +00003007 if (parseMany(parseOp))
3008 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbara10e5192009-06-24 23:30:00 +00003009 return false;
3010}
3011
Paul Robinson01954692018-04-11 15:14:05 +00003012static bool parseHexOcta(AsmParser &Asm, uint64_t &hi, uint64_t &lo) {
3013 if (Asm.getTok().isNot(AsmToken::Integer) &&
3014 Asm.getTok().isNot(AsmToken::BigNum))
3015 return Asm.TokError("unknown token in expression");
3016 SMLoc ExprLoc = Asm.getTok().getLoc();
3017 APInt IntValue = Asm.getTok().getAPIntVal();
3018 Asm.Lex();
3019 if (!IntValue.isIntN(128))
3020 return Asm.Error(ExprLoc, "out of range literal value");
3021 if (!IntValue.isIntN(64)) {
3022 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
3023 lo = IntValue.getLoBits(64).getZExtValue();
3024 } else {
3025 hi = 0;
3026 lo = IntValue.getZExtValue();
3027 }
3028 return false;
3029}
3030
David Woodhoused6de0d92014-02-01 16:20:59 +00003031/// ParseDirectiveOctaValue
3032/// ::= .octa [ hexconstant (, hexconstant)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00003033
3034bool AsmParser::parseDirectiveOctaValue(StringRef IDVal) {
3035 auto parseOp = [&]() -> bool {
Nirav Davef43cc9f2016-10-10 15:24:54 +00003036 if (checkForValidSection())
3037 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003038 uint64_t hi, lo;
Paul Robinson01954692018-04-11 15:14:05 +00003039 if (parseHexOcta(*this, hi, lo))
3040 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003041 if (MAI.isLittleEndian()) {
3042 getStreamer().EmitIntValue(lo, 8);
3043 getStreamer().EmitIntValue(hi, 8);
3044 } else {
3045 getStreamer().EmitIntValue(hi, 8);
3046 getStreamer().EmitIntValue(lo, 8);
3047 }
3048 return false;
3049 };
David Woodhoused6de0d92014-02-01 16:20:59 +00003050
Nirav Dave1a9044b2016-10-24 14:35:29 +00003051 if (parseMany(parseOp))
3052 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
David Woodhoused6de0d92014-02-01 16:20:59 +00003053 return false;
3054}
3055
Petr Hosek4cb08ce2016-09-23 19:25:15 +00003056bool AsmParser::parseRealValue(const fltSemantics &Semantics, APInt &Res) {
3057 // We don't truly support arithmetic on floating point expressions, so we
3058 // have to manually parse unary prefixes.
3059 bool IsNeg = false;
3060 if (getLexer().is(AsmToken::Minus)) {
3061 Lexer.Lex();
3062 IsNeg = true;
3063 } else if (getLexer().is(AsmToken::Plus))
3064 Lexer.Lex();
3065
3066 if (Lexer.is(AsmToken::Error))
3067 return TokError(Lexer.getErr());
3068 if (Lexer.isNot(AsmToken::Integer) && Lexer.isNot(AsmToken::Real) &&
3069 Lexer.isNot(AsmToken::Identifier))
3070 return TokError("unexpected token in directive");
3071
3072 // Convert to an APFloat.
3073 APFloat Value(Semantics);
3074 StringRef IDVal = getTok().getString();
3075 if (getLexer().is(AsmToken::Identifier)) {
3076 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
3077 Value = APFloat::getInf(Semantics);
3078 else if (!IDVal.compare_lower("nan"))
3079 Value = APFloat::getNaN(Semantics, false, ~0);
3080 else
3081 return TokError("invalid floating point literal");
3082 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
3083 APFloat::opInvalidOp)
3084 return TokError("invalid floating point literal");
3085 if (IsNeg)
3086 Value.changeSign();
3087
3088 // Consume the numeric token.
3089 Lex();
3090
3091 Res = Value.bitcastToAPInt();
3092
3093 return false;
3094}
3095
Jim Grosbach4b905842013-09-20 23:08:21 +00003096/// parseDirectiveRealValue
Daniel Dunbar2af16532010-09-24 01:59:56 +00003097/// ::= (.single | .double) [ expression (, expression)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00003098bool AsmParser::parseDirectiveRealValue(StringRef IDVal,
3099 const fltSemantics &Semantics) {
3100 auto parseOp = [&]() -> bool {
3101 APInt AsInt;
3102 if (checkForValidSection() || parseRealValue(Semantics, AsInt))
Nirav Davef43cc9f2016-10-10 15:24:54 +00003103 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003104 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
3105 AsInt.getBitWidth() / 8);
3106 return false;
3107 };
Daniel Dunbar2af16532010-09-24 01:59:56 +00003108
Nirav Dave1a9044b2016-10-24 14:35:29 +00003109 if (parseMany(parseOp))
3110 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbar2af16532010-09-24 01:59:56 +00003111 return false;
3112}
3113
Jim Grosbach4b905842013-09-20 23:08:21 +00003114/// parseDirectiveZero
Rafael Espindola922e3f42010-09-16 15:03:59 +00003115/// ::= .zero expression
Jim Grosbach4b905842013-09-20 23:08:21 +00003116bool AsmParser::parseDirectiveZero() {
Petr Hosek67a94a72016-05-28 05:57:48 +00003117 SMLoc NumBytesLoc = Lexer.getLoc();
3118 const MCExpr *NumBytes;
Nirav Davef43cc9f2016-10-10 15:24:54 +00003119 if (checkForValidSection() || parseExpression(NumBytes))
Rafael Espindola922e3f42010-09-16 15:03:59 +00003120 return true;
3121
Rafael Espindolab91bac62010-10-05 19:42:57 +00003122 int64_t Val = 0;
3123 if (getLexer().is(AsmToken::Comma)) {
3124 Lex();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003125 if (parseAbsoluteExpression(Val))
Rafael Espindolab91bac62010-10-05 19:42:57 +00003126 return true;
3127 }
3128
Nirav Davea645433c2016-07-18 15:24:03 +00003129 if (parseToken(AsmToken::EndOfStatement,
3130 "unexpected token in '.zero' directive"))
3131 return true;
Petr Hosek67a94a72016-05-28 05:57:48 +00003132 getStreamer().emitFill(*NumBytes, Val, NumBytesLoc);
Rafael Espindola922e3f42010-09-16 15:03:59 +00003133
3134 return false;
3135}
3136
Jim Grosbach4b905842013-09-20 23:08:21 +00003137/// parseDirectiveFill
Roman Divackye33098f2013-09-24 17:44:41 +00003138/// ::= .fill expression [ , expression [ , expression ] ]
Jim Grosbach4b905842013-09-20 23:08:21 +00003139bool AsmParser::parseDirectiveFill() {
Petr Hosek67a94a72016-05-28 05:57:48 +00003140 SMLoc NumValuesLoc = Lexer.getLoc();
3141 const MCExpr *NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00003142 if (checkForValidSection() || parseExpression(NumValues))
Daniel Dunbara10e5192009-06-24 23:30:00 +00003143 return true;
3144
Roman Divackye33098f2013-09-24 17:44:41 +00003145 int64_t FillSize = 1;
3146 int64_t FillExpr = 0;
Michael J. Spencer530ce852010-10-09 11:00:50 +00003147
David Majnemer522d3db2014-02-01 07:19:38 +00003148 SMLoc SizeLoc, ExprLoc;
Daniel Dunbara10e5192009-06-24 23:30:00 +00003149
Nirav Dave1a9044b2016-10-24 14:35:29 +00003150 if (parseOptionalToken(AsmToken::Comma)) {
3151 SizeLoc = getTok().getLoc();
3152 if (parseAbsoluteExpression(FillSize))
Roman Divackye33098f2013-09-24 17:44:41 +00003153 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003154 if (parseOptionalToken(AsmToken::Comma)) {
3155 ExprLoc = getTok().getLoc();
3156 if (parseAbsoluteExpression(FillExpr))
Roman Divackye33098f2013-09-24 17:44:41 +00003157 return true;
Roman Divackye33098f2013-09-24 17:44:41 +00003158 }
3159 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003160 if (parseToken(AsmToken::EndOfStatement,
3161 "unexpected token in '.fill' directive"))
3162 return true;
Daniel Dunbara10e5192009-06-24 23:30:00 +00003163
David Majnemer522d3db2014-02-01 07:19:38 +00003164 if (FillSize < 0) {
3165 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
Petr Hosek6abd38b2016-05-28 08:20:08 +00003166 return false;
David Majnemer522d3db2014-02-01 07:19:38 +00003167 }
3168 if (FillSize > 8) {
3169 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
3170 FillSize = 8;
3171 }
Daniel Dunbara10e5192009-06-24 23:30:00 +00003172
David Majnemer522d3db2014-02-01 07:19:38 +00003173 if (!isUInt<32>(FillExpr) && FillSize > 4)
3174 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
3175
Petr Hosek67a94a72016-05-28 05:57:48 +00003176 getStreamer().emitFill(*NumValues, FillSize, FillExpr, NumValuesLoc);
Daniel Dunbara10e5192009-06-24 23:30:00 +00003177
3178 return false;
3179}
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00003180
Jim Grosbach4b905842013-09-20 23:08:21 +00003181/// parseDirectiveOrg
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00003182/// ::= .org expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00003183bool AsmParser::parseDirectiveOrg() {
Daniel Dunbar897ffad2009-08-31 08:09:28 +00003184 const MCExpr *Offset;
Oliver Stannard268f42f2016-12-14 10:43:58 +00003185 SMLoc OffsetLoc = Lexer.getLoc();
Nirav Davef43cc9f2016-10-10 15:24:54 +00003186 if (checkForValidSection() || parseExpression(Offset))
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00003187 return true;
3188
3189 // Parse optional fill expression.
3190 int64_t FillExpr = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003191 if (parseOptionalToken(AsmToken::Comma))
3192 if (parseAbsoluteExpression(FillExpr))
3193 return addErrorSuffix(" in '.org' directive");
3194 if (parseToken(AsmToken::EndOfStatement))
3195 return addErrorSuffix(" in '.org' directive");
Nirav Davea645433c2016-07-18 15:24:03 +00003196
Oliver Stannard268f42f2016-12-14 10:43:58 +00003197 getStreamer().emitValueToOffset(Offset, FillExpr, OffsetLoc);
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00003198 return false;
3199}
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003200
Jim Grosbach4b905842013-09-20 23:08:21 +00003201/// parseDirectiveAlign
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003202/// ::= {.align, ...} expression [ , expression [ , expression ]]
Jim Grosbach4b905842013-09-20 23:08:21 +00003203bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003204 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003205 int64_t Alignment;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003206 SMLoc MaxBytesLoc;
3207 bool HasFillExpr = false;
3208 int64_t FillExpr = 0;
3209 int64_t MaxBytesToFill = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003210
3211 auto parseAlign = [&]() -> bool {
Coby Tayreed483a102017-08-02 17:36:10 +00003212 if (parseAbsoluteExpression(Alignment))
Nirav Davea645433c2016-07-18 15:24:03 +00003213 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003214 if (parseOptionalToken(AsmToken::Comma)) {
3215 // The fill expression can be omitted while specifying a maximum number of
3216 // alignment bytes, e.g:
3217 // .align 3,,4
3218 if (getTok().isNot(AsmToken::Comma)) {
3219 HasFillExpr = true;
3220 if (parseAbsoluteExpression(FillExpr))
3221 return true;
3222 }
3223 if (parseOptionalToken(AsmToken::Comma))
3224 if (parseTokenLoc(MaxBytesLoc) ||
3225 parseAbsoluteExpression(MaxBytesToFill))
3226 return true;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003227 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003228 return parseToken(AsmToken::EndOfStatement);
3229 };
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003230
Coby Tayreed483a102017-08-02 17:36:10 +00003231 if (checkForValidSection())
3232 return addErrorSuffix(" in directive");
3233 // Ignore empty '.p2align' directives for GNU-as compatibility
3234 if (IsPow2 && (ValueSize == 1) && getTok().is(AsmToken::EndOfStatement)) {
3235 Warning(AlignmentLoc, "p2align directive with no operand(s) is ignored");
3236 return parseToken(AsmToken::EndOfStatement);
3237 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003238 if (parseAlign())
3239 return addErrorSuffix(" in directive");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003240
Nirav Dave2364748a2016-09-16 18:30:20 +00003241 // Always emit an alignment here even if we thrown an error.
3242 bool ReturnVal = false;
3243
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003244 // Compute alignment in bytes.
3245 if (IsPow2) {
3246 // FIXME: Diagnose overflow.
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003247 if (Alignment >= 32) {
Nirav Dave2364748a2016-09-16 18:30:20 +00003248 ReturnVal |= Error(AlignmentLoc, "invalid alignment value");
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003249 Alignment = 31;
3250 }
3251
Benjamin Kramer63951ad2009-09-06 09:35:10 +00003252 Alignment = 1ULL << Alignment;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00003253 } else {
Davide Italianocb2da712015-09-08 18:59:47 +00003254 // Reject alignments that aren't either a power of two or zero,
3255 // for gas compatibility. Alignment of zero is silently rounded
3256 // up to one.
3257 if (Alignment == 0)
3258 Alignment = 1;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00003259 if (!isPowerOf2_64(Alignment))
Nirav Dave2364748a2016-09-16 18:30:20 +00003260 ReturnVal |= Error(AlignmentLoc, "alignment must be a power of 2");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003261 }
3262
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003263 // Diagnose non-sensical max bytes to align.
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003264 if (MaxBytesLoc.isValid()) {
3265 if (MaxBytesToFill < 1) {
Nirav Dave2364748a2016-09-16 18:30:20 +00003266 ReturnVal |= Error(MaxBytesLoc,
3267 "alignment directive can never be satisfied in this "
Jim Grosbach4b905842013-09-20 23:08:21 +00003268 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar4abcccb2009-08-21 23:01:53 +00003269 MaxBytesToFill = 0;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003270 }
3271
3272 if (MaxBytesToFill >= Alignment) {
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +00003273 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
Jim Grosbach4b905842013-09-20 23:08:21 +00003274 "has no effect");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003275 MaxBytesToFill = 0;
3276 }
3277 }
3278
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003279 // Check whether we should use optimal code alignment for this .align
3280 // directive.
Eric Christopher445c9522016-10-14 05:47:37 +00003281 const MCSection *Section = getStreamer().getCurrentSectionOnly();
Saleem Abdulrasool7f2f9f42014-03-21 05:13:23 +00003282 assert(Section && "must have section to emit alignment");
3283 bool UseCodeAlign = Section->UseCodeAlign();
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003284 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
3285 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003286 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003287 } else {
Kevin Enderby7f993022010-02-25 18:46:04 +00003288 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnerc2b36752010-07-15 21:19:31 +00003289 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
3290 MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003291 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003292
Nirav Dave2364748a2016-09-16 18:30:20 +00003293 return ReturnVal;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003294}
3295
Jim Grosbach4b905842013-09-20 23:08:21 +00003296/// parseDirectiveFile
Paul Robinson29f5f982018-01-09 23:31:48 +00003297/// ::= .file filename
Scott Linder16c7bda2018-02-23 23:01:06 +00003298/// ::= .file number [directory] filename [md5 checksum] [source source-text]
Jim Grosbach4b905842013-09-20 23:08:21 +00003299bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003300 // FIXME: I'm not sure what this is.
3301 int64_t FileNumber = -1;
Eli Bendersky17233942013-01-15 22:59:42 +00003302 if (getLexer().is(AsmToken::Integer)) {
3303 FileNumber = getTok().getIntVal();
3304 Lex();
3305
Paul Robinsonb271f312018-03-29 17:16:41 +00003306 if (FileNumber < 0)
3307 return TokError("negative file number");
Eli Bendersky17233942013-01-15 22:59:42 +00003308 }
3309
Paul Robinson37fbb922018-06-20 16:12:03 +00003310 std::string Path;
Eli Bendersky17233942013-01-15 22:59:42 +00003311
3312 // Usually the directory and filename together, otherwise just the directory.
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003313 // Allow the strings to have escaped octal character sequence.
Nirav Davea645433c2016-07-18 15:24:03 +00003314 if (check(getTok().isNot(AsmToken::String),
3315 "unexpected token in '.file' directive") ||
3316 parseEscapedString(Path))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003317 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003318
3319 StringRef Directory;
3320 StringRef Filename;
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003321 std::string FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00003322 if (getLexer().is(AsmToken::String)) {
Nirav Davea645433c2016-07-18 15:24:03 +00003323 if (check(FileNumber == -1,
3324 "explicit path specified, but no file number") ||
3325 parseEscapedString(FilenameData))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003326 return true;
3327 Filename = FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00003328 Directory = Path;
Eli Bendersky17233942013-01-15 22:59:42 +00003329 } else {
3330 Filename = Path;
3331 }
3332
Paul Robinson01954692018-04-11 15:14:05 +00003333 uint64_t MD5Hi, MD5Lo;
3334 bool HasMD5 = false;
Scott Linder16c7bda2018-02-23 23:01:06 +00003335
3336 Optional<StringRef> Source;
3337 bool HasSource = false;
3338 std::string SourceString;
3339
3340 while (!parseOptionalToken(AsmToken::EndOfStatement)) {
Paul Robinson29f5f982018-01-09 23:31:48 +00003341 StringRef Keyword;
3342 if (check(getTok().isNot(AsmToken::Identifier),
3343 "unexpected token in '.file' directive") ||
Scott Linder16c7bda2018-02-23 23:01:06 +00003344 parseIdentifier(Keyword))
Paul Robinson29f5f982018-01-09 23:31:48 +00003345 return true;
Scott Linder16c7bda2018-02-23 23:01:06 +00003346 if (Keyword == "md5") {
Paul Robinson01954692018-04-11 15:14:05 +00003347 HasMD5 = true;
Scott Linder16c7bda2018-02-23 23:01:06 +00003348 if (check(FileNumber == -1,
3349 "MD5 checksum specified, but no file number") ||
Paul Robinson01954692018-04-11 15:14:05 +00003350 parseHexOcta(*this, MD5Hi, MD5Lo))
Scott Linder16c7bda2018-02-23 23:01:06 +00003351 return true;
3352 } else if (Keyword == "source") {
3353 HasSource = true;
3354 if (check(FileNumber == -1,
3355 "source specified, but no file number") ||
3356 check(getTok().isNot(AsmToken::String),
3357 "unexpected token in '.file' directive") ||
3358 parseEscapedString(SourceString))
3359 return true;
3360 } else {
3361 return TokError("unexpected token in '.file' directive");
3362 }
Paul Robinson29f5f982018-01-09 23:31:48 +00003363 }
Eli Bendersky17233942013-01-15 22:59:42 +00003364
Reid Kleckner98bbd072018-12-21 23:35:48 +00003365 if (FileNumber == -1) {
3366 if (!getContext().getAsmInfo()->hasSingleParameterDotFile())
3367 return Error(DirectiveLoc,
3368 "target does not support '.file' without a number");
Eli Bendersky17233942013-01-15 22:59:42 +00003369 getStreamer().EmitFileDirective(Filename);
Reid Kleckner98bbd072018-12-21 23:35:48 +00003370 } else {
Brian Cain3e0ca572018-08-28 16:23:39 +00003371 // In case there is a -g option as well as debug info from directive .file,
3372 // we turn off the -g option, directly use the existing debug info instead.
3373 // Also reset any implicit ".file 0" for the assembler source.
3374 if (Ctx.getGenDwarfForAssembly()) {
3375 Ctx.getMCDwarfLineTable(0).resetRootFile();
3376 Ctx.setGenDwarfForAssembly(false);
3377 }
3378
Paul Robinson29f5f982018-01-09 23:31:48 +00003379 MD5::MD5Result *CKMem = nullptr;
Paul Robinson01954692018-04-11 15:14:05 +00003380 if (HasMD5) {
Paul Robinson29f5f982018-01-09 23:31:48 +00003381 CKMem = (MD5::MD5Result *)Ctx.allocate(sizeof(MD5::MD5Result), 1);
Paul Robinson01954692018-04-11 15:14:05 +00003382 for (unsigned i = 0; i != 8; ++i) {
3383 CKMem->Bytes[i] = uint8_t(MD5Hi >> ((7 - i) * 8));
3384 CKMem->Bytes[i + 8] = uint8_t(MD5Lo >> ((7 - i) * 8));
3385 }
Paul Robinson29f5f982018-01-09 23:31:48 +00003386 }
Scott Linder16c7bda2018-02-23 23:01:06 +00003387 if (HasSource) {
3388 char *SourceBuf = static_cast<char *>(Ctx.allocate(SourceString.size()));
3389 memcpy(SourceBuf, SourceString.data(), SourceString.size());
3390 Source = StringRef(SourceBuf, SourceString.size());
3391 }
Paul Robinson547adca2018-06-21 16:42:03 +00003392 if (FileNumber == 0) {
3393 if (Ctx.getDwarfVersion() < 5)
3394 return Warning(DirectiveLoc, "file 0 not supported prior to DWARF-5");
Paul Robinsonb271f312018-03-29 17:16:41 +00003395 getStreamer().emitDwarfFile0Directive(Directory, Filename, CKMem, Source);
Paul Robinson547adca2018-06-21 16:42:03 +00003396 } else {
Paul Robinsonb271f312018-03-29 17:16:41 +00003397 Expected<unsigned> FileNumOrErr = getStreamer().tryEmitDwarfFileDirective(
3398 FileNumber, Directory, Filename, CKMem, Source);
3399 if (!FileNumOrErr)
3400 return Error(DirectiveLoc, toString(FileNumOrErr.takeError()));
3401 FileNumber = FileNumOrErr.get();
3402 }
Paul Robinsoncc7344a2018-06-14 13:38:20 +00003403 // Alert the user if there are some .file directives with MD5 and some not.
3404 // But only do that once.
3405 if (!ReportedInconsistentMD5 && !Ctx.isDwarfMD5UsageConsistent(0)) {
3406 ReportedInconsistentMD5 = true;
3407 return Warning(DirectiveLoc, "inconsistent use of MD5 checksums");
3408 }
Eli Bendersky17233942013-01-15 22:59:42 +00003409 }
3410
3411 return false;
3412}
3413
Jim Grosbach4b905842013-09-20 23:08:21 +00003414/// parseDirectiveLine
Eli Bendersky17233942013-01-15 22:59:42 +00003415/// ::= .line [number]
Jim Grosbach4b905842013-09-20 23:08:21 +00003416bool AsmParser::parseDirectiveLine() {
Nirav Davea645433c2016-07-18 15:24:03 +00003417 int64_t LineNumber;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003418 if (getLexer().is(AsmToken::Integer)) {
Nirav Davea645433c2016-07-18 15:24:03 +00003419 if (parseIntToken(LineNumber, "unexpected token in '.line' directive"))
3420 return true;
Jim Grosbach4b905842013-09-20 23:08:21 +00003421 (void)LineNumber;
Eli Bendersky17233942013-01-15 22:59:42 +00003422 // FIXME: Do something with the .line.
3423 }
Nirav Davea645433c2016-07-18 15:24:03 +00003424 if (parseToken(AsmToken::EndOfStatement,
3425 "unexpected token in '.line' directive"))
3426 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003427
3428 return false;
3429}
3430
Jim Grosbach4b905842013-09-20 23:08:21 +00003431/// parseDirectiveLoc
Eli Bendersky17233942013-01-15 22:59:42 +00003432/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
3433/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
3434/// The first number is a file number, must have been previously assigned with
3435/// a .file directive, the second number is the line number and optionally the
3436/// third number is a column position (zero if not specified). The remaining
3437/// optional items are .loc sub-directives.
Jim Grosbach4b905842013-09-20 23:08:21 +00003438bool AsmParser::parseDirectiveLoc() {
Nirav Davea645433c2016-07-18 15:24:03 +00003439 int64_t FileNumber = 0, LineNumber = 0;
3440 SMLoc Loc = getTok().getLoc();
3441 if (parseIntToken(FileNumber, "unexpected token in '.loc' directive") ||
Paul Robinson11539b02018-06-22 14:16:11 +00003442 check(FileNumber < 1 && Ctx.getDwarfVersion() < 5, Loc,
Nirav Davea645433c2016-07-18 15:24:03 +00003443 "file number less than one in '.loc' directive") ||
3444 check(!getContext().isValidDwarfFileNumber(FileNumber), Loc,
3445 "unassigned file number in '.loc' directive"))
3446 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003447
Nirav Davea645433c2016-07-18 15:24:03 +00003448 // optional
Eli Bendersky17233942013-01-15 22:59:42 +00003449 if (getLexer().is(AsmToken::Integer)) {
3450 LineNumber = getTok().getIntVal();
Adrian Prantl6ac40032013-09-26 23:37:11 +00003451 if (LineNumber < 0)
3452 return TokError("line number less than zero in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003453 Lex();
3454 }
3455
3456 int64_t ColumnPos = 0;
3457 if (getLexer().is(AsmToken::Integer)) {
3458 ColumnPos = getTok().getIntVal();
3459 if (ColumnPos < 0)
3460 return TokError("column position less than zero in '.loc' directive");
3461 Lex();
3462 }
3463
3464 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
3465 unsigned Isa = 0;
3466 int64_t Discriminator = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003467
Nirav Dave1a9044b2016-10-24 14:35:29 +00003468 auto parseLocOp = [&]() -> bool {
3469 StringRef Name;
3470 SMLoc Loc = getTok().getLoc();
3471 if (parseIdentifier(Name))
3472 return TokError("unexpected token in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003473
Nirav Dave1a9044b2016-10-24 14:35:29 +00003474 if (Name == "basic_block")
3475 Flags |= DWARF2_FLAG_BASIC_BLOCK;
3476 else if (Name == "prologue_end")
3477 Flags |= DWARF2_FLAG_PROLOGUE_END;
3478 else if (Name == "epilogue_begin")
3479 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
3480 else if (Name == "is_stmt") {
3481 Loc = getTok().getLoc();
3482 const MCExpr *Value;
3483 if (parseExpression(Value))
3484 return true;
3485 // The expression must be the constant 0 or 1.
3486 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3487 int Value = MCE->getValue();
3488 if (Value == 0)
3489 Flags &= ~DWARF2_FLAG_IS_STMT;
3490 else if (Value == 1)
3491 Flags |= DWARF2_FLAG_IS_STMT;
3492 else
3493 return Error(Loc, "is_stmt value not 0 or 1");
Craig Topperf15655b2013-04-22 04:22:40 +00003494 } else {
Nirav Dave1a9044b2016-10-24 14:35:29 +00003495 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
Eli Bendersky17233942013-01-15 22:59:42 +00003496 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003497 } else if (Name == "isa") {
3498 Loc = getTok().getLoc();
3499 const MCExpr *Value;
3500 if (parseExpression(Value))
3501 return true;
3502 // The expression must be a constant greater or equal to 0.
3503 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3504 int Value = MCE->getValue();
3505 if (Value < 0)
3506 return Error(Loc, "isa number less than zero");
3507 Isa = Value;
3508 } else {
3509 return Error(Loc, "isa number not a constant value");
3510 }
3511 } else if (Name == "discriminator") {
3512 if (parseAbsoluteExpression(Discriminator))
3513 return true;
3514 } else {
3515 return Error(Loc, "unknown sub-directive in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003516 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003517 return false;
3518 };
3519
Nirav Davee2369aa2016-10-26 17:28:58 +00003520 if (parseMany(parseLocOp, false /*hasComma*/))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003521 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003522
3523 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
3524 Isa, Discriminator, StringRef());
3525
3526 return false;
3527}
3528
Jim Grosbach4b905842013-09-20 23:08:21 +00003529/// parseDirectiveStabs
Eli Bendersky17233942013-01-15 22:59:42 +00003530/// ::= .stabs string, number, number, number
Jim Grosbach4b905842013-09-20 23:08:21 +00003531bool AsmParser::parseDirectiveStabs() {
Eli Bendersky17233942013-01-15 22:59:42 +00003532 return TokError("unsupported directive '.stabs'");
3533}
3534
Reid Kleckner2214ed82016-01-29 00:49:42 +00003535/// parseDirectiveCVFile
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003536/// ::= .cv_file number filename [checksum] [checksumkind]
Reid Kleckner2214ed82016-01-29 00:49:42 +00003537bool AsmParser::parseDirectiveCVFile() {
Nirav Davea645433c2016-07-18 15:24:03 +00003538 SMLoc FileNumberLoc = getTok().getLoc();
3539 int64_t FileNumber;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003540 std::string Filename;
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003541 std::string Checksum;
3542 int64_t ChecksumKind = 0;
Nirav Davea645433c2016-07-18 15:24:03 +00003543
3544 if (parseIntToken(FileNumber,
3545 "expected file number in '.cv_file' directive") ||
3546 check(FileNumber < 1, FileNumberLoc, "file number less than one") ||
3547 check(getTok().isNot(AsmToken::String),
3548 "unexpected token in '.cv_file' directive") ||
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003549 parseEscapedString(Filename))
Reid Klecknera5b1eef2016-08-26 17:58:37 +00003550 return true;
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003551 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
3552 if (check(getTok().isNot(AsmToken::String),
3553 "unexpected token in '.cv_file' directive") ||
3554 parseEscapedString(Checksum) ||
3555 parseIntToken(ChecksumKind,
3556 "expected checksum kind in '.cv_file' directive") ||
3557 parseToken(AsmToken::EndOfStatement,
3558 "unexpected token in '.cv_file' directive"))
3559 return true;
3560 }
Nirav Dave1ab71992016-07-18 19:35:21 +00003561
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003562 Checksum = fromHex(Checksum);
3563 void *CKMem = Ctx.allocate(Checksum.size(), 1);
3564 memcpy(CKMem, Checksum.data(), Checksum.size());
3565 ArrayRef<uint8_t> ChecksumAsBytes(reinterpret_cast<const uint8_t *>(CKMem),
3566 Checksum.size());
3567
3568 if (!getStreamer().EmitCVFileDirective(FileNumber, Filename, ChecksumAsBytes,
3569 static_cast<uint8_t>(ChecksumKind)))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003570 return Error(FileNumberLoc, "file number already allocated");
Reid Kleckner2214ed82016-01-29 00:49:42 +00003571
3572 return false;
3573}
3574
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003575bool AsmParser::parseCVFunctionId(int64_t &FunctionId,
3576 StringRef DirectiveName) {
3577 SMLoc Loc;
3578 return parseTokenLoc(Loc) ||
3579 parseIntToken(FunctionId, "expected function id in '" + DirectiveName +
3580 "' directive") ||
3581 check(FunctionId < 0 || FunctionId >= UINT_MAX, Loc,
3582 "expected function id within range [0, UINT_MAX)");
3583}
3584
3585bool AsmParser::parseCVFileId(int64_t &FileNumber, StringRef DirectiveName) {
3586 SMLoc Loc;
3587 return parseTokenLoc(Loc) ||
3588 parseIntToken(FileNumber, "expected integer in '" + DirectiveName +
3589 "' directive") ||
3590 check(FileNumber < 1, Loc, "file number less than one in '" +
3591 DirectiveName + "' directive") ||
3592 check(!getCVContext().isValidFileNumber(FileNumber), Loc,
3593 "unassigned file number in '" + DirectiveName + "' directive");
3594}
3595
3596/// parseDirectiveCVFuncId
3597/// ::= .cv_func_id FunctionId
3598///
3599/// Introduces a function ID that can be used with .cv_loc.
3600bool AsmParser::parseDirectiveCVFuncId() {
3601 SMLoc FunctionIdLoc = getTok().getLoc();
3602 int64_t FunctionId;
3603
3604 if (parseCVFunctionId(FunctionId, ".cv_func_id") ||
3605 parseToken(AsmToken::EndOfStatement,
3606 "unexpected token in '.cv_func_id' directive"))
3607 return true;
3608
3609 if (!getStreamer().EmitCVFuncIdDirective(FunctionId))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003610 return Error(FunctionIdLoc, "function id already allocated");
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003611
3612 return false;
3613}
3614
3615/// parseDirectiveCVInlineSiteId
3616/// ::= .cv_inline_site_id FunctionId
3617/// "within" IAFunc
3618/// "inlined_at" IAFile IALine [IACol]
3619///
3620/// Introduces a function ID that can be used with .cv_loc. Includes "inlined
3621/// at" source location information for use in the line table of the caller,
3622/// whether the caller is a real function or another inlined call site.
3623bool AsmParser::parseDirectiveCVInlineSiteId() {
3624 SMLoc FunctionIdLoc = getTok().getLoc();
3625 int64_t FunctionId;
3626 int64_t IAFunc;
3627 int64_t IAFile;
3628 int64_t IALine;
3629 int64_t IACol = 0;
3630
3631 // FunctionId
3632 if (parseCVFunctionId(FunctionId, ".cv_inline_site_id"))
3633 return true;
3634
3635 // "within"
3636 if (check((getLexer().isNot(AsmToken::Identifier) ||
3637 getTok().getIdentifier() != "within"),
3638 "expected 'within' identifier in '.cv_inline_site_id' directive"))
3639 return true;
3640 Lex();
3641
3642 // IAFunc
3643 if (parseCVFunctionId(IAFunc, ".cv_inline_site_id"))
3644 return true;
3645
3646 // "inlined_at"
3647 if (check((getLexer().isNot(AsmToken::Identifier) ||
3648 getTok().getIdentifier() != "inlined_at"),
3649 "expected 'inlined_at' identifier in '.cv_inline_site_id' "
3650 "directive") )
3651 return true;
3652 Lex();
3653
3654 // IAFile IALine
3655 if (parseCVFileId(IAFile, ".cv_inline_site_id") ||
3656 parseIntToken(IALine, "expected line number after 'inlined_at'"))
3657 return true;
3658
3659 // [IACol]
3660 if (getLexer().is(AsmToken::Integer)) {
3661 IACol = getTok().getIntVal();
3662 Lex();
3663 }
3664
3665 if (parseToken(AsmToken::EndOfStatement,
3666 "unexpected token in '.cv_inline_site_id' directive"))
3667 return true;
3668
3669 if (!getStreamer().EmitCVInlineSiteIdDirective(FunctionId, IAFunc, IAFile,
3670 IALine, IACol, FunctionIdLoc))
Nirav Dave2364748a2016-09-16 18:30:20 +00003671 return Error(FunctionIdLoc, "function id already allocated");
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003672
3673 return false;
3674}
3675
Reid Kleckner2214ed82016-01-29 00:49:42 +00003676/// parseDirectiveCVLoc
3677/// ::= .cv_loc FunctionId FileNumber [LineNumber] [ColumnPos] [prologue_end]
3678/// [is_stmt VALUE]
3679/// The first number is a file number, must have been previously assigned with
3680/// a .file directive, the second number is the line number and optionally the
3681/// third number is a column position (zero if not specified). The remaining
3682/// optional items are .loc sub-directives.
3683bool AsmParser::parseDirectiveCVLoc() {
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003684 SMLoc DirectiveLoc = getTok().getLoc();
Nirav Davea645433c2016-07-18 15:24:03 +00003685 int64_t FunctionId, FileNumber;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003686 if (parseCVFunctionId(FunctionId, ".cv_loc") ||
3687 parseCVFileId(FileNumber, ".cv_loc"))
Nirav Davea645433c2016-07-18 15:24:03 +00003688 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003689
3690 int64_t LineNumber = 0;
3691 if (getLexer().is(AsmToken::Integer)) {
3692 LineNumber = getTok().getIntVal();
3693 if (LineNumber < 0)
3694 return TokError("line number less than zero in '.cv_loc' directive");
3695 Lex();
3696 }
3697
3698 int64_t ColumnPos = 0;
3699 if (getLexer().is(AsmToken::Integer)) {
3700 ColumnPos = getTok().getIntVal();
3701 if (ColumnPos < 0)
3702 return TokError("column position less than zero in '.cv_loc' directive");
3703 Lex();
3704 }
3705
3706 bool PrologueEnd = false;
3707 uint64_t IsStmt = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003708
3709 auto parseOp = [&]() -> bool {
Reid Kleckner2214ed82016-01-29 00:49:42 +00003710 StringRef Name;
3711 SMLoc Loc = getTok().getLoc();
3712 if (parseIdentifier(Name))
3713 return TokError("unexpected token in '.cv_loc' directive");
Reid Kleckner2214ed82016-01-29 00:49:42 +00003714 if (Name == "prologue_end")
3715 PrologueEnd = true;
3716 else if (Name == "is_stmt") {
3717 Loc = getTok().getLoc();
3718 const MCExpr *Value;
3719 if (parseExpression(Value))
3720 return true;
3721 // The expression must be the constant 0 or 1.
3722 IsStmt = ~0ULL;
3723 if (const auto *MCE = dyn_cast<MCConstantExpr>(Value))
3724 IsStmt = MCE->getValue();
3725
3726 if (IsStmt > 1)
3727 return Error(Loc, "is_stmt value not 0 or 1");
3728 } else {
3729 return Error(Loc, "unknown sub-directive in '.cv_loc' directive");
3730 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003731 return false;
3732 };
3733
3734 if (parseMany(parseOp, false /*hasComma*/))
3735 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003736
3737 getStreamer().EmitCVLocDirective(FunctionId, FileNumber, LineNumber,
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003738 ColumnPos, PrologueEnd, IsStmt, StringRef(),
3739 DirectiveLoc);
Reid Kleckner2214ed82016-01-29 00:49:42 +00003740 return false;
3741}
3742
3743/// parseDirectiveCVLinetable
3744/// ::= .cv_linetable FunctionId, FnStart, FnEnd
3745bool AsmParser::parseDirectiveCVLinetable() {
Nirav Davea645433c2016-07-18 15:24:03 +00003746 int64_t FunctionId;
3747 StringRef FnStartName, FnEndName;
3748 SMLoc Loc = getTok().getLoc();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003749 if (parseCVFunctionId(FunctionId, ".cv_linetable") ||
Nirav Davea645433c2016-07-18 15:24:03 +00003750 parseToken(AsmToken::Comma,
3751 "unexpected token in '.cv_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003752 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3753 "expected identifier in directive") ||
Nirav Davea645433c2016-07-18 15:24:03 +00003754 parseToken(AsmToken::Comma,
3755 "unexpected token in '.cv_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003756 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3757 "expected identifier in directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00003758 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003759
3760 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3761 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
3762
3763 getStreamer().EmitCVLinetableDirective(FunctionId, FnStartSym, FnEndSym);
3764 return false;
3765}
3766
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003767/// parseDirectiveCVInlineLinetable
David Majnemerc9911f22016-02-02 19:22:34 +00003768/// ::= .cv_inline_linetable PrimaryFunctionId FileId LineNum FnStart FnEnd
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003769bool AsmParser::parseDirectiveCVInlineLinetable() {
Nirav Davea645433c2016-07-18 15:24:03 +00003770 int64_t PrimaryFunctionId, SourceFileId, SourceLineNum;
3771 StringRef FnStartName, FnEndName;
3772 SMLoc Loc = getTok().getLoc();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003773 if (parseCVFunctionId(PrimaryFunctionId, ".cv_inline_linetable") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003774 parseTokenLoc(Loc) ||
Nirav Davea645433c2016-07-18 15:24:03 +00003775 parseIntToken(
3776 SourceFileId,
3777 "expected SourceField in '.cv_inline_linetable' directive") ||
3778 check(SourceFileId <= 0, Loc,
3779 "File id less than zero in '.cv_inline_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003780 parseTokenLoc(Loc) ||
Nirav Davea645433c2016-07-18 15:24:03 +00003781 parseIntToken(
3782 SourceLineNum,
3783 "expected SourceLineNum in '.cv_inline_linetable' directive") ||
3784 check(SourceLineNum < 0, Loc,
3785 "Line number less than zero in '.cv_inline_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003786 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3787 "expected identifier in directive") ||
3788 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3789 "expected identifier in directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00003790 return true;
David Majnemerc9911f22016-02-02 19:22:34 +00003791
Nirav Davea645433c2016-07-18 15:24:03 +00003792 if (parseToken(AsmToken::EndOfStatement, "Expected End of Statement"))
3793 return true;
3794
3795 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3796 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
Reid Kleckner1fcd6102016-02-02 17:41:18 +00003797 getStreamer().EmitCVInlineLinetableDirective(PrimaryFunctionId, SourceFileId,
3798 SourceLineNum, FnStartSym,
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003799 FnEndSym);
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003800 return false;
3801}
3802
David Majnemer408b5e62016-02-05 01:55:49 +00003803/// parseDirectiveCVDefRange
3804/// ::= .cv_def_range RangeStart RangeEnd (GapStart GapEnd)*, bytes*
3805bool AsmParser::parseDirectiveCVDefRange() {
3806 SMLoc Loc;
3807 std::vector<std::pair<const MCSymbol *, const MCSymbol *>> Ranges;
3808 while (getLexer().is(AsmToken::Identifier)) {
3809 Loc = getLexer().getLoc();
3810 StringRef GapStartName;
3811 if (parseIdentifier(GapStartName))
3812 return Error(Loc, "expected identifier in directive");
3813 MCSymbol *GapStartSym = getContext().getOrCreateSymbol(GapStartName);
3814
3815 Loc = getLexer().getLoc();
3816 StringRef GapEndName;
3817 if (parseIdentifier(GapEndName))
3818 return Error(Loc, "expected identifier in directive");
3819 MCSymbol *GapEndSym = getContext().getOrCreateSymbol(GapEndName);
3820
3821 Ranges.push_back({GapStartSym, GapEndSym});
3822 }
3823
David Majnemer408b5e62016-02-05 01:55:49 +00003824 std::string FixedSizePortion;
Nirav Davea645433c2016-07-18 15:24:03 +00003825 if (parseToken(AsmToken::Comma, "unexpected token in directive") ||
3826 parseEscapedString(FixedSizePortion))
David Majnemer408b5e62016-02-05 01:55:49 +00003827 return true;
David Majnemer408b5e62016-02-05 01:55:49 +00003828
3829 getStreamer().EmitCVDefRangeDirective(Ranges, FixedSizePortion);
3830 return false;
3831}
3832
Reid Kleckner06d02d02018-09-07 21:30:52 +00003833/// parseDirectiveCVString
3834/// ::= .cv_stringtable "string"
3835bool AsmParser::parseDirectiveCVString() {
3836 std::string Data;
3837 if (checkForValidSection() || parseEscapedString(Data))
3838 return addErrorSuffix(" in '.cv_string' directive");
3839
3840 // Put the string in the table and emit the offset.
3841 std::pair<StringRef, unsigned> Insertion =
3842 getCVContext().addToStringTable(Data);
3843 getStreamer().EmitIntValue(Insertion.second, 4);
3844 return false;
3845}
3846
Reid Kleckner2214ed82016-01-29 00:49:42 +00003847/// parseDirectiveCVStringTable
3848/// ::= .cv_stringtable
3849bool AsmParser::parseDirectiveCVStringTable() {
3850 getStreamer().EmitCVStringTableDirective();
3851 return false;
3852}
3853
3854/// parseDirectiveCVFileChecksums
3855/// ::= .cv_filechecksums
3856bool AsmParser::parseDirectiveCVFileChecksums() {
3857 getStreamer().EmitCVFileChecksumsDirective();
3858 return false;
3859}
3860
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003861/// parseDirectiveCVFileChecksumOffset
3862/// ::= .cv_filechecksumoffset fileno
3863bool AsmParser::parseDirectiveCVFileChecksumOffset() {
3864 int64_t FileNo;
3865 if (parseIntToken(FileNo, "expected identifier in directive"))
3866 return true;
3867 if (parseToken(AsmToken::EndOfStatement, "Expected End of Statement"))
3868 return true;
3869 getStreamer().EmitCVFileChecksumOffsetDirective(FileNo);
3870 return false;
3871}
3872
Reid Kleckner9cdd4df2017-10-11 21:24:33 +00003873/// parseDirectiveCVFPOData
3874/// ::= .cv_fpo_data procsym
3875bool AsmParser::parseDirectiveCVFPOData() {
3876 SMLoc DirLoc = getLexer().getLoc();
3877 StringRef ProcName;
3878 if (parseIdentifier(ProcName))
3879 return TokError("expected symbol name");
3880 if (parseEOL("unexpected tokens"))
3881 return addErrorSuffix(" in '.cv_fpo_data' directive");
3882 MCSymbol *ProcSym = getContext().getOrCreateSymbol(ProcName);
3883 getStreamer().EmitCVFPOData(ProcSym, DirLoc);
3884 return false;
3885}
3886
Jim Grosbach4b905842013-09-20 23:08:21 +00003887/// parseDirectiveCFISections
Eli Bendersky17233942013-01-15 22:59:42 +00003888/// ::= .cfi_sections section [, section]
Jim Grosbach4b905842013-09-20 23:08:21 +00003889bool AsmParser::parseDirectiveCFISections() {
Eli Bendersky17233942013-01-15 22:59:42 +00003890 StringRef Name;
3891 bool EH = false;
3892 bool Debug = false;
3893
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003894 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003895 return TokError("Expected an identifier");
3896
3897 if (Name == ".eh_frame")
3898 EH = true;
3899 else if (Name == ".debug_frame")
3900 Debug = true;
3901
3902 if (getLexer().is(AsmToken::Comma)) {
3903 Lex();
3904
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003905 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003906 return TokError("Expected an identifier");
3907
3908 if (Name == ".eh_frame")
3909 EH = true;
3910 else if (Name == ".debug_frame")
3911 Debug = true;
3912 }
3913
3914 getStreamer().EmitCFISections(EH, Debug);
3915 return false;
3916}
3917
Jim Grosbach4b905842013-09-20 23:08:21 +00003918/// parseDirectiveCFIStartProc
David Majnemere035cf92014-01-27 17:20:25 +00003919/// ::= .cfi_startproc [simple]
Jim Grosbach4b905842013-09-20 23:08:21 +00003920bool AsmParser::parseDirectiveCFIStartProc() {
David Majnemere035cf92014-01-27 17:20:25 +00003921 StringRef Simple;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003922 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
3923 if (check(parseIdentifier(Simple) || Simple != "simple",
3924 "unexpected token") ||
3925 parseToken(AsmToken::EndOfStatement))
3926 return addErrorSuffix(" in '.cfi_startproc' directive");
3927 }
Wouter van Oortmerssencc75e772018-11-12 20:15:01 +00003928
Kristina Brooks1a41a112018-10-19 12:14:30 +00003929 // TODO(kristina): Deal with a corner case of incorrect diagnostic context
3930 // being produced if this directive is emitted as part of preprocessor macro
3931 // expansion which can *ONLY* happen if Clang's cc1as is the API consumer.
3932 // Tools like llvm-mc on the other hand are not affected by it, and report
3933 // correct context information.
3934 getStreamer().EmitCFIStartProc(!Simple.empty(), Lexer.getLoc());
Eli Bendersky17233942013-01-15 22:59:42 +00003935 return false;
3936}
3937
Jim Grosbach4b905842013-09-20 23:08:21 +00003938/// parseDirectiveCFIEndProc
Eli Bendersky17233942013-01-15 22:59:42 +00003939/// ::= .cfi_endproc
Jim Grosbach4b905842013-09-20 23:08:21 +00003940bool AsmParser::parseDirectiveCFIEndProc() {
Eli Bendersky17233942013-01-15 22:59:42 +00003941 getStreamer().EmitCFIEndProc();
3942 return false;
3943}
3944
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003945/// parse register name or number.
Jim Grosbach4b905842013-09-20 23:08:21 +00003946bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
Eli Bendersky17233942013-01-15 22:59:42 +00003947 SMLoc DirectiveLoc) {
3948 unsigned RegNo;
3949
3950 if (getLexer().isNot(AsmToken::Integer)) {
3951 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
3952 return true;
Bill Wendlingbc07a892013-06-18 07:20:20 +00003953 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
Eli Bendersky17233942013-01-15 22:59:42 +00003954 } else
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003955 return parseAbsoluteExpression(Register);
Eli Bendersky17233942013-01-15 22:59:42 +00003956
3957 return false;
3958}
3959
Jim Grosbach4b905842013-09-20 23:08:21 +00003960/// parseDirectiveCFIDefCfa
Eli Bendersky17233942013-01-15 22:59:42 +00003961/// ::= .cfi_def_cfa register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003962bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003963 int64_t Register = 0, Offset = 0;
3964 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3965 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3966 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003967 return true;
3968
3969 getStreamer().EmitCFIDefCfa(Register, Offset);
3970 return false;
3971}
3972
Jim Grosbach4b905842013-09-20 23:08:21 +00003973/// parseDirectiveCFIDefCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003974/// ::= .cfi_def_cfa_offset offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003975bool AsmParser::parseDirectiveCFIDefCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00003976 int64_t Offset = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003977 if (parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003978 return true;
3979
3980 getStreamer().EmitCFIDefCfaOffset(Offset);
3981 return false;
3982}
3983
Jim Grosbach4b905842013-09-20 23:08:21 +00003984/// parseDirectiveCFIRegister
Eli Bendersky17233942013-01-15 22:59:42 +00003985/// ::= .cfi_register register, register
Jim Grosbach4b905842013-09-20 23:08:21 +00003986bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003987 int64_t Register1 = 0, Register2 = 0;
3988 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc) ||
3989 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3990 parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003991 return true;
3992
3993 getStreamer().EmitCFIRegister(Register1, Register2);
3994 return false;
3995}
3996
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00003997/// parseDirectiveCFIWindowSave
3998/// ::= .cfi_window_save
3999bool AsmParser::parseDirectiveCFIWindowSave() {
4000 getStreamer().EmitCFIWindowSave();
4001 return false;
4002}
4003
Jim Grosbach4b905842013-09-20 23:08:21 +00004004/// parseDirectiveCFIAdjustCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00004005/// ::= .cfi_adjust_cfa_offset adjustment
Jim Grosbach4b905842013-09-20 23:08:21 +00004006bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00004007 int64_t Adjustment = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004008 if (parseAbsoluteExpression(Adjustment))
Eli Bendersky17233942013-01-15 22:59:42 +00004009 return true;
4010
4011 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
4012 return false;
4013}
4014
Jim Grosbach4b905842013-09-20 23:08:21 +00004015/// parseDirectiveCFIDefCfaRegister
Eli Bendersky17233942013-01-15 22:59:42 +00004016/// ::= .cfi_def_cfa_register register
Jim Grosbach4b905842013-09-20 23:08:21 +00004017bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004018 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00004019 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00004020 return true;
4021
4022 getStreamer().EmitCFIDefCfaRegister(Register);
4023 return false;
4024}
4025
Jim Grosbach4b905842013-09-20 23:08:21 +00004026/// parseDirectiveCFIOffset
Eli Bendersky17233942013-01-15 22:59:42 +00004027/// ::= .cfi_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00004028bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004029 int64_t Register = 0;
4030 int64_t Offset = 0;
4031
Nirav Davea645433c2016-07-18 15:24:03 +00004032 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
4033 parseToken(AsmToken::Comma, "unexpected token in directive") ||
4034 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00004035 return true;
4036
4037 getStreamer().EmitCFIOffset(Register, Offset);
4038 return false;
4039}
4040
Jim Grosbach4b905842013-09-20 23:08:21 +00004041/// parseDirectiveCFIRelOffset
Eli Bendersky17233942013-01-15 22:59:42 +00004042/// ::= .cfi_rel_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00004043bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00004044 int64_t Register = 0, Offset = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00004045
Nirav Davea645433c2016-07-18 15:24:03 +00004046 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
4047 parseToken(AsmToken::Comma, "unexpected token in directive") ||
4048 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00004049 return true;
4050
4051 getStreamer().EmitCFIRelOffset(Register, Offset);
4052 return false;
4053}
4054
4055static bool isValidEncoding(int64_t Encoding) {
4056 if (Encoding & ~0xff)
4057 return false;
4058
4059 if (Encoding == dwarf::DW_EH_PE_omit)
4060 return true;
4061
4062 const unsigned Format = Encoding & 0xf;
4063 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
4064 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
4065 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
4066 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
4067 return false;
4068
4069 const unsigned Application = Encoding & 0x70;
4070 if (Application != dwarf::DW_EH_PE_absptr &&
4071 Application != dwarf::DW_EH_PE_pcrel)
4072 return false;
4073
4074 return true;
4075}
4076
Jim Grosbach4b905842013-09-20 23:08:21 +00004077/// parseDirectiveCFIPersonalityOrLsda
Eli Bendersky17233942013-01-15 22:59:42 +00004078/// IsPersonality true for cfi_personality, false for cfi_lsda
4079/// ::= .cfi_personality encoding, [symbol_name]
4080/// ::= .cfi_lsda encoding, [symbol_name]
Jim Grosbach4b905842013-09-20 23:08:21 +00004081bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
Eli Bendersky17233942013-01-15 22:59:42 +00004082 int64_t Encoding = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004083 if (parseAbsoluteExpression(Encoding))
Eli Bendersky17233942013-01-15 22:59:42 +00004084 return true;
4085 if (Encoding == dwarf::DW_EH_PE_omit)
4086 return false;
4087
Eli Bendersky17233942013-01-15 22:59:42 +00004088 StringRef Name;
Nirav Davea645433c2016-07-18 15:24:03 +00004089 if (check(!isValidEncoding(Encoding), "unsupported encoding.") ||
4090 parseToken(AsmToken::Comma, "unexpected token in directive") ||
4091 check(parseIdentifier(Name), "expected identifier in directive"))
4092 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004093
Jim Grosbach6f482002015-05-18 18:43:14 +00004094 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Eli Bendersky17233942013-01-15 22:59:42 +00004095
4096 if (IsPersonality)
4097 getStreamer().EmitCFIPersonality(Sym, Encoding);
4098 else
4099 getStreamer().EmitCFILsda(Sym, Encoding);
4100 return false;
4101}
4102
Jim Grosbach4b905842013-09-20 23:08:21 +00004103/// parseDirectiveCFIRememberState
Eli Bendersky17233942013-01-15 22:59:42 +00004104/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00004105bool AsmParser::parseDirectiveCFIRememberState() {
Eli Bendersky17233942013-01-15 22:59:42 +00004106 getStreamer().EmitCFIRememberState();
4107 return false;
4108}
4109
Jim Grosbach4b905842013-09-20 23:08:21 +00004110/// parseDirectiveCFIRestoreState
Eli Bendersky17233942013-01-15 22:59:42 +00004111/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00004112bool AsmParser::parseDirectiveCFIRestoreState() {
Eli Bendersky17233942013-01-15 22:59:42 +00004113 getStreamer().EmitCFIRestoreState();
4114 return false;
4115}
4116
Jim Grosbach4b905842013-09-20 23:08:21 +00004117/// parseDirectiveCFISameValue
Eli Bendersky17233942013-01-15 22:59:42 +00004118/// ::= .cfi_same_value register
Jim Grosbach4b905842013-09-20 23:08:21 +00004119bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004120 int64_t Register = 0;
4121
Jim Grosbach4b905842013-09-20 23:08:21 +00004122 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00004123 return true;
4124
4125 getStreamer().EmitCFISameValue(Register);
4126 return false;
4127}
4128
Jim Grosbach4b905842013-09-20 23:08:21 +00004129/// parseDirectiveCFIRestore
Eli Bendersky17233942013-01-15 22:59:42 +00004130/// ::= .cfi_restore register
Jim Grosbach4b905842013-09-20 23:08:21 +00004131bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004132 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00004133 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00004134 return true;
4135
4136 getStreamer().EmitCFIRestore(Register);
4137 return false;
4138}
4139
Jim Grosbach4b905842013-09-20 23:08:21 +00004140/// parseDirectiveCFIEscape
Eli Bendersky17233942013-01-15 22:59:42 +00004141/// ::= .cfi_escape expression[,...]
Jim Grosbach4b905842013-09-20 23:08:21 +00004142bool AsmParser::parseDirectiveCFIEscape() {
Eli Bendersky17233942013-01-15 22:59:42 +00004143 std::string Values;
4144 int64_t CurrValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004145 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00004146 return true;
4147
4148 Values.push_back((uint8_t)CurrValue);
4149
4150 while (getLexer().is(AsmToken::Comma)) {
4151 Lex();
4152
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004153 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00004154 return true;
4155
4156 Values.push_back((uint8_t)CurrValue);
4157 }
4158
4159 getStreamer().EmitCFIEscape(Values);
4160 return false;
4161}
4162
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +00004163/// parseDirectiveCFIReturnColumn
4164/// ::= .cfi_return_column register
4165bool AsmParser::parseDirectiveCFIReturnColumn(SMLoc DirectiveLoc) {
4166 int64_t Register = 0;
4167 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
4168 return true;
4169 getStreamer().EmitCFIReturnColumn(Register);
4170 return false;
4171}
4172
Jim Grosbach4b905842013-09-20 23:08:21 +00004173/// parseDirectiveCFISignalFrame
Eli Bendersky17233942013-01-15 22:59:42 +00004174/// ::= .cfi_signal_frame
Jim Grosbach4b905842013-09-20 23:08:21 +00004175bool AsmParser::parseDirectiveCFISignalFrame() {
Nirav Davea645433c2016-07-18 15:24:03 +00004176 if (parseToken(AsmToken::EndOfStatement,
4177 "unexpected token in '.cfi_signal_frame'"))
4178 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004179
4180 getStreamer().EmitCFISignalFrame();
4181 return false;
4182}
4183
Jim Grosbach4b905842013-09-20 23:08:21 +00004184/// parseDirectiveCFIUndefined
Eli Bendersky17233942013-01-15 22:59:42 +00004185/// ::= .cfi_undefined register
Jim Grosbach4b905842013-09-20 23:08:21 +00004186bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004187 int64_t Register = 0;
4188
Jim Grosbach4b905842013-09-20 23:08:21 +00004189 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00004190 return true;
4191
4192 getStreamer().EmitCFIUndefined(Register);
4193 return false;
4194}
4195
Michael Zuckerman56704612017-05-01 13:20:12 +00004196/// parseDirectiveAltmacro
4197/// ::= .altmacro
4198/// ::= .noaltmacro
4199bool AsmParser::parseDirectiveAltmacro(StringRef Directive) {
4200 if (getLexer().isNot(AsmToken::EndOfStatement))
4201 return TokError("unexpected token in '" + Directive + "' directive");
Craig Topperc81aff72018-09-25 20:55:55 +00004202 AltMacroMode = (Directive == ".altmacro");
Michael Zuckerman56704612017-05-01 13:20:12 +00004203 return false;
4204}
4205
Jim Grosbach4b905842013-09-20 23:08:21 +00004206/// parseDirectiveMacrosOnOff
Eli Bendersky17233942013-01-15 22:59:42 +00004207/// ::= .macros_on
4208/// ::= .macros_off
Jim Grosbach4b905842013-09-20 23:08:21 +00004209bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
Nirav Davea645433c2016-07-18 15:24:03 +00004210 if (parseToken(AsmToken::EndOfStatement,
4211 "unexpected token in '" + Directive + "' directive"))
4212 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004213
Jim Grosbach4b905842013-09-20 23:08:21 +00004214 setMacrosEnabled(Directive == ".macros_on");
Eli Bendersky17233942013-01-15 22:59:42 +00004215 return false;
4216}
4217
Jim Grosbach4b905842013-09-20 23:08:21 +00004218/// parseDirectiveMacro
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00004219/// ::= .macro name[,] [parameters]
Jim Grosbach4b905842013-09-20 23:08:21 +00004220bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004221 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004222 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00004223 return TokError("expected identifier in '.macro' directive");
4224
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00004225 if (getLexer().is(AsmToken::Comma))
4226 Lex();
4227
Eli Bendersky17233942013-01-15 22:59:42 +00004228 MCAsmMacroParameters Parameters;
David Majnemer91fc4c22014-01-29 18:57:46 +00004229 while (getLexer().isNot(AsmToken::EndOfStatement)) {
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00004230
Alexander Kornienko8c0809c2015-01-15 11:41:30 +00004231 if (!Parameters.empty() && Parameters.back().Vararg)
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00004232 return Error(Lexer.getLoc(),
4233 "Vararg parameter '" + Parameters.back().Name +
4234 "' should be last one in the list of parameters.");
4235
David Majnemer91fc4c22014-01-29 18:57:46 +00004236 MCAsmMacroParameter Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00004237 if (parseIdentifier(Parameter.Name))
David Majnemer91fc4c22014-01-29 18:57:46 +00004238 return TokError("expected identifier in '.macro' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00004239
Coby Tayreebedaae02017-04-08 20:29:03 +00004240 // Emit an error if two (or more) named parameters share the same name
4241 for (const MCAsmMacroParameter& CurrParam : Parameters)
4242 if (CurrParam.Name.equals(Parameter.Name))
4243 return TokError("macro '" + Name + "' has multiple parameters"
4244 " named '" + Parameter.Name + "'");
4245
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00004246 if (Lexer.is(AsmToken::Colon)) {
4247 Lex(); // consume ':'
4248
4249 SMLoc QualLoc;
4250 StringRef Qualifier;
4251
4252 QualLoc = Lexer.getLoc();
4253 if (parseIdentifier(Qualifier))
4254 return Error(QualLoc, "missing parameter qualifier for "
4255 "'" + Parameter.Name + "' in macro '" + Name + "'");
4256
4257 if (Qualifier == "req")
4258 Parameter.Required = true;
Kevin Enderbye3c13462014-08-04 23:14:37 +00004259 else if (Qualifier == "vararg")
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00004260 Parameter.Vararg = true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00004261 else
4262 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
4263 "for '" + Parameter.Name + "' in macro '" + Name + "'");
4264 }
4265
David Majnemer91fc4c22014-01-29 18:57:46 +00004266 if (getLexer().is(AsmToken::Equal)) {
4267 Lex();
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00004268
4269 SMLoc ParamLoc;
4270
4271 ParamLoc = Lexer.getLoc();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00004272 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
David Majnemer91fc4c22014-01-29 18:57:46 +00004273 return true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00004274
4275 if (Parameter.Required)
4276 Warning(ParamLoc, "pointless default value for required parameter "
4277 "'" + Parameter.Name + "' in macro '" + Name + "'");
Eli Bendersky17233942013-01-15 22:59:42 +00004278 }
David Majnemer91fc4c22014-01-29 18:57:46 +00004279
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00004280 Parameters.push_back(std::move(Parameter));
David Majnemer91fc4c22014-01-29 18:57:46 +00004281
4282 if (getLexer().is(AsmToken::Comma))
4283 Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00004284 }
4285
Nirav Dave1180e6892016-06-02 17:15:05 +00004286 // Eat just the end of statement.
4287 Lexer.Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00004288
Nirav Dave1180e6892016-06-02 17:15:05 +00004289 // Consuming deferred text, so use Lexer.Lex to ignore Lexing Errors
Eli Bendersky17233942013-01-15 22:59:42 +00004290 AsmToken EndToken, StartToken = getTok();
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00004291 unsigned MacroDepth = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00004292 // Lex the macro definition.
Eugene Zelenko33d7b762016-08-23 17:14:32 +00004293 while (true) {
Nirav Dave1180e6892016-06-02 17:15:05 +00004294 // Ignore Lexing errors in macros.
4295 while (Lexer.is(AsmToken::Error)) {
4296 Lexer.Lex();
4297 }
4298
Eli Bendersky17233942013-01-15 22:59:42 +00004299 // Check whether we have reached the end of the file.
4300 if (getLexer().is(AsmToken::Eof))
4301 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
4302
4303 // Otherwise, check whether we have reach the .endmacro.
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00004304 if (getLexer().is(AsmToken::Identifier)) {
4305 if (getTok().getIdentifier() == ".endm" ||
4306 getTok().getIdentifier() == ".endmacro") {
4307 if (MacroDepth == 0) { // Outermost macro.
4308 EndToken = getTok();
Nirav Dave1180e6892016-06-02 17:15:05 +00004309 Lexer.Lex();
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00004310 if (getLexer().isNot(AsmToken::EndOfStatement))
4311 return TokError("unexpected token in '" + EndToken.getIdentifier() +
4312 "' directive");
4313 break;
4314 } else {
4315 // Otherwise we just found the end of an inner macro.
4316 --MacroDepth;
4317 }
4318 } else if (getTok().getIdentifier() == ".macro") {
4319 // We allow nested macros. Those aren't instantiated until the outermost
4320 // macro is expanded so just ignore them for now.
4321 ++MacroDepth;
4322 }
Eli Bendersky17233942013-01-15 22:59:42 +00004323 }
4324
4325 // Otherwise, scan til the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004326 eatToEndOfStatement();
Eli Bendersky17233942013-01-15 22:59:42 +00004327 }
4328
Rafael Espindola22c38a02018-02-14 16:34:27 +00004329 if (getContext().lookupMacro(Name)) {
Eli Bendersky17233942013-01-15 22:59:42 +00004330 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
4331 }
4332
4333 const char *BodyStart = StartToken.getLoc().getPointer();
4334 const char *BodyEnd = EndToken.getLoc().getPointer();
4335 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Jim Grosbach4b905842013-09-20 23:08:21 +00004336 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
Oliver Stannardc3e7c6d2018-03-06 15:32:34 +00004337 MCAsmMacro Macro(Name, Body, std::move(Parameters));
4338 DEBUG_WITH_TYPE("asm-macros", dbgs() << "Defining new macro:\n";
4339 Macro.dump());
4340 getContext().defineMacro(Name, std::move(Macro));
Eli Bendersky17233942013-01-15 22:59:42 +00004341 return false;
4342}
4343
Jim Grosbach4b905842013-09-20 23:08:21 +00004344/// checkForBadMacro
Kevin Enderby81c944c2013-01-22 21:44:53 +00004345///
4346/// With the support added for named parameters there may be code out there that
4347/// is transitioning from positional parameters. In versions of gas that did
Alp Tokercb402912014-01-24 17:20:08 +00004348/// not support named parameters they would be ignored on the macro definition.
Kevin Enderby81c944c2013-01-22 21:44:53 +00004349/// But to support both styles of parameters this is not possible so if a macro
Alp Tokercb402912014-01-24 17:20:08 +00004350/// definition has named parameters but does not use them and has what appears
Kevin Enderby81c944c2013-01-22 21:44:53 +00004351/// to be positional parameters, strings like $1, $2, ... and $n, then issue a
4352/// warning that the positional parameter found in body which have no effect.
4353/// Hoping the developer will either remove the named parameters from the macro
Alp Tokercb402912014-01-24 17:20:08 +00004354/// definition so the positional parameters get used if that was what was
Kevin Enderby81c944c2013-01-22 21:44:53 +00004355/// intended or change the macro to use the named parameters. It is possible
4356/// this warning will trigger when the none of the named parameters are used
4357/// and the strings like $1 are infact to simply to be passed trough unchanged.
Jim Grosbach4b905842013-09-20 23:08:21 +00004358void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
Kevin Enderby81c944c2013-01-22 21:44:53 +00004359 StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00004360 ArrayRef<MCAsmMacroParameter> Parameters) {
Kevin Enderby81c944c2013-01-22 21:44:53 +00004361 // If this macro is not defined with named parameters the warning we are
4362 // checking for here doesn't apply.
4363 unsigned NParameters = Parameters.size();
4364 if (NParameters == 0)
4365 return;
4366
4367 bool NamedParametersFound = false;
4368 bool PositionalParametersFound = false;
4369
4370 // Look at the body of the macro for use of both the named parameters and what
4371 // are likely to be positional parameters. This is what expandMacro() is
4372 // doing when it finds the parameters in the body.
4373 while (!Body.empty()) {
4374 // Scan for the next possible parameter.
4375 std::size_t End = Body.size(), Pos = 0;
4376 for (; Pos != End; ++Pos) {
4377 // Check for a substitution or escape.
4378 // This macro is defined with parameters, look for \foo, \bar, etc.
4379 if (Body[Pos] == '\\' && Pos + 1 != End)
4380 break;
4381
4382 // This macro should have parameters, but look for $0, $1, ..., $n too.
4383 if (Body[Pos] != '$' || Pos + 1 == End)
4384 continue;
4385 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00004386 if (Next == '$' || Next == 'n' ||
4387 isdigit(static_cast<unsigned char>(Next)))
Kevin Enderby81c944c2013-01-22 21:44:53 +00004388 break;
4389 }
4390
4391 // Check if we reached the end.
4392 if (Pos == End)
4393 break;
4394
4395 if (Body[Pos] == '$') {
Jim Grosbach4b905842013-09-20 23:08:21 +00004396 switch (Body[Pos + 1]) {
4397 // $$ => $
Kevin Enderby81c944c2013-01-22 21:44:53 +00004398 case '$':
4399 break;
4400
Jim Grosbach4b905842013-09-20 23:08:21 +00004401 // $n => number of arguments
Kevin Enderby81c944c2013-01-22 21:44:53 +00004402 case 'n':
4403 PositionalParametersFound = true;
4404 break;
4405
Jim Grosbach4b905842013-09-20 23:08:21 +00004406 // $[0-9] => argument
Kevin Enderby81c944c2013-01-22 21:44:53 +00004407 default: {
4408 PositionalParametersFound = true;
4409 break;
Jim Grosbach4b905842013-09-20 23:08:21 +00004410 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00004411 }
4412 Pos += 2;
4413 } else {
4414 unsigned I = Pos + 1;
4415 while (isIdentifierChar(Body[I]) && I + 1 != End)
4416 ++I;
4417
Jim Grosbach4b905842013-09-20 23:08:21 +00004418 const char *Begin = Body.data() + Pos + 1;
4419 StringRef Argument(Begin, I - (Pos + 1));
Kevin Enderby81c944c2013-01-22 21:44:53 +00004420 unsigned Index = 0;
4421 for (; Index < NParameters; ++Index)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00004422 if (Parameters[Index].Name == Argument)
Kevin Enderby81c944c2013-01-22 21:44:53 +00004423 break;
4424
4425 if (Index == NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00004426 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
4427 Pos += 3;
4428 else {
4429 Pos = I;
4430 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00004431 } else {
4432 NamedParametersFound = true;
4433 Pos += 1 + Argument.size();
4434 }
4435 }
4436 // Update the scan point.
4437 Body = Body.substr(Pos);
4438 }
4439
4440 if (!NamedParametersFound && PositionalParametersFound)
4441 Warning(DirectiveLoc, "macro defined with named parameters which are not "
4442 "used in macro body, possible positional parameter "
4443 "found in body which will have no effect");
4444}
4445
Nico Weber155dccd12014-07-24 17:08:39 +00004446/// parseDirectiveExitMacro
4447/// ::= .exitm
4448bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
Nirav Davea645433c2016-07-18 15:24:03 +00004449 if (parseToken(AsmToken::EndOfStatement,
4450 "unexpected token in '" + Directive + "' directive"))
4451 return true;
Nico Weber155dccd12014-07-24 17:08:39 +00004452
4453 if (!isInsideMacroInstantiation())
4454 return TokError("unexpected '" + Directive + "' in file, "
4455 "no current macro definition");
4456
4457 // Exit all conditionals that are active in the current macro.
4458 while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
4459 TheCondState = TheCondStack.back();
4460 TheCondStack.pop_back();
4461 }
4462
4463 handleMacroExit();
4464 return false;
4465}
4466
Jim Grosbach4b905842013-09-20 23:08:21 +00004467/// parseDirectiveEndMacro
Eli Bendersky17233942013-01-15 22:59:42 +00004468/// ::= .endm
4469/// ::= .endmacro
Jim Grosbach4b905842013-09-20 23:08:21 +00004470bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
Eli Bendersky17233942013-01-15 22:59:42 +00004471 if (getLexer().isNot(AsmToken::EndOfStatement))
4472 return TokError("unexpected token in '" + Directive + "' directive");
4473
4474 // If we are inside a macro instantiation, terminate the current
4475 // instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00004476 if (isInsideMacroInstantiation()) {
4477 handleMacroExit();
Eli Bendersky17233942013-01-15 22:59:42 +00004478 return false;
4479 }
4480
4481 // Otherwise, this .endmacro is a stray entry in the file; well formed
4482 // .endmacro directives are handled during the macro definition parsing.
4483 return TokError("unexpected '" + Directive + "' in file, "
Jim Grosbach4b905842013-09-20 23:08:21 +00004484 "no current macro definition");
Eli Bendersky17233942013-01-15 22:59:42 +00004485}
4486
Jim Grosbach4b905842013-09-20 23:08:21 +00004487/// parseDirectivePurgeMacro
Eli Bendersky17233942013-01-15 22:59:42 +00004488/// ::= .purgem
Jim Grosbach4b905842013-09-20 23:08:21 +00004489bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004490 StringRef Name;
Nirav Davea645433c2016-07-18 15:24:03 +00004491 SMLoc Loc;
Nirav Daved8858ca2016-08-30 14:15:43 +00004492 if (parseTokenLoc(Loc) ||
4493 check(parseIdentifier(Name), Loc,
4494 "expected identifier in '.purgem' directive") ||
Nirav Davea645433c2016-07-18 15:24:03 +00004495 parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00004496 "unexpected token in '.purgem' directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00004497 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004498
Rafael Espindola22c38a02018-02-14 16:34:27 +00004499 if (!getContext().lookupMacro(Name))
Nirav Dave1ab71992016-07-18 19:35:21 +00004500 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
4501
Rafael Espindola22c38a02018-02-14 16:34:27 +00004502 getContext().undefineMacro(Name);
Oliver Stannardc3e7c6d2018-03-06 15:32:34 +00004503 DEBUG_WITH_TYPE("asm-macros", dbgs()
4504 << "Un-defining macro: " << Name << "\n");
Eli Bendersky17233942013-01-15 22:59:42 +00004505 return false;
4506}
Eli Benderskyf483ff92012-12-20 19:05:53 +00004507
Jim Grosbach4b905842013-09-20 23:08:21 +00004508/// parseDirectiveBundleAlignMode
Eli Benderskyf483ff92012-12-20 19:05:53 +00004509/// ::= {.bundle_align_mode} expression
Jim Grosbach4b905842013-09-20 23:08:21 +00004510bool AsmParser::parseDirectiveBundleAlignMode() {
Eli Benderskyf483ff92012-12-20 19:05:53 +00004511 // Expect a single argument: an expression that evaluates to a constant
4512 // in the inclusive range 0-30.
4513 SMLoc ExprLoc = getLexer().getLoc();
4514 int64_t AlignSizePow2;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004515 if (checkForValidSection() || parseAbsoluteExpression(AlignSizePow2) ||
Nirav Davea645433c2016-07-18 15:24:03 +00004516 parseToken(AsmToken::EndOfStatement, "unexpected token after expression "
4517 "in '.bundle_align_mode' "
4518 "directive") ||
4519 check(AlignSizePow2 < 0 || AlignSizePow2 > 30, ExprLoc,
4520 "invalid bundle alignment size (expected between 0 and 30)"))
Eli Benderskyf483ff92012-12-20 19:05:53 +00004521 return true;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004522
4523 // Because of AlignSizePow2's verified range we can safely truncate it to
4524 // unsigned.
4525 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
4526 return false;
4527}
4528
Jim Grosbach4b905842013-09-20 23:08:21 +00004529/// parseDirectiveBundleLock
Eli Bendersky802b6282013-01-07 21:51:08 +00004530/// ::= {.bundle_lock} [align_to_end]
Jim Grosbach4b905842013-09-20 23:08:21 +00004531bool AsmParser::parseDirectiveBundleLock() {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004532 if (checkForValidSection())
4533 return true;
Eli Bendersky802b6282013-01-07 21:51:08 +00004534 bool AlignToEnd = false;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004535
Nirav Dave1a9044b2016-10-24 14:35:29 +00004536 StringRef Option;
4537 SMLoc Loc = getTok().getLoc();
4538 const char *kInvalidOptionError =
4539 "invalid option for '.bundle_lock' directive";
Eli Bendersky802b6282013-01-07 21:51:08 +00004540
Nirav Dave1a9044b2016-10-24 14:35:29 +00004541 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
Nirav Davea645433c2016-07-18 15:24:03 +00004542 if (check(parseIdentifier(Option), Loc, kInvalidOptionError) ||
4543 check(Option != "align_to_end", Loc, kInvalidOptionError) ||
Nirav Dave1a9044b2016-10-24 14:35:29 +00004544 parseToken(AsmToken::EndOfStatement,
4545 "unexpected token after '.bundle_lock' directive option"))
Nirav Davea645433c2016-07-18 15:24:03 +00004546 return true;
Eli Bendersky802b6282013-01-07 21:51:08 +00004547 AlignToEnd = true;
4548 }
4549
Eli Bendersky802b6282013-01-07 21:51:08 +00004550 getStreamer().EmitBundleLock(AlignToEnd);
Eli Benderskyf483ff92012-12-20 19:05:53 +00004551 return false;
4552}
4553
Jim Grosbach4b905842013-09-20 23:08:21 +00004554/// parseDirectiveBundleLock
Eli Benderskyf483ff92012-12-20 19:05:53 +00004555/// ::= {.bundle_lock}
Jim Grosbach4b905842013-09-20 23:08:21 +00004556bool AsmParser::parseDirectiveBundleUnlock() {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004557 if (checkForValidSection() ||
4558 parseToken(AsmToken::EndOfStatement,
Nirav Davea645433c2016-07-18 15:24:03 +00004559 "unexpected token in '.bundle_unlock' directive"))
4560 return true;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004561
4562 getStreamer().EmitBundleUnlock();
4563 return false;
4564}
4565
Jim Grosbach4b905842013-09-20 23:08:21 +00004566/// parseDirectiveSpace
Eli Bendersky17233942013-01-15 22:59:42 +00004567/// ::= (.skip | .space) expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004568bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
Petr Hosek67a94a72016-05-28 05:57:48 +00004569 SMLoc NumBytesLoc = Lexer.getLoc();
4570 const MCExpr *NumBytes;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004571 if (checkForValidSection() || parseExpression(NumBytes))
Eli Bendersky17233942013-01-15 22:59:42 +00004572 return true;
4573
4574 int64_t FillExpr = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00004575 if (parseOptionalToken(AsmToken::Comma))
4576 if (parseAbsoluteExpression(FillExpr))
4577 return addErrorSuffix("in '" + Twine(IDVal) + "' directive");
4578 if (parseToken(AsmToken::EndOfStatement))
4579 return addErrorSuffix("in '" + Twine(IDVal) + "' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00004580
Eli Bendersky17233942013-01-15 22:59:42 +00004581 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
Petr Hosek67a94a72016-05-28 05:57:48 +00004582 getStreamer().emitFill(*NumBytes, FillExpr, NumBytesLoc);
Eli Bendersky17233942013-01-15 22:59:42 +00004583
4584 return false;
4585}
4586
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004587/// parseDirectiveDCB
4588/// ::= .dcb.{b, l, w} expression, expression
4589bool AsmParser::parseDirectiveDCB(StringRef IDVal, unsigned Size) {
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004590 SMLoc NumValuesLoc = Lexer.getLoc();
4591 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004592 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004593 return true;
4594
4595 if (NumValues < 0) {
4596 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4597 return false;
4598 }
4599
4600 if (parseToken(AsmToken::Comma,
4601 "unexpected token in '" + Twine(IDVal) + "' directive"))
4602 return true;
4603
4604 const MCExpr *Value;
4605 SMLoc ExprLoc = getLexer().getLoc();
4606 if (parseExpression(Value))
4607 return true;
4608
4609 // Special case constant expressions to match code generator.
4610 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
4611 assert(Size <= 8 && "Invalid size");
4612 uint64_t IntValue = MCE->getValue();
4613 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
4614 return Error(ExprLoc, "literal value out of range for directive");
4615 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4616 getStreamer().EmitIntValue(IntValue, Size);
4617 } else {
4618 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4619 getStreamer().EmitValue(Value, Size, ExprLoc);
4620 }
4621
4622 if (parseToken(AsmToken::EndOfStatement,
4623 "unexpected token in '" + Twine(IDVal) + "' directive"))
4624 return true;
4625
4626 return false;
4627}
4628
4629/// parseDirectiveRealDCB
4630/// ::= .dcb.{d, s} expression, expression
4631bool AsmParser::parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &Semantics) {
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004632 SMLoc NumValuesLoc = Lexer.getLoc();
4633 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004634 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004635 return true;
4636
4637 if (NumValues < 0) {
4638 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4639 return false;
4640 }
4641
4642 if (parseToken(AsmToken::Comma,
4643 "unexpected token in '" + Twine(IDVal) + "' directive"))
4644 return true;
4645
4646 APInt AsInt;
4647 if (parseRealValue(Semantics, AsInt))
4648 return true;
4649
4650 if (parseToken(AsmToken::EndOfStatement,
4651 "unexpected token in '" + Twine(IDVal) + "' directive"))
4652 return true;
4653
4654 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4655 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
4656 AsInt.getBitWidth() / 8);
4657
4658 return false;
4659}
4660
Petr Hosek85b2f672016-09-23 21:53:36 +00004661/// parseDirectiveDS
4662/// ::= .ds.{b, d, l, p, s, w, x} expression
4663bool AsmParser::parseDirectiveDS(StringRef IDVal, unsigned Size) {
Petr Hosek85b2f672016-09-23 21:53:36 +00004664 SMLoc NumValuesLoc = Lexer.getLoc();
4665 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004666 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek85b2f672016-09-23 21:53:36 +00004667 return true;
4668
4669 if (NumValues < 0) {
4670 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4671 return false;
4672 }
4673
4674 if (parseToken(AsmToken::EndOfStatement,
4675 "unexpected token in '" + Twine(IDVal) + "' directive"))
4676 return true;
4677
4678 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4679 getStreamer().emitFill(Size, 0);
4680
4681 return false;
4682}
4683
Jim Grosbach4b905842013-09-20 23:08:21 +00004684/// parseDirectiveLEB128
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004685/// ::= (.sleb128 | .uleb128) [ expression (, expression)* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004686bool AsmParser::parseDirectiveLEB128(bool Signed) {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004687 if (checkForValidSection())
4688 return true;
4689
Nirav Dave1a9044b2016-10-24 14:35:29 +00004690 auto parseOp = [&]() -> bool {
4691 const MCExpr *Value;
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004692 if (parseExpression(Value))
4693 return true;
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004694 if (Signed)
4695 getStreamer().EmitSLEB128Value(Value);
4696 else
4697 getStreamer().EmitULEB128Value(Value);
Nirav Dave1a9044b2016-10-24 14:35:29 +00004698 return false;
4699 };
Eli Bendersky17233942013-01-15 22:59:42 +00004700
Nirav Dave1a9044b2016-10-24 14:35:29 +00004701 if (parseMany(parseOp))
4702 return addErrorSuffix(" in directive");
Eli Bendersky17233942013-01-15 22:59:42 +00004703
4704 return false;
4705}
4706
Jim Grosbach4b905842013-09-20 23:08:21 +00004707/// parseDirectiveSymbolAttribute
Daniel Dunbara5508c82009-06-30 00:33:19 +00004708/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004709bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00004710 auto parseOp = [&]() -> bool {
4711 StringRef Name;
4712 SMLoc Loc = getTok().getLoc();
4713 if (parseIdentifier(Name))
4714 return Error(Loc, "expected identifier");
4715 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004716
Nirav Dave1a9044b2016-10-24 14:35:29 +00004717 // Assembler local symbols don't make any sense here. Complain loudly.
4718 if (Sym->isTemporary())
4719 return Error(Loc, "non-local symbol required");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004720
Nirav Dave1a9044b2016-10-24 14:35:29 +00004721 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
4722 return Error(Loc, "unable to emit symbol attribute");
4723 return false;
4724 };
Daniel Dunbara5508c82009-06-30 00:33:19 +00004725
Nirav Dave1a9044b2016-10-24 14:35:29 +00004726 if (parseMany(parseOp))
4727 return addErrorSuffix(" in directive");
Jan Wen Voungc7682872010-09-30 01:09:20 +00004728 return false;
Daniel Dunbara5508c82009-06-30 00:33:19 +00004729}
Chris Lattnera1e11f52009-07-07 20:30:46 +00004730
Jim Grosbach4b905842013-09-20 23:08:21 +00004731/// parseDirectiveComm
Chris Lattner28ad7542009-07-09 17:25:12 +00004732/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004733bool AsmParser::parseDirectiveComm(bool IsLocal) {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004734 if (checkForValidSection())
4735 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00004736
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004737 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004738 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004739 if (parseIdentifier(Name))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004740 return TokError("expected identifier in directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004741
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +00004742 // Handle the identifier as the key symbol.
Jim Grosbach6f482002015-05-18 18:43:14 +00004743 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Chris Lattnera1e11f52009-07-07 20:30:46 +00004744
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004745 if (getLexer().isNot(AsmToken::Comma))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004746 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00004747 Lex();
Chris Lattnera1e11f52009-07-07 20:30:46 +00004748
4749 int64_t Size;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004750 SMLoc SizeLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004751 if (parseAbsoluteExpression(Size))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004752 return true;
4753
4754 int64_t Pow2Alignment = 0;
4755 SMLoc Pow2AlignmentLoc;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004756 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan686ed8d2010-01-19 20:22:31 +00004757 Lex();
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004758 Pow2AlignmentLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004759 if (parseAbsoluteExpression(Pow2Alignment))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004760 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00004761
Benjamin Kramer68b9f052012-09-07 21:08:01 +00004762 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
4763 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00004764 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
4765
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00004766 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramer68b9f052012-09-07 21:08:01 +00004767 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
4768 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00004769 if (!isPowerOf2_64(Pow2Alignment))
4770 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
4771 Pow2Alignment = Log2_64(Pow2Alignment);
4772 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00004773 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00004774
Nirav Dave1a9044b2016-10-24 14:35:29 +00004775 if (parseToken(AsmToken::EndOfStatement,
4776 "unexpected token in '.comm' or '.lcomm' directive"))
4777 return true;
Chris Lattnera1e11f52009-07-07 20:30:46 +00004778
Chris Lattner28ad7542009-07-09 17:25:12 +00004779 // NOTE: a size of zero for a .comm should create a undefined symbol
4780 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattnera1e11f52009-07-07 20:30:46 +00004781 if (Size < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00004782 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
Jim Grosbach4b905842013-09-20 23:08:21 +00004783 "be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00004784
Eric Christopherbc818852010-05-14 01:38:54 +00004785 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattnera1e11f52009-07-07 20:30:46 +00004786 // may internally end up wanting an alignment in bytes.
4787 // FIXME: Diagnose overflow.
4788 if (Pow2Alignment < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00004789 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
Jim Grosbach4b905842013-09-20 23:08:21 +00004790 "alignment, can't be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00004791
Rafael Espindola13a79bb2017-02-02 21:26:06 +00004792 Sym->redefineIfPossible();
Daniel Dunbar6860ac72009-08-22 07:22:36 +00004793 if (!Sym->isUndefined())
Chris Lattnera1e11f52009-07-07 20:30:46 +00004794 return Error(IDLoc, "invalid symbol redefinition");
4795
Chris Lattner28ad7542009-07-09 17:25:12 +00004796 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00004797 if (IsLocal) {
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00004798 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00004799 return false;
4800 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00004801
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004802 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattnera1e11f52009-07-07 20:30:46 +00004803 return false;
4804}
Chris Lattner07cadaf2009-07-10 22:20:30 +00004805
Jim Grosbach4b905842013-09-20 23:08:21 +00004806/// parseDirectiveAbort
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004807/// ::= .abort [... message ...]
Jim Grosbach4b905842013-09-20 23:08:21 +00004808bool AsmParser::parseDirectiveAbort() {
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004809 // FIXME: Use loc from directive.
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004810 SMLoc Loc = getLexer().getLoc();
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004811
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004812 StringRef Str = parseStringToEndOfStatement();
Nirav Davea645433c2016-07-18 15:24:03 +00004813 if (parseToken(AsmToken::EndOfStatement,
4814 "unexpected token in '.abort' directive"))
4815 return true;
Kevin Enderby56523ce2009-07-13 23:15:14 +00004816
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004817 if (Str.empty())
Nirav Dave2364748a2016-09-16 18:30:20 +00004818 return Error(Loc, ".abort detected. Assembly stopping.");
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004819 else
Nirav Dave2364748a2016-09-16 18:30:20 +00004820 return Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004821 // FIXME: Actually abort assembly here.
Kevin Enderby56523ce2009-07-13 23:15:14 +00004822
4823 return false;
4824}
Kevin Enderbycbe475d2009-07-14 21:35:03 +00004825
Jim Grosbach4b905842013-09-20 23:08:21 +00004826/// parseDirectiveInclude
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004827/// ::= .include "filename"
Jim Grosbach4b905842013-09-20 23:08:21 +00004828bool AsmParser::parseDirectiveInclude() {
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004829 // Allow the strings to have escaped octal character sequence.
4830 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00004831 SMLoc IncludeLoc = getTok().getLoc();
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004832
Nirav Davea645433c2016-07-18 15:24:03 +00004833 if (check(getTok().isNot(AsmToken::String),
4834 "expected string in '.include' directive") ||
4835 parseEscapedString(Filename) ||
4836 check(getTok().isNot(AsmToken::EndOfStatement),
4837 "unexpected token in '.include' directive") ||
4838 // Attempt to switch the lexer to the included file before consuming the
4839 // end of statement to avoid losing it when we switch.
4840 check(enterIncludeFile(Filename), IncludeLoc,
4841 "Could not find include file '" + Filename + "'"))
Chris Lattner693fbb82009-07-16 06:14:39 +00004842 return true;
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004843
4844 return false;
4845}
Kevin Enderby09ea5702009-07-15 15:30:11 +00004846
Jim Grosbach4b905842013-09-20 23:08:21 +00004847/// parseDirectiveIncbin
Petr Hosek2f4ac442016-09-23 00:41:06 +00004848/// ::= .incbin "filename" [ , skip [ , count ] ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004849bool AsmParser::parseDirectiveIncbin() {
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004850 // Allow the strings to have escaped octal character sequence.
4851 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00004852 SMLoc IncbinLoc = getTok().getLoc();
4853 if (check(getTok().isNot(AsmToken::String),
4854 "expected string in '.incbin' directive") ||
Petr Hosek2f4ac442016-09-23 00:41:06 +00004855 parseEscapedString(Filename))
4856 return true;
4857
4858 int64_t Skip = 0;
4859 const MCExpr *Count = nullptr;
4860 SMLoc SkipLoc, CountLoc;
Nirav Dave1a9044b2016-10-24 14:35:29 +00004861 if (parseOptionalToken(AsmToken::Comma)) {
Petr Hosek2f4ac442016-09-23 00:41:06 +00004862 // The skip expression can be omitted while specifying the count, e.g:
4863 // .incbin "filename",,4
4864 if (getTok().isNot(AsmToken::Comma)) {
4865 if (parseTokenLoc(SkipLoc) || parseAbsoluteExpression(Skip))
4866 return true;
4867 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00004868 if (parseOptionalToken(AsmToken::Comma)) {
4869 CountLoc = getTok().getLoc();
4870 if (parseExpression(Count))
Petr Hosek2f4ac442016-09-23 00:41:06 +00004871 return true;
4872 }
4873 }
4874
4875 if (parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00004876 "unexpected token in '.incbin' directive"))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004877 return true;
Nirav Dave1ab71992016-07-18 19:35:21 +00004878
Petr Hosek2f4ac442016-09-23 00:41:06 +00004879 if (check(Skip < 0, SkipLoc, "skip is negative"))
4880 return true;
4881
Nirav Dave1ab71992016-07-18 19:35:21 +00004882 // Attempt to process the included file.
Petr Hosek2f4ac442016-09-23 00:41:06 +00004883 if (processIncbinFile(Filename, Skip, Count, CountLoc))
Nirav Dave1ab71992016-07-18 19:35:21 +00004884 return Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
Kevin Enderby109f25c2011-12-14 21:47:48 +00004885 return false;
4886}
4887
Jim Grosbach4b905842013-09-20 23:08:21 +00004888/// parseDirectiveIf
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004889/// ::= .if{,eq,ge,gt,le,lt,ne} expression
4890bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004891 TheCondStack.push_back(TheCondState);
4892 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004893 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004894 eatToEndOfStatement();
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004895 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004896 int64_t ExprValue;
Nirav Davea645433c2016-07-18 15:24:03 +00004897 if (parseAbsoluteExpression(ExprValue) ||
4898 parseToken(AsmToken::EndOfStatement,
4899 "unexpected token in '.if' directive"))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004900 return true;
4901
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004902 switch (DirKind) {
4903 default:
4904 llvm_unreachable("unsupported directive");
4905 case DK_IF:
4906 case DK_IFNE:
4907 break;
4908 case DK_IFEQ:
4909 ExprValue = ExprValue == 0;
4910 break;
4911 case DK_IFGE:
4912 ExprValue = ExprValue >= 0;
4913 break;
4914 case DK_IFGT:
4915 ExprValue = ExprValue > 0;
4916 break;
4917 case DK_IFLE:
4918 ExprValue = ExprValue <= 0;
4919 break;
4920 case DK_IFLT:
4921 ExprValue = ExprValue < 0;
4922 break;
4923 }
4924
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004925 TheCondState.CondMet = ExprValue;
4926 TheCondState.Ignore = !TheCondState.CondMet;
4927 }
4928
4929 return false;
4930}
4931
Jim Grosbach4b905842013-09-20 23:08:21 +00004932/// parseDirectiveIfb
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004933/// ::= .ifb string
Jim Grosbach4b905842013-09-20 23:08:21 +00004934bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004935 TheCondStack.push_back(TheCondState);
4936 TheCondState.TheCond = AsmCond::IfCond;
4937
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004938 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004939 eatToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004940 } else {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004941 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004942
Nirav Davea645433c2016-07-18 15:24:03 +00004943 if (parseToken(AsmToken::EndOfStatement,
4944 "unexpected token in '.ifb' directive"))
4945 return true;
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004946
4947 TheCondState.CondMet = ExpectBlank == Str.empty();
4948 TheCondState.Ignore = !TheCondState.CondMet;
4949 }
4950
4951 return false;
4952}
4953
Jim Grosbach4b905842013-09-20 23:08:21 +00004954/// parseDirectiveIfc
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004955/// ::= .ifc string1, string2
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00004956/// ::= .ifnc string1, string2
Jim Grosbach4b905842013-09-20 23:08:21 +00004957bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004958 TheCondStack.push_back(TheCondState);
4959 TheCondState.TheCond = AsmCond::IfCond;
4960
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004961 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004962 eatToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004963 } else {
Jim Grosbach4b905842013-09-20 23:08:21 +00004964 StringRef Str1 = parseStringToComma();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004965
Nirav Davea645433c2016-07-18 15:24:03 +00004966 if (parseToken(AsmToken::Comma, "unexpected token in '.ifc' directive"))
4967 return true;
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004968
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004969 StringRef Str2 = parseStringToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004970
Nirav Davea645433c2016-07-18 15:24:03 +00004971 if (parseToken(AsmToken::EndOfStatement,
4972 "unexpected token in '.ifc' directive"))
4973 return true;
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004974
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00004975 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004976 TheCondState.Ignore = !TheCondState.CondMet;
4977 }
4978
4979 return false;
4980}
4981
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004982/// parseDirectiveIfeqs
4983/// ::= .ifeqs string1, string2
Sid Manning51c35602015-03-18 14:20:54 +00004984bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual) {
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004985 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00004986 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00004987 return TokError("expected string parameter for '.ifeqs' directive");
4988 return TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004989 }
4990
4991 StringRef String1 = getTok().getStringContents();
4992 Lex();
4993
4994 if (Lexer.isNot(AsmToken::Comma)) {
Sid Manning51c35602015-03-18 14:20:54 +00004995 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00004996 return TokError(
4997 "expected comma after first string for '.ifeqs' directive");
4998 return TokError("expected comma after first string for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004999 }
5000
5001 Lex();
5002
5003 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00005004 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00005005 return TokError("expected string parameter for '.ifeqs' directive");
5006 return TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00005007 }
5008
5009 StringRef String2 = getTok().getStringContents();
5010 Lex();
5011
5012 TheCondStack.push_back(TheCondState);
5013 TheCondState.TheCond = AsmCond::IfCond;
Sid Manning51c35602015-03-18 14:20:54 +00005014 TheCondState.CondMet = ExpectEqual == (String1 == String2);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00005015 TheCondState.Ignore = !TheCondState.CondMet;
5016
5017 return false;
5018}
5019
Jim Grosbach4b905842013-09-20 23:08:21 +00005020/// parseDirectiveIfdef
Benjamin Kramere297b9f2012-05-12 11:18:51 +00005021/// ::= .ifdef symbol
Jim Grosbach4b905842013-09-20 23:08:21 +00005022bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00005023 StringRef Name;
5024 TheCondStack.push_back(TheCondState);
5025 TheCondState.TheCond = AsmCond::IfCond;
5026
5027 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005028 eatToEndOfStatement();
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00005029 } else {
Nirav Davea645433c2016-07-18 15:24:03 +00005030 if (check(parseIdentifier(Name), "expected identifier after '.ifdef'") ||
5031 parseToken(AsmToken::EndOfStatement, "unexpected token in '.ifdef'"))
5032 return true;
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00005033
Jim Grosbach6f482002015-05-18 18:43:14 +00005034 MCSymbol *Sym = getContext().lookupSymbol(Name);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00005035
5036 if (expect_defined)
Craig Topper353eda42014-04-24 06:44:33 +00005037 TheCondState.CondMet = (Sym && !Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00005038 else
Craig Topper353eda42014-04-24 06:44:33 +00005039 TheCondState.CondMet = (!Sym || Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00005040 TheCondState.Ignore = !TheCondState.CondMet;
5041 }
5042
5043 return false;
5044}
5045
Jim Grosbach4b905842013-09-20 23:08:21 +00005046/// parseDirectiveElseIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005047/// ::= .elseif expression
Jim Grosbach4b905842013-09-20 23:08:21 +00005048bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005049 if (TheCondState.TheCond != AsmCond::IfCond &&
5050 TheCondState.TheCond != AsmCond::ElseIfCond)
Nirav Dave2364748a2016-09-16 18:30:20 +00005051 return Error(DirectiveLoc, "Encountered a .elseif that doesn't follow an"
5052 " .if or an .elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005053 TheCondState.TheCond = AsmCond::ElseIfCond;
5054
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005055 bool LastIgnoreState = false;
5056 if (!TheCondStack.empty())
Craig Topper2172ad62013-04-22 04:24:02 +00005057 LastIgnoreState = TheCondStack.back().Ignore;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005058 if (LastIgnoreState || TheCondState.CondMet) {
5059 TheCondState.Ignore = true;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005060 eatToEndOfStatement();
Craig Topperf15655b2013-04-22 04:22:40 +00005061 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005062 int64_t ExprValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005063 if (parseAbsoluteExpression(ExprValue))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005064 return true;
5065
Nirav Dave1a9044b2016-10-24 14:35:29 +00005066 if (parseToken(AsmToken::EndOfStatement,
5067 "unexpected token in '.elseif' directive"))
5068 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00005069
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005070 TheCondState.CondMet = ExprValue;
5071 TheCondState.Ignore = !TheCondState.CondMet;
5072 }
5073
5074 return false;
5075}
5076
Jim Grosbach4b905842013-09-20 23:08:21 +00005077/// parseDirectiveElse
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005078/// ::= .else
Jim Grosbach4b905842013-09-20 23:08:21 +00005079bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00005080 if (parseToken(AsmToken::EndOfStatement,
5081 "unexpected token in '.else' directive"))
5082 return true;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005083
5084 if (TheCondState.TheCond != AsmCond::IfCond &&
5085 TheCondState.TheCond != AsmCond::ElseIfCond)
Nirav Dave2364748a2016-09-16 18:30:20 +00005086 return Error(DirectiveLoc, "Encountered a .else that doesn't follow "
5087 " an .if or an .elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005088 TheCondState.TheCond = AsmCond::ElseCond;
5089 bool LastIgnoreState = false;
5090 if (!TheCondStack.empty())
5091 LastIgnoreState = TheCondStack.back().Ignore;
5092 if (LastIgnoreState || TheCondState.CondMet)
5093 TheCondState.Ignore = true;
5094 else
5095 TheCondState.Ignore = false;
5096
5097 return false;
5098}
5099
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00005100/// parseDirectiveEnd
5101/// ::= .end
5102bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00005103 if (parseToken(AsmToken::EndOfStatement,
5104 "unexpected token in '.end' directive"))
5105 return true;
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00005106
5107 while (Lexer.isNot(AsmToken::Eof))
Nirav Dave1a9044b2016-10-24 14:35:29 +00005108 Lexer.Lex();
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00005109
5110 return false;
5111}
5112
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00005113/// parseDirectiveError
5114/// ::= .err
5115/// ::= .error [string]
5116bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
5117 if (!TheCondStack.empty()) {
5118 if (TheCondStack.back().Ignore) {
5119 eatToEndOfStatement();
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00005120 return false;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00005121 }
5122 }
5123
5124 if (!WithMessage)
5125 return Error(L, ".err encountered");
5126
5127 StringRef Message = ".error directive invoked in source file";
5128 if (Lexer.isNot(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00005129 if (Lexer.isNot(AsmToken::String))
5130 return TokError(".error argument must be a string");
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00005131
5132 Message = getTok().getStringContents();
5133 Lex();
5134 }
5135
Nirav Dave2364748a2016-09-16 18:30:20 +00005136 return Error(L, Message);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00005137}
5138
Nico Weber404012b2014-07-24 16:26:06 +00005139/// parseDirectiveWarning
5140/// ::= .warning [string]
5141bool AsmParser::parseDirectiveWarning(SMLoc L) {
5142 if (!TheCondStack.empty()) {
5143 if (TheCondStack.back().Ignore) {
5144 eatToEndOfStatement();
5145 return false;
5146 }
5147 }
5148
5149 StringRef Message = ".warning directive invoked in source file";
Nirav Dave1a9044b2016-10-24 14:35:29 +00005150
5151 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00005152 if (Lexer.isNot(AsmToken::String))
5153 return TokError(".warning argument must be a string");
Nico Weber404012b2014-07-24 16:26:06 +00005154
5155 Message = getTok().getStringContents();
5156 Lex();
Nirav Dave1a9044b2016-10-24 14:35:29 +00005157 if (parseToken(AsmToken::EndOfStatement,
5158 "expected end of statement in '.warning' directive"))
5159 return true;
Nico Weber404012b2014-07-24 16:26:06 +00005160 }
5161
Nirav Dave2364748a2016-09-16 18:30:20 +00005162 return Warning(L, Message);
Nico Weber404012b2014-07-24 16:26:06 +00005163}
5164
Jim Grosbach4b905842013-09-20 23:08:21 +00005165/// parseDirectiveEndIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005166/// ::= .endif
Jim Grosbach4b905842013-09-20 23:08:21 +00005167bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00005168 if (parseToken(AsmToken::EndOfStatement,
5169 "unexpected token in '.endif' directive"))
5170 return true;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005171
Jim Grosbach4b905842013-09-20 23:08:21 +00005172 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
Nirav Dave2364748a2016-09-16 18:30:20 +00005173 return Error(DirectiveLoc, "Encountered a .endif that doesn't follow "
5174 "an .if or .else");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005175 if (!TheCondStack.empty()) {
5176 TheCondState = TheCondStack.back();
5177 TheCondStack.pop_back();
5178 }
5179
5180 return false;
5181}
Daniel Dunbara4b069c2009-08-11 04:24:50 +00005182
Eli Bendersky17233942013-01-15 22:59:42 +00005183void AsmParser::initializeDirectiveKindMap() {
5184 DirectiveKindMap[".set"] = DK_SET;
5185 DirectiveKindMap[".equ"] = DK_EQU;
5186 DirectiveKindMap[".equiv"] = DK_EQUIV;
5187 DirectiveKindMap[".ascii"] = DK_ASCII;
5188 DirectiveKindMap[".asciz"] = DK_ASCIZ;
5189 DirectiveKindMap[".string"] = DK_STRING;
5190 DirectiveKindMap[".byte"] = DK_BYTE;
5191 DirectiveKindMap[".short"] = DK_SHORT;
5192 DirectiveKindMap[".value"] = DK_VALUE;
5193 DirectiveKindMap[".2byte"] = DK_2BYTE;
5194 DirectiveKindMap[".long"] = DK_LONG;
5195 DirectiveKindMap[".int"] = DK_INT;
5196 DirectiveKindMap[".4byte"] = DK_4BYTE;
5197 DirectiveKindMap[".quad"] = DK_QUAD;
5198 DirectiveKindMap[".8byte"] = DK_8BYTE;
David Woodhoused6de0d92014-02-01 16:20:59 +00005199 DirectiveKindMap[".octa"] = DK_OCTA;
Eli Bendersky17233942013-01-15 22:59:42 +00005200 DirectiveKindMap[".single"] = DK_SINGLE;
5201 DirectiveKindMap[".float"] = DK_FLOAT;
5202 DirectiveKindMap[".double"] = DK_DOUBLE;
5203 DirectiveKindMap[".align"] = DK_ALIGN;
5204 DirectiveKindMap[".align32"] = DK_ALIGN32;
5205 DirectiveKindMap[".balign"] = DK_BALIGN;
5206 DirectiveKindMap[".balignw"] = DK_BALIGNW;
5207 DirectiveKindMap[".balignl"] = DK_BALIGNL;
5208 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
5209 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
5210 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
5211 DirectiveKindMap[".org"] = DK_ORG;
5212 DirectiveKindMap[".fill"] = DK_FILL;
5213 DirectiveKindMap[".zero"] = DK_ZERO;
5214 DirectiveKindMap[".extern"] = DK_EXTERN;
5215 DirectiveKindMap[".globl"] = DK_GLOBL;
5216 DirectiveKindMap[".global"] = DK_GLOBAL;
Eli Bendersky17233942013-01-15 22:59:42 +00005217 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
5218 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
5219 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
5220 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
5221 DirectiveKindMap[".reference"] = DK_REFERENCE;
5222 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
5223 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
5224 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
5225 DirectiveKindMap[".comm"] = DK_COMM;
5226 DirectiveKindMap[".common"] = DK_COMMON;
5227 DirectiveKindMap[".lcomm"] = DK_LCOMM;
5228 DirectiveKindMap[".abort"] = DK_ABORT;
5229 DirectiveKindMap[".include"] = DK_INCLUDE;
5230 DirectiveKindMap[".incbin"] = DK_INCBIN;
5231 DirectiveKindMap[".code16"] = DK_CODE16;
5232 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
5233 DirectiveKindMap[".rept"] = DK_REPT;
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00005234 DirectiveKindMap[".rep"] = DK_REPT;
Eli Bendersky17233942013-01-15 22:59:42 +00005235 DirectiveKindMap[".irp"] = DK_IRP;
5236 DirectiveKindMap[".irpc"] = DK_IRPC;
5237 DirectiveKindMap[".endr"] = DK_ENDR;
5238 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
5239 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
5240 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
5241 DirectiveKindMap[".if"] = DK_IF;
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00005242 DirectiveKindMap[".ifeq"] = DK_IFEQ;
5243 DirectiveKindMap[".ifge"] = DK_IFGE;
5244 DirectiveKindMap[".ifgt"] = DK_IFGT;
5245 DirectiveKindMap[".ifle"] = DK_IFLE;
5246 DirectiveKindMap[".iflt"] = DK_IFLT;
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00005247 DirectiveKindMap[".ifne"] = DK_IFNE;
Eli Bendersky17233942013-01-15 22:59:42 +00005248 DirectiveKindMap[".ifb"] = DK_IFB;
5249 DirectiveKindMap[".ifnb"] = DK_IFNB;
5250 DirectiveKindMap[".ifc"] = DK_IFC;
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00005251 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
Eli Bendersky17233942013-01-15 22:59:42 +00005252 DirectiveKindMap[".ifnc"] = DK_IFNC;
Sid Manning51c35602015-03-18 14:20:54 +00005253 DirectiveKindMap[".ifnes"] = DK_IFNES;
Eli Bendersky17233942013-01-15 22:59:42 +00005254 DirectiveKindMap[".ifdef"] = DK_IFDEF;
5255 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
5256 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
5257 DirectiveKindMap[".elseif"] = DK_ELSEIF;
5258 DirectiveKindMap[".else"] = DK_ELSE;
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00005259 DirectiveKindMap[".end"] = DK_END;
Eli Bendersky17233942013-01-15 22:59:42 +00005260 DirectiveKindMap[".endif"] = DK_ENDIF;
5261 DirectiveKindMap[".skip"] = DK_SKIP;
5262 DirectiveKindMap[".space"] = DK_SPACE;
5263 DirectiveKindMap[".file"] = DK_FILE;
5264 DirectiveKindMap[".line"] = DK_LINE;
5265 DirectiveKindMap[".loc"] = DK_LOC;
5266 DirectiveKindMap[".stabs"] = DK_STABS;
Reid Kleckner2214ed82016-01-29 00:49:42 +00005267 DirectiveKindMap[".cv_file"] = DK_CV_FILE;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00005268 DirectiveKindMap[".cv_func_id"] = DK_CV_FUNC_ID;
Reid Kleckner2214ed82016-01-29 00:49:42 +00005269 DirectiveKindMap[".cv_loc"] = DK_CV_LOC;
5270 DirectiveKindMap[".cv_linetable"] = DK_CV_LINETABLE;
David Majnemer6fcbd7e2016-01-29 19:24:12 +00005271 DirectiveKindMap[".cv_inline_linetable"] = DK_CV_INLINE_LINETABLE;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00005272 DirectiveKindMap[".cv_inline_site_id"] = DK_CV_INLINE_SITE_ID;
David Majnemer408b5e62016-02-05 01:55:49 +00005273 DirectiveKindMap[".cv_def_range"] = DK_CV_DEF_RANGE;
Reid Kleckner06d02d02018-09-07 21:30:52 +00005274 DirectiveKindMap[".cv_string"] = DK_CV_STRING;
Reid Kleckner2214ed82016-01-29 00:49:42 +00005275 DirectiveKindMap[".cv_stringtable"] = DK_CV_STRINGTABLE;
5276 DirectiveKindMap[".cv_filechecksums"] = DK_CV_FILECHECKSUMS;
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00005277 DirectiveKindMap[".cv_filechecksumoffset"] = DK_CV_FILECHECKSUM_OFFSET;
Reid Kleckner9cdd4df2017-10-11 21:24:33 +00005278 DirectiveKindMap[".cv_fpo_data"] = DK_CV_FPO_DATA;
Eli Bendersky17233942013-01-15 22:59:42 +00005279 DirectiveKindMap[".sleb128"] = DK_SLEB128;
5280 DirectiveKindMap[".uleb128"] = DK_ULEB128;
5281 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
5282 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
5283 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
5284 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
5285 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
5286 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
5287 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
5288 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
5289 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
5290 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
5291 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
5292 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
5293 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
5294 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
5295 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
5296 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +00005297 DirectiveKindMap[".cfi_return_column"] = DK_CFI_RETURN_COLUMN;
Eli Bendersky17233942013-01-15 22:59:42 +00005298 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
5299 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
5300 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00005301 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
Luke Cheeseman41a9e532018-12-21 10:45:08 +00005302 DirectiveKindMap[".cfi_b_key_frame"] = DK_CFI_B_KEY_FRAME;
Eli Bendersky17233942013-01-15 22:59:42 +00005303 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
5304 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
5305 DirectiveKindMap[".macro"] = DK_MACRO;
Nico Weber155dccd12014-07-24 17:08:39 +00005306 DirectiveKindMap[".exitm"] = DK_EXITM;
Eli Bendersky17233942013-01-15 22:59:42 +00005307 DirectiveKindMap[".endm"] = DK_ENDM;
5308 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
5309 DirectiveKindMap[".purgem"] = DK_PURGEM;
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00005310 DirectiveKindMap[".err"] = DK_ERR;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00005311 DirectiveKindMap[".error"] = DK_ERROR;
Nico Weber404012b2014-07-24 16:26:06 +00005312 DirectiveKindMap[".warning"] = DK_WARNING;
Michael Zuckerman56704612017-05-01 13:20:12 +00005313 DirectiveKindMap[".altmacro"] = DK_ALTMACRO;
5314 DirectiveKindMap[".noaltmacro"] = DK_NOALTMACRO;
Daniel Sanders9f6ad492015-11-12 13:33:00 +00005315 DirectiveKindMap[".reloc"] = DK_RELOC;
Petr Hosek731bb9c2016-08-23 21:34:53 +00005316 DirectiveKindMap[".dc"] = DK_DC;
5317 DirectiveKindMap[".dc.a"] = DK_DC_A;
5318 DirectiveKindMap[".dc.b"] = DK_DC_B;
5319 DirectiveKindMap[".dc.d"] = DK_DC_D;
5320 DirectiveKindMap[".dc.l"] = DK_DC_L;
5321 DirectiveKindMap[".dc.s"] = DK_DC_S;
5322 DirectiveKindMap[".dc.w"] = DK_DC_W;
5323 DirectiveKindMap[".dc.x"] = DK_DC_X;
Petr Hosek4cb08ce2016-09-23 19:25:15 +00005324 DirectiveKindMap[".dcb"] = DK_DCB;
5325 DirectiveKindMap[".dcb.b"] = DK_DCB_B;
5326 DirectiveKindMap[".dcb.d"] = DK_DCB_D;
5327 DirectiveKindMap[".dcb.l"] = DK_DCB_L;
5328 DirectiveKindMap[".dcb.s"] = DK_DCB_S;
5329 DirectiveKindMap[".dcb.w"] = DK_DCB_W;
5330 DirectiveKindMap[".dcb.x"] = DK_DCB_X;
Petr Hosek85b2f672016-09-23 21:53:36 +00005331 DirectiveKindMap[".ds"] = DK_DS;
5332 DirectiveKindMap[".ds.b"] = DK_DS_B;
5333 DirectiveKindMap[".ds.d"] = DK_DS_D;
5334 DirectiveKindMap[".ds.l"] = DK_DS_L;
5335 DirectiveKindMap[".ds.p"] = DK_DS_P;
5336 DirectiveKindMap[".ds.s"] = DK_DS_S;
5337 DirectiveKindMap[".ds.w"] = DK_DS_W;
5338 DirectiveKindMap[".ds.x"] = DK_DS_X;
Coby Tayree01e53202017-10-02 14:36:31 +00005339 DirectiveKindMap[".print"] = DK_PRINT;
Peter Collingbourne3e227332018-07-17 22:17:18 +00005340 DirectiveKindMap[".addrsig"] = DK_ADDRSIG;
5341 DirectiveKindMap[".addrsig_sym"] = DK_ADDRSIG_SYM;
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00005342}
5343
Jim Grosbach4b905842013-09-20 23:08:21 +00005344MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005345 AsmToken EndToken, StartToken = getTok();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005346
Rafael Espindola34b9c512012-06-03 23:57:14 +00005347 unsigned NestLevel = 0;
Eugene Zelenko33d7b762016-08-23 17:14:32 +00005348 while (true) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005349 // Check whether we have reached the end of the file.
Rafael Espindola34b9c512012-06-03 23:57:14 +00005350 if (getLexer().is(AsmToken::Eof)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00005351 printError(DirectiveLoc, "no matching '.endr' in definition");
Craig Topper353eda42014-04-24 06:44:33 +00005352 return nullptr;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005353 }
5354
Rafael Espindola34b9c512012-06-03 23:57:14 +00005355 if (Lexer.is(AsmToken::Identifier) &&
Nirav Davee24fcd52018-07-18 16:17:03 +00005356 (getTok().getIdentifier() == ".rep" ||
5357 getTok().getIdentifier() == ".rept" ||
Nikolay Haustov95b4fcd2016-03-01 08:18:28 +00005358 getTok().getIdentifier() == ".irp" ||
5359 getTok().getIdentifier() == ".irpc")) {
Rafael Espindola34b9c512012-06-03 23:57:14 +00005360 ++NestLevel;
5361 }
5362
5363 // Otherwise, check whether we have reached the .endr.
Jim Grosbach4b905842013-09-20 23:08:21 +00005364 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
Rafael Espindola34b9c512012-06-03 23:57:14 +00005365 if (NestLevel == 0) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005366 EndToken = getTok();
5367 Lex();
Rafael Espindola34b9c512012-06-03 23:57:14 +00005368 if (Lexer.isNot(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00005369 printError(getTok().getLoc(),
5370 "unexpected token in '.endr' directive");
Craig Topper353eda42014-04-24 06:44:33 +00005371 return nullptr;
Rafael Espindola34b9c512012-06-03 23:57:14 +00005372 }
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005373 break;
5374 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00005375 --NestLevel;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005376 }
5377
Rafael Espindola34b9c512012-06-03 23:57:14 +00005378 // Otherwise, scan till the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005379 eatToEndOfStatement();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005380 }
5381
5382 const char *BodyStart = StartToken.getLoc().getPointer();
5383 const char *BodyEnd = EndToken.getLoc().getPointer();
5384 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
5385
Rafael Espindola34b9c512012-06-03 23:57:14 +00005386 // We Are Anonymous.
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00005387 MacroLikeBodies.emplace_back(StringRef(), Body, MCAsmMacroParameters());
Benjamin Kramer1df3a1f2013-08-04 09:06:29 +00005388 return &MacroLikeBodies.back();
Rafael Espindola34b9c512012-06-03 23:57:14 +00005389}
5390
Jim Grosbach4b905842013-09-20 23:08:21 +00005391void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +00005392 raw_svector_ostream &OS) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005393 OS << ".endr\n";
5394
Rafael Espindola3560ff22014-08-27 20:03:13 +00005395 std::unique_ptr<MemoryBuffer> Instantiation =
5396 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005397
Rafael Espindola34b9c512012-06-03 23:57:14 +00005398 // Create the macro instantiation object and add to the current macro
5399 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00005400 MacroInstantiation *MI = new MacroInstantiation(
5401 DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Rafael Espindola34b9c512012-06-03 23:57:14 +00005402 ActiveMacros.push_back(MI);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005403
Rafael Espindola34b9c512012-06-03 23:57:14 +00005404 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00005405 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00005406 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Rafael Espindola34b9c512012-06-03 23:57:14 +00005407 Lex();
5408}
5409
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00005410/// parseDirectiveRept
5411/// ::= .rep | .rept count
5412bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00005413 const MCExpr *CountExpr;
5414 SMLoc CountLoc = getTok().getLoc();
5415 if (parseExpression(CountExpr))
5416 return true;
5417
Rafael Espindola34b9c512012-06-03 23:57:14 +00005418 int64_t Count;
Nirav Dave6c0665e2018-04-30 19:22:40 +00005419 if (!CountExpr->evaluateAsAbsolute(Count, getStreamer().getAssemblerPtr())) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00005420 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
5421 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00005422
Nirav Davea645433c2016-07-18 15:24:03 +00005423 if (check(Count < 0, CountLoc, "Count is negative") ||
5424 parseToken(AsmToken::EndOfStatement,
5425 "unexpected token in '" + Dir + "' directive"))
5426 return true;
Rafael Espindola34b9c512012-06-03 23:57:14 +00005427
5428 // Lex the rept definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005429 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola34b9c512012-06-03 23:57:14 +00005430 if (!M)
5431 return true;
5432
5433 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5434 // to hold the macro body with substitutions.
5435 SmallString<256> Buf;
Rafael Espindola34b9c512012-06-03 23:57:14 +00005436 raw_svector_ostream OS(Buf);
5437 while (Count--) {
Toma Tabacu217116e2015-04-27 10:50:29 +00005438 // Note that the AtPseudoVariable is disabled for instantiations of .rep(t).
5439 if (expandMacro(OS, M->Body, None, None, false, getTok().getLoc()))
Rafael Espindola34b9c512012-06-03 23:57:14 +00005440 return true;
5441 }
Jim Grosbach4b905842013-09-20 23:08:21 +00005442 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005443
5444 return false;
5445}
5446
Jim Grosbach4b905842013-09-20 23:08:21 +00005447/// parseDirectiveIrp
Rafael Espindola768b41c2012-06-15 14:02:34 +00005448/// ::= .irp symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00005449bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00005450 MCAsmMacroParameter Parameter;
Eli Bendersky38274122013-01-14 23:22:36 +00005451 MCAsmMacroArguments A;
Nirav Davea645433c2016-07-18 15:24:03 +00005452 if (check(parseIdentifier(Parameter.Name),
5453 "expected identifier in '.irp' directive") ||
5454 parseToken(AsmToken::Comma, "expected comma in '.irp' directive") ||
5455 parseMacroArguments(nullptr, A) ||
5456 parseToken(AsmToken::EndOfStatement, "expected End of Statement"))
Rafael Espindola768b41c2012-06-15 14:02:34 +00005457 return true;
5458
Rafael Espindola768b41c2012-06-15 14:02:34 +00005459 // Lex the irp definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005460 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola768b41c2012-06-15 14:02:34 +00005461 if (!M)
5462 return true;
5463
5464 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5465 // to hold the macro body with substitutions.
5466 SmallString<256> Buf;
5467 raw_svector_ostream OS(Buf);
5468
Craig Topper84008482015-10-10 05:38:14 +00005469 for (const MCAsmMacroArgument &Arg : A) {
Toma Tabacu217116e2015-04-27 10:50:29 +00005470 // Note that the AtPseudoVariable is enabled for instantiations of .irp.
5471 // This is undocumented, but GAS seems to support it.
Craig Topper84008482015-10-10 05:38:14 +00005472 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindola768b41c2012-06-15 14:02:34 +00005473 return true;
5474 }
5475
Jim Grosbach4b905842013-09-20 23:08:21 +00005476 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola768b41c2012-06-15 14:02:34 +00005477
5478 return false;
5479}
5480
Jim Grosbach4b905842013-09-20 23:08:21 +00005481/// parseDirectiveIrpc
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005482/// ::= .irpc symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00005483bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00005484 MCAsmMacroParameter Parameter;
Eli Bendersky38274122013-01-14 23:22:36 +00005485 MCAsmMacroArguments A;
Nirav Davea645433c2016-07-18 15:24:03 +00005486
5487 if (check(parseIdentifier(Parameter.Name),
5488 "expected identifier in '.irpc' directive") ||
5489 parseToken(AsmToken::Comma, "expected comma in '.irpc' directive") ||
5490 parseMacroArguments(nullptr, A))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005491 return true;
5492
5493 if (A.size() != 1 || A.front().size() != 1)
5494 return TokError("unexpected token in '.irpc' directive");
5495
5496 // Eat the end of statement.
Nirav Davea645433c2016-07-18 15:24:03 +00005497 if (parseToken(AsmToken::EndOfStatement, "expected end of statement"))
5498 return true;
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005499
5500 // Lex the irpc definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005501 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005502 if (!M)
5503 return true;
5504
5505 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5506 // to hold the macro body with substitutions.
5507 SmallString<256> Buf;
5508 raw_svector_ostream OS(Buf);
5509
5510 StringRef Values = A.front().front().getString();
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00005511 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
Eli Benderskya7b905e2013-01-14 19:00:26 +00005512 MCAsmMacroArgument Arg;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00005513 Arg.emplace_back(AsmToken::Identifier, Values.slice(I, I + 1));
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005514
Toma Tabacu217116e2015-04-27 10:50:29 +00005515 // Note that the AtPseudoVariable is enabled for instantiations of .irpc.
5516 // This is undocumented, but GAS seems to support it.
5517 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005518 return true;
5519 }
5520
Jim Grosbach4b905842013-09-20 23:08:21 +00005521 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005522
5523 return false;
5524}
5525
Jim Grosbach4b905842013-09-20 23:08:21 +00005526bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
Rafael Espindola34b9c512012-06-03 23:57:14 +00005527 if (ActiveMacros.empty())
Preston Gurdeb3ebf12012-09-19 20:23:43 +00005528 return TokError("unmatched '.endr' directive");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005529
5530 // The only .repl that should get here are the ones created by
Jim Grosbach4b905842013-09-20 23:08:21 +00005531 // instantiateMacroLikeBody.
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005532 assert(getLexer().is(AsmToken::EndOfStatement));
5533
Jim Grosbach4b905842013-09-20 23:08:21 +00005534 handleMacroExit();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005535 return false;
5536}
Rafael Espindola12d73d12010-09-11 16:45:15 +00005537
Jim Grosbach4b905842013-09-20 23:08:21 +00005538bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
Benjamin Kramer1a136112013-02-15 20:37:21 +00005539 size_t Len) {
Eli Friedman0f4871d2012-10-22 23:58:19 +00005540 const MCExpr *Value;
5541 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005542 if (parseExpression(Value))
Eli Friedman0f4871d2012-10-22 23:58:19 +00005543 return true;
5544 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5545 if (!MCE)
5546 return Error(ExprLoc, "unexpected expression in _emit");
5547 uint64_t IntValue = MCE->getValue();
Craig Topper55b1f292015-10-10 20:17:07 +00005548 if (!isUInt<8>(IntValue) && !isInt<8>(IntValue))
Eli Friedman0f4871d2012-10-22 23:58:19 +00005549 return Error(ExprLoc, "literal value out of range for directive");
5550
Craig Topper7d5b2312015-10-10 05:25:02 +00005551 Info.AsmRewrites->emplace_back(AOK_Emit, IDLoc, Len);
Chad Rosierc7f552c2013-02-12 21:33:51 +00005552 return false;
5553}
5554
Jim Grosbach4b905842013-09-20 23:08:21 +00005555bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
Chad Rosierc7f552c2013-02-12 21:33:51 +00005556 const MCExpr *Value;
5557 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005558 if (parseExpression(Value))
Chad Rosierc7f552c2013-02-12 21:33:51 +00005559 return true;
5560 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5561 if (!MCE)
5562 return Error(ExprLoc, "unexpected expression in align");
5563 uint64_t IntValue = MCE->getValue();
5564 if (!isPowerOf2_64(IntValue))
5565 return Error(ExprLoc, "literal value not a power of two greater then zero");
5566
Craig Topper7d5b2312015-10-10 05:25:02 +00005567 Info.AsmRewrites->emplace_back(AOK_Align, IDLoc, 5, Log2_64(IntValue));
Eli Friedman0f4871d2012-10-22 23:58:19 +00005568 return false;
5569}
5570
Coby Tayree01e53202017-10-02 14:36:31 +00005571bool AsmParser::parseDirectivePrint(SMLoc DirectiveLoc) {
5572 const AsmToken StrTok = getTok();
5573 Lex();
5574 if (StrTok.isNot(AsmToken::String) || StrTok.getString().front() != '"')
5575 return Error(DirectiveLoc, "expected double quoted string after .print");
5576 if (parseToken(AsmToken::EndOfStatement, "expected end of statement"))
5577 return true;
5578 llvm::outs() << StrTok.getStringContents() << '\n';
5579 return false;
5580}
5581
Peter Collingbourne3e227332018-07-17 22:17:18 +00005582bool AsmParser::parseDirectiveAddrsig() {
5583 getStreamer().EmitAddrsig();
5584 return false;
5585}
5586
5587bool AsmParser::parseDirectiveAddrsigSym() {
5588 StringRef Name;
5589 if (check(parseIdentifier(Name),
5590 "expected identifier in '.addrsig_sym' directive"))
5591 return true;
5592 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
5593 getStreamer().EmitAddrsigSym(Sym);
5594 return false;
5595}
5596
Chad Rosierf43fcf52013-02-13 21:27:17 +00005597// We are comparing pointers, but the pointers are relative to a single string.
5598// Thus, this should always be deterministic.
Benjamin Kramer8817cca2013-09-22 14:09:50 +00005599static int rewritesSort(const AsmRewrite *AsmRewriteA,
5600 const AsmRewrite *AsmRewriteB) {
Chad Rosiereb5c1682013-02-13 18:38:58 +00005601 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
5602 return -1;
5603 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
5604 return 1;
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005605
Chad Rosierfce4fab2013-04-08 17:43:47 +00005606 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
5607 // rewrite to the same location. Make sure the SizeDirective rewrite is
5608 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
5609 // ensures the sort algorithm is stable.
Jim Grosbach4b905842013-09-20 23:08:21 +00005610 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
5611 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005612 return -1;
Chad Rosierfce4fab2013-04-08 17:43:47 +00005613
Jim Grosbach4b905842013-09-20 23:08:21 +00005614 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
5615 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005616 return 1;
Jim Grosbach4b905842013-09-20 23:08:21 +00005617 llvm_unreachable("Unstable rewrite sort.");
Chad Rosierb2144ce2013-02-13 01:03:13 +00005618}
5619
Jim Grosbach4b905842013-09-20 23:08:21 +00005620bool AsmParser::parseMSInlineAsm(
5621 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00005622 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool>> &OpDecls,
Jim Grosbach4b905842013-09-20 23:08:21 +00005623 SmallVectorImpl<std::string> &Constraints,
5624 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
5625 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
Chad Rosier37e755c2012-10-23 17:43:43 +00005626 SmallVector<void *, 4> InputDecls;
5627 SmallVector<void *, 4> OutputDecls;
Chad Rosiera4bc9432013-01-10 22:10:27 +00005628 SmallVector<bool, 4> InputDeclsAddressOf;
5629 SmallVector<bool, 4> OutputDeclsAddressOf;
Chad Rosier8bce6642012-10-18 15:49:34 +00005630 SmallVector<std::string, 4> InputConstraints;
5631 SmallVector<std::string, 4> OutputConstraints;
Benjamin Kramer1a136112013-02-15 20:37:21 +00005632 SmallVector<unsigned, 4> ClobberRegs;
Chad Rosier8bce6642012-10-18 15:49:34 +00005633
Benjamin Kramer1a136112013-02-15 20:37:21 +00005634 SmallVector<AsmRewrite, 4> AsmStrRewrites;
Chad Rosier8bce6642012-10-18 15:49:34 +00005635
5636 // Prime the lexer.
5637 Lex();
5638
5639 // While we have input, parse each statement.
5640 unsigned InputIdx = 0;
5641 unsigned OutputIdx = 0;
5642 while (getLexer().isNot(AsmToken::Eof)) {
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00005643 // Parse curly braces marking block start/end
5644 if (parseCurlyBlockScope(AsmStrRewrites))
5645 continue;
5646
Eli Friedman0f4871d2012-10-22 23:58:19 +00005647 ParseStatementInfo Info(&AsmStrRewrites);
Nirav Dave2364748a2016-09-16 18:30:20 +00005648 bool StatementErr = parseStatement(Info, &SI);
Nirav Dave9fa8af22016-09-13 13:55:06 +00005649
Nirav Dave2364748a2016-09-16 18:30:20 +00005650 if (StatementErr || Info.ParseError) {
5651 // Emit pending errors if any exist.
5652 printPendingErrors();
Nico Webere204c482016-09-13 18:17:00 +00005653 return true;
Nirav Dave2364748a2016-09-16 18:30:20 +00005654 }
5655
5656 // No pending error should exist here.
5657 assert(!hasPendingError() && "unexpected error from parseStatement");
Chad Rosier149e8e02012-12-12 22:45:52 +00005658
Benjamin Kramer1a136112013-02-15 20:37:21 +00005659 if (Info.Opcode == ~0U)
5660 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00005661
Benjamin Kramer1a136112013-02-15 20:37:21 +00005662 const MCInstrDesc &Desc = MII->get(Info.Opcode);
Chad Rosier8bce6642012-10-18 15:49:34 +00005663
Benjamin Kramer1a136112013-02-15 20:37:21 +00005664 // Build the list of clobbers, outputs and inputs.
5665 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
David Blaikie960ea3f2014-06-08 16:18:35 +00005666 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005667
Benjamin Kramer1a136112013-02-15 20:37:21 +00005668 // Immediate.
David Blaikie960ea3f2014-06-08 16:18:35 +00005669 if (Operand.isImm())
Benjamin Kramer1a136112013-02-15 20:37:21 +00005670 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00005671
Benjamin Kramer1a136112013-02-15 20:37:21 +00005672 // Register operand.
Nico Weber42f79db2014-07-17 20:24:55 +00005673 if (Operand.isReg() && !Operand.needAddressOf() &&
5674 !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
Benjamin Kramer1a136112013-02-15 20:37:21 +00005675 unsigned NumDefs = Desc.getNumDefs();
5676 // Clobber.
David Blaikie960ea3f2014-06-08 16:18:35 +00005677 if (NumDefs && Operand.getMCOperandNum() < NumDefs)
5678 ClobberRegs.push_back(Operand.getReg());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005679 continue;
5680 }
5681
5682 // Expr/Input or Output.
David Blaikie960ea3f2014-06-08 16:18:35 +00005683 StringRef SymName = Operand.getSymName();
Chad Rosiere81309b2013-04-09 17:53:49 +00005684 if (SymName.empty())
5685 continue;
5686
David Blaikie960ea3f2014-06-08 16:18:35 +00005687 void *OpDecl = Operand.getOpDecl();
Benjamin Kramer1a136112013-02-15 20:37:21 +00005688 if (!OpDecl)
5689 continue;
5690
5691 bool isOutput = (i == 1) && Desc.mayStore();
Chad Rosiere81309b2013-04-09 17:53:49 +00005692 SMLoc Start = SMLoc::getFromPointer(SymName.data());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005693 if (isOutput) {
5694 ++InputIdx;
5695 OutputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00005696 OutputDeclsAddressOf.push_back(Operand.needAddressOf());
Yaron Keren075759a2015-03-30 15:42:36 +00005697 OutputConstraints.push_back(("=" + Operand.getConstraint()).str());
Craig Topper7d5b2312015-10-10 05:25:02 +00005698 AsmStrRewrites.emplace_back(AOK_Output, Start, SymName.size());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005699 } else {
5700 InputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00005701 InputDeclsAddressOf.push_back(Operand.needAddressOf());
5702 InputConstraints.push_back(Operand.getConstraint().str());
Craig Topper7d5b2312015-10-10 05:25:02 +00005703 AsmStrRewrites.emplace_back(AOK_Input, Start, SymName.size());
Chad Rosier8bce6642012-10-18 15:49:34 +00005704 }
Chad Rosier8bce6642012-10-18 15:49:34 +00005705 }
Reid Kleckneree088972013-12-10 18:27:32 +00005706
5707 // Consider implicit defs to be clobbers. Think of cpuid and push.
Craig Toppere5e035a32015-12-05 07:13:35 +00005708 ArrayRef<MCPhysReg> ImpDefs(Desc.getImplicitDefs(),
5709 Desc.getNumImplicitDefs());
David Majnemer8114c1a2014-06-23 02:17:16 +00005710 ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end());
Chad Rosier8bce6642012-10-18 15:49:34 +00005711 }
5712
5713 // Set the number of Outputs and Inputs.
Chad Rosierf641baa2012-10-18 19:39:30 +00005714 NumOutputs = OutputDecls.size();
5715 NumInputs = InputDecls.size();
Chad Rosier8bce6642012-10-18 15:49:34 +00005716
5717 // Set the unique clobbers.
Benjamin Kramer1a136112013-02-15 20:37:21 +00005718 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
5719 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
5720 ClobberRegs.end());
5721 Clobbers.assign(ClobberRegs.size(), std::string());
5722 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
5723 raw_string_ostream OS(Clobbers[I]);
5724 IP->printRegName(OS, ClobberRegs[I]);
5725 }
Chad Rosier8bce6642012-10-18 15:49:34 +00005726
5727 // Merge the various outputs and inputs. Output are expected first.
5728 if (NumOutputs || NumInputs) {
5729 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierf641baa2012-10-18 19:39:30 +00005730 OpDecls.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00005731 Constraints.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00005732 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00005733 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00005734 Constraints[i] = OutputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005735 }
5736 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00005737 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00005738 Constraints[j] = InputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005739 }
5740 }
5741
5742 // Build the IR assembly string.
Alp Tokere69170a2014-06-26 22:52:05 +00005743 std::string AsmStringIR;
5744 raw_string_ostream OS(AsmStringIR);
Alp Tokera55b95b2014-07-06 10:33:31 +00005745 StringRef ASMString =
5746 SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
5747 const char *AsmStart = ASMString.begin();
5748 const char *AsmEnd = ASMString.end();
Jim Grosbach4b905842013-09-20 23:08:21 +00005749 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
David Majnemer8114c1a2014-06-23 02:17:16 +00005750 for (const AsmRewrite &AR : AsmStrRewrites) {
5751 AsmRewriteKind Kind = AR.Kind;
Chad Rosierff10ed12013-04-12 16:26:42 +00005752
David Majnemer8114c1a2014-06-23 02:17:16 +00005753 const char *Loc = AR.Loc.getPointer();
Chad Rosier17d37992013-03-19 21:12:14 +00005754 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
Chad Rosier0f48c552012-10-19 20:57:14 +00005755
Chad Rosier120eefd2013-03-19 17:32:17 +00005756 // Emit everything up to the immediate/expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00005757 if (unsigned Len = Loc - AsmStart)
Chad Rosier17d37992013-03-19 21:12:14 +00005758 OS << StringRef(AsmStart, Len);
Chad Rosier0f48c552012-10-19 20:57:14 +00005759
Chad Rosier37e755c2012-10-23 17:43:43 +00005760 // Skip the original expression.
5761 if (Kind == AOK_Skip) {
David Majnemer8114c1a2014-06-23 02:17:16 +00005762 AsmStart = Loc + AR.Len;
Chad Rosier37e755c2012-10-23 17:43:43 +00005763 continue;
5764 }
5765
Chad Rosierff10ed12013-04-12 16:26:42 +00005766 unsigned AdditionalSkip = 0;
Chad Rosier8bce6642012-10-18 15:49:34 +00005767 // Rewrite expressions in $N notation.
Chad Rosier0f48c552012-10-19 20:57:14 +00005768 switch (Kind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00005769 default:
5770 break;
Coby Tayreed8912892017-08-24 08:46:25 +00005771 case AOK_IntelExpr:
5772 assert(AR.IntelExp.isValid() && "cannot write invalid intel expression");
5773 if (AR.IntelExp.NeedBracs)
5774 OS << "[";
5775 if (AR.IntelExp.hasBaseReg())
5776 OS << AR.IntelExp.BaseReg;
5777 if (AR.IntelExp.hasIndexReg())
5778 OS << (AR.IntelExp.hasBaseReg() ? " + " : "")
5779 << AR.IntelExp.IndexReg;
5780 if (AR.IntelExp.Scale > 1)
5781 OS << " * $$" << AR.IntelExp.Scale;
5782 if (AR.IntelExp.Imm || !AR.IntelExp.hasRegs())
5783 OS << (AR.IntelExp.hasRegs() ? " + $$" : "$$") << AR.IntelExp.Imm;
5784 if (AR.IntelExp.NeedBracs)
5785 OS << "]";
Chad Rosier8bce6642012-10-18 15:49:34 +00005786 break;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005787 case AOK_Label:
Matt Arsenault4e273432014-12-04 00:06:57 +00005788 OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005789 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005790 case AOK_Input:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005791 OS << '$' << InputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00005792 break;
5793 case AOK_Output:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005794 OS << '$' << OutputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00005795 break;
Chad Rosier0f48c552012-10-19 20:57:14 +00005796 case AOK_SizeDirective:
David Majnemer8114c1a2014-06-23 02:17:16 +00005797 switch (AR.Val) {
Chad Rosier0f48c552012-10-19 20:57:14 +00005798 default: break;
5799 case 8: OS << "byte ptr "; break;
5800 case 16: OS << "word ptr "; break;
5801 case 32: OS << "dword ptr "; break;
5802 case 64: OS << "qword ptr "; break;
5803 case 80: OS << "xword ptr "; break;
5804 case 128: OS << "xmmword ptr "; break;
5805 case 256: OS << "ymmword ptr "; break;
5806 }
Eli Friedman0f4871d2012-10-22 23:58:19 +00005807 break;
5808 case AOK_Emit:
5809 OS << ".byte";
5810 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00005811 case AOK_Align: {
Reid Klecknerfb1c1c72015-10-27 17:32:48 +00005812 // MS alignment directives are measured in bytes. If the native assembler
5813 // measures alignment in bytes, we can pass it straight through.
5814 OS << ".align";
5815 if (getContext().getAsmInfo()->getAlignmentIsInBytes())
5816 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00005817
Reid Klecknerfb1c1c72015-10-27 17:32:48 +00005818 // Alignment is in log2 form, so print that instead and skip the original
5819 // immediate.
5820 unsigned Val = AR.Val;
5821 OS << ' ' << Val;
Benjamin Kramer1a136112013-02-15 20:37:21 +00005822 assert(Val < 10 && "Expected alignment less then 2^10.");
Chad Rosierc7f552c2013-02-12 21:33:51 +00005823 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
5824 break;
5825 }
Michael Zuckerman02ecd432015-12-13 17:07:23 +00005826 case AOK_EVEN:
5827 OS << ".even";
5828 break;
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00005829 case AOK_EndOfStatement:
5830 OS << "\n\t";
5831 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005832 }
Chad Rosier0f48c552012-10-19 20:57:14 +00005833
Chad Rosier8bce6642012-10-18 15:49:34 +00005834 // Skip the original expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00005835 AsmStart = Loc + AR.Len + AdditionalSkip;
Chad Rosier8bce6642012-10-18 15:49:34 +00005836 }
5837
5838 // Emit the remainder of the asm string.
Chad Rosier17d37992013-03-19 21:12:14 +00005839 if (AsmStart != AsmEnd)
5840 OS << StringRef(AsmStart, AsmEnd - AsmStart);
Chad Rosier8bce6642012-10-18 15:49:34 +00005841
5842 AsmString = OS.str();
5843 return false;
5844}
5845
Pete Cooper80d21cb2015-06-22 19:35:57 +00005846namespace llvm {
5847namespace MCParserUtils {
5848
5849/// Returns whether the given symbol is used anywhere in the given expression,
5850/// or subexpressions.
5851static bool isSymbolUsedInExpression(const MCSymbol *Sym, const MCExpr *Value) {
5852 switch (Value->getKind()) {
5853 case MCExpr::Binary: {
5854 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
5855 return isSymbolUsedInExpression(Sym, BE->getLHS()) ||
5856 isSymbolUsedInExpression(Sym, BE->getRHS());
5857 }
5858 case MCExpr::Target:
5859 case MCExpr::Constant:
5860 return false;
5861 case MCExpr::SymbolRef: {
5862 const MCSymbol &S =
5863 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
5864 if (S.isVariable())
5865 return isSymbolUsedInExpression(Sym, S.getVariableValue());
5866 return &S == Sym;
5867 }
5868 case MCExpr::Unary:
5869 return isSymbolUsedInExpression(
5870 Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
5871 }
5872
5873 llvm_unreachable("Unknown expr kind!");
5874}
5875
5876bool parseAssignmentExpression(StringRef Name, bool allow_redef,
5877 MCAsmParser &Parser, MCSymbol *&Sym,
Nirav Dave7fd992a2018-08-16 16:31:14 +00005878 const MCExpr *&Value) {
Pete Cooper80d21cb2015-06-22 19:35:57 +00005879
5880 // FIXME: Use better location, we should use proper tokens.
Nirav Davefd910412016-06-17 16:06:17 +00005881 SMLoc EqualLoc = Parser.getTok().getLoc();
Nirav Dave7fd992a2018-08-16 16:31:14 +00005882 if (Parser.parseExpression(Value))
5883 return Parser.TokError("missing expression");
Pete Cooper80d21cb2015-06-22 19:35:57 +00005884
5885 // Note: we don't count b as used in "a = b". This is to allow
5886 // a = b
5887 // b = c
5888
Nirav Dave1a9044b2016-10-24 14:35:29 +00005889 if (Parser.parseToken(AsmToken::EndOfStatement))
5890 return true;
Pete Cooper80d21cb2015-06-22 19:35:57 +00005891
5892 // Validate that the LHS is allowed to be a variable (either it has not been
5893 // used as a symbol, or it is an absolute symbol).
5894 Sym = Parser.getContext().lookupSymbol(Name);
5895 if (Sym) {
5896 // Diagnose assignment to a label.
5897 //
5898 // FIXME: Diagnostics. Note the location of the definition as a label.
5899 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
5900 if (isSymbolUsedInExpression(Sym, Value))
5901 return Parser.Error(EqualLoc, "Recursive use of '" + Name + "'");
Vedant Kumar86dbd922015-08-31 17:44:53 +00005902 else if (Sym->isUndefined(/*SetUsed*/ false) && !Sym->isUsed() &&
5903 !Sym->isVariable())
Pete Cooper80d21cb2015-06-22 19:35:57 +00005904 ; // Allow redefinitions of undefined symbols only used in directives.
5905 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
5906 ; // Allow redefinitions of variables that haven't yet been used.
5907 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
5908 return Parser.Error(EqualLoc, "redefinition of '" + Name + "'");
5909 else if (!Sym->isVariable())
5910 return Parser.Error(EqualLoc, "invalid assignment to '" + Name + "'");
5911 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
5912 return Parser.Error(EqualLoc,
5913 "invalid reassignment of non-absolute variable '" +
5914 Name + "'");
Pete Cooper80d21cb2015-06-22 19:35:57 +00005915 } else if (Name == ".") {
Oliver Stannard268f42f2016-12-14 10:43:58 +00005916 Parser.getStreamer().emitValueToOffset(Value, 0, EqualLoc);
Pete Cooper80d21cb2015-06-22 19:35:57 +00005917 return false;
5918 } else
5919 Sym = Parser.getContext().getOrCreateSymbol(Name);
5920
5921 Sym->setRedefinable(allow_redef);
5922
5923 return false;
5924}
5925
Eugene Zelenko33d7b762016-08-23 17:14:32 +00005926} // end namespace MCParserUtils
5927} // end namespace llvm
Pete Cooper80d21cb2015-06-22 19:35:57 +00005928
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00005929/// Create an MCAsmParser instance.
Jim Grosbach4b905842013-09-20 23:08:21 +00005930MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
Sanne Wouda29338752017-02-08 14:48:05 +00005931 MCStreamer &Out, const MCAsmInfo &MAI,
5932 unsigned CB) {
5933 return new AsmParser(SM, C, Out, MAI, CB);
Daniel Dunbar01e36072010-07-17 02:26:10 +00005934}