blob: f714aeef054428e0a62c1e8399ad53c9d596f368 [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 Carruth8a8cd2b2014-01-07 11:48:04 +000018#include "llvm/ADT/SmallString.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000019#include "llvm/ADT/SmallVector.h"
20#include "llvm/ADT/STLExtras.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000021#include "llvm/ADT/StringMap.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000022#include "llvm/ADT/StringRef.h"
Daniel Dunbareb6bb322009-07-27 23:20:52 +000023#include "llvm/ADT/Twine.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000024#include "llvm/MC/MCAsmInfo.h"
Reid Klecknera5b1eef2016-08-26 17:58:37 +000025#include "llvm/MC/MCCodeView.h"
Daniel Dunbarca29e4d2009-06-23 22:01:43 +000026#include "llvm/MC/MCContext.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000027#include "llvm/MC/MCDirectives.h"
Evan Cheng11424442011-07-26 00:24:13 +000028#include "llvm/MC/MCDwarf.h"
Daniel Dunbar115e4d62009-08-31 08:06:59 +000029#include "llvm/MC/MCExpr.h"
Chad Rosier8bce6642012-10-18 15:49:34 +000030#include "llvm/MC/MCInstPrinter.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000031#include "llvm/MC/MCInstrDesc.h"
Chad Rosier8bce6642012-10-18 15:49:34 +000032#include "llvm/MC/MCInstrInfo.h"
Rafael Espindolae28610d2013-12-09 20:26:40 +000033#include "llvm/MC/MCObjectFileInfo.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000034#include "llvm/MC/MCParser/AsmCond.h"
35#include "llvm/MC/MCParser/AsmLexer.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000036#include "llvm/MC/MCParser/MCAsmLexer.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000037#include "llvm/MC/MCParser/MCAsmParser.h"
Pete Cooper80d21cb2015-06-22 19:35:57 +000038#include "llvm/MC/MCParser/MCAsmParserUtils.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000039#include "llvm/MC/MCParser/MCParsedAsmOperand.h"
Benjamin Kramerb3e8a6d2016-01-27 10:01:28 +000040#include "llvm/MC/MCParser/MCTargetAsmParser.h"
Evan Cheng76792992011-07-20 05:58:47 +000041#include "llvm/MC/MCRegisterInfo.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000042#include "llvm/MC/MCSection.h"
Daniel Dunbarca29e4d2009-06-23 22:01:43 +000043#include "llvm/MC/MCStreamer.h"
Daniel Dunbarae7ac012009-06-29 23:43:14 +000044#include "llvm/MC/MCSymbol.h"
Daniel Sanders9f6ad492015-11-12 13:33:00 +000045#include "llvm/MC/MCValue.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000046#include "llvm/Support/Casting.h"
Davide Italiano7c9fc732016-07-27 05:51:56 +000047#include "llvm/Support/CommandLine.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000048#include "llvm/Support/Dwarf.h"
Benjamin Kramer4efe5062012-01-28 15:28:41 +000049#include "llvm/Support/ErrorHandling.h"
Jim Grosbach76346c32011-06-29 16:05:14 +000050#include "llvm/Support/MathExtras.h"
Kevin Enderbye233dda2010-06-28 21:45:58 +000051#include "llvm/Support/MemoryBuffer.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000052#include "llvm/Support/SMLoc.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000053#include "llvm/Support/SourceMgr.h"
Chris Lattner36e02122009-06-21 20:54:55 +000054#include "llvm/Support/raw_ostream.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000055#include <algorithm>
56#include <cassert>
Nick Lewycky0de20af2010-12-19 20:43:38 +000057#include <cctype>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000058#include <cstddef>
59#include <cstdint>
Benjamin Kramerd59664f2014-04-29 23:26:49 +000060#include <deque>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000061#include <memory>
Davide Italiano7c9fc732016-07-27 05:51:56 +000062#include <sstream>
Chad Rosier8bce6642012-10-18 15:49:34 +000063#include <string>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000064#include <tuple>
65#include <utility>
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000066#include <vector>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000067
Chris Lattnerb0133452009-06-21 20:16:42 +000068using namespace llvm;
69
Eric Christophera7c32732012-12-18 00:30:54 +000070MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {}
Nick Lewyckyac612272012-10-19 07:00:09 +000071
Davide Italiano7c9fc732016-07-27 05:51:56 +000072static cl::opt<unsigned> AsmMacroMaxNestingDepth(
73 "asm-macro-max-nesting-depth", cl::init(20), cl::Hidden,
74 cl::desc("The maximum nesting depth allowed for assembly macros."));
75
Daniel Dunbar86033402010-07-12 17:54:38 +000076namespace {
Eugene Zelenko33d7b762016-08-23 17:14:32 +000077
Eli Benderskya313ae62013-01-16 18:56:50 +000078/// \brief Helper types for tracking macro definitions.
79typedef std::vector<AsmToken> MCAsmMacroArgument;
80typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +000081
82struct MCAsmMacroParameter {
83 StringRef Name;
84 MCAsmMacroArgument Value;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +000085 bool Required;
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +000086 bool Vararg;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +000087
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +000088 MCAsmMacroParameter() : Required(false), Vararg(false) {}
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +000089};
90
Eli Benderskya313ae62013-01-16 18:56:50 +000091typedef std::vector<MCAsmMacroParameter> MCAsmMacroParameters;
92
93struct MCAsmMacro {
94 StringRef Name;
95 StringRef Body;
96 MCAsmMacroParameters Parameters;
97
98public:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +000099 MCAsmMacro(StringRef N, StringRef B, MCAsmMacroParameters P)
100 : Name(N), Body(B), Parameters(std::move(P)) {}
Eli Benderskya313ae62013-01-16 18:56:50 +0000101};
102
Daniel Dunbar43235712010-07-18 18:54:11 +0000103/// \brief Helper class for storing information about an active macro
104/// instantiation.
105struct MacroInstantiation {
Daniel Dunbar43235712010-07-18 18:54:11 +0000106 /// The location of the instantiation.
107 SMLoc InstantiationLoc;
108
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000109 /// The buffer where parsing should resume upon instantiation completion.
110 int ExitBuffer;
111
Daniel Dunbar43235712010-07-18 18:54:11 +0000112 /// The location where parsing should resume upon instantiation completion.
113 SMLoc ExitLoc;
114
Nico Weber155dccd12014-07-24 17:08:39 +0000115 /// The depth of TheCondStack at the start of the instantiation.
116 size_t CondStackDepth;
117
Daniel Dunbar43235712010-07-18 18:54:11 +0000118public:
Rafael Espindola9eef18c2014-08-27 19:49:03 +0000119 MacroInstantiation(SMLoc IL, int EB, SMLoc EL, size_t CondStackDepth);
Daniel Dunbar43235712010-07-18 18:54:11 +0000120};
121
Eli Friedman0f4871d2012-10-22 23:58:19 +0000122struct ParseStatementInfo {
Jim Grosbach4b905842013-09-20 23:08:21 +0000123 /// \brief The parsed operands from the last parsed statement.
David Blaikie960ea3f2014-06-08 16:18:35 +0000124 SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> ParsedOperands;
Eli Friedman0f4871d2012-10-22 23:58:19 +0000125
Jim Grosbach4b905842013-09-20 23:08:21 +0000126 /// \brief The opcode from the last parsed instruction.
Eli Friedman0f4871d2012-10-22 23:58:19 +0000127 unsigned Opcode;
128
Jim Grosbach4b905842013-09-20 23:08:21 +0000129 /// \brief Was there an error parsing the inline assembly?
Chad Rosier149e8e02012-12-12 22:45:52 +0000130 bool ParseError;
131
Eli Friedman0f4871d2012-10-22 23:58:19 +0000132 SmallVectorImpl<AsmRewrite> *AsmRewrites;
133
Craig Topper353eda42014-04-24 06:44:33 +0000134 ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(nullptr) {}
Eli Friedman0f4871d2012-10-22 23:58:19 +0000135 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
Chad Rosier149e8e02012-12-12 22:45:52 +0000136 : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
Eli Friedman0f4871d2012-10-22 23:58:19 +0000137};
138
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000139/// \brief The concrete assembly parser instance.
140class AsmParser : public MCAsmParser {
Aaron Ballmanf9a18972015-02-15 22:54:22 +0000141 AsmParser(const AsmParser &) = delete;
142 void operator=(const AsmParser &) = delete;
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000143
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000144private:
145 AsmLexer Lexer;
146 MCContext &Ctx;
147 MCStreamer &Out;
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000148 const MCAsmInfo &MAI;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000149 SourceMgr &SrcMgr;
Benjamin Kramer47f5e302011-10-16 10:48:29 +0000150 SourceMgr::DiagHandlerTy SavedDiagHandler;
151 void *SavedDiagContext;
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000152 std::unique_ptr<MCAsmParserExtension> PlatformParser;
Rafael Espindola82065cb2011-04-11 21:49:50 +0000153
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000154 /// This is the current buffer index we're lexing from as managed by the
155 /// SourceMgr object.
Alp Tokera55b95b2014-07-06 10:33:31 +0000156 unsigned CurBuffer;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000157
158 AsmCond TheCondState;
159 std::vector<AsmCond> TheCondStack;
160
Jim Grosbach4b905842013-09-20 23:08:21 +0000161 /// \brief maps directive names to handler methods in parser
Eli Bendersky17233942013-01-15 22:59:42 +0000162 /// extensions. Extensions register themselves in this map by calling
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000163 /// addDirectiveHandler.
Eli Bendersky17233942013-01-15 22:59:42 +0000164 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
Daniel Dunbar828984f2010-07-18 18:38:02 +0000165
Jim Grosbach4b905842013-09-20 23:08:21 +0000166 /// \brief Map of currently defined macros.
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000167 StringMap<MCAsmMacro> MacroMap;
Daniel Dunbarc1f58ec2010-07-18 18:47:21 +0000168
Jim Grosbach4b905842013-09-20 23:08:21 +0000169 /// \brief Stack of active macro instantiations.
Daniel Dunbar43235712010-07-18 18:54:11 +0000170 std::vector<MacroInstantiation*> ActiveMacros;
171
Jim Grosbach4b905842013-09-20 23:08:21 +0000172 /// \brief List of bodies of anonymous macros.
Benjamin Kramer1df3a1f2013-08-04 09:06:29 +0000173 std::deque<MCAsmMacro> MacroLikeBodies;
174
Daniel Dunbar828984f2010-07-18 18:38:02 +0000175 /// Boolean tracking whether macro substitution is enabled.
Eli Benderskyc2f6f922013-01-14 18:08:41 +0000176 unsigned MacrosEnabledFlag : 1;
Daniel Dunbar828984f2010-07-18 18:38:02 +0000177
Toma Tabacu217116e2015-04-27 10:50:29 +0000178 /// \brief Keeps track of how many .macro's have been instantiated.
179 unsigned NumOfMacroInstantiations;
180
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000181 /// The values from the last parsed cpp hash file line comment if any.
Tim Northoverc0bef992016-04-13 19:46:54 +0000182 struct CppHashInfoTy {
183 StringRef Filename;
Andrew Kaylorca196472016-04-21 20:09:35 +0000184 int64_t LineNumber = 0;
Tim Northoverc0bef992016-04-13 19:46:54 +0000185 SMLoc Loc;
Andrew Kaylorca196472016-04-21 20:09:35 +0000186 unsigned Buf = 0;
Tim Northoverc0bef992016-04-13 19:46:54 +0000187 };
188 CppHashInfoTy CppHashInfo;
189
190 /// \brief List of forward directional labels for diagnosis at the end.
191 SmallVector<std::tuple<SMLoc, CppHashInfoTy, MCSymbol *>, 4> DirLabels;
192
Kevin Enderby0fd064c2013-06-21 20:51:39 +0000193 /// When generating dwarf for assembly source files we need to calculate the
194 /// logical line number based on the last parsed cpp hash file line comment
Vladimir Medic9bad0d332013-08-20 13:33:18 +0000195 /// and current line. Since this is slow and messes up the SourceMgr's
Kevin Enderby0fd064c2013-06-21 20:51:39 +0000196 /// cache we save the last info we queried with SrcMgr.FindLineNumber().
197 SMLoc LastQueryIDLoc;
Alp Tokera55b95b2014-07-06 10:33:31 +0000198 unsigned LastQueryBuffer;
Kevin Enderby0fd064c2013-06-21 20:51:39 +0000199 unsigned LastQueryLine;
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000200
Devang Patela173ee52012-01-31 18:14:05 +0000201 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
202 unsigned AssemblerDialect;
203
Jim Grosbach4b905842013-09-20 23:08:21 +0000204 /// \brief is Darwin compatibility enabled?
Preston Gurd05500642012-09-19 20:36:12 +0000205 bool IsDarwin;
206
Jim Grosbach4b905842013-09-20 23:08:21 +0000207 /// \brief Are we parsing ms-style inline assembly?
Chad Rosier49963552012-10-13 00:26:04 +0000208 bool ParsingInlineAsm;
209
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000210public:
Jim Grosbach345768c2011-08-16 18:33:49 +0000211 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000212 const MCAsmInfo &MAI);
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000213 ~AsmParser() override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000214
Craig Topper59be68f2014-03-08 07:14:16 +0000215 bool Run(bool NoInitialTextSection, bool NoFinalize = false) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000216
Craig Topper59be68f2014-03-08 07:14:16 +0000217 void addDirectiveHandler(StringRef Directive,
218 ExtensionDirectiveHandler Handler) override {
Eli Bendersky29b9f472013-01-16 00:50:52 +0000219 ExtensionDirectiveMap[Directive] = Handler;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000220 }
221
Toma Tabacu11e14a92015-04-21 11:50:52 +0000222 void addAliasForDirective(StringRef Directive, StringRef Alias) override {
223 DirectiveKindMap[Directive] = DirectiveKindMap[Alias];
224 }
225
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000226public:
227 /// @name MCAsmParser Interface
228 /// {
229
Craig Topper59be68f2014-03-08 07:14:16 +0000230 SourceMgr &getSourceManager() override { return SrcMgr; }
231 MCAsmLexer &getLexer() override { return Lexer; }
232 MCContext &getContext() override { return Ctx; }
233 MCStreamer &getStreamer() override { return Out; }
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000234
Reid Klecknera5b1eef2016-08-26 17:58:37 +0000235 CodeViewContext &getCVContext() { return Ctx.getCVContext(); }
236
Craig Topper59be68f2014-03-08 07:14:16 +0000237 unsigned getAssemblerDialect() override {
Devang Patela173ee52012-01-31 18:14:05 +0000238 if (AssemblerDialect == ~0U)
Eric Christophera7c32732012-12-18 00:30:54 +0000239 return MAI.getAssemblerDialect();
Devang Patela173ee52012-01-31 18:14:05 +0000240 else
241 return AssemblerDialect;
242 }
Craig Topper59be68f2014-03-08 07:14:16 +0000243 void setAssemblerDialect(unsigned i) override {
Devang Patela173ee52012-01-31 18:14:05 +0000244 AssemblerDialect = i;
245 }
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000246
Nirav Dave2364748a2016-09-16 18:30:20 +0000247 void Note(SMLoc L, const Twine &Msg, SMRange Range = None) override;
248 bool Warning(SMLoc L, const Twine &Msg, SMRange Range = None) override;
249 bool printError(SMLoc L, const Twine &Msg, SMRange Range = None) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000250
Craig Topper59be68f2014-03-08 07:14:16 +0000251 const AsmToken &Lex() override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000252
Yunzhong Gao27ea29b2016-09-02 23:15:29 +0000253 void setParsingInlineAsm(bool V) override {
254 ParsingInlineAsm = V;
255 Lexer.setParsingMSInlineAsm(V);
256 }
Craig Topper59be68f2014-03-08 07:14:16 +0000257 bool isParsingInlineAsm() override { return ParsingInlineAsm; }
Chad Rosier8bce6642012-10-18 15:49:34 +0000258
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000259 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
Chad Rosier8bce6642012-10-18 15:49:34 +0000260 unsigned &NumOutputs, unsigned &NumInputs,
Chad Rosier37e755c2012-10-23 17:43:43 +0000261 SmallVectorImpl<std::pair<void *,bool> > &OpDecls,
Chad Rosier8bce6642012-10-18 15:49:34 +0000262 SmallVectorImpl<std::string> &Constraints,
Chad Rosier8bce6642012-10-18 15:49:34 +0000263 SmallVectorImpl<std::string> &Clobbers,
Craig Topper59be68f2014-03-08 07:14:16 +0000264 const MCInstrInfo *MII, const MCInstPrinter *IP,
265 MCAsmParserSemaCallback &SI) override;
Chad Rosier49963552012-10-13 00:26:04 +0000266
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000267 bool parseExpression(const MCExpr *&Res);
Craig Topper59be68f2014-03-08 07:14:16 +0000268 bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
269 bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) override;
270 bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
Toma Tabacu7bc44dc2015-06-25 09:52:02 +0000271 bool parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
272 SMLoc &EndLoc) override;
Craig Topper59be68f2014-03-08 07:14:16 +0000273 bool parseAbsoluteExpression(int64_t &Res) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000274
Petr Hosek4cb08ce2016-09-23 19:25:15 +0000275 /// \brief Parse a floating point expression using the float \p Semantics
276 /// and set \p Res to the value.
277 bool parseRealValue(const fltSemantics &Semantics, APInt &Res);
278
Jim Grosbach4b905842013-09-20 23:08:21 +0000279 /// \brief Parse an identifier or string (as a quoted identifier)
Eli Bendersky0cf0cb92013-01-12 00:05:00 +0000280 /// and set \p Res to the identifier contents.
Craig Topper59be68f2014-03-08 07:14:16 +0000281 bool parseIdentifier(StringRef &Res) override;
282 void eatToEndOfStatement() override;
Eli Bendersky0cf0cb92013-01-12 00:05:00 +0000283
Nirav Davef43cc9f2016-10-10 15:24:54 +0000284 bool checkForValidSection() override;
Nirav Davea645433c2016-07-18 15:24:03 +0000285
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000286 /// }
287
288private:
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +0000289 bool parseStatement(ParseStatementInfo &Info,
290 MCAsmParserSemaCallback *SI);
Marina Yatsina5f5de9f2016-03-07 18:11:16 +0000291 bool parseCurlyBlockScope(SmallVectorImpl<AsmRewrite>& AsmStrRewrites);
Craig Topper3c76c522015-09-20 23:35:59 +0000292 bool parseCppHashLineFilenameComment(SMLoc L);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000293
Jim Grosbach4b905842013-09-20 23:08:21 +0000294 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +0000295 ArrayRef<MCAsmMacroParameter> Parameters);
Rafael Espindola34b9c512012-06-03 23:57:14 +0000296 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +0000297 ArrayRef<MCAsmMacroParameter> Parameters,
Toma Tabacu217116e2015-04-27 10:50:29 +0000298 ArrayRef<MCAsmMacroArgument> A, bool EnableAtPseudoVariable,
Craig Topper3c76c522015-09-20 23:35:59 +0000299 SMLoc L);
Daniel Dunbar43235712010-07-18 18:54:11 +0000300
Eli Benderskya313ae62013-01-16 18:56:50 +0000301 /// \brief Are macros enabled in the parser?
Jim Grosbach4b905842013-09-20 23:08:21 +0000302 bool areMacrosEnabled() {return MacrosEnabledFlag;}
Eli Benderskya313ae62013-01-16 18:56:50 +0000303
304 /// \brief Control a flag in the parser that enables or disables macros.
Jim Grosbach4b905842013-09-20 23:08:21 +0000305 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
Eli Benderskya313ae62013-01-16 18:56:50 +0000306
307 /// \brief Lookup a previously defined macro.
308 /// \param Name Macro name.
309 /// \returns Pointer to macro. NULL if no such macro was defined.
Jim Grosbach4b905842013-09-20 23:08:21 +0000310 const MCAsmMacro* lookupMacro(StringRef Name);
Eli Benderskya313ae62013-01-16 18:56:50 +0000311
312 /// \brief Define a new macro with the given name and information.
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000313 void defineMacro(StringRef Name, MCAsmMacro Macro);
Eli Benderskya313ae62013-01-16 18:56:50 +0000314
315 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
Jim Grosbach4b905842013-09-20 23:08:21 +0000316 void undefineMacro(StringRef Name);
Eli Benderskya313ae62013-01-16 18:56:50 +0000317
318 /// \brief Are we inside a macro instantiation?
Jim Grosbach4b905842013-09-20 23:08:21 +0000319 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
Eli Benderskya313ae62013-01-16 18:56:50 +0000320
Vladimir Medic9bad0d332013-08-20 13:33:18 +0000321 /// \brief Handle entry to macro instantiation.
Eli Benderskya313ae62013-01-16 18:56:50 +0000322 ///
323 /// \param M The macro.
324 /// \param NameLoc Instantiation location.
Jim Grosbach4b905842013-09-20 23:08:21 +0000325 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
Eli Benderskya313ae62013-01-16 18:56:50 +0000326
327 /// \brief Handle exit from macro instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +0000328 void handleMacroExit();
Eli Benderskya313ae62013-01-16 18:56:50 +0000329
David Majnemer91fc4c22014-01-29 18:57:46 +0000330 /// \brief Extract AsmTokens for a macro argument.
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +0000331 bool parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg);
Eli Benderskya313ae62013-01-16 18:56:50 +0000332
333 /// \brief Parse all macro arguments for a given macro.
Jim Grosbach4b905842013-09-20 23:08:21 +0000334 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
Eli Benderskya313ae62013-01-16 18:56:50 +0000335
Jim Grosbach4b905842013-09-20 23:08:21 +0000336 void printMacroInstantiations();
337 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
Nirav Dave2364748a2016-09-16 18:30:20 +0000338 SMRange Range = None) const {
339 ArrayRef<SMRange> Ranges(Range);
Chris Lattner72845262011-10-16 05:47:55 +0000340 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
Benjamin Kramerc7583112010-09-27 17:42:11 +0000341 }
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000342 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
Benjamin Kramerc7583112010-09-27 17:42:11 +0000343
Jim Grosbach4b905842013-09-20 23:08:21 +0000344 /// \brief Enter the specified file. This returns true on failure.
345 bool enterIncludeFile(const std::string &Filename);
346
347 /// \brief Process the specified file for the .incbin directive.
Kevin Enderby109f25c2011-12-14 21:47:48 +0000348 /// This returns true on failure.
Petr Hosek2f4ac442016-09-23 00:41:06 +0000349 bool processIncbinFile(const std::string &Filename, int64_t Skip = 0,
350 const MCExpr *Count = nullptr, SMLoc Loc = SMLoc());
Daniel Dunbar43235712010-07-18 18:54:11 +0000351
Dmitri Gribenko5485acd2012-09-14 14:57:36 +0000352 /// \brief Reset the current lexer position to that given by \p Loc. The
Daniel Dunbar43235712010-07-18 18:54:11 +0000353 /// current token is not set; clients should ensure Lex() is called
354 /// subsequently.
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000355 ///
Alp Tokera55b95b2014-07-06 10:33:31 +0000356 /// \param InBuffer If not 0, should be the known buffer id that contains the
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000357 /// location.
Alp Tokera55b95b2014-07-06 10:33:31 +0000358 void jumpToLoc(SMLoc Loc, unsigned InBuffer = 0);
Daniel Dunbar43235712010-07-18 18:54:11 +0000359
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000360 /// \brief Parse up to the end of statement and a return the contents from the
361 /// current token until the end of the statement; the current token on exit
362 /// will be either the EndOfStatement or EOF.
Craig Topper59be68f2014-03-08 07:14:16 +0000363 StringRef parseStringToEndOfStatement() override;
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000364
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000365 /// \brief Parse until the end of a statement or a comma is encountered,
366 /// return the contents from the current token up to the end or comma.
Jim Grosbach4b905842013-09-20 23:08:21 +0000367 StringRef parseStringToComma();
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000368
Jim Grosbach4b905842013-09-20 23:08:21 +0000369 bool parseAssignment(StringRef Name, bool allow_redef,
Jim Grosbachb7b750d2012-09-13 23:11:31 +0000370 bool NoDeadStrip = false);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000371
Ahmed Bougacha457852f2015-04-28 00:17:39 +0000372 unsigned getBinOpPrecedence(AsmToken::TokenKind K,
373 MCBinaryExpr::Opcode &Kind);
374
Jim Grosbach4b905842013-09-20 23:08:21 +0000375 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
376 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
377 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000378
Jim Grosbach4b905842013-09-20 23:08:21 +0000379 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
Rafael Espindola63760ba2010-10-28 20:02:27 +0000380
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000381 bool parseCVFunctionId(int64_t &FunctionId, StringRef DirectiveName);
382 bool parseCVFileId(int64_t &FileId, StringRef DirectiveName);
383
Eli Bendersky17233942013-01-15 22:59:42 +0000384 // Generic (target and platform independent) directive parsing.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000385 enum DirectiveKind {
Eli Bendersky4d21fa02013-01-10 23:40:56 +0000386 DK_NO_DIRECTIVE, // Placeholder
387 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
Daniel Sanders9f6ad492015-11-12 13:33:00 +0000388 DK_RELOC,
David Woodhoused6de0d92014-02-01 16:20:59 +0000389 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_OCTA,
Petr Hosek731bb9c2016-08-23 21:34:53 +0000390 DK_DC, DK_DC_A, DK_DC_B, DK_DC_D, DK_DC_L, DK_DC_S, DK_DC_W, DK_DC_X,
Petr Hosek4cb08ce2016-09-23 19:25:15 +0000391 DK_DCB, DK_DCB_B, DK_DCB_D, DK_DCB_L, DK_DCB_S, DK_DCB_W, DK_DCB_X,
Petr Hosek85b2f672016-09-23 21:53:36 +0000392 DK_DS, DK_DS_B, DK_DS_D, DK_DS_L, DK_DS_P, DK_DS_S, DK_DS_W, DK_DS_X,
David Woodhoused6de0d92014-02-01 16:20:59 +0000393 DK_SINGLE, DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
Eli Bendersky96522722013-01-11 22:55:28 +0000394 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
Eli Bendersky4d21fa02013-01-10 23:40:56 +0000395 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
Kevin Enderby3aeada22013-08-28 17:50:59 +0000396 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL,
Lang Hamesf9033bb2016-04-11 18:33:45 +0000397 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER,
Lang Hames1b640e02016-03-15 01:43:05 +0000398 DK_PRIVATE_EXTERN, DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
Eli Bendersky4d21fa02013-01-10 23:40:56 +0000399 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
400 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +0000401 DK_IF, DK_IFEQ, DK_IFGE, DK_IFGT, DK_IFLE, DK_IFLT, DK_IFNE, DK_IFB,
Sid Manning51c35602015-03-18 14:20:54 +0000402 DK_IFNB, DK_IFC, DK_IFEQS, DK_IFNC, DK_IFNES, DK_IFDEF, DK_IFNDEF,
403 DK_IFNOTDEF, DK_ELSEIF, DK_ELSE, DK_ENDIF,
Eli Bendersky17233942013-01-15 22:59:42 +0000404 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000405 DK_CV_FILE, DK_CV_FUNC_ID, DK_CV_INLINE_SITE_ID, DK_CV_LOC, DK_CV_LINETABLE,
406 DK_CV_INLINE_LINETABLE, DK_CV_DEF_RANGE, DK_CV_STRINGTABLE,
407 DK_CV_FILECHECKSUMS,
Eli Bendersky17233942013-01-15 22:59:42 +0000408 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
409 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
410 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
411 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
412 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +0000413 DK_CFI_REGISTER, DK_CFI_WINDOW_SAVE,
Nico Weber155dccd12014-07-24 17:08:39 +0000414 DK_MACROS_ON, DK_MACROS_OFF,
415 DK_MACRO, DK_EXITM, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000416 DK_SLEB128, DK_ULEB128,
Nico Weber404012b2014-07-24 16:26:06 +0000417 DK_ERR, DK_ERROR, DK_WARNING,
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000418 DK_END
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000419 };
420
Jim Grosbach4b905842013-09-20 23:08:21 +0000421 /// \brief Maps directive name --> DirectiveKind enum, for
Eli Bendersky17233942013-01-15 22:59:42 +0000422 /// directives parsed by this class.
423 StringMap<DirectiveKind> DirectiveKindMap;
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000424
425 // ".ascii", ".asciz", ".string"
Jim Grosbach4b905842013-09-20 23:08:21 +0000426 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
Daniel Sanders9f6ad492015-11-12 13:33:00 +0000427 bool parseDirectiveReloc(SMLoc DirectiveLoc); // ".reloc"
Nirav Dave1a9044b2016-10-24 14:35:29 +0000428 bool parseDirectiveValue(StringRef IDVal,
429 unsigned Size); // ".byte", ".long", ...
430 bool parseDirectiveOctaValue(StringRef IDVal); // ".octa", ...
431 bool parseDirectiveRealValue(StringRef IDVal,
432 const fltSemantics &); // ".single", ...
Jim Grosbach4b905842013-09-20 23:08:21 +0000433 bool parseDirectiveFill(); // ".fill"
434 bool parseDirectiveZero(); // ".zero"
Eric Christophera7c32732012-12-18 00:30:54 +0000435 // ".set", ".equ", ".equiv"
Jim Grosbach4b905842013-09-20 23:08:21 +0000436 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
437 bool parseDirectiveOrg(); // ".org"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000438 // ".align{,32}", ".p2align{,w,l}"
Jim Grosbach4b905842013-09-20 23:08:21 +0000439 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000440
Eli Bendersky17233942013-01-15 22:59:42 +0000441 // ".file", ".line", ".loc", ".stabs"
Jim Grosbach4b905842013-09-20 23:08:21 +0000442 bool parseDirectiveFile(SMLoc DirectiveLoc);
443 bool parseDirectiveLine();
444 bool parseDirectiveLoc();
445 bool parseDirectiveStabs();
Eli Bendersky17233942013-01-15 22:59:42 +0000446
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000447 // ".cv_file", ".cv_func_id", ".cv_inline_site_id", ".cv_loc", ".cv_linetable",
448 // ".cv_inline_linetable", ".cv_def_range"
Reid Kleckner2214ed82016-01-29 00:49:42 +0000449 bool parseDirectiveCVFile();
Reid Klecknera9f4cc92016-09-07 16:15:31 +0000450 bool parseDirectiveCVFuncId();
451 bool parseDirectiveCVInlineSiteId();
Reid Kleckner2214ed82016-01-29 00:49:42 +0000452 bool parseDirectiveCVLoc();
453 bool parseDirectiveCVLinetable();
David Majnemer6fcbd7e2016-01-29 19:24:12 +0000454 bool parseDirectiveCVInlineLinetable();
David Majnemer408b5e62016-02-05 01:55:49 +0000455 bool parseDirectiveCVDefRange();
Reid Kleckner2214ed82016-01-29 00:49:42 +0000456 bool parseDirectiveCVStringTable();
457 bool parseDirectiveCVFileChecksums();
458
Eli Bendersky17233942013-01-15 22:59:42 +0000459 // .cfi directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000460 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +0000461 bool parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +0000462 bool parseDirectiveCFISections();
463 bool parseDirectiveCFIStartProc();
464 bool parseDirectiveCFIEndProc();
465 bool parseDirectiveCFIDefCfaOffset();
466 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
467 bool parseDirectiveCFIAdjustCfaOffset();
468 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
469 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
470 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
471 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
472 bool parseDirectiveCFIRememberState();
473 bool parseDirectiveCFIRestoreState();
474 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
475 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
476 bool parseDirectiveCFIEscape();
477 bool parseDirectiveCFISignalFrame();
478 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
Eli Bendersky17233942013-01-15 22:59:42 +0000479
480 // macro directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000481 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
Nico Weber155dccd12014-07-24 17:08:39 +0000482 bool parseDirectiveExitMacro(StringRef Directive);
Jim Grosbach4b905842013-09-20 23:08:21 +0000483 bool parseDirectiveEndMacro(StringRef Directive);
484 bool parseDirectiveMacro(SMLoc DirectiveLoc);
485 bool parseDirectiveMacrosOnOff(StringRef Directive);
Eli Bendersky17233942013-01-15 22:59:42 +0000486
Eli Benderskyf483ff92012-12-20 19:05:53 +0000487 // ".bundle_align_mode"
Jim Grosbach4b905842013-09-20 23:08:21 +0000488 bool parseDirectiveBundleAlignMode();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000489 // ".bundle_lock"
Jim Grosbach4b905842013-09-20 23:08:21 +0000490 bool parseDirectiveBundleLock();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000491 // ".bundle_unlock"
Jim Grosbach4b905842013-09-20 23:08:21 +0000492 bool parseDirectiveBundleUnlock();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000493
Eli Bendersky17233942013-01-15 22:59:42 +0000494 // ".space", ".skip"
Jim Grosbach4b905842013-09-20 23:08:21 +0000495 bool parseDirectiveSpace(StringRef IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +0000496
Petr Hosek4cb08ce2016-09-23 19:25:15 +0000497 // ".dcb"
498 bool parseDirectiveDCB(StringRef IDVal, unsigned Size);
499 bool parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &);
Petr Hosek85b2f672016-09-23 21:53:36 +0000500 // ".ds"
501 bool parseDirectiveDS(StringRef IDVal, unsigned Size);
Petr Hosek4cb08ce2016-09-23 19:25:15 +0000502
Eli Bendersky17233942013-01-15 22:59:42 +0000503 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
Jim Grosbach4b905842013-09-20 23:08:21 +0000504 bool parseDirectiveLEB128(bool Signed);
Eli Bendersky17233942013-01-15 22:59:42 +0000505
Jim Grosbach4b905842013-09-20 23:08:21 +0000506 /// \brief Parse a directive like ".globl" which
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000507 /// accepts a single symbol (which should be a label or an external).
Jim Grosbach4b905842013-09-20 23:08:21 +0000508 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000509
Jim Grosbach4b905842013-09-20 23:08:21 +0000510 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000511
Jim Grosbach4b905842013-09-20 23:08:21 +0000512 bool parseDirectiveAbort(); // ".abort"
513 bool parseDirectiveInclude(); // ".include"
514 bool parseDirectiveIncbin(); // ".incbin"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000515
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +0000516 // ".if", ".ifeq", ".ifge", ".ifgt" , ".ifle", ".iflt" or ".ifne"
517 bool parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind);
Benjamin Kramer62c18b02012-05-12 11:18:42 +0000518 // ".ifb" or ".ifnb", depending on ExpectBlank.
Jim Grosbach4b905842013-09-20 23:08:21 +0000519 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000520 // ".ifc" or ".ifnc", depending on ExpectEqual.
Jim Grosbach4b905842013-09-20 23:08:21 +0000521 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
Sid Manning51c35602015-03-18 14:20:54 +0000522 // ".ifeqs" or ".ifnes", depending on ExpectEqual.
523 bool parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +0000524 // ".ifdef" or ".ifndef", depending on expect_defined
Jim Grosbach4b905842013-09-20 23:08:21 +0000525 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
526 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
527 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
528 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
Craig Topper59be68f2014-03-08 07:14:16 +0000529 bool parseEscapedString(std::string &Data) override;
Daniel Dunbar55f16672010-09-17 02:47:07 +0000530
Jim Grosbach4b905842013-09-20 23:08:21 +0000531 const MCExpr *applyModifierToExpr(const MCExpr *E,
Daniel Dunbar55f16672010-09-17 02:47:07 +0000532 MCSymbolRefExpr::VariantKind Variant);
Rafael Espindola47b7dac2012-05-12 16:31:10 +0000533
Rafael Espindola34b9c512012-06-03 23:57:14 +0000534 // Macro-like directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000535 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
536 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +0000537 raw_svector_ostream &OS);
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +0000538 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
Jim Grosbach4b905842013-09-20 23:08:21 +0000539 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
540 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
541 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
Chad Rosier8bce6642012-10-18 15:49:34 +0000542
Chad Rosierc7f552c2013-02-12 21:33:51 +0000543 // "_emit" or "__emit"
Jim Grosbach4b905842013-09-20 23:08:21 +0000544 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
Chad Rosierc7f552c2013-02-12 21:33:51 +0000545 size_t Len);
546
547 // "align"
Jim Grosbach4b905842013-09-20 23:08:21 +0000548 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000549
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000550 // "end"
551 bool parseDirectiveEnd(SMLoc DirectiveLoc);
552
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +0000553 // ".err" or ".error"
554 bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +0000555
Nico Weber404012b2014-07-24 16:26:06 +0000556 // ".warning"
557 bool parseDirectiveWarning(SMLoc DirectiveLoc);
558
Eli Bendersky17233942013-01-15 22:59:42 +0000559 void initializeDirectiveKindMap();
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000560};
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000561
562} // end anonymous namespace
Daniel Dunbar86033402010-07-12 17:54:38 +0000563
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000564namespace llvm {
565
566extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbarab058b82010-07-12 21:23:32 +0000567extern MCAsmParserExtension *createELFAsmParser();
Michael J. Spencerc8dbdfd2010-10-09 11:01:07 +0000568extern MCAsmParserExtension *createCOFFAsmParser();
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000569
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000570} // end namespace llvm
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000571
Chris Lattnerc35681b2010-01-19 19:46:13 +0000572enum { DEFAULT_ADDRSPACE = 0 };
573
David Blaikie9f380a32015-03-16 18:06:57 +0000574AsmParser::AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
575 const MCAsmInfo &MAI)
576 : Lexer(MAI), Ctx(Ctx), Out(Out), MAI(MAI), SrcMgr(SM),
577 PlatformParser(nullptr), CurBuffer(SM.getMainFileID()),
Nirav Dave2364748a2016-09-16 18:30:20 +0000578 MacrosEnabledFlag(true), CppHashInfo(), AssemblerDialect(~0U),
579 IsDarwin(false), ParsingInlineAsm(false) {
580 HadError = false;
Benjamin Kramer47f5e302011-10-16 10:48:29 +0000581 // Save the old handler.
582 SavedDiagHandler = SrcMgr.getDiagHandler();
583 SavedDiagContext = SrcMgr.getDiagContext();
584 // Set our own handler which calls the saved handler.
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000585 SrcMgr.setDiagHandler(DiagHandler, this);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000586 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar86033402010-07-12 17:54:38 +0000587
Daniel Dunbarc5011082010-07-12 18:12:02 +0000588 // Initialize the platform / file format parser.
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000589 switch (Ctx.getObjectFileInfo()->getObjectFileType()) {
590 case MCObjectFileInfo::IsCOFF:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000591 PlatformParser.reset(createCOFFAsmParser());
592 break;
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000593 case MCObjectFileInfo::IsMachO:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000594 PlatformParser.reset(createDarwinAsmParser());
595 IsDarwin = true;
596 break;
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000597 case MCObjectFileInfo::IsELF:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000598 PlatformParser.reset(createELFAsmParser());
599 break;
Daniel Dunbarc5011082010-07-12 18:12:02 +0000600 }
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000601
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000602 PlatformParser->Initialize(*this);
Eli Bendersky17233942013-01-15 22:59:42 +0000603 initializeDirectiveKindMap();
Toma Tabacu217116e2015-04-27 10:50:29 +0000604
605 NumOfMacroInstantiations = 0;
Chris Lattner351a7ef2009-09-27 21:16:52 +0000606}
607
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000608AsmParser::~AsmParser() {
Saleem Abdulrasool6eae1e62014-05-21 17:53:18 +0000609 assert((HadError || ActiveMacros.empty()) &&
610 "Unexpected active macro instantiation!");
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000611}
612
Jim Grosbach4b905842013-09-20 23:08:21 +0000613void AsmParser::printMacroInstantiations() {
Daniel Dunbar43235712010-07-18 18:54:11 +0000614 // Print the active macro instantiation stack.
Jim Grosbach4b905842013-09-20 23:08:21 +0000615 for (std::vector<MacroInstantiation *>::const_reverse_iterator
616 it = ActiveMacros.rbegin(),
617 ie = ActiveMacros.rend();
618 it != ie; ++it)
619 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
Chris Lattner03b80a42011-10-16 05:43:57 +0000620 "while in macro instantiation");
Daniel Dunbar43235712010-07-18 18:54:11 +0000621}
622
Nirav Dave2364748a2016-09-16 18:30:20 +0000623void AsmParser::Note(SMLoc L, const Twine &Msg, SMRange Range) {
624 printPendingErrors();
625 printMessage(L, SourceMgr::DK_Note, Msg, Range);
Saleem Abdulrasool69c7caf2014-01-07 02:28:31 +0000626 printMacroInstantiations();
627}
628
Nirav Dave2364748a2016-09-16 18:30:20 +0000629bool AsmParser::Warning(SMLoc L, const Twine &Msg, SMRange Range) {
Colin LeMahieufe36f832015-07-27 22:39:14 +0000630 if(getTargetParser().getTargetOptions().MCNoWarn)
631 return false;
Joerg Sonnenberger29815912014-08-26 18:39:50 +0000632 if (getTargetParser().getTargetOptions().MCFatalWarnings)
Nirav Dave2364748a2016-09-16 18:30:20 +0000633 return Error(L, Msg, Range);
634 printMessage(L, SourceMgr::DK_Warning, Msg, Range);
Jim Grosbach4b905842013-09-20 23:08:21 +0000635 printMacroInstantiations();
Joerg Sonnenberger74ba2622011-05-19 18:00:13 +0000636 return false;
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +0000637}
638
Nirav Dave2364748a2016-09-16 18:30:20 +0000639bool AsmParser::printError(SMLoc L, const Twine &Msg, SMRange Range) {
Daniel Dunbar43325c42010-09-09 22:42:56 +0000640 HadError = true;
Nirav Dave2364748a2016-09-16 18:30:20 +0000641 printMessage(L, SourceMgr::DK_Error, Msg, Range);
Jim Grosbach4b905842013-09-20 23:08:21 +0000642 printMacroInstantiations();
Chris Lattner2adc9e72009-06-21 21:22:11 +0000643 return true;
644}
645
Jim Grosbach4b905842013-09-20 23:08:21 +0000646bool AsmParser::enterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergeraf5f23e2011-06-01 13:10:15 +0000647 std::string IncludedFile;
Alp Tokera55b95b2014-07-06 10:33:31 +0000648 unsigned NewBuf =
649 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
650 if (!NewBuf)
Sean Callanan7a77eae2010-01-21 00:19:58 +0000651 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +0000652
Sean Callanan7a77eae2010-01-21 00:19:58 +0000653 CurBuffer = NewBuf;
Rafael Espindola8026bd02014-07-06 14:17:29 +0000654 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Sean Callanan7a77eae2010-01-21 00:19:58 +0000655 return false;
656}
Daniel Dunbar43235712010-07-18 18:54:11 +0000657
Sylvestre Ledru149e2812013-05-14 23:36:24 +0000658/// Process the specified .incbin file by searching for it in the include paths
Benjamin Kramerbde91762012-06-02 10:20:22 +0000659/// then just emitting the byte contents of the file to the streamer. This
Kevin Enderby109f25c2011-12-14 21:47:48 +0000660/// returns true on failure.
Petr Hosek2f4ac442016-09-23 00:41:06 +0000661bool AsmParser::processIncbinFile(const std::string &Filename, int64_t Skip,
662 const MCExpr *Count, SMLoc Loc) {
Kevin Enderby109f25c2011-12-14 21:47:48 +0000663 std::string IncludedFile;
Alp Tokera55b95b2014-07-06 10:33:31 +0000664 unsigned NewBuf =
665 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
666 if (!NewBuf)
Kevin Enderby109f25c2011-12-14 21:47:48 +0000667 return true;
668
Kevin Enderbyad41ab52011-12-14 22:34:45 +0000669 // Pick up the bytes from the file and emit them.
Petr Hosek2f4ac442016-09-23 00:41:06 +0000670 StringRef Bytes = SrcMgr.getMemoryBuffer(NewBuf)->getBuffer();
671 Bytes = Bytes.drop_front(Skip);
672 if (Count) {
673 int64_t Res;
674 if (!Count->evaluateAsAbsolute(Res))
675 return Error(Loc, "expected absolute expression");
676 if (Res < 0)
677 return Warning(Loc, "negative count has no effect");
678 Bytes = Bytes.take_front(Res);
679 }
680 getStreamer().EmitBytes(Bytes);
Kevin Enderby109f25c2011-12-14 21:47:48 +0000681 return false;
682}
683
Alp Tokera55b95b2014-07-06 10:33:31 +0000684void AsmParser::jumpToLoc(SMLoc Loc, unsigned InBuffer) {
685 CurBuffer = InBuffer ? InBuffer : SrcMgr.FindBufferContainingLoc(Loc);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000686 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(),
687 Loc.getPointer());
Daniel Dunbar43235712010-07-18 18:54:11 +0000688}
689
Sean Callanan7a77eae2010-01-21 00:19:58 +0000690const AsmToken &AsmParser::Lex() {
Nirav Dave1180e6892016-06-02 17:15:05 +0000691 if (Lexer.getTok().is(AsmToken::Error))
692 Error(Lexer.getErrLoc(), Lexer.getErr());
693
Nirav Dave53a72f42016-07-11 12:42:14 +0000694 // if it's a end of statement with a comment in it
695 if (getTok().is(AsmToken::EndOfStatement)) {
696 // if this is a line comment output it.
697 if (getTok().getString().front() != '\n' &&
698 getTok().getString().front() != '\r' && MAI.preserveAsmComments())
699 Out.addExplicitComment(Twine(getTok().getString()));
700 }
701
Sean Callanan7a77eae2010-01-21 00:19:58 +0000702 const AsmToken *tok = &Lexer.Lex();
Nirav Dave53a72f42016-07-11 12:42:14 +0000703
704 // Parse comments here to be deferred until end of next statement.
Nirav Davefd910412016-06-17 16:06:17 +0000705 while (tok->is(AsmToken::Comment)) {
Nirav Dave53a72f42016-07-11 12:42:14 +0000706 if (MAI.preserveAsmComments())
707 Out.addExplicitComment(Twine(tok->getString()));
Nirav Davefd910412016-06-17 16:06:17 +0000708 tok = &Lexer.Lex();
709 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000710
Sean Callanan7a77eae2010-01-21 00:19:58 +0000711 if (tok->is(AsmToken::Eof)) {
712 // If this is the end of an included file, pop the parent file off the
713 // include stack.
714 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
715 if (ParentIncludeLoc != SMLoc()) {
Jim Grosbach4b905842013-09-20 23:08:21 +0000716 jumpToLoc(ParentIncludeLoc);
Nirav Davefd910412016-06-17 16:06:17 +0000717 return Lex();
Sean Callanan7a77eae2010-01-21 00:19:58 +0000718 }
719 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000720
Sean Callanan7a77eae2010-01-21 00:19:58 +0000721 return *tok;
Sean Callanan686ed8d2010-01-19 20:22:31 +0000722}
723
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000724bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar322fec62010-03-13 02:20:57 +0000725 // Create the initial section, if requested.
Daniel Dunbar322fec62010-03-13 02:20:57 +0000726 if (!NoInitialTextSection)
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000727 Out.InitSections(false);
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000728
Chris Lattner36e02122009-06-21 20:54:55 +0000729 // Prime the lexer.
Sean Callanan686ed8d2010-01-19 20:22:31 +0000730 Lex();
Daniel Dunbar43325c42010-09-09 22:42:56 +0000731
732 HadError = false;
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000733 AsmCond StartingCondState = TheCondState;
734
Kevin Enderby6469fc22011-11-01 22:27:22 +0000735 // If we are generating dwarf for assembly source files save the initial text
736 // section and generate a .file directive.
737 if (getContext().getGenDwarfForAssembly()) {
Eric Christopher445c9522016-10-14 05:47:37 +0000738 MCSection *Sec = getStreamer().getCurrentSectionOnly();
Rafael Espindola2f9bdd82015-05-27 20:52:32 +0000739 if (!Sec->getBeginSymbol()) {
740 MCSymbol *SectionStartSym = getContext().createTempSymbol();
741 getStreamer().EmitLabel(SectionStartSym);
742 Sec->setBeginSymbol(SectionStartSym);
743 }
Rafael Espindolae0746792015-05-21 16:52:32 +0000744 bool InsertResult = getContext().addGenDwarfSection(Sec);
745 assert(InsertResult && ".text section should not have debug info yet");
Rafael Espindolafa160c72015-05-21 17:09:22 +0000746 (void)InsertResult;
David Blaikiec714ef42014-03-17 01:52:11 +0000747 getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective(
748 0, StringRef(), getContext().getMainFileName()));
Kevin Enderby6469fc22011-11-01 22:27:22 +0000749 }
750
Chris Lattner73f36112009-07-02 21:53:43 +0000751 // While we have input, parse each statement.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000752 while (Lexer.isNot(AsmToken::Eof)) {
Eli Friedman0f4871d2012-10-22 23:58:19 +0000753 ParseStatementInfo Info;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +0000754 if (!parseStatement(Info, nullptr))
Jim Grosbach4b905842013-09-20 23:08:21 +0000755 continue;
Michael J. Spencer530ce852010-10-09 11:00:50 +0000756
Nirav Dave2364748a2016-09-16 18:30:20 +0000757 // If we have a Lexer Error we are on an Error Token. Load in Lexer Error
758 // for printing ErrMsg via Lex() only if no (presumably better) parser error
759 // exists.
760 if (!hasPendingError() && Lexer.getTok().is(AsmToken::Error)) {
Nirav Dave1180e6892016-06-02 17:15:05 +0000761 Lex();
762 }
763
Nirav Dave2364748a2016-09-16 18:30:20 +0000764 // parseStatement returned true so may need to emit an error.
765 printPendingErrors();
766
767 // Skipping to the next line if needed.
768 if (!getLexer().isAtStartOfStatement())
769 eatToEndOfStatement();
Chris Lattner73f36112009-07-02 21:53:43 +0000770 }
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000771
Nirav Dave2364748a2016-09-16 18:30:20 +0000772 // All errors should have been emitted.
773 assert(!hasPendingError() && "unexpected error from parseStatement");
774
Oliver Stannard21718282016-07-26 14:19:47 +0000775 getTargetParser().flushPendingInstructions(getStreamer());
776
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000777 if (TheCondState.TheCond != StartingCondState.TheCond ||
778 TheCondState.Ignore != StartingCondState.Ignore)
Nirav Dave2364748a2016-09-16 18:30:20 +0000779 printError(getTok().getLoc(), "unmatched .ifs or .elses");
Kevin Enderbye5930f12010-07-28 20:55:35 +0000780 // Check to see there are no empty DwarfFile slots.
David Blaikie8bf66c42014-04-01 07:35:52 +0000781 const auto &LineTables = getContext().getMCDwarfLineTables();
782 if (!LineTables.empty()) {
783 unsigned Index = 0;
784 for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) {
785 if (File.Name.empty() && Index != 0)
Nirav Dave2364748a2016-09-16 18:30:20 +0000786 printError(getTok().getLoc(), "unassigned file number: " +
787 Twine(Index) +
788 " for .file directives");
David Blaikie8bf66c42014-04-01 07:35:52 +0000789 ++Index;
790 }
Kevin Enderbye5930f12010-07-28 20:55:35 +0000791 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000792
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000793 // Check to see that all assembler local symbols were actually defined.
794 // Targets that don't do subsections via symbols may not want this, though,
795 // so conservatively exclude them. Only do this if we're finalizing, though,
796 // as otherwise we won't necessarilly have seen everything yet.
Tim Northover6b3169b2016-04-11 19:50:46 +0000797 if (!NoFinalize) {
798 if (MAI.hasSubsectionsViaSymbols()) {
799 for (const auto &TableEntry : getContext().getSymbols()) {
800 MCSymbol *Sym = TableEntry.getValue();
801 // Variable symbols may not be marked as defined, so check those
802 // explicitly. If we know it's a variable, we have a definition for
803 // the purposes of this check.
804 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
805 // FIXME: We would really like to refer back to where the symbol was
806 // first referenced for a source location. We need to add something
807 // to track that. Currently, we just point to the end of the file.
Nirav Dave2364748a2016-09-16 18:30:20 +0000808 printError(getTok().getLoc(), "assembler local symbol '" +
809 Sym->getName() + "' not defined");
Tim Northover6b3169b2016-04-11 19:50:46 +0000810 }
811 }
812
813 // Temporary symbols like the ones for directional jumps don't go in the
814 // symbol table. They also need to be diagnosed in all (final) cases.
Tim Northoverc0bef992016-04-13 19:46:54 +0000815 for (std::tuple<SMLoc, CppHashInfoTy, MCSymbol *> &LocSym : DirLabels) {
816 if (std::get<2>(LocSym)->isUndefined()) {
817 // Reset the state of any "# line file" directives we've seen to the
818 // context as it was at the diagnostic site.
819 CppHashInfo = std::get<1>(LocSym);
Nirav Dave2364748a2016-09-16 18:30:20 +0000820 printError(std::get<0>(LocSym), "directional label undefined");
Tim Northoverc0bef992016-04-13 19:46:54 +0000821 }
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000822 }
823 }
824
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000825 // Finalize the output stream if there are no errors and if the client wants
826 // us to.
Jack Carter13d5f752013-10-04 22:52:31 +0000827 if (!HadError && !NoFinalize)
Daniel Dunbar9df5f332009-08-21 08:34:18 +0000828 Out.Finish();
829
Oliver Stannard07b43d32015-11-17 09:58:07 +0000830 return HadError || getContext().hadError();
Chris Lattner36e02122009-06-21 20:54:55 +0000831}
832
Nirav Davef43cc9f2016-10-10 15:24:54 +0000833bool AsmParser::checkForValidSection() {
Eric Christopher445c9522016-10-14 05:47:37 +0000834 if (!ParsingInlineAsm && !getStreamer().getCurrentSectionOnly()) {
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000835 Out.InitSections(false);
Nirav Davef43cc9f2016-10-10 15:24:54 +0000836 return Error(getTok().getLoc(),
837 "expected section directive before assembly directive");
Daniel Dunbare5444a82010-09-09 22:42:59 +0000838 }
Nirav Davef43cc9f2016-10-10 15:24:54 +0000839 return false;
Daniel Dunbare5444a82010-09-09 22:42:59 +0000840}
841
Jim Grosbach4b905842013-09-20 23:08:21 +0000842/// \brief Throw away the rest of the line for testing purposes.
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000843void AsmParser::eatToEndOfStatement() {
Jim Grosbach4b905842013-09-20 23:08:21 +0000844 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Nirav Dave1180e6892016-06-02 17:15:05 +0000845 Lexer.Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +0000846
Chris Lattnere5074c42009-06-22 01:29:09 +0000847 // Eat EOL.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000848 if (Lexer.is(AsmToken::EndOfStatement))
Nirav Dave1180e6892016-06-02 17:15:05 +0000849 Lexer.Lex();
Chris Lattnere5074c42009-06-22 01:29:09 +0000850}
851
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000852StringRef AsmParser::parseStringToEndOfStatement() {
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000853 const char *Start = getTok().getLoc().getPointer();
854
Jim Grosbach4b905842013-09-20 23:08:21 +0000855 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Nirav Davefd910412016-06-17 16:06:17 +0000856 Lexer.Lex();
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000857
858 const char *End = getTok().getLoc().getPointer();
859 return StringRef(Start, End - Start);
860}
Chris Lattner78db3622009-06-22 05:51:26 +0000861
Jim Grosbach4b905842013-09-20 23:08:21 +0000862StringRef AsmParser::parseStringToComma() {
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000863 const char *Start = getTok().getLoc().getPointer();
864
865 while (Lexer.isNot(AsmToken::EndOfStatement) &&
Jim Grosbach4b905842013-09-20 23:08:21 +0000866 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
Nirav Davefd910412016-06-17 16:06:17 +0000867 Lexer.Lex();
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000868
869 const char *End = getTok().getLoc().getPointer();
870 return StringRef(Start, End - Start);
871}
872
Jim Grosbach4b905842013-09-20 23:08:21 +0000873/// \brief Parse a paren expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +0000874/// NOTE: This assumes the leading '(' has already been consumed.
875///
876/// parenexpr ::= expr)
877///
Jim Grosbach4b905842013-09-20 23:08:21 +0000878bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
879 if (parseExpression(Res))
880 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000881 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner7fdbce72009-06-22 06:32:03 +0000882 return TokError("expected ')' in parentheses expression");
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000883 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +0000884 Lex();
Chris Lattner7fdbce72009-06-22 06:32:03 +0000885 return false;
886}
Chris Lattner78db3622009-06-22 05:51:26 +0000887
Jim Grosbach4b905842013-09-20 23:08:21 +0000888/// \brief Parse a bracket expression and return it.
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +0000889/// NOTE: This assumes the leading '[' has already been consumed.
890///
891/// bracketexpr ::= expr]
892///
Jim Grosbach4b905842013-09-20 23:08:21 +0000893bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
894 if (parseExpression(Res))
895 return true;
Nirav Davea645433c2016-07-18 15:24:03 +0000896 EndLoc = getTok().getEndLoc();
897 if (parseToken(AsmToken::RBrac, "expected ']' in brackets expression"))
898 return true;
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +0000899 return false;
900}
901
Jim Grosbach4b905842013-09-20 23:08:21 +0000902/// \brief Parse a primary expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +0000903/// primaryexpr ::= (parenexpr
904/// primaryexpr ::= symbol
905/// primaryexpr ::= number
Chris Lattner6b55cb92010-04-14 04:40:28 +0000906/// primaryexpr ::= '.'
Chris Lattner7fdbce72009-06-22 06:32:03 +0000907/// primaryexpr ::= ~,+,- primaryexpr
Jim Grosbach4b905842013-09-20 23:08:21 +0000908bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Kevin Enderby0017d8a2013-01-22 21:09:20 +0000909 SMLoc FirstTokenLoc = getLexer().getLoc();
910 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
911 switch (FirstTokenKind) {
Chris Lattner78db3622009-06-22 05:51:26 +0000912 default:
913 return TokError("unknown token in expression");
Eric Christopher104af062011-04-12 00:03:13 +0000914 // If we have an error assume that we've already handled it.
915 case AsmToken::Error:
916 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000917 case AsmToken::Exclaim:
Sean Callanan686ed8d2010-01-19 20:22:31 +0000918 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +0000919 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000920 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +0000921 Res = MCUnaryExpr::createLNot(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000922 return false;
Daniel Dunbar24764322010-08-24 19:13:42 +0000923 case AsmToken::Dollar:
Hans Wennborgce69d772013-10-18 20:46:28 +0000924 case AsmToken::At:
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +0000925 case AsmToken::String:
Daniel Dunbard20cda02009-10-16 01:34:54 +0000926 case AsmToken::Identifier: {
Daniel Dunbar24764322010-08-24 19:13:42 +0000927 StringRef Identifier;
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000928 if (parseIdentifier(Identifier)) {
Nirav Daved0463322016-10-12 13:58:07 +0000929 // We may have failed but $ may be a valid token.
930 if (getTok().is(AsmToken::Dollar)) {
David Majnemer0c58bc62013-09-25 10:47:21 +0000931 if (Lexer.getMAI().getDollarIsPC()) {
Nirav Daved0463322016-10-12 13:58:07 +0000932 Lex();
David Majnemer0c58bc62013-09-25 10:47:21 +0000933 // This is a '$' reference, which references the current PC. Emit a
934 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +0000935 MCSymbol *Sym = Ctx.createTempSymbol();
David Majnemer0c58bc62013-09-25 10:47:21 +0000936 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +0000937 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None,
Jack Carter721726a2013-10-04 21:26:15 +0000938 getContext());
David Majnemer0c58bc62013-09-25 10:47:21 +0000939 EndLoc = FirstTokenLoc;
940 return false;
Ted Kremenek297febe2014-03-06 22:13:17 +0000941 }
942 return Error(FirstTokenLoc, "invalid token in expression");
David Majnemer0c58bc62013-09-25 10:47:21 +0000943 }
Kevin Enderby0017d8a2013-01-22 21:09:20 +0000944 }
David Peixotto8ad70b32013-12-04 22:43:20 +0000945 // Parse symbol variant
946 std::pair<StringRef, StringRef> Split;
947 if (!MAI.useParensForSymbolVariant()) {
David Majnemer6a5b8122014-06-19 01:25:43 +0000948 if (FirstTokenKind == AsmToken::String) {
949 if (Lexer.is(AsmToken::At)) {
Nirav Davefd910412016-06-17 16:06:17 +0000950 Lex(); // eat @
David Majnemer6a5b8122014-06-19 01:25:43 +0000951 SMLoc AtLoc = getLexer().getLoc();
952 StringRef VName;
953 if (parseIdentifier(VName))
954 return Error(AtLoc, "expected symbol variant after '@'");
955
956 Split = std::make_pair(Identifier, VName);
957 }
958 } else {
959 Split = Identifier.split('@');
960 }
David Peixotto8ad70b32013-12-04 22:43:20 +0000961 } else if (Lexer.is(AsmToken::LParen)) {
Nirav Davefd910412016-06-17 16:06:17 +0000962 Lex(); // eat '('.
David Peixotto8ad70b32013-12-04 22:43:20 +0000963 StringRef VName;
964 parseIdentifier(VName);
Nirav Davea645433c2016-07-18 15:24:03 +0000965 // eat ')'.
966 if (parseToken(AsmToken::RParen,
967 "unexpected token in variant, expected ')'"))
968 return true;
David Peixotto8ad70b32013-12-04 22:43:20 +0000969 Split = std::make_pair(Identifier, VName);
970 }
Daniel Dunbar24764322010-08-24 19:13:42 +0000971
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000972 EndLoc = SMLoc::getFromPointer(Identifier.end());
973
Daniel Dunbard20cda02009-10-16 01:34:54 +0000974 // This is a symbol reference.
Hans Wennborgce69d772013-10-18 20:46:28 +0000975 StringRef SymbolName = Identifier;
Weiming Zhaocf26d562016-12-01 18:00:36 +0000976 if (SymbolName.empty())
977 return true;
978
Hans Wennborgce69d772013-10-18 20:46:28 +0000979 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Hans Wennborg69918bc2013-10-17 01:13:02 +0000980
Hans Wennborg7ddcdc82013-10-18 02:14:40 +0000981 // Lookup the symbol variant if used.
David Peixotto8ad70b32013-12-04 22:43:20 +0000982 if (Split.second.size()) {
Hans Wennborg7ddcdc82013-10-18 02:14:40 +0000983 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Hans Wennborgce69d772013-10-18 20:46:28 +0000984 if (Variant != MCSymbolRefExpr::VK_Invalid) {
985 SymbolName = Split.first;
David Peixotto8ad70b32013-12-04 22:43:20 +0000986 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
Hans Wennborgce69d772013-10-18 20:46:28 +0000987 Variant = MCSymbolRefExpr::VK_None;
988 } else {
Saleem Abdulrasoola25e1e42014-01-26 22:29:43 +0000989 return Error(SMLoc::getFromPointer(Split.second.begin()),
990 "invalid variant '" + Split.second + "'");
Daniel Dunbar55f16672010-09-17 02:47:07 +0000991 }
992 }
Daniel Dunbar55992562010-03-15 23:51:06 +0000993
Jim Grosbach6f482002015-05-18 18:43:14 +0000994 MCSymbol *Sym = getContext().getOrCreateSymbol(SymbolName);
Hans Wennborgce69d772013-10-18 20:46:28 +0000995
Daniel Dunbard20cda02009-10-16 01:34:54 +0000996 // If this is an absolute variable reference, substitute it now to preserve
997 // semantics in the face of reassignment.
Vedant Kumar86dbd922015-08-31 17:44:53 +0000998 if (Sym->isVariable() &&
999 isa<MCConstantExpr>(Sym->getVariableValue(/*SetUsed*/ false))) {
Daniel Dunbar55992562010-03-15 23:51:06 +00001000 if (Variant)
Daniel Dunbar8a3c3f22010-11-08 17:53:02 +00001001 return Error(EndLoc, "unexpected modifier on variable reference");
Daniel Dunbar55992562010-03-15 23:51:06 +00001002
Vedant Kumar86dbd922015-08-31 17:44:53 +00001003 Res = Sym->getVariableValue(/*SetUsed*/ false);
Daniel Dunbard20cda02009-10-16 01:34:54 +00001004 return false;
1005 }
1006
1007 // Otherwise create a symbol ref.
Chad Rosier9245e122017-01-19 20:06:32 +00001008 Res = MCSymbolRefExpr::create(Sym, Variant, getContext(), FirstTokenLoc);
Chris Lattner78db3622009-06-22 05:51:26 +00001009 return false;
Daniel Dunbard20cda02009-10-16 01:34:54 +00001010 }
David Woodhousef42a6662014-02-01 16:20:54 +00001011 case AsmToken::BigNum:
1012 return TokError("literal value out of range for directive");
Kevin Enderby0510b482010-05-17 23:08:19 +00001013 case AsmToken::Integer: {
1014 SMLoc Loc = getTok().getLoc();
1015 int64_t IntVal = getTok().getIntVal();
Jim Grosbach13760bd2015-05-30 01:25:56 +00001016 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001017 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001018 Lex(); // Eat token.
Kevin Enderby0510b482010-05-17 23:08:19 +00001019 // Look for 'b' or 'f' following an Integer as a directional label
1020 if (Lexer.getKind() == AsmToken::Identifier) {
1021 StringRef IDVal = getTok().getString();
Ulrich Weigandd4120982013-06-20 16:24:17 +00001022 // Lookup the symbol variant if used.
1023 std::pair<StringRef, StringRef> Split = IDVal.split('@');
1024 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
1025 if (Split.first.size() != IDVal.size()) {
1026 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Arnaud A. de Grandmaisonc97727a2014-03-21 21:54:46 +00001027 if (Variant == MCSymbolRefExpr::VK_Invalid)
Ulrich Weigandd4120982013-06-20 16:24:17 +00001028 return TokError("invalid variant '" + Split.second + "'");
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001029 IDVal = Split.first;
Ulrich Weigandd4120982013-06-20 16:24:17 +00001030 }
Jim Grosbach4b905842013-09-20 23:08:21 +00001031 if (IDVal == "f" || IDVal == "b") {
1032 MCSymbol *Sym =
Jim Grosbach6f482002015-05-18 18:43:14 +00001033 Ctx.getDirectionalLocalSymbol(IntVal, IDVal == "b");
Jim Grosbach13760bd2015-05-30 01:25:56 +00001034 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00001035 if (IDVal == "b" && Sym->isUndefined())
Tim Northover6b3169b2016-04-11 19:50:46 +00001036 return Error(Loc, "directional label undefined");
Tim Northoverc0bef992016-04-13 19:46:54 +00001037 DirLabels.push_back(std::make_tuple(Loc, CppHashInfo, Sym));
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001038 EndLoc = Lexer.getTok().getEndLoc();
Kevin Enderby0510b482010-05-17 23:08:19 +00001039 Lex(); // Eat identifier.
1040 }
1041 }
Chris Lattner78db3622009-06-22 05:51:26 +00001042 return false;
Kevin Enderby0510b482010-05-17 23:08:19 +00001043 }
Bill Wendlingcdbf17b2011-01-25 21:26:41 +00001044 case AsmToken::Real: {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001045 APFloat RealVal(APFloat::IEEEdouble(), getTok().getString());
Bob Wilson813bdf62011-02-03 23:17:47 +00001046 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Jim Grosbach13760bd2015-05-30 01:25:56 +00001047 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001048 EndLoc = Lexer.getTok().getEndLoc();
Bill Wendlingcdbf17b2011-01-25 21:26:41 +00001049 Lex(); // Eat token.
1050 return false;
1051 }
Chris Lattner6b55cb92010-04-14 04:40:28 +00001052 case AsmToken::Dot: {
1053 // This is a '.' reference, which references the current PC. Emit a
1054 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +00001055 MCSymbol *Sym = Ctx.createTempSymbol();
Chris Lattner6b55cb92010-04-14 04:40:28 +00001056 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +00001057 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001058 EndLoc = Lexer.getTok().getEndLoc();
Chris Lattner6b55cb92010-04-14 04:40:28 +00001059 Lex(); // Eat identifier.
1060 return false;
1061 }
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001062 case AsmToken::LParen:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001063 Lex(); // Eat the '('.
Jim Grosbach4b905842013-09-20 23:08:21 +00001064 return parseParenExpr(Res, EndLoc);
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +00001065 case AsmToken::LBrac:
1066 if (!PlatformParser->HasBracketExpressions())
1067 return TokError("brackets expression not supported on this target");
1068 Lex(); // Eat the '['.
Jim Grosbach4b905842013-09-20 23:08:21 +00001069 return parseBracketExpr(Res, EndLoc);
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001070 case AsmToken::Minus:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001071 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001072 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001073 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001074 Res = MCUnaryExpr::createMinus(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001075 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001076 case AsmToken::Plus:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001077 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001078 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001079 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001080 Res = MCUnaryExpr::createPlus(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001081 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001082 case AsmToken::Tilde:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001083 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001084 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001085 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001086 Res = MCUnaryExpr::createNot(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001087 return false;
Daniel Sanders3feeb9c2016-08-08 11:50:25 +00001088 // MIPS unary expression operators. The lexer won't generate these tokens if
1089 // MCAsmInfo::HasMipsExpressions is false for the target.
1090 case AsmToken::PercentCall16:
1091 case AsmToken::PercentCall_Hi:
1092 case AsmToken::PercentCall_Lo:
1093 case AsmToken::PercentDtprel_Hi:
1094 case AsmToken::PercentDtprel_Lo:
1095 case AsmToken::PercentGot:
1096 case AsmToken::PercentGot_Disp:
1097 case AsmToken::PercentGot_Hi:
1098 case AsmToken::PercentGot_Lo:
1099 case AsmToken::PercentGot_Ofst:
1100 case AsmToken::PercentGot_Page:
1101 case AsmToken::PercentGottprel:
1102 case AsmToken::PercentGp_Rel:
1103 case AsmToken::PercentHi:
1104 case AsmToken::PercentHigher:
1105 case AsmToken::PercentHighest:
1106 case AsmToken::PercentLo:
1107 case AsmToken::PercentNeg:
1108 case AsmToken::PercentPcrel_Hi:
1109 case AsmToken::PercentPcrel_Lo:
1110 case AsmToken::PercentTlsgd:
1111 case AsmToken::PercentTlsldm:
1112 case AsmToken::PercentTprel_Hi:
1113 case AsmToken::PercentTprel_Lo:
1114 Lex(); // Eat the operator.
1115 if (Lexer.isNot(AsmToken::LParen))
1116 return TokError("expected '(' after operator");
1117 Lex(); // Eat the operator.
1118 if (parseExpression(Res, EndLoc))
1119 return true;
1120 if (Lexer.isNot(AsmToken::RParen))
1121 return TokError("expected ')'");
1122 Lex(); // Eat the operator.
1123 Res = getTargetParser().createTargetUnaryExpr(Res, FirstTokenKind, Ctx);
1124 return !Res;
Chris Lattner78db3622009-06-22 05:51:26 +00001125 }
1126}
Chris Lattner7fdbce72009-06-22 06:32:03 +00001127
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001128bool AsmParser::parseExpression(const MCExpr *&Res) {
Chris Lattnere17df0b2010-01-15 19:39:23 +00001129 SMLoc EndLoc;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001130 return parseExpression(Res, EndLoc);
Chris Lattner528d00b2010-01-15 19:28:38 +00001131}
1132
Daniel Dunbar55f16672010-09-17 02:47:07 +00001133const MCExpr *
Jim Grosbach4b905842013-09-20 23:08:21 +00001134AsmParser::applyModifierToExpr(const MCExpr *E,
Daniel Dunbar55f16672010-09-17 02:47:07 +00001135 MCSymbolRefExpr::VariantKind Variant) {
Joerg Sonnenbergerb822af42013-08-27 20:23:19 +00001136 // Ask the target implementation about this expression first.
1137 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
1138 if (NewE)
1139 return NewE;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001140 // Recurse over the given expression, rebuilding it to apply the given variant
1141 // if there is exactly one symbol.
1142 switch (E->getKind()) {
1143 case MCExpr::Target:
1144 case MCExpr::Constant:
Craig Topper353eda42014-04-24 06:44:33 +00001145 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001146
1147 case MCExpr::SymbolRef: {
1148 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
1149
1150 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001151 TokError("invalid variant on expression '" + getTok().getIdentifier() +
1152 "' (already modified)");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001153 return E;
1154 }
1155
Jim Grosbach13760bd2015-05-30 01:25:56 +00001156 return MCSymbolRefExpr::create(&SRE->getSymbol(), Variant, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001157 }
1158
1159 case MCExpr::Unary: {
1160 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +00001161 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001162 if (!Sub)
Craig Topper353eda42014-04-24 06:44:33 +00001163 return nullptr;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001164 return MCUnaryExpr::create(UE->getOpcode(), Sub, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001165 }
1166
1167 case MCExpr::Binary: {
1168 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +00001169 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
1170 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001171
1172 if (!LHS && !RHS)
Craig Topper353eda42014-04-24 06:44:33 +00001173 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001174
Jim Grosbach4b905842013-09-20 23:08:21 +00001175 if (!LHS)
1176 LHS = BE->getLHS();
1177 if (!RHS)
1178 RHS = BE->getRHS();
Daniel Dunbar55f16672010-09-17 02:47:07 +00001179
Jim Grosbach13760bd2015-05-30 01:25:56 +00001180 return MCBinaryExpr::create(BE->getOpcode(), LHS, RHS, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001181 }
1182 }
Daniel Dunbarbaad46c2010-09-17 16:34:24 +00001183
Craig Toppera2886c22012-02-07 05:05:23 +00001184 llvm_unreachable("Invalid expression kind!");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001185}
1186
Jim Grosbach4b905842013-09-20 23:08:21 +00001187/// \brief Parse an expression and return it.
Michael J. Spencer530ce852010-10-09 11:00:50 +00001188///
Jim Grosbachbd164242011-08-20 16:24:13 +00001189/// expr ::= expr &&,|| expr -> lowest.
1190/// expr ::= expr |,^,&,! expr
1191/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1192/// expr ::= expr <<,>> expr
1193/// expr ::= expr +,- expr
1194/// expr ::= expr *,/,% expr -> highest.
Chris Lattner7fdbce72009-06-22 06:32:03 +00001195/// expr ::= primaryexpr
1196///
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001197bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001198 // Parse the expression.
Craig Topper353eda42014-04-24 06:44:33 +00001199 Res = nullptr;
Jim Grosbach4b905842013-09-20 23:08:21 +00001200 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001201 return true;
1202
Daniel Dunbar55f16672010-09-17 02:47:07 +00001203 // As a special case, we support 'a op b @ modifier' by rewriting the
1204 // expression to include the modifier. This is inefficient, but in general we
1205 // expect users to use 'a@modifier op b'.
1206 if (Lexer.getKind() == AsmToken::At) {
1207 Lex();
1208
1209 if (Lexer.isNot(AsmToken::Identifier))
1210 return TokError("unexpected symbol modifier following '@'");
1211
1212 MCSymbolRefExpr::VariantKind Variant =
Jim Grosbach4b905842013-09-20 23:08:21 +00001213 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001214 if (Variant == MCSymbolRefExpr::VK_Invalid)
1215 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1216
Jim Grosbach4b905842013-09-20 23:08:21 +00001217 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001218 if (!ModifiedRes) {
1219 return TokError("invalid modifier '" + getTok().getIdentifier() +
1220 "' (no symbols present)");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001221 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001222
Daniel Dunbar55f16672010-09-17 02:47:07 +00001223 Res = ModifiedRes;
1224 Lex();
1225 }
1226
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001227 // Try to constant fold it up front, if possible.
1228 int64_t Value;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001229 if (Res->evaluateAsAbsolute(Value))
1230 Res = MCConstantExpr::create(Value, getContext());
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001231
1232 return false;
Chris Lattner7fdbce72009-06-22 06:32:03 +00001233}
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001234
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001235bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Craig Topper353eda42014-04-24 06:44:33 +00001236 Res = nullptr;
Jim Grosbach4b905842013-09-20 23:08:21 +00001237 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
Daniel Dunbar7c82d562009-08-31 08:08:17 +00001238}
1239
Toma Tabacu7bc44dc2015-06-25 09:52:02 +00001240bool AsmParser::parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
1241 SMLoc &EndLoc) {
1242 if (parseParenExpr(Res, EndLoc))
1243 return true;
1244
1245 for (; ParenDepth > 0; --ParenDepth) {
1246 if (parseBinOpRHS(1, Res, EndLoc))
1247 return true;
1248
1249 // We don't Lex() the last RParen.
1250 // This is the same behavior as parseParenExpression().
1251 if (ParenDepth - 1 > 0) {
Nirav Davea645433c2016-07-18 15:24:03 +00001252 EndLoc = getTok().getEndLoc();
1253 if (parseToken(AsmToken::RParen,
1254 "expected ')' in parentheses expression"))
1255 return true;
Toma Tabacu7bc44dc2015-06-25 09:52:02 +00001256 }
1257 }
1258 return false;
1259}
1260
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001261bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
Daniel Dunbarf3636452009-08-31 08:07:22 +00001262 const MCExpr *Expr;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001263
Daniel Dunbar75630b32009-06-30 02:10:03 +00001264 SMLoc StartLoc = Lexer.getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001265 if (parseExpression(Expr))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001266 return true;
1267
Jim Grosbach13760bd2015-05-30 01:25:56 +00001268 if (!Expr->evaluateAsAbsolute(Res))
Daniel Dunbar75630b32009-06-30 02:10:03 +00001269 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001270
1271 return false;
1272}
1273
David Majnemer0993e0b2015-10-26 03:15:34 +00001274static unsigned getDarwinBinOpPrecedence(AsmToken::TokenKind K,
1275 MCBinaryExpr::Opcode &Kind,
1276 bool ShouldUseLogicalShr) {
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001277 switch (K) {
Daniel Dunbar940cda22009-08-31 08:07:44 +00001278 default:
Jim Grosbach4b905842013-09-20 23:08:21 +00001279 return 0; // not a binop.
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001280
Jim Grosbach4b905842013-09-20 23:08:21 +00001281 // Lowest Precedence: &&, ||
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001282 case AsmToken::AmpAmp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001283 Kind = MCBinaryExpr::LAnd;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001284 return 1;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001285 case AsmToken::PipePipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001286 Kind = MCBinaryExpr::LOr;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001287 return 1;
1288
Jim Grosbach4b905842013-09-20 23:08:21 +00001289 // Low Precedence: |, &, ^
1290 //
1291 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001292 case AsmToken::Pipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001293 Kind = MCBinaryExpr::Or;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001294 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001295 case AsmToken::Caret:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001296 Kind = MCBinaryExpr::Xor;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001297 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001298 case AsmToken::Amp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001299 Kind = MCBinaryExpr::And;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001300 return 2;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001301
Jim Grosbach4b905842013-09-20 23:08:21 +00001302 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001303 case AsmToken::EqualEqual:
1304 Kind = MCBinaryExpr::EQ;
1305 return 3;
1306 case AsmToken::ExclaimEqual:
1307 case AsmToken::LessGreater:
1308 Kind = MCBinaryExpr::NE;
1309 return 3;
1310 case AsmToken::Less:
1311 Kind = MCBinaryExpr::LT;
1312 return 3;
1313 case AsmToken::LessEqual:
1314 Kind = MCBinaryExpr::LTE;
1315 return 3;
1316 case AsmToken::Greater:
1317 Kind = MCBinaryExpr::GT;
1318 return 3;
1319 case AsmToken::GreaterEqual:
1320 Kind = MCBinaryExpr::GTE;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001321 return 3;
1322
Jim Grosbach4b905842013-09-20 23:08:21 +00001323 // Intermediate Precedence: <<, >>
Jim Grosbachbd164242011-08-20 16:24:13 +00001324 case AsmToken::LessLess:
1325 Kind = MCBinaryExpr::Shl;
1326 return 4;
1327 case AsmToken::GreaterGreater:
David Majnemer0993e0b2015-10-26 03:15:34 +00001328 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
Jim Grosbachbd164242011-08-20 16:24:13 +00001329 return 4;
1330
Jim Grosbach4b905842013-09-20 23:08:21 +00001331 // High Intermediate Precedence: +, -
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001332 case AsmToken::Plus:
1333 Kind = MCBinaryExpr::Add;
Jim Grosbachbd164242011-08-20 16:24:13 +00001334 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001335 case AsmToken::Minus:
1336 Kind = MCBinaryExpr::Sub;
Jim Grosbachbd164242011-08-20 16:24:13 +00001337 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001338
Jim Grosbach4b905842013-09-20 23:08:21 +00001339 // Highest Precedence: *, /, %
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001340 case AsmToken::Star:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001341 Kind = MCBinaryExpr::Mul;
Jim Grosbachbd164242011-08-20 16:24:13 +00001342 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001343 case AsmToken::Slash:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001344 Kind = MCBinaryExpr::Div;
Jim Grosbachbd164242011-08-20 16:24:13 +00001345 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001346 case AsmToken::Percent:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001347 Kind = MCBinaryExpr::Mod;
Jim Grosbachbd164242011-08-20 16:24:13 +00001348 return 6;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001349 }
1350}
1351
David Majnemer0993e0b2015-10-26 03:15:34 +00001352static unsigned getGNUBinOpPrecedence(AsmToken::TokenKind K,
1353 MCBinaryExpr::Opcode &Kind,
1354 bool ShouldUseLogicalShr) {
1355 switch (K) {
1356 default:
1357 return 0; // not a binop.
1358
1359 // Lowest Precedence: &&, ||
1360 case AsmToken::AmpAmp:
1361 Kind = MCBinaryExpr::LAnd;
1362 return 2;
1363 case AsmToken::PipePipe:
1364 Kind = MCBinaryExpr::LOr;
1365 return 1;
1366
1367 // Low Precedence: ==, !=, <>, <, <=, >, >=
1368 case AsmToken::EqualEqual:
1369 Kind = MCBinaryExpr::EQ;
1370 return 3;
1371 case AsmToken::ExclaimEqual:
1372 case AsmToken::LessGreater:
1373 Kind = MCBinaryExpr::NE;
1374 return 3;
1375 case AsmToken::Less:
1376 Kind = MCBinaryExpr::LT;
1377 return 3;
1378 case AsmToken::LessEqual:
1379 Kind = MCBinaryExpr::LTE;
1380 return 3;
1381 case AsmToken::Greater:
1382 Kind = MCBinaryExpr::GT;
1383 return 3;
1384 case AsmToken::GreaterEqual:
1385 Kind = MCBinaryExpr::GTE;
1386 return 3;
1387
1388 // Low Intermediate Precedence: +, -
1389 case AsmToken::Plus:
1390 Kind = MCBinaryExpr::Add;
1391 return 4;
1392 case AsmToken::Minus:
1393 Kind = MCBinaryExpr::Sub;
1394 return 4;
1395
1396 // High Intermediate Precedence: |, &, ^
1397 //
1398 // FIXME: gas seems to support '!' as an infix operator?
1399 case AsmToken::Pipe:
1400 Kind = MCBinaryExpr::Or;
1401 return 5;
1402 case AsmToken::Caret:
1403 Kind = MCBinaryExpr::Xor;
1404 return 5;
1405 case AsmToken::Amp:
1406 Kind = MCBinaryExpr::And;
1407 return 5;
1408
1409 // Highest Precedence: *, /, %, <<, >>
1410 case AsmToken::Star:
1411 Kind = MCBinaryExpr::Mul;
1412 return 6;
1413 case AsmToken::Slash:
1414 Kind = MCBinaryExpr::Div;
1415 return 6;
1416 case AsmToken::Percent:
1417 Kind = MCBinaryExpr::Mod;
1418 return 6;
1419 case AsmToken::LessLess:
1420 Kind = MCBinaryExpr::Shl;
1421 return 6;
1422 case AsmToken::GreaterGreater:
1423 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1424 return 6;
1425 }
1426}
1427
1428unsigned AsmParser::getBinOpPrecedence(AsmToken::TokenKind K,
1429 MCBinaryExpr::Opcode &Kind) {
1430 bool ShouldUseLogicalShr = MAI.shouldUseLogicalShr();
1431 return IsDarwin ? getDarwinBinOpPrecedence(K, Kind, ShouldUseLogicalShr)
1432 : getGNUBinOpPrecedence(K, Kind, ShouldUseLogicalShr);
1433}
1434
Jim Grosbach4b905842013-09-20 23:08:21 +00001435/// \brief Parse all binary operators with precedence >= 'Precedence'.
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001436/// Res contains the LHS of the expression on input.
Jim Grosbach4b905842013-09-20 23:08:21 +00001437bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
Chris Lattner528d00b2010-01-15 19:28:38 +00001438 SMLoc &EndLoc) {
Chad Rosier9245e122017-01-19 20:06:32 +00001439 SMLoc StartLoc = Lexer.getLoc();
Eugene Zelenko33d7b762016-08-23 17:14:32 +00001440 while (true) {
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001441 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001442 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001443
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001444 // If the next token is lower precedence than we are allowed to eat, return
1445 // successfully with what we ate already.
1446 if (TokPrec < Precedence)
1447 return false;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001448
Sean Callanan686ed8d2010-01-19 20:22:31 +00001449 Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +00001450
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001451 // Eat the next primary expression.
Daniel Dunbarf3636452009-08-31 08:07:22 +00001452 const MCExpr *RHS;
Jim Grosbach4b905842013-09-20 23:08:21 +00001453 if (parsePrimaryExpr(RHS, EndLoc))
1454 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001455
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001456 // If BinOp binds less tightly with RHS than the operator after RHS, let
1457 // the pending operator take RHS as its LHS.
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001458 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001459 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Jim Grosbach4b905842013-09-20 23:08:21 +00001460 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1461 return true;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001462
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001463 // Merge LHS and RHS according to operator.
Chad Rosier9245e122017-01-19 20:06:32 +00001464 Res = MCBinaryExpr::create(Kind, Res, RHS, getContext(), StartLoc);
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001465 }
1466}
1467
Chris Lattner36e02122009-06-21 20:54:55 +00001468/// ParseStatement:
1469/// ::= EndOfStatement
Chris Lattnere5074c42009-06-22 01:29:09 +00001470/// ::= Label* Directive ...Operands... EndOfStatement
1471/// ::= Label* Identifier OperandList* EndOfStatement
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001472bool AsmParser::parseStatement(ParseStatementInfo &Info,
1473 MCAsmParserSemaCallback *SI) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001474 assert(!hasPendingError() && "parseStatement started with pending error");
Nirav Davefd910412016-06-17 16:06:17 +00001475 // Eat initial spaces and comments
1476 while (Lexer.is(AsmToken::Space))
1477 Lex();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001478 if (Lexer.is(AsmToken::EndOfStatement)) {
Nirav Davefd910412016-06-17 16:06:17 +00001479 // if this is a line comment we can drop it safely
1480 if (getTok().getString().front() == '\r' ||
1481 getTok().getString().front() == '\n')
1482 Out.AddBlankLine();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001483 Lex();
Chris Lattner36e02122009-06-21 20:54:55 +00001484 return false;
Chris Lattner36e02122009-06-21 20:54:55 +00001485 }
Nirav Dave9263ae32016-08-02 19:17:54 +00001486 if (Lexer.is(AsmToken::Hash)) {
1487 // Seeing a hash here means that it was an end-of-line comment in
1488 // an asm syntax where hash's are not comment and the previous
1489 // statement parser did not check the end of statement. Relex as
1490 // EndOfStatement.
1491 StringRef CommentStr = parseStringToEndOfStatement();
1492 Lexer.Lex();
1493 Lexer.UnLex(AsmToken(AsmToken::EndOfStatement, CommentStr));
1494 return false;
1495 }
Nirav Davefd910412016-06-17 16:06:17 +00001496 // Statements always start with an identifier.
Sean Callanan936b0d32010-01-19 21:44:56 +00001497 AsmToken ID = getTok();
Daniel Dunbaree4465c2009-07-28 16:38:40 +00001498 SMLoc IDLoc = ID.getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001499 StringRef IDVal;
Kevin Enderby0510b482010-05-17 23:08:19 +00001500 int64_t LocalLabelVal = -1;
Nirav Davefd910412016-06-17 16:06:17 +00001501 if (Lexer.is(AsmToken::HashDirective))
Jim Grosbach4b905842013-09-20 23:08:21 +00001502 return parseCppHashLineFilenameComment(IDLoc);
Kevin Enderbyfa3c6f12010-12-24 00:12:02 +00001503 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderby0510b482010-05-17 23:08:19 +00001504 if (Lexer.is(AsmToken::Integer)) {
1505 LocalLabelVal = getTok().getIntVal();
1506 if (LocalLabelVal < 0) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001507 if (!TheCondState.Ignore) {
1508 Lex(); // always eat a token
1509 return Error(IDLoc, "unexpected token at start of statement");
1510 }
Kevin Enderby0510b482010-05-17 23:08:19 +00001511 IDVal = "";
Eli Bendersky88024712013-01-16 19:32:36 +00001512 } else {
Kevin Enderby0510b482010-05-17 23:08:19 +00001513 IDVal = getTok().getString();
1514 Lex(); // Consume the integer token to be used as an identifier token.
1515 if (Lexer.getKind() != AsmToken::Colon) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001516 if (!TheCondState.Ignore) {
1517 Lex(); // always eat a token
1518 return Error(IDLoc, "unexpected token at start of statement");
1519 }
Kevin Enderby0510b482010-05-17 23:08:19 +00001520 }
1521 }
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001522 } else if (Lexer.is(AsmToken::Dot)) {
1523 // Treat '.' as a valid identifier in this context.
1524 Lex();
1525 IDVal = ".";
Colin LeMahieu8a0453e2015-11-09 00:31:07 +00001526 } else if (Lexer.is(AsmToken::LCurly)) {
1527 // Treat '{' as a valid identifier in this context.
1528 Lex();
1529 IDVal = "{";
1530
1531 } else if (Lexer.is(AsmToken::RCurly)) {
1532 // Treat '}' as a valid identifier in this context.
1533 Lex();
1534 IDVal = "}";
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001535 } else if (parseIdentifier(IDVal)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001536 if (!TheCondState.Ignore) {
1537 Lex(); // always eat a token
1538 return Error(IDLoc, "unexpected token at start of statement");
1539 }
Chris Lattner926885c2010-04-17 18:14:27 +00001540 IDVal = "";
1541 }
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001542
Chris Lattner926885c2010-04-17 18:14:27 +00001543 // Handle conditional assembly here before checking for skipping. We
1544 // have to do this so that .endif isn't skipped in a ".if 0" block for
1545 // example.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001546 StringMap<DirectiveKind>::const_iterator DirKindIt =
Jim Grosbach4b905842013-09-20 23:08:21 +00001547 DirectiveKindMap.find(IDVal);
1548 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1549 ? DK_NO_DIRECTIVE
1550 : DirKindIt->getValue();
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001551 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001552 default:
1553 break;
1554 case DK_IF:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001555 case DK_IFEQ:
1556 case DK_IFGE:
1557 case DK_IFGT:
1558 case DK_IFLE:
1559 case DK_IFLT:
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00001560 case DK_IFNE:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001561 return parseDirectiveIf(IDLoc, DirKind);
Jim Grosbach4b905842013-09-20 23:08:21 +00001562 case DK_IFB:
1563 return parseDirectiveIfb(IDLoc, true);
1564 case DK_IFNB:
1565 return parseDirectiveIfb(IDLoc, false);
1566 case DK_IFC:
1567 return parseDirectiveIfc(IDLoc, true);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00001568 case DK_IFEQS:
Sid Manning51c35602015-03-18 14:20:54 +00001569 return parseDirectiveIfeqs(IDLoc, true);
Jim Grosbach4b905842013-09-20 23:08:21 +00001570 case DK_IFNC:
1571 return parseDirectiveIfc(IDLoc, false);
Sid Manning51c35602015-03-18 14:20:54 +00001572 case DK_IFNES:
1573 return parseDirectiveIfeqs(IDLoc, false);
Jim Grosbach4b905842013-09-20 23:08:21 +00001574 case DK_IFDEF:
1575 return parseDirectiveIfdef(IDLoc, true);
1576 case DK_IFNDEF:
1577 case DK_IFNOTDEF:
1578 return parseDirectiveIfdef(IDLoc, false);
1579 case DK_ELSEIF:
1580 return parseDirectiveElseIf(IDLoc);
1581 case DK_ELSE:
1582 return parseDirectiveElse(IDLoc);
1583 case DK_ENDIF:
1584 return parseDirectiveEndIf(IDLoc);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001585 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001586
Eli Bendersky88024712013-01-16 19:32:36 +00001587 // Ignore the statement if in the middle of inactive conditional
1588 // (e.g. ".if 0").
Chad Rosiereda70b32012-10-20 00:47:08 +00001589 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001590 eatToEndOfStatement();
Chris Lattner926885c2010-04-17 18:14:27 +00001591 return false;
1592 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001593
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001594 // FIXME: Recurse on local labels?
1595
1596 // See what kind of statement we have.
1597 switch (Lexer.getKind()) {
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001598 case AsmToken::Colon: {
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001599 if (!getTargetParser().isLabel(ID))
1600 break;
Nirav Davef43cc9f2016-10-10 15:24:54 +00001601 if (checkForValidSection())
1602 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00001603
Chris Lattner36e02122009-06-21 20:54:55 +00001604 // identifier ':' -> Label.
Sean Callanan686ed8d2010-01-19 20:22:31 +00001605 Lex();
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001606
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001607 // Diagnose attempt to use '.' as a label.
1608 if (IDVal == ".")
1609 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1610
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001611 // Diagnose attempt to use a variable as a label.
1612 //
1613 // FIXME: Diagnostics. Note the location of the definition as a label.
1614 // FIXME: This doesn't diagnose assignment to a symbol which has been
1615 // implicitly marked as external.
Kevin Enderby0510b482010-05-17 23:08:19 +00001616 MCSymbol *Sym;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001617 if (LocalLabelVal == -1) {
1618 if (ParsingInlineAsm && SI) {
Nico Weber67e715f2015-06-19 23:43:47 +00001619 StringRef RewrittenLabel =
1620 SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true);
1621 assert(RewrittenLabel.size() &&
1622 "We should have an internal name here.");
Craig Topper7d5b2312015-10-10 05:25:02 +00001623 Info.AsmRewrites->emplace_back(AOK_Label, IDLoc, IDVal.size(),
1624 RewrittenLabel);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001625 IDVal = RewrittenLabel;
1626 }
Jim Grosbach6f482002015-05-18 18:43:14 +00001627 Sym = getContext().getOrCreateSymbol(IDVal);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001628 } else
Jim Grosbach6f482002015-05-18 18:43:14 +00001629 Sym = Ctx.createDirectionalLocalSymbol(LocalLabelVal);
David Majnemer58cb80c2014-12-24 10:27:50 +00001630
1631 Sym->redefineIfPossible();
1632
Daniel Dunbardeb7ba92010-05-05 19:01:00 +00001633 if (!Sym->isUndefined() || Sym->isVariable())
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001634 return Error(IDLoc, "invalid symbol redefinition");
Michael J. Spencer530ce852010-10-09 11:00:50 +00001635
Nirav Dave9263ae32016-08-02 19:17:54 +00001636 // End of Labels should be treated as end of line for lexing
1637 // purposes but that information is not available to the Lexer who
1638 // does not understand Labels. This may cause us to see a Hash
1639 // here instead of a preprocessor line comment.
1640 if (getTok().is(AsmToken::Hash)) {
1641 StringRef CommentStr = parseStringToEndOfStatement();
1642 Lexer.Lex();
1643 Lexer.UnLex(AsmToken(AsmToken::EndOfStatement, CommentStr));
1644 }
1645
Nirav Dave8ea792d2016-07-13 14:03:12 +00001646 // Consume any end of statement token, if present, to avoid spurious
1647 // AddBlankLine calls().
1648 if (getTok().is(AsmToken::EndOfStatement)) {
1649 Lex();
1650 }
1651
Daniel Dunbare73b2672009-08-26 22:13:22 +00001652 // Emit the label.
Chad Rosierf3feab32013-01-07 20:34:12 +00001653 if (!ParsingInlineAsm)
1654 Out.EmitLabel(Sym);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001655
Kevin Enderbye7739d42011-12-09 18:09:40 +00001656 // If we are generating dwarf for assembly source files then gather the
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001657 // info to make a dwarf label entry for this label if needed.
Kevin Enderbye7739d42011-12-09 18:09:40 +00001658 if (getContext().getGenDwarfForAssembly())
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001659 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1660 IDLoc);
Kevin Enderbye7739d42011-12-09 18:09:40 +00001661
Tim Northover1744d0a2013-10-25 12:49:50 +00001662 getTargetParser().onLabelParsed(Sym);
1663
Eli Friedman0f4871d2012-10-22 23:58:19 +00001664 return false;
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001665 }
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001666
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001667 case AsmToken::Equal:
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001668 if (!getTargetParser().equalIsAsmAssignment())
1669 break;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001670 // identifier '=' ... -> assignment statement
Sean Callanan686ed8d2010-01-19 20:22:31 +00001671 Lex();
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001672
Jim Grosbach4b905842013-09-20 23:08:21 +00001673 return parseAssignment(IDVal, true);
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001674
1675 default: // Normal instruction or directive.
1676 break;
Chris Lattner36e02122009-06-21 20:54:55 +00001677 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001678
1679 // If macros are enabled, check to see if this is a macro instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00001680 if (areMacrosEnabled())
1681 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1682 return handleMacroEntry(M, IDLoc);
Eli Bendersky38274122013-01-14 23:22:36 +00001683 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001684
Michael J. Spencer530ce852010-10-09 11:00:50 +00001685 // Otherwise, we have a normal instruction or directive.
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001686
Eli Bendersky17233942013-01-15 22:59:42 +00001687 // Directives start with "."
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001688 if (IDVal[0] == '.' && IDVal != ".") {
Eli Bendersky17233942013-01-15 22:59:42 +00001689 // There are several entities interested in parsing directives:
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001690 //
Eli Bendersky17233942013-01-15 22:59:42 +00001691 // 1. The target-specific assembly parser. Some directives are target
1692 // specific or may potentially behave differently on certain targets.
1693 // 2. Asm parser extensions. For example, platform-specific parsers
1694 // (like the ELF parser) register themselves as extensions.
1695 // 3. The generic directive parser implemented by this class. These are
1696 // all the directives that behave in a target and platform independent
1697 // manner, or at least have a default behavior that's shared between
1698 // all targets and platforms.
Akira Hatanakad3590752012-07-05 19:09:33 +00001699
Oliver Stannard21718282016-07-26 14:19:47 +00001700 getTargetParser().flushPendingInstructions(getStreamer());
1701
Nirav Dave2364748a2016-09-16 18:30:20 +00001702 SMLoc StartTokLoc = getTok().getLoc();
1703 bool TPDirectiveReturn = getTargetParser().ParseDirective(ID);
1704
1705 if (hasPendingError())
1706 return true;
1707 // Currently the return value should be true if we are
1708 // uninterested but as this is at odds with the standard parsing
1709 // convention (return true = error) we have instances of a parsed
1710 // directive that fails returning true as an error. Catch these
1711 // cases as best as possible errors here.
1712 if (TPDirectiveReturn && StartTokLoc != getTok().getLoc())
1713 return true;
1714 // Return if we did some parsing or believe we succeeded.
1715 if (!TPDirectiveReturn || StartTokLoc != getTok().getLoc())
Akira Hatanakad3590752012-07-05 19:09:33 +00001716 return false;
1717
Alp Tokercb402912014-01-24 17:20:08 +00001718 // Next, check the extension directive map to see if any extension has
Eli Bendersky17233942013-01-15 22:59:42 +00001719 // registered itself to parse this directive.
Jim Grosbach4b905842013-09-20 23:08:21 +00001720 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1721 ExtensionDirectiveMap.lookup(IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +00001722 if (Handler.first)
1723 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1724
1725 // Finally, if no one else is interested in this directive, it must be
1726 // generic and familiar to this class.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001727 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001728 default:
1729 break;
1730 case DK_SET:
1731 case DK_EQU:
1732 return parseDirectiveSet(IDVal, true);
1733 case DK_EQUIV:
1734 return parseDirectiveSet(IDVal, false);
1735 case DK_ASCII:
1736 return parseDirectiveAscii(IDVal, false);
1737 case DK_ASCIZ:
1738 case DK_STRING:
1739 return parseDirectiveAscii(IDVal, true);
1740 case DK_BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001741 case DK_DC_B:
1742 return parseDirectiveValue(IDVal, 1);
1743 case DK_DC:
1744 case DK_DC_W:
Jim Grosbach4b905842013-09-20 23:08:21 +00001745 case DK_SHORT:
1746 case DK_VALUE:
1747 case DK_2BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001748 return parseDirectiveValue(IDVal, 2);
Jim Grosbach4b905842013-09-20 23:08:21 +00001749 case DK_LONG:
1750 case DK_INT:
1751 case DK_4BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001752 case DK_DC_L:
1753 return parseDirectiveValue(IDVal, 4);
Jim Grosbach4b905842013-09-20 23:08:21 +00001754 case DK_QUAD:
1755 case DK_8BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001756 return parseDirectiveValue(IDVal, 8);
1757 case DK_DC_A:
1758 return parseDirectiveValue(IDVal,
1759 getContext().getAsmInfo()->getPointerSize());
David Woodhoused6de0d92014-02-01 16:20:59 +00001760 case DK_OCTA:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001761 return parseDirectiveOctaValue(IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001762 case DK_SINGLE:
1763 case DK_FLOAT:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001764 case DK_DC_S:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001765 return parseDirectiveRealValue(IDVal, APFloat::IEEEsingle());
Jim Grosbach4b905842013-09-20 23:08:21 +00001766 case DK_DOUBLE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001767 case DK_DC_D:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001768 return parseDirectiveRealValue(IDVal, APFloat::IEEEdouble());
Jim Grosbach4b905842013-09-20 23:08:21 +00001769 case DK_ALIGN: {
1770 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1771 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1772 }
1773 case DK_ALIGN32: {
1774 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1775 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1776 }
1777 case DK_BALIGN:
1778 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1779 case DK_BALIGNW:
1780 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1781 case DK_BALIGNL:
1782 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1783 case DK_P2ALIGN:
1784 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1785 case DK_P2ALIGNW:
1786 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1787 case DK_P2ALIGNL:
1788 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1789 case DK_ORG:
1790 return parseDirectiveOrg();
1791 case DK_FILL:
1792 return parseDirectiveFill();
1793 case DK_ZERO:
1794 return parseDirectiveZero();
1795 case DK_EXTERN:
1796 eatToEndOfStatement(); // .extern is the default, ignore it.
1797 return false;
1798 case DK_GLOBL:
1799 case DK_GLOBAL:
1800 return parseDirectiveSymbolAttribute(MCSA_Global);
1801 case DK_LAZY_REFERENCE:
1802 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1803 case DK_NO_DEAD_STRIP:
1804 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1805 case DK_SYMBOL_RESOLVER:
1806 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1807 case DK_PRIVATE_EXTERN:
1808 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1809 case DK_REFERENCE:
1810 return parseDirectiveSymbolAttribute(MCSA_Reference);
1811 case DK_WEAK_DEFINITION:
1812 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1813 case DK_WEAK_REFERENCE:
1814 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1815 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1816 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1817 case DK_COMM:
1818 case DK_COMMON:
1819 return parseDirectiveComm(/*IsLocal=*/false);
1820 case DK_LCOMM:
1821 return parseDirectiveComm(/*IsLocal=*/true);
1822 case DK_ABORT:
1823 return parseDirectiveAbort();
1824 case DK_INCLUDE:
1825 return parseDirectiveInclude();
1826 case DK_INCBIN:
1827 return parseDirectiveIncbin();
1828 case DK_CODE16:
1829 case DK_CODE16GCC:
Nirav Davefd910412016-06-17 16:06:17 +00001830 return TokError(Twine(IDVal) +
1831 " not currently supported for this target");
Jim Grosbach4b905842013-09-20 23:08:21 +00001832 case DK_REPT:
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00001833 return parseDirectiveRept(IDLoc, IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001834 case DK_IRP:
1835 return parseDirectiveIrp(IDLoc);
1836 case DK_IRPC:
1837 return parseDirectiveIrpc(IDLoc);
1838 case DK_ENDR:
1839 return parseDirectiveEndr(IDLoc);
1840 case DK_BUNDLE_ALIGN_MODE:
1841 return parseDirectiveBundleAlignMode();
1842 case DK_BUNDLE_LOCK:
1843 return parseDirectiveBundleLock();
1844 case DK_BUNDLE_UNLOCK:
1845 return parseDirectiveBundleUnlock();
1846 case DK_SLEB128:
1847 return parseDirectiveLEB128(true);
1848 case DK_ULEB128:
1849 return parseDirectiveLEB128(false);
1850 case DK_SPACE:
1851 case DK_SKIP:
1852 return parseDirectiveSpace(IDVal);
1853 case DK_FILE:
1854 return parseDirectiveFile(IDLoc);
1855 case DK_LINE:
1856 return parseDirectiveLine();
1857 case DK_LOC:
1858 return parseDirectiveLoc();
1859 case DK_STABS:
1860 return parseDirectiveStabs();
Reid Kleckner2214ed82016-01-29 00:49:42 +00001861 case DK_CV_FILE:
1862 return parseDirectiveCVFile();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00001863 case DK_CV_FUNC_ID:
1864 return parseDirectiveCVFuncId();
1865 case DK_CV_INLINE_SITE_ID:
1866 return parseDirectiveCVInlineSiteId();
Reid Kleckner2214ed82016-01-29 00:49:42 +00001867 case DK_CV_LOC:
1868 return parseDirectiveCVLoc();
1869 case DK_CV_LINETABLE:
1870 return parseDirectiveCVLinetable();
David Majnemer6fcbd7e2016-01-29 19:24:12 +00001871 case DK_CV_INLINE_LINETABLE:
1872 return parseDirectiveCVInlineLinetable();
David Majnemer408b5e62016-02-05 01:55:49 +00001873 case DK_CV_DEF_RANGE:
1874 return parseDirectiveCVDefRange();
Reid Kleckner2214ed82016-01-29 00:49:42 +00001875 case DK_CV_STRINGTABLE:
1876 return parseDirectiveCVStringTable();
1877 case DK_CV_FILECHECKSUMS:
1878 return parseDirectiveCVFileChecksums();
Jim Grosbach4b905842013-09-20 23:08:21 +00001879 case DK_CFI_SECTIONS:
1880 return parseDirectiveCFISections();
1881 case DK_CFI_STARTPROC:
1882 return parseDirectiveCFIStartProc();
1883 case DK_CFI_ENDPROC:
1884 return parseDirectiveCFIEndProc();
1885 case DK_CFI_DEF_CFA:
1886 return parseDirectiveCFIDefCfa(IDLoc);
1887 case DK_CFI_DEF_CFA_OFFSET:
1888 return parseDirectiveCFIDefCfaOffset();
1889 case DK_CFI_ADJUST_CFA_OFFSET:
1890 return parseDirectiveCFIAdjustCfaOffset();
1891 case DK_CFI_DEF_CFA_REGISTER:
1892 return parseDirectiveCFIDefCfaRegister(IDLoc);
1893 case DK_CFI_OFFSET:
1894 return parseDirectiveCFIOffset(IDLoc);
1895 case DK_CFI_REL_OFFSET:
1896 return parseDirectiveCFIRelOffset(IDLoc);
1897 case DK_CFI_PERSONALITY:
1898 return parseDirectiveCFIPersonalityOrLsda(true);
1899 case DK_CFI_LSDA:
1900 return parseDirectiveCFIPersonalityOrLsda(false);
1901 case DK_CFI_REMEMBER_STATE:
1902 return parseDirectiveCFIRememberState();
1903 case DK_CFI_RESTORE_STATE:
1904 return parseDirectiveCFIRestoreState();
1905 case DK_CFI_SAME_VALUE:
1906 return parseDirectiveCFISameValue(IDLoc);
1907 case DK_CFI_RESTORE:
1908 return parseDirectiveCFIRestore(IDLoc);
1909 case DK_CFI_ESCAPE:
1910 return parseDirectiveCFIEscape();
1911 case DK_CFI_SIGNAL_FRAME:
1912 return parseDirectiveCFISignalFrame();
1913 case DK_CFI_UNDEFINED:
1914 return parseDirectiveCFIUndefined(IDLoc);
1915 case DK_CFI_REGISTER:
1916 return parseDirectiveCFIRegister(IDLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00001917 case DK_CFI_WINDOW_SAVE:
1918 return parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +00001919 case DK_MACROS_ON:
1920 case DK_MACROS_OFF:
1921 return parseDirectiveMacrosOnOff(IDVal);
1922 case DK_MACRO:
1923 return parseDirectiveMacro(IDLoc);
Nico Weber155dccd12014-07-24 17:08:39 +00001924 case DK_EXITM:
1925 return parseDirectiveExitMacro(IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001926 case DK_ENDM:
1927 case DK_ENDMACRO:
1928 return parseDirectiveEndMacro(IDVal);
1929 case DK_PURGEM:
1930 return parseDirectivePurgeMacro(IDLoc);
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00001931 case DK_END:
1932 return parseDirectiveEnd(IDLoc);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00001933 case DK_ERR:
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00001934 return parseDirectiveError(IDLoc, false);
1935 case DK_ERROR:
1936 return parseDirectiveError(IDLoc, true);
Nico Weber404012b2014-07-24 16:26:06 +00001937 case DK_WARNING:
1938 return parseDirectiveWarning(IDLoc);
Daniel Sanders9f6ad492015-11-12 13:33:00 +00001939 case DK_RELOC:
1940 return parseDirectiveReloc(IDLoc);
Petr Hosek4cb08ce2016-09-23 19:25:15 +00001941 case DK_DCB:
1942 case DK_DCB_W:
1943 return parseDirectiveDCB(IDVal, 2);
1944 case DK_DCB_B:
1945 return parseDirectiveDCB(IDVal, 1);
1946 case DK_DCB_D:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001947 return parseDirectiveRealDCB(IDVal, APFloat::IEEEdouble());
Petr Hosek4cb08ce2016-09-23 19:25:15 +00001948 case DK_DCB_L:
1949 return parseDirectiveDCB(IDVal, 4);
1950 case DK_DCB_S:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001951 return parseDirectiveRealDCB(IDVal, APFloat::IEEEsingle());
Petr Hosek731bb9c2016-08-23 21:34:53 +00001952 case DK_DC_X:
Petr Hosek4cb08ce2016-09-23 19:25:15 +00001953 case DK_DCB_X:
Petr Hosek731bb9c2016-08-23 21:34:53 +00001954 return TokError(Twine(IDVal) +
1955 " not currently supported for this target");
Petr Hosek85b2f672016-09-23 21:53:36 +00001956 case DK_DS:
1957 case DK_DS_W:
1958 return parseDirectiveDS(IDVal, 2);
1959 case DK_DS_B:
1960 return parseDirectiveDS(IDVal, 1);
1961 case DK_DS_D:
1962 return parseDirectiveDS(IDVal, 8);
1963 case DK_DS_L:
1964 case DK_DS_S:
1965 return parseDirectiveDS(IDVal, 4);
1966 case DK_DS_P:
1967 case DK_DS_X:
1968 return parseDirectiveDS(IDVal, 12);
Eli Friedman20b02642010-07-19 04:17:25 +00001969 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00001970
Jim Grosbach758e0cc2012-05-01 18:38:27 +00001971 return Error(IDLoc, "unknown directive");
Chris Lattnere5074c42009-06-22 01:29:09 +00001972 }
Chris Lattner36e02122009-06-21 20:54:55 +00001973
Chad Rosierc7f552c2013-02-12 21:33:51 +00001974 // __asm _emit or __asm __emit
1975 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1976 IDVal == "_EMIT" || IDVal == "__EMIT"))
Jim Grosbach4b905842013-09-20 23:08:21 +00001977 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
Chad Rosierc7f552c2013-02-12 21:33:51 +00001978
1979 // __asm align
1980 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
Jim Grosbach4b905842013-09-20 23:08:21 +00001981 return parseDirectiveMSAlign(IDLoc, Info);
Eli Friedman0f4871d2012-10-22 23:58:19 +00001982
Michael Zuckerman02ecd432015-12-13 17:07:23 +00001983 if (ParsingInlineAsm && (IDVal == "even"))
1984 Info.AsmRewrites->emplace_back(AOK_EVEN, IDLoc, 4);
Nirav Davef43cc9f2016-10-10 15:24:54 +00001985 if (checkForValidSection())
1986 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00001987
Chris Lattner7cbfa442010-05-19 23:34:33 +00001988 // Canonicalize the opcode to lower case.
Eli Bendersky88024712013-01-16 19:32:36 +00001989 std::string OpcodeStr = IDVal.lower();
Chad Rosierf0e87202012-10-25 20:41:34 +00001990 ParseInstructionInfo IInfo(Info.AsmRewrites);
Nirav Dave2364748a2016-09-16 18:30:20 +00001991 bool ParseHadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, ID,
1992 Info.ParsedOperands);
1993 Info.ParseError = ParseHadError;
Chris Lattnere5074c42009-06-22 01:29:09 +00001994
Daniel Dunbar2eca0252010-08-11 06:37:09 +00001995 // Dump the parsed representation, if requested.
1996 if (getShowParsedOperands()) {
1997 SmallString<256> Str;
1998 raw_svector_ostream OS(Str);
1999 OS << "parsed instruction: [";
Eli Friedman0f4871d2012-10-22 23:58:19 +00002000 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002001 if (i != 0)
2002 OS << ", ";
Eli Friedman0f4871d2012-10-22 23:58:19 +00002003 Info.ParsedOperands[i]->print(OS);
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002004 }
2005 OS << "]";
2006
Jim Grosbach4b905842013-09-20 23:08:21 +00002007 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002008 }
2009
Nirav Dave2364748a2016-09-16 18:30:20 +00002010 // Fail even if ParseInstruction erroneously returns false.
2011 if (hasPendingError() || ParseHadError)
2012 return true;
2013
Oliver Stannard8b273082014-06-19 15:52:37 +00002014 // If we are generating dwarf for the current section then generate a .loc
2015 // directive for the instruction.
Nirav Dave2364748a2016-09-16 18:30:20 +00002016 if (!ParseHadError && getContext().getGenDwarfForAssembly() &&
Oliver Stannard8b273082014-06-19 15:52:37 +00002017 getContext().getGenDwarfSectionSyms().count(
Eric Christopher445c9522016-10-14 05:47:37 +00002018 getStreamer().getCurrentSectionOnly())) {
Saleem Abdulrasool4d6ed7c2014-12-24 06:32:43 +00002019 unsigned Line;
2020 if (ActiveMacros.empty())
2021 Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
2022 else
Frederic Riss16238d92015-06-25 21:57:33 +00002023 Line = SrcMgr.FindLineNumber(ActiveMacros.front()->InstantiationLoc,
2024 ActiveMacros.front()->ExitBuffer);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002025
Eli Bendersky88024712013-01-16 19:32:36 +00002026 // If we previously parsed a cpp hash file line comment then make sure the
2027 // current Dwarf File is for the CppHashFilename if not then emit the
2028 // Dwarf File table for it and adjust the line number for the .loc.
Tim Northoverc0bef992016-04-13 19:46:54 +00002029 if (CppHashInfo.Filename.size()) {
David Blaikiec714ef42014-03-17 01:52:11 +00002030 unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
Tim Northoverc0bef992016-04-13 19:46:54 +00002031 0, StringRef(), CppHashInfo.Filename);
David Blaikiec714ef42014-03-17 01:52:11 +00002032 getContext().setGenDwarfFileNumber(FileNumber);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002033
Jim Grosbach4b905842013-09-20 23:08:21 +00002034 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
2035 // cache with the different Loc from the call above we save the last
2036 // info we queried here with SrcMgr.FindLineNumber().
2037 unsigned CppHashLocLineNo;
Tim Northoverc0bef992016-04-13 19:46:54 +00002038 if (LastQueryIDLoc == CppHashInfo.Loc &&
2039 LastQueryBuffer == CppHashInfo.Buf)
Jim Grosbach4b905842013-09-20 23:08:21 +00002040 CppHashLocLineNo = LastQueryLine;
2041 else {
Tim Northoverc0bef992016-04-13 19:46:54 +00002042 CppHashLocLineNo =
2043 SrcMgr.FindLineNumber(CppHashInfo.Loc, CppHashInfo.Buf);
Jim Grosbach4b905842013-09-20 23:08:21 +00002044 LastQueryLine = CppHashLocLineNo;
Tim Northoverc0bef992016-04-13 19:46:54 +00002045 LastQueryIDLoc = CppHashInfo.Loc;
2046 LastQueryBuffer = CppHashInfo.Buf;
Jim Grosbach4b905842013-09-20 23:08:21 +00002047 }
Tim Northoverc0bef992016-04-13 19:46:54 +00002048 Line = CppHashInfo.LineNumber - 1 + (Line - CppHashLocLineNo);
Eli Bendersky88024712013-01-16 19:32:36 +00002049 }
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002050
Jim Grosbach4b905842013-09-20 23:08:21 +00002051 getStreamer().EmitDwarfLocDirective(
2052 getContext().getGenDwarfFileNumber(), Line, 0,
2053 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
2054 StringRef());
Kevin Enderby6469fc22011-11-01 22:27:22 +00002055 }
2056
Daniel Dunbarce0c1e12010-05-04 00:33:07 +00002057 // If parsing succeeded, match the instruction.
Nirav Dave2364748a2016-09-16 18:30:20 +00002058 if (!ParseHadError) {
Tim Northover26bb14e2014-08-18 11:49:42 +00002059 uint64_t ErrorInfo;
Nirav Dave2364748a2016-09-16 18:30:20 +00002060 if (getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
2061 Info.ParsedOperands, Out,
2062 ErrorInfo, ParsingInlineAsm))
2063 return true;
Chad Rosier49963552012-10-13 00:26:04 +00002064 }
Chris Lattnera2a9d162010-09-11 16:18:25 +00002065 return false;
Chris Lattnerb0133452009-06-21 20:16:42 +00002066}
Chris Lattnerbedf6c22009-06-24 04:43:34 +00002067
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00002068// Parse and erase curly braces marking block start/end
2069bool
2070AsmParser::parseCurlyBlockScope(SmallVectorImpl<AsmRewrite> &AsmStrRewrites) {
2071 // Identify curly brace marking block start/end
2072 if (Lexer.isNot(AsmToken::LCurly) && Lexer.isNot(AsmToken::RCurly))
2073 return false;
2074
2075 SMLoc StartLoc = Lexer.getLoc();
2076 Lex(); // Eat the brace
2077 if (Lexer.is(AsmToken::EndOfStatement))
2078 Lex(); // Eat EndOfStatement following the brace
2079
2080 // Erase the block start/end brace from the output asm string
2081 AsmStrRewrites.emplace_back(AOK_Skip, StartLoc, Lexer.getLoc().getPointer() -
2082 StartLoc.getPointer());
2083 return true;
2084}
2085
Jim Grosbach4b905842013-09-20 23:08:21 +00002086/// parseCppHashLineFilenameComment as this:
Kevin Enderby72553612011-09-13 23:45:18 +00002087/// ::= # number "filename"
Craig Topper3c76c522015-09-20 23:35:59 +00002088bool AsmParser::parseCppHashLineFilenameComment(SMLoc L) {
Kevin Enderby72553612011-09-13 23:45:18 +00002089 Lex(); // Eat the hash token.
Nirav Davefd910412016-06-17 16:06:17 +00002090 // Lexer only ever emits HashDirective if it fully formed if it's
2091 // done the checking already so this is an internal error.
2092 assert(getTok().is(AsmToken::Integer) &&
2093 "Lexing Cpp line comment: Expected Integer");
Kevin Enderby72553612011-09-13 23:45:18 +00002094 int64_t LineNumber = getTok().getIntVal();
Kevin Enderby72553612011-09-13 23:45:18 +00002095 Lex();
Nirav Davefd910412016-06-17 16:06:17 +00002096 assert(getTok().is(AsmToken::String) &&
2097 "Lexing Cpp line comment: Expected String");
Kevin Enderby72553612011-09-13 23:45:18 +00002098 StringRef Filename = getTok().getString();
Nirav Davefd910412016-06-17 16:06:17 +00002099 Lex();
Nirav Dave2364748a2016-09-16 18:30:20 +00002100
Kevin Enderby72553612011-09-13 23:45:18 +00002101 // Get rid of the enclosing quotes.
Jim Grosbach4b905842013-09-20 23:08:21 +00002102 Filename = Filename.substr(1, Filename.size() - 2);
Kevin Enderby72553612011-09-13 23:45:18 +00002103
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002104 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
Tim Northoverc0bef992016-04-13 19:46:54 +00002105 CppHashInfo.Loc = L;
2106 CppHashInfo.Filename = Filename;
2107 CppHashInfo.LineNumber = LineNumber;
2108 CppHashInfo.Buf = CurBuffer;
Kevin Enderby72553612011-09-13 23:45:18 +00002109 return false;
2110}
2111
Jim Grosbach4b905842013-09-20 23:08:21 +00002112/// \brief will use the last parsed cpp hash line filename comment
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002113/// for the Filename and LineNo if any in the diagnostic.
2114void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002115 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002116 raw_ostream &OS = errs();
2117
2118 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
Craig Topper3c76c522015-09-20 23:35:59 +00002119 SMLoc DiagLoc = Diag.getLoc();
Alp Tokera55b95b2014-07-06 10:33:31 +00002120 unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2121 unsigned CppHashBuf =
Tim Northoverc0bef992016-04-13 19:46:54 +00002122 Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashInfo.Loc);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002123
Jim Grosbach4b905842013-09-20 23:08:21 +00002124 // Like SourceMgr::printMessage() we need to print the include stack if any
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002125 // before printing the message.
Alp Tokera55b95b2014-07-06 10:33:31 +00002126 unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2127 if (!Parser->SavedDiagHandler && DiagCurBuffer &&
2128 DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002129 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
2130 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002131 }
2132
Eric Christophera7c32732012-12-18 00:30:54 +00002133 // If we have not parsed a cpp hash line filename comment or the source
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002134 // manager changed or buffer changed (like in a nested include) then just
2135 // print the normal diagnostic using its Filename and LineNo.
Tim Northoverc0bef992016-04-13 19:46:54 +00002136 if (!Parser->CppHashInfo.LineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002137 DiagBuf != CppHashBuf) {
Benjamin Kramer47f5e302011-10-16 10:48:29 +00002138 if (Parser->SavedDiagHandler)
2139 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
2140 else
Craig Topper353eda42014-04-24 06:44:33 +00002141 Diag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002142 return;
2143 }
2144
Eric Christophera7c32732012-12-18 00:30:54 +00002145 // Use the CppHashFilename and calculate a line number based on the
Tim Northoverc0bef992016-04-13 19:46:54 +00002146 // CppHashInfo.Loc and CppHashInfo.LineNumber relative to this Diag's SMLoc
2147 // for the diagnostic.
2148 const std::string &Filename = Parser->CppHashInfo.Filename;
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002149
2150 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
2151 int CppHashLocLineNo =
Tim Northoverc0bef992016-04-13 19:46:54 +00002152 Parser->SrcMgr.FindLineNumber(Parser->CppHashInfo.Loc, CppHashBuf);
Jim Grosbach4b905842013-09-20 23:08:21 +00002153 int LineNo =
Tim Northoverc0bef992016-04-13 19:46:54 +00002154 Parser->CppHashInfo.LineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002155
Jim Grosbach4b905842013-09-20 23:08:21 +00002156 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
2157 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
Chris Lattner72845262011-10-16 05:47:55 +00002158 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002159
Benjamin Kramer47f5e302011-10-16 10:48:29 +00002160 if (Parser->SavedDiagHandler)
2161 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
2162 else
Craig Topper353eda42014-04-24 06:44:33 +00002163 NewDiag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002164}
2165
Rafael Espindola2c064482012-08-21 18:29:30 +00002166// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
2167// difference being that that function accepts '@' as part of identifiers and
2168// we can't do that. AsmLexer.cpp should probably be changed to handle
2169// '@' as a special case when needed.
2170static bool isIdentifierChar(char c) {
Guy Benyei83c74e92013-02-12 21:21:59 +00002171 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
2172 c == '.';
Rafael Espindola2c064482012-08-21 18:29:30 +00002173}
2174
Rafael Espindola34b9c512012-06-03 23:57:14 +00002175bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00002176 ArrayRef<MCAsmMacroParameter> Parameters,
Toma Tabacu217116e2015-04-27 10:50:29 +00002177 ArrayRef<MCAsmMacroArgument> A,
Craig Topper3c76c522015-09-20 23:35:59 +00002178 bool EnableAtPseudoVariable, SMLoc L) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00002179 unsigned NParameters = Parameters.size();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002180 bool HasVararg = NParameters ? Parameters.back().Vararg : false;
Benjamin Kramer513e7442014-02-20 13:36:32 +00002181 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
Rafael Espindola1134ab232011-06-05 02:43:45 +00002182 return Error(L, "Wrong number of arguments");
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002183
Preston Gurd05500642012-09-19 20:36:12 +00002184 // A macro without parameters is handled differently on Darwin:
2185 // gas accepts no arguments and does no substitutions
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002186 while (!Body.empty()) {
2187 // Scan for the next substitution.
2188 std::size_t End = Body.size(), Pos = 0;
2189 for (; Pos != End; ++Pos) {
2190 // Check for a substitution or escape.
Benjamin Kramer513e7442014-02-20 13:36:32 +00002191 if (IsDarwin && !NParameters) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00002192 // This macro has no parameters, look for $0, $1, etc.
2193 if (Body[Pos] != '$' || Pos + 1 == End)
2194 continue;
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002195
Rafael Espindola1134ab232011-06-05 02:43:45 +00002196 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00002197 if (Next == '$' || Next == 'n' ||
2198 isdigit(static_cast<unsigned char>(Next)))
Rafael Espindola1134ab232011-06-05 02:43:45 +00002199 break;
2200 } else {
2201 // This macro has parameters, look for \foo, \bar, etc.
2202 if (Body[Pos] == '\\' && Pos + 1 != End)
2203 break;
2204 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002205 }
2206
2207 // Add the prefix.
2208 OS << Body.slice(0, Pos);
2209
2210 // Check if we reached the end.
2211 if (Pos == End)
2212 break;
2213
Benjamin Kramer513e7442014-02-20 13:36:32 +00002214 if (IsDarwin && !NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002215 switch (Body[Pos + 1]) {
2216 // $$ => $
Rafael Espindola1134ab232011-06-05 02:43:45 +00002217 case '$':
2218 OS << '$';
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002219 break;
2220
Jim Grosbach4b905842013-09-20 23:08:21 +00002221 // $n => number of arguments
Rafael Espindola1134ab232011-06-05 02:43:45 +00002222 case 'n':
2223 OS << A.size();
2224 break;
2225
Jim Grosbach4b905842013-09-20 23:08:21 +00002226 // $[0-9] => argument
Rafael Espindola1134ab232011-06-05 02:43:45 +00002227 default: {
2228 // Missing arguments are ignored.
Jim Grosbach4b905842013-09-20 23:08:21 +00002229 unsigned Index = Body[Pos + 1] - '0';
Rafael Espindola1134ab232011-06-05 02:43:45 +00002230 if (Index >= A.size())
2231 break;
2232
2233 // Otherwise substitute with the token values, with spaces eliminated.
Craig Topper84008482015-10-10 05:38:14 +00002234 for (const AsmToken &Token : A[Index])
2235 OS << Token.getString();
Rafael Espindola1134ab232011-06-05 02:43:45 +00002236 break;
2237 }
2238 }
2239 Pos += 2;
2240 } else {
2241 unsigned I = Pos + 1;
Toma Tabacu217116e2015-04-27 10:50:29 +00002242
2243 // Check for the \@ pseudo-variable.
2244 if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End)
Rafael Espindola1134ab232011-06-05 02:43:45 +00002245 ++I;
Toma Tabacu217116e2015-04-27 10:50:29 +00002246 else
2247 while (isIdentifierChar(Body[I]) && I + 1 != End)
2248 ++I;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002249
Jim Grosbach4b905842013-09-20 23:08:21 +00002250 const char *Begin = Body.data() + Pos + 1;
2251 StringRef Argument(Begin, I - (Pos + 1));
Rafael Espindola1134ab232011-06-05 02:43:45 +00002252 unsigned Index = 0;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002253
Toma Tabacu217116e2015-04-27 10:50:29 +00002254 if (Argument == "@") {
2255 OS << NumOfMacroInstantiations;
2256 Pos += 2;
Preston Gurd05500642012-09-19 20:36:12 +00002257 } else {
Toma Tabacu217116e2015-04-27 10:50:29 +00002258 for (; Index < NParameters; ++Index)
2259 if (Parameters[Index].Name == Argument)
2260 break;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002261
Toma Tabacu217116e2015-04-27 10:50:29 +00002262 if (Index == NParameters) {
2263 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
2264 Pos += 3;
2265 else {
2266 OS << '\\' << Argument;
2267 Pos = I;
2268 }
2269 } else {
2270 bool VarargParameter = HasVararg && Index == (NParameters - 1);
Craig Topper84008482015-10-10 05:38:14 +00002271 for (const AsmToken &Token : A[Index])
Toma Tabacu217116e2015-04-27 10:50:29 +00002272 // We expect no quotes around the string's contents when
2273 // parsing for varargs.
Craig Topper84008482015-10-10 05:38:14 +00002274 if (Token.getKind() != AsmToken::String || VarargParameter)
2275 OS << Token.getString();
Toma Tabacu217116e2015-04-27 10:50:29 +00002276 else
Craig Topper84008482015-10-10 05:38:14 +00002277 OS << Token.getStringContents();
Toma Tabacu217116e2015-04-27 10:50:29 +00002278
2279 Pos += 1 + Argument.size();
2280 }
Preston Gurd05500642012-09-19 20:36:12 +00002281 }
Rafael Espindola1134ab232011-06-05 02:43:45 +00002282 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002283 // Update the scan point.
Rafael Espindola1134ab232011-06-05 02:43:45 +00002284 Body = Body.substr(Pos);
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002285 }
Daniel Dunbar43235712010-07-18 18:54:11 +00002286
Rafael Espindola1134ab232011-06-05 02:43:45 +00002287 return false;
2288}
Daniel Dunbar43235712010-07-18 18:54:11 +00002289
Nico Weber2a8f9222014-07-24 16:29:04 +00002290MacroInstantiation::MacroInstantiation(SMLoc IL, int EB, SMLoc EL,
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002291 size_t CondStackDepth)
Rafael Espindolaf43a94e2014-08-17 22:48:55 +00002292 : InstantiationLoc(IL), ExitBuffer(EB), ExitLoc(EL),
Nico Weber155dccd12014-07-24 17:08:39 +00002293 CondStackDepth(CondStackDepth) {}
Daniel Dunbar43235712010-07-18 18:54:11 +00002294
Jim Grosbach4b905842013-09-20 23:08:21 +00002295static bool isOperator(AsmToken::TokenKind kind) {
2296 switch (kind) {
2297 default:
2298 return false;
2299 case AsmToken::Plus:
2300 case AsmToken::Minus:
2301 case AsmToken::Tilde:
2302 case AsmToken::Slash:
2303 case AsmToken::Star:
2304 case AsmToken::Dot:
2305 case AsmToken::Equal:
2306 case AsmToken::EqualEqual:
2307 case AsmToken::Pipe:
2308 case AsmToken::PipePipe:
2309 case AsmToken::Caret:
2310 case AsmToken::Amp:
2311 case AsmToken::AmpAmp:
2312 case AsmToken::Exclaim:
2313 case AsmToken::ExclaimEqual:
Jim Grosbach4b905842013-09-20 23:08:21 +00002314 case AsmToken::Less:
2315 case AsmToken::LessEqual:
2316 case AsmToken::LessLess:
2317 case AsmToken::LessGreater:
2318 case AsmToken::Greater:
2319 case AsmToken::GreaterEqual:
2320 case AsmToken::GreaterGreater:
2321 return true;
Preston Gurd05500642012-09-19 20:36:12 +00002322 }
2323}
2324
David Majnemer16252452014-01-29 00:07:39 +00002325namespace {
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002326
David Majnemer16252452014-01-29 00:07:39 +00002327class AsmLexerSkipSpaceRAII {
2328public:
2329 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
2330 Lexer.setSkipSpace(SkipSpace);
2331 }
2332
2333 ~AsmLexerSkipSpaceRAII() {
2334 Lexer.setSkipSpace(true);
2335 }
2336
2337private:
2338 AsmLexer &Lexer;
2339};
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002340
2341} // end anonymous namespace
David Majnemer16252452014-01-29 00:07:39 +00002342
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002343bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
2344
2345 if (Vararg) {
2346 if (Lexer.isNot(AsmToken::EndOfStatement)) {
2347 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002348 MA.emplace_back(AsmToken::String, Str);
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002349 }
2350 return false;
2351 }
2352
Rafael Espindola768b41c2012-06-15 14:02:34 +00002353 unsigned ParenLevel = 0;
Preston Gurd05500642012-09-19 20:36:12 +00002354
David Majnemer16252452014-01-29 00:07:39 +00002355 // Darwin doesn't use spaces to delmit arguments.
2356 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
Rafael Espindola768b41c2012-06-15 14:02:34 +00002357
Scott Egertona1fa68a2016-02-11 13:48:49 +00002358 bool SpaceEaten;
2359
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002360 while (true) {
Scott Egertona1fa68a2016-02-11 13:48:49 +00002361 SpaceEaten = false;
David Majnemer16252452014-01-29 00:07:39 +00002362 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002363 return TokError("unexpected token in macro instantiation");
Preston Gurd05500642012-09-19 20:36:12 +00002364
Scott Egertona1fa68a2016-02-11 13:48:49 +00002365 if (ParenLevel == 0) {
Preston Gurd05500642012-09-19 20:36:12 +00002366
Scott Egertona1fa68a2016-02-11 13:48:49 +00002367 if (Lexer.is(AsmToken::Comma))
2368 break;
2369
2370 if (Lexer.is(AsmToken::Space)) {
2371 SpaceEaten = true;
Nirav Dave1180e6892016-06-02 17:15:05 +00002372 Lexer.Lex(); // Eat spaces
Scott Egertona1fa68a2016-02-11 13:48:49 +00002373 }
Preston Gurd05500642012-09-19 20:36:12 +00002374
2375 // Spaces can delimit parameters, but could also be part an expression.
2376 // If the token after a space is an operator, add the token and the next
2377 // one into this argument
David Majnemer91fc4c22014-01-29 18:57:46 +00002378 if (!IsDarwin) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002379 if (isOperator(Lexer.getKind())) {
Scott Egertona1fa68a2016-02-11 13:48:49 +00002380 MA.push_back(getTok());
Nirav Dave1180e6892016-06-02 17:15:05 +00002381 Lexer.Lex();
Preston Gurd05500642012-09-19 20:36:12 +00002382
Scott Egertona1fa68a2016-02-11 13:48:49 +00002383 // Whitespace after an operator can be ignored.
2384 if (Lexer.is(AsmToken::Space))
Nirav Dave1180e6892016-06-02 17:15:05 +00002385 Lexer.Lex();
Scott Egertona1fa68a2016-02-11 13:48:49 +00002386
2387 continue;
Preston Gurd05500642012-09-19 20:36:12 +00002388 }
2389 }
Scott Egertona1fa68a2016-02-11 13:48:49 +00002390 if (SpaceEaten)
2391 break;
Preston Gurd05500642012-09-19 20:36:12 +00002392 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002393
Jim Grosbach4b905842013-09-20 23:08:21 +00002394 // handleMacroEntry relies on not advancing the lexer here
Rafael Espindola768b41c2012-06-15 14:02:34 +00002395 // to be able to fill in the remaining default parameter values
2396 if (Lexer.is(AsmToken::EndOfStatement))
2397 break;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002398
2399 // Adjust the current parentheses level.
2400 if (Lexer.is(AsmToken::LParen))
2401 ++ParenLevel;
2402 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
2403 --ParenLevel;
2404
2405 // Append the token to the current argument list.
2406 MA.push_back(getTok());
Nirav Dave1180e6892016-06-02 17:15:05 +00002407 Lexer.Lex();
Rafael Espindola768b41c2012-06-15 14:02:34 +00002408 }
Preston Gurd05500642012-09-19 20:36:12 +00002409
Rafael Espindola768b41c2012-06-15 14:02:34 +00002410 if (ParenLevel != 0)
Rafael Espindola3e5eb422012-08-21 15:55:04 +00002411 return TokError("unbalanced parentheses in macro argument");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002412 return false;
2413}
2414
2415// Parse the macro instantiation arguments.
Jim Grosbach4b905842013-09-20 23:08:21 +00002416bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
Vladimir Medic9bad0d332013-08-20 13:33:18 +00002417 MCAsmMacroArguments &A) {
Rafael Espindola768b41c2012-06-15 14:02:34 +00002418 const unsigned NParameters = M ? M->Parameters.size() : 0;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002419 bool NamedParametersFound = false;
2420 SmallVector<SMLoc, 4> FALocs;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002421
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002422 A.resize(NParameters);
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002423 FALocs.resize(NParameters);
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002424
Rafael Espindola768b41c2012-06-15 14:02:34 +00002425 // Parse two kinds of macro invocations:
2426 // - macros defined without any parameters accept an arbitrary number of them
2427 // - macros defined with parameters accept at most that many of them
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002428 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002429 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
2430 ++Parameter) {
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002431 SMLoc IDLoc = Lexer.getLoc();
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002432 MCAsmMacroParameter FA;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002433
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002434 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00002435 if (parseIdentifier(FA.Name))
2436 return Error(IDLoc, "invalid argument identifier for formal argument");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002437
Nirav Dave2364748a2016-09-16 18:30:20 +00002438 if (Lexer.isNot(AsmToken::Equal))
2439 return TokError("expected '=' after formal parameter identifier");
2440
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002441 Lex();
2442
2443 NamedParametersFound = true;
2444 }
2445
Nirav Dave2364748a2016-09-16 18:30:20 +00002446 if (NamedParametersFound && FA.Name.empty())
2447 return Error(IDLoc, "cannot mix positional and keyword arguments");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002448
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002449 bool Vararg = HasVararg && Parameter == (NParameters - 1);
2450 if (parseMacroArgument(FA.Value, Vararg))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002451 return true;
2452
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002453 unsigned PI = Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002454 if (!FA.Name.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002455 unsigned FAI = 0;
2456 for (FAI = 0; FAI < NParameters; ++FAI)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002457 if (M->Parameters[FAI].Name == FA.Name)
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002458 break;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002459
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002460 if (FAI >= NParameters) {
Nirav Davefd910412016-06-17 16:06:17 +00002461 assert(M && "expected macro to be defined");
Nirav Dave2364748a2016-09-16 18:30:20 +00002462 return Error(IDLoc, "parameter named '" + FA.Name +
2463 "' does not exist for macro '" + M->Name + "'");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002464 }
2465 PI = FAI;
2466 }
2467
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002468 if (!FA.Value.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002469 if (A.size() <= PI)
2470 A.resize(PI + 1);
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002471 A[PI] = FA.Value;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002472
2473 if (FALocs.size() <= PI)
2474 FALocs.resize(PI + 1);
2475
2476 FALocs[PI] = Lexer.getLoc();
Preston Gurd242ed3152012-09-19 20:29:04 +00002477 }
Jim Grosbach206661622012-07-30 22:44:17 +00002478
Preston Gurd242ed3152012-09-19 20:29:04 +00002479 // At the end of the statement, fill in remaining arguments that have
2480 // default values. If there aren't any, then the next argument is
2481 // required but missing
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002482 if (Lexer.is(AsmToken::EndOfStatement)) {
2483 bool Failure = false;
2484 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2485 if (A[FAI].empty()) {
2486 if (M->Parameters[FAI].Required) {
2487 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2488 "missing value for required parameter "
2489 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2490 Failure = true;
2491 }
2492
2493 if (!M->Parameters[FAI].Value.empty())
2494 A[FAI] = M->Parameters[FAI].Value;
2495 }
2496 }
2497 return Failure;
2498 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002499
2500 if (Lexer.is(AsmToken::Comma))
2501 Lex();
2502 }
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002503
2504 return TokError("too many positional arguments");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002505}
2506
Jim Grosbach4b905842013-09-20 23:08:21 +00002507const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002508 StringMap<MCAsmMacro>::iterator I = MacroMap.find(Name);
2509 return (I == MacroMap.end()) ? nullptr : &I->getValue();
Eli Bendersky38274122013-01-14 23:22:36 +00002510}
2511
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002512void AsmParser::defineMacro(StringRef Name, MCAsmMacro Macro) {
2513 MacroMap.insert(std::make_pair(Name, std::move(Macro)));
Eli Bendersky38274122013-01-14 23:22:36 +00002514}
2515
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002516void AsmParser::undefineMacro(StringRef Name) { MacroMap.erase(Name); }
Eli Bendersky38274122013-01-14 23:22:36 +00002517
Jim Grosbach4b905842013-09-20 23:08:21 +00002518bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
Davide Italiano7c9fc732016-07-27 05:51:56 +00002519 // Arbitrarily limit macro nesting depth (default matches 'as'). We can
2520 // eliminate this, although we should protect against infinite loops.
2521 unsigned MaxNestingDepth = AsmMacroMaxNestingDepth;
2522 if (ActiveMacros.size() == MaxNestingDepth) {
2523 std::ostringstream MaxNestingDepthError;
2524 MaxNestingDepthError << "macros cannot be nested more than "
2525 << MaxNestingDepth << " levels deep."
2526 << " Use -asm-macro-max-nesting-depth to increase "
2527 "this limit.";
2528 return TokError(MaxNestingDepthError.str());
2529 }
Daniel Dunbar43235712010-07-18 18:54:11 +00002530
Eli Bendersky38274122013-01-14 23:22:36 +00002531 MCAsmMacroArguments A;
Jim Grosbach4b905842013-09-20 23:08:21 +00002532 if (parseMacroArguments(M, A))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002533 return true;
Daniel Dunbar43235712010-07-18 18:54:11 +00002534
Rafael Espindola1134ab232011-06-05 02:43:45 +00002535 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2536 // to hold the macro body with substitutions.
2537 SmallString<256> Buf;
2538 StringRef Body = M->Body;
Rafael Espindola34b9c512012-06-03 23:57:14 +00002539 raw_svector_ostream OS(Buf);
Rafael Espindola1134ab232011-06-05 02:43:45 +00002540
Toma Tabacu217116e2015-04-27 10:50:29 +00002541 if (expandMacro(OS, Body, M->Parameters, A, true, getTok().getLoc()))
Rafael Espindola1134ab232011-06-05 02:43:45 +00002542 return true;
2543
Eli Bendersky38274122013-01-14 23:22:36 +00002544 // We include the .endmacro in the buffer as our cue to exit the macro
Rafael Espindola34b9c512012-06-03 23:57:14 +00002545 // instantiation.
2546 OS << ".endmacro\n";
2547
Rafael Espindola3560ff22014-08-27 20:03:13 +00002548 std::unique_ptr<MemoryBuffer> Instantiation =
2549 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola1134ab232011-06-05 02:43:45 +00002550
Daniel Dunbar43235712010-07-18 18:54:11 +00002551 // Create the macro instantiation object and add to the current macro
2552 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002553 MacroInstantiation *MI = new MacroInstantiation(
2554 NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Daniel Dunbar43235712010-07-18 18:54:11 +00002555 ActiveMacros.push_back(MI);
2556
Toma Tabacu217116e2015-04-27 10:50:29 +00002557 ++NumOfMacroInstantiations;
2558
Daniel Dunbar43235712010-07-18 18:54:11 +00002559 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00002560 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00002561 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar43235712010-07-18 18:54:11 +00002562 Lex();
2563
2564 return false;
2565}
2566
Jim Grosbach4b905842013-09-20 23:08:21 +00002567void AsmParser::handleMacroExit() {
Daniel Dunbar43235712010-07-18 18:54:11 +00002568 // Jump to the EndOfStatement we should return to, and consume it.
Jim Grosbach4b905842013-09-20 23:08:21 +00002569 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
Daniel Dunbar43235712010-07-18 18:54:11 +00002570 Lex();
2571
2572 // Pop the instantiation entry.
2573 delete ActiveMacros.back();
2574 ActiveMacros.pop_back();
2575}
2576
Jim Grosbach4b905842013-09-20 23:08:21 +00002577bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
Jim Grosbachb7b750d2012-09-13 23:11:31 +00002578 bool NoDeadStrip) {
Pete Cooper80d21cb2015-06-22 19:35:57 +00002579 MCSymbol *Sym;
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002580 const MCExpr *Value;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002581 if (MCParserUtils::parseAssignmentExpression(Name, allow_redef, *this, Sym,
2582 Value))
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002583 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002584
Pete Cooper80d21cb2015-06-22 19:35:57 +00002585 if (!Sym) {
2586 // In the case where we parse an expression starting with a '.', we will
2587 // not generate an error, nor will we create a symbol. In this case we
2588 // should just return out.
Anders Waldenborg84809572014-02-17 20:48:32 +00002589 return false;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002590 }
David Majnemer58cb80c2014-12-24 10:27:50 +00002591
Daniel Dunbarae7ac012009-06-29 23:43:14 +00002592 // Do the assignment.
Daniel Dunbarb7b20972009-08-31 08:09:09 +00002593 Out.EmitAssignment(Sym, Value);
Jim Grosbachb7b750d2012-09-13 23:11:31 +00002594 if (NoDeadStrip)
2595 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2596
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002597 return false;
2598}
2599
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002600/// parseIdentifier:
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002601/// ::= identifier
2602/// ::= string
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002603bool AsmParser::parseIdentifier(StringRef &Res) {
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002604 // The assembler has relaxed rules for accepting identifiers, in particular we
Hans Wennborgce69d772013-10-18 20:46:28 +00002605 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2606 // separate tokens. At this level, we have already lexed so we cannot (currently)
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002607 // handle this as a context dependent token, instead we detect adjacent tokens
2608 // and return the combined identifier.
Hans Wennborgce69d772013-10-18 20:46:28 +00002609 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2610 SMLoc PrefixLoc = getLexer().getLoc();
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002611
Hans Wennborgce69d772013-10-18 20:46:28 +00002612 // Consume the prefix character, and check for a following identifier.
Nirav Daved0463322016-10-12 13:58:07 +00002613
2614 AsmToken Buf[1];
2615 Lexer.peekTokens(Buf, false);
2616
2617 if (Buf[0].isNot(AsmToken::Identifier))
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002618 return true;
2619
Hans Wennborgce69d772013-10-18 20:46:28 +00002620 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
Nirav Daved0463322016-10-12 13:58:07 +00002621 if (PrefixLoc.getPointer() + 1 != Buf[0].getLoc().getPointer())
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002622 return true;
2623
Nirav Daved0463322016-10-12 13:58:07 +00002624 // eat $ or @
2625 Lexer.Lex(); // Lexer's Lex guarantees consecutive token.
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002626 // Construct the joined identifier and consume the token.
Jim Grosbach4b905842013-09-20 23:08:21 +00002627 Res =
Hans Wennborgce69d772013-10-18 20:46:28 +00002628 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
Nirav Davefd910412016-06-17 16:06:17 +00002629 Lex(); // Parser Lex to maintain invariants.
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002630 return false;
2631 }
2632
Jim Grosbach4b905842013-09-20 23:08:21 +00002633 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002634 return true;
2635
Sean Callanan936b0d32010-01-19 21:44:56 +00002636 Res = getTok().getIdentifier();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002637
Sean Callanan686ed8d2010-01-19 20:22:31 +00002638 Lex(); // Consume the identifier token.
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002639
2640 return false;
2641}
2642
Jim Grosbach4b905842013-09-20 23:08:21 +00002643/// parseDirectiveSet:
Nico Weber4ada0d92011-01-28 03:04:41 +00002644/// ::= .equ identifier ',' expression
2645/// ::= .equiv identifier ',' expression
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002646/// ::= .set identifier ',' expression
Jim Grosbach4b905842013-09-20 23:08:21 +00002647bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002648 StringRef Name;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002649 if (check(parseIdentifier(Name), "expected identifier") ||
2650 parseToken(AsmToken::Comma) || parseAssignment(Name, allow_redef, true))
2651 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
2652 return false;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002653}
2654
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002655bool AsmParser::parseEscapedString(std::string &Data) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00002656 if (check(getTok().isNot(AsmToken::String), "expected string"))
2657 return true;
Daniel Dunbaref668c12009-08-14 18:19:52 +00002658
2659 Data = "";
Sean Callanan936b0d32010-01-19 21:44:56 +00002660 StringRef Str = getTok().getStringContents();
Daniel Dunbaref668c12009-08-14 18:19:52 +00002661 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2662 if (Str[i] != '\\') {
2663 Data += Str[i];
2664 continue;
2665 }
2666
2667 // Recognize escaped characters. Note that this escape semantics currently
2668 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2669 ++i;
2670 if (i == e)
2671 return TokError("unexpected backslash at end of string");
2672
2673 // Recognize octal sequences.
Jim Grosbach4b905842013-09-20 23:08:21 +00002674 if ((unsigned)(Str[i] - '0') <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002675 // Consume up to three octal characters.
2676 unsigned Value = Str[i] - '0';
2677
Jim Grosbach4b905842013-09-20 23:08:21 +00002678 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002679 ++i;
2680 Value = Value * 8 + (Str[i] - '0');
2681
Jim Grosbach4b905842013-09-20 23:08:21 +00002682 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002683 ++i;
2684 Value = Value * 8 + (Str[i] - '0');
2685 }
2686 }
2687
2688 if (Value > 255)
2689 return TokError("invalid octal escape sequence (out of range)");
2690
Jim Grosbach4b905842013-09-20 23:08:21 +00002691 Data += (unsigned char)Value;
Daniel Dunbaref668c12009-08-14 18:19:52 +00002692 continue;
2693 }
2694
2695 // Otherwise recognize individual escapes.
2696 switch (Str[i]) {
2697 default:
2698 // Just reject invalid escape sequences for now.
2699 return TokError("invalid escape sequence (unrecognized character)");
2700
2701 case 'b': Data += '\b'; break;
2702 case 'f': Data += '\f'; break;
2703 case 'n': Data += '\n'; break;
2704 case 'r': Data += '\r'; break;
2705 case 't': Data += '\t'; break;
2706 case '"': Data += '"'; break;
2707 case '\\': Data += '\\'; break;
2708 }
2709 }
2710
Nirav Davea645433c2016-07-18 15:24:03 +00002711 Lex();
Daniel Dunbaref668c12009-08-14 18:19:52 +00002712 return false;
2713}
2714
Jim Grosbach4b905842013-09-20 23:08:21 +00002715/// parseDirectiveAscii:
Rafael Espindola63760ba2010-10-28 20:02:27 +00002716/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002717bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00002718 auto parseOp = [&]() -> bool {
2719 std::string Data;
2720 if (checkForValidSection() || parseEscapedString(Data))
Nirav Davef43cc9f2016-10-10 15:24:54 +00002721 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002722 getStreamer().EmitBytes(Data);
2723 if (ZeroTerminated)
2724 getStreamer().EmitBytes(StringRef("\0", 1));
2725 return false;
2726 };
Daniel Dunbare5444a82010-09-09 22:42:59 +00002727
Nirav Dave1a9044b2016-10-24 14:35:29 +00002728 if (parseMany(parseOp))
2729 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbara10e5192009-06-24 23:30:00 +00002730 return false;
2731}
2732
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002733/// parseDirectiveReloc
2734/// ::= .reloc expression , identifier [ , expression ]
2735bool AsmParser::parseDirectiveReloc(SMLoc DirectiveLoc) {
2736 const MCExpr *Offset;
2737 const MCExpr *Expr = nullptr;
2738
2739 SMLoc OffsetLoc = Lexer.getTok().getLoc();
Nirav Dave1a9044b2016-10-24 14:35:29 +00002740 int64_t OffsetValue;
2741 // We can only deal with constant expressions at the moment.
2742
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002743 if (parseExpression(Offset))
2744 return true;
2745
Nirav Davea645433c2016-07-18 15:24:03 +00002746 if (check(!Offset->evaluateAsAbsolute(OffsetValue), OffsetLoc,
2747 "expression is not a constant value") ||
2748 check(OffsetValue < 0, OffsetLoc, "expression is negative") ||
2749 parseToken(AsmToken::Comma, "expected comma") ||
2750 check(getTok().isNot(AsmToken::Identifier), "expected relocation name"))
2751 return true;
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002752
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002753 SMLoc NameLoc = Lexer.getTok().getLoc();
2754 StringRef Name = Lexer.getTok().getIdentifier();
Nirav Davefd910412016-06-17 16:06:17 +00002755 Lex();
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002756
2757 if (Lexer.is(AsmToken::Comma)) {
Nirav Davefd910412016-06-17 16:06:17 +00002758 Lex();
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002759 SMLoc ExprLoc = Lexer.getLoc();
2760 if (parseExpression(Expr))
2761 return true;
2762
2763 MCValue Value;
2764 if (!Expr->evaluateAsRelocatable(Value, nullptr, nullptr))
2765 return Error(ExprLoc, "expression must be relocatable");
2766 }
2767
Nirav Davea645433c2016-07-18 15:24:03 +00002768 if (parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00002769 "unexpected token in .reloc directive"))
2770 return true;
2771
2772 if (getStreamer().EmitRelocDirective(*Offset, Name, Expr, DirectiveLoc))
2773 return Error(NameLoc, "unknown relocation name");
2774
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002775 return false;
2776}
2777
Jim Grosbach4b905842013-09-20 23:08:21 +00002778/// parseDirectiveValue
Daniel Dunbara10e5192009-06-24 23:30:00 +00002779/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00002780bool AsmParser::parseDirectiveValue(StringRef IDVal, unsigned Size) {
2781 auto parseOp = [&]() -> bool {
2782 const MCExpr *Value;
2783 SMLoc ExprLoc = getLexer().getLoc();
2784 if (checkForValidSection() || parseExpression(Value))
Nirav Davef43cc9f2016-10-10 15:24:54 +00002785 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002786 // Special case constant expressions to match code generator.
2787 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2788 assert(Size <= 8 && "Invalid size");
2789 uint64_t IntValue = MCE->getValue();
2790 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2791 return Error(ExprLoc, "out of range literal value");
2792 getStreamer().EmitIntValue(IntValue, Size);
2793 } else
2794 getStreamer().EmitValue(Value, Size, ExprLoc);
2795 return false;
2796 };
Daniel Dunbare5444a82010-09-09 22:42:59 +00002797
Nirav Dave1a9044b2016-10-24 14:35:29 +00002798 if (parseMany(parseOp))
2799 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbara10e5192009-06-24 23:30:00 +00002800 return false;
2801}
2802
David Woodhoused6de0d92014-02-01 16:20:59 +00002803/// ParseDirectiveOctaValue
2804/// ::= .octa [ hexconstant (, hexconstant)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00002805
2806bool AsmParser::parseDirectiveOctaValue(StringRef IDVal) {
2807 auto parseOp = [&]() -> bool {
Nirav Davef43cc9f2016-10-10 15:24:54 +00002808 if (checkForValidSection())
2809 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002810 if (getTok().isNot(AsmToken::Integer) && getTok().isNot(AsmToken::BigNum))
2811 return TokError("unknown token in expression");
2812 SMLoc ExprLoc = getTok().getLoc();
2813 APInt IntValue = getTok().getAPIntVal();
2814 uint64_t hi, lo;
2815 Lex();
2816 if (!IntValue.isIntN(128))
2817 return Error(ExprLoc, "out of range literal value");
2818 if (!IntValue.isIntN(64)) {
2819 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
2820 lo = IntValue.getLoBits(64).getZExtValue();
2821 } else {
2822 hi = 0;
2823 lo = IntValue.getZExtValue();
David Woodhoused6de0d92014-02-01 16:20:59 +00002824 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00002825 if (MAI.isLittleEndian()) {
2826 getStreamer().EmitIntValue(lo, 8);
2827 getStreamer().EmitIntValue(hi, 8);
2828 } else {
2829 getStreamer().EmitIntValue(hi, 8);
2830 getStreamer().EmitIntValue(lo, 8);
2831 }
2832 return false;
2833 };
David Woodhoused6de0d92014-02-01 16:20:59 +00002834
Nirav Dave1a9044b2016-10-24 14:35:29 +00002835 if (parseMany(parseOp))
2836 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
David Woodhoused6de0d92014-02-01 16:20:59 +00002837 return false;
2838}
2839
Petr Hosek4cb08ce2016-09-23 19:25:15 +00002840bool AsmParser::parseRealValue(const fltSemantics &Semantics, APInt &Res) {
2841 // We don't truly support arithmetic on floating point expressions, so we
2842 // have to manually parse unary prefixes.
2843 bool IsNeg = false;
2844 if (getLexer().is(AsmToken::Minus)) {
2845 Lexer.Lex();
2846 IsNeg = true;
2847 } else if (getLexer().is(AsmToken::Plus))
2848 Lexer.Lex();
2849
2850 if (Lexer.is(AsmToken::Error))
2851 return TokError(Lexer.getErr());
2852 if (Lexer.isNot(AsmToken::Integer) && Lexer.isNot(AsmToken::Real) &&
2853 Lexer.isNot(AsmToken::Identifier))
2854 return TokError("unexpected token in directive");
2855
2856 // Convert to an APFloat.
2857 APFloat Value(Semantics);
2858 StringRef IDVal = getTok().getString();
2859 if (getLexer().is(AsmToken::Identifier)) {
2860 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2861 Value = APFloat::getInf(Semantics);
2862 else if (!IDVal.compare_lower("nan"))
2863 Value = APFloat::getNaN(Semantics, false, ~0);
2864 else
2865 return TokError("invalid floating point literal");
2866 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2867 APFloat::opInvalidOp)
2868 return TokError("invalid floating point literal");
2869 if (IsNeg)
2870 Value.changeSign();
2871
2872 // Consume the numeric token.
2873 Lex();
2874
2875 Res = Value.bitcastToAPInt();
2876
2877 return false;
2878}
2879
Jim Grosbach4b905842013-09-20 23:08:21 +00002880/// parseDirectiveRealValue
Daniel Dunbar2af16532010-09-24 01:59:56 +00002881/// ::= (.single | .double) [ expression (, expression)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00002882bool AsmParser::parseDirectiveRealValue(StringRef IDVal,
2883 const fltSemantics &Semantics) {
2884 auto parseOp = [&]() -> bool {
2885 APInt AsInt;
2886 if (checkForValidSection() || parseRealValue(Semantics, AsInt))
Nirav Davef43cc9f2016-10-10 15:24:54 +00002887 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002888 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2889 AsInt.getBitWidth() / 8);
2890 return false;
2891 };
Daniel Dunbar2af16532010-09-24 01:59:56 +00002892
Nirav Dave1a9044b2016-10-24 14:35:29 +00002893 if (parseMany(parseOp))
2894 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbar2af16532010-09-24 01:59:56 +00002895 return false;
2896}
2897
Jim Grosbach4b905842013-09-20 23:08:21 +00002898/// parseDirectiveZero
Rafael Espindola922e3f42010-09-16 15:03:59 +00002899/// ::= .zero expression
Jim Grosbach4b905842013-09-20 23:08:21 +00002900bool AsmParser::parseDirectiveZero() {
Petr Hosek67a94a72016-05-28 05:57:48 +00002901 SMLoc NumBytesLoc = Lexer.getLoc();
2902 const MCExpr *NumBytes;
Nirav Davef43cc9f2016-10-10 15:24:54 +00002903 if (checkForValidSection() || parseExpression(NumBytes))
Rafael Espindola922e3f42010-09-16 15:03:59 +00002904 return true;
2905
Rafael Espindolab91bac62010-10-05 19:42:57 +00002906 int64_t Val = 0;
2907 if (getLexer().is(AsmToken::Comma)) {
2908 Lex();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002909 if (parseAbsoluteExpression(Val))
Rafael Espindolab91bac62010-10-05 19:42:57 +00002910 return true;
2911 }
2912
Nirav Davea645433c2016-07-18 15:24:03 +00002913 if (parseToken(AsmToken::EndOfStatement,
2914 "unexpected token in '.zero' directive"))
2915 return true;
Petr Hosek67a94a72016-05-28 05:57:48 +00002916 getStreamer().emitFill(*NumBytes, Val, NumBytesLoc);
Rafael Espindola922e3f42010-09-16 15:03:59 +00002917
2918 return false;
2919}
2920
Jim Grosbach4b905842013-09-20 23:08:21 +00002921/// parseDirectiveFill
Roman Divackye33098f2013-09-24 17:44:41 +00002922/// ::= .fill expression [ , expression [ , expression ] ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002923bool AsmParser::parseDirectiveFill() {
Petr Hosek67a94a72016-05-28 05:57:48 +00002924 SMLoc NumValuesLoc = Lexer.getLoc();
2925 const MCExpr *NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00002926 if (checkForValidSection() || parseExpression(NumValues))
Daniel Dunbara10e5192009-06-24 23:30:00 +00002927 return true;
2928
Roman Divackye33098f2013-09-24 17:44:41 +00002929 int64_t FillSize = 1;
2930 int64_t FillExpr = 0;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002931
David Majnemer522d3db2014-02-01 07:19:38 +00002932 SMLoc SizeLoc, ExprLoc;
Daniel Dunbara10e5192009-06-24 23:30:00 +00002933
Nirav Dave1a9044b2016-10-24 14:35:29 +00002934 if (parseOptionalToken(AsmToken::Comma)) {
2935 SizeLoc = getTok().getLoc();
2936 if (parseAbsoluteExpression(FillSize))
Roman Divackye33098f2013-09-24 17:44:41 +00002937 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002938 if (parseOptionalToken(AsmToken::Comma)) {
2939 ExprLoc = getTok().getLoc();
2940 if (parseAbsoluteExpression(FillExpr))
Roman Divackye33098f2013-09-24 17:44:41 +00002941 return true;
Roman Divackye33098f2013-09-24 17:44:41 +00002942 }
2943 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00002944 if (parseToken(AsmToken::EndOfStatement,
2945 "unexpected token in '.fill' directive"))
2946 return true;
Daniel Dunbara10e5192009-06-24 23:30:00 +00002947
David Majnemer522d3db2014-02-01 07:19:38 +00002948 if (FillSize < 0) {
2949 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
Petr Hosek6abd38b2016-05-28 08:20:08 +00002950 return false;
David Majnemer522d3db2014-02-01 07:19:38 +00002951 }
2952 if (FillSize > 8) {
2953 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
2954 FillSize = 8;
2955 }
Daniel Dunbara10e5192009-06-24 23:30:00 +00002956
David Majnemer522d3db2014-02-01 07:19:38 +00002957 if (!isUInt<32>(FillExpr) && FillSize > 4)
2958 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
2959
Petr Hosek67a94a72016-05-28 05:57:48 +00002960 getStreamer().emitFill(*NumValues, FillSize, FillExpr, NumValuesLoc);
Daniel Dunbara10e5192009-06-24 23:30:00 +00002961
2962 return false;
2963}
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002964
Jim Grosbach4b905842013-09-20 23:08:21 +00002965/// parseDirectiveOrg
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002966/// ::= .org expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002967bool AsmParser::parseDirectiveOrg() {
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002968 const MCExpr *Offset;
Oliver Stannard268f42f2016-12-14 10:43:58 +00002969 SMLoc OffsetLoc = Lexer.getLoc();
Nirav Davef43cc9f2016-10-10 15:24:54 +00002970 if (checkForValidSection() || parseExpression(Offset))
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002971 return true;
2972
2973 // Parse optional fill expression.
2974 int64_t FillExpr = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002975 if (parseOptionalToken(AsmToken::Comma))
2976 if (parseAbsoluteExpression(FillExpr))
2977 return addErrorSuffix(" in '.org' directive");
2978 if (parseToken(AsmToken::EndOfStatement))
2979 return addErrorSuffix(" in '.org' directive");
Nirav Davea645433c2016-07-18 15:24:03 +00002980
Oliver Stannard268f42f2016-12-14 10:43:58 +00002981 getStreamer().emitValueToOffset(Offset, FillExpr, OffsetLoc);
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002982 return false;
2983}
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002984
Jim Grosbach4b905842013-09-20 23:08:21 +00002985/// parseDirectiveAlign
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002986/// ::= {.align, ...} expression [ , expression [ , expression ]]
Jim Grosbach4b905842013-09-20 23:08:21 +00002987bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002988 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002989 int64_t Alignment;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002990 SMLoc MaxBytesLoc;
2991 bool HasFillExpr = false;
2992 int64_t FillExpr = 0;
2993 int64_t MaxBytesToFill = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002994
2995 auto parseAlign = [&]() -> bool {
2996 if (checkForValidSection() || parseAbsoluteExpression(Alignment))
Nirav Davea645433c2016-07-18 15:24:03 +00002997 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002998 if (parseOptionalToken(AsmToken::Comma)) {
2999 // The fill expression can be omitted while specifying a maximum number of
3000 // alignment bytes, e.g:
3001 // .align 3,,4
3002 if (getTok().isNot(AsmToken::Comma)) {
3003 HasFillExpr = true;
3004 if (parseAbsoluteExpression(FillExpr))
3005 return true;
3006 }
3007 if (parseOptionalToken(AsmToken::Comma))
3008 if (parseTokenLoc(MaxBytesLoc) ||
3009 parseAbsoluteExpression(MaxBytesToFill))
3010 return true;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003011 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003012 return parseToken(AsmToken::EndOfStatement);
3013 };
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003014
Nirav Dave1a9044b2016-10-24 14:35:29 +00003015 if (parseAlign())
3016 return addErrorSuffix(" in directive");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003017
Nirav Dave2364748a2016-09-16 18:30:20 +00003018 // Always emit an alignment here even if we thrown an error.
3019 bool ReturnVal = false;
3020
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003021 // Compute alignment in bytes.
3022 if (IsPow2) {
3023 // FIXME: Diagnose overflow.
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003024 if (Alignment >= 32) {
Nirav Dave2364748a2016-09-16 18:30:20 +00003025 ReturnVal |= Error(AlignmentLoc, "invalid alignment value");
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003026 Alignment = 31;
3027 }
3028
Benjamin Kramer63951ad2009-09-06 09:35:10 +00003029 Alignment = 1ULL << Alignment;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00003030 } else {
Davide Italianocb2da712015-09-08 18:59:47 +00003031 // Reject alignments that aren't either a power of two or zero,
3032 // for gas compatibility. Alignment of zero is silently rounded
3033 // up to one.
3034 if (Alignment == 0)
3035 Alignment = 1;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00003036 if (!isPowerOf2_64(Alignment))
Nirav Dave2364748a2016-09-16 18:30:20 +00003037 ReturnVal |= Error(AlignmentLoc, "alignment must be a power of 2");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003038 }
3039
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003040 // Diagnose non-sensical max bytes to align.
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003041 if (MaxBytesLoc.isValid()) {
3042 if (MaxBytesToFill < 1) {
Nirav Dave2364748a2016-09-16 18:30:20 +00003043 ReturnVal |= Error(MaxBytesLoc,
3044 "alignment directive can never be satisfied in this "
Jim Grosbach4b905842013-09-20 23:08:21 +00003045 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar4abcccb2009-08-21 23:01:53 +00003046 MaxBytesToFill = 0;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003047 }
3048
3049 if (MaxBytesToFill >= Alignment) {
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +00003050 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
Jim Grosbach4b905842013-09-20 23:08:21 +00003051 "has no effect");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003052 MaxBytesToFill = 0;
3053 }
3054 }
3055
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003056 // Check whether we should use optimal code alignment for this .align
3057 // directive.
Eric Christopher445c9522016-10-14 05:47:37 +00003058 const MCSection *Section = getStreamer().getCurrentSectionOnly();
Saleem Abdulrasool7f2f9f42014-03-21 05:13:23 +00003059 assert(Section && "must have section to emit alignment");
3060 bool UseCodeAlign = Section->UseCodeAlign();
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003061 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
3062 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003063 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003064 } else {
Kevin Enderby7f993022010-02-25 18:46:04 +00003065 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnerc2b36752010-07-15 21:19:31 +00003066 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
3067 MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003068 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003069
Nirav Dave2364748a2016-09-16 18:30:20 +00003070 return ReturnVal;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003071}
3072
Jim Grosbach4b905842013-09-20 23:08:21 +00003073/// parseDirectiveFile
Eli Bendersky17233942013-01-15 22:59:42 +00003074/// ::= .file [number] filename
3075/// ::= .file number directory filename
Jim Grosbach4b905842013-09-20 23:08:21 +00003076bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003077 // FIXME: I'm not sure what this is.
3078 int64_t FileNumber = -1;
3079 SMLoc FileNumberLoc = getLexer().getLoc();
3080 if (getLexer().is(AsmToken::Integer)) {
3081 FileNumber = getTok().getIntVal();
3082 Lex();
3083
3084 if (FileNumber < 1)
3085 return TokError("file number less than one");
3086 }
3087
Nirav Davea645433c2016-07-18 15:24:03 +00003088 std::string Path = getTok().getString();
Eli Bendersky17233942013-01-15 22:59:42 +00003089
3090 // Usually the directory and filename together, otherwise just the directory.
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003091 // Allow the strings to have escaped octal character sequence.
Nirav Davea645433c2016-07-18 15:24:03 +00003092 if (check(getTok().isNot(AsmToken::String),
3093 "unexpected token in '.file' directive") ||
3094 parseEscapedString(Path))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003095 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003096
3097 StringRef Directory;
3098 StringRef Filename;
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003099 std::string FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00003100 if (getLexer().is(AsmToken::String)) {
Nirav Davea645433c2016-07-18 15:24:03 +00003101 if (check(FileNumber == -1,
3102 "explicit path specified, but no file number") ||
3103 parseEscapedString(FilenameData))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003104 return true;
3105 Filename = FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00003106 Directory = Path;
Eli Bendersky17233942013-01-15 22:59:42 +00003107 } else {
3108 Filename = Path;
3109 }
3110
Nirav Davea645433c2016-07-18 15:24:03 +00003111 if (parseToken(AsmToken::EndOfStatement,
3112 "unexpected token in '.file' directive"))
3113 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003114
3115 if (FileNumber == -1)
3116 getStreamer().EmitFileDirective(Filename);
3117 else {
David Blaikie22748082016-05-26 00:22:26 +00003118 // If there is -g option as well as debug info from directive file,
3119 // we turn off -g option, directly use the existing debug info instead.
David Blaikiedc3f01e2015-03-09 01:57:13 +00003120 if (getContext().getGenDwarfForAssembly())
David Blaikie22748082016-05-26 00:22:26 +00003121 getContext().setGenDwarfForAssembly(false);
3122 else if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename) ==
David Blaikiec714ef42014-03-17 01:52:11 +00003123 0)
Nirav Dave2364748a2016-09-16 18:30:20 +00003124 return Error(FileNumberLoc, "file number already allocated");
Eli Bendersky17233942013-01-15 22:59:42 +00003125 }
3126
3127 return false;
3128}
3129
Jim Grosbach4b905842013-09-20 23:08:21 +00003130/// parseDirectiveLine
Eli Bendersky17233942013-01-15 22:59:42 +00003131/// ::= .line [number]
Jim Grosbach4b905842013-09-20 23:08:21 +00003132bool AsmParser::parseDirectiveLine() {
Nirav Davea645433c2016-07-18 15:24:03 +00003133 int64_t LineNumber;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003134 if (getLexer().is(AsmToken::Integer)) {
Nirav Davea645433c2016-07-18 15:24:03 +00003135 if (parseIntToken(LineNumber, "unexpected token in '.line' directive"))
3136 return true;
Jim Grosbach4b905842013-09-20 23:08:21 +00003137 (void)LineNumber;
Eli Bendersky17233942013-01-15 22:59:42 +00003138 // FIXME: Do something with the .line.
3139 }
Nirav Davea645433c2016-07-18 15:24:03 +00003140 if (parseToken(AsmToken::EndOfStatement,
3141 "unexpected token in '.line' directive"))
3142 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003143
3144 return false;
3145}
3146
Jim Grosbach4b905842013-09-20 23:08:21 +00003147/// parseDirectiveLoc
Eli Bendersky17233942013-01-15 22:59:42 +00003148/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
3149/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
3150/// The first number is a file number, must have been previously assigned with
3151/// a .file directive, the second number is the line number and optionally the
3152/// third number is a column position (zero if not specified). The remaining
3153/// optional items are .loc sub-directives.
Jim Grosbach4b905842013-09-20 23:08:21 +00003154bool AsmParser::parseDirectiveLoc() {
Nirav Davea645433c2016-07-18 15:24:03 +00003155 int64_t FileNumber = 0, LineNumber = 0;
3156 SMLoc Loc = getTok().getLoc();
3157 if (parseIntToken(FileNumber, "unexpected token in '.loc' directive") ||
3158 check(FileNumber < 1, Loc,
3159 "file number less than one in '.loc' directive") ||
3160 check(!getContext().isValidDwarfFileNumber(FileNumber), Loc,
3161 "unassigned file number in '.loc' directive"))
3162 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003163
Nirav Davea645433c2016-07-18 15:24:03 +00003164 // optional
Eli Bendersky17233942013-01-15 22:59:42 +00003165 if (getLexer().is(AsmToken::Integer)) {
3166 LineNumber = getTok().getIntVal();
Adrian Prantl6ac40032013-09-26 23:37:11 +00003167 if (LineNumber < 0)
3168 return TokError("line number less than zero in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003169 Lex();
3170 }
3171
3172 int64_t ColumnPos = 0;
3173 if (getLexer().is(AsmToken::Integer)) {
3174 ColumnPos = getTok().getIntVal();
3175 if (ColumnPos < 0)
3176 return TokError("column position less than zero in '.loc' directive");
3177 Lex();
3178 }
3179
3180 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
3181 unsigned Isa = 0;
3182 int64_t Discriminator = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003183
Nirav Dave1a9044b2016-10-24 14:35:29 +00003184 auto parseLocOp = [&]() -> bool {
3185 StringRef Name;
3186 SMLoc Loc = getTok().getLoc();
3187 if (parseIdentifier(Name))
3188 return TokError("unexpected token in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003189
Nirav Dave1a9044b2016-10-24 14:35:29 +00003190 if (Name == "basic_block")
3191 Flags |= DWARF2_FLAG_BASIC_BLOCK;
3192 else if (Name == "prologue_end")
3193 Flags |= DWARF2_FLAG_PROLOGUE_END;
3194 else if (Name == "epilogue_begin")
3195 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
3196 else if (Name == "is_stmt") {
3197 Loc = getTok().getLoc();
3198 const MCExpr *Value;
3199 if (parseExpression(Value))
3200 return true;
3201 // The expression must be the constant 0 or 1.
3202 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3203 int Value = MCE->getValue();
3204 if (Value == 0)
3205 Flags &= ~DWARF2_FLAG_IS_STMT;
3206 else if (Value == 1)
3207 Flags |= DWARF2_FLAG_IS_STMT;
3208 else
3209 return Error(Loc, "is_stmt value not 0 or 1");
Craig Topperf15655b2013-04-22 04:22:40 +00003210 } else {
Nirav Dave1a9044b2016-10-24 14:35:29 +00003211 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
Eli Bendersky17233942013-01-15 22:59:42 +00003212 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003213 } else if (Name == "isa") {
3214 Loc = getTok().getLoc();
3215 const MCExpr *Value;
3216 if (parseExpression(Value))
3217 return true;
3218 // The expression must be a constant greater or equal to 0.
3219 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3220 int Value = MCE->getValue();
3221 if (Value < 0)
3222 return Error(Loc, "isa number less than zero");
3223 Isa = Value;
3224 } else {
3225 return Error(Loc, "isa number not a constant value");
3226 }
3227 } else if (Name == "discriminator") {
3228 if (parseAbsoluteExpression(Discriminator))
3229 return true;
3230 } else {
3231 return Error(Loc, "unknown sub-directive in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003232 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003233 return false;
3234 };
3235
Nirav Davee2369aa2016-10-26 17:28:58 +00003236 if (parseMany(parseLocOp, false /*hasComma*/))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003237 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003238
3239 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
3240 Isa, Discriminator, StringRef());
3241
3242 return false;
3243}
3244
Jim Grosbach4b905842013-09-20 23:08:21 +00003245/// parseDirectiveStabs
Eli Bendersky17233942013-01-15 22:59:42 +00003246/// ::= .stabs string, number, number, number
Jim Grosbach4b905842013-09-20 23:08:21 +00003247bool AsmParser::parseDirectiveStabs() {
Eli Bendersky17233942013-01-15 22:59:42 +00003248 return TokError("unsupported directive '.stabs'");
3249}
3250
Reid Kleckner2214ed82016-01-29 00:49:42 +00003251/// parseDirectiveCVFile
3252/// ::= .cv_file number filename
3253bool AsmParser::parseDirectiveCVFile() {
Nirav Davea645433c2016-07-18 15:24:03 +00003254 SMLoc FileNumberLoc = getTok().getLoc();
3255 int64_t FileNumber;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003256 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00003257
3258 if (parseIntToken(FileNumber,
3259 "expected file number in '.cv_file' directive") ||
3260 check(FileNumber < 1, FileNumberLoc, "file number less than one") ||
3261 check(getTok().isNot(AsmToken::String),
3262 "unexpected token in '.cv_file' directive") ||
3263 // Usually directory and filename are together, otherwise just
3264 // directory. Allow the strings to have escaped octal character sequence.
3265 parseEscapedString(Filename) ||
3266 parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00003267 "unexpected token in '.cv_file' directive"))
Reid Klecknera5b1eef2016-08-26 17:58:37 +00003268 return true;
Nirav Dave1ab71992016-07-18 19:35:21 +00003269
Reid Klecknera5b1eef2016-08-26 17:58:37 +00003270 if (!getStreamer().EmitCVFileDirective(FileNumber, Filename))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003271 return Error(FileNumberLoc, "file number already allocated");
Reid Kleckner2214ed82016-01-29 00:49:42 +00003272
3273 return false;
3274}
3275
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003276bool AsmParser::parseCVFunctionId(int64_t &FunctionId,
3277 StringRef DirectiveName) {
3278 SMLoc Loc;
3279 return parseTokenLoc(Loc) ||
3280 parseIntToken(FunctionId, "expected function id in '" + DirectiveName +
3281 "' directive") ||
3282 check(FunctionId < 0 || FunctionId >= UINT_MAX, Loc,
3283 "expected function id within range [0, UINT_MAX)");
3284}
3285
3286bool AsmParser::parseCVFileId(int64_t &FileNumber, StringRef DirectiveName) {
3287 SMLoc Loc;
3288 return parseTokenLoc(Loc) ||
3289 parseIntToken(FileNumber, "expected integer in '" + DirectiveName +
3290 "' directive") ||
3291 check(FileNumber < 1, Loc, "file number less than one in '" +
3292 DirectiveName + "' directive") ||
3293 check(!getCVContext().isValidFileNumber(FileNumber), Loc,
3294 "unassigned file number in '" + DirectiveName + "' directive");
3295}
3296
3297/// parseDirectiveCVFuncId
3298/// ::= .cv_func_id FunctionId
3299///
3300/// Introduces a function ID that can be used with .cv_loc.
3301bool AsmParser::parseDirectiveCVFuncId() {
3302 SMLoc FunctionIdLoc = getTok().getLoc();
3303 int64_t FunctionId;
3304
3305 if (parseCVFunctionId(FunctionId, ".cv_func_id") ||
3306 parseToken(AsmToken::EndOfStatement,
3307 "unexpected token in '.cv_func_id' directive"))
3308 return true;
3309
3310 if (!getStreamer().EmitCVFuncIdDirective(FunctionId))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003311 return Error(FunctionIdLoc, "function id already allocated");
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003312
3313 return false;
3314}
3315
3316/// parseDirectiveCVInlineSiteId
3317/// ::= .cv_inline_site_id FunctionId
3318/// "within" IAFunc
3319/// "inlined_at" IAFile IALine [IACol]
3320///
3321/// Introduces a function ID that can be used with .cv_loc. Includes "inlined
3322/// at" source location information for use in the line table of the caller,
3323/// whether the caller is a real function or another inlined call site.
3324bool AsmParser::parseDirectiveCVInlineSiteId() {
3325 SMLoc FunctionIdLoc = getTok().getLoc();
3326 int64_t FunctionId;
3327 int64_t IAFunc;
3328 int64_t IAFile;
3329 int64_t IALine;
3330 int64_t IACol = 0;
3331
3332 // FunctionId
3333 if (parseCVFunctionId(FunctionId, ".cv_inline_site_id"))
3334 return true;
3335
3336 // "within"
3337 if (check((getLexer().isNot(AsmToken::Identifier) ||
3338 getTok().getIdentifier() != "within"),
3339 "expected 'within' identifier in '.cv_inline_site_id' directive"))
3340 return true;
3341 Lex();
3342
3343 // IAFunc
3344 if (parseCVFunctionId(IAFunc, ".cv_inline_site_id"))
3345 return true;
3346
3347 // "inlined_at"
3348 if (check((getLexer().isNot(AsmToken::Identifier) ||
3349 getTok().getIdentifier() != "inlined_at"),
3350 "expected 'inlined_at' identifier in '.cv_inline_site_id' "
3351 "directive") )
3352 return true;
3353 Lex();
3354
3355 // IAFile IALine
3356 if (parseCVFileId(IAFile, ".cv_inline_site_id") ||
3357 parseIntToken(IALine, "expected line number after 'inlined_at'"))
3358 return true;
3359
3360 // [IACol]
3361 if (getLexer().is(AsmToken::Integer)) {
3362 IACol = getTok().getIntVal();
3363 Lex();
3364 }
3365
3366 if (parseToken(AsmToken::EndOfStatement,
3367 "unexpected token in '.cv_inline_site_id' directive"))
3368 return true;
3369
3370 if (!getStreamer().EmitCVInlineSiteIdDirective(FunctionId, IAFunc, IAFile,
3371 IALine, IACol, FunctionIdLoc))
Nirav Dave2364748a2016-09-16 18:30:20 +00003372 return Error(FunctionIdLoc, "function id already allocated");
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003373
3374 return false;
3375}
3376
Reid Kleckner2214ed82016-01-29 00:49:42 +00003377/// parseDirectiveCVLoc
3378/// ::= .cv_loc FunctionId FileNumber [LineNumber] [ColumnPos] [prologue_end]
3379/// [is_stmt VALUE]
3380/// The first number is a file number, must have been previously assigned with
3381/// a .file directive, the second number is the line number and optionally the
3382/// third number is a column position (zero if not specified). The remaining
3383/// optional items are .loc sub-directives.
3384bool AsmParser::parseDirectiveCVLoc() {
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003385 SMLoc DirectiveLoc = getTok().getLoc();
Nirav Davea645433c2016-07-18 15:24:03 +00003386 SMLoc Loc;
3387 int64_t FunctionId, FileNumber;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003388 if (parseCVFunctionId(FunctionId, ".cv_loc") ||
3389 parseCVFileId(FileNumber, ".cv_loc"))
Nirav Davea645433c2016-07-18 15:24:03 +00003390 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003391
3392 int64_t LineNumber = 0;
3393 if (getLexer().is(AsmToken::Integer)) {
3394 LineNumber = getTok().getIntVal();
3395 if (LineNumber < 0)
3396 return TokError("line number less than zero in '.cv_loc' directive");
3397 Lex();
3398 }
3399
3400 int64_t ColumnPos = 0;
3401 if (getLexer().is(AsmToken::Integer)) {
3402 ColumnPos = getTok().getIntVal();
3403 if (ColumnPos < 0)
3404 return TokError("column position less than zero in '.cv_loc' directive");
3405 Lex();
3406 }
3407
3408 bool PrologueEnd = false;
3409 uint64_t IsStmt = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003410
3411 auto parseOp = [&]() -> bool {
Reid Kleckner2214ed82016-01-29 00:49:42 +00003412 StringRef Name;
3413 SMLoc Loc = getTok().getLoc();
3414 if (parseIdentifier(Name))
3415 return TokError("unexpected token in '.cv_loc' directive");
Reid Kleckner2214ed82016-01-29 00:49:42 +00003416 if (Name == "prologue_end")
3417 PrologueEnd = true;
3418 else if (Name == "is_stmt") {
3419 Loc = getTok().getLoc();
3420 const MCExpr *Value;
3421 if (parseExpression(Value))
3422 return true;
3423 // The expression must be the constant 0 or 1.
3424 IsStmt = ~0ULL;
3425 if (const auto *MCE = dyn_cast<MCConstantExpr>(Value))
3426 IsStmt = MCE->getValue();
3427
3428 if (IsStmt > 1)
3429 return Error(Loc, "is_stmt value not 0 or 1");
3430 } else {
3431 return Error(Loc, "unknown sub-directive in '.cv_loc' directive");
3432 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003433 return false;
3434 };
3435
3436 if (parseMany(parseOp, false /*hasComma*/))
3437 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003438
3439 getStreamer().EmitCVLocDirective(FunctionId, FileNumber, LineNumber,
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003440 ColumnPos, PrologueEnd, IsStmt, StringRef(),
3441 DirectiveLoc);
Reid Kleckner2214ed82016-01-29 00:49:42 +00003442 return false;
3443}
3444
3445/// parseDirectiveCVLinetable
3446/// ::= .cv_linetable FunctionId, FnStart, FnEnd
3447bool AsmParser::parseDirectiveCVLinetable() {
Nirav Davea645433c2016-07-18 15:24:03 +00003448 int64_t FunctionId;
3449 StringRef FnStartName, FnEndName;
3450 SMLoc Loc = getTok().getLoc();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003451 if (parseCVFunctionId(FunctionId, ".cv_linetable") ||
Nirav Davea645433c2016-07-18 15:24:03 +00003452 parseToken(AsmToken::Comma,
3453 "unexpected token in '.cv_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003454 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3455 "expected identifier in directive") ||
Nirav Davea645433c2016-07-18 15:24:03 +00003456 parseToken(AsmToken::Comma,
3457 "unexpected token in '.cv_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003458 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3459 "expected identifier in directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00003460 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003461
3462 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3463 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
3464
3465 getStreamer().EmitCVLinetableDirective(FunctionId, FnStartSym, FnEndSym);
3466 return false;
3467}
3468
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003469/// parseDirectiveCVInlineLinetable
David Majnemerc9911f22016-02-02 19:22:34 +00003470/// ::= .cv_inline_linetable PrimaryFunctionId FileId LineNum FnStart FnEnd
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003471bool AsmParser::parseDirectiveCVInlineLinetable() {
Nirav Davea645433c2016-07-18 15:24:03 +00003472 int64_t PrimaryFunctionId, SourceFileId, SourceLineNum;
3473 StringRef FnStartName, FnEndName;
3474 SMLoc Loc = getTok().getLoc();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003475 if (parseCVFunctionId(PrimaryFunctionId, ".cv_inline_linetable") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003476 parseTokenLoc(Loc) ||
Nirav Davea645433c2016-07-18 15:24:03 +00003477 parseIntToken(
3478 SourceFileId,
3479 "expected SourceField in '.cv_inline_linetable' directive") ||
3480 check(SourceFileId <= 0, Loc,
3481 "File id less than zero in '.cv_inline_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003482 parseTokenLoc(Loc) ||
Nirav Davea645433c2016-07-18 15:24:03 +00003483 parseIntToken(
3484 SourceLineNum,
3485 "expected SourceLineNum in '.cv_inline_linetable' directive") ||
3486 check(SourceLineNum < 0, Loc,
3487 "Line number less than zero in '.cv_inline_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003488 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3489 "expected identifier in directive") ||
3490 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3491 "expected identifier in directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00003492 return true;
David Majnemerc9911f22016-02-02 19:22:34 +00003493
Nirav Davea645433c2016-07-18 15:24:03 +00003494 if (parseToken(AsmToken::EndOfStatement, "Expected End of Statement"))
3495 return true;
3496
3497 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3498 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
Reid Kleckner1fcd6102016-02-02 17:41:18 +00003499 getStreamer().EmitCVInlineLinetableDirective(PrimaryFunctionId, SourceFileId,
3500 SourceLineNum, FnStartSym,
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003501 FnEndSym);
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003502 return false;
3503}
3504
David Majnemer408b5e62016-02-05 01:55:49 +00003505/// parseDirectiveCVDefRange
3506/// ::= .cv_def_range RangeStart RangeEnd (GapStart GapEnd)*, bytes*
3507bool AsmParser::parseDirectiveCVDefRange() {
3508 SMLoc Loc;
3509 std::vector<std::pair<const MCSymbol *, const MCSymbol *>> Ranges;
3510 while (getLexer().is(AsmToken::Identifier)) {
3511 Loc = getLexer().getLoc();
3512 StringRef GapStartName;
3513 if (parseIdentifier(GapStartName))
3514 return Error(Loc, "expected identifier in directive");
3515 MCSymbol *GapStartSym = getContext().getOrCreateSymbol(GapStartName);
3516
3517 Loc = getLexer().getLoc();
3518 StringRef GapEndName;
3519 if (parseIdentifier(GapEndName))
3520 return Error(Loc, "expected identifier in directive");
3521 MCSymbol *GapEndSym = getContext().getOrCreateSymbol(GapEndName);
3522
3523 Ranges.push_back({GapStartSym, GapEndSym});
3524 }
3525
David Majnemer408b5e62016-02-05 01:55:49 +00003526 std::string FixedSizePortion;
Nirav Davea645433c2016-07-18 15:24:03 +00003527 if (parseToken(AsmToken::Comma, "unexpected token in directive") ||
3528 parseEscapedString(FixedSizePortion))
David Majnemer408b5e62016-02-05 01:55:49 +00003529 return true;
David Majnemer408b5e62016-02-05 01:55:49 +00003530
3531 getStreamer().EmitCVDefRangeDirective(Ranges, FixedSizePortion);
3532 return false;
3533}
3534
Reid Kleckner2214ed82016-01-29 00:49:42 +00003535/// parseDirectiveCVStringTable
3536/// ::= .cv_stringtable
3537bool AsmParser::parseDirectiveCVStringTable() {
3538 getStreamer().EmitCVStringTableDirective();
3539 return false;
3540}
3541
3542/// parseDirectiveCVFileChecksums
3543/// ::= .cv_filechecksums
3544bool AsmParser::parseDirectiveCVFileChecksums() {
3545 getStreamer().EmitCVFileChecksumsDirective();
3546 return false;
3547}
3548
Jim Grosbach4b905842013-09-20 23:08:21 +00003549/// parseDirectiveCFISections
Eli Bendersky17233942013-01-15 22:59:42 +00003550/// ::= .cfi_sections section [, section]
Jim Grosbach4b905842013-09-20 23:08:21 +00003551bool AsmParser::parseDirectiveCFISections() {
Eli Bendersky17233942013-01-15 22:59:42 +00003552 StringRef Name;
3553 bool EH = false;
3554 bool Debug = false;
3555
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003556 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003557 return TokError("Expected an identifier");
3558
3559 if (Name == ".eh_frame")
3560 EH = true;
3561 else if (Name == ".debug_frame")
3562 Debug = true;
3563
3564 if (getLexer().is(AsmToken::Comma)) {
3565 Lex();
3566
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003567 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003568 return TokError("Expected an identifier");
3569
3570 if (Name == ".eh_frame")
3571 EH = true;
3572 else if (Name == ".debug_frame")
3573 Debug = true;
3574 }
3575
3576 getStreamer().EmitCFISections(EH, Debug);
3577 return false;
3578}
3579
Jim Grosbach4b905842013-09-20 23:08:21 +00003580/// parseDirectiveCFIStartProc
David Majnemere035cf92014-01-27 17:20:25 +00003581/// ::= .cfi_startproc [simple]
Jim Grosbach4b905842013-09-20 23:08:21 +00003582bool AsmParser::parseDirectiveCFIStartProc() {
David Majnemere035cf92014-01-27 17:20:25 +00003583 StringRef Simple;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003584 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
3585 if (check(parseIdentifier(Simple) || Simple != "simple",
3586 "unexpected token") ||
3587 parseToken(AsmToken::EndOfStatement))
3588 return addErrorSuffix(" in '.cfi_startproc' directive");
3589 }
Nirav Davea645433c2016-07-18 15:24:03 +00003590
Oliver Stannardcf6bfb12014-11-03 12:19:03 +00003591 getStreamer().EmitCFIStartProc(!Simple.empty());
Eli Bendersky17233942013-01-15 22:59:42 +00003592 return false;
3593}
3594
Jim Grosbach4b905842013-09-20 23:08:21 +00003595/// parseDirectiveCFIEndProc
Eli Bendersky17233942013-01-15 22:59:42 +00003596/// ::= .cfi_endproc
Jim Grosbach4b905842013-09-20 23:08:21 +00003597bool AsmParser::parseDirectiveCFIEndProc() {
Eli Bendersky17233942013-01-15 22:59:42 +00003598 getStreamer().EmitCFIEndProc();
3599 return false;
3600}
3601
Jim Grosbach4b905842013-09-20 23:08:21 +00003602/// \brief parse register name or number.
3603bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
Eli Bendersky17233942013-01-15 22:59:42 +00003604 SMLoc DirectiveLoc) {
3605 unsigned RegNo;
3606
3607 if (getLexer().isNot(AsmToken::Integer)) {
3608 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
3609 return true;
Bill Wendlingbc07a892013-06-18 07:20:20 +00003610 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
Eli Bendersky17233942013-01-15 22:59:42 +00003611 } else
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003612 return parseAbsoluteExpression(Register);
Eli Bendersky17233942013-01-15 22:59:42 +00003613
3614 return false;
3615}
3616
Jim Grosbach4b905842013-09-20 23:08:21 +00003617/// parseDirectiveCFIDefCfa
Eli Bendersky17233942013-01-15 22:59:42 +00003618/// ::= .cfi_def_cfa register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003619bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003620 int64_t Register = 0, Offset = 0;
3621 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3622 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3623 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003624 return true;
3625
3626 getStreamer().EmitCFIDefCfa(Register, Offset);
3627 return false;
3628}
3629
Jim Grosbach4b905842013-09-20 23:08:21 +00003630/// parseDirectiveCFIDefCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003631/// ::= .cfi_def_cfa_offset offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003632bool AsmParser::parseDirectiveCFIDefCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00003633 int64_t Offset = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003634 if (parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003635 return true;
3636
3637 getStreamer().EmitCFIDefCfaOffset(Offset);
3638 return false;
3639}
3640
Jim Grosbach4b905842013-09-20 23:08:21 +00003641/// parseDirectiveCFIRegister
Eli Bendersky17233942013-01-15 22:59:42 +00003642/// ::= .cfi_register register, register
Jim Grosbach4b905842013-09-20 23:08:21 +00003643bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003644 int64_t Register1 = 0, Register2 = 0;
3645 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc) ||
3646 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3647 parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003648 return true;
3649
3650 getStreamer().EmitCFIRegister(Register1, Register2);
3651 return false;
3652}
3653
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00003654/// parseDirectiveCFIWindowSave
3655/// ::= .cfi_window_save
3656bool AsmParser::parseDirectiveCFIWindowSave() {
3657 getStreamer().EmitCFIWindowSave();
3658 return false;
3659}
3660
Jim Grosbach4b905842013-09-20 23:08:21 +00003661/// parseDirectiveCFIAdjustCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003662/// ::= .cfi_adjust_cfa_offset adjustment
Jim Grosbach4b905842013-09-20 23:08:21 +00003663bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00003664 int64_t Adjustment = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003665 if (parseAbsoluteExpression(Adjustment))
Eli Bendersky17233942013-01-15 22:59:42 +00003666 return true;
3667
3668 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3669 return false;
3670}
3671
Jim Grosbach4b905842013-09-20 23:08:21 +00003672/// parseDirectiveCFIDefCfaRegister
Eli Bendersky17233942013-01-15 22:59:42 +00003673/// ::= .cfi_def_cfa_register register
Jim Grosbach4b905842013-09-20 23:08:21 +00003674bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003675 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003676 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003677 return true;
3678
3679 getStreamer().EmitCFIDefCfaRegister(Register);
3680 return false;
3681}
3682
Jim Grosbach4b905842013-09-20 23:08:21 +00003683/// parseDirectiveCFIOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003684/// ::= .cfi_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003685bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003686 int64_t Register = 0;
3687 int64_t Offset = 0;
3688
Nirav Davea645433c2016-07-18 15:24:03 +00003689 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3690 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3691 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003692 return true;
3693
3694 getStreamer().EmitCFIOffset(Register, Offset);
3695 return false;
3696}
3697
Jim Grosbach4b905842013-09-20 23:08:21 +00003698/// parseDirectiveCFIRelOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003699/// ::= .cfi_rel_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003700bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003701 int64_t Register = 0, Offset = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003702
Nirav Davea645433c2016-07-18 15:24:03 +00003703 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3704 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3705 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003706 return true;
3707
3708 getStreamer().EmitCFIRelOffset(Register, Offset);
3709 return false;
3710}
3711
3712static bool isValidEncoding(int64_t Encoding) {
3713 if (Encoding & ~0xff)
3714 return false;
3715
3716 if (Encoding == dwarf::DW_EH_PE_omit)
3717 return true;
3718
3719 const unsigned Format = Encoding & 0xf;
3720 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3721 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3722 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3723 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3724 return false;
3725
3726 const unsigned Application = Encoding & 0x70;
3727 if (Application != dwarf::DW_EH_PE_absptr &&
3728 Application != dwarf::DW_EH_PE_pcrel)
3729 return false;
3730
3731 return true;
3732}
3733
Jim Grosbach4b905842013-09-20 23:08:21 +00003734/// parseDirectiveCFIPersonalityOrLsda
Eli Bendersky17233942013-01-15 22:59:42 +00003735/// IsPersonality true for cfi_personality, false for cfi_lsda
3736/// ::= .cfi_personality encoding, [symbol_name]
3737/// ::= .cfi_lsda encoding, [symbol_name]
Jim Grosbach4b905842013-09-20 23:08:21 +00003738bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
Eli Bendersky17233942013-01-15 22:59:42 +00003739 int64_t Encoding = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003740 if (parseAbsoluteExpression(Encoding))
Eli Bendersky17233942013-01-15 22:59:42 +00003741 return true;
3742 if (Encoding == dwarf::DW_EH_PE_omit)
3743 return false;
3744
Eli Bendersky17233942013-01-15 22:59:42 +00003745 StringRef Name;
Nirav Davea645433c2016-07-18 15:24:03 +00003746 if (check(!isValidEncoding(Encoding), "unsupported encoding.") ||
3747 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3748 check(parseIdentifier(Name), "expected identifier in directive"))
3749 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003750
Jim Grosbach6f482002015-05-18 18:43:14 +00003751 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Eli Bendersky17233942013-01-15 22:59:42 +00003752
3753 if (IsPersonality)
3754 getStreamer().EmitCFIPersonality(Sym, Encoding);
3755 else
3756 getStreamer().EmitCFILsda(Sym, Encoding);
3757 return false;
3758}
3759
Jim Grosbach4b905842013-09-20 23:08:21 +00003760/// parseDirectiveCFIRememberState
Eli Bendersky17233942013-01-15 22:59:42 +00003761/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00003762bool AsmParser::parseDirectiveCFIRememberState() {
Eli Bendersky17233942013-01-15 22:59:42 +00003763 getStreamer().EmitCFIRememberState();
3764 return false;
3765}
3766
Jim Grosbach4b905842013-09-20 23:08:21 +00003767/// parseDirectiveCFIRestoreState
Eli Bendersky17233942013-01-15 22:59:42 +00003768/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00003769bool AsmParser::parseDirectiveCFIRestoreState() {
Eli Bendersky17233942013-01-15 22:59:42 +00003770 getStreamer().EmitCFIRestoreState();
3771 return false;
3772}
3773
Jim Grosbach4b905842013-09-20 23:08:21 +00003774/// parseDirectiveCFISameValue
Eli Bendersky17233942013-01-15 22:59:42 +00003775/// ::= .cfi_same_value register
Jim Grosbach4b905842013-09-20 23:08:21 +00003776bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003777 int64_t Register = 0;
3778
Jim Grosbach4b905842013-09-20 23:08:21 +00003779 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003780 return true;
3781
3782 getStreamer().EmitCFISameValue(Register);
3783 return false;
3784}
3785
Jim Grosbach4b905842013-09-20 23:08:21 +00003786/// parseDirectiveCFIRestore
Eli Bendersky17233942013-01-15 22:59:42 +00003787/// ::= .cfi_restore register
Jim Grosbach4b905842013-09-20 23:08:21 +00003788bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003789 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003790 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003791 return true;
3792
3793 getStreamer().EmitCFIRestore(Register);
3794 return false;
3795}
3796
Jim Grosbach4b905842013-09-20 23:08:21 +00003797/// parseDirectiveCFIEscape
Eli Bendersky17233942013-01-15 22:59:42 +00003798/// ::= .cfi_escape expression[,...]
Jim Grosbach4b905842013-09-20 23:08:21 +00003799bool AsmParser::parseDirectiveCFIEscape() {
Eli Bendersky17233942013-01-15 22:59:42 +00003800 std::string Values;
3801 int64_t CurrValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003802 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00003803 return true;
3804
3805 Values.push_back((uint8_t)CurrValue);
3806
3807 while (getLexer().is(AsmToken::Comma)) {
3808 Lex();
3809
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003810 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00003811 return true;
3812
3813 Values.push_back((uint8_t)CurrValue);
3814 }
3815
3816 getStreamer().EmitCFIEscape(Values);
3817 return false;
3818}
3819
Jim Grosbach4b905842013-09-20 23:08:21 +00003820/// parseDirectiveCFISignalFrame
Eli Bendersky17233942013-01-15 22:59:42 +00003821/// ::= .cfi_signal_frame
Jim Grosbach4b905842013-09-20 23:08:21 +00003822bool AsmParser::parseDirectiveCFISignalFrame() {
Nirav Davea645433c2016-07-18 15:24:03 +00003823 if (parseToken(AsmToken::EndOfStatement,
3824 "unexpected token in '.cfi_signal_frame'"))
3825 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003826
3827 getStreamer().EmitCFISignalFrame();
3828 return false;
3829}
3830
Jim Grosbach4b905842013-09-20 23:08:21 +00003831/// parseDirectiveCFIUndefined
Eli Bendersky17233942013-01-15 22:59:42 +00003832/// ::= .cfi_undefined register
Jim Grosbach4b905842013-09-20 23:08:21 +00003833bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003834 int64_t Register = 0;
3835
Jim Grosbach4b905842013-09-20 23:08:21 +00003836 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003837 return true;
3838
3839 getStreamer().EmitCFIUndefined(Register);
3840 return false;
3841}
3842
Jim Grosbach4b905842013-09-20 23:08:21 +00003843/// parseDirectiveMacrosOnOff
Eli Bendersky17233942013-01-15 22:59:42 +00003844/// ::= .macros_on
3845/// ::= .macros_off
Jim Grosbach4b905842013-09-20 23:08:21 +00003846bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
Nirav Davea645433c2016-07-18 15:24:03 +00003847 if (parseToken(AsmToken::EndOfStatement,
3848 "unexpected token in '" + Directive + "' directive"))
3849 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003850
Jim Grosbach4b905842013-09-20 23:08:21 +00003851 setMacrosEnabled(Directive == ".macros_on");
Eli Bendersky17233942013-01-15 22:59:42 +00003852 return false;
3853}
3854
Jim Grosbach4b905842013-09-20 23:08:21 +00003855/// parseDirectiveMacro
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00003856/// ::= .macro name[,] [parameters]
Jim Grosbach4b905842013-09-20 23:08:21 +00003857bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003858 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003859 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003860 return TokError("expected identifier in '.macro' directive");
3861
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00003862 if (getLexer().is(AsmToken::Comma))
3863 Lex();
3864
Eli Bendersky17233942013-01-15 22:59:42 +00003865 MCAsmMacroParameters Parameters;
David Majnemer91fc4c22014-01-29 18:57:46 +00003866 while (getLexer().isNot(AsmToken::EndOfStatement)) {
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003867
Alexander Kornienko8c0809c2015-01-15 11:41:30 +00003868 if (!Parameters.empty() && Parameters.back().Vararg)
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003869 return Error(Lexer.getLoc(),
3870 "Vararg parameter '" + Parameters.back().Name +
3871 "' should be last one in the list of parameters.");
3872
David Majnemer91fc4c22014-01-29 18:57:46 +00003873 MCAsmMacroParameter Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00003874 if (parseIdentifier(Parameter.Name))
David Majnemer91fc4c22014-01-29 18:57:46 +00003875 return TokError("expected identifier in '.macro' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003876
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003877 if (Lexer.is(AsmToken::Colon)) {
3878 Lex(); // consume ':'
3879
3880 SMLoc QualLoc;
3881 StringRef Qualifier;
3882
3883 QualLoc = Lexer.getLoc();
3884 if (parseIdentifier(Qualifier))
3885 return Error(QualLoc, "missing parameter qualifier for "
3886 "'" + Parameter.Name + "' in macro '" + Name + "'");
3887
3888 if (Qualifier == "req")
3889 Parameter.Required = true;
Kevin Enderbye3c13462014-08-04 23:14:37 +00003890 else if (Qualifier == "vararg")
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003891 Parameter.Vararg = true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003892 else
3893 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
3894 "for '" + Parameter.Name + "' in macro '" + Name + "'");
3895 }
3896
David Majnemer91fc4c22014-01-29 18:57:46 +00003897 if (getLexer().is(AsmToken::Equal)) {
3898 Lex();
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003899
3900 SMLoc ParamLoc;
3901
3902 ParamLoc = Lexer.getLoc();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003903 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
David Majnemer91fc4c22014-01-29 18:57:46 +00003904 return true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003905
3906 if (Parameter.Required)
3907 Warning(ParamLoc, "pointless default value for required parameter "
3908 "'" + Parameter.Name + "' in macro '" + Name + "'");
Eli Bendersky17233942013-01-15 22:59:42 +00003909 }
David Majnemer91fc4c22014-01-29 18:57:46 +00003910
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00003911 Parameters.push_back(std::move(Parameter));
David Majnemer91fc4c22014-01-29 18:57:46 +00003912
3913 if (getLexer().is(AsmToken::Comma))
3914 Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00003915 }
3916
Nirav Dave1180e6892016-06-02 17:15:05 +00003917 // Eat just the end of statement.
3918 Lexer.Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00003919
Nirav Dave1180e6892016-06-02 17:15:05 +00003920 // Consuming deferred text, so use Lexer.Lex to ignore Lexing Errors
Eli Bendersky17233942013-01-15 22:59:42 +00003921 AsmToken EndToken, StartToken = getTok();
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00003922 unsigned MacroDepth = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003923 // Lex the macro definition.
Eugene Zelenko33d7b762016-08-23 17:14:32 +00003924 while (true) {
Nirav Dave1180e6892016-06-02 17:15:05 +00003925 // Ignore Lexing errors in macros.
3926 while (Lexer.is(AsmToken::Error)) {
3927 Lexer.Lex();
3928 }
3929
Eli Bendersky17233942013-01-15 22:59:42 +00003930 // Check whether we have reached the end of the file.
3931 if (getLexer().is(AsmToken::Eof))
3932 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3933
3934 // Otherwise, check whether we have reach the .endmacro.
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00003935 if (getLexer().is(AsmToken::Identifier)) {
3936 if (getTok().getIdentifier() == ".endm" ||
3937 getTok().getIdentifier() == ".endmacro") {
3938 if (MacroDepth == 0) { // Outermost macro.
3939 EndToken = getTok();
Nirav Dave1180e6892016-06-02 17:15:05 +00003940 Lexer.Lex();
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00003941 if (getLexer().isNot(AsmToken::EndOfStatement))
3942 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3943 "' directive");
3944 break;
3945 } else {
3946 // Otherwise we just found the end of an inner macro.
3947 --MacroDepth;
3948 }
3949 } else if (getTok().getIdentifier() == ".macro") {
3950 // We allow nested macros. Those aren't instantiated until the outermost
3951 // macro is expanded so just ignore them for now.
3952 ++MacroDepth;
3953 }
Eli Bendersky17233942013-01-15 22:59:42 +00003954 }
3955
3956 // Otherwise, scan til the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003957 eatToEndOfStatement();
Eli Bendersky17233942013-01-15 22:59:42 +00003958 }
3959
Jim Grosbach4b905842013-09-20 23:08:21 +00003960 if (lookupMacro(Name)) {
Eli Bendersky17233942013-01-15 22:59:42 +00003961 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3962 }
3963
3964 const char *BodyStart = StartToken.getLoc().getPointer();
3965 const char *BodyEnd = EndToken.getLoc().getPointer();
3966 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Jim Grosbach4b905842013-09-20 23:08:21 +00003967 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00003968 defineMacro(Name, MCAsmMacro(Name, Body, std::move(Parameters)));
Eli Bendersky17233942013-01-15 22:59:42 +00003969 return false;
3970}
3971
Jim Grosbach4b905842013-09-20 23:08:21 +00003972/// checkForBadMacro
Kevin Enderby81c944c2013-01-22 21:44:53 +00003973///
3974/// With the support added for named parameters there may be code out there that
3975/// is transitioning from positional parameters. In versions of gas that did
Alp Tokercb402912014-01-24 17:20:08 +00003976/// not support named parameters they would be ignored on the macro definition.
Kevin Enderby81c944c2013-01-22 21:44:53 +00003977/// But to support both styles of parameters this is not possible so if a macro
Alp Tokercb402912014-01-24 17:20:08 +00003978/// definition has named parameters but does not use them and has what appears
Kevin Enderby81c944c2013-01-22 21:44:53 +00003979/// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3980/// warning that the positional parameter found in body which have no effect.
3981/// Hoping the developer will either remove the named parameters from the macro
Alp Tokercb402912014-01-24 17:20:08 +00003982/// definition so the positional parameters get used if that was what was
Kevin Enderby81c944c2013-01-22 21:44:53 +00003983/// intended or change the macro to use the named parameters. It is possible
3984/// this warning will trigger when the none of the named parameters are used
3985/// and the strings like $1 are infact to simply to be passed trough unchanged.
Jim Grosbach4b905842013-09-20 23:08:21 +00003986void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
Kevin Enderby81c944c2013-01-22 21:44:53 +00003987 StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00003988 ArrayRef<MCAsmMacroParameter> Parameters) {
Kevin Enderby81c944c2013-01-22 21:44:53 +00003989 // If this macro is not defined with named parameters the warning we are
3990 // checking for here doesn't apply.
3991 unsigned NParameters = Parameters.size();
3992 if (NParameters == 0)
3993 return;
3994
3995 bool NamedParametersFound = false;
3996 bool PositionalParametersFound = false;
3997
3998 // Look at the body of the macro for use of both the named parameters and what
3999 // are likely to be positional parameters. This is what expandMacro() is
4000 // doing when it finds the parameters in the body.
4001 while (!Body.empty()) {
4002 // Scan for the next possible parameter.
4003 std::size_t End = Body.size(), Pos = 0;
4004 for (; Pos != End; ++Pos) {
4005 // Check for a substitution or escape.
4006 // This macro is defined with parameters, look for \foo, \bar, etc.
4007 if (Body[Pos] == '\\' && Pos + 1 != End)
4008 break;
4009
4010 // This macro should have parameters, but look for $0, $1, ..., $n too.
4011 if (Body[Pos] != '$' || Pos + 1 == End)
4012 continue;
4013 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00004014 if (Next == '$' || Next == 'n' ||
4015 isdigit(static_cast<unsigned char>(Next)))
Kevin Enderby81c944c2013-01-22 21:44:53 +00004016 break;
4017 }
4018
4019 // Check if we reached the end.
4020 if (Pos == End)
4021 break;
4022
4023 if (Body[Pos] == '$') {
Jim Grosbach4b905842013-09-20 23:08:21 +00004024 switch (Body[Pos + 1]) {
4025 // $$ => $
Kevin Enderby81c944c2013-01-22 21:44:53 +00004026 case '$':
4027 break;
4028
Jim Grosbach4b905842013-09-20 23:08:21 +00004029 // $n => number of arguments
Kevin Enderby81c944c2013-01-22 21:44:53 +00004030 case 'n':
4031 PositionalParametersFound = true;
4032 break;
4033
Jim Grosbach4b905842013-09-20 23:08:21 +00004034 // $[0-9] => argument
Kevin Enderby81c944c2013-01-22 21:44:53 +00004035 default: {
4036 PositionalParametersFound = true;
4037 break;
Jim Grosbach4b905842013-09-20 23:08:21 +00004038 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00004039 }
4040 Pos += 2;
4041 } else {
4042 unsigned I = Pos + 1;
4043 while (isIdentifierChar(Body[I]) && I + 1 != End)
4044 ++I;
4045
Jim Grosbach4b905842013-09-20 23:08:21 +00004046 const char *Begin = Body.data() + Pos + 1;
4047 StringRef Argument(Begin, I - (Pos + 1));
Kevin Enderby81c944c2013-01-22 21:44:53 +00004048 unsigned Index = 0;
4049 for (; Index < NParameters; ++Index)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00004050 if (Parameters[Index].Name == Argument)
Kevin Enderby81c944c2013-01-22 21:44:53 +00004051 break;
4052
4053 if (Index == NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00004054 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
4055 Pos += 3;
4056 else {
4057 Pos = I;
4058 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00004059 } else {
4060 NamedParametersFound = true;
4061 Pos += 1 + Argument.size();
4062 }
4063 }
4064 // Update the scan point.
4065 Body = Body.substr(Pos);
4066 }
4067
4068 if (!NamedParametersFound && PositionalParametersFound)
4069 Warning(DirectiveLoc, "macro defined with named parameters which are not "
4070 "used in macro body, possible positional parameter "
4071 "found in body which will have no effect");
4072}
4073
Nico Weber155dccd12014-07-24 17:08:39 +00004074/// parseDirectiveExitMacro
4075/// ::= .exitm
4076bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
Nirav Davea645433c2016-07-18 15:24:03 +00004077 if (parseToken(AsmToken::EndOfStatement,
4078 "unexpected token in '" + Directive + "' directive"))
4079 return true;
Nico Weber155dccd12014-07-24 17:08:39 +00004080
4081 if (!isInsideMacroInstantiation())
4082 return TokError("unexpected '" + Directive + "' in file, "
4083 "no current macro definition");
4084
4085 // Exit all conditionals that are active in the current macro.
4086 while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
4087 TheCondState = TheCondStack.back();
4088 TheCondStack.pop_back();
4089 }
4090
4091 handleMacroExit();
4092 return false;
4093}
4094
Jim Grosbach4b905842013-09-20 23:08:21 +00004095/// parseDirectiveEndMacro
Eli Bendersky17233942013-01-15 22:59:42 +00004096/// ::= .endm
4097/// ::= .endmacro
Jim Grosbach4b905842013-09-20 23:08:21 +00004098bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
Eli Bendersky17233942013-01-15 22:59:42 +00004099 if (getLexer().isNot(AsmToken::EndOfStatement))
4100 return TokError("unexpected token in '" + Directive + "' directive");
4101
4102 // If we are inside a macro instantiation, terminate the current
4103 // instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00004104 if (isInsideMacroInstantiation()) {
4105 handleMacroExit();
Eli Bendersky17233942013-01-15 22:59:42 +00004106 return false;
4107 }
4108
4109 // Otherwise, this .endmacro is a stray entry in the file; well formed
4110 // .endmacro directives are handled during the macro definition parsing.
4111 return TokError("unexpected '" + Directive + "' in file, "
Jim Grosbach4b905842013-09-20 23:08:21 +00004112 "no current macro definition");
Eli Bendersky17233942013-01-15 22:59:42 +00004113}
4114
Jim Grosbach4b905842013-09-20 23:08:21 +00004115/// parseDirectivePurgeMacro
Eli Bendersky17233942013-01-15 22:59:42 +00004116/// ::= .purgem
Jim Grosbach4b905842013-09-20 23:08:21 +00004117bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004118 StringRef Name;
Nirav Davea645433c2016-07-18 15:24:03 +00004119 SMLoc Loc;
Nirav Daved8858ca2016-08-30 14:15:43 +00004120 if (parseTokenLoc(Loc) ||
4121 check(parseIdentifier(Name), Loc,
4122 "expected identifier in '.purgem' directive") ||
Nirav Davea645433c2016-07-18 15:24:03 +00004123 parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00004124 "unexpected token in '.purgem' directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00004125 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004126
Nirav Dave1ab71992016-07-18 19:35:21 +00004127 if (!lookupMacro(Name))
4128 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
4129
Jim Grosbach4b905842013-09-20 23:08:21 +00004130 undefineMacro(Name);
Eli Bendersky17233942013-01-15 22:59:42 +00004131 return false;
4132}
Eli Benderskyf483ff92012-12-20 19:05:53 +00004133
Jim Grosbach4b905842013-09-20 23:08:21 +00004134/// parseDirectiveBundleAlignMode
Eli Benderskyf483ff92012-12-20 19:05:53 +00004135/// ::= {.bundle_align_mode} expression
Jim Grosbach4b905842013-09-20 23:08:21 +00004136bool AsmParser::parseDirectiveBundleAlignMode() {
Eli Benderskyf483ff92012-12-20 19:05:53 +00004137 // Expect a single argument: an expression that evaluates to a constant
4138 // in the inclusive range 0-30.
4139 SMLoc ExprLoc = getLexer().getLoc();
4140 int64_t AlignSizePow2;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004141 if (checkForValidSection() || parseAbsoluteExpression(AlignSizePow2) ||
Nirav Davea645433c2016-07-18 15:24:03 +00004142 parseToken(AsmToken::EndOfStatement, "unexpected token after expression "
4143 "in '.bundle_align_mode' "
4144 "directive") ||
4145 check(AlignSizePow2 < 0 || AlignSizePow2 > 30, ExprLoc,
4146 "invalid bundle alignment size (expected between 0 and 30)"))
Eli Benderskyf483ff92012-12-20 19:05:53 +00004147 return true;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004148
4149 // Because of AlignSizePow2's verified range we can safely truncate it to
4150 // unsigned.
4151 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
4152 return false;
4153}
4154
Jim Grosbach4b905842013-09-20 23:08:21 +00004155/// parseDirectiveBundleLock
Eli Bendersky802b6282013-01-07 21:51:08 +00004156/// ::= {.bundle_lock} [align_to_end]
Jim Grosbach4b905842013-09-20 23:08:21 +00004157bool AsmParser::parseDirectiveBundleLock() {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004158 if (checkForValidSection())
4159 return true;
Eli Bendersky802b6282013-01-07 21:51:08 +00004160 bool AlignToEnd = false;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004161
Nirav Dave1a9044b2016-10-24 14:35:29 +00004162 StringRef Option;
4163 SMLoc Loc = getTok().getLoc();
4164 const char *kInvalidOptionError =
4165 "invalid option for '.bundle_lock' directive";
Eli Bendersky802b6282013-01-07 21:51:08 +00004166
Nirav Dave1a9044b2016-10-24 14:35:29 +00004167 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
Nirav Davea645433c2016-07-18 15:24:03 +00004168 if (check(parseIdentifier(Option), Loc, kInvalidOptionError) ||
4169 check(Option != "align_to_end", Loc, kInvalidOptionError) ||
Nirav Dave1a9044b2016-10-24 14:35:29 +00004170 parseToken(AsmToken::EndOfStatement,
4171 "unexpected token after '.bundle_lock' directive option"))
Nirav Davea645433c2016-07-18 15:24:03 +00004172 return true;
Eli Bendersky802b6282013-01-07 21:51:08 +00004173 AlignToEnd = true;
4174 }
4175
Eli Bendersky802b6282013-01-07 21:51:08 +00004176 getStreamer().EmitBundleLock(AlignToEnd);
Eli Benderskyf483ff92012-12-20 19:05:53 +00004177 return false;
4178}
4179
Jim Grosbach4b905842013-09-20 23:08:21 +00004180/// parseDirectiveBundleLock
Eli Benderskyf483ff92012-12-20 19:05:53 +00004181/// ::= {.bundle_lock}
Jim Grosbach4b905842013-09-20 23:08:21 +00004182bool AsmParser::parseDirectiveBundleUnlock() {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004183 if (checkForValidSection() ||
4184 parseToken(AsmToken::EndOfStatement,
Nirav Davea645433c2016-07-18 15:24:03 +00004185 "unexpected token in '.bundle_unlock' directive"))
4186 return true;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004187
4188 getStreamer().EmitBundleUnlock();
4189 return false;
4190}
4191
Jim Grosbach4b905842013-09-20 23:08:21 +00004192/// parseDirectiveSpace
Eli Bendersky17233942013-01-15 22:59:42 +00004193/// ::= (.skip | .space) expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004194bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
Eli Bendersky17233942013-01-15 22:59:42 +00004195
Petr Hosek67a94a72016-05-28 05:57:48 +00004196 SMLoc NumBytesLoc = Lexer.getLoc();
4197 const MCExpr *NumBytes;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004198 if (checkForValidSection() || parseExpression(NumBytes))
Eli Bendersky17233942013-01-15 22:59:42 +00004199 return true;
4200
4201 int64_t FillExpr = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00004202 if (parseOptionalToken(AsmToken::Comma))
4203 if (parseAbsoluteExpression(FillExpr))
4204 return addErrorSuffix("in '" + Twine(IDVal) + "' directive");
4205 if (parseToken(AsmToken::EndOfStatement))
4206 return addErrorSuffix("in '" + Twine(IDVal) + "' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00004207
Eli Bendersky17233942013-01-15 22:59:42 +00004208 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
Petr Hosek67a94a72016-05-28 05:57:48 +00004209 getStreamer().emitFill(*NumBytes, FillExpr, NumBytesLoc);
Eli Bendersky17233942013-01-15 22:59:42 +00004210
4211 return false;
4212}
4213
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004214/// parseDirectiveDCB
4215/// ::= .dcb.{b, l, w} expression, expression
4216bool AsmParser::parseDirectiveDCB(StringRef IDVal, unsigned Size) {
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004217 SMLoc NumValuesLoc = Lexer.getLoc();
4218 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004219 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004220 return true;
4221
4222 if (NumValues < 0) {
4223 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4224 return false;
4225 }
4226
4227 if (parseToken(AsmToken::Comma,
4228 "unexpected token in '" + Twine(IDVal) + "' directive"))
4229 return true;
4230
4231 const MCExpr *Value;
4232 SMLoc ExprLoc = getLexer().getLoc();
4233 if (parseExpression(Value))
4234 return true;
4235
4236 // Special case constant expressions to match code generator.
4237 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
4238 assert(Size <= 8 && "Invalid size");
4239 uint64_t IntValue = MCE->getValue();
4240 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
4241 return Error(ExprLoc, "literal value out of range for directive");
4242 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4243 getStreamer().EmitIntValue(IntValue, Size);
4244 } else {
4245 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4246 getStreamer().EmitValue(Value, Size, ExprLoc);
4247 }
4248
4249 if (parseToken(AsmToken::EndOfStatement,
4250 "unexpected token in '" + Twine(IDVal) + "' directive"))
4251 return true;
4252
4253 return false;
4254}
4255
4256/// parseDirectiveRealDCB
4257/// ::= .dcb.{d, s} expression, expression
4258bool AsmParser::parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &Semantics) {
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004259 SMLoc NumValuesLoc = Lexer.getLoc();
4260 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004261 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004262 return true;
4263
4264 if (NumValues < 0) {
4265 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4266 return false;
4267 }
4268
4269 if (parseToken(AsmToken::Comma,
4270 "unexpected token in '" + Twine(IDVal) + "' directive"))
4271 return true;
4272
4273 APInt AsInt;
4274 if (parseRealValue(Semantics, AsInt))
4275 return true;
4276
4277 if (parseToken(AsmToken::EndOfStatement,
4278 "unexpected token in '" + Twine(IDVal) + "' directive"))
4279 return true;
4280
4281 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4282 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
4283 AsInt.getBitWidth() / 8);
4284
4285 return false;
4286}
4287
Petr Hosek85b2f672016-09-23 21:53:36 +00004288/// parseDirectiveDS
4289/// ::= .ds.{b, d, l, p, s, w, x} expression
4290bool AsmParser::parseDirectiveDS(StringRef IDVal, unsigned Size) {
Petr Hosek85b2f672016-09-23 21:53:36 +00004291
4292 SMLoc NumValuesLoc = Lexer.getLoc();
4293 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004294 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek85b2f672016-09-23 21:53:36 +00004295 return true;
4296
4297 if (NumValues < 0) {
4298 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4299 return false;
4300 }
4301
4302 if (parseToken(AsmToken::EndOfStatement,
4303 "unexpected token in '" + Twine(IDVal) + "' directive"))
4304 return true;
4305
4306 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4307 getStreamer().emitFill(Size, 0);
4308
4309 return false;
4310}
4311
Jim Grosbach4b905842013-09-20 23:08:21 +00004312/// parseDirectiveLEB128
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004313/// ::= (.sleb128 | .uleb128) [ expression (, expression)* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004314bool AsmParser::parseDirectiveLEB128(bool Signed) {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004315 if (checkForValidSection())
4316 return true;
4317
Nirav Dave1a9044b2016-10-24 14:35:29 +00004318 auto parseOp = [&]() -> bool {
4319 const MCExpr *Value;
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004320 if (parseExpression(Value))
4321 return true;
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004322 if (Signed)
4323 getStreamer().EmitSLEB128Value(Value);
4324 else
4325 getStreamer().EmitULEB128Value(Value);
Nirav Dave1a9044b2016-10-24 14:35:29 +00004326 return false;
4327 };
Eli Bendersky17233942013-01-15 22:59:42 +00004328
Nirav Dave1a9044b2016-10-24 14:35:29 +00004329 if (parseMany(parseOp))
4330 return addErrorSuffix(" in directive");
Eli Bendersky17233942013-01-15 22:59:42 +00004331
4332 return false;
4333}
4334
Jim Grosbach4b905842013-09-20 23:08:21 +00004335/// parseDirectiveSymbolAttribute
Daniel Dunbara5508c82009-06-30 00:33:19 +00004336/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004337bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00004338 auto parseOp = [&]() -> bool {
4339 StringRef Name;
4340 SMLoc Loc = getTok().getLoc();
4341 if (parseIdentifier(Name))
4342 return Error(Loc, "expected identifier");
4343 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004344
Nirav Dave1a9044b2016-10-24 14:35:29 +00004345 // Assembler local symbols don't make any sense here. Complain loudly.
4346 if (Sym->isTemporary())
4347 return Error(Loc, "non-local symbol required");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004348
Nirav Dave1a9044b2016-10-24 14:35:29 +00004349 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
4350 return Error(Loc, "unable to emit symbol attribute");
4351 return false;
4352 };
Daniel Dunbara5508c82009-06-30 00:33:19 +00004353
Nirav Dave1a9044b2016-10-24 14:35:29 +00004354 if (parseMany(parseOp))
4355 return addErrorSuffix(" in directive");
Jan Wen Voungc7682872010-09-30 01:09:20 +00004356 return false;
Daniel Dunbara5508c82009-06-30 00:33:19 +00004357}
Chris Lattnera1e11f52009-07-07 20:30:46 +00004358
Jim Grosbach4b905842013-09-20 23:08:21 +00004359/// parseDirectiveComm
Chris Lattner28ad7542009-07-09 17:25:12 +00004360/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004361bool AsmParser::parseDirectiveComm(bool IsLocal) {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004362 if (checkForValidSection())
4363 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00004364
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004365 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004366 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004367 if (parseIdentifier(Name))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004368 return TokError("expected identifier in directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004369
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +00004370 // Handle the identifier as the key symbol.
Jim Grosbach6f482002015-05-18 18:43:14 +00004371 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Chris Lattnera1e11f52009-07-07 20:30:46 +00004372
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004373 if (getLexer().isNot(AsmToken::Comma))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004374 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00004375 Lex();
Chris Lattnera1e11f52009-07-07 20:30:46 +00004376
4377 int64_t Size;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004378 SMLoc SizeLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004379 if (parseAbsoluteExpression(Size))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004380 return true;
4381
4382 int64_t Pow2Alignment = 0;
4383 SMLoc Pow2AlignmentLoc;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004384 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan686ed8d2010-01-19 20:22:31 +00004385 Lex();
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004386 Pow2AlignmentLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004387 if (parseAbsoluteExpression(Pow2Alignment))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004388 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00004389
Benjamin Kramer68b9f052012-09-07 21:08:01 +00004390 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
4391 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00004392 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
4393
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00004394 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramer68b9f052012-09-07 21:08:01 +00004395 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
4396 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00004397 if (!isPowerOf2_64(Pow2Alignment))
4398 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
4399 Pow2Alignment = Log2_64(Pow2Alignment);
4400 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00004401 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00004402
Nirav Dave1a9044b2016-10-24 14:35:29 +00004403 if (parseToken(AsmToken::EndOfStatement,
4404 "unexpected token in '.comm' or '.lcomm' directive"))
4405 return true;
Chris Lattnera1e11f52009-07-07 20:30:46 +00004406
Chris Lattner28ad7542009-07-09 17:25:12 +00004407 // NOTE: a size of zero for a .comm should create a undefined symbol
4408 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattnera1e11f52009-07-07 20:30:46 +00004409 if (Size < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00004410 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
Jim Grosbach4b905842013-09-20 23:08:21 +00004411 "be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00004412
Eric Christopherbc818852010-05-14 01:38:54 +00004413 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattnera1e11f52009-07-07 20:30:46 +00004414 // may internally end up wanting an alignment in bytes.
4415 // FIXME: Diagnose overflow.
4416 if (Pow2Alignment < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00004417 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
Jim Grosbach4b905842013-09-20 23:08:21 +00004418 "alignment, can't be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00004419
Rafael Espindola13a79bb2017-02-02 21:26:06 +00004420 Sym->redefineIfPossible();
Daniel Dunbar6860ac72009-08-22 07:22:36 +00004421 if (!Sym->isUndefined())
Chris Lattnera1e11f52009-07-07 20:30:46 +00004422 return Error(IDLoc, "invalid symbol redefinition");
4423
Chris Lattner28ad7542009-07-09 17:25:12 +00004424 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00004425 if (IsLocal) {
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00004426 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00004427 return false;
4428 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00004429
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004430 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattnera1e11f52009-07-07 20:30:46 +00004431 return false;
4432}
Chris Lattner07cadaf2009-07-10 22:20:30 +00004433
Jim Grosbach4b905842013-09-20 23:08:21 +00004434/// parseDirectiveAbort
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004435/// ::= .abort [... message ...]
Jim Grosbach4b905842013-09-20 23:08:21 +00004436bool AsmParser::parseDirectiveAbort() {
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004437 // FIXME: Use loc from directive.
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004438 SMLoc Loc = getLexer().getLoc();
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004439
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004440 StringRef Str = parseStringToEndOfStatement();
Nirav Davea645433c2016-07-18 15:24:03 +00004441 if (parseToken(AsmToken::EndOfStatement,
4442 "unexpected token in '.abort' directive"))
4443 return true;
Kevin Enderby56523ce2009-07-13 23:15:14 +00004444
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004445 if (Str.empty())
Nirav Dave2364748a2016-09-16 18:30:20 +00004446 return Error(Loc, ".abort detected. Assembly stopping.");
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004447 else
Nirav Dave2364748a2016-09-16 18:30:20 +00004448 return Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004449 // FIXME: Actually abort assembly here.
Kevin Enderby56523ce2009-07-13 23:15:14 +00004450
4451 return false;
4452}
Kevin Enderbycbe475d2009-07-14 21:35:03 +00004453
Jim Grosbach4b905842013-09-20 23:08:21 +00004454/// parseDirectiveInclude
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004455/// ::= .include "filename"
Jim Grosbach4b905842013-09-20 23:08:21 +00004456bool AsmParser::parseDirectiveInclude() {
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004457 // Allow the strings to have escaped octal character sequence.
4458 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00004459 SMLoc IncludeLoc = getTok().getLoc();
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004460
Nirav Davea645433c2016-07-18 15:24:03 +00004461 if (check(getTok().isNot(AsmToken::String),
4462 "expected string in '.include' directive") ||
4463 parseEscapedString(Filename) ||
4464 check(getTok().isNot(AsmToken::EndOfStatement),
4465 "unexpected token in '.include' directive") ||
4466 // Attempt to switch the lexer to the included file before consuming the
4467 // end of statement to avoid losing it when we switch.
4468 check(enterIncludeFile(Filename), IncludeLoc,
4469 "Could not find include file '" + Filename + "'"))
Chris Lattner693fbb82009-07-16 06:14:39 +00004470 return true;
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004471
4472 return false;
4473}
Kevin Enderby09ea5702009-07-15 15:30:11 +00004474
Jim Grosbach4b905842013-09-20 23:08:21 +00004475/// parseDirectiveIncbin
Petr Hosek2f4ac442016-09-23 00:41:06 +00004476/// ::= .incbin "filename" [ , skip [ , count ] ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004477bool AsmParser::parseDirectiveIncbin() {
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004478 // Allow the strings to have escaped octal character sequence.
4479 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00004480 SMLoc IncbinLoc = getTok().getLoc();
4481 if (check(getTok().isNot(AsmToken::String),
4482 "expected string in '.incbin' directive") ||
Petr Hosek2f4ac442016-09-23 00:41:06 +00004483 parseEscapedString(Filename))
4484 return true;
4485
4486 int64_t Skip = 0;
4487 const MCExpr *Count = nullptr;
4488 SMLoc SkipLoc, CountLoc;
Nirav Dave1a9044b2016-10-24 14:35:29 +00004489 if (parseOptionalToken(AsmToken::Comma)) {
Petr Hosek2f4ac442016-09-23 00:41:06 +00004490 // The skip expression can be omitted while specifying the count, e.g:
4491 // .incbin "filename",,4
4492 if (getTok().isNot(AsmToken::Comma)) {
4493 if (parseTokenLoc(SkipLoc) || parseAbsoluteExpression(Skip))
4494 return true;
4495 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00004496 if (parseOptionalToken(AsmToken::Comma)) {
4497 CountLoc = getTok().getLoc();
4498 if (parseExpression(Count))
Petr Hosek2f4ac442016-09-23 00:41:06 +00004499 return true;
4500 }
4501 }
4502
4503 if (parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00004504 "unexpected token in '.incbin' directive"))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004505 return true;
Nirav Dave1ab71992016-07-18 19:35:21 +00004506
Petr Hosek2f4ac442016-09-23 00:41:06 +00004507 if (check(Skip < 0, SkipLoc, "skip is negative"))
4508 return true;
4509
Nirav Dave1ab71992016-07-18 19:35:21 +00004510 // Attempt to process the included file.
Petr Hosek2f4ac442016-09-23 00:41:06 +00004511 if (processIncbinFile(Filename, Skip, Count, CountLoc))
Nirav Dave1ab71992016-07-18 19:35:21 +00004512 return Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
Kevin Enderby109f25c2011-12-14 21:47:48 +00004513 return false;
4514}
4515
Jim Grosbach4b905842013-09-20 23:08:21 +00004516/// parseDirectiveIf
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004517/// ::= .if{,eq,ge,gt,le,lt,ne} expression
4518bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004519 TheCondStack.push_back(TheCondState);
4520 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004521 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004522 eatToEndOfStatement();
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004523 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004524 int64_t ExprValue;
Nirav Davea645433c2016-07-18 15:24:03 +00004525 if (parseAbsoluteExpression(ExprValue) ||
4526 parseToken(AsmToken::EndOfStatement,
4527 "unexpected token in '.if' directive"))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004528 return true;
4529
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004530 switch (DirKind) {
4531 default:
4532 llvm_unreachable("unsupported directive");
4533 case DK_IF:
4534 case DK_IFNE:
4535 break;
4536 case DK_IFEQ:
4537 ExprValue = ExprValue == 0;
4538 break;
4539 case DK_IFGE:
4540 ExprValue = ExprValue >= 0;
4541 break;
4542 case DK_IFGT:
4543 ExprValue = ExprValue > 0;
4544 break;
4545 case DK_IFLE:
4546 ExprValue = ExprValue <= 0;
4547 break;
4548 case DK_IFLT:
4549 ExprValue = ExprValue < 0;
4550 break;
4551 }
4552
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004553 TheCondState.CondMet = ExprValue;
4554 TheCondState.Ignore = !TheCondState.CondMet;
4555 }
4556
4557 return false;
4558}
4559
Jim Grosbach4b905842013-09-20 23:08:21 +00004560/// parseDirectiveIfb
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004561/// ::= .ifb string
Jim Grosbach4b905842013-09-20 23:08:21 +00004562bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004563 TheCondStack.push_back(TheCondState);
4564 TheCondState.TheCond = AsmCond::IfCond;
4565
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004566 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004567 eatToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004568 } else {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004569 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004570
Nirav Davea645433c2016-07-18 15:24:03 +00004571 if (parseToken(AsmToken::EndOfStatement,
4572 "unexpected token in '.ifb' directive"))
4573 return true;
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004574
4575 TheCondState.CondMet = ExpectBlank == Str.empty();
4576 TheCondState.Ignore = !TheCondState.CondMet;
4577 }
4578
4579 return false;
4580}
4581
Jim Grosbach4b905842013-09-20 23:08:21 +00004582/// parseDirectiveIfc
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004583/// ::= .ifc string1, string2
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00004584/// ::= .ifnc string1, string2
Jim Grosbach4b905842013-09-20 23:08:21 +00004585bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004586 TheCondStack.push_back(TheCondState);
4587 TheCondState.TheCond = AsmCond::IfCond;
4588
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004589 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004590 eatToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004591 } else {
Jim Grosbach4b905842013-09-20 23:08:21 +00004592 StringRef Str1 = parseStringToComma();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004593
Nirav Davea645433c2016-07-18 15:24:03 +00004594 if (parseToken(AsmToken::Comma, "unexpected token in '.ifc' directive"))
4595 return true;
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004596
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004597 StringRef Str2 = parseStringToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004598
Nirav Davea645433c2016-07-18 15:24:03 +00004599 if (parseToken(AsmToken::EndOfStatement,
4600 "unexpected token in '.ifc' directive"))
4601 return true;
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004602
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00004603 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004604 TheCondState.Ignore = !TheCondState.CondMet;
4605 }
4606
4607 return false;
4608}
4609
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004610/// parseDirectiveIfeqs
4611/// ::= .ifeqs string1, string2
Sid Manning51c35602015-03-18 14:20:54 +00004612bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual) {
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004613 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00004614 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00004615 return TokError("expected string parameter for '.ifeqs' directive");
4616 return TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004617 }
4618
4619 StringRef String1 = getTok().getStringContents();
4620 Lex();
4621
4622 if (Lexer.isNot(AsmToken::Comma)) {
Sid Manning51c35602015-03-18 14:20:54 +00004623 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00004624 return TokError(
4625 "expected comma after first string for '.ifeqs' directive");
4626 return TokError("expected comma after first string for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004627 }
4628
4629 Lex();
4630
4631 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00004632 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00004633 return TokError("expected string parameter for '.ifeqs' directive");
4634 return TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004635 }
4636
4637 StringRef String2 = getTok().getStringContents();
4638 Lex();
4639
4640 TheCondStack.push_back(TheCondState);
4641 TheCondState.TheCond = AsmCond::IfCond;
Sid Manning51c35602015-03-18 14:20:54 +00004642 TheCondState.CondMet = ExpectEqual == (String1 == String2);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004643 TheCondState.Ignore = !TheCondState.CondMet;
4644
4645 return false;
4646}
4647
Jim Grosbach4b905842013-09-20 23:08:21 +00004648/// parseDirectiveIfdef
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004649/// ::= .ifdef symbol
Jim Grosbach4b905842013-09-20 23:08:21 +00004650bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004651 StringRef Name;
4652 TheCondStack.push_back(TheCondState);
4653 TheCondState.TheCond = AsmCond::IfCond;
4654
4655 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004656 eatToEndOfStatement();
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004657 } else {
Nirav Davea645433c2016-07-18 15:24:03 +00004658 if (check(parseIdentifier(Name), "expected identifier after '.ifdef'") ||
4659 parseToken(AsmToken::EndOfStatement, "unexpected token in '.ifdef'"))
4660 return true;
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004661
Jim Grosbach6f482002015-05-18 18:43:14 +00004662 MCSymbol *Sym = getContext().lookupSymbol(Name);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004663
4664 if (expect_defined)
Craig Topper353eda42014-04-24 06:44:33 +00004665 TheCondState.CondMet = (Sym && !Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004666 else
Craig Topper353eda42014-04-24 06:44:33 +00004667 TheCondState.CondMet = (!Sym || Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004668 TheCondState.Ignore = !TheCondState.CondMet;
4669 }
4670
4671 return false;
4672}
4673
Jim Grosbach4b905842013-09-20 23:08:21 +00004674/// parseDirectiveElseIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004675/// ::= .elseif expression
Jim Grosbach4b905842013-09-20 23:08:21 +00004676bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004677 if (TheCondState.TheCond != AsmCond::IfCond &&
4678 TheCondState.TheCond != AsmCond::ElseIfCond)
Nirav Dave2364748a2016-09-16 18:30:20 +00004679 return Error(DirectiveLoc, "Encountered a .elseif that doesn't follow an"
4680 " .if or an .elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004681 TheCondState.TheCond = AsmCond::ElseIfCond;
4682
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004683 bool LastIgnoreState = false;
4684 if (!TheCondStack.empty())
Craig Topper2172ad62013-04-22 04:24:02 +00004685 LastIgnoreState = TheCondStack.back().Ignore;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004686 if (LastIgnoreState || TheCondState.CondMet) {
4687 TheCondState.Ignore = true;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004688 eatToEndOfStatement();
Craig Topperf15655b2013-04-22 04:22:40 +00004689 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004690 int64_t ExprValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004691 if (parseAbsoluteExpression(ExprValue))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004692 return true;
4693
Nirav Dave1a9044b2016-10-24 14:35:29 +00004694 if (parseToken(AsmToken::EndOfStatement,
4695 "unexpected token in '.elseif' directive"))
4696 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00004697
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004698 TheCondState.CondMet = ExprValue;
4699 TheCondState.Ignore = !TheCondState.CondMet;
4700 }
4701
4702 return false;
4703}
4704
Jim Grosbach4b905842013-09-20 23:08:21 +00004705/// parseDirectiveElse
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004706/// ::= .else
Jim Grosbach4b905842013-09-20 23:08:21 +00004707bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00004708 if (parseToken(AsmToken::EndOfStatement,
4709 "unexpected token in '.else' directive"))
4710 return true;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004711
4712 if (TheCondState.TheCond != AsmCond::IfCond &&
4713 TheCondState.TheCond != AsmCond::ElseIfCond)
Nirav Dave2364748a2016-09-16 18:30:20 +00004714 return Error(DirectiveLoc, "Encountered a .else that doesn't follow "
4715 " an .if or an .elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004716 TheCondState.TheCond = AsmCond::ElseCond;
4717 bool LastIgnoreState = false;
4718 if (!TheCondStack.empty())
4719 LastIgnoreState = TheCondStack.back().Ignore;
4720 if (LastIgnoreState || TheCondState.CondMet)
4721 TheCondState.Ignore = true;
4722 else
4723 TheCondState.Ignore = false;
4724
4725 return false;
4726}
4727
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004728/// parseDirectiveEnd
4729/// ::= .end
4730bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00004731 if (parseToken(AsmToken::EndOfStatement,
4732 "unexpected token in '.end' directive"))
4733 return true;
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004734
4735 while (Lexer.isNot(AsmToken::Eof))
Nirav Dave1a9044b2016-10-24 14:35:29 +00004736 Lexer.Lex();
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004737
4738 return false;
4739}
4740
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004741/// parseDirectiveError
4742/// ::= .err
4743/// ::= .error [string]
4744bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
4745 if (!TheCondStack.empty()) {
4746 if (TheCondStack.back().Ignore) {
4747 eatToEndOfStatement();
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004748 return false;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004749 }
4750 }
4751
4752 if (!WithMessage)
4753 return Error(L, ".err encountered");
4754
4755 StringRef Message = ".error directive invoked in source file";
4756 if (Lexer.isNot(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00004757 if (Lexer.isNot(AsmToken::String))
4758 return TokError(".error argument must be a string");
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004759
4760 Message = getTok().getStringContents();
4761 Lex();
4762 }
4763
Nirav Dave2364748a2016-09-16 18:30:20 +00004764 return Error(L, Message);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004765}
4766
Nico Weber404012b2014-07-24 16:26:06 +00004767/// parseDirectiveWarning
4768/// ::= .warning [string]
4769bool AsmParser::parseDirectiveWarning(SMLoc L) {
4770 if (!TheCondStack.empty()) {
4771 if (TheCondStack.back().Ignore) {
4772 eatToEndOfStatement();
4773 return false;
4774 }
4775 }
4776
4777 StringRef Message = ".warning directive invoked in source file";
Nirav Dave1a9044b2016-10-24 14:35:29 +00004778
4779 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00004780 if (Lexer.isNot(AsmToken::String))
4781 return TokError(".warning argument must be a string");
Nico Weber404012b2014-07-24 16:26:06 +00004782
4783 Message = getTok().getStringContents();
4784 Lex();
Nirav Dave1a9044b2016-10-24 14:35:29 +00004785 if (parseToken(AsmToken::EndOfStatement,
4786 "expected end of statement in '.warning' directive"))
4787 return true;
Nico Weber404012b2014-07-24 16:26:06 +00004788 }
4789
Nirav Dave2364748a2016-09-16 18:30:20 +00004790 return Warning(L, Message);
Nico Weber404012b2014-07-24 16:26:06 +00004791}
4792
Jim Grosbach4b905842013-09-20 23:08:21 +00004793/// parseDirectiveEndIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004794/// ::= .endif
Jim Grosbach4b905842013-09-20 23:08:21 +00004795bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00004796 if (parseToken(AsmToken::EndOfStatement,
4797 "unexpected token in '.endif' directive"))
4798 return true;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004799
Jim Grosbach4b905842013-09-20 23:08:21 +00004800 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
Nirav Dave2364748a2016-09-16 18:30:20 +00004801 return Error(DirectiveLoc, "Encountered a .endif that doesn't follow "
4802 "an .if or .else");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004803 if (!TheCondStack.empty()) {
4804 TheCondState = TheCondStack.back();
4805 TheCondStack.pop_back();
4806 }
4807
4808 return false;
4809}
Daniel Dunbara4b069c2009-08-11 04:24:50 +00004810
Eli Bendersky17233942013-01-15 22:59:42 +00004811void AsmParser::initializeDirectiveKindMap() {
4812 DirectiveKindMap[".set"] = DK_SET;
4813 DirectiveKindMap[".equ"] = DK_EQU;
4814 DirectiveKindMap[".equiv"] = DK_EQUIV;
4815 DirectiveKindMap[".ascii"] = DK_ASCII;
4816 DirectiveKindMap[".asciz"] = DK_ASCIZ;
4817 DirectiveKindMap[".string"] = DK_STRING;
4818 DirectiveKindMap[".byte"] = DK_BYTE;
4819 DirectiveKindMap[".short"] = DK_SHORT;
4820 DirectiveKindMap[".value"] = DK_VALUE;
4821 DirectiveKindMap[".2byte"] = DK_2BYTE;
4822 DirectiveKindMap[".long"] = DK_LONG;
4823 DirectiveKindMap[".int"] = DK_INT;
4824 DirectiveKindMap[".4byte"] = DK_4BYTE;
4825 DirectiveKindMap[".quad"] = DK_QUAD;
4826 DirectiveKindMap[".8byte"] = DK_8BYTE;
David Woodhoused6de0d92014-02-01 16:20:59 +00004827 DirectiveKindMap[".octa"] = DK_OCTA;
Eli Bendersky17233942013-01-15 22:59:42 +00004828 DirectiveKindMap[".single"] = DK_SINGLE;
4829 DirectiveKindMap[".float"] = DK_FLOAT;
4830 DirectiveKindMap[".double"] = DK_DOUBLE;
4831 DirectiveKindMap[".align"] = DK_ALIGN;
4832 DirectiveKindMap[".align32"] = DK_ALIGN32;
4833 DirectiveKindMap[".balign"] = DK_BALIGN;
4834 DirectiveKindMap[".balignw"] = DK_BALIGNW;
4835 DirectiveKindMap[".balignl"] = DK_BALIGNL;
4836 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
4837 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
4838 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
4839 DirectiveKindMap[".org"] = DK_ORG;
4840 DirectiveKindMap[".fill"] = DK_FILL;
4841 DirectiveKindMap[".zero"] = DK_ZERO;
4842 DirectiveKindMap[".extern"] = DK_EXTERN;
4843 DirectiveKindMap[".globl"] = DK_GLOBL;
4844 DirectiveKindMap[".global"] = DK_GLOBAL;
Eli Bendersky17233942013-01-15 22:59:42 +00004845 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
4846 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
4847 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
4848 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
4849 DirectiveKindMap[".reference"] = DK_REFERENCE;
4850 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
4851 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
4852 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
4853 DirectiveKindMap[".comm"] = DK_COMM;
4854 DirectiveKindMap[".common"] = DK_COMMON;
4855 DirectiveKindMap[".lcomm"] = DK_LCOMM;
4856 DirectiveKindMap[".abort"] = DK_ABORT;
4857 DirectiveKindMap[".include"] = DK_INCLUDE;
4858 DirectiveKindMap[".incbin"] = DK_INCBIN;
4859 DirectiveKindMap[".code16"] = DK_CODE16;
4860 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
4861 DirectiveKindMap[".rept"] = DK_REPT;
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00004862 DirectiveKindMap[".rep"] = DK_REPT;
Eli Bendersky17233942013-01-15 22:59:42 +00004863 DirectiveKindMap[".irp"] = DK_IRP;
4864 DirectiveKindMap[".irpc"] = DK_IRPC;
4865 DirectiveKindMap[".endr"] = DK_ENDR;
4866 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
4867 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
4868 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
4869 DirectiveKindMap[".if"] = DK_IF;
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004870 DirectiveKindMap[".ifeq"] = DK_IFEQ;
4871 DirectiveKindMap[".ifge"] = DK_IFGE;
4872 DirectiveKindMap[".ifgt"] = DK_IFGT;
4873 DirectiveKindMap[".ifle"] = DK_IFLE;
4874 DirectiveKindMap[".iflt"] = DK_IFLT;
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00004875 DirectiveKindMap[".ifne"] = DK_IFNE;
Eli Bendersky17233942013-01-15 22:59:42 +00004876 DirectiveKindMap[".ifb"] = DK_IFB;
4877 DirectiveKindMap[".ifnb"] = DK_IFNB;
4878 DirectiveKindMap[".ifc"] = DK_IFC;
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004879 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
Eli Bendersky17233942013-01-15 22:59:42 +00004880 DirectiveKindMap[".ifnc"] = DK_IFNC;
Sid Manning51c35602015-03-18 14:20:54 +00004881 DirectiveKindMap[".ifnes"] = DK_IFNES;
Eli Bendersky17233942013-01-15 22:59:42 +00004882 DirectiveKindMap[".ifdef"] = DK_IFDEF;
4883 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
4884 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
4885 DirectiveKindMap[".elseif"] = DK_ELSEIF;
4886 DirectiveKindMap[".else"] = DK_ELSE;
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004887 DirectiveKindMap[".end"] = DK_END;
Eli Bendersky17233942013-01-15 22:59:42 +00004888 DirectiveKindMap[".endif"] = DK_ENDIF;
4889 DirectiveKindMap[".skip"] = DK_SKIP;
4890 DirectiveKindMap[".space"] = DK_SPACE;
4891 DirectiveKindMap[".file"] = DK_FILE;
4892 DirectiveKindMap[".line"] = DK_LINE;
4893 DirectiveKindMap[".loc"] = DK_LOC;
4894 DirectiveKindMap[".stabs"] = DK_STABS;
Reid Kleckner2214ed82016-01-29 00:49:42 +00004895 DirectiveKindMap[".cv_file"] = DK_CV_FILE;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00004896 DirectiveKindMap[".cv_func_id"] = DK_CV_FUNC_ID;
Reid Kleckner2214ed82016-01-29 00:49:42 +00004897 DirectiveKindMap[".cv_loc"] = DK_CV_LOC;
4898 DirectiveKindMap[".cv_linetable"] = DK_CV_LINETABLE;
David Majnemer6fcbd7e2016-01-29 19:24:12 +00004899 DirectiveKindMap[".cv_inline_linetable"] = DK_CV_INLINE_LINETABLE;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00004900 DirectiveKindMap[".cv_inline_site_id"] = DK_CV_INLINE_SITE_ID;
David Majnemer408b5e62016-02-05 01:55:49 +00004901 DirectiveKindMap[".cv_def_range"] = DK_CV_DEF_RANGE;
Reid Kleckner2214ed82016-01-29 00:49:42 +00004902 DirectiveKindMap[".cv_stringtable"] = DK_CV_STRINGTABLE;
4903 DirectiveKindMap[".cv_filechecksums"] = DK_CV_FILECHECKSUMS;
Eli Bendersky17233942013-01-15 22:59:42 +00004904 DirectiveKindMap[".sleb128"] = DK_SLEB128;
4905 DirectiveKindMap[".uleb128"] = DK_ULEB128;
4906 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
4907 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
4908 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
4909 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
4910 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
4911 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
4912 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
4913 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
4914 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
4915 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
4916 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
4917 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
4918 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
4919 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
4920 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
4921 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
4922 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
4923 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
4924 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00004925 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
Eli Bendersky17233942013-01-15 22:59:42 +00004926 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
4927 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
4928 DirectiveKindMap[".macro"] = DK_MACRO;
Nico Weber155dccd12014-07-24 17:08:39 +00004929 DirectiveKindMap[".exitm"] = DK_EXITM;
Eli Bendersky17233942013-01-15 22:59:42 +00004930 DirectiveKindMap[".endm"] = DK_ENDM;
4931 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
4932 DirectiveKindMap[".purgem"] = DK_PURGEM;
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004933 DirectiveKindMap[".err"] = DK_ERR;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004934 DirectiveKindMap[".error"] = DK_ERROR;
Nico Weber404012b2014-07-24 16:26:06 +00004935 DirectiveKindMap[".warning"] = DK_WARNING;
Daniel Sanders9f6ad492015-11-12 13:33:00 +00004936 DirectiveKindMap[".reloc"] = DK_RELOC;
Petr Hosek731bb9c2016-08-23 21:34:53 +00004937 DirectiveKindMap[".dc"] = DK_DC;
4938 DirectiveKindMap[".dc.a"] = DK_DC_A;
4939 DirectiveKindMap[".dc.b"] = DK_DC_B;
4940 DirectiveKindMap[".dc.d"] = DK_DC_D;
4941 DirectiveKindMap[".dc.l"] = DK_DC_L;
4942 DirectiveKindMap[".dc.s"] = DK_DC_S;
4943 DirectiveKindMap[".dc.w"] = DK_DC_W;
4944 DirectiveKindMap[".dc.x"] = DK_DC_X;
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004945 DirectiveKindMap[".dcb"] = DK_DCB;
4946 DirectiveKindMap[".dcb.b"] = DK_DCB_B;
4947 DirectiveKindMap[".dcb.d"] = DK_DCB_D;
4948 DirectiveKindMap[".dcb.l"] = DK_DCB_L;
4949 DirectiveKindMap[".dcb.s"] = DK_DCB_S;
4950 DirectiveKindMap[".dcb.w"] = DK_DCB_W;
4951 DirectiveKindMap[".dcb.x"] = DK_DCB_X;
Petr Hosek85b2f672016-09-23 21:53:36 +00004952 DirectiveKindMap[".ds"] = DK_DS;
4953 DirectiveKindMap[".ds.b"] = DK_DS_B;
4954 DirectiveKindMap[".ds.d"] = DK_DS_D;
4955 DirectiveKindMap[".ds.l"] = DK_DS_L;
4956 DirectiveKindMap[".ds.p"] = DK_DS_P;
4957 DirectiveKindMap[".ds.s"] = DK_DS_S;
4958 DirectiveKindMap[".ds.w"] = DK_DS_W;
4959 DirectiveKindMap[".ds.x"] = DK_DS_X;
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00004960}
4961
Jim Grosbach4b905842013-09-20 23:08:21 +00004962MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004963 AsmToken EndToken, StartToken = getTok();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004964
Rafael Espindola34b9c512012-06-03 23:57:14 +00004965 unsigned NestLevel = 0;
Eugene Zelenko33d7b762016-08-23 17:14:32 +00004966 while (true) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004967 // Check whether we have reached the end of the file.
Rafael Espindola34b9c512012-06-03 23:57:14 +00004968 if (getLexer().is(AsmToken::Eof)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00004969 printError(DirectiveLoc, "no matching '.endr' in definition");
Craig Topper353eda42014-04-24 06:44:33 +00004970 return nullptr;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004971 }
4972
Rafael Espindola34b9c512012-06-03 23:57:14 +00004973 if (Lexer.is(AsmToken::Identifier) &&
Nikolay Haustov95b4fcd2016-03-01 08:18:28 +00004974 (getTok().getIdentifier() == ".rept" ||
4975 getTok().getIdentifier() == ".irp" ||
4976 getTok().getIdentifier() == ".irpc")) {
Rafael Espindola34b9c512012-06-03 23:57:14 +00004977 ++NestLevel;
4978 }
4979
4980 // Otherwise, check whether we have reached the .endr.
Jim Grosbach4b905842013-09-20 23:08:21 +00004981 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
Rafael Espindola34b9c512012-06-03 23:57:14 +00004982 if (NestLevel == 0) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004983 EndToken = getTok();
4984 Lex();
Rafael Espindola34b9c512012-06-03 23:57:14 +00004985 if (Lexer.isNot(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00004986 printError(getTok().getLoc(),
4987 "unexpected token in '.endr' directive");
Craig Topper353eda42014-04-24 06:44:33 +00004988 return nullptr;
Rafael Espindola34b9c512012-06-03 23:57:14 +00004989 }
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004990 break;
4991 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00004992 --NestLevel;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004993 }
4994
Rafael Espindola34b9c512012-06-03 23:57:14 +00004995 // Otherwise, scan till the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004996 eatToEndOfStatement();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004997 }
4998
4999 const char *BodyStart = StartToken.getLoc().getPointer();
5000 const char *BodyEnd = EndToken.getLoc().getPointer();
5001 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
5002
Rafael Espindola34b9c512012-06-03 23:57:14 +00005003 // We Are Anonymous.
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00005004 MacroLikeBodies.emplace_back(StringRef(), Body, MCAsmMacroParameters());
Benjamin Kramer1df3a1f2013-08-04 09:06:29 +00005005 return &MacroLikeBodies.back();
Rafael Espindola34b9c512012-06-03 23:57:14 +00005006}
5007
Jim Grosbach4b905842013-09-20 23:08:21 +00005008void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +00005009 raw_svector_ostream &OS) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005010 OS << ".endr\n";
5011
Rafael Espindola3560ff22014-08-27 20:03:13 +00005012 std::unique_ptr<MemoryBuffer> Instantiation =
5013 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005014
Rafael Espindola34b9c512012-06-03 23:57:14 +00005015 // Create the macro instantiation object and add to the current macro
5016 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00005017 MacroInstantiation *MI = new MacroInstantiation(
5018 DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Rafael Espindola34b9c512012-06-03 23:57:14 +00005019 ActiveMacros.push_back(MI);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005020
Rafael Espindola34b9c512012-06-03 23:57:14 +00005021 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00005022 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00005023 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Rafael Espindola34b9c512012-06-03 23:57:14 +00005024 Lex();
5025}
5026
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00005027/// parseDirectiveRept
5028/// ::= .rep | .rept count
5029bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00005030 const MCExpr *CountExpr;
5031 SMLoc CountLoc = getTok().getLoc();
5032 if (parseExpression(CountExpr))
5033 return true;
5034
Rafael Espindola34b9c512012-06-03 23:57:14 +00005035 int64_t Count;
Jim Grosbach13760bd2015-05-30 01:25:56 +00005036 if (!CountExpr->evaluateAsAbsolute(Count)) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00005037 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
5038 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00005039
Nirav Davea645433c2016-07-18 15:24:03 +00005040 if (check(Count < 0, CountLoc, "Count is negative") ||
5041 parseToken(AsmToken::EndOfStatement,
5042 "unexpected token in '" + Dir + "' directive"))
5043 return true;
Rafael Espindola34b9c512012-06-03 23:57:14 +00005044
5045 // Lex the rept definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005046 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola34b9c512012-06-03 23:57:14 +00005047 if (!M)
5048 return true;
5049
5050 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5051 // to hold the macro body with substitutions.
5052 SmallString<256> Buf;
Rafael Espindola34b9c512012-06-03 23:57:14 +00005053 raw_svector_ostream OS(Buf);
5054 while (Count--) {
Toma Tabacu217116e2015-04-27 10:50:29 +00005055 // Note that the AtPseudoVariable is disabled for instantiations of .rep(t).
5056 if (expandMacro(OS, M->Body, None, None, false, getTok().getLoc()))
Rafael Espindola34b9c512012-06-03 23:57:14 +00005057 return true;
5058 }
Jim Grosbach4b905842013-09-20 23:08:21 +00005059 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005060
5061 return false;
5062}
5063
Jim Grosbach4b905842013-09-20 23:08:21 +00005064/// parseDirectiveIrp
Rafael Espindola768b41c2012-06-15 14:02:34 +00005065/// ::= .irp symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00005066bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00005067 MCAsmMacroParameter Parameter;
Eli Bendersky38274122013-01-14 23:22:36 +00005068 MCAsmMacroArguments A;
Nirav Davea645433c2016-07-18 15:24:03 +00005069 if (check(parseIdentifier(Parameter.Name),
5070 "expected identifier in '.irp' directive") ||
5071 parseToken(AsmToken::Comma, "expected comma in '.irp' directive") ||
5072 parseMacroArguments(nullptr, A) ||
5073 parseToken(AsmToken::EndOfStatement, "expected End of Statement"))
Rafael Espindola768b41c2012-06-15 14:02:34 +00005074 return true;
5075
Rafael Espindola768b41c2012-06-15 14:02:34 +00005076 // Lex the irp definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005077 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola768b41c2012-06-15 14:02:34 +00005078 if (!M)
5079 return true;
5080
5081 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5082 // to hold the macro body with substitutions.
5083 SmallString<256> Buf;
5084 raw_svector_ostream OS(Buf);
5085
Craig Topper84008482015-10-10 05:38:14 +00005086 for (const MCAsmMacroArgument &Arg : A) {
Toma Tabacu217116e2015-04-27 10:50:29 +00005087 // Note that the AtPseudoVariable is enabled for instantiations of .irp.
5088 // This is undocumented, but GAS seems to support it.
Craig Topper84008482015-10-10 05:38:14 +00005089 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindola768b41c2012-06-15 14:02:34 +00005090 return true;
5091 }
5092
Jim Grosbach4b905842013-09-20 23:08:21 +00005093 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola768b41c2012-06-15 14:02:34 +00005094
5095 return false;
5096}
5097
Jim Grosbach4b905842013-09-20 23:08:21 +00005098/// parseDirectiveIrpc
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005099/// ::= .irpc symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00005100bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00005101 MCAsmMacroParameter Parameter;
Eli Bendersky38274122013-01-14 23:22:36 +00005102 MCAsmMacroArguments A;
Nirav Davea645433c2016-07-18 15:24:03 +00005103
5104 if (check(parseIdentifier(Parameter.Name),
5105 "expected identifier in '.irpc' directive") ||
5106 parseToken(AsmToken::Comma, "expected comma in '.irpc' directive") ||
5107 parseMacroArguments(nullptr, A))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005108 return true;
5109
5110 if (A.size() != 1 || A.front().size() != 1)
5111 return TokError("unexpected token in '.irpc' directive");
5112
5113 // Eat the end of statement.
Nirav Davea645433c2016-07-18 15:24:03 +00005114 if (parseToken(AsmToken::EndOfStatement, "expected end of statement"))
5115 return true;
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005116
5117 // Lex the irpc definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005118 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005119 if (!M)
5120 return true;
5121
5122 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5123 // to hold the macro body with substitutions.
5124 SmallString<256> Buf;
5125 raw_svector_ostream OS(Buf);
5126
5127 StringRef Values = A.front().front().getString();
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00005128 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
Eli Benderskya7b905e2013-01-14 19:00:26 +00005129 MCAsmMacroArgument Arg;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00005130 Arg.emplace_back(AsmToken::Identifier, Values.slice(I, I + 1));
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005131
Toma Tabacu217116e2015-04-27 10:50:29 +00005132 // Note that the AtPseudoVariable is enabled for instantiations of .irpc.
5133 // This is undocumented, but GAS seems to support it.
5134 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005135 return true;
5136 }
5137
Jim Grosbach4b905842013-09-20 23:08:21 +00005138 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005139
5140 return false;
5141}
5142
Jim Grosbach4b905842013-09-20 23:08:21 +00005143bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
Rafael Espindola34b9c512012-06-03 23:57:14 +00005144 if (ActiveMacros.empty())
Preston Gurdeb3ebf12012-09-19 20:23:43 +00005145 return TokError("unmatched '.endr' directive");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005146
5147 // The only .repl that should get here are the ones created by
Jim Grosbach4b905842013-09-20 23:08:21 +00005148 // instantiateMacroLikeBody.
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005149 assert(getLexer().is(AsmToken::EndOfStatement));
5150
Jim Grosbach4b905842013-09-20 23:08:21 +00005151 handleMacroExit();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005152 return false;
5153}
Rafael Espindola12d73d12010-09-11 16:45:15 +00005154
Jim Grosbach4b905842013-09-20 23:08:21 +00005155bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
Benjamin Kramer1a136112013-02-15 20:37:21 +00005156 size_t Len) {
Eli Friedman0f4871d2012-10-22 23:58:19 +00005157 const MCExpr *Value;
5158 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005159 if (parseExpression(Value))
Eli Friedman0f4871d2012-10-22 23:58:19 +00005160 return true;
5161 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5162 if (!MCE)
5163 return Error(ExprLoc, "unexpected expression in _emit");
5164 uint64_t IntValue = MCE->getValue();
Craig Topper55b1f292015-10-10 20:17:07 +00005165 if (!isUInt<8>(IntValue) && !isInt<8>(IntValue))
Eli Friedman0f4871d2012-10-22 23:58:19 +00005166 return Error(ExprLoc, "literal value out of range for directive");
5167
Craig Topper7d5b2312015-10-10 05:25:02 +00005168 Info.AsmRewrites->emplace_back(AOK_Emit, IDLoc, Len);
Chad Rosierc7f552c2013-02-12 21:33:51 +00005169 return false;
5170}
5171
Jim Grosbach4b905842013-09-20 23:08:21 +00005172bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
Chad Rosierc7f552c2013-02-12 21:33:51 +00005173 const MCExpr *Value;
5174 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005175 if (parseExpression(Value))
Chad Rosierc7f552c2013-02-12 21:33:51 +00005176 return true;
5177 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5178 if (!MCE)
5179 return Error(ExprLoc, "unexpected expression in align");
5180 uint64_t IntValue = MCE->getValue();
5181 if (!isPowerOf2_64(IntValue))
5182 return Error(ExprLoc, "literal value not a power of two greater then zero");
5183
Craig Topper7d5b2312015-10-10 05:25:02 +00005184 Info.AsmRewrites->emplace_back(AOK_Align, IDLoc, 5, Log2_64(IntValue));
Eli Friedman0f4871d2012-10-22 23:58:19 +00005185 return false;
5186}
5187
Chad Rosierf43fcf52013-02-13 21:27:17 +00005188// We are comparing pointers, but the pointers are relative to a single string.
5189// Thus, this should always be deterministic.
Benjamin Kramer8817cca2013-09-22 14:09:50 +00005190static int rewritesSort(const AsmRewrite *AsmRewriteA,
5191 const AsmRewrite *AsmRewriteB) {
Chad Rosiereb5c1682013-02-13 18:38:58 +00005192 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
5193 return -1;
5194 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
5195 return 1;
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005196
Chad Rosierfce4fab2013-04-08 17:43:47 +00005197 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
5198 // rewrite to the same location. Make sure the SizeDirective rewrite is
5199 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
5200 // ensures the sort algorithm is stable.
Jim Grosbach4b905842013-09-20 23:08:21 +00005201 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
5202 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005203 return -1;
Chad Rosierfce4fab2013-04-08 17:43:47 +00005204
Jim Grosbach4b905842013-09-20 23:08:21 +00005205 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
5206 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005207 return 1;
Jim Grosbach4b905842013-09-20 23:08:21 +00005208 llvm_unreachable("Unstable rewrite sort.");
Chad Rosierb2144ce2013-02-13 01:03:13 +00005209}
5210
Jim Grosbach4b905842013-09-20 23:08:21 +00005211bool AsmParser::parseMSInlineAsm(
5212 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
5213 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
5214 SmallVectorImpl<std::string> &Constraints,
5215 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
5216 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
Chad Rosier37e755c2012-10-23 17:43:43 +00005217 SmallVector<void *, 4> InputDecls;
5218 SmallVector<void *, 4> OutputDecls;
Chad Rosiera4bc9432013-01-10 22:10:27 +00005219 SmallVector<bool, 4> InputDeclsAddressOf;
5220 SmallVector<bool, 4> OutputDeclsAddressOf;
Chad Rosier8bce6642012-10-18 15:49:34 +00005221 SmallVector<std::string, 4> InputConstraints;
5222 SmallVector<std::string, 4> OutputConstraints;
Benjamin Kramer1a136112013-02-15 20:37:21 +00005223 SmallVector<unsigned, 4> ClobberRegs;
Chad Rosier8bce6642012-10-18 15:49:34 +00005224
Benjamin Kramer1a136112013-02-15 20:37:21 +00005225 SmallVector<AsmRewrite, 4> AsmStrRewrites;
Chad Rosier8bce6642012-10-18 15:49:34 +00005226
5227 // Prime the lexer.
5228 Lex();
5229
5230 // While we have input, parse each statement.
5231 unsigned InputIdx = 0;
5232 unsigned OutputIdx = 0;
5233 while (getLexer().isNot(AsmToken::Eof)) {
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00005234 // Parse curly braces marking block start/end
5235 if (parseCurlyBlockScope(AsmStrRewrites))
5236 continue;
5237
Eli Friedman0f4871d2012-10-22 23:58:19 +00005238 ParseStatementInfo Info(&AsmStrRewrites);
Nirav Dave2364748a2016-09-16 18:30:20 +00005239 bool StatementErr = parseStatement(Info, &SI);
Nirav Dave9fa8af22016-09-13 13:55:06 +00005240
Nirav Dave2364748a2016-09-16 18:30:20 +00005241 if (StatementErr || Info.ParseError) {
5242 // Emit pending errors if any exist.
5243 printPendingErrors();
Nico Webere204c482016-09-13 18:17:00 +00005244 return true;
Nirav Dave2364748a2016-09-16 18:30:20 +00005245 }
5246
5247 // No pending error should exist here.
5248 assert(!hasPendingError() && "unexpected error from parseStatement");
Chad Rosier149e8e02012-12-12 22:45:52 +00005249
Benjamin Kramer1a136112013-02-15 20:37:21 +00005250 if (Info.Opcode == ~0U)
5251 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00005252
Benjamin Kramer1a136112013-02-15 20:37:21 +00005253 const MCInstrDesc &Desc = MII->get(Info.Opcode);
Chad Rosier8bce6642012-10-18 15:49:34 +00005254
Benjamin Kramer1a136112013-02-15 20:37:21 +00005255 // Build the list of clobbers, outputs and inputs.
5256 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
David Blaikie960ea3f2014-06-08 16:18:35 +00005257 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005258
Benjamin Kramer1a136112013-02-15 20:37:21 +00005259 // Immediate.
David Blaikie960ea3f2014-06-08 16:18:35 +00005260 if (Operand.isImm())
Benjamin Kramer1a136112013-02-15 20:37:21 +00005261 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00005262
Benjamin Kramer1a136112013-02-15 20:37:21 +00005263 // Register operand.
Nico Weber42f79db2014-07-17 20:24:55 +00005264 if (Operand.isReg() && !Operand.needAddressOf() &&
5265 !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
Benjamin Kramer1a136112013-02-15 20:37:21 +00005266 unsigned NumDefs = Desc.getNumDefs();
5267 // Clobber.
David Blaikie960ea3f2014-06-08 16:18:35 +00005268 if (NumDefs && Operand.getMCOperandNum() < NumDefs)
5269 ClobberRegs.push_back(Operand.getReg());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005270 continue;
5271 }
5272
5273 // Expr/Input or Output.
David Blaikie960ea3f2014-06-08 16:18:35 +00005274 StringRef SymName = Operand.getSymName();
Chad Rosiere81309b2013-04-09 17:53:49 +00005275 if (SymName.empty())
5276 continue;
5277
David Blaikie960ea3f2014-06-08 16:18:35 +00005278 void *OpDecl = Operand.getOpDecl();
Benjamin Kramer1a136112013-02-15 20:37:21 +00005279 if (!OpDecl)
5280 continue;
5281
5282 bool isOutput = (i == 1) && Desc.mayStore();
Chad Rosiere81309b2013-04-09 17:53:49 +00005283 SMLoc Start = SMLoc::getFromPointer(SymName.data());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005284 if (isOutput) {
5285 ++InputIdx;
5286 OutputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00005287 OutputDeclsAddressOf.push_back(Operand.needAddressOf());
Yaron Keren075759a2015-03-30 15:42:36 +00005288 OutputConstraints.push_back(("=" + Operand.getConstraint()).str());
Craig Topper7d5b2312015-10-10 05:25:02 +00005289 AsmStrRewrites.emplace_back(AOK_Output, Start, SymName.size());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005290 } else {
5291 InputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00005292 InputDeclsAddressOf.push_back(Operand.needAddressOf());
5293 InputConstraints.push_back(Operand.getConstraint().str());
Craig Topper7d5b2312015-10-10 05:25:02 +00005294 AsmStrRewrites.emplace_back(AOK_Input, Start, SymName.size());
Chad Rosier8bce6642012-10-18 15:49:34 +00005295 }
Chad Rosier8bce6642012-10-18 15:49:34 +00005296 }
Reid Kleckneree088972013-12-10 18:27:32 +00005297
5298 // Consider implicit defs to be clobbers. Think of cpuid and push.
Craig Toppere5e035a32015-12-05 07:13:35 +00005299 ArrayRef<MCPhysReg> ImpDefs(Desc.getImplicitDefs(),
5300 Desc.getNumImplicitDefs());
David Majnemer8114c1a2014-06-23 02:17:16 +00005301 ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end());
Chad Rosier8bce6642012-10-18 15:49:34 +00005302 }
5303
5304 // Set the number of Outputs and Inputs.
Chad Rosierf641baa2012-10-18 19:39:30 +00005305 NumOutputs = OutputDecls.size();
5306 NumInputs = InputDecls.size();
Chad Rosier8bce6642012-10-18 15:49:34 +00005307
5308 // Set the unique clobbers.
Benjamin Kramer1a136112013-02-15 20:37:21 +00005309 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
5310 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
5311 ClobberRegs.end());
5312 Clobbers.assign(ClobberRegs.size(), std::string());
5313 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
5314 raw_string_ostream OS(Clobbers[I]);
5315 IP->printRegName(OS, ClobberRegs[I]);
5316 }
Chad Rosier8bce6642012-10-18 15:49:34 +00005317
5318 // Merge the various outputs and inputs. Output are expected first.
5319 if (NumOutputs || NumInputs) {
5320 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierf641baa2012-10-18 19:39:30 +00005321 OpDecls.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00005322 Constraints.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00005323 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00005324 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00005325 Constraints[i] = OutputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005326 }
5327 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00005328 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00005329 Constraints[j] = InputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005330 }
5331 }
5332
5333 // Build the IR assembly string.
Alp Tokere69170a2014-06-26 22:52:05 +00005334 std::string AsmStringIR;
5335 raw_string_ostream OS(AsmStringIR);
Alp Tokera55b95b2014-07-06 10:33:31 +00005336 StringRef ASMString =
5337 SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
5338 const char *AsmStart = ASMString.begin();
5339 const char *AsmEnd = ASMString.end();
Jim Grosbach4b905842013-09-20 23:08:21 +00005340 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
David Majnemer8114c1a2014-06-23 02:17:16 +00005341 for (const AsmRewrite &AR : AsmStrRewrites) {
5342 AsmRewriteKind Kind = AR.Kind;
Chad Rosierff10ed12013-04-12 16:26:42 +00005343 if (Kind == AOK_Delete)
5344 continue;
5345
David Majnemer8114c1a2014-06-23 02:17:16 +00005346 const char *Loc = AR.Loc.getPointer();
Chad Rosier17d37992013-03-19 21:12:14 +00005347 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
Chad Rosier0f48c552012-10-19 20:57:14 +00005348
Chad Rosier120eefd2013-03-19 17:32:17 +00005349 // Emit everything up to the immediate/expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00005350 if (unsigned Len = Loc - AsmStart)
Chad Rosier17d37992013-03-19 21:12:14 +00005351 OS << StringRef(AsmStart, Len);
Chad Rosier0f48c552012-10-19 20:57:14 +00005352
Chad Rosier37e755c2012-10-23 17:43:43 +00005353 // Skip the original expression.
5354 if (Kind == AOK_Skip) {
David Majnemer8114c1a2014-06-23 02:17:16 +00005355 AsmStart = Loc + AR.Len;
Chad Rosier37e755c2012-10-23 17:43:43 +00005356 continue;
5357 }
5358
Chad Rosierff10ed12013-04-12 16:26:42 +00005359 unsigned AdditionalSkip = 0;
Chad Rosier8bce6642012-10-18 15:49:34 +00005360 // Rewrite expressions in $N notation.
Chad Rosier0f48c552012-10-19 20:57:14 +00005361 switch (Kind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00005362 default:
5363 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005364 case AOK_Imm:
David Majnemer8114c1a2014-06-23 02:17:16 +00005365 OS << "$$" << AR.Val;
Chad Rosier11c42f22012-10-26 18:04:20 +00005366 break;
5367 case AOK_ImmPrefix:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005368 OS << "$$";
Chad Rosier8bce6642012-10-18 15:49:34 +00005369 break;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005370 case AOK_Label:
Matt Arsenault4e273432014-12-04 00:06:57 +00005371 OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005372 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005373 case AOK_Input:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005374 OS << '$' << InputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00005375 break;
5376 case AOK_Output:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005377 OS << '$' << OutputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00005378 break;
Chad Rosier0f48c552012-10-19 20:57:14 +00005379 case AOK_SizeDirective:
David Majnemer8114c1a2014-06-23 02:17:16 +00005380 switch (AR.Val) {
Chad Rosier0f48c552012-10-19 20:57:14 +00005381 default: break;
5382 case 8: OS << "byte ptr "; break;
5383 case 16: OS << "word ptr "; break;
5384 case 32: OS << "dword ptr "; break;
5385 case 64: OS << "qword ptr "; break;
5386 case 80: OS << "xword ptr "; break;
5387 case 128: OS << "xmmword ptr "; break;
5388 case 256: OS << "ymmword ptr "; break;
5389 }
Eli Friedman0f4871d2012-10-22 23:58:19 +00005390 break;
5391 case AOK_Emit:
5392 OS << ".byte";
5393 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00005394 case AOK_Align: {
Reid Klecknerfb1c1c72015-10-27 17:32:48 +00005395 // MS alignment directives are measured in bytes. If the native assembler
5396 // measures alignment in bytes, we can pass it straight through.
5397 OS << ".align";
5398 if (getContext().getAsmInfo()->getAlignmentIsInBytes())
5399 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00005400
Reid Klecknerfb1c1c72015-10-27 17:32:48 +00005401 // Alignment is in log2 form, so print that instead and skip the original
5402 // immediate.
5403 unsigned Val = AR.Val;
5404 OS << ' ' << Val;
Benjamin Kramer1a136112013-02-15 20:37:21 +00005405 assert(Val < 10 && "Expected alignment less then 2^10.");
Chad Rosierc7f552c2013-02-12 21:33:51 +00005406 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
5407 break;
5408 }
Michael Zuckerman02ecd432015-12-13 17:07:23 +00005409 case AOK_EVEN:
5410 OS << ".even";
5411 break;
Chad Rosierf0e87202012-10-25 20:41:34 +00005412 case AOK_DotOperator:
Reid Kleckner94a1c4d2014-03-06 19:19:12 +00005413 // Insert the dot if the user omitted it.
Alp Tokere69170a2014-06-26 22:52:05 +00005414 OS.flush();
5415 if (AsmStringIR.back() != '.')
Reid Kleckner94a1c4d2014-03-06 19:19:12 +00005416 OS << '.';
David Majnemer8114c1a2014-06-23 02:17:16 +00005417 OS << AR.Val;
Chad Rosierf0e87202012-10-25 20:41:34 +00005418 break;
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00005419 case AOK_EndOfStatement:
5420 OS << "\n\t";
5421 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005422 }
Chad Rosier0f48c552012-10-19 20:57:14 +00005423
Chad Rosier8bce6642012-10-18 15:49:34 +00005424 // Skip the original expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00005425 AsmStart = Loc + AR.Len + AdditionalSkip;
Chad Rosier8bce6642012-10-18 15:49:34 +00005426 }
5427
5428 // Emit the remainder of the asm string.
Chad Rosier17d37992013-03-19 21:12:14 +00005429 if (AsmStart != AsmEnd)
5430 OS << StringRef(AsmStart, AsmEnd - AsmStart);
Chad Rosier8bce6642012-10-18 15:49:34 +00005431
5432 AsmString = OS.str();
5433 return false;
5434}
5435
Pete Cooper80d21cb2015-06-22 19:35:57 +00005436namespace llvm {
5437namespace MCParserUtils {
5438
5439/// Returns whether the given symbol is used anywhere in the given expression,
5440/// or subexpressions.
5441static bool isSymbolUsedInExpression(const MCSymbol *Sym, const MCExpr *Value) {
5442 switch (Value->getKind()) {
5443 case MCExpr::Binary: {
5444 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
5445 return isSymbolUsedInExpression(Sym, BE->getLHS()) ||
5446 isSymbolUsedInExpression(Sym, BE->getRHS());
5447 }
5448 case MCExpr::Target:
5449 case MCExpr::Constant:
5450 return false;
5451 case MCExpr::SymbolRef: {
5452 const MCSymbol &S =
5453 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
5454 if (S.isVariable())
5455 return isSymbolUsedInExpression(Sym, S.getVariableValue());
5456 return &S == Sym;
5457 }
5458 case MCExpr::Unary:
5459 return isSymbolUsedInExpression(
5460 Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
5461 }
5462
5463 llvm_unreachable("Unknown expr kind!");
5464}
5465
5466bool parseAssignmentExpression(StringRef Name, bool allow_redef,
5467 MCAsmParser &Parser, MCSymbol *&Sym,
5468 const MCExpr *&Value) {
Pete Cooper80d21cb2015-06-22 19:35:57 +00005469
5470 // FIXME: Use better location, we should use proper tokens.
Nirav Davefd910412016-06-17 16:06:17 +00005471 SMLoc EqualLoc = Parser.getTok().getLoc();
Pete Cooper80d21cb2015-06-22 19:35:57 +00005472
5473 if (Parser.parseExpression(Value)) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00005474 return Parser.TokError("missing expression");
Pete Cooper80d21cb2015-06-22 19:35:57 +00005475 }
5476
5477 // Note: we don't count b as used in "a = b". This is to allow
5478 // a = b
5479 // b = c
5480
Nirav Dave1a9044b2016-10-24 14:35:29 +00005481 if (Parser.parseToken(AsmToken::EndOfStatement))
5482 return true;
Pete Cooper80d21cb2015-06-22 19:35:57 +00005483
5484 // Validate that the LHS is allowed to be a variable (either it has not been
5485 // used as a symbol, or it is an absolute symbol).
5486 Sym = Parser.getContext().lookupSymbol(Name);
5487 if (Sym) {
5488 // Diagnose assignment to a label.
5489 //
5490 // FIXME: Diagnostics. Note the location of the definition as a label.
5491 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
5492 if (isSymbolUsedInExpression(Sym, Value))
5493 return Parser.Error(EqualLoc, "Recursive use of '" + Name + "'");
Vedant Kumar86dbd922015-08-31 17:44:53 +00005494 else if (Sym->isUndefined(/*SetUsed*/ false) && !Sym->isUsed() &&
5495 !Sym->isVariable())
Pete Cooper80d21cb2015-06-22 19:35:57 +00005496 ; // Allow redefinitions of undefined symbols only used in directives.
5497 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
5498 ; // Allow redefinitions of variables that haven't yet been used.
5499 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
5500 return Parser.Error(EqualLoc, "redefinition of '" + Name + "'");
5501 else if (!Sym->isVariable())
5502 return Parser.Error(EqualLoc, "invalid assignment to '" + Name + "'");
5503 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
5504 return Parser.Error(EqualLoc,
5505 "invalid reassignment of non-absolute variable '" +
5506 Name + "'");
Pete Cooper80d21cb2015-06-22 19:35:57 +00005507 } else if (Name == ".") {
Oliver Stannard268f42f2016-12-14 10:43:58 +00005508 Parser.getStreamer().emitValueToOffset(Value, 0, EqualLoc);
Pete Cooper80d21cb2015-06-22 19:35:57 +00005509 return false;
5510 } else
5511 Sym = Parser.getContext().getOrCreateSymbol(Name);
5512
5513 Sym->setRedefinable(allow_redef);
5514
5515 return false;
5516}
5517
Eugene Zelenko33d7b762016-08-23 17:14:32 +00005518} // end namespace MCParserUtils
5519} // end namespace llvm
Pete Cooper80d21cb2015-06-22 19:35:57 +00005520
Daniel Dunbar01e36072010-07-17 02:26:10 +00005521/// \brief Create an MCAsmParser instance.
Jim Grosbach4b905842013-09-20 23:08:21 +00005522MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
5523 MCStreamer &Out, const MCAsmInfo &MAI) {
Jim Grosbach345768c2011-08-16 18:33:49 +00005524 return new AsmParser(SM, C, Out, MAI);
Daniel Dunbar01e36072010-07-17 02:26:10 +00005525}