blob: b43839db2d037fbf634dc376599413d45b2d742f [file] [log] [blame]
Chris Lattnerb0133452009-06-21 20:16:42 +00001//===- AsmParser.cpp - Parser for Assembly Files --------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This class implements the parser for assembly files.
11//
12//===----------------------------------------------------------------------===//
13
Daniel Dunbar2af16532010-09-24 01:59:56 +000014#include "llvm/ADT/APFloat.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000015#include "llvm/ADT/APInt.h"
16#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/None.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000018#include "llvm/ADT/STLExtras.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000019#include "llvm/ADT/SmallString.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000020#include "llvm/ADT/SmallVector.h"
Reid Kleckner26fa1bf2017-09-19 18:14:45 +000021#include "llvm/ADT/StringExtras.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000022#include "llvm/ADT/StringMap.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000023#include "llvm/ADT/StringRef.h"
Daniel Dunbareb6bb322009-07-27 23:20:52 +000024#include "llvm/ADT/Twine.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000025#include "llvm/BinaryFormat/Dwarf.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000026#include "llvm/MC/MCAsmInfo.h"
Reid Klecknera5b1eef2016-08-26 17:58:37 +000027#include "llvm/MC/MCCodeView.h"
Daniel Dunbarca29e4d2009-06-23 22:01:43 +000028#include "llvm/MC/MCContext.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000029#include "llvm/MC/MCDirectives.h"
Evan Cheng11424442011-07-26 00:24:13 +000030#include "llvm/MC/MCDwarf.h"
Daniel Dunbar115e4d62009-08-31 08:06:59 +000031#include "llvm/MC/MCExpr.h"
Chad Rosier8bce6642012-10-18 15:49:34 +000032#include "llvm/MC/MCInstPrinter.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000033#include "llvm/MC/MCInstrDesc.h"
Chad Rosier8bce6642012-10-18 15:49:34 +000034#include "llvm/MC/MCInstrInfo.h"
Rafael Espindolae28610d2013-12-09 20:26:40 +000035#include "llvm/MC/MCObjectFileInfo.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000036#include "llvm/MC/MCParser/AsmCond.h"
37#include "llvm/MC/MCParser/AsmLexer.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000038#include "llvm/MC/MCParser/MCAsmLexer.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000039#include "llvm/MC/MCParser/MCAsmParser.h"
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +000040#include "llvm/MC/MCParser/MCAsmParserExtension.h"
Pete Cooper80d21cb2015-06-22 19:35:57 +000041#include "llvm/MC/MCParser/MCAsmParserUtils.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000042#include "llvm/MC/MCParser/MCParsedAsmOperand.h"
Benjamin Kramerb3e8a6d2016-01-27 10:01:28 +000043#include "llvm/MC/MCParser/MCTargetAsmParser.h"
Evan Cheng76792992011-07-20 05:58:47 +000044#include "llvm/MC/MCRegisterInfo.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000045#include "llvm/MC/MCSection.h"
Daniel Dunbarca29e4d2009-06-23 22:01:43 +000046#include "llvm/MC/MCStreamer.h"
Daniel Dunbarae7ac012009-06-29 23:43:14 +000047#include "llvm/MC/MCSymbol.h"
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +000048#include "llvm/MC/MCTargetOptions.h"
Daniel Sanders9f6ad492015-11-12 13:33:00 +000049#include "llvm/MC/MCValue.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000050#include "llvm/Support/Casting.h"
Davide Italiano7c9fc732016-07-27 05:51:56 +000051#include "llvm/Support/CommandLine.h"
Benjamin Kramer4efe5062012-01-28 15:28:41 +000052#include "llvm/Support/ErrorHandling.h"
Paul Robinson29f5f982018-01-09 23:31:48 +000053#include "llvm/Support/MD5.h"
Jim Grosbach76346c32011-06-29 16:05:14 +000054#include "llvm/Support/MathExtras.h"
Kevin Enderbye233dda2010-06-28 21:45:58 +000055#include "llvm/Support/MemoryBuffer.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000056#include "llvm/Support/SMLoc.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000057#include "llvm/Support/SourceMgr.h"
Chris Lattner36e02122009-06-21 20:54:55 +000058#include "llvm/Support/raw_ostream.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000059#include <algorithm>
60#include <cassert>
Nick Lewycky0de20af2010-12-19 20:43:38 +000061#include <cctype>
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +000062#include <climits>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000063#include <cstddef>
64#include <cstdint>
Benjamin Kramerd59664f2014-04-29 23:26:49 +000065#include <deque>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000066#include <memory>
Davide Italiano7c9fc732016-07-27 05:51:56 +000067#include <sstream>
Chad Rosier8bce6642012-10-18 15:49:34 +000068#include <string>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000069#include <tuple>
70#include <utility>
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000071#include <vector>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000072
Chris Lattnerb0133452009-06-21 20:16:42 +000073using namespace llvm;
74
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +000075MCAsmParserSemaCallback::~MCAsmParserSemaCallback() = default;
Nick Lewyckyac612272012-10-19 07:00:09 +000076
Davide Italiano7c9fc732016-07-27 05:51:56 +000077static cl::opt<unsigned> AsmMacroMaxNestingDepth(
78 "asm-macro-max-nesting-depth", cl::init(20), cl::Hidden,
79 cl::desc("The maximum nesting depth allowed for assembly macros."));
80
Daniel Dunbar86033402010-07-12 17:54:38 +000081namespace {
Eugene Zelenko33d7b762016-08-23 17:14:32 +000082
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000083/// Helper types for tracking macro definitions.
Eli Benderskya313ae62013-01-16 18:56:50 +000084typedef std::vector<AsmToken> MCAsmMacroArgument;
85typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +000086
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000087/// Helper class for storing information about an active macro
Daniel Dunbar43235712010-07-18 18:54:11 +000088/// instantiation.
89struct MacroInstantiation {
Daniel Dunbar43235712010-07-18 18:54:11 +000090 /// The location of the instantiation.
91 SMLoc InstantiationLoc;
92
Daniel Dunbar40f1d852012-12-01 01:38:48 +000093 /// The buffer where parsing should resume upon instantiation completion.
94 int ExitBuffer;
95
Daniel Dunbar43235712010-07-18 18:54:11 +000096 /// The location where parsing should resume upon instantiation completion.
97 SMLoc ExitLoc;
98
Nico Weber155dccd12014-07-24 17:08:39 +000099 /// The depth of TheCondStack at the start of the instantiation.
100 size_t CondStackDepth;
101
Daniel Dunbar43235712010-07-18 18:54:11 +0000102public:
Rafael Espindola9eef18c2014-08-27 19:49:03 +0000103 MacroInstantiation(SMLoc IL, int EB, SMLoc EL, size_t CondStackDepth);
Daniel Dunbar43235712010-07-18 18:54:11 +0000104};
105
Eli Friedman0f4871d2012-10-22 23:58:19 +0000106struct ParseStatementInfo {
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000107 /// The parsed operands from the last parsed statement.
David Blaikie960ea3f2014-06-08 16:18:35 +0000108 SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> ParsedOperands;
Eli Friedman0f4871d2012-10-22 23:58:19 +0000109
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000110 /// The opcode from the last parsed instruction.
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000111 unsigned Opcode = ~0U;
Eli Friedman0f4871d2012-10-22 23:58:19 +0000112
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000113 /// Was there an error parsing the inline assembly?
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000114 bool ParseError = false;
Chad Rosier149e8e02012-12-12 22:45:52 +0000115
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000116 SmallVectorImpl<AsmRewrite> *AsmRewrites = nullptr;
Eli Friedman0f4871d2012-10-22 23:58:19 +0000117
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +0000118 ParseStatementInfo() = delete;
Eli Friedman0f4871d2012-10-22 23:58:19 +0000119 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000120 : AsmRewrites(rewrites) {}
Eli Friedman0f4871d2012-10-22 23:58:19 +0000121};
122
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000123/// The concrete assembly parser instance.
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000124class AsmParser : public MCAsmParser {
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000125private:
126 AsmLexer Lexer;
127 MCContext &Ctx;
128 MCStreamer &Out;
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000129 const MCAsmInfo &MAI;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000130 SourceMgr &SrcMgr;
Benjamin Kramer47f5e302011-10-16 10:48:29 +0000131 SourceMgr::DiagHandlerTy SavedDiagHandler;
132 void *SavedDiagContext;
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000133 std::unique_ptr<MCAsmParserExtension> PlatformParser;
Rafael Espindola82065cb2011-04-11 21:49:50 +0000134
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000135 /// This is the current buffer index we're lexing from as managed by the
136 /// SourceMgr object.
Alp Tokera55b95b2014-07-06 10:33:31 +0000137 unsigned CurBuffer;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000138
139 AsmCond TheCondState;
140 std::vector<AsmCond> TheCondStack;
141
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000142 /// maps directive names to handler methods in parser
Eli Bendersky17233942013-01-15 22:59:42 +0000143 /// extensions. Extensions register themselves in this map by calling
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000144 /// addDirectiveHandler.
Eli Bendersky17233942013-01-15 22:59:42 +0000145 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
Daniel Dunbar828984f2010-07-18 18:38:02 +0000146
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000147 /// Stack of active macro instantiations.
Daniel Dunbar43235712010-07-18 18:54:11 +0000148 std::vector<MacroInstantiation*> ActiveMacros;
149
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000150 /// List of bodies of anonymous macros.
Benjamin Kramer1df3a1f2013-08-04 09:06:29 +0000151 std::deque<MCAsmMacro> MacroLikeBodies;
152
Daniel Dunbar828984f2010-07-18 18:38:02 +0000153 /// Boolean tracking whether macro substitution is enabled.
Eli Benderskyc2f6f922013-01-14 18:08:41 +0000154 unsigned MacrosEnabledFlag : 1;
Daniel Dunbar828984f2010-07-18 18:38:02 +0000155
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000156 /// Keeps track of how many .macro's have been instantiated.
Toma Tabacu217116e2015-04-27 10:50:29 +0000157 unsigned NumOfMacroInstantiations;
158
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000159 /// The values from the last parsed cpp hash file line comment if any.
Tim Northoverc0bef992016-04-13 19:46:54 +0000160 struct CppHashInfoTy {
161 StringRef Filename;
Andrew Kaylorca196472016-04-21 20:09:35 +0000162 int64_t LineNumber = 0;
Tim Northoverc0bef992016-04-13 19:46:54 +0000163 SMLoc Loc;
Andrew Kaylorca196472016-04-21 20:09:35 +0000164 unsigned Buf = 0;
Tim Northoverc0bef992016-04-13 19:46:54 +0000165 };
166 CppHashInfoTy CppHashInfo;
167
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000168 /// List of forward directional labels for diagnosis at the end.
Tim Northoverc0bef992016-04-13 19:46:54 +0000169 SmallVector<std::tuple<SMLoc, CppHashInfoTy, MCSymbol *>, 4> DirLabels;
170
Devang Patela173ee52012-01-31 18:14:05 +0000171 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000172 unsigned AssemblerDialect = ~0U;
Devang Patela173ee52012-01-31 18:14:05 +0000173
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000174 /// is Darwin compatibility enabled?
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000175 bool IsDarwin = false;
Preston Gurd05500642012-09-19 20:36:12 +0000176
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000177 /// Are we parsing ms-style inline assembly?
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000178 bool ParsingInlineAsm = false;
Chad Rosier49963552012-10-13 00:26:04 +0000179
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000180public:
Jim Grosbach345768c2011-08-16 18:33:49 +0000181 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Sanne Wouda29338752017-02-08 14:48:05 +0000182 const MCAsmInfo &MAI, unsigned CB);
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000183 AsmParser(const AsmParser &) = delete;
184 AsmParser &operator=(const AsmParser &) = delete;
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000185 ~AsmParser() override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000186
Craig Topper59be68f2014-03-08 07:14:16 +0000187 bool Run(bool NoInitialTextSection, bool NoFinalize = false) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000188
Craig Topper59be68f2014-03-08 07:14:16 +0000189 void addDirectiveHandler(StringRef Directive,
190 ExtensionDirectiveHandler Handler) override {
Eli Bendersky29b9f472013-01-16 00:50:52 +0000191 ExtensionDirectiveMap[Directive] = Handler;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000192 }
193
Toma Tabacu11e14a92015-04-21 11:50:52 +0000194 void addAliasForDirective(StringRef Directive, StringRef Alias) override {
195 DirectiveKindMap[Directive] = DirectiveKindMap[Alias];
196 }
197
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000198 /// @name MCAsmParser Interface
199 /// {
200
Craig Topper59be68f2014-03-08 07:14:16 +0000201 SourceMgr &getSourceManager() override { return SrcMgr; }
202 MCAsmLexer &getLexer() override { return Lexer; }
203 MCContext &getContext() override { return Ctx; }
204 MCStreamer &getStreamer() override { return Out; }
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000205
Reid Klecknera5b1eef2016-08-26 17:58:37 +0000206 CodeViewContext &getCVContext() { return Ctx.getCVContext(); }
207
Craig Topper59be68f2014-03-08 07:14:16 +0000208 unsigned getAssemblerDialect() override {
Devang Patela173ee52012-01-31 18:14:05 +0000209 if (AssemblerDialect == ~0U)
Eric Christophera7c32732012-12-18 00:30:54 +0000210 return MAI.getAssemblerDialect();
Devang Patela173ee52012-01-31 18:14:05 +0000211 else
212 return AssemblerDialect;
213 }
Craig Topper59be68f2014-03-08 07:14:16 +0000214 void setAssemblerDialect(unsigned i) override {
Devang Patela173ee52012-01-31 18:14:05 +0000215 AssemblerDialect = i;
216 }
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000217
Nirav Dave2364748a2016-09-16 18:30:20 +0000218 void Note(SMLoc L, const Twine &Msg, SMRange Range = None) override;
219 bool Warning(SMLoc L, const Twine &Msg, SMRange Range = None) override;
220 bool printError(SMLoc L, const Twine &Msg, SMRange Range = None) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000221
Craig Topper59be68f2014-03-08 07:14:16 +0000222 const AsmToken &Lex() override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000223
Yunzhong Gao27ea29b2016-09-02 23:15:29 +0000224 void setParsingInlineAsm(bool V) override {
225 ParsingInlineAsm = V;
226 Lexer.setParsingMSInlineAsm(V);
227 }
Craig Topper59be68f2014-03-08 07:14:16 +0000228 bool isParsingInlineAsm() override { return ParsingInlineAsm; }
Chad Rosier8bce6642012-10-18 15:49:34 +0000229
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000230 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
Chad Rosier8bce6642012-10-18 15:49:34 +0000231 unsigned &NumOutputs, unsigned &NumInputs,
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000232 SmallVectorImpl<std::pair<void *,bool>> &OpDecls,
Chad Rosier8bce6642012-10-18 15:49:34 +0000233 SmallVectorImpl<std::string> &Constraints,
Chad Rosier8bce6642012-10-18 15:49:34 +0000234 SmallVectorImpl<std::string> &Clobbers,
Craig Topper59be68f2014-03-08 07:14:16 +0000235 const MCInstrInfo *MII, const MCInstPrinter *IP,
236 MCAsmParserSemaCallback &SI) override;
Chad Rosier49963552012-10-13 00:26:04 +0000237
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000238 bool parseExpression(const MCExpr *&Res);
Craig Topper59be68f2014-03-08 07:14:16 +0000239 bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
240 bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) override;
241 bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
Toma Tabacu7bc44dc2015-06-25 09:52:02 +0000242 bool parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
243 SMLoc &EndLoc) override;
Craig Topper59be68f2014-03-08 07:14:16 +0000244 bool parseAbsoluteExpression(int64_t &Res) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000245
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000246 /// Parse a floating point expression using the float \p Semantics
Petr Hosek4cb08ce2016-09-23 19:25:15 +0000247 /// and set \p Res to the value.
248 bool parseRealValue(const fltSemantics &Semantics, APInt &Res);
249
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000250 /// Parse an identifier or string (as a quoted identifier)
Eli Bendersky0cf0cb92013-01-12 00:05:00 +0000251 /// and set \p Res to the identifier contents.
Craig Topper59be68f2014-03-08 07:14:16 +0000252 bool parseIdentifier(StringRef &Res) override;
253 void eatToEndOfStatement() override;
Eli Bendersky0cf0cb92013-01-12 00:05:00 +0000254
Nirav Davef43cc9f2016-10-10 15:24:54 +0000255 bool checkForValidSection() override;
Nirav Davea645433c2016-07-18 15:24:03 +0000256
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000257 /// }
258
259private:
Michael Zuckerman763e60e2017-05-04 10:37:00 +0000260 bool isAltmacroString(SMLoc &StrLoc, SMLoc &EndLoc);
Michael Zuckerman1f1a9122017-05-10 13:08:11 +0000261 void altMacroString(StringRef AltMacroStr, std::string &Res);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +0000262 bool parseStatement(ParseStatementInfo &Info,
263 MCAsmParserSemaCallback *SI);
Marina Yatsina5f5de9f2016-03-07 18:11:16 +0000264 bool parseCurlyBlockScope(SmallVectorImpl<AsmRewrite>& AsmStrRewrites);
Craig Topper3c76c522015-09-20 23:35:59 +0000265 bool parseCppHashLineFilenameComment(SMLoc L);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000266
Jim Grosbach4b905842013-09-20 23:08:21 +0000267 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +0000268 ArrayRef<MCAsmMacroParameter> Parameters);
Rafael Espindola34b9c512012-06-03 23:57:14 +0000269 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +0000270 ArrayRef<MCAsmMacroParameter> Parameters,
Toma Tabacu217116e2015-04-27 10:50:29 +0000271 ArrayRef<MCAsmMacroArgument> A, bool EnableAtPseudoVariable,
Craig Topper3c76c522015-09-20 23:35:59 +0000272 SMLoc L);
Daniel Dunbar43235712010-07-18 18:54:11 +0000273
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000274 /// Are macros enabled in the parser?
Jim Grosbach4b905842013-09-20 23:08:21 +0000275 bool areMacrosEnabled() {return MacrosEnabledFlag;}
Eli Benderskya313ae62013-01-16 18:56:50 +0000276
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000277 /// Control a flag in the parser that enables or disables macros.
Jim Grosbach4b905842013-09-20 23:08:21 +0000278 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
Eli Benderskya313ae62013-01-16 18:56:50 +0000279
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000280 /// Are we inside a macro instantiation?
Jim Grosbach4b905842013-09-20 23:08:21 +0000281 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
Eli Benderskya313ae62013-01-16 18:56:50 +0000282
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000283 /// Handle entry to macro instantiation.
Eli Benderskya313ae62013-01-16 18:56:50 +0000284 ///
285 /// \param M The macro.
286 /// \param NameLoc Instantiation location.
Jim Grosbach4b905842013-09-20 23:08:21 +0000287 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
Eli Benderskya313ae62013-01-16 18:56:50 +0000288
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000289 /// Handle exit from macro instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +0000290 void handleMacroExit();
Eli Benderskya313ae62013-01-16 18:56:50 +0000291
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000292 /// Extract AsmTokens for a macro argument.
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +0000293 bool parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg);
Eli Benderskya313ae62013-01-16 18:56:50 +0000294
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000295 /// Parse all macro arguments for a given macro.
Jim Grosbach4b905842013-09-20 23:08:21 +0000296 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
Eli Benderskya313ae62013-01-16 18:56:50 +0000297
Jim Grosbach4b905842013-09-20 23:08:21 +0000298 void printMacroInstantiations();
299 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
Nirav Dave2364748a2016-09-16 18:30:20 +0000300 SMRange Range = None) const {
301 ArrayRef<SMRange> Ranges(Range);
Chris Lattner72845262011-10-16 05:47:55 +0000302 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
Benjamin Kramerc7583112010-09-27 17:42:11 +0000303 }
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000304 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
Benjamin Kramerc7583112010-09-27 17:42:11 +0000305
Paul Robinson938d9a02018-03-22 15:48:01 +0000306 /// Should we emit DWARF describing this assembler source? (Returns false if
307 /// the source has .file directives, which means we don't want to generate
308 /// info describing the assembler source itself.)
309 bool enabledGenDwarfForAssembly();
310
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000311 /// Enter the specified file. This returns true on failure.
Jim Grosbach4b905842013-09-20 23:08:21 +0000312 bool enterIncludeFile(const std::string &Filename);
313
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000314 /// Process the specified file for the .incbin directive.
Kevin Enderby109f25c2011-12-14 21:47:48 +0000315 /// This returns true on failure.
Petr Hosek2f4ac442016-09-23 00:41:06 +0000316 bool processIncbinFile(const std::string &Filename, int64_t Skip = 0,
317 const MCExpr *Count = nullptr, SMLoc Loc = SMLoc());
Daniel Dunbar43235712010-07-18 18:54:11 +0000318
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000319 /// Reset the current lexer position to that given by \p Loc. The
Daniel Dunbar43235712010-07-18 18:54:11 +0000320 /// current token is not set; clients should ensure Lex() is called
321 /// subsequently.
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000322 ///
Alp Tokera55b95b2014-07-06 10:33:31 +0000323 /// \param InBuffer If not 0, should be the known buffer id that contains the
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000324 /// location.
Alp Tokera55b95b2014-07-06 10:33:31 +0000325 void jumpToLoc(SMLoc Loc, unsigned InBuffer = 0);
Daniel Dunbar43235712010-07-18 18:54:11 +0000326
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000327 /// Parse up to the end of statement and a return the contents from the
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000328 /// current token until the end of the statement; the current token on exit
329 /// will be either the EndOfStatement or EOF.
Craig Topper59be68f2014-03-08 07:14:16 +0000330 StringRef parseStringToEndOfStatement() override;
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000331
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000332 /// Parse until the end of a statement or a comma is encountered,
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000333 /// return the contents from the current token up to the end or comma.
Jim Grosbach4b905842013-09-20 23:08:21 +0000334 StringRef parseStringToComma();
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000335
Jim Grosbach4b905842013-09-20 23:08:21 +0000336 bool parseAssignment(StringRef Name, bool allow_redef,
Nirav Dave05b58912018-06-05 15:13:39 +0000337 bool NoDeadStrip = false, bool AllowExtendedExpr = false);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000338
Ahmed Bougacha457852f2015-04-28 00:17:39 +0000339 unsigned getBinOpPrecedence(AsmToken::TokenKind K,
340 MCBinaryExpr::Opcode &Kind);
341
Jim Grosbach4b905842013-09-20 23:08:21 +0000342 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
343 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
344 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000345
Jim Grosbach4b905842013-09-20 23:08:21 +0000346 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
Rafael Espindola63760ba2010-10-28 20:02:27 +0000347
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000348 bool parseCVFunctionId(int64_t &FunctionId, StringRef DirectiveName);
349 bool parseCVFileId(int64_t &FileId, StringRef DirectiveName);
350
Eli Bendersky17233942013-01-15 22:59:42 +0000351 // Generic (target and platform independent) directive parsing.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000352 enum DirectiveKind {
Eli Bendersky4d21fa02013-01-10 23:40:56 +0000353 DK_NO_DIRECTIVE, // Placeholder
Saleem Abdulrasoolb3c70c02017-07-28 03:39:18 +0000354 DK_SET,
355 DK_EQU,
356 DK_EQUIV,
357 DK_ASCII,
358 DK_ASCIZ,
359 DK_STRING,
360 DK_BYTE,
361 DK_SHORT,
Daniel Sanders9f6ad492015-11-12 13:33:00 +0000362 DK_RELOC,
Saleem Abdulrasoolb3c70c02017-07-28 03:39:18 +0000363 DK_VALUE,
364 DK_2BYTE,
365 DK_LONG,
366 DK_INT,
367 DK_4BYTE,
368 DK_QUAD,
369 DK_8BYTE,
370 DK_OCTA,
371 DK_DC,
372 DK_DC_A,
373 DK_DC_B,
374 DK_DC_D,
375 DK_DC_L,
376 DK_DC_S,
377 DK_DC_W,
378 DK_DC_X,
379 DK_DCB,
380 DK_DCB_B,
381 DK_DCB_D,
382 DK_DCB_L,
383 DK_DCB_S,
384 DK_DCB_W,
385 DK_DCB_X,
386 DK_DS,
387 DK_DS_B,
388 DK_DS_D,
389 DK_DS_L,
390 DK_DS_P,
391 DK_DS_S,
392 DK_DS_W,
393 DK_DS_X,
394 DK_SINGLE,
395 DK_FLOAT,
396 DK_DOUBLE,
397 DK_ALIGN,
398 DK_ALIGN32,
399 DK_BALIGN,
400 DK_BALIGNW,
401 DK_BALIGNL,
402 DK_P2ALIGN,
403 DK_P2ALIGNW,
404 DK_P2ALIGNL,
405 DK_ORG,
406 DK_FILL,
407 DK_ENDR,
408 DK_BUNDLE_ALIGN_MODE,
409 DK_BUNDLE_LOCK,
410 DK_BUNDLE_UNLOCK,
411 DK_ZERO,
412 DK_EXTERN,
413 DK_GLOBL,
414 DK_GLOBAL,
415 DK_LAZY_REFERENCE,
416 DK_NO_DEAD_STRIP,
417 DK_SYMBOL_RESOLVER,
418 DK_PRIVATE_EXTERN,
419 DK_REFERENCE,
420 DK_WEAK_DEFINITION,
421 DK_WEAK_REFERENCE,
422 DK_WEAK_DEF_CAN_BE_HIDDEN,
423 DK_COMM,
424 DK_COMMON,
425 DK_LCOMM,
426 DK_ABORT,
427 DK_INCLUDE,
428 DK_INCBIN,
429 DK_CODE16,
430 DK_CODE16GCC,
431 DK_REPT,
432 DK_IRP,
433 DK_IRPC,
434 DK_IF,
435 DK_IFEQ,
436 DK_IFGE,
437 DK_IFGT,
438 DK_IFLE,
439 DK_IFLT,
440 DK_IFNE,
441 DK_IFB,
442 DK_IFNB,
443 DK_IFC,
444 DK_IFEQS,
445 DK_IFNC,
446 DK_IFNES,
447 DK_IFDEF,
448 DK_IFNDEF,
449 DK_IFNOTDEF,
450 DK_ELSEIF,
451 DK_ELSE,
452 DK_ENDIF,
453 DK_SPACE,
454 DK_SKIP,
455 DK_FILE,
456 DK_LINE,
457 DK_LOC,
458 DK_STABS,
459 DK_CV_FILE,
460 DK_CV_FUNC_ID,
461 DK_CV_INLINE_SITE_ID,
462 DK_CV_LOC,
463 DK_CV_LINETABLE,
464 DK_CV_INLINE_LINETABLE,
465 DK_CV_DEF_RANGE,
466 DK_CV_STRINGTABLE,
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000467 DK_CV_FILECHECKSUMS,
Reid Kleckner26fa1bf2017-09-19 18:14:45 +0000468 DK_CV_FILECHECKSUM_OFFSET,
Reid Kleckner9cdd4df2017-10-11 21:24:33 +0000469 DK_CV_FPO_DATA,
Saleem Abdulrasoolb3c70c02017-07-28 03:39:18 +0000470 DK_CFI_SECTIONS,
471 DK_CFI_STARTPROC,
472 DK_CFI_ENDPROC,
473 DK_CFI_DEF_CFA,
474 DK_CFI_DEF_CFA_OFFSET,
475 DK_CFI_ADJUST_CFA_OFFSET,
476 DK_CFI_DEF_CFA_REGISTER,
477 DK_CFI_OFFSET,
478 DK_CFI_REL_OFFSET,
479 DK_CFI_PERSONALITY,
480 DK_CFI_LSDA,
481 DK_CFI_REMEMBER_STATE,
482 DK_CFI_RESTORE_STATE,
483 DK_CFI_SAME_VALUE,
484 DK_CFI_RESTORE,
485 DK_CFI_ESCAPE,
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +0000486 DK_CFI_RETURN_COLUMN,
Saleem Abdulrasoolb3c70c02017-07-28 03:39:18 +0000487 DK_CFI_SIGNAL_FRAME,
488 DK_CFI_UNDEFINED,
489 DK_CFI_REGISTER,
490 DK_CFI_WINDOW_SAVE,
491 DK_MACROS_ON,
492 DK_MACROS_OFF,
493 DK_ALTMACRO,
494 DK_NOALTMACRO,
495 DK_MACRO,
496 DK_EXITM,
497 DK_ENDM,
498 DK_ENDMACRO,
499 DK_PURGEM,
500 DK_SLEB128,
501 DK_ULEB128,
502 DK_ERR,
503 DK_ERROR,
504 DK_WARNING,
Coby Tayree01e53202017-10-02 14:36:31 +0000505 DK_PRINT,
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000506 DK_END
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000507 };
508
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000509 /// Maps directive name --> DirectiveKind enum, for
Eli Bendersky17233942013-01-15 22:59:42 +0000510 /// directives parsed by this class.
511 StringMap<DirectiveKind> DirectiveKindMap;
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000512
513 // ".ascii", ".asciz", ".string"
Jim Grosbach4b905842013-09-20 23:08:21 +0000514 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
Daniel Sanders9f6ad492015-11-12 13:33:00 +0000515 bool parseDirectiveReloc(SMLoc DirectiveLoc); // ".reloc"
Nirav Dave1a9044b2016-10-24 14:35:29 +0000516 bool parseDirectiveValue(StringRef IDVal,
517 unsigned Size); // ".byte", ".long", ...
518 bool parseDirectiveOctaValue(StringRef IDVal); // ".octa", ...
519 bool parseDirectiveRealValue(StringRef IDVal,
520 const fltSemantics &); // ".single", ...
Jim Grosbach4b905842013-09-20 23:08:21 +0000521 bool parseDirectiveFill(); // ".fill"
522 bool parseDirectiveZero(); // ".zero"
Eric Christophera7c32732012-12-18 00:30:54 +0000523 // ".set", ".equ", ".equiv"
Jim Grosbach4b905842013-09-20 23:08:21 +0000524 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
525 bool parseDirectiveOrg(); // ".org"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000526 // ".align{,32}", ".p2align{,w,l}"
Jim Grosbach4b905842013-09-20 23:08:21 +0000527 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000528
Eli Bendersky17233942013-01-15 22:59:42 +0000529 // ".file", ".line", ".loc", ".stabs"
Jim Grosbach4b905842013-09-20 23:08:21 +0000530 bool parseDirectiveFile(SMLoc DirectiveLoc);
531 bool parseDirectiveLine();
532 bool parseDirectiveLoc();
533 bool parseDirectiveStabs();
Eli Bendersky17233942013-01-15 22:59:42 +0000534
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000535 // ".cv_file", ".cv_func_id", ".cv_inline_site_id", ".cv_loc", ".cv_linetable",
536 // ".cv_inline_linetable", ".cv_def_range"
Reid Kleckner2214ed82016-01-29 00:49:42 +0000537 bool parseDirectiveCVFile();
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000538 bool parseDirectiveCVFuncId();
539 bool parseDirectiveCVInlineSiteId();
Reid Kleckner2214ed82016-01-29 00:49:42 +0000540 bool parseDirectiveCVLoc();
541 bool parseDirectiveCVLinetable();
David Majnemer6fcbd7e2016-01-29 19:24:12 +0000542 bool parseDirectiveCVInlineLinetable();
David Majnemer408b5e62016-02-05 01:55:49 +0000543 bool parseDirectiveCVDefRange();
Reid Kleckner2214ed82016-01-29 00:49:42 +0000544 bool parseDirectiveCVStringTable();
545 bool parseDirectiveCVFileChecksums();
Reid Kleckner26fa1bf2017-09-19 18:14:45 +0000546 bool parseDirectiveCVFileChecksumOffset();
Reid Kleckner9cdd4df2017-10-11 21:24:33 +0000547 bool parseDirectiveCVFPOData();
Reid Kleckner2214ed82016-01-29 00:49:42 +0000548
Eli Bendersky17233942013-01-15 22:59:42 +0000549 // .cfi directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000550 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +0000551 bool parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +0000552 bool parseDirectiveCFISections();
553 bool parseDirectiveCFIStartProc();
554 bool parseDirectiveCFIEndProc();
555 bool parseDirectiveCFIDefCfaOffset();
556 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
557 bool parseDirectiveCFIAdjustCfaOffset();
558 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
559 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
560 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
561 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
562 bool parseDirectiveCFIRememberState();
563 bool parseDirectiveCFIRestoreState();
564 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
565 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
566 bool parseDirectiveCFIEscape();
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +0000567 bool parseDirectiveCFIReturnColumn(SMLoc DirectiveLoc);
Jim Grosbach4b905842013-09-20 23:08:21 +0000568 bool parseDirectiveCFISignalFrame();
569 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
Eli Bendersky17233942013-01-15 22:59:42 +0000570
571 // macro directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000572 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
Nico Weber155dccd12014-07-24 17:08:39 +0000573 bool parseDirectiveExitMacro(StringRef Directive);
Jim Grosbach4b905842013-09-20 23:08:21 +0000574 bool parseDirectiveEndMacro(StringRef Directive);
575 bool parseDirectiveMacro(SMLoc DirectiveLoc);
576 bool parseDirectiveMacrosOnOff(StringRef Directive);
Michael Zuckerman56704612017-05-01 13:20:12 +0000577 // alternate macro mode directives
578 bool parseDirectiveAltmacro(StringRef Directive);
Eli Benderskyf483ff92012-12-20 19:05:53 +0000579 // ".bundle_align_mode"
Jim Grosbach4b905842013-09-20 23:08:21 +0000580 bool parseDirectiveBundleAlignMode();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000581 // ".bundle_lock"
Jim Grosbach4b905842013-09-20 23:08:21 +0000582 bool parseDirectiveBundleLock();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000583 // ".bundle_unlock"
Jim Grosbach4b905842013-09-20 23:08:21 +0000584 bool parseDirectiveBundleUnlock();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000585
Eli Bendersky17233942013-01-15 22:59:42 +0000586 // ".space", ".skip"
Jim Grosbach4b905842013-09-20 23:08:21 +0000587 bool parseDirectiveSpace(StringRef IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +0000588
Petr Hosek4cb08ce2016-09-23 19:25:15 +0000589 // ".dcb"
590 bool parseDirectiveDCB(StringRef IDVal, unsigned Size);
591 bool parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &);
Petr Hosek85b2f672016-09-23 21:53:36 +0000592 // ".ds"
593 bool parseDirectiveDS(StringRef IDVal, unsigned Size);
Petr Hosek4cb08ce2016-09-23 19:25:15 +0000594
Eli Bendersky17233942013-01-15 22:59:42 +0000595 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
Jim Grosbach4b905842013-09-20 23:08:21 +0000596 bool parseDirectiveLEB128(bool Signed);
Eli Bendersky17233942013-01-15 22:59:42 +0000597
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000598 /// Parse a directive like ".globl" which
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000599 /// accepts a single symbol (which should be a label or an external).
Jim Grosbach4b905842013-09-20 23:08:21 +0000600 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000601
Jim Grosbach4b905842013-09-20 23:08:21 +0000602 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000603
Jim Grosbach4b905842013-09-20 23:08:21 +0000604 bool parseDirectiveAbort(); // ".abort"
605 bool parseDirectiveInclude(); // ".include"
606 bool parseDirectiveIncbin(); // ".incbin"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000607
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +0000608 // ".if", ".ifeq", ".ifge", ".ifgt" , ".ifle", ".iflt" or ".ifne"
609 bool parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind);
Benjamin Kramer62c18b02012-05-12 11:18:42 +0000610 // ".ifb" or ".ifnb", depending on ExpectBlank.
Jim Grosbach4b905842013-09-20 23:08:21 +0000611 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000612 // ".ifc" or ".ifnc", depending on ExpectEqual.
Jim Grosbach4b905842013-09-20 23:08:21 +0000613 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
Sid Manning51c35602015-03-18 14:20:54 +0000614 // ".ifeqs" or ".ifnes", depending on ExpectEqual.
615 bool parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +0000616 // ".ifdef" or ".ifndef", depending on expect_defined
Jim Grosbach4b905842013-09-20 23:08:21 +0000617 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
618 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
619 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
620 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
Craig Topper59be68f2014-03-08 07:14:16 +0000621 bool parseEscapedString(std::string &Data) override;
Daniel Dunbar55f16672010-09-17 02:47:07 +0000622
Jim Grosbach4b905842013-09-20 23:08:21 +0000623 const MCExpr *applyModifierToExpr(const MCExpr *E,
Daniel Dunbar55f16672010-09-17 02:47:07 +0000624 MCSymbolRefExpr::VariantKind Variant);
Rafael Espindola47b7dac2012-05-12 16:31:10 +0000625
Rafael Espindola34b9c512012-06-03 23:57:14 +0000626 // Macro-like directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000627 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
628 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +0000629 raw_svector_ostream &OS);
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +0000630 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
Jim Grosbach4b905842013-09-20 23:08:21 +0000631 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
632 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
633 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
Chad Rosier8bce6642012-10-18 15:49:34 +0000634
Chad Rosierc7f552c2013-02-12 21:33:51 +0000635 // "_emit" or "__emit"
Jim Grosbach4b905842013-09-20 23:08:21 +0000636 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
Chad Rosierc7f552c2013-02-12 21:33:51 +0000637 size_t Len);
638
639 // "align"
Jim Grosbach4b905842013-09-20 23:08:21 +0000640 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000641
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000642 // "end"
643 bool parseDirectiveEnd(SMLoc DirectiveLoc);
644
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +0000645 // ".err" or ".error"
646 bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +0000647
Nico Weber404012b2014-07-24 16:26:06 +0000648 // ".warning"
649 bool parseDirectiveWarning(SMLoc DirectiveLoc);
650
Coby Tayree01e53202017-10-02 14:36:31 +0000651 // .print <double-quotes-string>
652 bool parseDirectivePrint(SMLoc DirectiveLoc);
653
Eli Bendersky17233942013-01-15 22:59:42 +0000654 void initializeDirectiveKindMap();
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000655};
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000656
657} // end anonymous namespace
Daniel Dunbar86033402010-07-12 17:54:38 +0000658
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000659namespace llvm {
660
661extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbarab058b82010-07-12 21:23:32 +0000662extern MCAsmParserExtension *createELFAsmParser();
Michael J. Spencerc8dbdfd2010-10-09 11:01:07 +0000663extern MCAsmParserExtension *createCOFFAsmParser();
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000664
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000665} // end namespace llvm
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000666
Chris Lattnerc35681b2010-01-19 19:46:13 +0000667enum { DEFAULT_ADDRSPACE = 0 };
668
David Blaikie9f380a32015-03-16 18:06:57 +0000669AsmParser::AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Sanne Wouda29338752017-02-08 14:48:05 +0000670 const MCAsmInfo &MAI, unsigned CB = 0)
David Blaikie9f380a32015-03-16 18:06:57 +0000671 : Lexer(MAI), Ctx(Ctx), Out(Out), MAI(MAI), SrcMgr(SM),
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +0000672 CurBuffer(CB ? CB : SM.getMainFileID()), MacrosEnabledFlag(true) {
Nirav Dave2364748a2016-09-16 18:30:20 +0000673 HadError = false;
Benjamin Kramer47f5e302011-10-16 10:48:29 +0000674 // Save the old handler.
675 SavedDiagHandler = SrcMgr.getDiagHandler();
676 SavedDiagContext = SrcMgr.getDiagContext();
677 // Set our own handler which calls the saved handler.
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000678 SrcMgr.setDiagHandler(DiagHandler, this);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000679 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar86033402010-07-12 17:54:38 +0000680
Daniel Dunbarc5011082010-07-12 18:12:02 +0000681 // Initialize the platform / file format parser.
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000682 switch (Ctx.getObjectFileInfo()->getObjectFileType()) {
683 case MCObjectFileInfo::IsCOFF:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000684 PlatformParser.reset(createCOFFAsmParser());
685 break;
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000686 case MCObjectFileInfo::IsMachO:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000687 PlatformParser.reset(createDarwinAsmParser());
688 IsDarwin = true;
689 break;
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000690 case MCObjectFileInfo::IsELF:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000691 PlatformParser.reset(createELFAsmParser());
692 break;
Dan Gohman18eafb62017-02-22 01:23:18 +0000693 case MCObjectFileInfo::IsWasm:
Sam Cleggf009da22018-04-19 22:00:53 +0000694 // TODO: WASM will need its own MCAsmParserExtension implementation, but
695 // for now we can re-use the ELF one, since the directives can be the
696 // same for now, and this makes the -triple=wasm32-unknown-unknown-wasm
697 // path work.
698 PlatformParser.reset(createELFAsmParser());
Dan Gohman18eafb62017-02-22 01:23:18 +0000699 break;
Daniel Dunbarc5011082010-07-12 18:12:02 +0000700 }
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000701
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000702 PlatformParser->Initialize(*this);
Eli Bendersky17233942013-01-15 22:59:42 +0000703 initializeDirectiveKindMap();
Toma Tabacu217116e2015-04-27 10:50:29 +0000704
705 NumOfMacroInstantiations = 0;
Chris Lattner351a7ef2009-09-27 21:16:52 +0000706}
707
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000708AsmParser::~AsmParser() {
Saleem Abdulrasool6eae1e62014-05-21 17:53:18 +0000709 assert((HadError || ActiveMacros.empty()) &&
710 "Unexpected active macro instantiation!");
Sanne Wouda29338752017-02-08 14:48:05 +0000711
712 // Restore the saved diagnostics handler and context for use during
713 // finalization.
714 SrcMgr.setDiagHandler(SavedDiagHandler, SavedDiagContext);
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000715}
716
Jim Grosbach4b905842013-09-20 23:08:21 +0000717void AsmParser::printMacroInstantiations() {
Daniel Dunbar43235712010-07-18 18:54:11 +0000718 // Print the active macro instantiation stack.
Jim Grosbach4b905842013-09-20 23:08:21 +0000719 for (std::vector<MacroInstantiation *>::const_reverse_iterator
720 it = ActiveMacros.rbegin(),
721 ie = ActiveMacros.rend();
722 it != ie; ++it)
723 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
Chris Lattner03b80a42011-10-16 05:43:57 +0000724 "while in macro instantiation");
Daniel Dunbar43235712010-07-18 18:54:11 +0000725}
726
Nirav Dave2364748a2016-09-16 18:30:20 +0000727void AsmParser::Note(SMLoc L, const Twine &Msg, SMRange Range) {
728 printPendingErrors();
729 printMessage(L, SourceMgr::DK_Note, Msg, Range);
Saleem Abdulrasool69c7caf2014-01-07 02:28:31 +0000730 printMacroInstantiations();
731}
732
Nirav Dave2364748a2016-09-16 18:30:20 +0000733bool AsmParser::Warning(SMLoc L, const Twine &Msg, SMRange Range) {
Colin LeMahieufe36f832015-07-27 22:39:14 +0000734 if(getTargetParser().getTargetOptions().MCNoWarn)
735 return false;
Joerg Sonnenberger29815912014-08-26 18:39:50 +0000736 if (getTargetParser().getTargetOptions().MCFatalWarnings)
Nirav Dave2364748a2016-09-16 18:30:20 +0000737 return Error(L, Msg, Range);
738 printMessage(L, SourceMgr::DK_Warning, Msg, Range);
Jim Grosbach4b905842013-09-20 23:08:21 +0000739 printMacroInstantiations();
Joerg Sonnenberger74ba2622011-05-19 18:00:13 +0000740 return false;
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +0000741}
742
Nirav Dave2364748a2016-09-16 18:30:20 +0000743bool AsmParser::printError(SMLoc L, const Twine &Msg, SMRange Range) {
Daniel Dunbar43325c42010-09-09 22:42:56 +0000744 HadError = true;
Nirav Dave2364748a2016-09-16 18:30:20 +0000745 printMessage(L, SourceMgr::DK_Error, Msg, Range);
Jim Grosbach4b905842013-09-20 23:08:21 +0000746 printMacroInstantiations();
Chris Lattner2adc9e72009-06-21 21:22:11 +0000747 return true;
748}
749
Jim Grosbach4b905842013-09-20 23:08:21 +0000750bool AsmParser::enterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergeraf5f23e2011-06-01 13:10:15 +0000751 std::string IncludedFile;
Alp Tokera55b95b2014-07-06 10:33:31 +0000752 unsigned NewBuf =
753 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
754 if (!NewBuf)
Sean Callanan7a77eae2010-01-21 00:19:58 +0000755 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +0000756
Sean Callanan7a77eae2010-01-21 00:19:58 +0000757 CurBuffer = NewBuf;
Rafael Espindola8026bd02014-07-06 14:17:29 +0000758 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Sean Callanan7a77eae2010-01-21 00:19:58 +0000759 return false;
760}
Daniel Dunbar43235712010-07-18 18:54:11 +0000761
Sylvestre Ledru149e2812013-05-14 23:36:24 +0000762/// Process the specified .incbin file by searching for it in the include paths
Benjamin Kramerbde91762012-06-02 10:20:22 +0000763/// then just emitting the byte contents of the file to the streamer. This
Kevin Enderby109f25c2011-12-14 21:47:48 +0000764/// returns true on failure.
Petr Hosek2f4ac442016-09-23 00:41:06 +0000765bool AsmParser::processIncbinFile(const std::string &Filename, int64_t Skip,
766 const MCExpr *Count, SMLoc Loc) {
Kevin Enderby109f25c2011-12-14 21:47:48 +0000767 std::string IncludedFile;
Alp Tokera55b95b2014-07-06 10:33:31 +0000768 unsigned NewBuf =
769 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
770 if (!NewBuf)
Kevin Enderby109f25c2011-12-14 21:47:48 +0000771 return true;
772
Kevin Enderbyad41ab52011-12-14 22:34:45 +0000773 // Pick up the bytes from the file and emit them.
Petr Hosek2f4ac442016-09-23 00:41:06 +0000774 StringRef Bytes = SrcMgr.getMemoryBuffer(NewBuf)->getBuffer();
775 Bytes = Bytes.drop_front(Skip);
776 if (Count) {
777 int64_t Res;
Nirav Dave6c0665e2018-04-30 19:22:40 +0000778 if (!Count->evaluateAsAbsolute(Res, getStreamer().getAssemblerPtr()))
Petr Hosek2f4ac442016-09-23 00:41:06 +0000779 return Error(Loc, "expected absolute expression");
780 if (Res < 0)
781 return Warning(Loc, "negative count has no effect");
782 Bytes = Bytes.take_front(Res);
783 }
784 getStreamer().EmitBytes(Bytes);
Kevin Enderby109f25c2011-12-14 21:47:48 +0000785 return false;
786}
787
Alp Tokera55b95b2014-07-06 10:33:31 +0000788void AsmParser::jumpToLoc(SMLoc Loc, unsigned InBuffer) {
789 CurBuffer = InBuffer ? InBuffer : SrcMgr.FindBufferContainingLoc(Loc);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000790 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(),
791 Loc.getPointer());
Daniel Dunbar43235712010-07-18 18:54:11 +0000792}
793
Sean Callanan7a77eae2010-01-21 00:19:58 +0000794const AsmToken &AsmParser::Lex() {
Nirav Dave1180e6892016-06-02 17:15:05 +0000795 if (Lexer.getTok().is(AsmToken::Error))
796 Error(Lexer.getErrLoc(), Lexer.getErr());
797
Nirav Dave53a72f42016-07-11 12:42:14 +0000798 // if it's a end of statement with a comment in it
799 if (getTok().is(AsmToken::EndOfStatement)) {
800 // if this is a line comment output it.
Nirav Dave670109d2017-06-09 14:04:03 +0000801 if (!getTok().getString().empty() && getTok().getString().front() != '\n' &&
Nirav Dave53a72f42016-07-11 12:42:14 +0000802 getTok().getString().front() != '\r' && MAI.preserveAsmComments())
803 Out.addExplicitComment(Twine(getTok().getString()));
804 }
805
Sean Callanan7a77eae2010-01-21 00:19:58 +0000806 const AsmToken *tok = &Lexer.Lex();
Nirav Dave53a72f42016-07-11 12:42:14 +0000807
808 // Parse comments here to be deferred until end of next statement.
Nirav Davefd910412016-06-17 16:06:17 +0000809 while (tok->is(AsmToken::Comment)) {
Nirav Dave53a72f42016-07-11 12:42:14 +0000810 if (MAI.preserveAsmComments())
811 Out.addExplicitComment(Twine(tok->getString()));
Nirav Davefd910412016-06-17 16:06:17 +0000812 tok = &Lexer.Lex();
813 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000814
Sean Callanan7a77eae2010-01-21 00:19:58 +0000815 if (tok->is(AsmToken::Eof)) {
816 // If this is the end of an included file, pop the parent file off the
817 // include stack.
818 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
819 if (ParentIncludeLoc != SMLoc()) {
Jim Grosbach4b905842013-09-20 23:08:21 +0000820 jumpToLoc(ParentIncludeLoc);
Nirav Davefd910412016-06-17 16:06:17 +0000821 return Lex();
Sean Callanan7a77eae2010-01-21 00:19:58 +0000822 }
823 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000824
Sean Callanan7a77eae2010-01-21 00:19:58 +0000825 return *tok;
Sean Callanan686ed8d2010-01-19 20:22:31 +0000826}
827
Paul Robinson938d9a02018-03-22 15:48:01 +0000828bool AsmParser::enabledGenDwarfForAssembly() {
829 // Check whether the user specified -g.
830 if (!getContext().getGenDwarfForAssembly())
831 return false;
832 // If we haven't encountered any .file directives (which would imply that
833 // the assembler source was produced with debug info already) then emit one
834 // describing the assembler source file itself.
835 if (getContext().getGenDwarfFileNumber() == 0)
836 getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective(
837 0, StringRef(), getContext().getMainFileName()));
838 return true;
839}
840
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000841bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar322fec62010-03-13 02:20:57 +0000842 // Create the initial section, if requested.
Daniel Dunbar322fec62010-03-13 02:20:57 +0000843 if (!NoInitialTextSection)
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000844 Out.InitSections(false);
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000845
Chris Lattner36e02122009-06-21 20:54:55 +0000846 // Prime the lexer.
Sean Callanan686ed8d2010-01-19 20:22:31 +0000847 Lex();
Daniel Dunbar43325c42010-09-09 22:42:56 +0000848
849 HadError = false;
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000850 AsmCond StartingCondState = TheCondState;
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +0000851 SmallVector<AsmRewrite, 4> AsmStrRewrites;
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000852
Kevin Enderby6469fc22011-11-01 22:27:22 +0000853 // If we are generating dwarf for assembly source files save the initial text
Paul Robinson938d9a02018-03-22 15:48:01 +0000854 // section. (Don't use enabledGenDwarfForAssembly() here, as we aren't
855 // emitting any actual debug info yet and haven't had a chance to parse any
856 // embedded .file directives.)
Kevin Enderby6469fc22011-11-01 22:27:22 +0000857 if (getContext().getGenDwarfForAssembly()) {
Eric Christopher445c9522016-10-14 05:47:37 +0000858 MCSection *Sec = getStreamer().getCurrentSectionOnly();
Rafael Espindola2f9bdd82015-05-27 20:52:32 +0000859 if (!Sec->getBeginSymbol()) {
860 MCSymbol *SectionStartSym = getContext().createTempSymbol();
861 getStreamer().EmitLabel(SectionStartSym);
862 Sec->setBeginSymbol(SectionStartSym);
863 }
Rafael Espindolae0746792015-05-21 16:52:32 +0000864 bool InsertResult = getContext().addGenDwarfSection(Sec);
865 assert(InsertResult && ".text section should not have debug info yet");
Rafael Espindolafa160c72015-05-21 17:09:22 +0000866 (void)InsertResult;
Kevin Enderby6469fc22011-11-01 22:27:22 +0000867 }
868
Chris Lattner73f36112009-07-02 21:53:43 +0000869 // While we have input, parse each statement.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000870 while (Lexer.isNot(AsmToken::Eof)) {
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +0000871 ParseStatementInfo Info(&AsmStrRewrites);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +0000872 if (!parseStatement(Info, nullptr))
Jim Grosbach4b905842013-09-20 23:08:21 +0000873 continue;
Michael J. Spencer530ce852010-10-09 11:00:50 +0000874
Nirav Dave2364748a2016-09-16 18:30:20 +0000875 // If we have a Lexer Error we are on an Error Token. Load in Lexer Error
876 // for printing ErrMsg via Lex() only if no (presumably better) parser error
877 // exists.
878 if (!hasPendingError() && Lexer.getTok().is(AsmToken::Error)) {
Nirav Dave1180e6892016-06-02 17:15:05 +0000879 Lex();
880 }
881
Nirav Dave2364748a2016-09-16 18:30:20 +0000882 // parseStatement returned true so may need to emit an error.
883 printPendingErrors();
884
885 // Skipping to the next line if needed.
886 if (!getLexer().isAtStartOfStatement())
887 eatToEndOfStatement();
Chris Lattner73f36112009-07-02 21:53:43 +0000888 }
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000889
Nirav Dave2364748a2016-09-16 18:30:20 +0000890 // All errors should have been emitted.
891 assert(!hasPendingError() && "unexpected error from parseStatement");
892
Oliver Stannard21718282016-07-26 14:19:47 +0000893 getTargetParser().flushPendingInstructions(getStreamer());
894
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000895 if (TheCondState.TheCond != StartingCondState.TheCond ||
896 TheCondState.Ignore != StartingCondState.Ignore)
Nirav Dave2364748a2016-09-16 18:30:20 +0000897 printError(getTok().getLoc(), "unmatched .ifs or .elses");
Kevin Enderbye5930f12010-07-28 20:55:35 +0000898 // Check to see there are no empty DwarfFile slots.
David Blaikie8bf66c42014-04-01 07:35:52 +0000899 const auto &LineTables = getContext().getMCDwarfLineTables();
900 if (!LineTables.empty()) {
901 unsigned Index = 0;
902 for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) {
903 if (File.Name.empty() && Index != 0)
Nirav Dave2364748a2016-09-16 18:30:20 +0000904 printError(getTok().getLoc(), "unassigned file number: " +
905 Twine(Index) +
906 " for .file directives");
David Blaikie8bf66c42014-04-01 07:35:52 +0000907 ++Index;
908 }
Kevin Enderbye5930f12010-07-28 20:55:35 +0000909 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000910
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000911 // Check to see that all assembler local symbols were actually defined.
912 // Targets that don't do subsections via symbols may not want this, though,
913 // so conservatively exclude them. Only do this if we're finalizing, though,
914 // as otherwise we won't necessarilly have seen everything yet.
Tim Northover6b3169b2016-04-11 19:50:46 +0000915 if (!NoFinalize) {
916 if (MAI.hasSubsectionsViaSymbols()) {
917 for (const auto &TableEntry : getContext().getSymbols()) {
918 MCSymbol *Sym = TableEntry.getValue();
919 // Variable symbols may not be marked as defined, so check those
920 // explicitly. If we know it's a variable, we have a definition for
921 // the purposes of this check.
922 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
923 // FIXME: We would really like to refer back to where the symbol was
924 // first referenced for a source location. We need to add something
925 // to track that. Currently, we just point to the end of the file.
Nirav Dave2364748a2016-09-16 18:30:20 +0000926 printError(getTok().getLoc(), "assembler local symbol '" +
927 Sym->getName() + "' not defined");
Tim Northover6b3169b2016-04-11 19:50:46 +0000928 }
929 }
930
931 // Temporary symbols like the ones for directional jumps don't go in the
932 // symbol table. They also need to be diagnosed in all (final) cases.
Tim Northoverc0bef992016-04-13 19:46:54 +0000933 for (std::tuple<SMLoc, CppHashInfoTy, MCSymbol *> &LocSym : DirLabels) {
934 if (std::get<2>(LocSym)->isUndefined()) {
935 // Reset the state of any "# line file" directives we've seen to the
936 // context as it was at the diagnostic site.
937 CppHashInfo = std::get<1>(LocSym);
Nirav Dave2364748a2016-09-16 18:30:20 +0000938 printError(std::get<0>(LocSym), "directional label undefined");
Tim Northoverc0bef992016-04-13 19:46:54 +0000939 }
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000940 }
941 }
942
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000943 // Finalize the output stream if there are no errors and if the client wants
944 // us to.
Jack Carter13d5f752013-10-04 22:52:31 +0000945 if (!HadError && !NoFinalize)
Daniel Dunbar9df5f332009-08-21 08:34:18 +0000946 Out.Finish();
947
Oliver Stannard07b43d32015-11-17 09:58:07 +0000948 return HadError || getContext().hadError();
Chris Lattner36e02122009-06-21 20:54:55 +0000949}
950
Nirav Davef43cc9f2016-10-10 15:24:54 +0000951bool AsmParser::checkForValidSection() {
Eric Christopher445c9522016-10-14 05:47:37 +0000952 if (!ParsingInlineAsm && !getStreamer().getCurrentSectionOnly()) {
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000953 Out.InitSections(false);
Nirav Davef43cc9f2016-10-10 15:24:54 +0000954 return Error(getTok().getLoc(),
955 "expected section directive before assembly directive");
Daniel Dunbare5444a82010-09-09 22:42:59 +0000956 }
Nirav Davef43cc9f2016-10-10 15:24:54 +0000957 return false;
Daniel Dunbare5444a82010-09-09 22:42:59 +0000958}
959
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000960/// Throw away the rest of the line for testing purposes.
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000961void AsmParser::eatToEndOfStatement() {
Jim Grosbach4b905842013-09-20 23:08:21 +0000962 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Nirav Dave1180e6892016-06-02 17:15:05 +0000963 Lexer.Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +0000964
Chris Lattnere5074c42009-06-22 01:29:09 +0000965 // Eat EOL.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000966 if (Lexer.is(AsmToken::EndOfStatement))
Nirav Dave1180e6892016-06-02 17:15:05 +0000967 Lexer.Lex();
Chris Lattnere5074c42009-06-22 01:29:09 +0000968}
969
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000970StringRef AsmParser::parseStringToEndOfStatement() {
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000971 const char *Start = getTok().getLoc().getPointer();
972
Jim Grosbach4b905842013-09-20 23:08:21 +0000973 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Nirav Davefd910412016-06-17 16:06:17 +0000974 Lexer.Lex();
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000975
976 const char *End = getTok().getLoc().getPointer();
977 return StringRef(Start, End - Start);
978}
Chris Lattner78db3622009-06-22 05:51:26 +0000979
Jim Grosbach4b905842013-09-20 23:08:21 +0000980StringRef AsmParser::parseStringToComma() {
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000981 const char *Start = getTok().getLoc().getPointer();
982
983 while (Lexer.isNot(AsmToken::EndOfStatement) &&
Jim Grosbach4b905842013-09-20 23:08:21 +0000984 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
Nirav Davefd910412016-06-17 16:06:17 +0000985 Lexer.Lex();
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000986
987 const char *End = getTok().getLoc().getPointer();
988 return StringRef(Start, End - Start);
989}
990
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000991/// Parse a paren expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +0000992/// NOTE: This assumes the leading '(' has already been consumed.
993///
994/// parenexpr ::= expr)
995///
Jim Grosbach4b905842013-09-20 23:08:21 +0000996bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
997 if (parseExpression(Res))
998 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000999 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner7fdbce72009-06-22 06:32:03 +00001000 return TokError("expected ')' in parentheses expression");
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001001 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001002 Lex();
Chris Lattner7fdbce72009-06-22 06:32:03 +00001003 return false;
1004}
Chris Lattner78db3622009-06-22 05:51:26 +00001005
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001006/// Parse a bracket expression and return it.
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +00001007/// NOTE: This assumes the leading '[' has already been consumed.
1008///
1009/// bracketexpr ::= expr]
1010///
Jim Grosbach4b905842013-09-20 23:08:21 +00001011bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
1012 if (parseExpression(Res))
1013 return true;
Nirav Davea645433c2016-07-18 15:24:03 +00001014 EndLoc = getTok().getEndLoc();
1015 if (parseToken(AsmToken::RBrac, "expected ']' in brackets expression"))
1016 return true;
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +00001017 return false;
1018}
1019
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001020/// Parse a primary expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +00001021/// primaryexpr ::= (parenexpr
1022/// primaryexpr ::= symbol
1023/// primaryexpr ::= number
Chris Lattner6b55cb92010-04-14 04:40:28 +00001024/// primaryexpr ::= '.'
Chris Lattner7fdbce72009-06-22 06:32:03 +00001025/// primaryexpr ::= ~,+,- primaryexpr
Jim Grosbach4b905842013-09-20 23:08:21 +00001026bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Kevin Enderby0017d8a2013-01-22 21:09:20 +00001027 SMLoc FirstTokenLoc = getLexer().getLoc();
1028 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
1029 switch (FirstTokenKind) {
Chris Lattner78db3622009-06-22 05:51:26 +00001030 default:
1031 return TokError("unknown token in expression");
Eric Christopher104af062011-04-12 00:03:13 +00001032 // If we have an error assume that we've already handled it.
1033 case AsmToken::Error:
1034 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001035 case AsmToken::Exclaim:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001036 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001037 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001038 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +00001039 Res = MCUnaryExpr::createLNot(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001040 return false;
Daniel Dunbar24764322010-08-24 19:13:42 +00001041 case AsmToken::Dollar:
Hans Wennborgce69d772013-10-18 20:46:28 +00001042 case AsmToken::At:
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +00001043 case AsmToken::String:
Daniel Dunbard20cda02009-10-16 01:34:54 +00001044 case AsmToken::Identifier: {
Daniel Dunbar24764322010-08-24 19:13:42 +00001045 StringRef Identifier;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001046 if (parseIdentifier(Identifier)) {
Nirav Daved0463322016-10-12 13:58:07 +00001047 // We may have failed but $ may be a valid token.
1048 if (getTok().is(AsmToken::Dollar)) {
David Majnemer0c58bc62013-09-25 10:47:21 +00001049 if (Lexer.getMAI().getDollarIsPC()) {
Nirav Daved0463322016-10-12 13:58:07 +00001050 Lex();
David Majnemer0c58bc62013-09-25 10:47:21 +00001051 // This is a '$' reference, which references the current PC. Emit a
1052 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +00001053 MCSymbol *Sym = Ctx.createTempSymbol();
David Majnemer0c58bc62013-09-25 10:47:21 +00001054 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +00001055 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None,
Jack Carter721726a2013-10-04 21:26:15 +00001056 getContext());
David Majnemer0c58bc62013-09-25 10:47:21 +00001057 EndLoc = FirstTokenLoc;
1058 return false;
Ted Kremenek297febe2014-03-06 22:13:17 +00001059 }
1060 return Error(FirstTokenLoc, "invalid token in expression");
David Majnemer0c58bc62013-09-25 10:47:21 +00001061 }
Kevin Enderby0017d8a2013-01-22 21:09:20 +00001062 }
David Peixotto8ad70b32013-12-04 22:43:20 +00001063 // Parse symbol variant
1064 std::pair<StringRef, StringRef> Split;
1065 if (!MAI.useParensForSymbolVariant()) {
David Majnemer6a5b8122014-06-19 01:25:43 +00001066 if (FirstTokenKind == AsmToken::String) {
1067 if (Lexer.is(AsmToken::At)) {
Nirav Davefd910412016-06-17 16:06:17 +00001068 Lex(); // eat @
David Majnemer6a5b8122014-06-19 01:25:43 +00001069 SMLoc AtLoc = getLexer().getLoc();
1070 StringRef VName;
1071 if (parseIdentifier(VName))
1072 return Error(AtLoc, "expected symbol variant after '@'");
1073
1074 Split = std::make_pair(Identifier, VName);
1075 }
1076 } else {
1077 Split = Identifier.split('@');
1078 }
David Peixotto8ad70b32013-12-04 22:43:20 +00001079 } else if (Lexer.is(AsmToken::LParen)) {
Nirav Davefd910412016-06-17 16:06:17 +00001080 Lex(); // eat '('.
David Peixotto8ad70b32013-12-04 22:43:20 +00001081 StringRef VName;
1082 parseIdentifier(VName);
Nirav Davea645433c2016-07-18 15:24:03 +00001083 // eat ')'.
1084 if (parseToken(AsmToken::RParen,
1085 "unexpected token in variant, expected ')'"))
1086 return true;
David Peixotto8ad70b32013-12-04 22:43:20 +00001087 Split = std::make_pair(Identifier, VName);
1088 }
Daniel Dunbar24764322010-08-24 19:13:42 +00001089
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001090 EndLoc = SMLoc::getFromPointer(Identifier.end());
1091
Daniel Dunbard20cda02009-10-16 01:34:54 +00001092 // This is a symbol reference.
Hans Wennborgce69d772013-10-18 20:46:28 +00001093 StringRef SymbolName = Identifier;
Weiming Zhaocf26d562016-12-01 18:00:36 +00001094 if (SymbolName.empty())
1095 return true;
1096
Hans Wennborgce69d772013-10-18 20:46:28 +00001097 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Hans Wennborg69918bc2013-10-17 01:13:02 +00001098
Hans Wennborg7ddcdc82013-10-18 02:14:40 +00001099 // Lookup the symbol variant if used.
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00001100 if (!Split.second.empty()) {
Hans Wennborg7ddcdc82013-10-18 02:14:40 +00001101 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Hans Wennborgce69d772013-10-18 20:46:28 +00001102 if (Variant != MCSymbolRefExpr::VK_Invalid) {
1103 SymbolName = Split.first;
David Peixotto8ad70b32013-12-04 22:43:20 +00001104 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
Hans Wennborgce69d772013-10-18 20:46:28 +00001105 Variant = MCSymbolRefExpr::VK_None;
1106 } else {
Saleem Abdulrasoola25e1e42014-01-26 22:29:43 +00001107 return Error(SMLoc::getFromPointer(Split.second.begin()),
1108 "invalid variant '" + Split.second + "'");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001109 }
1110 }
Daniel Dunbar55992562010-03-15 23:51:06 +00001111
Jim Grosbach6f482002015-05-18 18:43:14 +00001112 MCSymbol *Sym = getContext().getOrCreateSymbol(SymbolName);
Hans Wennborgce69d772013-10-18 20:46:28 +00001113
Daniel Dunbard20cda02009-10-16 01:34:54 +00001114 // If this is an absolute variable reference, substitute it now to preserve
1115 // semantics in the face of reassignment.
Nirav Dave05b58912018-06-05 15:13:39 +00001116 if (Sym->isVariable()) {
1117 auto V = Sym->getVariableValue(/*SetUsed*/ false);
1118 bool DoInline = isa<MCConstantExpr>(V);
1119 if (auto TV = dyn_cast<MCTargetExpr>(V))
1120 DoInline = TV->inlineAssignedExpr();
1121 if (DoInline) {
1122 if (Variant)
1123 return Error(EndLoc, "unexpected modifier on variable reference");
1124 Res = Sym->getVariableValue(/*SetUsed*/ false);
1125 return false;
1126 }
Daniel Dunbard20cda02009-10-16 01:34:54 +00001127 }
1128
1129 // Otherwise create a symbol ref.
Chad Rosier9245e122017-01-19 20:06:32 +00001130 Res = MCSymbolRefExpr::create(Sym, Variant, getContext(), FirstTokenLoc);
Chris Lattner78db3622009-06-22 05:51:26 +00001131 return false;
Daniel Dunbard20cda02009-10-16 01:34:54 +00001132 }
David Woodhousef42a6662014-02-01 16:20:54 +00001133 case AsmToken::BigNum:
1134 return TokError("literal value out of range for directive");
Kevin Enderby0510b482010-05-17 23:08:19 +00001135 case AsmToken::Integer: {
1136 SMLoc Loc = getTok().getLoc();
1137 int64_t IntVal = getTok().getIntVal();
Jim Grosbach13760bd2015-05-30 01:25:56 +00001138 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001139 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001140 Lex(); // Eat token.
Kevin Enderby0510b482010-05-17 23:08:19 +00001141 // Look for 'b' or 'f' following an Integer as a directional label
1142 if (Lexer.getKind() == AsmToken::Identifier) {
1143 StringRef IDVal = getTok().getString();
Ulrich Weigandd4120982013-06-20 16:24:17 +00001144 // Lookup the symbol variant if used.
1145 std::pair<StringRef, StringRef> Split = IDVal.split('@');
1146 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
1147 if (Split.first.size() != IDVal.size()) {
1148 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Arnaud A. de Grandmaisonc97727a2014-03-21 21:54:46 +00001149 if (Variant == MCSymbolRefExpr::VK_Invalid)
Ulrich Weigandd4120982013-06-20 16:24:17 +00001150 return TokError("invalid variant '" + Split.second + "'");
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001151 IDVal = Split.first;
Ulrich Weigandd4120982013-06-20 16:24:17 +00001152 }
Jim Grosbach4b905842013-09-20 23:08:21 +00001153 if (IDVal == "f" || IDVal == "b") {
1154 MCSymbol *Sym =
Jim Grosbach6f482002015-05-18 18:43:14 +00001155 Ctx.getDirectionalLocalSymbol(IntVal, IDVal == "b");
Jim Grosbach13760bd2015-05-30 01:25:56 +00001156 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00001157 if (IDVal == "b" && Sym->isUndefined())
Tim Northover6b3169b2016-04-11 19:50:46 +00001158 return Error(Loc, "directional label undefined");
Tim Northoverc0bef992016-04-13 19:46:54 +00001159 DirLabels.push_back(std::make_tuple(Loc, CppHashInfo, Sym));
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001160 EndLoc = Lexer.getTok().getEndLoc();
Kevin Enderby0510b482010-05-17 23:08:19 +00001161 Lex(); // Eat identifier.
1162 }
1163 }
Chris Lattner78db3622009-06-22 05:51:26 +00001164 return false;
Kevin Enderby0510b482010-05-17 23:08:19 +00001165 }
Bill Wendlingcdbf17b2011-01-25 21:26:41 +00001166 case AsmToken::Real: {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001167 APFloat RealVal(APFloat::IEEEdouble(), getTok().getString());
Bob Wilson813bdf62011-02-03 23:17:47 +00001168 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Jim Grosbach13760bd2015-05-30 01:25:56 +00001169 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001170 EndLoc = Lexer.getTok().getEndLoc();
Bill Wendlingcdbf17b2011-01-25 21:26:41 +00001171 Lex(); // Eat token.
1172 return false;
1173 }
Chris Lattner6b55cb92010-04-14 04:40:28 +00001174 case AsmToken::Dot: {
1175 // This is a '.' reference, which references the current PC. Emit a
1176 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +00001177 MCSymbol *Sym = Ctx.createTempSymbol();
Chris Lattner6b55cb92010-04-14 04:40:28 +00001178 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +00001179 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001180 EndLoc = Lexer.getTok().getEndLoc();
Chris Lattner6b55cb92010-04-14 04:40:28 +00001181 Lex(); // Eat identifier.
1182 return false;
1183 }
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001184 case AsmToken::LParen:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001185 Lex(); // Eat the '('.
Jim Grosbach4b905842013-09-20 23:08:21 +00001186 return parseParenExpr(Res, EndLoc);
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +00001187 case AsmToken::LBrac:
1188 if (!PlatformParser->HasBracketExpressions())
1189 return TokError("brackets expression not supported on this target");
1190 Lex(); // Eat the '['.
Jim Grosbach4b905842013-09-20 23:08:21 +00001191 return parseBracketExpr(Res, EndLoc);
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001192 case AsmToken::Minus:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001193 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001194 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001195 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +00001196 Res = MCUnaryExpr::createMinus(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001197 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001198 case AsmToken::Plus:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001199 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001200 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001201 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +00001202 Res = MCUnaryExpr::createPlus(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001203 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001204 case AsmToken::Tilde:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001205 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001206 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001207 return true;
Sanne Wouda9dfa6ad2017-03-10 13:08:20 +00001208 Res = MCUnaryExpr::createNot(Res, getContext(), FirstTokenLoc);
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001209 return false;
Daniel Sanders3feeb9c2016-08-08 11:50:25 +00001210 // MIPS unary expression operators. The lexer won't generate these tokens if
1211 // MCAsmInfo::HasMipsExpressions is false for the target.
1212 case AsmToken::PercentCall16:
1213 case AsmToken::PercentCall_Hi:
1214 case AsmToken::PercentCall_Lo:
1215 case AsmToken::PercentDtprel_Hi:
1216 case AsmToken::PercentDtprel_Lo:
1217 case AsmToken::PercentGot:
1218 case AsmToken::PercentGot_Disp:
1219 case AsmToken::PercentGot_Hi:
1220 case AsmToken::PercentGot_Lo:
1221 case AsmToken::PercentGot_Ofst:
1222 case AsmToken::PercentGot_Page:
1223 case AsmToken::PercentGottprel:
1224 case AsmToken::PercentGp_Rel:
1225 case AsmToken::PercentHi:
1226 case AsmToken::PercentHigher:
1227 case AsmToken::PercentHighest:
1228 case AsmToken::PercentLo:
1229 case AsmToken::PercentNeg:
1230 case AsmToken::PercentPcrel_Hi:
1231 case AsmToken::PercentPcrel_Lo:
1232 case AsmToken::PercentTlsgd:
1233 case AsmToken::PercentTlsldm:
1234 case AsmToken::PercentTprel_Hi:
1235 case AsmToken::PercentTprel_Lo:
1236 Lex(); // Eat the operator.
1237 if (Lexer.isNot(AsmToken::LParen))
1238 return TokError("expected '(' after operator");
1239 Lex(); // Eat the operator.
1240 if (parseExpression(Res, EndLoc))
1241 return true;
1242 if (Lexer.isNot(AsmToken::RParen))
1243 return TokError("expected ')'");
1244 Lex(); // Eat the operator.
1245 Res = getTargetParser().createTargetUnaryExpr(Res, FirstTokenKind, Ctx);
1246 return !Res;
Chris Lattner78db3622009-06-22 05:51:26 +00001247 }
1248}
Chris Lattner7fdbce72009-06-22 06:32:03 +00001249
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001250bool AsmParser::parseExpression(const MCExpr *&Res) {
Chris Lattnere17df0b2010-01-15 19:39:23 +00001251 SMLoc EndLoc;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001252 return parseExpression(Res, EndLoc);
Chris Lattner528d00b2010-01-15 19:28:38 +00001253}
1254
Daniel Dunbar55f16672010-09-17 02:47:07 +00001255const MCExpr *
Jim Grosbach4b905842013-09-20 23:08:21 +00001256AsmParser::applyModifierToExpr(const MCExpr *E,
Daniel Dunbar55f16672010-09-17 02:47:07 +00001257 MCSymbolRefExpr::VariantKind Variant) {
Joerg Sonnenbergerb822af42013-08-27 20:23:19 +00001258 // Ask the target implementation about this expression first.
1259 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
1260 if (NewE)
1261 return NewE;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001262 // Recurse over the given expression, rebuilding it to apply the given variant
1263 // if there is exactly one symbol.
1264 switch (E->getKind()) {
1265 case MCExpr::Target:
1266 case MCExpr::Constant:
Craig Topper353eda42014-04-24 06:44:33 +00001267 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001268
1269 case MCExpr::SymbolRef: {
1270 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
1271
1272 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001273 TokError("invalid variant on expression '" + getTok().getIdentifier() +
1274 "' (already modified)");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001275 return E;
1276 }
1277
Jim Grosbach13760bd2015-05-30 01:25:56 +00001278 return MCSymbolRefExpr::create(&SRE->getSymbol(), Variant, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001279 }
1280
1281 case MCExpr::Unary: {
1282 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +00001283 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001284 if (!Sub)
Craig Topper353eda42014-04-24 06:44:33 +00001285 return nullptr;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001286 return MCUnaryExpr::create(UE->getOpcode(), Sub, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001287 }
1288
1289 case MCExpr::Binary: {
1290 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +00001291 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
1292 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001293
1294 if (!LHS && !RHS)
Craig Topper353eda42014-04-24 06:44:33 +00001295 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001296
Jim Grosbach4b905842013-09-20 23:08:21 +00001297 if (!LHS)
1298 LHS = BE->getLHS();
1299 if (!RHS)
1300 RHS = BE->getRHS();
Daniel Dunbar55f16672010-09-17 02:47:07 +00001301
Jim Grosbach13760bd2015-05-30 01:25:56 +00001302 return MCBinaryExpr::create(BE->getOpcode(), LHS, RHS, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001303 }
1304 }
Daniel Dunbarbaad46c2010-09-17 16:34:24 +00001305
Craig Toppera2886c22012-02-07 05:05:23 +00001306 llvm_unreachable("Invalid expression kind!");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001307}
1308
Michael Zuckerman763e60e2017-05-04 10:37:00 +00001309/// This function checks if the next token is <string> type or arithmetic.
1310/// string that begin with character '<' must end with character '>'.
1311/// otherwise it is arithmetics.
1312/// If the function returns a 'true' value,
1313/// the End argument will be filled with the last location pointed to the '>'
1314/// character.
1315
Sam Cleggf009da22018-04-19 22:00:53 +00001316/// There is a gap between the AltMacro's documentation and the single quote implementation.
Michael Zuckerman763e60e2017-05-04 10:37:00 +00001317/// GCC does not fully support this feature and so we will not support it.
1318/// TODO: Adding single quote as a string.
1319bool AsmParser::isAltmacroString(SMLoc &StrLoc, SMLoc &EndLoc) {
1320 assert((StrLoc.getPointer() != NULL) &&
1321 "Argument to the function cannot be a NULL value");
1322 const char *CharPtr = StrLoc.getPointer();
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00001323 while ((*CharPtr != '>') && (*CharPtr != '\n') && (*CharPtr != '\r') &&
1324 (*CharPtr != '\0')) {
1325 if (*CharPtr == '!')
1326 CharPtr++;
Michael Zuckerman763e60e2017-05-04 10:37:00 +00001327 CharPtr++;
1328 }
1329 if (*CharPtr == '>') {
1330 EndLoc = StrLoc.getFromPointer(CharPtr + 1);
1331 return true;
1332 }
1333 return false;
1334}
1335
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001336/// creating a string without the escape characters '!'.
Michael Zuckerman1f1a9122017-05-10 13:08:11 +00001337void AsmParser::altMacroString(StringRef AltMacroStr,std::string &Res) {
Michael Zuckermanff298792017-05-10 14:00:57 +00001338 for (size_t Pos = 0; Pos < AltMacroStr.size(); Pos++) {
Michael Zuckerman1f1a9122017-05-10 13:08:11 +00001339 if (AltMacroStr[Pos] == '!')
1340 Pos++;
1341 Res += AltMacroStr[Pos];
1342 }
1343}
1344
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001345/// Parse an expression and return it.
Michael J. Spencer530ce852010-10-09 11:00:50 +00001346///
Jim Grosbachbd164242011-08-20 16:24:13 +00001347/// expr ::= expr &&,|| expr -> lowest.
1348/// expr ::= expr |,^,&,! expr
1349/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1350/// expr ::= expr <<,>> expr
1351/// expr ::= expr +,- expr
1352/// expr ::= expr *,/,% expr -> highest.
Chris Lattner7fdbce72009-06-22 06:32:03 +00001353/// expr ::= primaryexpr
1354///
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001355bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001356 // Parse the expression.
Craig Topper353eda42014-04-24 06:44:33 +00001357 Res = nullptr;
Jim Grosbach4b905842013-09-20 23:08:21 +00001358 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001359 return true;
1360
Daniel Dunbar55f16672010-09-17 02:47:07 +00001361 // As a special case, we support 'a op b @ modifier' by rewriting the
1362 // expression to include the modifier. This is inefficient, but in general we
1363 // expect users to use 'a@modifier op b'.
1364 if (Lexer.getKind() == AsmToken::At) {
1365 Lex();
1366
1367 if (Lexer.isNot(AsmToken::Identifier))
1368 return TokError("unexpected symbol modifier following '@'");
1369
1370 MCSymbolRefExpr::VariantKind Variant =
Jim Grosbach4b905842013-09-20 23:08:21 +00001371 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001372 if (Variant == MCSymbolRefExpr::VK_Invalid)
1373 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1374
Jim Grosbach4b905842013-09-20 23:08:21 +00001375 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001376 if (!ModifiedRes) {
1377 return TokError("invalid modifier '" + getTok().getIdentifier() +
1378 "' (no symbols present)");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001379 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001380
Daniel Dunbar55f16672010-09-17 02:47:07 +00001381 Res = ModifiedRes;
1382 Lex();
1383 }
1384
Nirav Dave6c0665e2018-04-30 19:22:40 +00001385 // Try to constant fold it up front, if possible. Do not exploit
1386 // assembler here.
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001387 int64_t Value;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001388 if (Res->evaluateAsAbsolute(Value))
1389 Res = MCConstantExpr::create(Value, getContext());
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001390
1391 return false;
Chris Lattner7fdbce72009-06-22 06:32:03 +00001392}
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001393
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001394bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Craig Topper353eda42014-04-24 06:44:33 +00001395 Res = nullptr;
Jim Grosbach4b905842013-09-20 23:08:21 +00001396 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
Daniel Dunbar7c82d562009-08-31 08:08:17 +00001397}
1398
Toma Tabacu7bc44dc2015-06-25 09:52:02 +00001399bool AsmParser::parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
1400 SMLoc &EndLoc) {
1401 if (parseParenExpr(Res, EndLoc))
1402 return true;
1403
1404 for (; ParenDepth > 0; --ParenDepth) {
1405 if (parseBinOpRHS(1, Res, EndLoc))
1406 return true;
1407
1408 // We don't Lex() the last RParen.
1409 // This is the same behavior as parseParenExpression().
1410 if (ParenDepth - 1 > 0) {
Nirav Davea645433c2016-07-18 15:24:03 +00001411 EndLoc = getTok().getEndLoc();
1412 if (parseToken(AsmToken::RParen,
1413 "expected ')' in parentheses expression"))
1414 return true;
Toma Tabacu7bc44dc2015-06-25 09:52:02 +00001415 }
1416 }
1417 return false;
1418}
1419
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001420bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
Daniel Dunbarf3636452009-08-31 08:07:22 +00001421 const MCExpr *Expr;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001422
Daniel Dunbar75630b32009-06-30 02:10:03 +00001423 SMLoc StartLoc = Lexer.getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001424 if (parseExpression(Expr))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001425 return true;
1426
Nirav Dave6c0665e2018-04-30 19:22:40 +00001427 if (!Expr->evaluateAsAbsolute(Res, getStreamer().getAssemblerPtr()))
Daniel Dunbar75630b32009-06-30 02:10:03 +00001428 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001429
1430 return false;
1431}
1432
David Majnemer0993e0b2015-10-26 03:15:34 +00001433static unsigned getDarwinBinOpPrecedence(AsmToken::TokenKind K,
1434 MCBinaryExpr::Opcode &Kind,
1435 bool ShouldUseLogicalShr) {
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001436 switch (K) {
Daniel Dunbar940cda22009-08-31 08:07:44 +00001437 default:
Jim Grosbach4b905842013-09-20 23:08:21 +00001438 return 0; // not a binop.
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001439
Jim Grosbach4b905842013-09-20 23:08:21 +00001440 // Lowest Precedence: &&, ||
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001441 case AsmToken::AmpAmp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001442 Kind = MCBinaryExpr::LAnd;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001443 return 1;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001444 case AsmToken::PipePipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001445 Kind = MCBinaryExpr::LOr;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001446 return 1;
1447
Jim Grosbach4b905842013-09-20 23:08:21 +00001448 // Low Precedence: |, &, ^
1449 //
1450 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001451 case AsmToken::Pipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001452 Kind = MCBinaryExpr::Or;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001453 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001454 case AsmToken::Caret:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001455 Kind = MCBinaryExpr::Xor;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001456 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001457 case AsmToken::Amp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001458 Kind = MCBinaryExpr::And;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001459 return 2;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001460
Jim Grosbach4b905842013-09-20 23:08:21 +00001461 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001462 case AsmToken::EqualEqual:
1463 Kind = MCBinaryExpr::EQ;
1464 return 3;
1465 case AsmToken::ExclaimEqual:
1466 case AsmToken::LessGreater:
1467 Kind = MCBinaryExpr::NE;
1468 return 3;
1469 case AsmToken::Less:
1470 Kind = MCBinaryExpr::LT;
1471 return 3;
1472 case AsmToken::LessEqual:
1473 Kind = MCBinaryExpr::LTE;
1474 return 3;
1475 case AsmToken::Greater:
1476 Kind = MCBinaryExpr::GT;
1477 return 3;
1478 case AsmToken::GreaterEqual:
1479 Kind = MCBinaryExpr::GTE;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001480 return 3;
1481
Jim Grosbach4b905842013-09-20 23:08:21 +00001482 // Intermediate Precedence: <<, >>
Jim Grosbachbd164242011-08-20 16:24:13 +00001483 case AsmToken::LessLess:
1484 Kind = MCBinaryExpr::Shl;
1485 return 4;
1486 case AsmToken::GreaterGreater:
David Majnemer0993e0b2015-10-26 03:15:34 +00001487 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
Jim Grosbachbd164242011-08-20 16:24:13 +00001488 return 4;
1489
Jim Grosbach4b905842013-09-20 23:08:21 +00001490 // High Intermediate Precedence: +, -
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001491 case AsmToken::Plus:
1492 Kind = MCBinaryExpr::Add;
Jim Grosbachbd164242011-08-20 16:24:13 +00001493 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001494 case AsmToken::Minus:
1495 Kind = MCBinaryExpr::Sub;
Jim Grosbachbd164242011-08-20 16:24:13 +00001496 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001497
Jim Grosbach4b905842013-09-20 23:08:21 +00001498 // Highest Precedence: *, /, %
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001499 case AsmToken::Star:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001500 Kind = MCBinaryExpr::Mul;
Jim Grosbachbd164242011-08-20 16:24:13 +00001501 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001502 case AsmToken::Slash:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001503 Kind = MCBinaryExpr::Div;
Jim Grosbachbd164242011-08-20 16:24:13 +00001504 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001505 case AsmToken::Percent:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001506 Kind = MCBinaryExpr::Mod;
Jim Grosbachbd164242011-08-20 16:24:13 +00001507 return 6;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001508 }
1509}
1510
David Majnemer0993e0b2015-10-26 03:15:34 +00001511static unsigned getGNUBinOpPrecedence(AsmToken::TokenKind K,
1512 MCBinaryExpr::Opcode &Kind,
1513 bool ShouldUseLogicalShr) {
1514 switch (K) {
1515 default:
1516 return 0; // not a binop.
1517
1518 // Lowest Precedence: &&, ||
1519 case AsmToken::AmpAmp:
1520 Kind = MCBinaryExpr::LAnd;
1521 return 2;
1522 case AsmToken::PipePipe:
1523 Kind = MCBinaryExpr::LOr;
1524 return 1;
1525
1526 // Low Precedence: ==, !=, <>, <, <=, >, >=
1527 case AsmToken::EqualEqual:
1528 Kind = MCBinaryExpr::EQ;
1529 return 3;
1530 case AsmToken::ExclaimEqual:
1531 case AsmToken::LessGreater:
1532 Kind = MCBinaryExpr::NE;
1533 return 3;
1534 case AsmToken::Less:
1535 Kind = MCBinaryExpr::LT;
1536 return 3;
1537 case AsmToken::LessEqual:
1538 Kind = MCBinaryExpr::LTE;
1539 return 3;
1540 case AsmToken::Greater:
1541 Kind = MCBinaryExpr::GT;
1542 return 3;
1543 case AsmToken::GreaterEqual:
1544 Kind = MCBinaryExpr::GTE;
1545 return 3;
1546
1547 // Low Intermediate Precedence: +, -
1548 case AsmToken::Plus:
1549 Kind = MCBinaryExpr::Add;
1550 return 4;
1551 case AsmToken::Minus:
1552 Kind = MCBinaryExpr::Sub;
1553 return 4;
1554
1555 // High Intermediate Precedence: |, &, ^
1556 //
1557 // FIXME: gas seems to support '!' as an infix operator?
1558 case AsmToken::Pipe:
1559 Kind = MCBinaryExpr::Or;
1560 return 5;
1561 case AsmToken::Caret:
1562 Kind = MCBinaryExpr::Xor;
1563 return 5;
1564 case AsmToken::Amp:
1565 Kind = MCBinaryExpr::And;
1566 return 5;
1567
1568 // Highest Precedence: *, /, %, <<, >>
1569 case AsmToken::Star:
1570 Kind = MCBinaryExpr::Mul;
1571 return 6;
1572 case AsmToken::Slash:
1573 Kind = MCBinaryExpr::Div;
1574 return 6;
1575 case AsmToken::Percent:
1576 Kind = MCBinaryExpr::Mod;
1577 return 6;
1578 case AsmToken::LessLess:
1579 Kind = MCBinaryExpr::Shl;
1580 return 6;
1581 case AsmToken::GreaterGreater:
1582 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1583 return 6;
1584 }
1585}
1586
1587unsigned AsmParser::getBinOpPrecedence(AsmToken::TokenKind K,
1588 MCBinaryExpr::Opcode &Kind) {
1589 bool ShouldUseLogicalShr = MAI.shouldUseLogicalShr();
1590 return IsDarwin ? getDarwinBinOpPrecedence(K, Kind, ShouldUseLogicalShr)
1591 : getGNUBinOpPrecedence(K, Kind, ShouldUseLogicalShr);
1592}
1593
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001594/// Parse all binary operators with precedence >= 'Precedence'.
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001595/// Res contains the LHS of the expression on input.
Jim Grosbach4b905842013-09-20 23:08:21 +00001596bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
Chris Lattner528d00b2010-01-15 19:28:38 +00001597 SMLoc &EndLoc) {
Chad Rosier9245e122017-01-19 20:06:32 +00001598 SMLoc StartLoc = Lexer.getLoc();
Eugene Zelenko33d7b762016-08-23 17:14:32 +00001599 while (true) {
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001600 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001601 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001602
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001603 // If the next token is lower precedence than we are allowed to eat, return
1604 // successfully with what we ate already.
1605 if (TokPrec < Precedence)
1606 return false;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001607
Sean Callanan686ed8d2010-01-19 20:22:31 +00001608 Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +00001609
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001610 // Eat the next primary expression.
Daniel Dunbarf3636452009-08-31 08:07:22 +00001611 const MCExpr *RHS;
Jim Grosbach4b905842013-09-20 23:08:21 +00001612 if (parsePrimaryExpr(RHS, EndLoc))
1613 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001614
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001615 // If BinOp binds less tightly with RHS than the operator after RHS, let
1616 // the pending operator take RHS as its LHS.
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001617 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001618 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Jim Grosbach4b905842013-09-20 23:08:21 +00001619 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1620 return true;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001621
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001622 // Merge LHS and RHS according to operator.
Chad Rosier9245e122017-01-19 20:06:32 +00001623 Res = MCBinaryExpr::create(Kind, Res, RHS, getContext(), StartLoc);
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001624 }
1625}
1626
Chris Lattner36e02122009-06-21 20:54:55 +00001627/// ParseStatement:
1628/// ::= EndOfStatement
Chris Lattnere5074c42009-06-22 01:29:09 +00001629/// ::= Label* Directive ...Operands... EndOfStatement
1630/// ::= Label* Identifier OperandList* EndOfStatement
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001631bool AsmParser::parseStatement(ParseStatementInfo &Info,
1632 MCAsmParserSemaCallback *SI) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001633 assert(!hasPendingError() && "parseStatement started with pending error");
Nirav Davefd910412016-06-17 16:06:17 +00001634 // Eat initial spaces and comments
1635 while (Lexer.is(AsmToken::Space))
1636 Lex();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001637 if (Lexer.is(AsmToken::EndOfStatement)) {
Nirav Davefd910412016-06-17 16:06:17 +00001638 // if this is a line comment we can drop it safely
Nirav Dave670109d2017-06-09 14:04:03 +00001639 if (getTok().getString().empty() || getTok().getString().front() == '\r' ||
Nirav Davefd910412016-06-17 16:06:17 +00001640 getTok().getString().front() == '\n')
1641 Out.AddBlankLine();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001642 Lex();
Chris Lattner36e02122009-06-21 20:54:55 +00001643 return false;
Chris Lattner36e02122009-06-21 20:54:55 +00001644 }
Nirav Davefd910412016-06-17 16:06:17 +00001645 // Statements always start with an identifier.
Sean Callanan936b0d32010-01-19 21:44:56 +00001646 AsmToken ID = getTok();
Daniel Dunbaree4465c2009-07-28 16:38:40 +00001647 SMLoc IDLoc = ID.getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001648 StringRef IDVal;
Kevin Enderby0510b482010-05-17 23:08:19 +00001649 int64_t LocalLabelVal = -1;
Nirav Davefd910412016-06-17 16:06:17 +00001650 if (Lexer.is(AsmToken::HashDirective))
Jim Grosbach4b905842013-09-20 23:08:21 +00001651 return parseCppHashLineFilenameComment(IDLoc);
Kevin Enderbyfa3c6f12010-12-24 00:12:02 +00001652 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderby0510b482010-05-17 23:08:19 +00001653 if (Lexer.is(AsmToken::Integer)) {
1654 LocalLabelVal = getTok().getIntVal();
1655 if (LocalLabelVal < 0) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001656 if (!TheCondState.Ignore) {
1657 Lex(); // always eat a token
1658 return Error(IDLoc, "unexpected token at start of statement");
1659 }
Kevin Enderby0510b482010-05-17 23:08:19 +00001660 IDVal = "";
Eli Bendersky88024712013-01-16 19:32:36 +00001661 } else {
Kevin Enderby0510b482010-05-17 23:08:19 +00001662 IDVal = getTok().getString();
1663 Lex(); // Consume the integer token to be used as an identifier token.
1664 if (Lexer.getKind() != AsmToken::Colon) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001665 if (!TheCondState.Ignore) {
1666 Lex(); // always eat a token
1667 return Error(IDLoc, "unexpected token at start of statement");
1668 }
Kevin Enderby0510b482010-05-17 23:08:19 +00001669 }
1670 }
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001671 } else if (Lexer.is(AsmToken::Dot)) {
1672 // Treat '.' as a valid identifier in this context.
1673 Lex();
1674 IDVal = ".";
Colin LeMahieu8a0453e2015-11-09 00:31:07 +00001675 } else if (Lexer.is(AsmToken::LCurly)) {
1676 // Treat '{' as a valid identifier in this context.
1677 Lex();
1678 IDVal = "{";
1679
1680 } else if (Lexer.is(AsmToken::RCurly)) {
1681 // Treat '}' as a valid identifier in this context.
1682 Lex();
1683 IDVal = "}";
Yonghong Song06ff6552017-09-12 17:55:23 +00001684 } else if (Lexer.is(AsmToken::Star) &&
1685 getTargetParser().starIsStartOfStatement()) {
1686 // Accept '*' as a valid start of statement.
1687 Lex();
1688 IDVal = "*";
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001689 } else if (parseIdentifier(IDVal)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001690 if (!TheCondState.Ignore) {
1691 Lex(); // always eat a token
1692 return Error(IDLoc, "unexpected token at start of statement");
1693 }
Chris Lattner926885c2010-04-17 18:14:27 +00001694 IDVal = "";
1695 }
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001696
Chris Lattner926885c2010-04-17 18:14:27 +00001697 // Handle conditional assembly here before checking for skipping. We
1698 // have to do this so that .endif isn't skipped in a ".if 0" block for
1699 // example.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001700 StringMap<DirectiveKind>::const_iterator DirKindIt =
Jim Grosbach4b905842013-09-20 23:08:21 +00001701 DirectiveKindMap.find(IDVal);
1702 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1703 ? DK_NO_DIRECTIVE
1704 : DirKindIt->getValue();
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001705 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001706 default:
1707 break;
1708 case DK_IF:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001709 case DK_IFEQ:
1710 case DK_IFGE:
1711 case DK_IFGT:
1712 case DK_IFLE:
1713 case DK_IFLT:
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00001714 case DK_IFNE:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001715 return parseDirectiveIf(IDLoc, DirKind);
Jim Grosbach4b905842013-09-20 23:08:21 +00001716 case DK_IFB:
1717 return parseDirectiveIfb(IDLoc, true);
1718 case DK_IFNB:
1719 return parseDirectiveIfb(IDLoc, false);
1720 case DK_IFC:
1721 return parseDirectiveIfc(IDLoc, true);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00001722 case DK_IFEQS:
Sid Manning51c35602015-03-18 14:20:54 +00001723 return parseDirectiveIfeqs(IDLoc, true);
Jim Grosbach4b905842013-09-20 23:08:21 +00001724 case DK_IFNC:
1725 return parseDirectiveIfc(IDLoc, false);
Sid Manning51c35602015-03-18 14:20:54 +00001726 case DK_IFNES:
1727 return parseDirectiveIfeqs(IDLoc, false);
Jim Grosbach4b905842013-09-20 23:08:21 +00001728 case DK_IFDEF:
1729 return parseDirectiveIfdef(IDLoc, true);
1730 case DK_IFNDEF:
1731 case DK_IFNOTDEF:
1732 return parseDirectiveIfdef(IDLoc, false);
1733 case DK_ELSEIF:
1734 return parseDirectiveElseIf(IDLoc);
1735 case DK_ELSE:
1736 return parseDirectiveElse(IDLoc);
1737 case DK_ENDIF:
1738 return parseDirectiveEndIf(IDLoc);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001739 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001740
Eli Bendersky88024712013-01-16 19:32:36 +00001741 // Ignore the statement if in the middle of inactive conditional
1742 // (e.g. ".if 0").
Chad Rosiereda70b32012-10-20 00:47:08 +00001743 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001744 eatToEndOfStatement();
Chris Lattner926885c2010-04-17 18:14:27 +00001745 return false;
1746 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001747
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001748 // FIXME: Recurse on local labels?
1749
1750 // See what kind of statement we have.
1751 switch (Lexer.getKind()) {
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001752 case AsmToken::Colon: {
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001753 if (!getTargetParser().isLabel(ID))
1754 break;
Nirav Davef43cc9f2016-10-10 15:24:54 +00001755 if (checkForValidSection())
1756 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00001757
Chris Lattner36e02122009-06-21 20:54:55 +00001758 // identifier ':' -> Label.
Sean Callanan686ed8d2010-01-19 20:22:31 +00001759 Lex();
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001760
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001761 // Diagnose attempt to use '.' as a label.
1762 if (IDVal == ".")
1763 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1764
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001765 // Diagnose attempt to use a variable as a label.
1766 //
1767 // FIXME: Diagnostics. Note the location of the definition as a label.
1768 // FIXME: This doesn't diagnose assignment to a symbol which has been
1769 // implicitly marked as external.
Kevin Enderby0510b482010-05-17 23:08:19 +00001770 MCSymbol *Sym;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001771 if (LocalLabelVal == -1) {
1772 if (ParsingInlineAsm && SI) {
Nico Weber67e715f2015-06-19 23:43:47 +00001773 StringRef RewrittenLabel =
1774 SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true);
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00001775 assert(!RewrittenLabel.empty() &&
Nico Weber67e715f2015-06-19 23:43:47 +00001776 "We should have an internal name here.");
Craig Topper7d5b2312015-10-10 05:25:02 +00001777 Info.AsmRewrites->emplace_back(AOK_Label, IDLoc, IDVal.size(),
1778 RewrittenLabel);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001779 IDVal = RewrittenLabel;
1780 }
Jim Grosbach6f482002015-05-18 18:43:14 +00001781 Sym = getContext().getOrCreateSymbol(IDVal);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001782 } else
Jim Grosbach6f482002015-05-18 18:43:14 +00001783 Sym = Ctx.createDirectionalLocalSymbol(LocalLabelVal);
Nirav Dave9263ae32016-08-02 19:17:54 +00001784 // End of Labels should be treated as end of line for lexing
1785 // purposes but that information is not available to the Lexer who
1786 // does not understand Labels. This may cause us to see a Hash
1787 // here instead of a preprocessor line comment.
1788 if (getTok().is(AsmToken::Hash)) {
1789 StringRef CommentStr = parseStringToEndOfStatement();
1790 Lexer.Lex();
1791 Lexer.UnLex(AsmToken(AsmToken::EndOfStatement, CommentStr));
1792 }
1793
Nirav Dave8ea792d2016-07-13 14:03:12 +00001794 // Consume any end of statement token, if present, to avoid spurious
1795 // AddBlankLine calls().
1796 if (getTok().is(AsmToken::EndOfStatement)) {
1797 Lex();
1798 }
1799
Daniel Dunbare73b2672009-08-26 22:13:22 +00001800 // Emit the label.
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +00001801 if (!getTargetParser().isParsingInlineAsm())
Rafael Espindolabe991572017-02-10 15:13:12 +00001802 Out.EmitLabel(Sym, IDLoc);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001803
Kevin Enderbye7739d42011-12-09 18:09:40 +00001804 // If we are generating dwarf for assembly source files then gather the
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001805 // info to make a dwarf label entry for this label if needed.
Paul Robinson938d9a02018-03-22 15:48:01 +00001806 if (enabledGenDwarfForAssembly())
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001807 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1808 IDLoc);
Kevin Enderbye7739d42011-12-09 18:09:40 +00001809
Tim Northover1744d0a2013-10-25 12:49:50 +00001810 getTargetParser().onLabelParsed(Sym);
1811
Eli Friedman0f4871d2012-10-22 23:58:19 +00001812 return false;
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001813 }
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001814
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001815 case AsmToken::Equal:
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001816 if (!getTargetParser().equalIsAsmAssignment())
1817 break;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001818 // identifier '=' ... -> assignment statement
Sean Callanan686ed8d2010-01-19 20:22:31 +00001819 Lex();
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001820
Nirav Dave05b58912018-06-05 15:13:39 +00001821 return parseAssignment(IDVal, true, /*NoDeadStrip*/ false, /*AllowExtendedExpr*/true);
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001822
1823 default: // Normal instruction or directive.
1824 break;
Chris Lattner36e02122009-06-21 20:54:55 +00001825 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001826
1827 // If macros are enabled, check to see if this is a macro instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00001828 if (areMacrosEnabled())
Rafael Espindola22c38a02018-02-14 16:34:27 +00001829 if (const MCAsmMacro *M = getContext().lookupMacro(IDVal)) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001830 return handleMacroEntry(M, IDLoc);
Eli Bendersky38274122013-01-14 23:22:36 +00001831 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001832
Michael J. Spencer530ce852010-10-09 11:00:50 +00001833 // Otherwise, we have a normal instruction or directive.
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001834
Eli Bendersky17233942013-01-15 22:59:42 +00001835 // Directives start with "."
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001836 if (IDVal[0] == '.' && IDVal != ".") {
Eli Bendersky17233942013-01-15 22:59:42 +00001837 // There are several entities interested in parsing directives:
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001838 //
Eli Bendersky17233942013-01-15 22:59:42 +00001839 // 1. The target-specific assembly parser. Some directives are target
1840 // specific or may potentially behave differently on certain targets.
1841 // 2. Asm parser extensions. For example, platform-specific parsers
1842 // (like the ELF parser) register themselves as extensions.
1843 // 3. The generic directive parser implemented by this class. These are
1844 // all the directives that behave in a target and platform independent
1845 // manner, or at least have a default behavior that's shared between
1846 // all targets and platforms.
Akira Hatanakad3590752012-07-05 19:09:33 +00001847
Oliver Stannard21718282016-07-26 14:19:47 +00001848 getTargetParser().flushPendingInstructions(getStreamer());
1849
Nirav Dave2364748a2016-09-16 18:30:20 +00001850 SMLoc StartTokLoc = getTok().getLoc();
1851 bool TPDirectiveReturn = getTargetParser().ParseDirective(ID);
1852
1853 if (hasPendingError())
1854 return true;
1855 // Currently the return value should be true if we are
1856 // uninterested but as this is at odds with the standard parsing
1857 // convention (return true = error) we have instances of a parsed
1858 // directive that fails returning true as an error. Catch these
1859 // cases as best as possible errors here.
1860 if (TPDirectiveReturn && StartTokLoc != getTok().getLoc())
1861 return true;
1862 // Return if we did some parsing or believe we succeeded.
1863 if (!TPDirectiveReturn || StartTokLoc != getTok().getLoc())
Akira Hatanakad3590752012-07-05 19:09:33 +00001864 return false;
1865
Alp Tokercb402912014-01-24 17:20:08 +00001866 // Next, check the extension directive map to see if any extension has
Eli Bendersky17233942013-01-15 22:59:42 +00001867 // registered itself to parse this directive.
Jim Grosbach4b905842013-09-20 23:08:21 +00001868 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1869 ExtensionDirectiveMap.lookup(IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +00001870 if (Handler.first)
1871 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1872
1873 // Finally, if no one else is interested in this directive, it must be
1874 // generic and familiar to this class.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001875 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001876 default:
1877 break;
1878 case DK_SET:
1879 case DK_EQU:
1880 return parseDirectiveSet(IDVal, true);
1881 case DK_EQUIV:
1882 return parseDirectiveSet(IDVal, false);
1883 case DK_ASCII:
1884 return parseDirectiveAscii(IDVal, false);
1885 case DK_ASCIZ:
1886 case DK_STRING:
1887 return parseDirectiveAscii(IDVal, true);
1888 case DK_BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001889 case DK_DC_B:
1890 return parseDirectiveValue(IDVal, 1);
1891 case DK_DC:
1892 case DK_DC_W:
Jim Grosbach4b905842013-09-20 23:08:21 +00001893 case DK_SHORT:
1894 case DK_VALUE:
1895 case DK_2BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001896 return parseDirectiveValue(IDVal, 2);
Jim Grosbach4b905842013-09-20 23:08:21 +00001897 case DK_LONG:
1898 case DK_INT:
1899 case DK_4BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001900 case DK_DC_L:
1901 return parseDirectiveValue(IDVal, 4);
Jim Grosbach4b905842013-09-20 23:08:21 +00001902 case DK_QUAD:
1903 case DK_8BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001904 return parseDirectiveValue(IDVal, 8);
1905 case DK_DC_A:
Konstantin Zhuravlyovdc77b2e2017-04-17 17:41:25 +00001906 return parseDirectiveValue(
1907 IDVal, getContext().getAsmInfo()->getCodePointerSize());
David Woodhoused6de0d92014-02-01 16:20:59 +00001908 case DK_OCTA:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001909 return parseDirectiveOctaValue(IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001910 case DK_SINGLE:
1911 case DK_FLOAT:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001912 case DK_DC_S:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001913 return parseDirectiveRealValue(IDVal, APFloat::IEEEsingle());
Jim Grosbach4b905842013-09-20 23:08:21 +00001914 case DK_DOUBLE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001915 case DK_DC_D:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001916 return parseDirectiveRealValue(IDVal, APFloat::IEEEdouble());
Jim Grosbach4b905842013-09-20 23:08:21 +00001917 case DK_ALIGN: {
1918 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1919 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1920 }
1921 case DK_ALIGN32: {
1922 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1923 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1924 }
1925 case DK_BALIGN:
1926 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1927 case DK_BALIGNW:
1928 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1929 case DK_BALIGNL:
1930 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1931 case DK_P2ALIGN:
1932 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1933 case DK_P2ALIGNW:
1934 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1935 case DK_P2ALIGNL:
1936 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1937 case DK_ORG:
1938 return parseDirectiveOrg();
1939 case DK_FILL:
1940 return parseDirectiveFill();
1941 case DK_ZERO:
1942 return parseDirectiveZero();
1943 case DK_EXTERN:
1944 eatToEndOfStatement(); // .extern is the default, ignore it.
1945 return false;
1946 case DK_GLOBL:
1947 case DK_GLOBAL:
1948 return parseDirectiveSymbolAttribute(MCSA_Global);
1949 case DK_LAZY_REFERENCE:
1950 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1951 case DK_NO_DEAD_STRIP:
1952 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1953 case DK_SYMBOL_RESOLVER:
1954 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1955 case DK_PRIVATE_EXTERN:
1956 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1957 case DK_REFERENCE:
1958 return parseDirectiveSymbolAttribute(MCSA_Reference);
1959 case DK_WEAK_DEFINITION:
1960 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1961 case DK_WEAK_REFERENCE:
1962 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1963 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1964 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1965 case DK_COMM:
1966 case DK_COMMON:
1967 return parseDirectiveComm(/*IsLocal=*/false);
1968 case DK_LCOMM:
1969 return parseDirectiveComm(/*IsLocal=*/true);
1970 case DK_ABORT:
1971 return parseDirectiveAbort();
1972 case DK_INCLUDE:
1973 return parseDirectiveInclude();
1974 case DK_INCBIN:
1975 return parseDirectiveIncbin();
1976 case DK_CODE16:
1977 case DK_CODE16GCC:
Nirav Davefd910412016-06-17 16:06:17 +00001978 return TokError(Twine(IDVal) +
1979 " not currently supported for this target");
Jim Grosbach4b905842013-09-20 23:08:21 +00001980 case DK_REPT:
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00001981 return parseDirectiveRept(IDLoc, IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001982 case DK_IRP:
1983 return parseDirectiveIrp(IDLoc);
1984 case DK_IRPC:
1985 return parseDirectiveIrpc(IDLoc);
1986 case DK_ENDR:
1987 return parseDirectiveEndr(IDLoc);
1988 case DK_BUNDLE_ALIGN_MODE:
1989 return parseDirectiveBundleAlignMode();
1990 case DK_BUNDLE_LOCK:
1991 return parseDirectiveBundleLock();
1992 case DK_BUNDLE_UNLOCK:
1993 return parseDirectiveBundleUnlock();
1994 case DK_SLEB128:
1995 return parseDirectiveLEB128(true);
1996 case DK_ULEB128:
1997 return parseDirectiveLEB128(false);
1998 case DK_SPACE:
1999 case DK_SKIP:
2000 return parseDirectiveSpace(IDVal);
2001 case DK_FILE:
2002 return parseDirectiveFile(IDLoc);
2003 case DK_LINE:
2004 return parseDirectiveLine();
2005 case DK_LOC:
2006 return parseDirectiveLoc();
2007 case DK_STABS:
2008 return parseDirectiveStabs();
Reid Kleckner2214ed82016-01-29 00:49:42 +00002009 case DK_CV_FILE:
2010 return parseDirectiveCVFile();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00002011 case DK_CV_FUNC_ID:
2012 return parseDirectiveCVFuncId();
2013 case DK_CV_INLINE_SITE_ID:
2014 return parseDirectiveCVInlineSiteId();
Reid Kleckner2214ed82016-01-29 00:49:42 +00002015 case DK_CV_LOC:
2016 return parseDirectiveCVLoc();
2017 case DK_CV_LINETABLE:
2018 return parseDirectiveCVLinetable();
David Majnemer6fcbd7e2016-01-29 19:24:12 +00002019 case DK_CV_INLINE_LINETABLE:
2020 return parseDirectiveCVInlineLinetable();
David Majnemer408b5e62016-02-05 01:55:49 +00002021 case DK_CV_DEF_RANGE:
2022 return parseDirectiveCVDefRange();
Reid Kleckner2214ed82016-01-29 00:49:42 +00002023 case DK_CV_STRINGTABLE:
2024 return parseDirectiveCVStringTable();
2025 case DK_CV_FILECHECKSUMS:
2026 return parseDirectiveCVFileChecksums();
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00002027 case DK_CV_FILECHECKSUM_OFFSET:
2028 return parseDirectiveCVFileChecksumOffset();
Reid Kleckner9cdd4df2017-10-11 21:24:33 +00002029 case DK_CV_FPO_DATA:
2030 return parseDirectiveCVFPOData();
Jim Grosbach4b905842013-09-20 23:08:21 +00002031 case DK_CFI_SECTIONS:
2032 return parseDirectiveCFISections();
2033 case DK_CFI_STARTPROC:
2034 return parseDirectiveCFIStartProc();
2035 case DK_CFI_ENDPROC:
2036 return parseDirectiveCFIEndProc();
2037 case DK_CFI_DEF_CFA:
2038 return parseDirectiveCFIDefCfa(IDLoc);
2039 case DK_CFI_DEF_CFA_OFFSET:
2040 return parseDirectiveCFIDefCfaOffset();
2041 case DK_CFI_ADJUST_CFA_OFFSET:
2042 return parseDirectiveCFIAdjustCfaOffset();
2043 case DK_CFI_DEF_CFA_REGISTER:
2044 return parseDirectiveCFIDefCfaRegister(IDLoc);
2045 case DK_CFI_OFFSET:
2046 return parseDirectiveCFIOffset(IDLoc);
2047 case DK_CFI_REL_OFFSET:
2048 return parseDirectiveCFIRelOffset(IDLoc);
2049 case DK_CFI_PERSONALITY:
2050 return parseDirectiveCFIPersonalityOrLsda(true);
2051 case DK_CFI_LSDA:
2052 return parseDirectiveCFIPersonalityOrLsda(false);
2053 case DK_CFI_REMEMBER_STATE:
2054 return parseDirectiveCFIRememberState();
2055 case DK_CFI_RESTORE_STATE:
2056 return parseDirectiveCFIRestoreState();
2057 case DK_CFI_SAME_VALUE:
2058 return parseDirectiveCFISameValue(IDLoc);
2059 case DK_CFI_RESTORE:
2060 return parseDirectiveCFIRestore(IDLoc);
2061 case DK_CFI_ESCAPE:
2062 return parseDirectiveCFIEscape();
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +00002063 case DK_CFI_RETURN_COLUMN:
2064 return parseDirectiveCFIReturnColumn(IDLoc);
Jim Grosbach4b905842013-09-20 23:08:21 +00002065 case DK_CFI_SIGNAL_FRAME:
2066 return parseDirectiveCFISignalFrame();
2067 case DK_CFI_UNDEFINED:
2068 return parseDirectiveCFIUndefined(IDLoc);
2069 case DK_CFI_REGISTER:
2070 return parseDirectiveCFIRegister(IDLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00002071 case DK_CFI_WINDOW_SAVE:
2072 return parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +00002073 case DK_MACROS_ON:
2074 case DK_MACROS_OFF:
2075 return parseDirectiveMacrosOnOff(IDVal);
2076 case DK_MACRO:
2077 return parseDirectiveMacro(IDLoc);
Michael Zuckerman56704612017-05-01 13:20:12 +00002078 case DK_ALTMACRO:
2079 case DK_NOALTMACRO:
2080 return parseDirectiveAltmacro(IDVal);
Nico Weber155dccd12014-07-24 17:08:39 +00002081 case DK_EXITM:
2082 return parseDirectiveExitMacro(IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00002083 case DK_ENDM:
2084 case DK_ENDMACRO:
2085 return parseDirectiveEndMacro(IDVal);
2086 case DK_PURGEM:
2087 return parseDirectivePurgeMacro(IDLoc);
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00002088 case DK_END:
2089 return parseDirectiveEnd(IDLoc);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00002090 case DK_ERR:
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00002091 return parseDirectiveError(IDLoc, false);
2092 case DK_ERROR:
2093 return parseDirectiveError(IDLoc, true);
Nico Weber404012b2014-07-24 16:26:06 +00002094 case DK_WARNING:
2095 return parseDirectiveWarning(IDLoc);
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002096 case DK_RELOC:
2097 return parseDirectiveReloc(IDLoc);
Petr Hosek4cb08ce2016-09-23 19:25:15 +00002098 case DK_DCB:
2099 case DK_DCB_W:
2100 return parseDirectiveDCB(IDVal, 2);
2101 case DK_DCB_B:
2102 return parseDirectiveDCB(IDVal, 1);
2103 case DK_DCB_D:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002104 return parseDirectiveRealDCB(IDVal, APFloat::IEEEdouble());
Petr Hosek4cb08ce2016-09-23 19:25:15 +00002105 case DK_DCB_L:
2106 return parseDirectiveDCB(IDVal, 4);
2107 case DK_DCB_S:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002108 return parseDirectiveRealDCB(IDVal, APFloat::IEEEsingle());
Petr Hosek731bb9c2016-08-23 21:34:53 +00002109 case DK_DC_X:
Petr Hosek4cb08ce2016-09-23 19:25:15 +00002110 case DK_DCB_X:
Petr Hosek731bb9c2016-08-23 21:34:53 +00002111 return TokError(Twine(IDVal) +
2112 " not currently supported for this target");
Petr Hosek85b2f672016-09-23 21:53:36 +00002113 case DK_DS:
2114 case DK_DS_W:
2115 return parseDirectiveDS(IDVal, 2);
2116 case DK_DS_B:
2117 return parseDirectiveDS(IDVal, 1);
2118 case DK_DS_D:
2119 return parseDirectiveDS(IDVal, 8);
2120 case DK_DS_L:
2121 case DK_DS_S:
2122 return parseDirectiveDS(IDVal, 4);
2123 case DK_DS_P:
2124 case DK_DS_X:
2125 return parseDirectiveDS(IDVal, 12);
Coby Tayree01e53202017-10-02 14:36:31 +00002126 case DK_PRINT:
2127 return parseDirectivePrint(IDLoc);
Eli Friedman20b02642010-07-19 04:17:25 +00002128 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002129
Jim Grosbach758e0cc2012-05-01 18:38:27 +00002130 return Error(IDLoc, "unknown directive");
Chris Lattnere5074c42009-06-22 01:29:09 +00002131 }
Chris Lattner36e02122009-06-21 20:54:55 +00002132
Chad Rosierc7f552c2013-02-12 21:33:51 +00002133 // __asm _emit or __asm __emit
2134 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
2135 IDVal == "_EMIT" || IDVal == "__EMIT"))
Jim Grosbach4b905842013-09-20 23:08:21 +00002136 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
Chad Rosierc7f552c2013-02-12 21:33:51 +00002137
2138 // __asm align
2139 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
Jim Grosbach4b905842013-09-20 23:08:21 +00002140 return parseDirectiveMSAlign(IDLoc, Info);
Eli Friedman0f4871d2012-10-22 23:58:19 +00002141
Coby Tayree3847be92017-04-04 17:57:23 +00002142 if (ParsingInlineAsm && (IDVal == "even" || IDVal == "EVEN"))
Michael Zuckerman02ecd432015-12-13 17:07:23 +00002143 Info.AsmRewrites->emplace_back(AOK_EVEN, IDLoc, 4);
Nirav Davef43cc9f2016-10-10 15:24:54 +00002144 if (checkForValidSection())
2145 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00002146
Chris Lattner7cbfa442010-05-19 23:34:33 +00002147 // Canonicalize the opcode to lower case.
Eli Bendersky88024712013-01-16 19:32:36 +00002148 std::string OpcodeStr = IDVal.lower();
Chad Rosierf0e87202012-10-25 20:41:34 +00002149 ParseInstructionInfo IInfo(Info.AsmRewrites);
Nirav Dave2364748a2016-09-16 18:30:20 +00002150 bool ParseHadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, ID,
2151 Info.ParsedOperands);
2152 Info.ParseError = ParseHadError;
Chris Lattnere5074c42009-06-22 01:29:09 +00002153
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002154 // Dump the parsed representation, if requested.
2155 if (getShowParsedOperands()) {
2156 SmallString<256> Str;
2157 raw_svector_ostream OS(Str);
2158 OS << "parsed instruction: [";
Eli Friedman0f4871d2012-10-22 23:58:19 +00002159 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002160 if (i != 0)
2161 OS << ", ";
Eli Friedman0f4871d2012-10-22 23:58:19 +00002162 Info.ParsedOperands[i]->print(OS);
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002163 }
2164 OS << "]";
2165
Jim Grosbach4b905842013-09-20 23:08:21 +00002166 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002167 }
2168
Nirav Dave2364748a2016-09-16 18:30:20 +00002169 // Fail even if ParseInstruction erroneously returns false.
2170 if (hasPendingError() || ParseHadError)
2171 return true;
2172
Oliver Stannard8b273082014-06-19 15:52:37 +00002173 // If we are generating dwarf for the current section then generate a .loc
2174 // directive for the instruction.
Paul Robinson938d9a02018-03-22 15:48:01 +00002175 if (!ParseHadError && enabledGenDwarfForAssembly() &&
Oliver Stannard8b273082014-06-19 15:52:37 +00002176 getContext().getGenDwarfSectionSyms().count(
Eric Christopher445c9522016-10-14 05:47:37 +00002177 getStreamer().getCurrentSectionOnly())) {
Saleem Abdulrasool4d6ed7c2014-12-24 06:32:43 +00002178 unsigned Line;
2179 if (ActiveMacros.empty())
2180 Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
2181 else
Frederic Riss16238d92015-06-25 21:57:33 +00002182 Line = SrcMgr.FindLineNumber(ActiveMacros.front()->InstantiationLoc,
2183 ActiveMacros.front()->ExitBuffer);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002184
Eli Bendersky88024712013-01-16 19:32:36 +00002185 // If we previously parsed a cpp hash file line comment then make sure the
2186 // current Dwarf File is for the CppHashFilename if not then emit the
2187 // Dwarf File table for it and adjust the line number for the .loc.
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00002188 if (!CppHashInfo.Filename.empty()) {
David Blaikiec714ef42014-03-17 01:52:11 +00002189 unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
Tim Northoverc0bef992016-04-13 19:46:54 +00002190 0, StringRef(), CppHashInfo.Filename);
David Blaikiec714ef42014-03-17 01:52:11 +00002191 getContext().setGenDwarfFileNumber(FileNumber);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002192
Graydon Hoare54fe2082018-04-07 00:44:02 +00002193 unsigned CppHashLocLineNo =
2194 SrcMgr.FindLineNumber(CppHashInfo.Loc, CppHashInfo.Buf);
Tim Northoverc0bef992016-04-13 19:46:54 +00002195 Line = CppHashInfo.LineNumber - 1 + (Line - CppHashLocLineNo);
Eli Bendersky88024712013-01-16 19:32:36 +00002196 }
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002197
Jim Grosbach4b905842013-09-20 23:08:21 +00002198 getStreamer().EmitDwarfLocDirective(
2199 getContext().getGenDwarfFileNumber(), Line, 0,
2200 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
2201 StringRef());
Kevin Enderby6469fc22011-11-01 22:27:22 +00002202 }
2203
Daniel Dunbarce0c1e12010-05-04 00:33:07 +00002204 // If parsing succeeded, match the instruction.
Nirav Dave2364748a2016-09-16 18:30:20 +00002205 if (!ParseHadError) {
Tim Northover26bb14e2014-08-18 11:49:42 +00002206 uint64_t ErrorInfo;
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +00002207 if (getTargetParser().MatchAndEmitInstruction(
2208 IDLoc, Info.Opcode, Info.ParsedOperands, Out, ErrorInfo,
2209 getTargetParser().isParsingInlineAsm()))
Nirav Dave2364748a2016-09-16 18:30:20 +00002210 return true;
Chad Rosier49963552012-10-13 00:26:04 +00002211 }
Chris Lattnera2a9d162010-09-11 16:18:25 +00002212 return false;
Chris Lattnerb0133452009-06-21 20:16:42 +00002213}
Chris Lattnerbedf6c22009-06-24 04:43:34 +00002214
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00002215// Parse and erase curly braces marking block start/end
Sam Cleggf009da22018-04-19 22:00:53 +00002216bool
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00002217AsmParser::parseCurlyBlockScope(SmallVectorImpl<AsmRewrite> &AsmStrRewrites) {
2218 // Identify curly brace marking block start/end
2219 if (Lexer.isNot(AsmToken::LCurly) && Lexer.isNot(AsmToken::RCurly))
2220 return false;
2221
2222 SMLoc StartLoc = Lexer.getLoc();
2223 Lex(); // Eat the brace
2224 if (Lexer.is(AsmToken::EndOfStatement))
2225 Lex(); // Eat EndOfStatement following the brace
2226
2227 // Erase the block start/end brace from the output asm string
2228 AsmStrRewrites.emplace_back(AOK_Skip, StartLoc, Lexer.getLoc().getPointer() -
2229 StartLoc.getPointer());
2230 return true;
2231}
2232
Jim Grosbach4b905842013-09-20 23:08:21 +00002233/// parseCppHashLineFilenameComment as this:
Kevin Enderby72553612011-09-13 23:45:18 +00002234/// ::= # number "filename"
Craig Topper3c76c522015-09-20 23:35:59 +00002235bool AsmParser::parseCppHashLineFilenameComment(SMLoc L) {
Kevin Enderby72553612011-09-13 23:45:18 +00002236 Lex(); // Eat the hash token.
Nirav Davefd910412016-06-17 16:06:17 +00002237 // Lexer only ever emits HashDirective if it fully formed if it's
2238 // done the checking already so this is an internal error.
2239 assert(getTok().is(AsmToken::Integer) &&
2240 "Lexing Cpp line comment: Expected Integer");
Kevin Enderby72553612011-09-13 23:45:18 +00002241 int64_t LineNumber = getTok().getIntVal();
Kevin Enderby72553612011-09-13 23:45:18 +00002242 Lex();
Nirav Davefd910412016-06-17 16:06:17 +00002243 assert(getTok().is(AsmToken::String) &&
2244 "Lexing Cpp line comment: Expected String");
Kevin Enderby72553612011-09-13 23:45:18 +00002245 StringRef Filename = getTok().getString();
Nirav Davefd910412016-06-17 16:06:17 +00002246 Lex();
Nirav Dave2364748a2016-09-16 18:30:20 +00002247
Kevin Enderby72553612011-09-13 23:45:18 +00002248 // Get rid of the enclosing quotes.
Jim Grosbach4b905842013-09-20 23:08:21 +00002249 Filename = Filename.substr(1, Filename.size() - 2);
Kevin Enderby72553612011-09-13 23:45:18 +00002250
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002251 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
Tim Northoverc0bef992016-04-13 19:46:54 +00002252 CppHashInfo.Loc = L;
2253 CppHashInfo.Filename = Filename;
2254 CppHashInfo.LineNumber = LineNumber;
2255 CppHashInfo.Buf = CurBuffer;
Kevin Enderby72553612011-09-13 23:45:18 +00002256 return false;
2257}
2258
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002259/// will use the last parsed cpp hash line filename comment
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002260/// for the Filename and LineNo if any in the diagnostic.
2261void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002262 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002263 raw_ostream &OS = errs();
2264
2265 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
Craig Topper3c76c522015-09-20 23:35:59 +00002266 SMLoc DiagLoc = Diag.getLoc();
Alp Tokera55b95b2014-07-06 10:33:31 +00002267 unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2268 unsigned CppHashBuf =
Tim Northoverc0bef992016-04-13 19:46:54 +00002269 Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashInfo.Loc);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002270
Jim Grosbach4b905842013-09-20 23:08:21 +00002271 // Like SourceMgr::printMessage() we need to print the include stack if any
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002272 // before printing the message.
Alp Tokera55b95b2014-07-06 10:33:31 +00002273 unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2274 if (!Parser->SavedDiagHandler && DiagCurBuffer &&
2275 DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002276 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
2277 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002278 }
2279
Eric Christophera7c32732012-12-18 00:30:54 +00002280 // If we have not parsed a cpp hash line filename comment or the source
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002281 // manager changed or buffer changed (like in a nested include) then just
2282 // print the normal diagnostic using its Filename and LineNo.
Tim Northoverc0bef992016-04-13 19:46:54 +00002283 if (!Parser->CppHashInfo.LineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002284 DiagBuf != CppHashBuf) {
Benjamin Kramer47f5e302011-10-16 10:48:29 +00002285 if (Parser->SavedDiagHandler)
2286 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
2287 else
Craig Topper353eda42014-04-24 06:44:33 +00002288 Diag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002289 return;
2290 }
2291
Eric Christophera7c32732012-12-18 00:30:54 +00002292 // Use the CppHashFilename and calculate a line number based on the
Tim Northoverc0bef992016-04-13 19:46:54 +00002293 // CppHashInfo.Loc and CppHashInfo.LineNumber relative to this Diag's SMLoc
2294 // for the diagnostic.
2295 const std::string &Filename = Parser->CppHashInfo.Filename;
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002296
2297 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
2298 int CppHashLocLineNo =
Tim Northoverc0bef992016-04-13 19:46:54 +00002299 Parser->SrcMgr.FindLineNumber(Parser->CppHashInfo.Loc, CppHashBuf);
Jim Grosbach4b905842013-09-20 23:08:21 +00002300 int LineNo =
Tim Northoverc0bef992016-04-13 19:46:54 +00002301 Parser->CppHashInfo.LineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002302
Jim Grosbach4b905842013-09-20 23:08:21 +00002303 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
2304 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
Chris Lattner72845262011-10-16 05:47:55 +00002305 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002306
Benjamin Kramer47f5e302011-10-16 10:48:29 +00002307 if (Parser->SavedDiagHandler)
2308 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
2309 else
Craig Topper353eda42014-04-24 06:44:33 +00002310 NewDiag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002311}
2312
Rafael Espindola2c064482012-08-21 18:29:30 +00002313// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
2314// difference being that that function accepts '@' as part of identifiers and
2315// we can't do that. AsmLexer.cpp should probably be changed to handle
2316// '@' as a special case when needed.
2317static bool isIdentifierChar(char c) {
Guy Benyei83c74e92013-02-12 21:21:59 +00002318 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
2319 c == '.';
Rafael Espindola2c064482012-08-21 18:29:30 +00002320}
2321
Rafael Espindola34b9c512012-06-03 23:57:14 +00002322bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00002323 ArrayRef<MCAsmMacroParameter> Parameters,
Toma Tabacu217116e2015-04-27 10:50:29 +00002324 ArrayRef<MCAsmMacroArgument> A,
Craig Topper3c76c522015-09-20 23:35:59 +00002325 bool EnableAtPseudoVariable, SMLoc L) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00002326 unsigned NParameters = Parameters.size();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002327 bool HasVararg = NParameters ? Parameters.back().Vararg : false;
Benjamin Kramer513e7442014-02-20 13:36:32 +00002328 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
Rafael Espindola1134ab232011-06-05 02:43:45 +00002329 return Error(L, "Wrong number of arguments");
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002330
Preston Gurd05500642012-09-19 20:36:12 +00002331 // A macro without parameters is handled differently on Darwin:
2332 // gas accepts no arguments and does no substitutions
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002333 while (!Body.empty()) {
2334 // Scan for the next substitution.
2335 std::size_t End = Body.size(), Pos = 0;
2336 for (; Pos != End; ++Pos) {
2337 // Check for a substitution or escape.
Benjamin Kramer513e7442014-02-20 13:36:32 +00002338 if (IsDarwin && !NParameters) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00002339 // This macro has no parameters, look for $0, $1, etc.
2340 if (Body[Pos] != '$' || Pos + 1 == End)
2341 continue;
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002342
Rafael Espindola1134ab232011-06-05 02:43:45 +00002343 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00002344 if (Next == '$' || Next == 'n' ||
2345 isdigit(static_cast<unsigned char>(Next)))
Rafael Espindola1134ab232011-06-05 02:43:45 +00002346 break;
2347 } else {
2348 // This macro has parameters, look for \foo, \bar, etc.
2349 if (Body[Pos] == '\\' && Pos + 1 != End)
2350 break;
2351 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002352 }
2353
2354 // Add the prefix.
2355 OS << Body.slice(0, Pos);
2356
2357 // Check if we reached the end.
2358 if (Pos == End)
2359 break;
2360
Benjamin Kramer513e7442014-02-20 13:36:32 +00002361 if (IsDarwin && !NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002362 switch (Body[Pos + 1]) {
2363 // $$ => $
Rafael Espindola1134ab232011-06-05 02:43:45 +00002364 case '$':
2365 OS << '$';
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002366 break;
2367
Jim Grosbach4b905842013-09-20 23:08:21 +00002368 // $n => number of arguments
Rafael Espindola1134ab232011-06-05 02:43:45 +00002369 case 'n':
2370 OS << A.size();
2371 break;
2372
Jim Grosbach4b905842013-09-20 23:08:21 +00002373 // $[0-9] => argument
Rafael Espindola1134ab232011-06-05 02:43:45 +00002374 default: {
2375 // Missing arguments are ignored.
Jim Grosbach4b905842013-09-20 23:08:21 +00002376 unsigned Index = Body[Pos + 1] - '0';
Rafael Espindola1134ab232011-06-05 02:43:45 +00002377 if (Index >= A.size())
2378 break;
2379
2380 // Otherwise substitute with the token values, with spaces eliminated.
Craig Topper84008482015-10-10 05:38:14 +00002381 for (const AsmToken &Token : A[Index])
2382 OS << Token.getString();
Rafael Espindola1134ab232011-06-05 02:43:45 +00002383 break;
2384 }
2385 }
2386 Pos += 2;
2387 } else {
2388 unsigned I = Pos + 1;
Toma Tabacu217116e2015-04-27 10:50:29 +00002389
2390 // Check for the \@ pseudo-variable.
2391 if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End)
Rafael Espindola1134ab232011-06-05 02:43:45 +00002392 ++I;
Toma Tabacu217116e2015-04-27 10:50:29 +00002393 else
2394 while (isIdentifierChar(Body[I]) && I + 1 != End)
2395 ++I;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002396
Jim Grosbach4b905842013-09-20 23:08:21 +00002397 const char *Begin = Body.data() + Pos + 1;
2398 StringRef Argument(Begin, I - (Pos + 1));
Rafael Espindola1134ab232011-06-05 02:43:45 +00002399 unsigned Index = 0;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002400
Toma Tabacu217116e2015-04-27 10:50:29 +00002401 if (Argument == "@") {
2402 OS << NumOfMacroInstantiations;
2403 Pos += 2;
Preston Gurd05500642012-09-19 20:36:12 +00002404 } else {
Toma Tabacu217116e2015-04-27 10:50:29 +00002405 for (; Index < NParameters; ++Index)
2406 if (Parameters[Index].Name == Argument)
2407 break;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002408
Toma Tabacu217116e2015-04-27 10:50:29 +00002409 if (Index == NParameters) {
2410 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
2411 Pos += 3;
2412 else {
2413 OS << '\\' << Argument;
2414 Pos = I;
2415 }
2416 } else {
2417 bool VarargParameter = HasVararg && Index == (NParameters - 1);
Craig Topper84008482015-10-10 05:38:14 +00002418 for (const AsmToken &Token : A[Index])
Michael Zuckerman56704612017-05-01 13:20:12 +00002419 // For altmacro mode, you can write '%expr'.
2420 // The prefix '%' evaluates the expression 'expr'
2421 // and uses the result as a string (e.g. replace %(1+2) with the string "3").
2422 // Here, we identify the integer token which is the result of the
2423 // absolute expression evaluation and replace it with its string representation.
2424 if ((Lexer.IsaAltMacroMode()) &&
2425 (*(Token.getString().begin()) == '%') && Token.is(AsmToken::Integer))
2426 // Emit an integer value to the buffer.
2427 OS << Token.getIntVal();
Michael Zuckerman1f1a9122017-05-10 13:08:11 +00002428 // Only Token that was validated as a string and begins with '<'
2429 // is considered altMacroString!!!
2430 else if ((Lexer.IsaAltMacroMode()) &&
2431 (*(Token.getString().begin()) == '<') &&
2432 Token.is(AsmToken::String)) {
2433 std::string Res;
2434 altMacroString(Token.getStringContents(), Res);
2435 OS << Res;
2436 }
Toma Tabacu217116e2015-04-27 10:50:29 +00002437 // We expect no quotes around the string's contents when
2438 // parsing for varargs.
Michael Zuckerman56704612017-05-01 13:20:12 +00002439 else if (Token.isNot(AsmToken::String) || VarargParameter)
Craig Topper84008482015-10-10 05:38:14 +00002440 OS << Token.getString();
Toma Tabacu217116e2015-04-27 10:50:29 +00002441 else
Craig Topper84008482015-10-10 05:38:14 +00002442 OS << Token.getStringContents();
Toma Tabacu217116e2015-04-27 10:50:29 +00002443
2444 Pos += 1 + Argument.size();
2445 }
Preston Gurd05500642012-09-19 20:36:12 +00002446 }
Rafael Espindola1134ab232011-06-05 02:43:45 +00002447 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002448 // Update the scan point.
Rafael Espindola1134ab232011-06-05 02:43:45 +00002449 Body = Body.substr(Pos);
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002450 }
Daniel Dunbar43235712010-07-18 18:54:11 +00002451
Rafael Espindola1134ab232011-06-05 02:43:45 +00002452 return false;
2453}
Daniel Dunbar43235712010-07-18 18:54:11 +00002454
Nico Weber2a8f9222014-07-24 16:29:04 +00002455MacroInstantiation::MacroInstantiation(SMLoc IL, int EB, SMLoc EL,
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002456 size_t CondStackDepth)
Rafael Espindolaf43a94e2014-08-17 22:48:55 +00002457 : InstantiationLoc(IL), ExitBuffer(EB), ExitLoc(EL),
Nico Weber155dccd12014-07-24 17:08:39 +00002458 CondStackDepth(CondStackDepth) {}
Daniel Dunbar43235712010-07-18 18:54:11 +00002459
Jim Grosbach4b905842013-09-20 23:08:21 +00002460static bool isOperator(AsmToken::TokenKind kind) {
2461 switch (kind) {
2462 default:
2463 return false;
2464 case AsmToken::Plus:
2465 case AsmToken::Minus:
2466 case AsmToken::Tilde:
2467 case AsmToken::Slash:
2468 case AsmToken::Star:
2469 case AsmToken::Dot:
2470 case AsmToken::Equal:
2471 case AsmToken::EqualEqual:
2472 case AsmToken::Pipe:
2473 case AsmToken::PipePipe:
2474 case AsmToken::Caret:
2475 case AsmToken::Amp:
2476 case AsmToken::AmpAmp:
2477 case AsmToken::Exclaim:
2478 case AsmToken::ExclaimEqual:
Jim Grosbach4b905842013-09-20 23:08:21 +00002479 case AsmToken::Less:
2480 case AsmToken::LessEqual:
2481 case AsmToken::LessLess:
2482 case AsmToken::LessGreater:
2483 case AsmToken::Greater:
2484 case AsmToken::GreaterEqual:
2485 case AsmToken::GreaterGreater:
2486 return true;
Preston Gurd05500642012-09-19 20:36:12 +00002487 }
2488}
2489
David Majnemer16252452014-01-29 00:07:39 +00002490namespace {
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002491
David Majnemer16252452014-01-29 00:07:39 +00002492class AsmLexerSkipSpaceRAII {
2493public:
2494 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
2495 Lexer.setSkipSpace(SkipSpace);
2496 }
2497
2498 ~AsmLexerSkipSpaceRAII() {
2499 Lexer.setSkipSpace(true);
2500 }
2501
2502private:
2503 AsmLexer &Lexer;
2504};
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002505
2506} // end anonymous namespace
David Majnemer16252452014-01-29 00:07:39 +00002507
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002508bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
2509
2510 if (Vararg) {
2511 if (Lexer.isNot(AsmToken::EndOfStatement)) {
2512 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002513 MA.emplace_back(AsmToken::String, Str);
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002514 }
2515 return false;
2516 }
2517
Rafael Espindola768b41c2012-06-15 14:02:34 +00002518 unsigned ParenLevel = 0;
Preston Gurd05500642012-09-19 20:36:12 +00002519
David Majnemer16252452014-01-29 00:07:39 +00002520 // Darwin doesn't use spaces to delmit arguments.
2521 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
Rafael Espindola768b41c2012-06-15 14:02:34 +00002522
Scott Egertona1fa68a2016-02-11 13:48:49 +00002523 bool SpaceEaten;
2524
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002525 while (true) {
Scott Egertona1fa68a2016-02-11 13:48:49 +00002526 SpaceEaten = false;
David Majnemer16252452014-01-29 00:07:39 +00002527 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002528 return TokError("unexpected token in macro instantiation");
Preston Gurd05500642012-09-19 20:36:12 +00002529
Scott Egertona1fa68a2016-02-11 13:48:49 +00002530 if (ParenLevel == 0) {
Preston Gurd05500642012-09-19 20:36:12 +00002531
Scott Egertona1fa68a2016-02-11 13:48:49 +00002532 if (Lexer.is(AsmToken::Comma))
2533 break;
2534
2535 if (Lexer.is(AsmToken::Space)) {
2536 SpaceEaten = true;
Nirav Dave1180e6892016-06-02 17:15:05 +00002537 Lexer.Lex(); // Eat spaces
Scott Egertona1fa68a2016-02-11 13:48:49 +00002538 }
Preston Gurd05500642012-09-19 20:36:12 +00002539
2540 // Spaces can delimit parameters, but could also be part an expression.
2541 // If the token after a space is an operator, add the token and the next
2542 // one into this argument
David Majnemer91fc4c22014-01-29 18:57:46 +00002543 if (!IsDarwin) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002544 if (isOperator(Lexer.getKind())) {
Scott Egertona1fa68a2016-02-11 13:48:49 +00002545 MA.push_back(getTok());
Nirav Dave1180e6892016-06-02 17:15:05 +00002546 Lexer.Lex();
Preston Gurd05500642012-09-19 20:36:12 +00002547
Scott Egertona1fa68a2016-02-11 13:48:49 +00002548 // Whitespace after an operator can be ignored.
2549 if (Lexer.is(AsmToken::Space))
Nirav Dave1180e6892016-06-02 17:15:05 +00002550 Lexer.Lex();
Scott Egertona1fa68a2016-02-11 13:48:49 +00002551
2552 continue;
Preston Gurd05500642012-09-19 20:36:12 +00002553 }
2554 }
Scott Egertona1fa68a2016-02-11 13:48:49 +00002555 if (SpaceEaten)
2556 break;
Preston Gurd05500642012-09-19 20:36:12 +00002557 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002558
Jim Grosbach4b905842013-09-20 23:08:21 +00002559 // handleMacroEntry relies on not advancing the lexer here
Rafael Espindola768b41c2012-06-15 14:02:34 +00002560 // to be able to fill in the remaining default parameter values
2561 if (Lexer.is(AsmToken::EndOfStatement))
2562 break;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002563
2564 // Adjust the current parentheses level.
2565 if (Lexer.is(AsmToken::LParen))
2566 ++ParenLevel;
2567 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
2568 --ParenLevel;
2569
2570 // Append the token to the current argument list.
2571 MA.push_back(getTok());
Nirav Dave1180e6892016-06-02 17:15:05 +00002572 Lexer.Lex();
Rafael Espindola768b41c2012-06-15 14:02:34 +00002573 }
Preston Gurd05500642012-09-19 20:36:12 +00002574
Rafael Espindola768b41c2012-06-15 14:02:34 +00002575 if (ParenLevel != 0)
Rafael Espindola3e5eb422012-08-21 15:55:04 +00002576 return TokError("unbalanced parentheses in macro argument");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002577 return false;
2578}
2579
2580// Parse the macro instantiation arguments.
Jim Grosbach4b905842013-09-20 23:08:21 +00002581bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
Vladimir Medic9bad0d332013-08-20 13:33:18 +00002582 MCAsmMacroArguments &A) {
Rafael Espindola768b41c2012-06-15 14:02:34 +00002583 const unsigned NParameters = M ? M->Parameters.size() : 0;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002584 bool NamedParametersFound = false;
2585 SmallVector<SMLoc, 4> FALocs;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002586
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002587 A.resize(NParameters);
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002588 FALocs.resize(NParameters);
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002589
Rafael Espindola768b41c2012-06-15 14:02:34 +00002590 // Parse two kinds of macro invocations:
2591 // - macros defined without any parameters accept an arbitrary number of them
2592 // - macros defined with parameters accept at most that many of them
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002593 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002594 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
2595 ++Parameter) {
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002596 SMLoc IDLoc = Lexer.getLoc();
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002597 MCAsmMacroParameter FA;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002598
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002599 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00002600 if (parseIdentifier(FA.Name))
2601 return Error(IDLoc, "invalid argument identifier for formal argument");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002602
Nirav Dave2364748a2016-09-16 18:30:20 +00002603 if (Lexer.isNot(AsmToken::Equal))
2604 return TokError("expected '=' after formal parameter identifier");
2605
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002606 Lex();
2607
2608 NamedParametersFound = true;
2609 }
Michael Zuckerman56704612017-05-01 13:20:12 +00002610 bool Vararg = HasVararg && Parameter == (NParameters - 1);
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002611
Nirav Dave2364748a2016-09-16 18:30:20 +00002612 if (NamedParametersFound && FA.Name.empty())
2613 return Error(IDLoc, "cannot mix positional and keyword arguments");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002614
Michael Zuckerman763e60e2017-05-04 10:37:00 +00002615 SMLoc StrLoc = Lexer.getLoc();
2616 SMLoc EndLoc;
Michael Zuckerman56704612017-05-01 13:20:12 +00002617 if (Lexer.IsaAltMacroMode() && Lexer.is(AsmToken::Percent)) {
Michael Zuckerman56704612017-05-01 13:20:12 +00002618 const MCExpr *AbsoluteExp;
2619 int64_t Value;
2620 /// Eat '%'
2621 Lex();
2622 if (parseExpression(AbsoluteExp, EndLoc))
2623 return false;
Nirav Dave6c0665e2018-04-30 19:22:40 +00002624 if (!AbsoluteExp->evaluateAsAbsolute(Value,
2625 getStreamer().getAssemblerPtr()))
Michael Zuckerman56704612017-05-01 13:20:12 +00002626 return Error(StrLoc, "expected absolute expression");
2627 const char *StrChar = StrLoc.getPointer();
2628 const char *EndChar = EndLoc.getPointer();
2629 AsmToken newToken(AsmToken::Integer, StringRef(StrChar , EndChar - StrChar), Value);
2630 FA.Value.push_back(newToken);
Michael Zuckerman763e60e2017-05-04 10:37:00 +00002631 } else if (Lexer.IsaAltMacroMode() && Lexer.is(AsmToken::Less) &&
2632 isAltmacroString(StrLoc, EndLoc)) {
2633 const char *StrChar = StrLoc.getPointer();
2634 const char *EndChar = EndLoc.getPointer();
2635 jumpToLoc(EndLoc, CurBuffer);
2636 /// Eat from '<' to '>'
2637 Lex();
2638 AsmToken newToken(AsmToken::String, StringRef(StrChar, EndChar - StrChar));
2639 FA.Value.push_back(newToken);
2640 } else if(parseMacroArgument(FA.Value, Vararg))
Michael Zuckerman56704612017-05-01 13:20:12 +00002641 return true;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002642
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002643 unsigned PI = Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002644 if (!FA.Name.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002645 unsigned FAI = 0;
2646 for (FAI = 0; FAI < NParameters; ++FAI)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002647 if (M->Parameters[FAI].Name == FA.Name)
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002648 break;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002649
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002650 if (FAI >= NParameters) {
Nirav Davefd910412016-06-17 16:06:17 +00002651 assert(M && "expected macro to be defined");
Nirav Dave2364748a2016-09-16 18:30:20 +00002652 return Error(IDLoc, "parameter named '" + FA.Name +
2653 "' does not exist for macro '" + M->Name + "'");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002654 }
2655 PI = FAI;
2656 }
2657
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002658 if (!FA.Value.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002659 if (A.size() <= PI)
2660 A.resize(PI + 1);
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002661 A[PI] = FA.Value;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002662
2663 if (FALocs.size() <= PI)
2664 FALocs.resize(PI + 1);
2665
2666 FALocs[PI] = Lexer.getLoc();
Preston Gurd242ed3152012-09-19 20:29:04 +00002667 }
Jim Grosbach206661622012-07-30 22:44:17 +00002668
Preston Gurd242ed3152012-09-19 20:29:04 +00002669 // At the end of the statement, fill in remaining arguments that have
2670 // default values. If there aren't any, then the next argument is
2671 // required but missing
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002672 if (Lexer.is(AsmToken::EndOfStatement)) {
2673 bool Failure = false;
2674 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2675 if (A[FAI].empty()) {
2676 if (M->Parameters[FAI].Required) {
2677 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2678 "missing value for required parameter "
2679 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2680 Failure = true;
2681 }
2682
2683 if (!M->Parameters[FAI].Value.empty())
2684 A[FAI] = M->Parameters[FAI].Value;
2685 }
2686 }
2687 return Failure;
2688 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002689
2690 if (Lexer.is(AsmToken::Comma))
2691 Lex();
2692 }
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002693
2694 return TokError("too many positional arguments");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002695}
2696
Jim Grosbach4b905842013-09-20 23:08:21 +00002697bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
Davide Italiano7c9fc732016-07-27 05:51:56 +00002698 // Arbitrarily limit macro nesting depth (default matches 'as'). We can
2699 // eliminate this, although we should protect against infinite loops.
2700 unsigned MaxNestingDepth = AsmMacroMaxNestingDepth;
2701 if (ActiveMacros.size() == MaxNestingDepth) {
2702 std::ostringstream MaxNestingDepthError;
2703 MaxNestingDepthError << "macros cannot be nested more than "
2704 << MaxNestingDepth << " levels deep."
2705 << " Use -asm-macro-max-nesting-depth to increase "
2706 "this limit.";
2707 return TokError(MaxNestingDepthError.str());
2708 }
Daniel Dunbar43235712010-07-18 18:54:11 +00002709
Eli Bendersky38274122013-01-14 23:22:36 +00002710 MCAsmMacroArguments A;
Jim Grosbach4b905842013-09-20 23:08:21 +00002711 if (parseMacroArguments(M, A))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002712 return true;
Daniel Dunbar43235712010-07-18 18:54:11 +00002713
Rafael Espindola1134ab232011-06-05 02:43:45 +00002714 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2715 // to hold the macro body with substitutions.
2716 SmallString<256> Buf;
2717 StringRef Body = M->Body;
Rafael Espindola34b9c512012-06-03 23:57:14 +00002718 raw_svector_ostream OS(Buf);
Rafael Espindola1134ab232011-06-05 02:43:45 +00002719
Toma Tabacu217116e2015-04-27 10:50:29 +00002720 if (expandMacro(OS, Body, M->Parameters, A, true, getTok().getLoc()))
Rafael Espindola1134ab232011-06-05 02:43:45 +00002721 return true;
2722
Eli Bendersky38274122013-01-14 23:22:36 +00002723 // We include the .endmacro in the buffer as our cue to exit the macro
Rafael Espindola34b9c512012-06-03 23:57:14 +00002724 // instantiation.
2725 OS << ".endmacro\n";
2726
Rafael Espindola3560ff22014-08-27 20:03:13 +00002727 std::unique_ptr<MemoryBuffer> Instantiation =
2728 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola1134ab232011-06-05 02:43:45 +00002729
Daniel Dunbar43235712010-07-18 18:54:11 +00002730 // Create the macro instantiation object and add to the current macro
2731 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002732 MacroInstantiation *MI = new MacroInstantiation(
2733 NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Daniel Dunbar43235712010-07-18 18:54:11 +00002734 ActiveMacros.push_back(MI);
2735
Toma Tabacu217116e2015-04-27 10:50:29 +00002736 ++NumOfMacroInstantiations;
2737
Daniel Dunbar43235712010-07-18 18:54:11 +00002738 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00002739 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00002740 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar43235712010-07-18 18:54:11 +00002741 Lex();
2742
2743 return false;
2744}
2745
Jim Grosbach4b905842013-09-20 23:08:21 +00002746void AsmParser::handleMacroExit() {
Daniel Dunbar43235712010-07-18 18:54:11 +00002747 // Jump to the EndOfStatement we should return to, and consume it.
Jim Grosbach4b905842013-09-20 23:08:21 +00002748 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
Daniel Dunbar43235712010-07-18 18:54:11 +00002749 Lex();
2750
2751 // Pop the instantiation entry.
2752 delete ActiveMacros.back();
2753 ActiveMacros.pop_back();
2754}
2755
Jim Grosbach4b905842013-09-20 23:08:21 +00002756bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
Nirav Dave05b58912018-06-05 15:13:39 +00002757 bool NoDeadStrip, bool AllowExtendedExpr) {
Pete Cooper80d21cb2015-06-22 19:35:57 +00002758 MCSymbol *Sym;
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002759 const MCExpr *Value;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002760 if (MCParserUtils::parseAssignmentExpression(Name, allow_redef, *this, Sym,
Nirav Dave05b58912018-06-05 15:13:39 +00002761 Value, AllowExtendedExpr))
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002762 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002763
Pete Cooper80d21cb2015-06-22 19:35:57 +00002764 if (!Sym) {
2765 // In the case where we parse an expression starting with a '.', we will
2766 // not generate an error, nor will we create a symbol. In this case we
2767 // should just return out.
Anders Waldenborg84809572014-02-17 20:48:32 +00002768 return false;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002769 }
David Majnemer58cb80c2014-12-24 10:27:50 +00002770
Daniel Dunbarae7ac012009-06-29 23:43:14 +00002771 // Do the assignment.
Daniel Dunbarb7b20972009-08-31 08:09:09 +00002772 Out.EmitAssignment(Sym, Value);
Jim Grosbachb7b750d2012-09-13 23:11:31 +00002773 if (NoDeadStrip)
2774 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2775
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002776 return false;
2777}
2778
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002779/// parseIdentifier:
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002780/// ::= identifier
2781/// ::= string
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002782bool AsmParser::parseIdentifier(StringRef &Res) {
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002783 // The assembler has relaxed rules for accepting identifiers, in particular we
Hans Wennborgce69d772013-10-18 20:46:28 +00002784 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2785 // separate tokens. At this level, we have already lexed so we cannot (currently)
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002786 // handle this as a context dependent token, instead we detect adjacent tokens
2787 // and return the combined identifier.
Hans Wennborgce69d772013-10-18 20:46:28 +00002788 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2789 SMLoc PrefixLoc = getLexer().getLoc();
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002790
Hans Wennborgce69d772013-10-18 20:46:28 +00002791 // Consume the prefix character, and check for a following identifier.
Nirav Daved0463322016-10-12 13:58:07 +00002792
2793 AsmToken Buf[1];
2794 Lexer.peekTokens(Buf, false);
2795
2796 if (Buf[0].isNot(AsmToken::Identifier))
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002797 return true;
2798
Hans Wennborgce69d772013-10-18 20:46:28 +00002799 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
Nirav Daved0463322016-10-12 13:58:07 +00002800 if (PrefixLoc.getPointer() + 1 != Buf[0].getLoc().getPointer())
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002801 return true;
2802
Nirav Daved0463322016-10-12 13:58:07 +00002803 // eat $ or @
2804 Lexer.Lex(); // Lexer's Lex guarantees consecutive token.
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002805 // Construct the joined identifier and consume the token.
Jim Grosbach4b905842013-09-20 23:08:21 +00002806 Res =
Hans Wennborgce69d772013-10-18 20:46:28 +00002807 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
Nirav Davefd910412016-06-17 16:06:17 +00002808 Lex(); // Parser Lex to maintain invariants.
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002809 return false;
2810 }
2811
Jim Grosbach4b905842013-09-20 23:08:21 +00002812 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002813 return true;
2814
Sean Callanan936b0d32010-01-19 21:44:56 +00002815 Res = getTok().getIdentifier();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002816
Sean Callanan686ed8d2010-01-19 20:22:31 +00002817 Lex(); // Consume the identifier token.
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002818
2819 return false;
2820}
2821
Jim Grosbach4b905842013-09-20 23:08:21 +00002822/// parseDirectiveSet:
Nico Weber4ada0d92011-01-28 03:04:41 +00002823/// ::= .equ identifier ',' expression
2824/// ::= .equiv identifier ',' expression
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002825/// ::= .set identifier ',' expression
Jim Grosbach4b905842013-09-20 23:08:21 +00002826bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002827 StringRef Name;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002828 if (check(parseIdentifier(Name), "expected identifier") ||
2829 parseToken(AsmToken::Comma) || parseAssignment(Name, allow_redef, true))
2830 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
2831 return false;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002832}
2833
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002834bool AsmParser::parseEscapedString(std::string &Data) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00002835 if (check(getTok().isNot(AsmToken::String), "expected string"))
2836 return true;
Daniel Dunbaref668c12009-08-14 18:19:52 +00002837
2838 Data = "";
Sean Callanan936b0d32010-01-19 21:44:56 +00002839 StringRef Str = getTok().getStringContents();
Daniel Dunbaref668c12009-08-14 18:19:52 +00002840 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2841 if (Str[i] != '\\') {
2842 Data += Str[i];
2843 continue;
2844 }
2845
2846 // Recognize escaped characters. Note that this escape semantics currently
2847 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2848 ++i;
2849 if (i == e)
2850 return TokError("unexpected backslash at end of string");
2851
2852 // Recognize octal sequences.
Jim Grosbach4b905842013-09-20 23:08:21 +00002853 if ((unsigned)(Str[i] - '0') <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002854 // Consume up to three octal characters.
2855 unsigned Value = Str[i] - '0';
2856
Jim Grosbach4b905842013-09-20 23:08:21 +00002857 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002858 ++i;
2859 Value = Value * 8 + (Str[i] - '0');
2860
Jim Grosbach4b905842013-09-20 23:08:21 +00002861 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002862 ++i;
2863 Value = Value * 8 + (Str[i] - '0');
2864 }
2865 }
2866
2867 if (Value > 255)
2868 return TokError("invalid octal escape sequence (out of range)");
2869
Jim Grosbach4b905842013-09-20 23:08:21 +00002870 Data += (unsigned char)Value;
Daniel Dunbaref668c12009-08-14 18:19:52 +00002871 continue;
2872 }
2873
2874 // Otherwise recognize individual escapes.
2875 switch (Str[i]) {
2876 default:
2877 // Just reject invalid escape sequences for now.
2878 return TokError("invalid escape sequence (unrecognized character)");
2879
2880 case 'b': Data += '\b'; break;
2881 case 'f': Data += '\f'; break;
2882 case 'n': Data += '\n'; break;
2883 case 'r': Data += '\r'; break;
2884 case 't': Data += '\t'; break;
2885 case '"': Data += '"'; break;
2886 case '\\': Data += '\\'; break;
2887 }
2888 }
2889
Nirav Davea645433c2016-07-18 15:24:03 +00002890 Lex();
Daniel Dunbaref668c12009-08-14 18:19:52 +00002891 return false;
2892}
2893
Jim Grosbach4b905842013-09-20 23:08:21 +00002894/// parseDirectiveAscii:
Rafael Espindola63760ba2010-10-28 20:02:27 +00002895/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002896bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00002897 auto parseOp = [&]() -> bool {
2898 std::string Data;
2899 if (checkForValidSection() || parseEscapedString(Data))
Nirav Davef43cc9f2016-10-10 15:24:54 +00002900 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002901 getStreamer().EmitBytes(Data);
2902 if (ZeroTerminated)
2903 getStreamer().EmitBytes(StringRef("\0", 1));
2904 return false;
2905 };
Daniel Dunbare5444a82010-09-09 22:42:59 +00002906
Nirav Dave1a9044b2016-10-24 14:35:29 +00002907 if (parseMany(parseOp))
2908 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbara10e5192009-06-24 23:30:00 +00002909 return false;
2910}
2911
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002912/// parseDirectiveReloc
2913/// ::= .reloc expression , identifier [ , expression ]
2914bool AsmParser::parseDirectiveReloc(SMLoc DirectiveLoc) {
2915 const MCExpr *Offset;
2916 const MCExpr *Expr = nullptr;
2917
2918 SMLoc OffsetLoc = Lexer.getTok().getLoc();
Nirav Dave1a9044b2016-10-24 14:35:29 +00002919 int64_t OffsetValue;
2920 // We can only deal with constant expressions at the moment.
2921
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002922 if (parseExpression(Offset))
2923 return true;
2924
Nirav Dave6c0665e2018-04-30 19:22:40 +00002925 if (check(!Offset->evaluateAsAbsolute(OffsetValue,
2926 getStreamer().getAssemblerPtr()),
2927 OffsetLoc, "expression is not a constant value") ||
Nirav Davea645433c2016-07-18 15:24:03 +00002928 check(OffsetValue < 0, OffsetLoc, "expression is negative") ||
2929 parseToken(AsmToken::Comma, "expected comma") ||
2930 check(getTok().isNot(AsmToken::Identifier), "expected relocation name"))
2931 return true;
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002932
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002933 SMLoc NameLoc = Lexer.getTok().getLoc();
2934 StringRef Name = Lexer.getTok().getIdentifier();
Nirav Davefd910412016-06-17 16:06:17 +00002935 Lex();
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002936
2937 if (Lexer.is(AsmToken::Comma)) {
Nirav Davefd910412016-06-17 16:06:17 +00002938 Lex();
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002939 SMLoc ExprLoc = Lexer.getLoc();
2940 if (parseExpression(Expr))
2941 return true;
2942
2943 MCValue Value;
2944 if (!Expr->evaluateAsRelocatable(Value, nullptr, nullptr))
2945 return Error(ExprLoc, "expression must be relocatable");
2946 }
2947
Nirav Davea645433c2016-07-18 15:24:03 +00002948 if (parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00002949 "unexpected token in .reloc directive"))
2950 return true;
2951
2952 if (getStreamer().EmitRelocDirective(*Offset, Name, Expr, DirectiveLoc))
2953 return Error(NameLoc, "unknown relocation name");
2954
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002955 return false;
2956}
2957
Jim Grosbach4b905842013-09-20 23:08:21 +00002958/// parseDirectiveValue
Daniel Dunbara10e5192009-06-24 23:30:00 +00002959/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00002960bool AsmParser::parseDirectiveValue(StringRef IDVal, unsigned Size) {
2961 auto parseOp = [&]() -> bool {
2962 const MCExpr *Value;
2963 SMLoc ExprLoc = getLexer().getLoc();
2964 if (checkForValidSection() || parseExpression(Value))
Nirav Davef43cc9f2016-10-10 15:24:54 +00002965 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002966 // Special case constant expressions to match code generator.
2967 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2968 assert(Size <= 8 && "Invalid size");
2969 uint64_t IntValue = MCE->getValue();
2970 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2971 return Error(ExprLoc, "out of range literal value");
2972 getStreamer().EmitIntValue(IntValue, Size);
2973 } else
2974 getStreamer().EmitValue(Value, Size, ExprLoc);
2975 return false;
2976 };
Daniel Dunbare5444a82010-09-09 22:42:59 +00002977
Nirav Dave1a9044b2016-10-24 14:35:29 +00002978 if (parseMany(parseOp))
2979 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbara10e5192009-06-24 23:30:00 +00002980 return false;
2981}
2982
Paul Robinson01954692018-04-11 15:14:05 +00002983static bool parseHexOcta(AsmParser &Asm, uint64_t &hi, uint64_t &lo) {
2984 if (Asm.getTok().isNot(AsmToken::Integer) &&
2985 Asm.getTok().isNot(AsmToken::BigNum))
2986 return Asm.TokError("unknown token in expression");
2987 SMLoc ExprLoc = Asm.getTok().getLoc();
2988 APInt IntValue = Asm.getTok().getAPIntVal();
2989 Asm.Lex();
2990 if (!IntValue.isIntN(128))
2991 return Asm.Error(ExprLoc, "out of range literal value");
2992 if (!IntValue.isIntN(64)) {
2993 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
2994 lo = IntValue.getLoBits(64).getZExtValue();
2995 } else {
2996 hi = 0;
2997 lo = IntValue.getZExtValue();
2998 }
2999 return false;
3000}
3001
David Woodhoused6de0d92014-02-01 16:20:59 +00003002/// ParseDirectiveOctaValue
3003/// ::= .octa [ hexconstant (, hexconstant)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00003004
3005bool AsmParser::parseDirectiveOctaValue(StringRef IDVal) {
3006 auto parseOp = [&]() -> bool {
Nirav Davef43cc9f2016-10-10 15:24:54 +00003007 if (checkForValidSection())
3008 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003009 uint64_t hi, lo;
Paul Robinson01954692018-04-11 15:14:05 +00003010 if (parseHexOcta(*this, hi, lo))
3011 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003012 if (MAI.isLittleEndian()) {
3013 getStreamer().EmitIntValue(lo, 8);
3014 getStreamer().EmitIntValue(hi, 8);
3015 } else {
3016 getStreamer().EmitIntValue(hi, 8);
3017 getStreamer().EmitIntValue(lo, 8);
3018 }
3019 return false;
3020 };
David Woodhoused6de0d92014-02-01 16:20:59 +00003021
Nirav Dave1a9044b2016-10-24 14:35:29 +00003022 if (parseMany(parseOp))
3023 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
David Woodhoused6de0d92014-02-01 16:20:59 +00003024 return false;
3025}
3026
Petr Hosek4cb08ce2016-09-23 19:25:15 +00003027bool AsmParser::parseRealValue(const fltSemantics &Semantics, APInt &Res) {
3028 // We don't truly support arithmetic on floating point expressions, so we
3029 // have to manually parse unary prefixes.
3030 bool IsNeg = false;
3031 if (getLexer().is(AsmToken::Minus)) {
3032 Lexer.Lex();
3033 IsNeg = true;
3034 } else if (getLexer().is(AsmToken::Plus))
3035 Lexer.Lex();
3036
3037 if (Lexer.is(AsmToken::Error))
3038 return TokError(Lexer.getErr());
3039 if (Lexer.isNot(AsmToken::Integer) && Lexer.isNot(AsmToken::Real) &&
3040 Lexer.isNot(AsmToken::Identifier))
3041 return TokError("unexpected token in directive");
3042
3043 // Convert to an APFloat.
3044 APFloat Value(Semantics);
3045 StringRef IDVal = getTok().getString();
3046 if (getLexer().is(AsmToken::Identifier)) {
3047 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
3048 Value = APFloat::getInf(Semantics);
3049 else if (!IDVal.compare_lower("nan"))
3050 Value = APFloat::getNaN(Semantics, false, ~0);
3051 else
3052 return TokError("invalid floating point literal");
3053 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
3054 APFloat::opInvalidOp)
3055 return TokError("invalid floating point literal");
3056 if (IsNeg)
3057 Value.changeSign();
3058
3059 // Consume the numeric token.
3060 Lex();
3061
3062 Res = Value.bitcastToAPInt();
3063
3064 return false;
3065}
3066
Jim Grosbach4b905842013-09-20 23:08:21 +00003067/// parseDirectiveRealValue
Daniel Dunbar2af16532010-09-24 01:59:56 +00003068/// ::= (.single | .double) [ expression (, expression)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00003069bool AsmParser::parseDirectiveRealValue(StringRef IDVal,
3070 const fltSemantics &Semantics) {
3071 auto parseOp = [&]() -> bool {
3072 APInt AsInt;
3073 if (checkForValidSection() || parseRealValue(Semantics, AsInt))
Nirav Davef43cc9f2016-10-10 15:24:54 +00003074 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003075 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
3076 AsInt.getBitWidth() / 8);
3077 return false;
3078 };
Daniel Dunbar2af16532010-09-24 01:59:56 +00003079
Nirav Dave1a9044b2016-10-24 14:35:29 +00003080 if (parseMany(parseOp))
3081 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbar2af16532010-09-24 01:59:56 +00003082 return false;
3083}
3084
Jim Grosbach4b905842013-09-20 23:08:21 +00003085/// parseDirectiveZero
Rafael Espindola922e3f42010-09-16 15:03:59 +00003086/// ::= .zero expression
Jim Grosbach4b905842013-09-20 23:08:21 +00003087bool AsmParser::parseDirectiveZero() {
Petr Hosek67a94a72016-05-28 05:57:48 +00003088 SMLoc NumBytesLoc = Lexer.getLoc();
3089 const MCExpr *NumBytes;
Nirav Davef43cc9f2016-10-10 15:24:54 +00003090 if (checkForValidSection() || parseExpression(NumBytes))
Rafael Espindola922e3f42010-09-16 15:03:59 +00003091 return true;
3092
Rafael Espindolab91bac62010-10-05 19:42:57 +00003093 int64_t Val = 0;
3094 if (getLexer().is(AsmToken::Comma)) {
3095 Lex();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003096 if (parseAbsoluteExpression(Val))
Rafael Espindolab91bac62010-10-05 19:42:57 +00003097 return true;
3098 }
3099
Nirav Davea645433c2016-07-18 15:24:03 +00003100 if (parseToken(AsmToken::EndOfStatement,
3101 "unexpected token in '.zero' directive"))
3102 return true;
Petr Hosek67a94a72016-05-28 05:57:48 +00003103 getStreamer().emitFill(*NumBytes, Val, NumBytesLoc);
Rafael Espindola922e3f42010-09-16 15:03:59 +00003104
3105 return false;
3106}
3107
Jim Grosbach4b905842013-09-20 23:08:21 +00003108/// parseDirectiveFill
Roman Divackye33098f2013-09-24 17:44:41 +00003109/// ::= .fill expression [ , expression [ , expression ] ]
Jim Grosbach4b905842013-09-20 23:08:21 +00003110bool AsmParser::parseDirectiveFill() {
Petr Hosek67a94a72016-05-28 05:57:48 +00003111 SMLoc NumValuesLoc = Lexer.getLoc();
3112 const MCExpr *NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00003113 if (checkForValidSection() || parseExpression(NumValues))
Daniel Dunbara10e5192009-06-24 23:30:00 +00003114 return true;
3115
Roman Divackye33098f2013-09-24 17:44:41 +00003116 int64_t FillSize = 1;
3117 int64_t FillExpr = 0;
Michael J. Spencer530ce852010-10-09 11:00:50 +00003118
David Majnemer522d3db2014-02-01 07:19:38 +00003119 SMLoc SizeLoc, ExprLoc;
Daniel Dunbara10e5192009-06-24 23:30:00 +00003120
Nirav Dave1a9044b2016-10-24 14:35:29 +00003121 if (parseOptionalToken(AsmToken::Comma)) {
3122 SizeLoc = getTok().getLoc();
3123 if (parseAbsoluteExpression(FillSize))
Roman Divackye33098f2013-09-24 17:44:41 +00003124 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003125 if (parseOptionalToken(AsmToken::Comma)) {
3126 ExprLoc = getTok().getLoc();
3127 if (parseAbsoluteExpression(FillExpr))
Roman Divackye33098f2013-09-24 17:44:41 +00003128 return true;
Roman Divackye33098f2013-09-24 17:44:41 +00003129 }
3130 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003131 if (parseToken(AsmToken::EndOfStatement,
3132 "unexpected token in '.fill' directive"))
3133 return true;
Daniel Dunbara10e5192009-06-24 23:30:00 +00003134
David Majnemer522d3db2014-02-01 07:19:38 +00003135 if (FillSize < 0) {
3136 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
Petr Hosek6abd38b2016-05-28 08:20:08 +00003137 return false;
David Majnemer522d3db2014-02-01 07:19:38 +00003138 }
3139 if (FillSize > 8) {
3140 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
3141 FillSize = 8;
3142 }
Daniel Dunbara10e5192009-06-24 23:30:00 +00003143
David Majnemer522d3db2014-02-01 07:19:38 +00003144 if (!isUInt<32>(FillExpr) && FillSize > 4)
3145 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
3146
Petr Hosek67a94a72016-05-28 05:57:48 +00003147 getStreamer().emitFill(*NumValues, FillSize, FillExpr, NumValuesLoc);
Daniel Dunbara10e5192009-06-24 23:30:00 +00003148
3149 return false;
3150}
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00003151
Jim Grosbach4b905842013-09-20 23:08:21 +00003152/// parseDirectiveOrg
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00003153/// ::= .org expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00003154bool AsmParser::parseDirectiveOrg() {
Daniel Dunbar897ffad2009-08-31 08:09:28 +00003155 const MCExpr *Offset;
Oliver Stannard268f42f2016-12-14 10:43:58 +00003156 SMLoc OffsetLoc = Lexer.getLoc();
Nirav Davef43cc9f2016-10-10 15:24:54 +00003157 if (checkForValidSection() || parseExpression(Offset))
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00003158 return true;
3159
3160 // Parse optional fill expression.
3161 int64_t FillExpr = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003162 if (parseOptionalToken(AsmToken::Comma))
3163 if (parseAbsoluteExpression(FillExpr))
3164 return addErrorSuffix(" in '.org' directive");
3165 if (parseToken(AsmToken::EndOfStatement))
3166 return addErrorSuffix(" in '.org' directive");
Nirav Davea645433c2016-07-18 15:24:03 +00003167
Oliver Stannard268f42f2016-12-14 10:43:58 +00003168 getStreamer().emitValueToOffset(Offset, FillExpr, OffsetLoc);
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00003169 return false;
3170}
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003171
Jim Grosbach4b905842013-09-20 23:08:21 +00003172/// parseDirectiveAlign
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003173/// ::= {.align, ...} expression [ , expression [ , expression ]]
Jim Grosbach4b905842013-09-20 23:08:21 +00003174bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003175 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003176 int64_t Alignment;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003177 SMLoc MaxBytesLoc;
3178 bool HasFillExpr = false;
3179 int64_t FillExpr = 0;
3180 int64_t MaxBytesToFill = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003181
3182 auto parseAlign = [&]() -> bool {
Coby Tayreed483a102017-08-02 17:36:10 +00003183 if (parseAbsoluteExpression(Alignment))
Nirav Davea645433c2016-07-18 15:24:03 +00003184 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003185 if (parseOptionalToken(AsmToken::Comma)) {
3186 // The fill expression can be omitted while specifying a maximum number of
3187 // alignment bytes, e.g:
3188 // .align 3,,4
3189 if (getTok().isNot(AsmToken::Comma)) {
3190 HasFillExpr = true;
3191 if (parseAbsoluteExpression(FillExpr))
3192 return true;
3193 }
3194 if (parseOptionalToken(AsmToken::Comma))
3195 if (parseTokenLoc(MaxBytesLoc) ||
3196 parseAbsoluteExpression(MaxBytesToFill))
3197 return true;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003198 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003199 return parseToken(AsmToken::EndOfStatement);
3200 };
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003201
Coby Tayreed483a102017-08-02 17:36:10 +00003202 if (checkForValidSection())
3203 return addErrorSuffix(" in directive");
3204 // Ignore empty '.p2align' directives for GNU-as compatibility
3205 if (IsPow2 && (ValueSize == 1) && getTok().is(AsmToken::EndOfStatement)) {
3206 Warning(AlignmentLoc, "p2align directive with no operand(s) is ignored");
3207 return parseToken(AsmToken::EndOfStatement);
3208 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003209 if (parseAlign())
3210 return addErrorSuffix(" in directive");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003211
Nirav Dave2364748a2016-09-16 18:30:20 +00003212 // Always emit an alignment here even if we thrown an error.
3213 bool ReturnVal = false;
3214
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003215 // Compute alignment in bytes.
3216 if (IsPow2) {
3217 // FIXME: Diagnose overflow.
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003218 if (Alignment >= 32) {
Nirav Dave2364748a2016-09-16 18:30:20 +00003219 ReturnVal |= Error(AlignmentLoc, "invalid alignment value");
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003220 Alignment = 31;
3221 }
3222
Benjamin Kramer63951ad2009-09-06 09:35:10 +00003223 Alignment = 1ULL << Alignment;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00003224 } else {
Davide Italianocb2da712015-09-08 18:59:47 +00003225 // Reject alignments that aren't either a power of two or zero,
3226 // for gas compatibility. Alignment of zero is silently rounded
3227 // up to one.
3228 if (Alignment == 0)
3229 Alignment = 1;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00003230 if (!isPowerOf2_64(Alignment))
Nirav Dave2364748a2016-09-16 18:30:20 +00003231 ReturnVal |= Error(AlignmentLoc, "alignment must be a power of 2");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003232 }
3233
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003234 // Diagnose non-sensical max bytes to align.
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003235 if (MaxBytesLoc.isValid()) {
3236 if (MaxBytesToFill < 1) {
Nirav Dave2364748a2016-09-16 18:30:20 +00003237 ReturnVal |= Error(MaxBytesLoc,
3238 "alignment directive can never be satisfied in this "
Jim Grosbach4b905842013-09-20 23:08:21 +00003239 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar4abcccb2009-08-21 23:01:53 +00003240 MaxBytesToFill = 0;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003241 }
3242
3243 if (MaxBytesToFill >= Alignment) {
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +00003244 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
Jim Grosbach4b905842013-09-20 23:08:21 +00003245 "has no effect");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003246 MaxBytesToFill = 0;
3247 }
3248 }
3249
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003250 // Check whether we should use optimal code alignment for this .align
3251 // directive.
Eric Christopher445c9522016-10-14 05:47:37 +00003252 const MCSection *Section = getStreamer().getCurrentSectionOnly();
Saleem Abdulrasool7f2f9f42014-03-21 05:13:23 +00003253 assert(Section && "must have section to emit alignment");
3254 bool UseCodeAlign = Section->UseCodeAlign();
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003255 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
3256 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003257 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003258 } else {
Kevin Enderby7f993022010-02-25 18:46:04 +00003259 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnerc2b36752010-07-15 21:19:31 +00003260 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
3261 MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003262 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003263
Nirav Dave2364748a2016-09-16 18:30:20 +00003264 return ReturnVal;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003265}
3266
Jim Grosbach4b905842013-09-20 23:08:21 +00003267/// parseDirectiveFile
Paul Robinson29f5f982018-01-09 23:31:48 +00003268/// ::= .file filename
Scott Linder16c7bda2018-02-23 23:01:06 +00003269/// ::= .file number [directory] filename [md5 checksum] [source source-text]
Jim Grosbach4b905842013-09-20 23:08:21 +00003270bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003271 // FIXME: I'm not sure what this is.
3272 int64_t FileNumber = -1;
Eli Bendersky17233942013-01-15 22:59:42 +00003273 if (getLexer().is(AsmToken::Integer)) {
3274 FileNumber = getTok().getIntVal();
3275 Lex();
3276
Paul Robinsonb271f312018-03-29 17:16:41 +00003277 if (FileNumber < 0)
3278 return TokError("negative file number");
Eli Bendersky17233942013-01-15 22:59:42 +00003279 }
3280
Nirav Davea645433c2016-07-18 15:24:03 +00003281 std::string Path = getTok().getString();
Eli Bendersky17233942013-01-15 22:59:42 +00003282
3283 // Usually the directory and filename together, otherwise just the directory.
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003284 // Allow the strings to have escaped octal character sequence.
Nirav Davea645433c2016-07-18 15:24:03 +00003285 if (check(getTok().isNot(AsmToken::String),
3286 "unexpected token in '.file' directive") ||
3287 parseEscapedString(Path))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003288 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003289
3290 StringRef Directory;
3291 StringRef Filename;
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003292 std::string FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00003293 if (getLexer().is(AsmToken::String)) {
Nirav Davea645433c2016-07-18 15:24:03 +00003294 if (check(FileNumber == -1,
3295 "explicit path specified, but no file number") ||
3296 parseEscapedString(FilenameData))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003297 return true;
3298 Filename = FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00003299 Directory = Path;
Eli Bendersky17233942013-01-15 22:59:42 +00003300 } else {
3301 Filename = Path;
3302 }
3303
Paul Robinson01954692018-04-11 15:14:05 +00003304 uint64_t MD5Hi, MD5Lo;
3305 bool HasMD5 = false;
Scott Linder16c7bda2018-02-23 23:01:06 +00003306
3307 Optional<StringRef> Source;
3308 bool HasSource = false;
3309 std::string SourceString;
3310
3311 while (!parseOptionalToken(AsmToken::EndOfStatement)) {
Paul Robinson29f5f982018-01-09 23:31:48 +00003312 StringRef Keyword;
3313 if (check(getTok().isNot(AsmToken::Identifier),
3314 "unexpected token in '.file' directive") ||
Scott Linder16c7bda2018-02-23 23:01:06 +00003315 parseIdentifier(Keyword))
Paul Robinson29f5f982018-01-09 23:31:48 +00003316 return true;
Scott Linder16c7bda2018-02-23 23:01:06 +00003317 if (Keyword == "md5") {
Paul Robinson01954692018-04-11 15:14:05 +00003318 HasMD5 = true;
Scott Linder16c7bda2018-02-23 23:01:06 +00003319 if (check(FileNumber == -1,
3320 "MD5 checksum specified, but no file number") ||
Paul Robinson01954692018-04-11 15:14:05 +00003321 parseHexOcta(*this, MD5Hi, MD5Lo))
Scott Linder16c7bda2018-02-23 23:01:06 +00003322 return true;
3323 } else if (Keyword == "source") {
3324 HasSource = true;
3325 if (check(FileNumber == -1,
3326 "source specified, but no file number") ||
3327 check(getTok().isNot(AsmToken::String),
3328 "unexpected token in '.file' directive") ||
3329 parseEscapedString(SourceString))
3330 return true;
3331 } else {
3332 return TokError("unexpected token in '.file' directive");
3333 }
Paul Robinson29f5f982018-01-09 23:31:48 +00003334 }
Eli Bendersky17233942013-01-15 22:59:42 +00003335
Paul Robinson938d9a02018-03-22 15:48:01 +00003336 // In case there is a -g option as well as debug info from directive .file,
3337 // we turn off the -g option, directly use the existing debug info instead.
3338 getContext().setGenDwarfForAssembly(false);
3339
Eli Bendersky17233942013-01-15 22:59:42 +00003340 if (FileNumber == -1)
3341 getStreamer().EmitFileDirective(Filename);
3342 else {
Paul Robinson29f5f982018-01-09 23:31:48 +00003343 MD5::MD5Result *CKMem = nullptr;
Paul Robinson01954692018-04-11 15:14:05 +00003344 if (HasMD5) {
Paul Robinson29f5f982018-01-09 23:31:48 +00003345 CKMem = (MD5::MD5Result *)Ctx.allocate(sizeof(MD5::MD5Result), 1);
Paul Robinson01954692018-04-11 15:14:05 +00003346 for (unsigned i = 0; i != 8; ++i) {
3347 CKMem->Bytes[i] = uint8_t(MD5Hi >> ((7 - i) * 8));
3348 CKMem->Bytes[i + 8] = uint8_t(MD5Lo >> ((7 - i) * 8));
3349 }
Paul Robinson29f5f982018-01-09 23:31:48 +00003350 }
Scott Linder16c7bda2018-02-23 23:01:06 +00003351 if (HasSource) {
3352 char *SourceBuf = static_cast<char *>(Ctx.allocate(SourceString.size()));
3353 memcpy(SourceBuf, SourceString.data(), SourceString.size());
3354 Source = StringRef(SourceBuf, SourceString.size());
3355 }
Paul Robinsonb271f312018-03-29 17:16:41 +00003356 if (FileNumber == 0)
3357 getStreamer().emitDwarfFile0Directive(Directory, Filename, CKMem, Source);
3358 else {
3359 Expected<unsigned> FileNumOrErr = getStreamer().tryEmitDwarfFileDirective(
3360 FileNumber, Directory, Filename, CKMem, Source);
3361 if (!FileNumOrErr)
3362 return Error(DirectiveLoc, toString(FileNumOrErr.takeError()));
3363 FileNumber = FileNumOrErr.get();
3364 }
Eli Bendersky17233942013-01-15 22:59:42 +00003365 }
3366
3367 return false;
3368}
3369
Jim Grosbach4b905842013-09-20 23:08:21 +00003370/// parseDirectiveLine
Eli Bendersky17233942013-01-15 22:59:42 +00003371/// ::= .line [number]
Jim Grosbach4b905842013-09-20 23:08:21 +00003372bool AsmParser::parseDirectiveLine() {
Nirav Davea645433c2016-07-18 15:24:03 +00003373 int64_t LineNumber;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003374 if (getLexer().is(AsmToken::Integer)) {
Nirav Davea645433c2016-07-18 15:24:03 +00003375 if (parseIntToken(LineNumber, "unexpected token in '.line' directive"))
3376 return true;
Jim Grosbach4b905842013-09-20 23:08:21 +00003377 (void)LineNumber;
Eli Bendersky17233942013-01-15 22:59:42 +00003378 // FIXME: Do something with the .line.
3379 }
Nirav Davea645433c2016-07-18 15:24:03 +00003380 if (parseToken(AsmToken::EndOfStatement,
3381 "unexpected token in '.line' directive"))
3382 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003383
3384 return false;
3385}
3386
Jim Grosbach4b905842013-09-20 23:08:21 +00003387/// parseDirectiveLoc
Eli Bendersky17233942013-01-15 22:59:42 +00003388/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
3389/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
3390/// The first number is a file number, must have been previously assigned with
3391/// a .file directive, the second number is the line number and optionally the
3392/// third number is a column position (zero if not specified). The remaining
3393/// optional items are .loc sub-directives.
Jim Grosbach4b905842013-09-20 23:08:21 +00003394bool AsmParser::parseDirectiveLoc() {
Nirav Davea645433c2016-07-18 15:24:03 +00003395 int64_t FileNumber = 0, LineNumber = 0;
3396 SMLoc Loc = getTok().getLoc();
3397 if (parseIntToken(FileNumber, "unexpected token in '.loc' directive") ||
3398 check(FileNumber < 1, Loc,
3399 "file number less than one in '.loc' directive") ||
3400 check(!getContext().isValidDwarfFileNumber(FileNumber), Loc,
3401 "unassigned file number in '.loc' directive"))
3402 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003403
Nirav Davea645433c2016-07-18 15:24:03 +00003404 // optional
Eli Bendersky17233942013-01-15 22:59:42 +00003405 if (getLexer().is(AsmToken::Integer)) {
3406 LineNumber = getTok().getIntVal();
Adrian Prantl6ac40032013-09-26 23:37:11 +00003407 if (LineNumber < 0)
3408 return TokError("line number less than zero in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003409 Lex();
3410 }
3411
3412 int64_t ColumnPos = 0;
3413 if (getLexer().is(AsmToken::Integer)) {
3414 ColumnPos = getTok().getIntVal();
3415 if (ColumnPos < 0)
3416 return TokError("column position less than zero in '.loc' directive");
3417 Lex();
3418 }
3419
3420 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
3421 unsigned Isa = 0;
3422 int64_t Discriminator = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003423
Nirav Dave1a9044b2016-10-24 14:35:29 +00003424 auto parseLocOp = [&]() -> bool {
3425 StringRef Name;
3426 SMLoc Loc = getTok().getLoc();
3427 if (parseIdentifier(Name))
3428 return TokError("unexpected token in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003429
Nirav Dave1a9044b2016-10-24 14:35:29 +00003430 if (Name == "basic_block")
3431 Flags |= DWARF2_FLAG_BASIC_BLOCK;
3432 else if (Name == "prologue_end")
3433 Flags |= DWARF2_FLAG_PROLOGUE_END;
3434 else if (Name == "epilogue_begin")
3435 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
3436 else if (Name == "is_stmt") {
3437 Loc = getTok().getLoc();
3438 const MCExpr *Value;
3439 if (parseExpression(Value))
3440 return true;
3441 // The expression must be the constant 0 or 1.
3442 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3443 int Value = MCE->getValue();
3444 if (Value == 0)
3445 Flags &= ~DWARF2_FLAG_IS_STMT;
3446 else if (Value == 1)
3447 Flags |= DWARF2_FLAG_IS_STMT;
3448 else
3449 return Error(Loc, "is_stmt value not 0 or 1");
Craig Topperf15655b2013-04-22 04:22:40 +00003450 } else {
Nirav Dave1a9044b2016-10-24 14:35:29 +00003451 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
Eli Bendersky17233942013-01-15 22:59:42 +00003452 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003453 } else if (Name == "isa") {
3454 Loc = getTok().getLoc();
3455 const MCExpr *Value;
3456 if (parseExpression(Value))
3457 return true;
3458 // The expression must be a constant greater or equal to 0.
3459 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3460 int Value = MCE->getValue();
3461 if (Value < 0)
3462 return Error(Loc, "isa number less than zero");
3463 Isa = Value;
3464 } else {
3465 return Error(Loc, "isa number not a constant value");
3466 }
3467 } else if (Name == "discriminator") {
3468 if (parseAbsoluteExpression(Discriminator))
3469 return true;
3470 } else {
3471 return Error(Loc, "unknown sub-directive in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003472 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003473 return false;
3474 };
3475
Nirav Davee2369aa2016-10-26 17:28:58 +00003476 if (parseMany(parseLocOp, false /*hasComma*/))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003477 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003478
3479 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
3480 Isa, Discriminator, StringRef());
3481
3482 return false;
3483}
3484
Jim Grosbach4b905842013-09-20 23:08:21 +00003485/// parseDirectiveStabs
Eli Bendersky17233942013-01-15 22:59:42 +00003486/// ::= .stabs string, number, number, number
Jim Grosbach4b905842013-09-20 23:08:21 +00003487bool AsmParser::parseDirectiveStabs() {
Eli Bendersky17233942013-01-15 22:59:42 +00003488 return TokError("unsupported directive '.stabs'");
3489}
3490
Reid Kleckner2214ed82016-01-29 00:49:42 +00003491/// parseDirectiveCVFile
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003492/// ::= .cv_file number filename [checksum] [checksumkind]
Reid Kleckner2214ed82016-01-29 00:49:42 +00003493bool AsmParser::parseDirectiveCVFile() {
Nirav Davea645433c2016-07-18 15:24:03 +00003494 SMLoc FileNumberLoc = getTok().getLoc();
3495 int64_t FileNumber;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003496 std::string Filename;
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003497 std::string Checksum;
3498 int64_t ChecksumKind = 0;
Nirav Davea645433c2016-07-18 15:24:03 +00003499
3500 if (parseIntToken(FileNumber,
3501 "expected file number in '.cv_file' directive") ||
3502 check(FileNumber < 1, FileNumberLoc, "file number less than one") ||
3503 check(getTok().isNot(AsmToken::String),
3504 "unexpected token in '.cv_file' directive") ||
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003505 parseEscapedString(Filename))
Reid Klecknera5b1eef2016-08-26 17:58:37 +00003506 return true;
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003507 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
3508 if (check(getTok().isNot(AsmToken::String),
3509 "unexpected token in '.cv_file' directive") ||
3510 parseEscapedString(Checksum) ||
3511 parseIntToken(ChecksumKind,
3512 "expected checksum kind in '.cv_file' directive") ||
3513 parseToken(AsmToken::EndOfStatement,
3514 "unexpected token in '.cv_file' directive"))
3515 return true;
3516 }
Nirav Dave1ab71992016-07-18 19:35:21 +00003517
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003518 Checksum = fromHex(Checksum);
3519 void *CKMem = Ctx.allocate(Checksum.size(), 1);
3520 memcpy(CKMem, Checksum.data(), Checksum.size());
3521 ArrayRef<uint8_t> ChecksumAsBytes(reinterpret_cast<const uint8_t *>(CKMem),
3522 Checksum.size());
3523
3524 if (!getStreamer().EmitCVFileDirective(FileNumber, Filename, ChecksumAsBytes,
3525 static_cast<uint8_t>(ChecksumKind)))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003526 return Error(FileNumberLoc, "file number already allocated");
Reid Kleckner2214ed82016-01-29 00:49:42 +00003527
3528 return false;
3529}
3530
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003531bool AsmParser::parseCVFunctionId(int64_t &FunctionId,
3532 StringRef DirectiveName) {
3533 SMLoc Loc;
3534 return parseTokenLoc(Loc) ||
3535 parseIntToken(FunctionId, "expected function id in '" + DirectiveName +
3536 "' directive") ||
3537 check(FunctionId < 0 || FunctionId >= UINT_MAX, Loc,
3538 "expected function id within range [0, UINT_MAX)");
3539}
3540
3541bool AsmParser::parseCVFileId(int64_t &FileNumber, StringRef DirectiveName) {
3542 SMLoc Loc;
3543 return parseTokenLoc(Loc) ||
3544 parseIntToken(FileNumber, "expected integer in '" + DirectiveName +
3545 "' directive") ||
3546 check(FileNumber < 1, Loc, "file number less than one in '" +
3547 DirectiveName + "' directive") ||
3548 check(!getCVContext().isValidFileNumber(FileNumber), Loc,
3549 "unassigned file number in '" + DirectiveName + "' directive");
3550}
3551
3552/// parseDirectiveCVFuncId
3553/// ::= .cv_func_id FunctionId
3554///
3555/// Introduces a function ID that can be used with .cv_loc.
3556bool AsmParser::parseDirectiveCVFuncId() {
3557 SMLoc FunctionIdLoc = getTok().getLoc();
3558 int64_t FunctionId;
3559
3560 if (parseCVFunctionId(FunctionId, ".cv_func_id") ||
3561 parseToken(AsmToken::EndOfStatement,
3562 "unexpected token in '.cv_func_id' directive"))
3563 return true;
3564
3565 if (!getStreamer().EmitCVFuncIdDirective(FunctionId))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003566 return Error(FunctionIdLoc, "function id already allocated");
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003567
3568 return false;
3569}
3570
3571/// parseDirectiveCVInlineSiteId
3572/// ::= .cv_inline_site_id FunctionId
3573/// "within" IAFunc
3574/// "inlined_at" IAFile IALine [IACol]
3575///
3576/// Introduces a function ID that can be used with .cv_loc. Includes "inlined
3577/// at" source location information for use in the line table of the caller,
3578/// whether the caller is a real function or another inlined call site.
3579bool AsmParser::parseDirectiveCVInlineSiteId() {
3580 SMLoc FunctionIdLoc = getTok().getLoc();
3581 int64_t FunctionId;
3582 int64_t IAFunc;
3583 int64_t IAFile;
3584 int64_t IALine;
3585 int64_t IACol = 0;
3586
3587 // FunctionId
3588 if (parseCVFunctionId(FunctionId, ".cv_inline_site_id"))
3589 return true;
3590
3591 // "within"
3592 if (check((getLexer().isNot(AsmToken::Identifier) ||
3593 getTok().getIdentifier() != "within"),
3594 "expected 'within' identifier in '.cv_inline_site_id' directive"))
3595 return true;
3596 Lex();
3597
3598 // IAFunc
3599 if (parseCVFunctionId(IAFunc, ".cv_inline_site_id"))
3600 return true;
3601
3602 // "inlined_at"
3603 if (check((getLexer().isNot(AsmToken::Identifier) ||
3604 getTok().getIdentifier() != "inlined_at"),
3605 "expected 'inlined_at' identifier in '.cv_inline_site_id' "
3606 "directive") )
3607 return true;
3608 Lex();
3609
3610 // IAFile IALine
3611 if (parseCVFileId(IAFile, ".cv_inline_site_id") ||
3612 parseIntToken(IALine, "expected line number after 'inlined_at'"))
3613 return true;
3614
3615 // [IACol]
3616 if (getLexer().is(AsmToken::Integer)) {
3617 IACol = getTok().getIntVal();
3618 Lex();
3619 }
3620
3621 if (parseToken(AsmToken::EndOfStatement,
3622 "unexpected token in '.cv_inline_site_id' directive"))
3623 return true;
3624
3625 if (!getStreamer().EmitCVInlineSiteIdDirective(FunctionId, IAFunc, IAFile,
3626 IALine, IACol, FunctionIdLoc))
Nirav Dave2364748a2016-09-16 18:30:20 +00003627 return Error(FunctionIdLoc, "function id already allocated");
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003628
3629 return false;
3630}
3631
Reid Kleckner2214ed82016-01-29 00:49:42 +00003632/// parseDirectiveCVLoc
3633/// ::= .cv_loc FunctionId FileNumber [LineNumber] [ColumnPos] [prologue_end]
3634/// [is_stmt VALUE]
3635/// The first number is a file number, must have been previously assigned with
3636/// a .file directive, the second number is the line number and optionally the
3637/// third number is a column position (zero if not specified). The remaining
3638/// optional items are .loc sub-directives.
3639bool AsmParser::parseDirectiveCVLoc() {
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003640 SMLoc DirectiveLoc = getTok().getLoc();
Nirav Davea645433c2016-07-18 15:24:03 +00003641 int64_t FunctionId, FileNumber;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003642 if (parseCVFunctionId(FunctionId, ".cv_loc") ||
3643 parseCVFileId(FileNumber, ".cv_loc"))
Nirav Davea645433c2016-07-18 15:24:03 +00003644 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003645
3646 int64_t LineNumber = 0;
3647 if (getLexer().is(AsmToken::Integer)) {
3648 LineNumber = getTok().getIntVal();
3649 if (LineNumber < 0)
3650 return TokError("line number less than zero in '.cv_loc' directive");
3651 Lex();
3652 }
3653
3654 int64_t ColumnPos = 0;
3655 if (getLexer().is(AsmToken::Integer)) {
3656 ColumnPos = getTok().getIntVal();
3657 if (ColumnPos < 0)
3658 return TokError("column position less than zero in '.cv_loc' directive");
3659 Lex();
3660 }
3661
3662 bool PrologueEnd = false;
3663 uint64_t IsStmt = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003664
3665 auto parseOp = [&]() -> bool {
Reid Kleckner2214ed82016-01-29 00:49:42 +00003666 StringRef Name;
3667 SMLoc Loc = getTok().getLoc();
3668 if (parseIdentifier(Name))
3669 return TokError("unexpected token in '.cv_loc' directive");
Reid Kleckner2214ed82016-01-29 00:49:42 +00003670 if (Name == "prologue_end")
3671 PrologueEnd = true;
3672 else if (Name == "is_stmt") {
3673 Loc = getTok().getLoc();
3674 const MCExpr *Value;
3675 if (parseExpression(Value))
3676 return true;
3677 // The expression must be the constant 0 or 1.
3678 IsStmt = ~0ULL;
3679 if (const auto *MCE = dyn_cast<MCConstantExpr>(Value))
3680 IsStmt = MCE->getValue();
3681
3682 if (IsStmt > 1)
3683 return Error(Loc, "is_stmt value not 0 or 1");
3684 } else {
3685 return Error(Loc, "unknown sub-directive in '.cv_loc' directive");
3686 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003687 return false;
3688 };
3689
3690 if (parseMany(parseOp, false /*hasComma*/))
3691 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003692
3693 getStreamer().EmitCVLocDirective(FunctionId, FileNumber, LineNumber,
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003694 ColumnPos, PrologueEnd, IsStmt, StringRef(),
3695 DirectiveLoc);
Reid Kleckner2214ed82016-01-29 00:49:42 +00003696 return false;
3697}
3698
3699/// parseDirectiveCVLinetable
3700/// ::= .cv_linetable FunctionId, FnStart, FnEnd
3701bool AsmParser::parseDirectiveCVLinetable() {
Nirav Davea645433c2016-07-18 15:24:03 +00003702 int64_t FunctionId;
3703 StringRef FnStartName, FnEndName;
3704 SMLoc Loc = getTok().getLoc();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003705 if (parseCVFunctionId(FunctionId, ".cv_linetable") ||
Nirav Davea645433c2016-07-18 15:24:03 +00003706 parseToken(AsmToken::Comma,
3707 "unexpected token in '.cv_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003708 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3709 "expected identifier in directive") ||
Nirav Davea645433c2016-07-18 15:24:03 +00003710 parseToken(AsmToken::Comma,
3711 "unexpected token in '.cv_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003712 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3713 "expected identifier in directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00003714 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003715
3716 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3717 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
3718
3719 getStreamer().EmitCVLinetableDirective(FunctionId, FnStartSym, FnEndSym);
3720 return false;
3721}
3722
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003723/// parseDirectiveCVInlineLinetable
David Majnemerc9911f22016-02-02 19:22:34 +00003724/// ::= .cv_inline_linetable PrimaryFunctionId FileId LineNum FnStart FnEnd
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003725bool AsmParser::parseDirectiveCVInlineLinetable() {
Nirav Davea645433c2016-07-18 15:24:03 +00003726 int64_t PrimaryFunctionId, SourceFileId, SourceLineNum;
3727 StringRef FnStartName, FnEndName;
3728 SMLoc Loc = getTok().getLoc();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003729 if (parseCVFunctionId(PrimaryFunctionId, ".cv_inline_linetable") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003730 parseTokenLoc(Loc) ||
Nirav Davea645433c2016-07-18 15:24:03 +00003731 parseIntToken(
3732 SourceFileId,
3733 "expected SourceField in '.cv_inline_linetable' directive") ||
3734 check(SourceFileId <= 0, Loc,
3735 "File id less than zero in '.cv_inline_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003736 parseTokenLoc(Loc) ||
Nirav Davea645433c2016-07-18 15:24:03 +00003737 parseIntToken(
3738 SourceLineNum,
3739 "expected SourceLineNum in '.cv_inline_linetable' directive") ||
3740 check(SourceLineNum < 0, Loc,
3741 "Line number less than zero in '.cv_inline_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003742 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3743 "expected identifier in directive") ||
3744 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3745 "expected identifier in directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00003746 return true;
David Majnemerc9911f22016-02-02 19:22:34 +00003747
Nirav Davea645433c2016-07-18 15:24:03 +00003748 if (parseToken(AsmToken::EndOfStatement, "Expected End of Statement"))
3749 return true;
3750
3751 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3752 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
Reid Kleckner1fcd6102016-02-02 17:41:18 +00003753 getStreamer().EmitCVInlineLinetableDirective(PrimaryFunctionId, SourceFileId,
3754 SourceLineNum, FnStartSym,
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003755 FnEndSym);
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003756 return false;
3757}
3758
David Majnemer408b5e62016-02-05 01:55:49 +00003759/// parseDirectiveCVDefRange
3760/// ::= .cv_def_range RangeStart RangeEnd (GapStart GapEnd)*, bytes*
3761bool AsmParser::parseDirectiveCVDefRange() {
3762 SMLoc Loc;
3763 std::vector<std::pair<const MCSymbol *, const MCSymbol *>> Ranges;
3764 while (getLexer().is(AsmToken::Identifier)) {
3765 Loc = getLexer().getLoc();
3766 StringRef GapStartName;
3767 if (parseIdentifier(GapStartName))
3768 return Error(Loc, "expected identifier in directive");
3769 MCSymbol *GapStartSym = getContext().getOrCreateSymbol(GapStartName);
3770
3771 Loc = getLexer().getLoc();
3772 StringRef GapEndName;
3773 if (parseIdentifier(GapEndName))
3774 return Error(Loc, "expected identifier in directive");
3775 MCSymbol *GapEndSym = getContext().getOrCreateSymbol(GapEndName);
3776
3777 Ranges.push_back({GapStartSym, GapEndSym});
3778 }
3779
David Majnemer408b5e62016-02-05 01:55:49 +00003780 std::string FixedSizePortion;
Nirav Davea645433c2016-07-18 15:24:03 +00003781 if (parseToken(AsmToken::Comma, "unexpected token in directive") ||
3782 parseEscapedString(FixedSizePortion))
David Majnemer408b5e62016-02-05 01:55:49 +00003783 return true;
David Majnemer408b5e62016-02-05 01:55:49 +00003784
3785 getStreamer().EmitCVDefRangeDirective(Ranges, FixedSizePortion);
3786 return false;
3787}
3788
Reid Kleckner2214ed82016-01-29 00:49:42 +00003789/// parseDirectiveCVStringTable
3790/// ::= .cv_stringtable
3791bool AsmParser::parseDirectiveCVStringTable() {
3792 getStreamer().EmitCVStringTableDirective();
3793 return false;
3794}
3795
3796/// parseDirectiveCVFileChecksums
3797/// ::= .cv_filechecksums
3798bool AsmParser::parseDirectiveCVFileChecksums() {
3799 getStreamer().EmitCVFileChecksumsDirective();
3800 return false;
3801}
3802
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00003803/// parseDirectiveCVFileChecksumOffset
3804/// ::= .cv_filechecksumoffset fileno
3805bool AsmParser::parseDirectiveCVFileChecksumOffset() {
3806 int64_t FileNo;
3807 if (parseIntToken(FileNo, "expected identifier in directive"))
3808 return true;
3809 if (parseToken(AsmToken::EndOfStatement, "Expected End of Statement"))
3810 return true;
3811 getStreamer().EmitCVFileChecksumOffsetDirective(FileNo);
3812 return false;
3813}
3814
Reid Kleckner9cdd4df2017-10-11 21:24:33 +00003815/// parseDirectiveCVFPOData
3816/// ::= .cv_fpo_data procsym
3817bool AsmParser::parseDirectiveCVFPOData() {
3818 SMLoc DirLoc = getLexer().getLoc();
3819 StringRef ProcName;
3820 if (parseIdentifier(ProcName))
3821 return TokError("expected symbol name");
3822 if (parseEOL("unexpected tokens"))
3823 return addErrorSuffix(" in '.cv_fpo_data' directive");
3824 MCSymbol *ProcSym = getContext().getOrCreateSymbol(ProcName);
3825 getStreamer().EmitCVFPOData(ProcSym, DirLoc);
3826 return false;
3827}
3828
Jim Grosbach4b905842013-09-20 23:08:21 +00003829/// parseDirectiveCFISections
Eli Bendersky17233942013-01-15 22:59:42 +00003830/// ::= .cfi_sections section [, section]
Jim Grosbach4b905842013-09-20 23:08:21 +00003831bool AsmParser::parseDirectiveCFISections() {
Eli Bendersky17233942013-01-15 22:59:42 +00003832 StringRef Name;
3833 bool EH = false;
3834 bool Debug = false;
3835
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003836 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003837 return TokError("Expected an identifier");
3838
3839 if (Name == ".eh_frame")
3840 EH = true;
3841 else if (Name == ".debug_frame")
3842 Debug = true;
3843
3844 if (getLexer().is(AsmToken::Comma)) {
3845 Lex();
3846
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003847 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003848 return TokError("Expected an identifier");
3849
3850 if (Name == ".eh_frame")
3851 EH = true;
3852 else if (Name == ".debug_frame")
3853 Debug = true;
3854 }
3855
3856 getStreamer().EmitCFISections(EH, Debug);
3857 return false;
3858}
3859
Jim Grosbach4b905842013-09-20 23:08:21 +00003860/// parseDirectiveCFIStartProc
David Majnemere035cf92014-01-27 17:20:25 +00003861/// ::= .cfi_startproc [simple]
Jim Grosbach4b905842013-09-20 23:08:21 +00003862bool AsmParser::parseDirectiveCFIStartProc() {
David Majnemere035cf92014-01-27 17:20:25 +00003863 StringRef Simple;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003864 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
3865 if (check(parseIdentifier(Simple) || Simple != "simple",
3866 "unexpected token") ||
3867 parseToken(AsmToken::EndOfStatement))
3868 return addErrorSuffix(" in '.cfi_startproc' directive");
3869 }
Nirav Davea645433c2016-07-18 15:24:03 +00003870
Oliver Stannardcf6bfb12014-11-03 12:19:03 +00003871 getStreamer().EmitCFIStartProc(!Simple.empty());
Eli Bendersky17233942013-01-15 22:59:42 +00003872 return false;
3873}
3874
Jim Grosbach4b905842013-09-20 23:08:21 +00003875/// parseDirectiveCFIEndProc
Eli Bendersky17233942013-01-15 22:59:42 +00003876/// ::= .cfi_endproc
Jim Grosbach4b905842013-09-20 23:08:21 +00003877bool AsmParser::parseDirectiveCFIEndProc() {
Eli Bendersky17233942013-01-15 22:59:42 +00003878 getStreamer().EmitCFIEndProc();
3879 return false;
3880}
3881
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003882/// parse register name or number.
Jim Grosbach4b905842013-09-20 23:08:21 +00003883bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
Eli Bendersky17233942013-01-15 22:59:42 +00003884 SMLoc DirectiveLoc) {
3885 unsigned RegNo;
3886
3887 if (getLexer().isNot(AsmToken::Integer)) {
3888 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
3889 return true;
Bill Wendlingbc07a892013-06-18 07:20:20 +00003890 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
Eli Bendersky17233942013-01-15 22:59:42 +00003891 } else
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003892 return parseAbsoluteExpression(Register);
Eli Bendersky17233942013-01-15 22:59:42 +00003893
3894 return false;
3895}
3896
Jim Grosbach4b905842013-09-20 23:08:21 +00003897/// parseDirectiveCFIDefCfa
Eli Bendersky17233942013-01-15 22:59:42 +00003898/// ::= .cfi_def_cfa register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003899bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003900 int64_t Register = 0, Offset = 0;
3901 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3902 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3903 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003904 return true;
3905
3906 getStreamer().EmitCFIDefCfa(Register, Offset);
3907 return false;
3908}
3909
Jim Grosbach4b905842013-09-20 23:08:21 +00003910/// parseDirectiveCFIDefCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003911/// ::= .cfi_def_cfa_offset offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003912bool AsmParser::parseDirectiveCFIDefCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00003913 int64_t Offset = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003914 if (parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003915 return true;
3916
3917 getStreamer().EmitCFIDefCfaOffset(Offset);
3918 return false;
3919}
3920
Jim Grosbach4b905842013-09-20 23:08:21 +00003921/// parseDirectiveCFIRegister
Eli Bendersky17233942013-01-15 22:59:42 +00003922/// ::= .cfi_register register, register
Jim Grosbach4b905842013-09-20 23:08:21 +00003923bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003924 int64_t Register1 = 0, Register2 = 0;
3925 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc) ||
3926 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3927 parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003928 return true;
3929
3930 getStreamer().EmitCFIRegister(Register1, Register2);
3931 return false;
3932}
3933
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00003934/// parseDirectiveCFIWindowSave
3935/// ::= .cfi_window_save
3936bool AsmParser::parseDirectiveCFIWindowSave() {
3937 getStreamer().EmitCFIWindowSave();
3938 return false;
3939}
3940
Jim Grosbach4b905842013-09-20 23:08:21 +00003941/// parseDirectiveCFIAdjustCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003942/// ::= .cfi_adjust_cfa_offset adjustment
Jim Grosbach4b905842013-09-20 23:08:21 +00003943bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00003944 int64_t Adjustment = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003945 if (parseAbsoluteExpression(Adjustment))
Eli Bendersky17233942013-01-15 22:59:42 +00003946 return true;
3947
3948 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3949 return false;
3950}
3951
Jim Grosbach4b905842013-09-20 23:08:21 +00003952/// parseDirectiveCFIDefCfaRegister
Eli Bendersky17233942013-01-15 22:59:42 +00003953/// ::= .cfi_def_cfa_register register
Jim Grosbach4b905842013-09-20 23:08:21 +00003954bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003955 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003956 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003957 return true;
3958
3959 getStreamer().EmitCFIDefCfaRegister(Register);
3960 return false;
3961}
3962
Jim Grosbach4b905842013-09-20 23:08:21 +00003963/// parseDirectiveCFIOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003964/// ::= .cfi_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003965bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003966 int64_t Register = 0;
3967 int64_t Offset = 0;
3968
Nirav Davea645433c2016-07-18 15:24:03 +00003969 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3970 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3971 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003972 return true;
3973
3974 getStreamer().EmitCFIOffset(Register, Offset);
3975 return false;
3976}
3977
Jim Grosbach4b905842013-09-20 23:08:21 +00003978/// parseDirectiveCFIRelOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003979/// ::= .cfi_rel_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003980bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003981 int64_t Register = 0, Offset = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003982
Nirav Davea645433c2016-07-18 15:24:03 +00003983 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3984 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3985 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003986 return true;
3987
3988 getStreamer().EmitCFIRelOffset(Register, Offset);
3989 return false;
3990}
3991
3992static bool isValidEncoding(int64_t Encoding) {
3993 if (Encoding & ~0xff)
3994 return false;
3995
3996 if (Encoding == dwarf::DW_EH_PE_omit)
3997 return true;
3998
3999 const unsigned Format = Encoding & 0xf;
4000 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
4001 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
4002 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
4003 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
4004 return false;
4005
4006 const unsigned Application = Encoding & 0x70;
4007 if (Application != dwarf::DW_EH_PE_absptr &&
4008 Application != dwarf::DW_EH_PE_pcrel)
4009 return false;
4010
4011 return true;
4012}
4013
Jim Grosbach4b905842013-09-20 23:08:21 +00004014/// parseDirectiveCFIPersonalityOrLsda
Eli Bendersky17233942013-01-15 22:59:42 +00004015/// IsPersonality true for cfi_personality, false for cfi_lsda
4016/// ::= .cfi_personality encoding, [symbol_name]
4017/// ::= .cfi_lsda encoding, [symbol_name]
Jim Grosbach4b905842013-09-20 23:08:21 +00004018bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
Eli Bendersky17233942013-01-15 22:59:42 +00004019 int64_t Encoding = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004020 if (parseAbsoluteExpression(Encoding))
Eli Bendersky17233942013-01-15 22:59:42 +00004021 return true;
4022 if (Encoding == dwarf::DW_EH_PE_omit)
4023 return false;
4024
Eli Bendersky17233942013-01-15 22:59:42 +00004025 StringRef Name;
Nirav Davea645433c2016-07-18 15:24:03 +00004026 if (check(!isValidEncoding(Encoding), "unsupported encoding.") ||
4027 parseToken(AsmToken::Comma, "unexpected token in directive") ||
4028 check(parseIdentifier(Name), "expected identifier in directive"))
4029 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004030
Jim Grosbach6f482002015-05-18 18:43:14 +00004031 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Eli Bendersky17233942013-01-15 22:59:42 +00004032
4033 if (IsPersonality)
4034 getStreamer().EmitCFIPersonality(Sym, Encoding);
4035 else
4036 getStreamer().EmitCFILsda(Sym, Encoding);
4037 return false;
4038}
4039
Jim Grosbach4b905842013-09-20 23:08:21 +00004040/// parseDirectiveCFIRememberState
Eli Bendersky17233942013-01-15 22:59:42 +00004041/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00004042bool AsmParser::parseDirectiveCFIRememberState() {
Eli Bendersky17233942013-01-15 22:59:42 +00004043 getStreamer().EmitCFIRememberState();
4044 return false;
4045}
4046
Jim Grosbach4b905842013-09-20 23:08:21 +00004047/// parseDirectiveCFIRestoreState
Eli Bendersky17233942013-01-15 22:59:42 +00004048/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00004049bool AsmParser::parseDirectiveCFIRestoreState() {
Eli Bendersky17233942013-01-15 22:59:42 +00004050 getStreamer().EmitCFIRestoreState();
4051 return false;
4052}
4053
Jim Grosbach4b905842013-09-20 23:08:21 +00004054/// parseDirectiveCFISameValue
Eli Bendersky17233942013-01-15 22:59:42 +00004055/// ::= .cfi_same_value register
Jim Grosbach4b905842013-09-20 23:08:21 +00004056bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004057 int64_t Register = 0;
4058
Jim Grosbach4b905842013-09-20 23:08:21 +00004059 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00004060 return true;
4061
4062 getStreamer().EmitCFISameValue(Register);
4063 return false;
4064}
4065
Jim Grosbach4b905842013-09-20 23:08:21 +00004066/// parseDirectiveCFIRestore
Eli Bendersky17233942013-01-15 22:59:42 +00004067/// ::= .cfi_restore register
Jim Grosbach4b905842013-09-20 23:08:21 +00004068bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004069 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00004070 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00004071 return true;
4072
4073 getStreamer().EmitCFIRestore(Register);
4074 return false;
4075}
4076
Jim Grosbach4b905842013-09-20 23:08:21 +00004077/// parseDirectiveCFIEscape
Eli Bendersky17233942013-01-15 22:59:42 +00004078/// ::= .cfi_escape expression[,...]
Jim Grosbach4b905842013-09-20 23:08:21 +00004079bool AsmParser::parseDirectiveCFIEscape() {
Eli Bendersky17233942013-01-15 22:59:42 +00004080 std::string Values;
4081 int64_t CurrValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004082 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00004083 return true;
4084
4085 Values.push_back((uint8_t)CurrValue);
4086
4087 while (getLexer().is(AsmToken::Comma)) {
4088 Lex();
4089
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004090 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00004091 return true;
4092
4093 Values.push_back((uint8_t)CurrValue);
4094 }
4095
4096 getStreamer().EmitCFIEscape(Values);
4097 return false;
4098}
4099
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +00004100/// parseDirectiveCFIReturnColumn
4101/// ::= .cfi_return_column register
4102bool AsmParser::parseDirectiveCFIReturnColumn(SMLoc DirectiveLoc) {
4103 int64_t Register = 0;
4104 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
4105 return true;
4106 getStreamer().EmitCFIReturnColumn(Register);
4107 return false;
4108}
4109
Jim Grosbach4b905842013-09-20 23:08:21 +00004110/// parseDirectiveCFISignalFrame
Eli Bendersky17233942013-01-15 22:59:42 +00004111/// ::= .cfi_signal_frame
Jim Grosbach4b905842013-09-20 23:08:21 +00004112bool AsmParser::parseDirectiveCFISignalFrame() {
Nirav Davea645433c2016-07-18 15:24:03 +00004113 if (parseToken(AsmToken::EndOfStatement,
4114 "unexpected token in '.cfi_signal_frame'"))
4115 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004116
4117 getStreamer().EmitCFISignalFrame();
4118 return false;
4119}
4120
Jim Grosbach4b905842013-09-20 23:08:21 +00004121/// parseDirectiveCFIUndefined
Eli Bendersky17233942013-01-15 22:59:42 +00004122/// ::= .cfi_undefined register
Jim Grosbach4b905842013-09-20 23:08:21 +00004123bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004124 int64_t Register = 0;
4125
Jim Grosbach4b905842013-09-20 23:08:21 +00004126 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00004127 return true;
4128
4129 getStreamer().EmitCFIUndefined(Register);
4130 return false;
4131}
4132
Michael Zuckerman56704612017-05-01 13:20:12 +00004133/// parseDirectiveAltmacro
4134/// ::= .altmacro
4135/// ::= .noaltmacro
4136bool AsmParser::parseDirectiveAltmacro(StringRef Directive) {
4137 if (getLexer().isNot(AsmToken::EndOfStatement))
4138 return TokError("unexpected token in '" + Directive + "' directive");
4139 if (Directive == ".altmacro")
4140 getLexer().SetAltMacroMode(true);
4141 else
4142 getLexer().SetAltMacroMode(false);
4143 return false;
4144}
4145
Jim Grosbach4b905842013-09-20 23:08:21 +00004146/// parseDirectiveMacrosOnOff
Eli Bendersky17233942013-01-15 22:59:42 +00004147/// ::= .macros_on
4148/// ::= .macros_off
Jim Grosbach4b905842013-09-20 23:08:21 +00004149bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
Nirav Davea645433c2016-07-18 15:24:03 +00004150 if (parseToken(AsmToken::EndOfStatement,
4151 "unexpected token in '" + Directive + "' directive"))
4152 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004153
Jim Grosbach4b905842013-09-20 23:08:21 +00004154 setMacrosEnabled(Directive == ".macros_on");
Eli Bendersky17233942013-01-15 22:59:42 +00004155 return false;
4156}
4157
Jim Grosbach4b905842013-09-20 23:08:21 +00004158/// parseDirectiveMacro
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00004159/// ::= .macro name[,] [parameters]
Jim Grosbach4b905842013-09-20 23:08:21 +00004160bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004161 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004162 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00004163 return TokError("expected identifier in '.macro' directive");
4164
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00004165 if (getLexer().is(AsmToken::Comma))
4166 Lex();
4167
Eli Bendersky17233942013-01-15 22:59:42 +00004168 MCAsmMacroParameters Parameters;
David Majnemer91fc4c22014-01-29 18:57:46 +00004169 while (getLexer().isNot(AsmToken::EndOfStatement)) {
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00004170
Alexander Kornienko8c0809c2015-01-15 11:41:30 +00004171 if (!Parameters.empty() && Parameters.back().Vararg)
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00004172 return Error(Lexer.getLoc(),
4173 "Vararg parameter '" + Parameters.back().Name +
4174 "' should be last one in the list of parameters.");
4175
David Majnemer91fc4c22014-01-29 18:57:46 +00004176 MCAsmMacroParameter Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00004177 if (parseIdentifier(Parameter.Name))
David Majnemer91fc4c22014-01-29 18:57:46 +00004178 return TokError("expected identifier in '.macro' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00004179
Coby Tayreebedaae02017-04-08 20:29:03 +00004180 // Emit an error if two (or more) named parameters share the same name
4181 for (const MCAsmMacroParameter& CurrParam : Parameters)
4182 if (CurrParam.Name.equals(Parameter.Name))
4183 return TokError("macro '" + Name + "' has multiple parameters"
4184 " named '" + Parameter.Name + "'");
4185
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00004186 if (Lexer.is(AsmToken::Colon)) {
4187 Lex(); // consume ':'
4188
4189 SMLoc QualLoc;
4190 StringRef Qualifier;
4191
4192 QualLoc = Lexer.getLoc();
4193 if (parseIdentifier(Qualifier))
4194 return Error(QualLoc, "missing parameter qualifier for "
4195 "'" + Parameter.Name + "' in macro '" + Name + "'");
4196
4197 if (Qualifier == "req")
4198 Parameter.Required = true;
Kevin Enderbye3c13462014-08-04 23:14:37 +00004199 else if (Qualifier == "vararg")
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00004200 Parameter.Vararg = true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00004201 else
4202 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
4203 "for '" + Parameter.Name + "' in macro '" + Name + "'");
4204 }
4205
David Majnemer91fc4c22014-01-29 18:57:46 +00004206 if (getLexer().is(AsmToken::Equal)) {
4207 Lex();
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00004208
4209 SMLoc ParamLoc;
4210
4211 ParamLoc = Lexer.getLoc();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00004212 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
David Majnemer91fc4c22014-01-29 18:57:46 +00004213 return true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00004214
4215 if (Parameter.Required)
4216 Warning(ParamLoc, "pointless default value for required parameter "
4217 "'" + Parameter.Name + "' in macro '" + Name + "'");
Eli Bendersky17233942013-01-15 22:59:42 +00004218 }
David Majnemer91fc4c22014-01-29 18:57:46 +00004219
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00004220 Parameters.push_back(std::move(Parameter));
David Majnemer91fc4c22014-01-29 18:57:46 +00004221
4222 if (getLexer().is(AsmToken::Comma))
4223 Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00004224 }
4225
Nirav Dave1180e6892016-06-02 17:15:05 +00004226 // Eat just the end of statement.
4227 Lexer.Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00004228
Nirav Dave1180e6892016-06-02 17:15:05 +00004229 // Consuming deferred text, so use Lexer.Lex to ignore Lexing Errors
Eli Bendersky17233942013-01-15 22:59:42 +00004230 AsmToken EndToken, StartToken = getTok();
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00004231 unsigned MacroDepth = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00004232 // Lex the macro definition.
Eugene Zelenko33d7b762016-08-23 17:14:32 +00004233 while (true) {
Nirav Dave1180e6892016-06-02 17:15:05 +00004234 // Ignore Lexing errors in macros.
4235 while (Lexer.is(AsmToken::Error)) {
4236 Lexer.Lex();
4237 }
4238
Eli Bendersky17233942013-01-15 22:59:42 +00004239 // Check whether we have reached the end of the file.
4240 if (getLexer().is(AsmToken::Eof))
4241 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
4242
4243 // Otherwise, check whether we have reach the .endmacro.
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00004244 if (getLexer().is(AsmToken::Identifier)) {
4245 if (getTok().getIdentifier() == ".endm" ||
4246 getTok().getIdentifier() == ".endmacro") {
4247 if (MacroDepth == 0) { // Outermost macro.
4248 EndToken = getTok();
Nirav Dave1180e6892016-06-02 17:15:05 +00004249 Lexer.Lex();
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00004250 if (getLexer().isNot(AsmToken::EndOfStatement))
4251 return TokError("unexpected token in '" + EndToken.getIdentifier() +
4252 "' directive");
4253 break;
4254 } else {
4255 // Otherwise we just found the end of an inner macro.
4256 --MacroDepth;
4257 }
4258 } else if (getTok().getIdentifier() == ".macro") {
4259 // We allow nested macros. Those aren't instantiated until the outermost
4260 // macro is expanded so just ignore them for now.
4261 ++MacroDepth;
4262 }
Eli Bendersky17233942013-01-15 22:59:42 +00004263 }
4264
4265 // Otherwise, scan til the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004266 eatToEndOfStatement();
Eli Bendersky17233942013-01-15 22:59:42 +00004267 }
4268
Rafael Espindola22c38a02018-02-14 16:34:27 +00004269 if (getContext().lookupMacro(Name)) {
Eli Bendersky17233942013-01-15 22:59:42 +00004270 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
4271 }
4272
4273 const char *BodyStart = StartToken.getLoc().getPointer();
4274 const char *BodyEnd = EndToken.getLoc().getPointer();
4275 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Jim Grosbach4b905842013-09-20 23:08:21 +00004276 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
Oliver Stannardc3e7c6d2018-03-06 15:32:34 +00004277 MCAsmMacro Macro(Name, Body, std::move(Parameters));
4278 DEBUG_WITH_TYPE("asm-macros", dbgs() << "Defining new macro:\n";
4279 Macro.dump());
4280 getContext().defineMacro(Name, std::move(Macro));
Eli Bendersky17233942013-01-15 22:59:42 +00004281 return false;
4282}
4283
Jim Grosbach4b905842013-09-20 23:08:21 +00004284/// checkForBadMacro
Kevin Enderby81c944c2013-01-22 21:44:53 +00004285///
4286/// With the support added for named parameters there may be code out there that
4287/// is transitioning from positional parameters. In versions of gas that did
Alp Tokercb402912014-01-24 17:20:08 +00004288/// not support named parameters they would be ignored on the macro definition.
Kevin Enderby81c944c2013-01-22 21:44:53 +00004289/// But to support both styles of parameters this is not possible so if a macro
Alp Tokercb402912014-01-24 17:20:08 +00004290/// definition has named parameters but does not use them and has what appears
Kevin Enderby81c944c2013-01-22 21:44:53 +00004291/// to be positional parameters, strings like $1, $2, ... and $n, then issue a
4292/// warning that the positional parameter found in body which have no effect.
4293/// Hoping the developer will either remove the named parameters from the macro
Alp Tokercb402912014-01-24 17:20:08 +00004294/// definition so the positional parameters get used if that was what was
Kevin Enderby81c944c2013-01-22 21:44:53 +00004295/// intended or change the macro to use the named parameters. It is possible
4296/// this warning will trigger when the none of the named parameters are used
4297/// and the strings like $1 are infact to simply to be passed trough unchanged.
Jim Grosbach4b905842013-09-20 23:08:21 +00004298void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
Kevin Enderby81c944c2013-01-22 21:44:53 +00004299 StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00004300 ArrayRef<MCAsmMacroParameter> Parameters) {
Kevin Enderby81c944c2013-01-22 21:44:53 +00004301 // If this macro is not defined with named parameters the warning we are
4302 // checking for here doesn't apply.
4303 unsigned NParameters = Parameters.size();
4304 if (NParameters == 0)
4305 return;
4306
4307 bool NamedParametersFound = false;
4308 bool PositionalParametersFound = false;
4309
4310 // Look at the body of the macro for use of both the named parameters and what
4311 // are likely to be positional parameters. This is what expandMacro() is
4312 // doing when it finds the parameters in the body.
4313 while (!Body.empty()) {
4314 // Scan for the next possible parameter.
4315 std::size_t End = Body.size(), Pos = 0;
4316 for (; Pos != End; ++Pos) {
4317 // Check for a substitution or escape.
4318 // This macro is defined with parameters, look for \foo, \bar, etc.
4319 if (Body[Pos] == '\\' && Pos + 1 != End)
4320 break;
4321
4322 // This macro should have parameters, but look for $0, $1, ..., $n too.
4323 if (Body[Pos] != '$' || Pos + 1 == End)
4324 continue;
4325 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00004326 if (Next == '$' || Next == 'n' ||
4327 isdigit(static_cast<unsigned char>(Next)))
Kevin Enderby81c944c2013-01-22 21:44:53 +00004328 break;
4329 }
4330
4331 // Check if we reached the end.
4332 if (Pos == End)
4333 break;
4334
4335 if (Body[Pos] == '$') {
Jim Grosbach4b905842013-09-20 23:08:21 +00004336 switch (Body[Pos + 1]) {
4337 // $$ => $
Kevin Enderby81c944c2013-01-22 21:44:53 +00004338 case '$':
4339 break;
4340
Jim Grosbach4b905842013-09-20 23:08:21 +00004341 // $n => number of arguments
Kevin Enderby81c944c2013-01-22 21:44:53 +00004342 case 'n':
4343 PositionalParametersFound = true;
4344 break;
4345
Jim Grosbach4b905842013-09-20 23:08:21 +00004346 // $[0-9] => argument
Kevin Enderby81c944c2013-01-22 21:44:53 +00004347 default: {
4348 PositionalParametersFound = true;
4349 break;
Jim Grosbach4b905842013-09-20 23:08:21 +00004350 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00004351 }
4352 Pos += 2;
4353 } else {
4354 unsigned I = Pos + 1;
4355 while (isIdentifierChar(Body[I]) && I + 1 != End)
4356 ++I;
4357
Jim Grosbach4b905842013-09-20 23:08:21 +00004358 const char *Begin = Body.data() + Pos + 1;
4359 StringRef Argument(Begin, I - (Pos + 1));
Kevin Enderby81c944c2013-01-22 21:44:53 +00004360 unsigned Index = 0;
4361 for (; Index < NParameters; ++Index)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00004362 if (Parameters[Index].Name == Argument)
Kevin Enderby81c944c2013-01-22 21:44:53 +00004363 break;
4364
4365 if (Index == NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00004366 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
4367 Pos += 3;
4368 else {
4369 Pos = I;
4370 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00004371 } else {
4372 NamedParametersFound = true;
4373 Pos += 1 + Argument.size();
4374 }
4375 }
4376 // Update the scan point.
4377 Body = Body.substr(Pos);
4378 }
4379
4380 if (!NamedParametersFound && PositionalParametersFound)
4381 Warning(DirectiveLoc, "macro defined with named parameters which are not "
4382 "used in macro body, possible positional parameter "
4383 "found in body which will have no effect");
4384}
4385
Nico Weber155dccd12014-07-24 17:08:39 +00004386/// parseDirectiveExitMacro
4387/// ::= .exitm
4388bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
Nirav Davea645433c2016-07-18 15:24:03 +00004389 if (parseToken(AsmToken::EndOfStatement,
4390 "unexpected token in '" + Directive + "' directive"))
4391 return true;
Nico Weber155dccd12014-07-24 17:08:39 +00004392
4393 if (!isInsideMacroInstantiation())
4394 return TokError("unexpected '" + Directive + "' in file, "
4395 "no current macro definition");
4396
4397 // Exit all conditionals that are active in the current macro.
4398 while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
4399 TheCondState = TheCondStack.back();
4400 TheCondStack.pop_back();
4401 }
4402
4403 handleMacroExit();
4404 return false;
4405}
4406
Jim Grosbach4b905842013-09-20 23:08:21 +00004407/// parseDirectiveEndMacro
Eli Bendersky17233942013-01-15 22:59:42 +00004408/// ::= .endm
4409/// ::= .endmacro
Jim Grosbach4b905842013-09-20 23:08:21 +00004410bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
Eli Bendersky17233942013-01-15 22:59:42 +00004411 if (getLexer().isNot(AsmToken::EndOfStatement))
4412 return TokError("unexpected token in '" + Directive + "' directive");
4413
4414 // If we are inside a macro instantiation, terminate the current
4415 // instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00004416 if (isInsideMacroInstantiation()) {
4417 handleMacroExit();
Eli Bendersky17233942013-01-15 22:59:42 +00004418 return false;
4419 }
4420
4421 // Otherwise, this .endmacro is a stray entry in the file; well formed
4422 // .endmacro directives are handled during the macro definition parsing.
4423 return TokError("unexpected '" + Directive + "' in file, "
Jim Grosbach4b905842013-09-20 23:08:21 +00004424 "no current macro definition");
Eli Bendersky17233942013-01-15 22:59:42 +00004425}
4426
Jim Grosbach4b905842013-09-20 23:08:21 +00004427/// parseDirectivePurgeMacro
Eli Bendersky17233942013-01-15 22:59:42 +00004428/// ::= .purgem
Jim Grosbach4b905842013-09-20 23:08:21 +00004429bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004430 StringRef Name;
Nirav Davea645433c2016-07-18 15:24:03 +00004431 SMLoc Loc;
Nirav Daved8858ca2016-08-30 14:15:43 +00004432 if (parseTokenLoc(Loc) ||
4433 check(parseIdentifier(Name), Loc,
4434 "expected identifier in '.purgem' directive") ||
Nirav Davea645433c2016-07-18 15:24:03 +00004435 parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00004436 "unexpected token in '.purgem' directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00004437 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004438
Rafael Espindola22c38a02018-02-14 16:34:27 +00004439 if (!getContext().lookupMacro(Name))
Nirav Dave1ab71992016-07-18 19:35:21 +00004440 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
4441
Rafael Espindola22c38a02018-02-14 16:34:27 +00004442 getContext().undefineMacro(Name);
Oliver Stannardc3e7c6d2018-03-06 15:32:34 +00004443 DEBUG_WITH_TYPE("asm-macros", dbgs()
4444 << "Un-defining macro: " << Name << "\n");
Eli Bendersky17233942013-01-15 22:59:42 +00004445 return false;
4446}
Eli Benderskyf483ff92012-12-20 19:05:53 +00004447
Jim Grosbach4b905842013-09-20 23:08:21 +00004448/// parseDirectiveBundleAlignMode
Eli Benderskyf483ff92012-12-20 19:05:53 +00004449/// ::= {.bundle_align_mode} expression
Jim Grosbach4b905842013-09-20 23:08:21 +00004450bool AsmParser::parseDirectiveBundleAlignMode() {
Eli Benderskyf483ff92012-12-20 19:05:53 +00004451 // Expect a single argument: an expression that evaluates to a constant
4452 // in the inclusive range 0-30.
4453 SMLoc ExprLoc = getLexer().getLoc();
4454 int64_t AlignSizePow2;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004455 if (checkForValidSection() || parseAbsoluteExpression(AlignSizePow2) ||
Nirav Davea645433c2016-07-18 15:24:03 +00004456 parseToken(AsmToken::EndOfStatement, "unexpected token after expression "
4457 "in '.bundle_align_mode' "
4458 "directive") ||
4459 check(AlignSizePow2 < 0 || AlignSizePow2 > 30, ExprLoc,
4460 "invalid bundle alignment size (expected between 0 and 30)"))
Eli Benderskyf483ff92012-12-20 19:05:53 +00004461 return true;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004462
4463 // Because of AlignSizePow2's verified range we can safely truncate it to
4464 // unsigned.
4465 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
4466 return false;
4467}
4468
Jim Grosbach4b905842013-09-20 23:08:21 +00004469/// parseDirectiveBundleLock
Eli Bendersky802b6282013-01-07 21:51:08 +00004470/// ::= {.bundle_lock} [align_to_end]
Jim Grosbach4b905842013-09-20 23:08:21 +00004471bool AsmParser::parseDirectiveBundleLock() {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004472 if (checkForValidSection())
4473 return true;
Eli Bendersky802b6282013-01-07 21:51:08 +00004474 bool AlignToEnd = false;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004475
Nirav Dave1a9044b2016-10-24 14:35:29 +00004476 StringRef Option;
4477 SMLoc Loc = getTok().getLoc();
4478 const char *kInvalidOptionError =
4479 "invalid option for '.bundle_lock' directive";
Eli Bendersky802b6282013-01-07 21:51:08 +00004480
Nirav Dave1a9044b2016-10-24 14:35:29 +00004481 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
Nirav Davea645433c2016-07-18 15:24:03 +00004482 if (check(parseIdentifier(Option), Loc, kInvalidOptionError) ||
4483 check(Option != "align_to_end", Loc, kInvalidOptionError) ||
Nirav Dave1a9044b2016-10-24 14:35:29 +00004484 parseToken(AsmToken::EndOfStatement,
4485 "unexpected token after '.bundle_lock' directive option"))
Nirav Davea645433c2016-07-18 15:24:03 +00004486 return true;
Eli Bendersky802b6282013-01-07 21:51:08 +00004487 AlignToEnd = true;
4488 }
4489
Eli Bendersky802b6282013-01-07 21:51:08 +00004490 getStreamer().EmitBundleLock(AlignToEnd);
Eli Benderskyf483ff92012-12-20 19:05:53 +00004491 return false;
4492}
4493
Jim Grosbach4b905842013-09-20 23:08:21 +00004494/// parseDirectiveBundleLock
Eli Benderskyf483ff92012-12-20 19:05:53 +00004495/// ::= {.bundle_lock}
Jim Grosbach4b905842013-09-20 23:08:21 +00004496bool AsmParser::parseDirectiveBundleUnlock() {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004497 if (checkForValidSection() ||
4498 parseToken(AsmToken::EndOfStatement,
Nirav Davea645433c2016-07-18 15:24:03 +00004499 "unexpected token in '.bundle_unlock' directive"))
4500 return true;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004501
4502 getStreamer().EmitBundleUnlock();
4503 return false;
4504}
4505
Jim Grosbach4b905842013-09-20 23:08:21 +00004506/// parseDirectiveSpace
Eli Bendersky17233942013-01-15 22:59:42 +00004507/// ::= (.skip | .space) expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004508bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
Petr Hosek67a94a72016-05-28 05:57:48 +00004509 SMLoc NumBytesLoc = Lexer.getLoc();
4510 const MCExpr *NumBytes;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004511 if (checkForValidSection() || parseExpression(NumBytes))
Eli Bendersky17233942013-01-15 22:59:42 +00004512 return true;
4513
4514 int64_t FillExpr = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00004515 if (parseOptionalToken(AsmToken::Comma))
4516 if (parseAbsoluteExpression(FillExpr))
4517 return addErrorSuffix("in '" + Twine(IDVal) + "' directive");
4518 if (parseToken(AsmToken::EndOfStatement))
4519 return addErrorSuffix("in '" + Twine(IDVal) + "' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00004520
Eli Bendersky17233942013-01-15 22:59:42 +00004521 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
Petr Hosek67a94a72016-05-28 05:57:48 +00004522 getStreamer().emitFill(*NumBytes, FillExpr, NumBytesLoc);
Eli Bendersky17233942013-01-15 22:59:42 +00004523
4524 return false;
4525}
4526
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004527/// parseDirectiveDCB
4528/// ::= .dcb.{b, l, w} expression, expression
4529bool AsmParser::parseDirectiveDCB(StringRef IDVal, unsigned Size) {
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004530 SMLoc NumValuesLoc = Lexer.getLoc();
4531 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004532 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004533 return true;
4534
4535 if (NumValues < 0) {
4536 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4537 return false;
4538 }
4539
4540 if (parseToken(AsmToken::Comma,
4541 "unexpected token in '" + Twine(IDVal) + "' directive"))
4542 return true;
4543
4544 const MCExpr *Value;
4545 SMLoc ExprLoc = getLexer().getLoc();
4546 if (parseExpression(Value))
4547 return true;
4548
4549 // Special case constant expressions to match code generator.
4550 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
4551 assert(Size <= 8 && "Invalid size");
4552 uint64_t IntValue = MCE->getValue();
4553 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
4554 return Error(ExprLoc, "literal value out of range for directive");
4555 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4556 getStreamer().EmitIntValue(IntValue, Size);
4557 } else {
4558 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4559 getStreamer().EmitValue(Value, Size, ExprLoc);
4560 }
4561
4562 if (parseToken(AsmToken::EndOfStatement,
4563 "unexpected token in '" + Twine(IDVal) + "' directive"))
4564 return true;
4565
4566 return false;
4567}
4568
4569/// parseDirectiveRealDCB
4570/// ::= .dcb.{d, s} expression, expression
4571bool AsmParser::parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &Semantics) {
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004572 SMLoc NumValuesLoc = Lexer.getLoc();
4573 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004574 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004575 return true;
4576
4577 if (NumValues < 0) {
4578 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4579 return false;
4580 }
4581
4582 if (parseToken(AsmToken::Comma,
4583 "unexpected token in '" + Twine(IDVal) + "' directive"))
4584 return true;
4585
4586 APInt AsInt;
4587 if (parseRealValue(Semantics, AsInt))
4588 return true;
4589
4590 if (parseToken(AsmToken::EndOfStatement,
4591 "unexpected token in '" + Twine(IDVal) + "' directive"))
4592 return true;
4593
4594 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4595 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
4596 AsInt.getBitWidth() / 8);
4597
4598 return false;
4599}
4600
Petr Hosek85b2f672016-09-23 21:53:36 +00004601/// parseDirectiveDS
4602/// ::= .ds.{b, d, l, p, s, w, x} expression
4603bool AsmParser::parseDirectiveDS(StringRef IDVal, unsigned Size) {
Petr Hosek85b2f672016-09-23 21:53:36 +00004604 SMLoc NumValuesLoc = Lexer.getLoc();
4605 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004606 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek85b2f672016-09-23 21:53:36 +00004607 return true;
4608
4609 if (NumValues < 0) {
4610 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4611 return false;
4612 }
4613
4614 if (parseToken(AsmToken::EndOfStatement,
4615 "unexpected token in '" + Twine(IDVal) + "' directive"))
4616 return true;
4617
4618 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4619 getStreamer().emitFill(Size, 0);
4620
4621 return false;
4622}
4623
Jim Grosbach4b905842013-09-20 23:08:21 +00004624/// parseDirectiveLEB128
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004625/// ::= (.sleb128 | .uleb128) [ expression (, expression)* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004626bool AsmParser::parseDirectiveLEB128(bool Signed) {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004627 if (checkForValidSection())
4628 return true;
4629
Nirav Dave1a9044b2016-10-24 14:35:29 +00004630 auto parseOp = [&]() -> bool {
4631 const MCExpr *Value;
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004632 if (parseExpression(Value))
4633 return true;
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004634 if (Signed)
4635 getStreamer().EmitSLEB128Value(Value);
4636 else
4637 getStreamer().EmitULEB128Value(Value);
Nirav Dave1a9044b2016-10-24 14:35:29 +00004638 return false;
4639 };
Eli Bendersky17233942013-01-15 22:59:42 +00004640
Nirav Dave1a9044b2016-10-24 14:35:29 +00004641 if (parseMany(parseOp))
4642 return addErrorSuffix(" in directive");
Eli Bendersky17233942013-01-15 22:59:42 +00004643
4644 return false;
4645}
4646
Jim Grosbach4b905842013-09-20 23:08:21 +00004647/// parseDirectiveSymbolAttribute
Daniel Dunbara5508c82009-06-30 00:33:19 +00004648/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004649bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00004650 auto parseOp = [&]() -> bool {
4651 StringRef Name;
4652 SMLoc Loc = getTok().getLoc();
4653 if (parseIdentifier(Name))
4654 return Error(Loc, "expected identifier");
4655 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004656
Nirav Dave1a9044b2016-10-24 14:35:29 +00004657 // Assembler local symbols don't make any sense here. Complain loudly.
4658 if (Sym->isTemporary())
4659 return Error(Loc, "non-local symbol required");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004660
Nirav Dave1a9044b2016-10-24 14:35:29 +00004661 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
4662 return Error(Loc, "unable to emit symbol attribute");
4663 return false;
4664 };
Daniel Dunbara5508c82009-06-30 00:33:19 +00004665
Nirav Dave1a9044b2016-10-24 14:35:29 +00004666 if (parseMany(parseOp))
4667 return addErrorSuffix(" in directive");
Jan Wen Voungc7682872010-09-30 01:09:20 +00004668 return false;
Daniel Dunbara5508c82009-06-30 00:33:19 +00004669}
Chris Lattnera1e11f52009-07-07 20:30:46 +00004670
Jim Grosbach4b905842013-09-20 23:08:21 +00004671/// parseDirectiveComm
Chris Lattner28ad7542009-07-09 17:25:12 +00004672/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004673bool AsmParser::parseDirectiveComm(bool IsLocal) {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004674 if (checkForValidSection())
4675 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00004676
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004677 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004678 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004679 if (parseIdentifier(Name))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004680 return TokError("expected identifier in directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004681
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +00004682 // Handle the identifier as the key symbol.
Jim Grosbach6f482002015-05-18 18:43:14 +00004683 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Chris Lattnera1e11f52009-07-07 20:30:46 +00004684
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004685 if (getLexer().isNot(AsmToken::Comma))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004686 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00004687 Lex();
Chris Lattnera1e11f52009-07-07 20:30:46 +00004688
4689 int64_t Size;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004690 SMLoc SizeLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004691 if (parseAbsoluteExpression(Size))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004692 return true;
4693
4694 int64_t Pow2Alignment = 0;
4695 SMLoc Pow2AlignmentLoc;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004696 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan686ed8d2010-01-19 20:22:31 +00004697 Lex();
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004698 Pow2AlignmentLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004699 if (parseAbsoluteExpression(Pow2Alignment))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004700 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00004701
Benjamin Kramer68b9f052012-09-07 21:08:01 +00004702 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
4703 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00004704 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
4705
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00004706 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramer68b9f052012-09-07 21:08:01 +00004707 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
4708 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00004709 if (!isPowerOf2_64(Pow2Alignment))
4710 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
4711 Pow2Alignment = Log2_64(Pow2Alignment);
4712 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00004713 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00004714
Nirav Dave1a9044b2016-10-24 14:35:29 +00004715 if (parseToken(AsmToken::EndOfStatement,
4716 "unexpected token in '.comm' or '.lcomm' directive"))
4717 return true;
Chris Lattnera1e11f52009-07-07 20:30:46 +00004718
Chris Lattner28ad7542009-07-09 17:25:12 +00004719 // NOTE: a size of zero for a .comm should create a undefined symbol
4720 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattnera1e11f52009-07-07 20:30:46 +00004721 if (Size < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00004722 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
Jim Grosbach4b905842013-09-20 23:08:21 +00004723 "be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00004724
Eric Christopherbc818852010-05-14 01:38:54 +00004725 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattnera1e11f52009-07-07 20:30:46 +00004726 // may internally end up wanting an alignment in bytes.
4727 // FIXME: Diagnose overflow.
4728 if (Pow2Alignment < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00004729 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
Jim Grosbach4b905842013-09-20 23:08:21 +00004730 "alignment, can't be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00004731
Rafael Espindola13a79bb2017-02-02 21:26:06 +00004732 Sym->redefineIfPossible();
Daniel Dunbar6860ac72009-08-22 07:22:36 +00004733 if (!Sym->isUndefined())
Chris Lattnera1e11f52009-07-07 20:30:46 +00004734 return Error(IDLoc, "invalid symbol redefinition");
4735
Chris Lattner28ad7542009-07-09 17:25:12 +00004736 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00004737 if (IsLocal) {
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00004738 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00004739 return false;
4740 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00004741
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004742 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattnera1e11f52009-07-07 20:30:46 +00004743 return false;
4744}
Chris Lattner07cadaf2009-07-10 22:20:30 +00004745
Jim Grosbach4b905842013-09-20 23:08:21 +00004746/// parseDirectiveAbort
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004747/// ::= .abort [... message ...]
Jim Grosbach4b905842013-09-20 23:08:21 +00004748bool AsmParser::parseDirectiveAbort() {
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004749 // FIXME: Use loc from directive.
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004750 SMLoc Loc = getLexer().getLoc();
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004751
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004752 StringRef Str = parseStringToEndOfStatement();
Nirav Davea645433c2016-07-18 15:24:03 +00004753 if (parseToken(AsmToken::EndOfStatement,
4754 "unexpected token in '.abort' directive"))
4755 return true;
Kevin Enderby56523ce2009-07-13 23:15:14 +00004756
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004757 if (Str.empty())
Nirav Dave2364748a2016-09-16 18:30:20 +00004758 return Error(Loc, ".abort detected. Assembly stopping.");
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004759 else
Nirav Dave2364748a2016-09-16 18:30:20 +00004760 return Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004761 // FIXME: Actually abort assembly here.
Kevin Enderby56523ce2009-07-13 23:15:14 +00004762
4763 return false;
4764}
Kevin Enderbycbe475d2009-07-14 21:35:03 +00004765
Jim Grosbach4b905842013-09-20 23:08:21 +00004766/// parseDirectiveInclude
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004767/// ::= .include "filename"
Jim Grosbach4b905842013-09-20 23:08:21 +00004768bool AsmParser::parseDirectiveInclude() {
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004769 // Allow the strings to have escaped octal character sequence.
4770 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00004771 SMLoc IncludeLoc = getTok().getLoc();
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004772
Nirav Davea645433c2016-07-18 15:24:03 +00004773 if (check(getTok().isNot(AsmToken::String),
4774 "expected string in '.include' directive") ||
4775 parseEscapedString(Filename) ||
4776 check(getTok().isNot(AsmToken::EndOfStatement),
4777 "unexpected token in '.include' directive") ||
4778 // Attempt to switch the lexer to the included file before consuming the
4779 // end of statement to avoid losing it when we switch.
4780 check(enterIncludeFile(Filename), IncludeLoc,
4781 "Could not find include file '" + Filename + "'"))
Chris Lattner693fbb82009-07-16 06:14:39 +00004782 return true;
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004783
4784 return false;
4785}
Kevin Enderby09ea5702009-07-15 15:30:11 +00004786
Jim Grosbach4b905842013-09-20 23:08:21 +00004787/// parseDirectiveIncbin
Petr Hosek2f4ac442016-09-23 00:41:06 +00004788/// ::= .incbin "filename" [ , skip [ , count ] ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004789bool AsmParser::parseDirectiveIncbin() {
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004790 // Allow the strings to have escaped octal character sequence.
4791 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00004792 SMLoc IncbinLoc = getTok().getLoc();
4793 if (check(getTok().isNot(AsmToken::String),
4794 "expected string in '.incbin' directive") ||
Petr Hosek2f4ac442016-09-23 00:41:06 +00004795 parseEscapedString(Filename))
4796 return true;
4797
4798 int64_t Skip = 0;
4799 const MCExpr *Count = nullptr;
4800 SMLoc SkipLoc, CountLoc;
Nirav Dave1a9044b2016-10-24 14:35:29 +00004801 if (parseOptionalToken(AsmToken::Comma)) {
Petr Hosek2f4ac442016-09-23 00:41:06 +00004802 // The skip expression can be omitted while specifying the count, e.g:
4803 // .incbin "filename",,4
4804 if (getTok().isNot(AsmToken::Comma)) {
4805 if (parseTokenLoc(SkipLoc) || parseAbsoluteExpression(Skip))
4806 return true;
4807 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00004808 if (parseOptionalToken(AsmToken::Comma)) {
4809 CountLoc = getTok().getLoc();
4810 if (parseExpression(Count))
Petr Hosek2f4ac442016-09-23 00:41:06 +00004811 return true;
4812 }
4813 }
4814
4815 if (parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00004816 "unexpected token in '.incbin' directive"))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004817 return true;
Nirav Dave1ab71992016-07-18 19:35:21 +00004818
Petr Hosek2f4ac442016-09-23 00:41:06 +00004819 if (check(Skip < 0, SkipLoc, "skip is negative"))
4820 return true;
4821
Nirav Dave1ab71992016-07-18 19:35:21 +00004822 // Attempt to process the included file.
Petr Hosek2f4ac442016-09-23 00:41:06 +00004823 if (processIncbinFile(Filename, Skip, Count, CountLoc))
Nirav Dave1ab71992016-07-18 19:35:21 +00004824 return Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
Kevin Enderby109f25c2011-12-14 21:47:48 +00004825 return false;
4826}
4827
Jim Grosbach4b905842013-09-20 23:08:21 +00004828/// parseDirectiveIf
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004829/// ::= .if{,eq,ge,gt,le,lt,ne} expression
4830bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004831 TheCondStack.push_back(TheCondState);
4832 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004833 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004834 eatToEndOfStatement();
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004835 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004836 int64_t ExprValue;
Nirav Davea645433c2016-07-18 15:24:03 +00004837 if (parseAbsoluteExpression(ExprValue) ||
4838 parseToken(AsmToken::EndOfStatement,
4839 "unexpected token in '.if' directive"))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004840 return true;
4841
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004842 switch (DirKind) {
4843 default:
4844 llvm_unreachable("unsupported directive");
4845 case DK_IF:
4846 case DK_IFNE:
4847 break;
4848 case DK_IFEQ:
4849 ExprValue = ExprValue == 0;
4850 break;
4851 case DK_IFGE:
4852 ExprValue = ExprValue >= 0;
4853 break;
4854 case DK_IFGT:
4855 ExprValue = ExprValue > 0;
4856 break;
4857 case DK_IFLE:
4858 ExprValue = ExprValue <= 0;
4859 break;
4860 case DK_IFLT:
4861 ExprValue = ExprValue < 0;
4862 break;
4863 }
4864
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004865 TheCondState.CondMet = ExprValue;
4866 TheCondState.Ignore = !TheCondState.CondMet;
4867 }
4868
4869 return false;
4870}
4871
Jim Grosbach4b905842013-09-20 23:08:21 +00004872/// parseDirectiveIfb
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004873/// ::= .ifb string
Jim Grosbach4b905842013-09-20 23:08:21 +00004874bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004875 TheCondStack.push_back(TheCondState);
4876 TheCondState.TheCond = AsmCond::IfCond;
4877
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004878 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004879 eatToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004880 } else {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004881 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004882
Nirav Davea645433c2016-07-18 15:24:03 +00004883 if (parseToken(AsmToken::EndOfStatement,
4884 "unexpected token in '.ifb' directive"))
4885 return true;
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004886
4887 TheCondState.CondMet = ExpectBlank == Str.empty();
4888 TheCondState.Ignore = !TheCondState.CondMet;
4889 }
4890
4891 return false;
4892}
4893
Jim Grosbach4b905842013-09-20 23:08:21 +00004894/// parseDirectiveIfc
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004895/// ::= .ifc string1, string2
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00004896/// ::= .ifnc string1, string2
Jim Grosbach4b905842013-09-20 23:08:21 +00004897bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004898 TheCondStack.push_back(TheCondState);
4899 TheCondState.TheCond = AsmCond::IfCond;
4900
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004901 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004902 eatToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004903 } else {
Jim Grosbach4b905842013-09-20 23:08:21 +00004904 StringRef Str1 = parseStringToComma();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004905
Nirav Davea645433c2016-07-18 15:24:03 +00004906 if (parseToken(AsmToken::Comma, "unexpected token in '.ifc' directive"))
4907 return true;
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004908
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004909 StringRef Str2 = parseStringToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004910
Nirav Davea645433c2016-07-18 15:24:03 +00004911 if (parseToken(AsmToken::EndOfStatement,
4912 "unexpected token in '.ifc' directive"))
4913 return true;
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004914
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00004915 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004916 TheCondState.Ignore = !TheCondState.CondMet;
4917 }
4918
4919 return false;
4920}
4921
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004922/// parseDirectiveIfeqs
4923/// ::= .ifeqs string1, string2
Sid Manning51c35602015-03-18 14:20:54 +00004924bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual) {
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004925 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00004926 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00004927 return TokError("expected string parameter for '.ifeqs' directive");
4928 return TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004929 }
4930
4931 StringRef String1 = getTok().getStringContents();
4932 Lex();
4933
4934 if (Lexer.isNot(AsmToken::Comma)) {
Sid Manning51c35602015-03-18 14:20:54 +00004935 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00004936 return TokError(
4937 "expected comma after first string for '.ifeqs' directive");
4938 return TokError("expected comma after first string for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004939 }
4940
4941 Lex();
4942
4943 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00004944 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00004945 return TokError("expected string parameter for '.ifeqs' directive");
4946 return TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004947 }
4948
4949 StringRef String2 = getTok().getStringContents();
4950 Lex();
4951
4952 TheCondStack.push_back(TheCondState);
4953 TheCondState.TheCond = AsmCond::IfCond;
Sid Manning51c35602015-03-18 14:20:54 +00004954 TheCondState.CondMet = ExpectEqual == (String1 == String2);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004955 TheCondState.Ignore = !TheCondState.CondMet;
4956
4957 return false;
4958}
4959
Jim Grosbach4b905842013-09-20 23:08:21 +00004960/// parseDirectiveIfdef
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004961/// ::= .ifdef symbol
Jim Grosbach4b905842013-09-20 23:08:21 +00004962bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004963 StringRef Name;
4964 TheCondStack.push_back(TheCondState);
4965 TheCondState.TheCond = AsmCond::IfCond;
4966
4967 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004968 eatToEndOfStatement();
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004969 } else {
Nirav Davea645433c2016-07-18 15:24:03 +00004970 if (check(parseIdentifier(Name), "expected identifier after '.ifdef'") ||
4971 parseToken(AsmToken::EndOfStatement, "unexpected token in '.ifdef'"))
4972 return true;
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004973
Jim Grosbach6f482002015-05-18 18:43:14 +00004974 MCSymbol *Sym = getContext().lookupSymbol(Name);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004975
4976 if (expect_defined)
Craig Topper353eda42014-04-24 06:44:33 +00004977 TheCondState.CondMet = (Sym && !Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004978 else
Craig Topper353eda42014-04-24 06:44:33 +00004979 TheCondState.CondMet = (!Sym || Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004980 TheCondState.Ignore = !TheCondState.CondMet;
4981 }
4982
4983 return false;
4984}
4985
Jim Grosbach4b905842013-09-20 23:08:21 +00004986/// parseDirectiveElseIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004987/// ::= .elseif expression
Jim Grosbach4b905842013-09-20 23:08:21 +00004988bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004989 if (TheCondState.TheCond != AsmCond::IfCond &&
4990 TheCondState.TheCond != AsmCond::ElseIfCond)
Nirav Dave2364748a2016-09-16 18:30:20 +00004991 return Error(DirectiveLoc, "Encountered a .elseif that doesn't follow an"
4992 " .if or an .elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004993 TheCondState.TheCond = AsmCond::ElseIfCond;
4994
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004995 bool LastIgnoreState = false;
4996 if (!TheCondStack.empty())
Craig Topper2172ad62013-04-22 04:24:02 +00004997 LastIgnoreState = TheCondStack.back().Ignore;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004998 if (LastIgnoreState || TheCondState.CondMet) {
4999 TheCondState.Ignore = true;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005000 eatToEndOfStatement();
Craig Topperf15655b2013-04-22 04:22:40 +00005001 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005002 int64_t ExprValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005003 if (parseAbsoluteExpression(ExprValue))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005004 return true;
5005
Nirav Dave1a9044b2016-10-24 14:35:29 +00005006 if (parseToken(AsmToken::EndOfStatement,
5007 "unexpected token in '.elseif' directive"))
5008 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00005009
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005010 TheCondState.CondMet = ExprValue;
5011 TheCondState.Ignore = !TheCondState.CondMet;
5012 }
5013
5014 return false;
5015}
5016
Jim Grosbach4b905842013-09-20 23:08:21 +00005017/// parseDirectiveElse
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005018/// ::= .else
Jim Grosbach4b905842013-09-20 23:08:21 +00005019bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00005020 if (parseToken(AsmToken::EndOfStatement,
5021 "unexpected token in '.else' directive"))
5022 return true;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005023
5024 if (TheCondState.TheCond != AsmCond::IfCond &&
5025 TheCondState.TheCond != AsmCond::ElseIfCond)
Nirav Dave2364748a2016-09-16 18:30:20 +00005026 return Error(DirectiveLoc, "Encountered a .else that doesn't follow "
5027 " an .if or an .elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005028 TheCondState.TheCond = AsmCond::ElseCond;
5029 bool LastIgnoreState = false;
5030 if (!TheCondStack.empty())
5031 LastIgnoreState = TheCondStack.back().Ignore;
5032 if (LastIgnoreState || TheCondState.CondMet)
5033 TheCondState.Ignore = true;
5034 else
5035 TheCondState.Ignore = false;
5036
5037 return false;
5038}
5039
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00005040/// parseDirectiveEnd
5041/// ::= .end
5042bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00005043 if (parseToken(AsmToken::EndOfStatement,
5044 "unexpected token in '.end' directive"))
5045 return true;
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00005046
5047 while (Lexer.isNot(AsmToken::Eof))
Nirav Dave1a9044b2016-10-24 14:35:29 +00005048 Lexer.Lex();
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00005049
5050 return false;
5051}
5052
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00005053/// parseDirectiveError
5054/// ::= .err
5055/// ::= .error [string]
5056bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
5057 if (!TheCondStack.empty()) {
5058 if (TheCondStack.back().Ignore) {
5059 eatToEndOfStatement();
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00005060 return false;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00005061 }
5062 }
5063
5064 if (!WithMessage)
5065 return Error(L, ".err encountered");
5066
5067 StringRef Message = ".error directive invoked in source file";
5068 if (Lexer.isNot(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00005069 if (Lexer.isNot(AsmToken::String))
5070 return TokError(".error argument must be a string");
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00005071
5072 Message = getTok().getStringContents();
5073 Lex();
5074 }
5075
Nirav Dave2364748a2016-09-16 18:30:20 +00005076 return Error(L, Message);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00005077}
5078
Nico Weber404012b2014-07-24 16:26:06 +00005079/// parseDirectiveWarning
5080/// ::= .warning [string]
5081bool AsmParser::parseDirectiveWarning(SMLoc L) {
5082 if (!TheCondStack.empty()) {
5083 if (TheCondStack.back().Ignore) {
5084 eatToEndOfStatement();
5085 return false;
5086 }
5087 }
5088
5089 StringRef Message = ".warning directive invoked in source file";
Nirav Dave1a9044b2016-10-24 14:35:29 +00005090
5091 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00005092 if (Lexer.isNot(AsmToken::String))
5093 return TokError(".warning argument must be a string");
Nico Weber404012b2014-07-24 16:26:06 +00005094
5095 Message = getTok().getStringContents();
5096 Lex();
Nirav Dave1a9044b2016-10-24 14:35:29 +00005097 if (parseToken(AsmToken::EndOfStatement,
5098 "expected end of statement in '.warning' directive"))
5099 return true;
Nico Weber404012b2014-07-24 16:26:06 +00005100 }
5101
Nirav Dave2364748a2016-09-16 18:30:20 +00005102 return Warning(L, Message);
Nico Weber404012b2014-07-24 16:26:06 +00005103}
5104
Jim Grosbach4b905842013-09-20 23:08:21 +00005105/// parseDirectiveEndIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005106/// ::= .endif
Jim Grosbach4b905842013-09-20 23:08:21 +00005107bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00005108 if (parseToken(AsmToken::EndOfStatement,
5109 "unexpected token in '.endif' directive"))
5110 return true;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005111
Jim Grosbach4b905842013-09-20 23:08:21 +00005112 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
Nirav Dave2364748a2016-09-16 18:30:20 +00005113 return Error(DirectiveLoc, "Encountered a .endif that doesn't follow "
5114 "an .if or .else");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00005115 if (!TheCondStack.empty()) {
5116 TheCondState = TheCondStack.back();
5117 TheCondStack.pop_back();
5118 }
5119
5120 return false;
5121}
Daniel Dunbara4b069c2009-08-11 04:24:50 +00005122
Eli Bendersky17233942013-01-15 22:59:42 +00005123void AsmParser::initializeDirectiveKindMap() {
5124 DirectiveKindMap[".set"] = DK_SET;
5125 DirectiveKindMap[".equ"] = DK_EQU;
5126 DirectiveKindMap[".equiv"] = DK_EQUIV;
5127 DirectiveKindMap[".ascii"] = DK_ASCII;
5128 DirectiveKindMap[".asciz"] = DK_ASCIZ;
5129 DirectiveKindMap[".string"] = DK_STRING;
5130 DirectiveKindMap[".byte"] = DK_BYTE;
5131 DirectiveKindMap[".short"] = DK_SHORT;
5132 DirectiveKindMap[".value"] = DK_VALUE;
5133 DirectiveKindMap[".2byte"] = DK_2BYTE;
5134 DirectiveKindMap[".long"] = DK_LONG;
5135 DirectiveKindMap[".int"] = DK_INT;
5136 DirectiveKindMap[".4byte"] = DK_4BYTE;
5137 DirectiveKindMap[".quad"] = DK_QUAD;
5138 DirectiveKindMap[".8byte"] = DK_8BYTE;
David Woodhoused6de0d92014-02-01 16:20:59 +00005139 DirectiveKindMap[".octa"] = DK_OCTA;
Eli Bendersky17233942013-01-15 22:59:42 +00005140 DirectiveKindMap[".single"] = DK_SINGLE;
5141 DirectiveKindMap[".float"] = DK_FLOAT;
5142 DirectiveKindMap[".double"] = DK_DOUBLE;
5143 DirectiveKindMap[".align"] = DK_ALIGN;
5144 DirectiveKindMap[".align32"] = DK_ALIGN32;
5145 DirectiveKindMap[".balign"] = DK_BALIGN;
5146 DirectiveKindMap[".balignw"] = DK_BALIGNW;
5147 DirectiveKindMap[".balignl"] = DK_BALIGNL;
5148 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
5149 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
5150 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
5151 DirectiveKindMap[".org"] = DK_ORG;
5152 DirectiveKindMap[".fill"] = DK_FILL;
5153 DirectiveKindMap[".zero"] = DK_ZERO;
5154 DirectiveKindMap[".extern"] = DK_EXTERN;
5155 DirectiveKindMap[".globl"] = DK_GLOBL;
5156 DirectiveKindMap[".global"] = DK_GLOBAL;
Eli Bendersky17233942013-01-15 22:59:42 +00005157 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
5158 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
5159 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
5160 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
5161 DirectiveKindMap[".reference"] = DK_REFERENCE;
5162 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
5163 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
5164 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
5165 DirectiveKindMap[".comm"] = DK_COMM;
5166 DirectiveKindMap[".common"] = DK_COMMON;
5167 DirectiveKindMap[".lcomm"] = DK_LCOMM;
5168 DirectiveKindMap[".abort"] = DK_ABORT;
5169 DirectiveKindMap[".include"] = DK_INCLUDE;
5170 DirectiveKindMap[".incbin"] = DK_INCBIN;
5171 DirectiveKindMap[".code16"] = DK_CODE16;
5172 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
5173 DirectiveKindMap[".rept"] = DK_REPT;
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00005174 DirectiveKindMap[".rep"] = DK_REPT;
Eli Bendersky17233942013-01-15 22:59:42 +00005175 DirectiveKindMap[".irp"] = DK_IRP;
5176 DirectiveKindMap[".irpc"] = DK_IRPC;
5177 DirectiveKindMap[".endr"] = DK_ENDR;
5178 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
5179 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
5180 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
5181 DirectiveKindMap[".if"] = DK_IF;
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00005182 DirectiveKindMap[".ifeq"] = DK_IFEQ;
5183 DirectiveKindMap[".ifge"] = DK_IFGE;
5184 DirectiveKindMap[".ifgt"] = DK_IFGT;
5185 DirectiveKindMap[".ifle"] = DK_IFLE;
5186 DirectiveKindMap[".iflt"] = DK_IFLT;
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00005187 DirectiveKindMap[".ifne"] = DK_IFNE;
Eli Bendersky17233942013-01-15 22:59:42 +00005188 DirectiveKindMap[".ifb"] = DK_IFB;
5189 DirectiveKindMap[".ifnb"] = DK_IFNB;
5190 DirectiveKindMap[".ifc"] = DK_IFC;
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00005191 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
Eli Bendersky17233942013-01-15 22:59:42 +00005192 DirectiveKindMap[".ifnc"] = DK_IFNC;
Sid Manning51c35602015-03-18 14:20:54 +00005193 DirectiveKindMap[".ifnes"] = DK_IFNES;
Eli Bendersky17233942013-01-15 22:59:42 +00005194 DirectiveKindMap[".ifdef"] = DK_IFDEF;
5195 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
5196 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
5197 DirectiveKindMap[".elseif"] = DK_ELSEIF;
5198 DirectiveKindMap[".else"] = DK_ELSE;
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00005199 DirectiveKindMap[".end"] = DK_END;
Eli Bendersky17233942013-01-15 22:59:42 +00005200 DirectiveKindMap[".endif"] = DK_ENDIF;
5201 DirectiveKindMap[".skip"] = DK_SKIP;
5202 DirectiveKindMap[".space"] = DK_SPACE;
5203 DirectiveKindMap[".file"] = DK_FILE;
5204 DirectiveKindMap[".line"] = DK_LINE;
5205 DirectiveKindMap[".loc"] = DK_LOC;
5206 DirectiveKindMap[".stabs"] = DK_STABS;
Reid Kleckner2214ed82016-01-29 00:49:42 +00005207 DirectiveKindMap[".cv_file"] = DK_CV_FILE;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00005208 DirectiveKindMap[".cv_func_id"] = DK_CV_FUNC_ID;
Reid Kleckner2214ed82016-01-29 00:49:42 +00005209 DirectiveKindMap[".cv_loc"] = DK_CV_LOC;
5210 DirectiveKindMap[".cv_linetable"] = DK_CV_LINETABLE;
David Majnemer6fcbd7e2016-01-29 19:24:12 +00005211 DirectiveKindMap[".cv_inline_linetable"] = DK_CV_INLINE_LINETABLE;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00005212 DirectiveKindMap[".cv_inline_site_id"] = DK_CV_INLINE_SITE_ID;
David Majnemer408b5e62016-02-05 01:55:49 +00005213 DirectiveKindMap[".cv_def_range"] = DK_CV_DEF_RANGE;
Reid Kleckner2214ed82016-01-29 00:49:42 +00005214 DirectiveKindMap[".cv_stringtable"] = DK_CV_STRINGTABLE;
5215 DirectiveKindMap[".cv_filechecksums"] = DK_CV_FILECHECKSUMS;
Reid Kleckner26fa1bf2017-09-19 18:14:45 +00005216 DirectiveKindMap[".cv_filechecksumoffset"] = DK_CV_FILECHECKSUM_OFFSET;
Reid Kleckner9cdd4df2017-10-11 21:24:33 +00005217 DirectiveKindMap[".cv_fpo_data"] = DK_CV_FPO_DATA;
Eli Bendersky17233942013-01-15 22:59:42 +00005218 DirectiveKindMap[".sleb128"] = DK_SLEB128;
5219 DirectiveKindMap[".uleb128"] = DK_ULEB128;
5220 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
5221 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
5222 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
5223 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
5224 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
5225 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
5226 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
5227 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
5228 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
5229 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
5230 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
5231 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
5232 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
5233 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
5234 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
5235 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
Saleem Abdulrasoola219b3d2017-07-28 03:39:19 +00005236 DirectiveKindMap[".cfi_return_column"] = DK_CFI_RETURN_COLUMN;
Eli Bendersky17233942013-01-15 22:59:42 +00005237 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
5238 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
5239 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00005240 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
Eli Bendersky17233942013-01-15 22:59:42 +00005241 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
5242 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
5243 DirectiveKindMap[".macro"] = DK_MACRO;
Nico Weber155dccd12014-07-24 17:08:39 +00005244 DirectiveKindMap[".exitm"] = DK_EXITM;
Eli Bendersky17233942013-01-15 22:59:42 +00005245 DirectiveKindMap[".endm"] = DK_ENDM;
5246 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
5247 DirectiveKindMap[".purgem"] = DK_PURGEM;
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00005248 DirectiveKindMap[".err"] = DK_ERR;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00005249 DirectiveKindMap[".error"] = DK_ERROR;
Nico Weber404012b2014-07-24 16:26:06 +00005250 DirectiveKindMap[".warning"] = DK_WARNING;
Michael Zuckerman56704612017-05-01 13:20:12 +00005251 DirectiveKindMap[".altmacro"] = DK_ALTMACRO;
5252 DirectiveKindMap[".noaltmacro"] = DK_NOALTMACRO;
Daniel Sanders9f6ad492015-11-12 13:33:00 +00005253 DirectiveKindMap[".reloc"] = DK_RELOC;
Petr Hosek731bb9c2016-08-23 21:34:53 +00005254 DirectiveKindMap[".dc"] = DK_DC;
5255 DirectiveKindMap[".dc.a"] = DK_DC_A;
5256 DirectiveKindMap[".dc.b"] = DK_DC_B;
5257 DirectiveKindMap[".dc.d"] = DK_DC_D;
5258 DirectiveKindMap[".dc.l"] = DK_DC_L;
5259 DirectiveKindMap[".dc.s"] = DK_DC_S;
5260 DirectiveKindMap[".dc.w"] = DK_DC_W;
5261 DirectiveKindMap[".dc.x"] = DK_DC_X;
Petr Hosek4cb08ce2016-09-23 19:25:15 +00005262 DirectiveKindMap[".dcb"] = DK_DCB;
5263 DirectiveKindMap[".dcb.b"] = DK_DCB_B;
5264 DirectiveKindMap[".dcb.d"] = DK_DCB_D;
5265 DirectiveKindMap[".dcb.l"] = DK_DCB_L;
5266 DirectiveKindMap[".dcb.s"] = DK_DCB_S;
5267 DirectiveKindMap[".dcb.w"] = DK_DCB_W;
5268 DirectiveKindMap[".dcb.x"] = DK_DCB_X;
Petr Hosek85b2f672016-09-23 21:53:36 +00005269 DirectiveKindMap[".ds"] = DK_DS;
5270 DirectiveKindMap[".ds.b"] = DK_DS_B;
5271 DirectiveKindMap[".ds.d"] = DK_DS_D;
5272 DirectiveKindMap[".ds.l"] = DK_DS_L;
5273 DirectiveKindMap[".ds.p"] = DK_DS_P;
5274 DirectiveKindMap[".ds.s"] = DK_DS_S;
5275 DirectiveKindMap[".ds.w"] = DK_DS_W;
5276 DirectiveKindMap[".ds.x"] = DK_DS_X;
Coby Tayree01e53202017-10-02 14:36:31 +00005277 DirectiveKindMap[".print"] = DK_PRINT;
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00005278}
5279
Jim Grosbach4b905842013-09-20 23:08:21 +00005280MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005281 AsmToken EndToken, StartToken = getTok();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005282
Rafael Espindola34b9c512012-06-03 23:57:14 +00005283 unsigned NestLevel = 0;
Eugene Zelenko33d7b762016-08-23 17:14:32 +00005284 while (true) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005285 // Check whether we have reached the end of the file.
Rafael Espindola34b9c512012-06-03 23:57:14 +00005286 if (getLexer().is(AsmToken::Eof)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00005287 printError(DirectiveLoc, "no matching '.endr' in definition");
Craig Topper353eda42014-04-24 06:44:33 +00005288 return nullptr;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005289 }
5290
Rafael Espindola34b9c512012-06-03 23:57:14 +00005291 if (Lexer.is(AsmToken::Identifier) &&
Nikolay Haustov95b4fcd2016-03-01 08:18:28 +00005292 (getTok().getIdentifier() == ".rept" ||
5293 getTok().getIdentifier() == ".irp" ||
5294 getTok().getIdentifier() == ".irpc")) {
Rafael Espindola34b9c512012-06-03 23:57:14 +00005295 ++NestLevel;
5296 }
5297
5298 // Otherwise, check whether we have reached the .endr.
Jim Grosbach4b905842013-09-20 23:08:21 +00005299 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
Rafael Espindola34b9c512012-06-03 23:57:14 +00005300 if (NestLevel == 0) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005301 EndToken = getTok();
5302 Lex();
Rafael Espindola34b9c512012-06-03 23:57:14 +00005303 if (Lexer.isNot(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00005304 printError(getTok().getLoc(),
5305 "unexpected token in '.endr' directive");
Craig Topper353eda42014-04-24 06:44:33 +00005306 return nullptr;
Rafael Espindola34b9c512012-06-03 23:57:14 +00005307 }
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005308 break;
5309 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00005310 --NestLevel;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005311 }
5312
Rafael Espindola34b9c512012-06-03 23:57:14 +00005313 // Otherwise, scan till the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005314 eatToEndOfStatement();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005315 }
5316
5317 const char *BodyStart = StartToken.getLoc().getPointer();
5318 const char *BodyEnd = EndToken.getLoc().getPointer();
5319 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
5320
Rafael Espindola34b9c512012-06-03 23:57:14 +00005321 // We Are Anonymous.
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00005322 MacroLikeBodies.emplace_back(StringRef(), Body, MCAsmMacroParameters());
Benjamin Kramer1df3a1f2013-08-04 09:06:29 +00005323 return &MacroLikeBodies.back();
Rafael Espindola34b9c512012-06-03 23:57:14 +00005324}
5325
Jim Grosbach4b905842013-09-20 23:08:21 +00005326void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +00005327 raw_svector_ostream &OS) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005328 OS << ".endr\n";
5329
Rafael Espindola3560ff22014-08-27 20:03:13 +00005330 std::unique_ptr<MemoryBuffer> Instantiation =
5331 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005332
Rafael Espindola34b9c512012-06-03 23:57:14 +00005333 // Create the macro instantiation object and add to the current macro
5334 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00005335 MacroInstantiation *MI = new MacroInstantiation(
5336 DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Rafael Espindola34b9c512012-06-03 23:57:14 +00005337 ActiveMacros.push_back(MI);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005338
Rafael Espindola34b9c512012-06-03 23:57:14 +00005339 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00005340 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00005341 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Rafael Espindola34b9c512012-06-03 23:57:14 +00005342 Lex();
5343}
5344
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00005345/// parseDirectiveRept
5346/// ::= .rep | .rept count
5347bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00005348 const MCExpr *CountExpr;
5349 SMLoc CountLoc = getTok().getLoc();
5350 if (parseExpression(CountExpr))
5351 return true;
5352
Rafael Espindola34b9c512012-06-03 23:57:14 +00005353 int64_t Count;
Nirav Dave6c0665e2018-04-30 19:22:40 +00005354 if (!CountExpr->evaluateAsAbsolute(Count, getStreamer().getAssemblerPtr())) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00005355 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
5356 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00005357
Nirav Davea645433c2016-07-18 15:24:03 +00005358 if (check(Count < 0, CountLoc, "Count is negative") ||
5359 parseToken(AsmToken::EndOfStatement,
5360 "unexpected token in '" + Dir + "' directive"))
5361 return true;
Rafael Espindola34b9c512012-06-03 23:57:14 +00005362
5363 // Lex the rept definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005364 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola34b9c512012-06-03 23:57:14 +00005365 if (!M)
5366 return true;
5367
5368 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5369 // to hold the macro body with substitutions.
5370 SmallString<256> Buf;
Rafael Espindola34b9c512012-06-03 23:57:14 +00005371 raw_svector_ostream OS(Buf);
5372 while (Count--) {
Toma Tabacu217116e2015-04-27 10:50:29 +00005373 // Note that the AtPseudoVariable is disabled for instantiations of .rep(t).
5374 if (expandMacro(OS, M->Body, None, None, false, getTok().getLoc()))
Rafael Espindola34b9c512012-06-03 23:57:14 +00005375 return true;
5376 }
Jim Grosbach4b905842013-09-20 23:08:21 +00005377 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005378
5379 return false;
5380}
5381
Jim Grosbach4b905842013-09-20 23:08:21 +00005382/// parseDirectiveIrp
Rafael Espindola768b41c2012-06-15 14:02:34 +00005383/// ::= .irp symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00005384bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00005385 MCAsmMacroParameter Parameter;
Eli Bendersky38274122013-01-14 23:22:36 +00005386 MCAsmMacroArguments A;
Nirav Davea645433c2016-07-18 15:24:03 +00005387 if (check(parseIdentifier(Parameter.Name),
5388 "expected identifier in '.irp' directive") ||
5389 parseToken(AsmToken::Comma, "expected comma in '.irp' directive") ||
5390 parseMacroArguments(nullptr, A) ||
5391 parseToken(AsmToken::EndOfStatement, "expected End of Statement"))
Rafael Espindola768b41c2012-06-15 14:02:34 +00005392 return true;
5393
Rafael Espindola768b41c2012-06-15 14:02:34 +00005394 // Lex the irp definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005395 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola768b41c2012-06-15 14:02:34 +00005396 if (!M)
5397 return true;
5398
5399 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5400 // to hold the macro body with substitutions.
5401 SmallString<256> Buf;
5402 raw_svector_ostream OS(Buf);
5403
Craig Topper84008482015-10-10 05:38:14 +00005404 for (const MCAsmMacroArgument &Arg : A) {
Toma Tabacu217116e2015-04-27 10:50:29 +00005405 // Note that the AtPseudoVariable is enabled for instantiations of .irp.
5406 // This is undocumented, but GAS seems to support it.
Craig Topper84008482015-10-10 05:38:14 +00005407 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindola768b41c2012-06-15 14:02:34 +00005408 return true;
5409 }
5410
Jim Grosbach4b905842013-09-20 23:08:21 +00005411 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola768b41c2012-06-15 14:02:34 +00005412
5413 return false;
5414}
5415
Jim Grosbach4b905842013-09-20 23:08:21 +00005416/// parseDirectiveIrpc
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005417/// ::= .irpc symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00005418bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00005419 MCAsmMacroParameter Parameter;
Eli Bendersky38274122013-01-14 23:22:36 +00005420 MCAsmMacroArguments A;
Nirav Davea645433c2016-07-18 15:24:03 +00005421
5422 if (check(parseIdentifier(Parameter.Name),
5423 "expected identifier in '.irpc' directive") ||
5424 parseToken(AsmToken::Comma, "expected comma in '.irpc' directive") ||
5425 parseMacroArguments(nullptr, A))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005426 return true;
5427
5428 if (A.size() != 1 || A.front().size() != 1)
5429 return TokError("unexpected token in '.irpc' directive");
5430
5431 // Eat the end of statement.
Nirav Davea645433c2016-07-18 15:24:03 +00005432 if (parseToken(AsmToken::EndOfStatement, "expected end of statement"))
5433 return true;
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005434
5435 // Lex the irpc definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005436 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005437 if (!M)
5438 return true;
5439
5440 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5441 // to hold the macro body with substitutions.
5442 SmallString<256> Buf;
5443 raw_svector_ostream OS(Buf);
5444
5445 StringRef Values = A.front().front().getString();
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00005446 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
Eli Benderskya7b905e2013-01-14 19:00:26 +00005447 MCAsmMacroArgument Arg;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00005448 Arg.emplace_back(AsmToken::Identifier, Values.slice(I, I + 1));
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005449
Toma Tabacu217116e2015-04-27 10:50:29 +00005450 // Note that the AtPseudoVariable is enabled for instantiations of .irpc.
5451 // This is undocumented, but GAS seems to support it.
5452 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005453 return true;
5454 }
5455
Jim Grosbach4b905842013-09-20 23:08:21 +00005456 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005457
5458 return false;
5459}
5460
Jim Grosbach4b905842013-09-20 23:08:21 +00005461bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
Rafael Espindola34b9c512012-06-03 23:57:14 +00005462 if (ActiveMacros.empty())
Preston Gurdeb3ebf12012-09-19 20:23:43 +00005463 return TokError("unmatched '.endr' directive");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005464
5465 // The only .repl that should get here are the ones created by
Jim Grosbach4b905842013-09-20 23:08:21 +00005466 // instantiateMacroLikeBody.
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005467 assert(getLexer().is(AsmToken::EndOfStatement));
5468
Jim Grosbach4b905842013-09-20 23:08:21 +00005469 handleMacroExit();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005470 return false;
5471}
Rafael Espindola12d73d12010-09-11 16:45:15 +00005472
Jim Grosbach4b905842013-09-20 23:08:21 +00005473bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
Benjamin Kramer1a136112013-02-15 20:37:21 +00005474 size_t Len) {
Eli Friedman0f4871d2012-10-22 23:58:19 +00005475 const MCExpr *Value;
5476 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005477 if (parseExpression(Value))
Eli Friedman0f4871d2012-10-22 23:58:19 +00005478 return true;
5479 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5480 if (!MCE)
5481 return Error(ExprLoc, "unexpected expression in _emit");
5482 uint64_t IntValue = MCE->getValue();
Craig Topper55b1f292015-10-10 20:17:07 +00005483 if (!isUInt<8>(IntValue) && !isInt<8>(IntValue))
Eli Friedman0f4871d2012-10-22 23:58:19 +00005484 return Error(ExprLoc, "literal value out of range for directive");
5485
Craig Topper7d5b2312015-10-10 05:25:02 +00005486 Info.AsmRewrites->emplace_back(AOK_Emit, IDLoc, Len);
Chad Rosierc7f552c2013-02-12 21:33:51 +00005487 return false;
5488}
5489
Jim Grosbach4b905842013-09-20 23:08:21 +00005490bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
Chad Rosierc7f552c2013-02-12 21:33:51 +00005491 const MCExpr *Value;
5492 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005493 if (parseExpression(Value))
Chad Rosierc7f552c2013-02-12 21:33:51 +00005494 return true;
5495 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5496 if (!MCE)
5497 return Error(ExprLoc, "unexpected expression in align");
5498 uint64_t IntValue = MCE->getValue();
5499 if (!isPowerOf2_64(IntValue))
5500 return Error(ExprLoc, "literal value not a power of two greater then zero");
5501
Craig Topper7d5b2312015-10-10 05:25:02 +00005502 Info.AsmRewrites->emplace_back(AOK_Align, IDLoc, 5, Log2_64(IntValue));
Eli Friedman0f4871d2012-10-22 23:58:19 +00005503 return false;
5504}
5505
Coby Tayree01e53202017-10-02 14:36:31 +00005506bool AsmParser::parseDirectivePrint(SMLoc DirectiveLoc) {
5507 const AsmToken StrTok = getTok();
5508 Lex();
5509 if (StrTok.isNot(AsmToken::String) || StrTok.getString().front() != '"')
5510 return Error(DirectiveLoc, "expected double quoted string after .print");
5511 if (parseToken(AsmToken::EndOfStatement, "expected end of statement"))
5512 return true;
5513 llvm::outs() << StrTok.getStringContents() << '\n';
5514 return false;
5515}
5516
Chad Rosierf43fcf52013-02-13 21:27:17 +00005517// We are comparing pointers, but the pointers are relative to a single string.
5518// Thus, this should always be deterministic.
Benjamin Kramer8817cca2013-09-22 14:09:50 +00005519static int rewritesSort(const AsmRewrite *AsmRewriteA,
5520 const AsmRewrite *AsmRewriteB) {
Chad Rosiereb5c1682013-02-13 18:38:58 +00005521 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
5522 return -1;
5523 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
5524 return 1;
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005525
Chad Rosierfce4fab2013-04-08 17:43:47 +00005526 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
5527 // rewrite to the same location. Make sure the SizeDirective rewrite is
5528 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
5529 // ensures the sort algorithm is stable.
Jim Grosbach4b905842013-09-20 23:08:21 +00005530 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
5531 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005532 return -1;
Chad Rosierfce4fab2013-04-08 17:43:47 +00005533
Jim Grosbach4b905842013-09-20 23:08:21 +00005534 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
5535 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005536 return 1;
Jim Grosbach4b905842013-09-20 23:08:21 +00005537 llvm_unreachable("Unstable rewrite sort.");
Chad Rosierb2144ce2013-02-13 01:03:13 +00005538}
5539
Jim Grosbach4b905842013-09-20 23:08:21 +00005540bool AsmParser::parseMSInlineAsm(
5541 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
Eugene Zelenko4b6ff6b2017-02-10 01:33:54 +00005542 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool>> &OpDecls,
Jim Grosbach4b905842013-09-20 23:08:21 +00005543 SmallVectorImpl<std::string> &Constraints,
5544 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
5545 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
Chad Rosier37e755c2012-10-23 17:43:43 +00005546 SmallVector<void *, 4> InputDecls;
5547 SmallVector<void *, 4> OutputDecls;
Chad Rosiera4bc9432013-01-10 22:10:27 +00005548 SmallVector<bool, 4> InputDeclsAddressOf;
5549 SmallVector<bool, 4> OutputDeclsAddressOf;
Chad Rosier8bce6642012-10-18 15:49:34 +00005550 SmallVector<std::string, 4> InputConstraints;
5551 SmallVector<std::string, 4> OutputConstraints;
Benjamin Kramer1a136112013-02-15 20:37:21 +00005552 SmallVector<unsigned, 4> ClobberRegs;
Chad Rosier8bce6642012-10-18 15:49:34 +00005553
Benjamin Kramer1a136112013-02-15 20:37:21 +00005554 SmallVector<AsmRewrite, 4> AsmStrRewrites;
Chad Rosier8bce6642012-10-18 15:49:34 +00005555
5556 // Prime the lexer.
5557 Lex();
5558
5559 // While we have input, parse each statement.
5560 unsigned InputIdx = 0;
5561 unsigned OutputIdx = 0;
5562 while (getLexer().isNot(AsmToken::Eof)) {
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00005563 // Parse curly braces marking block start/end
5564 if (parseCurlyBlockScope(AsmStrRewrites))
5565 continue;
5566
Eli Friedman0f4871d2012-10-22 23:58:19 +00005567 ParseStatementInfo Info(&AsmStrRewrites);
Nirav Dave2364748a2016-09-16 18:30:20 +00005568 bool StatementErr = parseStatement(Info, &SI);
Nirav Dave9fa8af22016-09-13 13:55:06 +00005569
Nirav Dave2364748a2016-09-16 18:30:20 +00005570 if (StatementErr || Info.ParseError) {
5571 // Emit pending errors if any exist.
5572 printPendingErrors();
Nico Webere204c482016-09-13 18:17:00 +00005573 return true;
Nirav Dave2364748a2016-09-16 18:30:20 +00005574 }
5575
5576 // No pending error should exist here.
5577 assert(!hasPendingError() && "unexpected error from parseStatement");
Chad Rosier149e8e02012-12-12 22:45:52 +00005578
Benjamin Kramer1a136112013-02-15 20:37:21 +00005579 if (Info.Opcode == ~0U)
5580 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00005581
Benjamin Kramer1a136112013-02-15 20:37:21 +00005582 const MCInstrDesc &Desc = MII->get(Info.Opcode);
Chad Rosier8bce6642012-10-18 15:49:34 +00005583
Benjamin Kramer1a136112013-02-15 20:37:21 +00005584 // Build the list of clobbers, outputs and inputs.
5585 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
David Blaikie960ea3f2014-06-08 16:18:35 +00005586 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005587
Benjamin Kramer1a136112013-02-15 20:37:21 +00005588 // Immediate.
David Blaikie960ea3f2014-06-08 16:18:35 +00005589 if (Operand.isImm())
Benjamin Kramer1a136112013-02-15 20:37:21 +00005590 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00005591
Benjamin Kramer1a136112013-02-15 20:37:21 +00005592 // Register operand.
Nico Weber42f79db2014-07-17 20:24:55 +00005593 if (Operand.isReg() && !Operand.needAddressOf() &&
5594 !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
Benjamin Kramer1a136112013-02-15 20:37:21 +00005595 unsigned NumDefs = Desc.getNumDefs();
5596 // Clobber.
David Blaikie960ea3f2014-06-08 16:18:35 +00005597 if (NumDefs && Operand.getMCOperandNum() < NumDefs)
5598 ClobberRegs.push_back(Operand.getReg());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005599 continue;
5600 }
5601
5602 // Expr/Input or Output.
David Blaikie960ea3f2014-06-08 16:18:35 +00005603 StringRef SymName = Operand.getSymName();
Chad Rosiere81309b2013-04-09 17:53:49 +00005604 if (SymName.empty())
5605 continue;
5606
David Blaikie960ea3f2014-06-08 16:18:35 +00005607 void *OpDecl = Operand.getOpDecl();
Benjamin Kramer1a136112013-02-15 20:37:21 +00005608 if (!OpDecl)
5609 continue;
5610
5611 bool isOutput = (i == 1) && Desc.mayStore();
Chad Rosiere81309b2013-04-09 17:53:49 +00005612 SMLoc Start = SMLoc::getFromPointer(SymName.data());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005613 if (isOutput) {
5614 ++InputIdx;
5615 OutputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00005616 OutputDeclsAddressOf.push_back(Operand.needAddressOf());
Yaron Keren075759a2015-03-30 15:42:36 +00005617 OutputConstraints.push_back(("=" + Operand.getConstraint()).str());
Craig Topper7d5b2312015-10-10 05:25:02 +00005618 AsmStrRewrites.emplace_back(AOK_Output, Start, SymName.size());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005619 } else {
5620 InputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00005621 InputDeclsAddressOf.push_back(Operand.needAddressOf());
5622 InputConstraints.push_back(Operand.getConstraint().str());
Craig Topper7d5b2312015-10-10 05:25:02 +00005623 AsmStrRewrites.emplace_back(AOK_Input, Start, SymName.size());
Chad Rosier8bce6642012-10-18 15:49:34 +00005624 }
Chad Rosier8bce6642012-10-18 15:49:34 +00005625 }
Reid Kleckneree088972013-12-10 18:27:32 +00005626
5627 // Consider implicit defs to be clobbers. Think of cpuid and push.
Craig Toppere5e035a32015-12-05 07:13:35 +00005628 ArrayRef<MCPhysReg> ImpDefs(Desc.getImplicitDefs(),
5629 Desc.getNumImplicitDefs());
David Majnemer8114c1a2014-06-23 02:17:16 +00005630 ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end());
Chad Rosier8bce6642012-10-18 15:49:34 +00005631 }
5632
5633 // Set the number of Outputs and Inputs.
Chad Rosierf641baa2012-10-18 19:39:30 +00005634 NumOutputs = OutputDecls.size();
5635 NumInputs = InputDecls.size();
Chad Rosier8bce6642012-10-18 15:49:34 +00005636
5637 // Set the unique clobbers.
Benjamin Kramer1a136112013-02-15 20:37:21 +00005638 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
5639 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
5640 ClobberRegs.end());
5641 Clobbers.assign(ClobberRegs.size(), std::string());
5642 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
5643 raw_string_ostream OS(Clobbers[I]);
5644 IP->printRegName(OS, ClobberRegs[I]);
5645 }
Chad Rosier8bce6642012-10-18 15:49:34 +00005646
5647 // Merge the various outputs and inputs. Output are expected first.
5648 if (NumOutputs || NumInputs) {
5649 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierf641baa2012-10-18 19:39:30 +00005650 OpDecls.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00005651 Constraints.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00005652 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00005653 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00005654 Constraints[i] = OutputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005655 }
5656 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00005657 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00005658 Constraints[j] = InputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005659 }
5660 }
5661
5662 // Build the IR assembly string.
Alp Tokere69170a2014-06-26 22:52:05 +00005663 std::string AsmStringIR;
5664 raw_string_ostream OS(AsmStringIR);
Alp Tokera55b95b2014-07-06 10:33:31 +00005665 StringRef ASMString =
5666 SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
5667 const char *AsmStart = ASMString.begin();
5668 const char *AsmEnd = ASMString.end();
Jim Grosbach4b905842013-09-20 23:08:21 +00005669 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
David Majnemer8114c1a2014-06-23 02:17:16 +00005670 for (const AsmRewrite &AR : AsmStrRewrites) {
5671 AsmRewriteKind Kind = AR.Kind;
Chad Rosierff10ed12013-04-12 16:26:42 +00005672
David Majnemer8114c1a2014-06-23 02:17:16 +00005673 const char *Loc = AR.Loc.getPointer();
Chad Rosier17d37992013-03-19 21:12:14 +00005674 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
Chad Rosier0f48c552012-10-19 20:57:14 +00005675
Chad Rosier120eefd2013-03-19 17:32:17 +00005676 // Emit everything up to the immediate/expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00005677 if (unsigned Len = Loc - AsmStart)
Chad Rosier17d37992013-03-19 21:12:14 +00005678 OS << StringRef(AsmStart, Len);
Chad Rosier0f48c552012-10-19 20:57:14 +00005679
Chad Rosier37e755c2012-10-23 17:43:43 +00005680 // Skip the original expression.
5681 if (Kind == AOK_Skip) {
David Majnemer8114c1a2014-06-23 02:17:16 +00005682 AsmStart = Loc + AR.Len;
Chad Rosier37e755c2012-10-23 17:43:43 +00005683 continue;
5684 }
5685
Chad Rosierff10ed12013-04-12 16:26:42 +00005686 unsigned AdditionalSkip = 0;
Chad Rosier8bce6642012-10-18 15:49:34 +00005687 // Rewrite expressions in $N notation.
Chad Rosier0f48c552012-10-19 20:57:14 +00005688 switch (Kind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00005689 default:
5690 break;
Coby Tayreed8912892017-08-24 08:46:25 +00005691 case AOK_IntelExpr:
5692 assert(AR.IntelExp.isValid() && "cannot write invalid intel expression");
5693 if (AR.IntelExp.NeedBracs)
5694 OS << "[";
5695 if (AR.IntelExp.hasBaseReg())
5696 OS << AR.IntelExp.BaseReg;
5697 if (AR.IntelExp.hasIndexReg())
5698 OS << (AR.IntelExp.hasBaseReg() ? " + " : "")
5699 << AR.IntelExp.IndexReg;
5700 if (AR.IntelExp.Scale > 1)
5701 OS << " * $$" << AR.IntelExp.Scale;
5702 if (AR.IntelExp.Imm || !AR.IntelExp.hasRegs())
5703 OS << (AR.IntelExp.hasRegs() ? " + $$" : "$$") << AR.IntelExp.Imm;
5704 if (AR.IntelExp.NeedBracs)
5705 OS << "]";
Chad Rosier8bce6642012-10-18 15:49:34 +00005706 break;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005707 case AOK_Label:
Matt Arsenault4e273432014-12-04 00:06:57 +00005708 OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005709 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005710 case AOK_Input:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005711 OS << '$' << InputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00005712 break;
5713 case AOK_Output:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005714 OS << '$' << OutputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00005715 break;
Chad Rosier0f48c552012-10-19 20:57:14 +00005716 case AOK_SizeDirective:
David Majnemer8114c1a2014-06-23 02:17:16 +00005717 switch (AR.Val) {
Chad Rosier0f48c552012-10-19 20:57:14 +00005718 default: break;
5719 case 8: OS << "byte ptr "; break;
5720 case 16: OS << "word ptr "; break;
5721 case 32: OS << "dword ptr "; break;
5722 case 64: OS << "qword ptr "; break;
5723 case 80: OS << "xword ptr "; break;
5724 case 128: OS << "xmmword ptr "; break;
5725 case 256: OS << "ymmword ptr "; break;
5726 }
Eli Friedman0f4871d2012-10-22 23:58:19 +00005727 break;
5728 case AOK_Emit:
5729 OS << ".byte";
5730 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00005731 case AOK_Align: {
Reid Klecknerfb1c1c72015-10-27 17:32:48 +00005732 // MS alignment directives are measured in bytes. If the native assembler
5733 // measures alignment in bytes, we can pass it straight through.
5734 OS << ".align";
5735 if (getContext().getAsmInfo()->getAlignmentIsInBytes())
5736 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00005737
Reid Klecknerfb1c1c72015-10-27 17:32:48 +00005738 // Alignment is in log2 form, so print that instead and skip the original
5739 // immediate.
5740 unsigned Val = AR.Val;
5741 OS << ' ' << Val;
Benjamin Kramer1a136112013-02-15 20:37:21 +00005742 assert(Val < 10 && "Expected alignment less then 2^10.");
Chad Rosierc7f552c2013-02-12 21:33:51 +00005743 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
5744 break;
5745 }
Michael Zuckerman02ecd432015-12-13 17:07:23 +00005746 case AOK_EVEN:
5747 OS << ".even";
5748 break;
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00005749 case AOK_EndOfStatement:
5750 OS << "\n\t";
5751 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005752 }
Chad Rosier0f48c552012-10-19 20:57:14 +00005753
Chad Rosier8bce6642012-10-18 15:49:34 +00005754 // Skip the original expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00005755 AsmStart = Loc + AR.Len + AdditionalSkip;
Chad Rosier8bce6642012-10-18 15:49:34 +00005756 }
5757
5758 // Emit the remainder of the asm string.
Chad Rosier17d37992013-03-19 21:12:14 +00005759 if (AsmStart != AsmEnd)
5760 OS << StringRef(AsmStart, AsmEnd - AsmStart);
Chad Rosier8bce6642012-10-18 15:49:34 +00005761
5762 AsmString = OS.str();
5763 return false;
5764}
5765
Pete Cooper80d21cb2015-06-22 19:35:57 +00005766namespace llvm {
5767namespace MCParserUtils {
5768
5769/// Returns whether the given symbol is used anywhere in the given expression,
5770/// or subexpressions.
5771static bool isSymbolUsedInExpression(const MCSymbol *Sym, const MCExpr *Value) {
5772 switch (Value->getKind()) {
5773 case MCExpr::Binary: {
5774 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
5775 return isSymbolUsedInExpression(Sym, BE->getLHS()) ||
5776 isSymbolUsedInExpression(Sym, BE->getRHS());
5777 }
5778 case MCExpr::Target:
5779 case MCExpr::Constant:
5780 return false;
5781 case MCExpr::SymbolRef: {
5782 const MCSymbol &S =
5783 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
5784 if (S.isVariable())
5785 return isSymbolUsedInExpression(Sym, S.getVariableValue());
5786 return &S == Sym;
5787 }
5788 case MCExpr::Unary:
5789 return isSymbolUsedInExpression(
5790 Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
5791 }
5792
5793 llvm_unreachable("Unknown expr kind!");
5794}
5795
5796bool parseAssignmentExpression(StringRef Name, bool allow_redef,
5797 MCAsmParser &Parser, MCSymbol *&Sym,
Nirav Dave05b58912018-06-05 15:13:39 +00005798 const MCExpr *&Value, bool AllowExtendedExpr) {
Pete Cooper80d21cb2015-06-22 19:35:57 +00005799
5800 // FIXME: Use better location, we should use proper tokens.
Nirav Davefd910412016-06-17 16:06:17 +00005801 SMLoc EqualLoc = Parser.getTok().getLoc();
Nirav Dave05b58912018-06-05 15:13:39 +00005802 SMLoc EndLoc;
5803 if (AllowExtendedExpr) {
5804 if (Parser.getTargetParser().parseAssignmentExpression(Value, EndLoc)) {
5805 return Parser.TokError("missing expression");
5806 }
5807 } else if (Parser.parseExpression(Value, EndLoc))
5808 return Parser.TokError("missing expression");
Pete Cooper80d21cb2015-06-22 19:35:57 +00005809
5810 // Note: we don't count b as used in "a = b". This is to allow
5811 // a = b
5812 // b = c
5813
Nirav Dave1a9044b2016-10-24 14:35:29 +00005814 if (Parser.parseToken(AsmToken::EndOfStatement))
5815 return true;
Pete Cooper80d21cb2015-06-22 19:35:57 +00005816
5817 // Validate that the LHS is allowed to be a variable (either it has not been
5818 // used as a symbol, or it is an absolute symbol).
5819 Sym = Parser.getContext().lookupSymbol(Name);
5820 if (Sym) {
5821 // Diagnose assignment to a label.
5822 //
5823 // FIXME: Diagnostics. Note the location of the definition as a label.
5824 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
5825 if (isSymbolUsedInExpression(Sym, Value))
5826 return Parser.Error(EqualLoc, "Recursive use of '" + Name + "'");
Vedant Kumar86dbd922015-08-31 17:44:53 +00005827 else if (Sym->isUndefined(/*SetUsed*/ false) && !Sym->isUsed() &&
5828 !Sym->isVariable())
Pete Cooper80d21cb2015-06-22 19:35:57 +00005829 ; // Allow redefinitions of undefined symbols only used in directives.
5830 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
5831 ; // Allow redefinitions of variables that haven't yet been used.
5832 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
5833 return Parser.Error(EqualLoc, "redefinition of '" + Name + "'");
5834 else if (!Sym->isVariable())
5835 return Parser.Error(EqualLoc, "invalid assignment to '" + Name + "'");
5836 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
5837 return Parser.Error(EqualLoc,
5838 "invalid reassignment of non-absolute variable '" +
5839 Name + "'");
Pete Cooper80d21cb2015-06-22 19:35:57 +00005840 } else if (Name == ".") {
Oliver Stannard268f42f2016-12-14 10:43:58 +00005841 Parser.getStreamer().emitValueToOffset(Value, 0, EqualLoc);
Pete Cooper80d21cb2015-06-22 19:35:57 +00005842 return false;
5843 } else
5844 Sym = Parser.getContext().getOrCreateSymbol(Name);
5845
5846 Sym->setRedefinable(allow_redef);
5847
5848 return false;
5849}
5850
Eugene Zelenko33d7b762016-08-23 17:14:32 +00005851} // end namespace MCParserUtils
5852} // end namespace llvm
Pete Cooper80d21cb2015-06-22 19:35:57 +00005853
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00005854/// Create an MCAsmParser instance.
Jim Grosbach4b905842013-09-20 23:08:21 +00005855MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
Sanne Wouda29338752017-02-08 14:48:05 +00005856 MCStreamer &Out, const MCAsmInfo &MAI,
5857 unsigned CB) {
5858 return new AsmParser(SM, C, Out, MAI, CB);
Daniel Dunbar01e36072010-07-17 02:26:10 +00005859}