blob: 7ebe7b538a21b227dbf9edab32a59191276d0a4a [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.
Jim Grosbach13760bd2015-05-30 01:25:56 +00001008 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
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: {
1045 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) {
Eugene Zelenko33d7b762016-08-23 17:14:32 +00001439 while (true) {
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001440 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001441 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001442
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001443 // If the next token is lower precedence than we are allowed to eat, return
1444 // successfully with what we ate already.
1445 if (TokPrec < Precedence)
1446 return false;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001447
Sean Callanan686ed8d2010-01-19 20:22:31 +00001448 Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +00001449
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001450 // Eat the next primary expression.
Daniel Dunbarf3636452009-08-31 08:07:22 +00001451 const MCExpr *RHS;
Jim Grosbach4b905842013-09-20 23:08:21 +00001452 if (parsePrimaryExpr(RHS, EndLoc))
1453 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001454
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001455 // If BinOp binds less tightly with RHS than the operator after RHS, let
1456 // the pending operator take RHS as its LHS.
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001457 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001458 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Jim Grosbach4b905842013-09-20 23:08:21 +00001459 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1460 return true;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001461
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001462 // Merge LHS and RHS according to operator.
Jim Grosbach13760bd2015-05-30 01:25:56 +00001463 Res = MCBinaryExpr::create(Kind, Res, RHS, getContext());
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001464 }
1465}
1466
Chris Lattner36e02122009-06-21 20:54:55 +00001467/// ParseStatement:
1468/// ::= EndOfStatement
Chris Lattnere5074c42009-06-22 01:29:09 +00001469/// ::= Label* Directive ...Operands... EndOfStatement
1470/// ::= Label* Identifier OperandList* EndOfStatement
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001471bool AsmParser::parseStatement(ParseStatementInfo &Info,
1472 MCAsmParserSemaCallback *SI) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001473 assert(!hasPendingError() && "parseStatement started with pending error");
Nirav Davefd910412016-06-17 16:06:17 +00001474 // Eat initial spaces and comments
1475 while (Lexer.is(AsmToken::Space))
1476 Lex();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001477 if (Lexer.is(AsmToken::EndOfStatement)) {
Nirav Davefd910412016-06-17 16:06:17 +00001478 // if this is a line comment we can drop it safely
1479 if (getTok().getString().front() == '\r' ||
1480 getTok().getString().front() == '\n')
1481 Out.AddBlankLine();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001482 Lex();
Chris Lattner36e02122009-06-21 20:54:55 +00001483 return false;
Chris Lattner36e02122009-06-21 20:54:55 +00001484 }
Nirav Dave9263ae32016-08-02 19:17:54 +00001485 if (Lexer.is(AsmToken::Hash)) {
1486 // Seeing a hash here means that it was an end-of-line comment in
1487 // an asm syntax where hash's are not comment and the previous
1488 // statement parser did not check the end of statement. Relex as
1489 // EndOfStatement.
1490 StringRef CommentStr = parseStringToEndOfStatement();
1491 Lexer.Lex();
1492 Lexer.UnLex(AsmToken(AsmToken::EndOfStatement, CommentStr));
1493 return false;
1494 }
Nirav Davefd910412016-06-17 16:06:17 +00001495 // Statements always start with an identifier.
Sean Callanan936b0d32010-01-19 21:44:56 +00001496 AsmToken ID = getTok();
Daniel Dunbaree4465c2009-07-28 16:38:40 +00001497 SMLoc IDLoc = ID.getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001498 StringRef IDVal;
Kevin Enderby0510b482010-05-17 23:08:19 +00001499 int64_t LocalLabelVal = -1;
Nirav Davefd910412016-06-17 16:06:17 +00001500 if (Lexer.is(AsmToken::HashDirective))
Jim Grosbach4b905842013-09-20 23:08:21 +00001501 return parseCppHashLineFilenameComment(IDLoc);
Kevin Enderbyfa3c6f12010-12-24 00:12:02 +00001502 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderby0510b482010-05-17 23:08:19 +00001503 if (Lexer.is(AsmToken::Integer)) {
1504 LocalLabelVal = getTok().getIntVal();
1505 if (LocalLabelVal < 0) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001506 if (!TheCondState.Ignore) {
1507 Lex(); // always eat a token
1508 return Error(IDLoc, "unexpected token at start of statement");
1509 }
Kevin Enderby0510b482010-05-17 23:08:19 +00001510 IDVal = "";
Eli Bendersky88024712013-01-16 19:32:36 +00001511 } else {
Kevin Enderby0510b482010-05-17 23:08:19 +00001512 IDVal = getTok().getString();
1513 Lex(); // Consume the integer token to be used as an identifier token.
1514 if (Lexer.getKind() != AsmToken::Colon) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001515 if (!TheCondState.Ignore) {
1516 Lex(); // always eat a token
1517 return Error(IDLoc, "unexpected token at start of statement");
1518 }
Kevin Enderby0510b482010-05-17 23:08:19 +00001519 }
1520 }
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001521 } else if (Lexer.is(AsmToken::Dot)) {
1522 // Treat '.' as a valid identifier in this context.
1523 Lex();
1524 IDVal = ".";
Colin LeMahieu8a0453e2015-11-09 00:31:07 +00001525 } else if (Lexer.is(AsmToken::LCurly)) {
1526 // Treat '{' as a valid identifier in this context.
1527 Lex();
1528 IDVal = "{";
1529
1530 } else if (Lexer.is(AsmToken::RCurly)) {
1531 // Treat '}' as a valid identifier in this context.
1532 Lex();
1533 IDVal = "}";
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001534 } else if (parseIdentifier(IDVal)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001535 if (!TheCondState.Ignore) {
1536 Lex(); // always eat a token
1537 return Error(IDLoc, "unexpected token at start of statement");
1538 }
Chris Lattner926885c2010-04-17 18:14:27 +00001539 IDVal = "";
1540 }
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001541
Chris Lattner926885c2010-04-17 18:14:27 +00001542 // Handle conditional assembly here before checking for skipping. We
1543 // have to do this so that .endif isn't skipped in a ".if 0" block for
1544 // example.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001545 StringMap<DirectiveKind>::const_iterator DirKindIt =
Jim Grosbach4b905842013-09-20 23:08:21 +00001546 DirectiveKindMap.find(IDVal);
1547 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1548 ? DK_NO_DIRECTIVE
1549 : DirKindIt->getValue();
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001550 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001551 default:
1552 break;
1553 case DK_IF:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001554 case DK_IFEQ:
1555 case DK_IFGE:
1556 case DK_IFGT:
1557 case DK_IFLE:
1558 case DK_IFLT:
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00001559 case DK_IFNE:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001560 return parseDirectiveIf(IDLoc, DirKind);
Jim Grosbach4b905842013-09-20 23:08:21 +00001561 case DK_IFB:
1562 return parseDirectiveIfb(IDLoc, true);
1563 case DK_IFNB:
1564 return parseDirectiveIfb(IDLoc, false);
1565 case DK_IFC:
1566 return parseDirectiveIfc(IDLoc, true);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00001567 case DK_IFEQS:
Sid Manning51c35602015-03-18 14:20:54 +00001568 return parseDirectiveIfeqs(IDLoc, true);
Jim Grosbach4b905842013-09-20 23:08:21 +00001569 case DK_IFNC:
1570 return parseDirectiveIfc(IDLoc, false);
Sid Manning51c35602015-03-18 14:20:54 +00001571 case DK_IFNES:
1572 return parseDirectiveIfeqs(IDLoc, false);
Jim Grosbach4b905842013-09-20 23:08:21 +00001573 case DK_IFDEF:
1574 return parseDirectiveIfdef(IDLoc, true);
1575 case DK_IFNDEF:
1576 case DK_IFNOTDEF:
1577 return parseDirectiveIfdef(IDLoc, false);
1578 case DK_ELSEIF:
1579 return parseDirectiveElseIf(IDLoc);
1580 case DK_ELSE:
1581 return parseDirectiveElse(IDLoc);
1582 case DK_ENDIF:
1583 return parseDirectiveEndIf(IDLoc);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001584 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001585
Eli Bendersky88024712013-01-16 19:32:36 +00001586 // Ignore the statement if in the middle of inactive conditional
1587 // (e.g. ".if 0").
Chad Rosiereda70b32012-10-20 00:47:08 +00001588 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001589 eatToEndOfStatement();
Chris Lattner926885c2010-04-17 18:14:27 +00001590 return false;
1591 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001592
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001593 // FIXME: Recurse on local labels?
1594
1595 // See what kind of statement we have.
1596 switch (Lexer.getKind()) {
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001597 case AsmToken::Colon: {
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001598 if (!getTargetParser().isLabel(ID))
1599 break;
Nirav Davef43cc9f2016-10-10 15:24:54 +00001600 if (checkForValidSection())
1601 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00001602
Chris Lattner36e02122009-06-21 20:54:55 +00001603 // identifier ':' -> Label.
Sean Callanan686ed8d2010-01-19 20:22:31 +00001604 Lex();
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001605
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001606 // Diagnose attempt to use '.' as a label.
1607 if (IDVal == ".")
1608 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1609
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001610 // Diagnose attempt to use a variable as a label.
1611 //
1612 // FIXME: Diagnostics. Note the location of the definition as a label.
1613 // FIXME: This doesn't diagnose assignment to a symbol which has been
1614 // implicitly marked as external.
Kevin Enderby0510b482010-05-17 23:08:19 +00001615 MCSymbol *Sym;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001616 if (LocalLabelVal == -1) {
1617 if (ParsingInlineAsm && SI) {
Nico Weber67e715f2015-06-19 23:43:47 +00001618 StringRef RewrittenLabel =
1619 SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true);
1620 assert(RewrittenLabel.size() &&
1621 "We should have an internal name here.");
Craig Topper7d5b2312015-10-10 05:25:02 +00001622 Info.AsmRewrites->emplace_back(AOK_Label, IDLoc, IDVal.size(),
1623 RewrittenLabel);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001624 IDVal = RewrittenLabel;
1625 }
Jim Grosbach6f482002015-05-18 18:43:14 +00001626 Sym = getContext().getOrCreateSymbol(IDVal);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001627 } else
Jim Grosbach6f482002015-05-18 18:43:14 +00001628 Sym = Ctx.createDirectionalLocalSymbol(LocalLabelVal);
David Majnemer58cb80c2014-12-24 10:27:50 +00001629
1630 Sym->redefineIfPossible();
1631
Daniel Dunbardeb7ba92010-05-05 19:01:00 +00001632 if (!Sym->isUndefined() || Sym->isVariable())
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001633 return Error(IDLoc, "invalid symbol redefinition");
Michael J. Spencer530ce852010-10-09 11:00:50 +00001634
Nirav Dave9263ae32016-08-02 19:17:54 +00001635 // End of Labels should be treated as end of line for lexing
1636 // purposes but that information is not available to the Lexer who
1637 // does not understand Labels. This may cause us to see a Hash
1638 // here instead of a preprocessor line comment.
1639 if (getTok().is(AsmToken::Hash)) {
1640 StringRef CommentStr = parseStringToEndOfStatement();
1641 Lexer.Lex();
1642 Lexer.UnLex(AsmToken(AsmToken::EndOfStatement, CommentStr));
1643 }
1644
Nirav Dave8ea792d2016-07-13 14:03:12 +00001645 // Consume any end of statement token, if present, to avoid spurious
1646 // AddBlankLine calls().
1647 if (getTok().is(AsmToken::EndOfStatement)) {
1648 Lex();
1649 }
1650
Daniel Dunbare73b2672009-08-26 22:13:22 +00001651 // Emit the label.
Chad Rosierf3feab32013-01-07 20:34:12 +00001652 if (!ParsingInlineAsm)
1653 Out.EmitLabel(Sym);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001654
Kevin Enderbye7739d42011-12-09 18:09:40 +00001655 // If we are generating dwarf for assembly source files then gather the
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001656 // info to make a dwarf label entry for this label if needed.
Kevin Enderbye7739d42011-12-09 18:09:40 +00001657 if (getContext().getGenDwarfForAssembly())
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001658 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1659 IDLoc);
Kevin Enderbye7739d42011-12-09 18:09:40 +00001660
Tim Northover1744d0a2013-10-25 12:49:50 +00001661 getTargetParser().onLabelParsed(Sym);
1662
Eli Friedman0f4871d2012-10-22 23:58:19 +00001663 return false;
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001664 }
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001665
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001666 case AsmToken::Equal:
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001667 if (!getTargetParser().equalIsAsmAssignment())
1668 break;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001669 // identifier '=' ... -> assignment statement
Sean Callanan686ed8d2010-01-19 20:22:31 +00001670 Lex();
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001671
Jim Grosbach4b905842013-09-20 23:08:21 +00001672 return parseAssignment(IDVal, true);
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001673
1674 default: // Normal instruction or directive.
1675 break;
Chris Lattner36e02122009-06-21 20:54:55 +00001676 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001677
1678 // If macros are enabled, check to see if this is a macro instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00001679 if (areMacrosEnabled())
1680 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1681 return handleMacroEntry(M, IDLoc);
Eli Bendersky38274122013-01-14 23:22:36 +00001682 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001683
Michael J. Spencer530ce852010-10-09 11:00:50 +00001684 // Otherwise, we have a normal instruction or directive.
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001685
Eli Bendersky17233942013-01-15 22:59:42 +00001686 // Directives start with "."
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001687 if (IDVal[0] == '.' && IDVal != ".") {
Eli Bendersky17233942013-01-15 22:59:42 +00001688 // There are several entities interested in parsing directives:
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001689 //
Eli Bendersky17233942013-01-15 22:59:42 +00001690 // 1. The target-specific assembly parser. Some directives are target
1691 // specific or may potentially behave differently on certain targets.
1692 // 2. Asm parser extensions. For example, platform-specific parsers
1693 // (like the ELF parser) register themselves as extensions.
1694 // 3. The generic directive parser implemented by this class. These are
1695 // all the directives that behave in a target and platform independent
1696 // manner, or at least have a default behavior that's shared between
1697 // all targets and platforms.
Akira Hatanakad3590752012-07-05 19:09:33 +00001698
Oliver Stannard21718282016-07-26 14:19:47 +00001699 getTargetParser().flushPendingInstructions(getStreamer());
1700
Nirav Dave2364748a2016-09-16 18:30:20 +00001701 SMLoc StartTokLoc = getTok().getLoc();
1702 bool TPDirectiveReturn = getTargetParser().ParseDirective(ID);
1703
1704 if (hasPendingError())
1705 return true;
1706 // Currently the return value should be true if we are
1707 // uninterested but as this is at odds with the standard parsing
1708 // convention (return true = error) we have instances of a parsed
1709 // directive that fails returning true as an error. Catch these
1710 // cases as best as possible errors here.
1711 if (TPDirectiveReturn && StartTokLoc != getTok().getLoc())
1712 return true;
1713 // Return if we did some parsing or believe we succeeded.
1714 if (!TPDirectiveReturn || StartTokLoc != getTok().getLoc())
Akira Hatanakad3590752012-07-05 19:09:33 +00001715 return false;
1716
Alp Tokercb402912014-01-24 17:20:08 +00001717 // Next, check the extension directive map to see if any extension has
Eli Bendersky17233942013-01-15 22:59:42 +00001718 // registered itself to parse this directive.
Jim Grosbach4b905842013-09-20 23:08:21 +00001719 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1720 ExtensionDirectiveMap.lookup(IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +00001721 if (Handler.first)
1722 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1723
1724 // Finally, if no one else is interested in this directive, it must be
1725 // generic and familiar to this class.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001726 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001727 default:
1728 break;
1729 case DK_SET:
1730 case DK_EQU:
1731 return parseDirectiveSet(IDVal, true);
1732 case DK_EQUIV:
1733 return parseDirectiveSet(IDVal, false);
1734 case DK_ASCII:
1735 return parseDirectiveAscii(IDVal, false);
1736 case DK_ASCIZ:
1737 case DK_STRING:
1738 return parseDirectiveAscii(IDVal, true);
1739 case DK_BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001740 case DK_DC_B:
1741 return parseDirectiveValue(IDVal, 1);
1742 case DK_DC:
1743 case DK_DC_W:
Jim Grosbach4b905842013-09-20 23:08:21 +00001744 case DK_SHORT:
1745 case DK_VALUE:
1746 case DK_2BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001747 return parseDirectiveValue(IDVal, 2);
Jim Grosbach4b905842013-09-20 23:08:21 +00001748 case DK_LONG:
1749 case DK_INT:
1750 case DK_4BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001751 case DK_DC_L:
1752 return parseDirectiveValue(IDVal, 4);
Jim Grosbach4b905842013-09-20 23:08:21 +00001753 case DK_QUAD:
1754 case DK_8BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001755 return parseDirectiveValue(IDVal, 8);
1756 case DK_DC_A:
1757 return parseDirectiveValue(IDVal,
1758 getContext().getAsmInfo()->getPointerSize());
David Woodhoused6de0d92014-02-01 16:20:59 +00001759 case DK_OCTA:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001760 return parseDirectiveOctaValue(IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001761 case DK_SINGLE:
1762 case DK_FLOAT:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001763 case DK_DC_S:
1764 return parseDirectiveRealValue(IDVal, APFloat::IEEEsingle);
Jim Grosbach4b905842013-09-20 23:08:21 +00001765 case DK_DOUBLE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001766 case DK_DC_D:
1767 return parseDirectiveRealValue(IDVal, APFloat::IEEEdouble);
Jim Grosbach4b905842013-09-20 23:08:21 +00001768 case DK_ALIGN: {
1769 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1770 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1771 }
1772 case DK_ALIGN32: {
1773 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1774 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1775 }
1776 case DK_BALIGN:
1777 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1778 case DK_BALIGNW:
1779 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1780 case DK_BALIGNL:
1781 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1782 case DK_P2ALIGN:
1783 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1784 case DK_P2ALIGNW:
1785 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1786 case DK_P2ALIGNL:
1787 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1788 case DK_ORG:
1789 return parseDirectiveOrg();
1790 case DK_FILL:
1791 return parseDirectiveFill();
1792 case DK_ZERO:
1793 return parseDirectiveZero();
1794 case DK_EXTERN:
1795 eatToEndOfStatement(); // .extern is the default, ignore it.
1796 return false;
1797 case DK_GLOBL:
1798 case DK_GLOBAL:
1799 return parseDirectiveSymbolAttribute(MCSA_Global);
1800 case DK_LAZY_REFERENCE:
1801 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1802 case DK_NO_DEAD_STRIP:
1803 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1804 case DK_SYMBOL_RESOLVER:
1805 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1806 case DK_PRIVATE_EXTERN:
1807 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1808 case DK_REFERENCE:
1809 return parseDirectiveSymbolAttribute(MCSA_Reference);
1810 case DK_WEAK_DEFINITION:
1811 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1812 case DK_WEAK_REFERENCE:
1813 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1814 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1815 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1816 case DK_COMM:
1817 case DK_COMMON:
1818 return parseDirectiveComm(/*IsLocal=*/false);
1819 case DK_LCOMM:
1820 return parseDirectiveComm(/*IsLocal=*/true);
1821 case DK_ABORT:
1822 return parseDirectiveAbort();
1823 case DK_INCLUDE:
1824 return parseDirectiveInclude();
1825 case DK_INCBIN:
1826 return parseDirectiveIncbin();
1827 case DK_CODE16:
1828 case DK_CODE16GCC:
Nirav Davefd910412016-06-17 16:06:17 +00001829 return TokError(Twine(IDVal) +
1830 " not currently supported for this target");
Jim Grosbach4b905842013-09-20 23:08:21 +00001831 case DK_REPT:
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00001832 return parseDirectiveRept(IDLoc, IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001833 case DK_IRP:
1834 return parseDirectiveIrp(IDLoc);
1835 case DK_IRPC:
1836 return parseDirectiveIrpc(IDLoc);
1837 case DK_ENDR:
1838 return parseDirectiveEndr(IDLoc);
1839 case DK_BUNDLE_ALIGN_MODE:
1840 return parseDirectiveBundleAlignMode();
1841 case DK_BUNDLE_LOCK:
1842 return parseDirectiveBundleLock();
1843 case DK_BUNDLE_UNLOCK:
1844 return parseDirectiveBundleUnlock();
1845 case DK_SLEB128:
1846 return parseDirectiveLEB128(true);
1847 case DK_ULEB128:
1848 return parseDirectiveLEB128(false);
1849 case DK_SPACE:
1850 case DK_SKIP:
1851 return parseDirectiveSpace(IDVal);
1852 case DK_FILE:
1853 return parseDirectiveFile(IDLoc);
1854 case DK_LINE:
1855 return parseDirectiveLine();
1856 case DK_LOC:
1857 return parseDirectiveLoc();
1858 case DK_STABS:
1859 return parseDirectiveStabs();
Reid Kleckner2214ed82016-01-29 00:49:42 +00001860 case DK_CV_FILE:
1861 return parseDirectiveCVFile();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00001862 case DK_CV_FUNC_ID:
1863 return parseDirectiveCVFuncId();
1864 case DK_CV_INLINE_SITE_ID:
1865 return parseDirectiveCVInlineSiteId();
Reid Kleckner2214ed82016-01-29 00:49:42 +00001866 case DK_CV_LOC:
1867 return parseDirectiveCVLoc();
1868 case DK_CV_LINETABLE:
1869 return parseDirectiveCVLinetable();
David Majnemer6fcbd7e2016-01-29 19:24:12 +00001870 case DK_CV_INLINE_LINETABLE:
1871 return parseDirectiveCVInlineLinetable();
David Majnemer408b5e62016-02-05 01:55:49 +00001872 case DK_CV_DEF_RANGE:
1873 return parseDirectiveCVDefRange();
Reid Kleckner2214ed82016-01-29 00:49:42 +00001874 case DK_CV_STRINGTABLE:
1875 return parseDirectiveCVStringTable();
1876 case DK_CV_FILECHECKSUMS:
1877 return parseDirectiveCVFileChecksums();
Jim Grosbach4b905842013-09-20 23:08:21 +00001878 case DK_CFI_SECTIONS:
1879 return parseDirectiveCFISections();
1880 case DK_CFI_STARTPROC:
1881 return parseDirectiveCFIStartProc();
1882 case DK_CFI_ENDPROC:
1883 return parseDirectiveCFIEndProc();
1884 case DK_CFI_DEF_CFA:
1885 return parseDirectiveCFIDefCfa(IDLoc);
1886 case DK_CFI_DEF_CFA_OFFSET:
1887 return parseDirectiveCFIDefCfaOffset();
1888 case DK_CFI_ADJUST_CFA_OFFSET:
1889 return parseDirectiveCFIAdjustCfaOffset();
1890 case DK_CFI_DEF_CFA_REGISTER:
1891 return parseDirectiveCFIDefCfaRegister(IDLoc);
1892 case DK_CFI_OFFSET:
1893 return parseDirectiveCFIOffset(IDLoc);
1894 case DK_CFI_REL_OFFSET:
1895 return parseDirectiveCFIRelOffset(IDLoc);
1896 case DK_CFI_PERSONALITY:
1897 return parseDirectiveCFIPersonalityOrLsda(true);
1898 case DK_CFI_LSDA:
1899 return parseDirectiveCFIPersonalityOrLsda(false);
1900 case DK_CFI_REMEMBER_STATE:
1901 return parseDirectiveCFIRememberState();
1902 case DK_CFI_RESTORE_STATE:
1903 return parseDirectiveCFIRestoreState();
1904 case DK_CFI_SAME_VALUE:
1905 return parseDirectiveCFISameValue(IDLoc);
1906 case DK_CFI_RESTORE:
1907 return parseDirectiveCFIRestore(IDLoc);
1908 case DK_CFI_ESCAPE:
1909 return parseDirectiveCFIEscape();
1910 case DK_CFI_SIGNAL_FRAME:
1911 return parseDirectiveCFISignalFrame();
1912 case DK_CFI_UNDEFINED:
1913 return parseDirectiveCFIUndefined(IDLoc);
1914 case DK_CFI_REGISTER:
1915 return parseDirectiveCFIRegister(IDLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00001916 case DK_CFI_WINDOW_SAVE:
1917 return parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +00001918 case DK_MACROS_ON:
1919 case DK_MACROS_OFF:
1920 return parseDirectiveMacrosOnOff(IDVal);
1921 case DK_MACRO:
1922 return parseDirectiveMacro(IDLoc);
Nico Weber155dccd12014-07-24 17:08:39 +00001923 case DK_EXITM:
1924 return parseDirectiveExitMacro(IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001925 case DK_ENDM:
1926 case DK_ENDMACRO:
1927 return parseDirectiveEndMacro(IDVal);
1928 case DK_PURGEM:
1929 return parseDirectivePurgeMacro(IDLoc);
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00001930 case DK_END:
1931 return parseDirectiveEnd(IDLoc);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00001932 case DK_ERR:
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00001933 return parseDirectiveError(IDLoc, false);
1934 case DK_ERROR:
1935 return parseDirectiveError(IDLoc, true);
Nico Weber404012b2014-07-24 16:26:06 +00001936 case DK_WARNING:
1937 return parseDirectiveWarning(IDLoc);
Daniel Sanders9f6ad492015-11-12 13:33:00 +00001938 case DK_RELOC:
1939 return parseDirectiveReloc(IDLoc);
Petr Hosek4cb08ce2016-09-23 19:25:15 +00001940 case DK_DCB:
1941 case DK_DCB_W:
1942 return parseDirectiveDCB(IDVal, 2);
1943 case DK_DCB_B:
1944 return parseDirectiveDCB(IDVal, 1);
1945 case DK_DCB_D:
1946 return parseDirectiveRealDCB(IDVal, APFloat::IEEEdouble);
1947 case DK_DCB_L:
1948 return parseDirectiveDCB(IDVal, 4);
1949 case DK_DCB_S:
1950 return parseDirectiveRealDCB(IDVal, APFloat::IEEEsingle);
Petr Hosek731bb9c2016-08-23 21:34:53 +00001951 case DK_DC_X:
Petr Hosek4cb08ce2016-09-23 19:25:15 +00001952 case DK_DCB_X:
Petr Hosek731bb9c2016-08-23 21:34:53 +00001953 return TokError(Twine(IDVal) +
1954 " not currently supported for this target");
Petr Hosek85b2f672016-09-23 21:53:36 +00001955 case DK_DS:
1956 case DK_DS_W:
1957 return parseDirectiveDS(IDVal, 2);
1958 case DK_DS_B:
1959 return parseDirectiveDS(IDVal, 1);
1960 case DK_DS_D:
1961 return parseDirectiveDS(IDVal, 8);
1962 case DK_DS_L:
1963 case DK_DS_S:
1964 return parseDirectiveDS(IDVal, 4);
1965 case DK_DS_P:
1966 case DK_DS_X:
1967 return parseDirectiveDS(IDVal, 12);
Eli Friedman20b02642010-07-19 04:17:25 +00001968 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00001969
Jim Grosbach758e0cc2012-05-01 18:38:27 +00001970 return Error(IDLoc, "unknown directive");
Chris Lattnere5074c42009-06-22 01:29:09 +00001971 }
Chris Lattner36e02122009-06-21 20:54:55 +00001972
Chad Rosierc7f552c2013-02-12 21:33:51 +00001973 // __asm _emit or __asm __emit
1974 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1975 IDVal == "_EMIT" || IDVal == "__EMIT"))
Jim Grosbach4b905842013-09-20 23:08:21 +00001976 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
Chad Rosierc7f552c2013-02-12 21:33:51 +00001977
1978 // __asm align
1979 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
Jim Grosbach4b905842013-09-20 23:08:21 +00001980 return parseDirectiveMSAlign(IDLoc, Info);
Eli Friedman0f4871d2012-10-22 23:58:19 +00001981
Michael Zuckerman02ecd432015-12-13 17:07:23 +00001982 if (ParsingInlineAsm && (IDVal == "even"))
1983 Info.AsmRewrites->emplace_back(AOK_EVEN, IDLoc, 4);
Nirav Davef43cc9f2016-10-10 15:24:54 +00001984 if (checkForValidSection())
1985 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00001986
Chris Lattner7cbfa442010-05-19 23:34:33 +00001987 // Canonicalize the opcode to lower case.
Eli Bendersky88024712013-01-16 19:32:36 +00001988 std::string OpcodeStr = IDVal.lower();
Chad Rosierf0e87202012-10-25 20:41:34 +00001989 ParseInstructionInfo IInfo(Info.AsmRewrites);
Nirav Dave2364748a2016-09-16 18:30:20 +00001990 bool ParseHadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, ID,
1991 Info.ParsedOperands);
1992 Info.ParseError = ParseHadError;
Chris Lattnere5074c42009-06-22 01:29:09 +00001993
Daniel Dunbar2eca0252010-08-11 06:37:09 +00001994 // Dump the parsed representation, if requested.
1995 if (getShowParsedOperands()) {
1996 SmallString<256> Str;
1997 raw_svector_ostream OS(Str);
1998 OS << "parsed instruction: [";
Eli Friedman0f4871d2012-10-22 23:58:19 +00001999 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002000 if (i != 0)
2001 OS << ", ";
Eli Friedman0f4871d2012-10-22 23:58:19 +00002002 Info.ParsedOperands[i]->print(OS);
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002003 }
2004 OS << "]";
2005
Jim Grosbach4b905842013-09-20 23:08:21 +00002006 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002007 }
2008
Nirav Dave2364748a2016-09-16 18:30:20 +00002009 // Fail even if ParseInstruction erroneously returns false.
2010 if (hasPendingError() || ParseHadError)
2011 return true;
2012
Oliver Stannard8b273082014-06-19 15:52:37 +00002013 // If we are generating dwarf for the current section then generate a .loc
2014 // directive for the instruction.
Nirav Dave2364748a2016-09-16 18:30:20 +00002015 if (!ParseHadError && getContext().getGenDwarfForAssembly() &&
Oliver Stannard8b273082014-06-19 15:52:37 +00002016 getContext().getGenDwarfSectionSyms().count(
Eric Christopher445c9522016-10-14 05:47:37 +00002017 getStreamer().getCurrentSectionOnly())) {
Saleem Abdulrasool4d6ed7c2014-12-24 06:32:43 +00002018 unsigned Line;
2019 if (ActiveMacros.empty())
2020 Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
2021 else
Frederic Riss16238d92015-06-25 21:57:33 +00002022 Line = SrcMgr.FindLineNumber(ActiveMacros.front()->InstantiationLoc,
2023 ActiveMacros.front()->ExitBuffer);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002024
Eli Bendersky88024712013-01-16 19:32:36 +00002025 // If we previously parsed a cpp hash file line comment then make sure the
2026 // current Dwarf File is for the CppHashFilename if not then emit the
2027 // Dwarf File table for it and adjust the line number for the .loc.
Tim Northoverc0bef992016-04-13 19:46:54 +00002028 if (CppHashInfo.Filename.size()) {
David Blaikiec714ef42014-03-17 01:52:11 +00002029 unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
Tim Northoverc0bef992016-04-13 19:46:54 +00002030 0, StringRef(), CppHashInfo.Filename);
David Blaikiec714ef42014-03-17 01:52:11 +00002031 getContext().setGenDwarfFileNumber(FileNumber);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002032
Jim Grosbach4b905842013-09-20 23:08:21 +00002033 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
2034 // cache with the different Loc from the call above we save the last
2035 // info we queried here with SrcMgr.FindLineNumber().
2036 unsigned CppHashLocLineNo;
Tim Northoverc0bef992016-04-13 19:46:54 +00002037 if (LastQueryIDLoc == CppHashInfo.Loc &&
2038 LastQueryBuffer == CppHashInfo.Buf)
Jim Grosbach4b905842013-09-20 23:08:21 +00002039 CppHashLocLineNo = LastQueryLine;
2040 else {
Tim Northoverc0bef992016-04-13 19:46:54 +00002041 CppHashLocLineNo =
2042 SrcMgr.FindLineNumber(CppHashInfo.Loc, CppHashInfo.Buf);
Jim Grosbach4b905842013-09-20 23:08:21 +00002043 LastQueryLine = CppHashLocLineNo;
Tim Northoverc0bef992016-04-13 19:46:54 +00002044 LastQueryIDLoc = CppHashInfo.Loc;
2045 LastQueryBuffer = CppHashInfo.Buf;
Jim Grosbach4b905842013-09-20 23:08:21 +00002046 }
Tim Northoverc0bef992016-04-13 19:46:54 +00002047 Line = CppHashInfo.LineNumber - 1 + (Line - CppHashLocLineNo);
Eli Bendersky88024712013-01-16 19:32:36 +00002048 }
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002049
Jim Grosbach4b905842013-09-20 23:08:21 +00002050 getStreamer().EmitDwarfLocDirective(
2051 getContext().getGenDwarfFileNumber(), Line, 0,
2052 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
2053 StringRef());
Kevin Enderby6469fc22011-11-01 22:27:22 +00002054 }
2055
Daniel Dunbarce0c1e12010-05-04 00:33:07 +00002056 // If parsing succeeded, match the instruction.
Nirav Dave2364748a2016-09-16 18:30:20 +00002057 if (!ParseHadError) {
Tim Northover26bb14e2014-08-18 11:49:42 +00002058 uint64_t ErrorInfo;
Nirav Dave2364748a2016-09-16 18:30:20 +00002059 if (getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
2060 Info.ParsedOperands, Out,
2061 ErrorInfo, ParsingInlineAsm))
2062 return true;
Chad Rosier49963552012-10-13 00:26:04 +00002063 }
Chris Lattnera2a9d162010-09-11 16:18:25 +00002064 return false;
Chris Lattnerb0133452009-06-21 20:16:42 +00002065}
Chris Lattnerbedf6c22009-06-24 04:43:34 +00002066
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00002067// Parse and erase curly braces marking block start/end
2068bool
2069AsmParser::parseCurlyBlockScope(SmallVectorImpl<AsmRewrite> &AsmStrRewrites) {
2070 // Identify curly brace marking block start/end
2071 if (Lexer.isNot(AsmToken::LCurly) && Lexer.isNot(AsmToken::RCurly))
2072 return false;
2073
2074 SMLoc StartLoc = Lexer.getLoc();
2075 Lex(); // Eat the brace
2076 if (Lexer.is(AsmToken::EndOfStatement))
2077 Lex(); // Eat EndOfStatement following the brace
2078
2079 // Erase the block start/end brace from the output asm string
2080 AsmStrRewrites.emplace_back(AOK_Skip, StartLoc, Lexer.getLoc().getPointer() -
2081 StartLoc.getPointer());
2082 return true;
2083}
2084
Jim Grosbach4b905842013-09-20 23:08:21 +00002085/// parseCppHashLineFilenameComment as this:
Kevin Enderby72553612011-09-13 23:45:18 +00002086/// ::= # number "filename"
Craig Topper3c76c522015-09-20 23:35:59 +00002087bool AsmParser::parseCppHashLineFilenameComment(SMLoc L) {
Kevin Enderby72553612011-09-13 23:45:18 +00002088 Lex(); // Eat the hash token.
Nirav Davefd910412016-06-17 16:06:17 +00002089 // Lexer only ever emits HashDirective if it fully formed if it's
2090 // done the checking already so this is an internal error.
2091 assert(getTok().is(AsmToken::Integer) &&
2092 "Lexing Cpp line comment: Expected Integer");
Kevin Enderby72553612011-09-13 23:45:18 +00002093 int64_t LineNumber = getTok().getIntVal();
Kevin Enderby72553612011-09-13 23:45:18 +00002094 Lex();
Nirav Davefd910412016-06-17 16:06:17 +00002095 assert(getTok().is(AsmToken::String) &&
2096 "Lexing Cpp line comment: Expected String");
Kevin Enderby72553612011-09-13 23:45:18 +00002097 StringRef Filename = getTok().getString();
Nirav Davefd910412016-06-17 16:06:17 +00002098 Lex();
Nirav Dave2364748a2016-09-16 18:30:20 +00002099
Kevin Enderby72553612011-09-13 23:45:18 +00002100 // Get rid of the enclosing quotes.
Jim Grosbach4b905842013-09-20 23:08:21 +00002101 Filename = Filename.substr(1, Filename.size() - 2);
Kevin Enderby72553612011-09-13 23:45:18 +00002102
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002103 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
Tim Northoverc0bef992016-04-13 19:46:54 +00002104 CppHashInfo.Loc = L;
2105 CppHashInfo.Filename = Filename;
2106 CppHashInfo.LineNumber = LineNumber;
2107 CppHashInfo.Buf = CurBuffer;
Kevin Enderby72553612011-09-13 23:45:18 +00002108 return false;
2109}
2110
Jim Grosbach4b905842013-09-20 23:08:21 +00002111/// \brief will use the last parsed cpp hash line filename comment
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002112/// for the Filename and LineNo if any in the diagnostic.
2113void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002114 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002115 raw_ostream &OS = errs();
2116
2117 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
Craig Topper3c76c522015-09-20 23:35:59 +00002118 SMLoc DiagLoc = Diag.getLoc();
Alp Tokera55b95b2014-07-06 10:33:31 +00002119 unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2120 unsigned CppHashBuf =
Tim Northoverc0bef992016-04-13 19:46:54 +00002121 Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashInfo.Loc);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002122
Jim Grosbach4b905842013-09-20 23:08:21 +00002123 // Like SourceMgr::printMessage() we need to print the include stack if any
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002124 // before printing the message.
Alp Tokera55b95b2014-07-06 10:33:31 +00002125 unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2126 if (!Parser->SavedDiagHandler && DiagCurBuffer &&
2127 DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002128 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
2129 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002130 }
2131
Eric Christophera7c32732012-12-18 00:30:54 +00002132 // If we have not parsed a cpp hash line filename comment or the source
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002133 // manager changed or buffer changed (like in a nested include) then just
2134 // print the normal diagnostic using its Filename and LineNo.
Tim Northoverc0bef992016-04-13 19:46:54 +00002135 if (!Parser->CppHashInfo.LineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002136 DiagBuf != CppHashBuf) {
Benjamin Kramer47f5e302011-10-16 10:48:29 +00002137 if (Parser->SavedDiagHandler)
2138 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
2139 else
Craig Topper353eda42014-04-24 06:44:33 +00002140 Diag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002141 return;
2142 }
2143
Eric Christophera7c32732012-12-18 00:30:54 +00002144 // Use the CppHashFilename and calculate a line number based on the
Tim Northoverc0bef992016-04-13 19:46:54 +00002145 // CppHashInfo.Loc and CppHashInfo.LineNumber relative to this Diag's SMLoc
2146 // for the diagnostic.
2147 const std::string &Filename = Parser->CppHashInfo.Filename;
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002148
2149 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
2150 int CppHashLocLineNo =
Tim Northoverc0bef992016-04-13 19:46:54 +00002151 Parser->SrcMgr.FindLineNumber(Parser->CppHashInfo.Loc, CppHashBuf);
Jim Grosbach4b905842013-09-20 23:08:21 +00002152 int LineNo =
Tim Northoverc0bef992016-04-13 19:46:54 +00002153 Parser->CppHashInfo.LineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002154
Jim Grosbach4b905842013-09-20 23:08:21 +00002155 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
2156 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
Chris Lattner72845262011-10-16 05:47:55 +00002157 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002158
Benjamin Kramer47f5e302011-10-16 10:48:29 +00002159 if (Parser->SavedDiagHandler)
2160 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
2161 else
Craig Topper353eda42014-04-24 06:44:33 +00002162 NewDiag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002163}
2164
Rafael Espindola2c064482012-08-21 18:29:30 +00002165// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
2166// difference being that that function accepts '@' as part of identifiers and
2167// we can't do that. AsmLexer.cpp should probably be changed to handle
2168// '@' as a special case when needed.
2169static bool isIdentifierChar(char c) {
Guy Benyei83c74e92013-02-12 21:21:59 +00002170 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
2171 c == '.';
Rafael Espindola2c064482012-08-21 18:29:30 +00002172}
2173
Rafael Espindola34b9c512012-06-03 23:57:14 +00002174bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00002175 ArrayRef<MCAsmMacroParameter> Parameters,
Toma Tabacu217116e2015-04-27 10:50:29 +00002176 ArrayRef<MCAsmMacroArgument> A,
Craig Topper3c76c522015-09-20 23:35:59 +00002177 bool EnableAtPseudoVariable, SMLoc L) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00002178 unsigned NParameters = Parameters.size();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002179 bool HasVararg = NParameters ? Parameters.back().Vararg : false;
Benjamin Kramer513e7442014-02-20 13:36:32 +00002180 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
Rafael Espindola1134ab232011-06-05 02:43:45 +00002181 return Error(L, "Wrong number of arguments");
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002182
Preston Gurd05500642012-09-19 20:36:12 +00002183 // A macro without parameters is handled differently on Darwin:
2184 // gas accepts no arguments and does no substitutions
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002185 while (!Body.empty()) {
2186 // Scan for the next substitution.
2187 std::size_t End = Body.size(), Pos = 0;
2188 for (; Pos != End; ++Pos) {
2189 // Check for a substitution or escape.
Benjamin Kramer513e7442014-02-20 13:36:32 +00002190 if (IsDarwin && !NParameters) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00002191 // This macro has no parameters, look for $0, $1, etc.
2192 if (Body[Pos] != '$' || Pos + 1 == End)
2193 continue;
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002194
Rafael Espindola1134ab232011-06-05 02:43:45 +00002195 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00002196 if (Next == '$' || Next == 'n' ||
2197 isdigit(static_cast<unsigned char>(Next)))
Rafael Espindola1134ab232011-06-05 02:43:45 +00002198 break;
2199 } else {
2200 // This macro has parameters, look for \foo, \bar, etc.
2201 if (Body[Pos] == '\\' && Pos + 1 != End)
2202 break;
2203 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002204 }
2205
2206 // Add the prefix.
2207 OS << Body.slice(0, Pos);
2208
2209 // Check if we reached the end.
2210 if (Pos == End)
2211 break;
2212
Benjamin Kramer513e7442014-02-20 13:36:32 +00002213 if (IsDarwin && !NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002214 switch (Body[Pos + 1]) {
2215 // $$ => $
Rafael Espindola1134ab232011-06-05 02:43:45 +00002216 case '$':
2217 OS << '$';
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002218 break;
2219
Jim Grosbach4b905842013-09-20 23:08:21 +00002220 // $n => number of arguments
Rafael Espindola1134ab232011-06-05 02:43:45 +00002221 case 'n':
2222 OS << A.size();
2223 break;
2224
Jim Grosbach4b905842013-09-20 23:08:21 +00002225 // $[0-9] => argument
Rafael Espindola1134ab232011-06-05 02:43:45 +00002226 default: {
2227 // Missing arguments are ignored.
Jim Grosbach4b905842013-09-20 23:08:21 +00002228 unsigned Index = Body[Pos + 1] - '0';
Rafael Espindola1134ab232011-06-05 02:43:45 +00002229 if (Index >= A.size())
2230 break;
2231
2232 // Otherwise substitute with the token values, with spaces eliminated.
Craig Topper84008482015-10-10 05:38:14 +00002233 for (const AsmToken &Token : A[Index])
2234 OS << Token.getString();
Rafael Espindola1134ab232011-06-05 02:43:45 +00002235 break;
2236 }
2237 }
2238 Pos += 2;
2239 } else {
2240 unsigned I = Pos + 1;
Toma Tabacu217116e2015-04-27 10:50:29 +00002241
2242 // Check for the \@ pseudo-variable.
2243 if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End)
Rafael Espindola1134ab232011-06-05 02:43:45 +00002244 ++I;
Toma Tabacu217116e2015-04-27 10:50:29 +00002245 else
2246 while (isIdentifierChar(Body[I]) && I + 1 != End)
2247 ++I;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002248
Jim Grosbach4b905842013-09-20 23:08:21 +00002249 const char *Begin = Body.data() + Pos + 1;
2250 StringRef Argument(Begin, I - (Pos + 1));
Rafael Espindola1134ab232011-06-05 02:43:45 +00002251 unsigned Index = 0;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002252
Toma Tabacu217116e2015-04-27 10:50:29 +00002253 if (Argument == "@") {
2254 OS << NumOfMacroInstantiations;
2255 Pos += 2;
Preston Gurd05500642012-09-19 20:36:12 +00002256 } else {
Toma Tabacu217116e2015-04-27 10:50:29 +00002257 for (; Index < NParameters; ++Index)
2258 if (Parameters[Index].Name == Argument)
2259 break;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002260
Toma Tabacu217116e2015-04-27 10:50:29 +00002261 if (Index == NParameters) {
2262 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
2263 Pos += 3;
2264 else {
2265 OS << '\\' << Argument;
2266 Pos = I;
2267 }
2268 } else {
2269 bool VarargParameter = HasVararg && Index == (NParameters - 1);
Craig Topper84008482015-10-10 05:38:14 +00002270 for (const AsmToken &Token : A[Index])
Toma Tabacu217116e2015-04-27 10:50:29 +00002271 // We expect no quotes around the string's contents when
2272 // parsing for varargs.
Craig Topper84008482015-10-10 05:38:14 +00002273 if (Token.getKind() != AsmToken::String || VarargParameter)
2274 OS << Token.getString();
Toma Tabacu217116e2015-04-27 10:50:29 +00002275 else
Craig Topper84008482015-10-10 05:38:14 +00002276 OS << Token.getStringContents();
Toma Tabacu217116e2015-04-27 10:50:29 +00002277
2278 Pos += 1 + Argument.size();
2279 }
Preston Gurd05500642012-09-19 20:36:12 +00002280 }
Rafael Espindola1134ab232011-06-05 02:43:45 +00002281 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002282 // Update the scan point.
Rafael Espindola1134ab232011-06-05 02:43:45 +00002283 Body = Body.substr(Pos);
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002284 }
Daniel Dunbar43235712010-07-18 18:54:11 +00002285
Rafael Espindola1134ab232011-06-05 02:43:45 +00002286 return false;
2287}
Daniel Dunbar43235712010-07-18 18:54:11 +00002288
Nico Weber2a8f9222014-07-24 16:29:04 +00002289MacroInstantiation::MacroInstantiation(SMLoc IL, int EB, SMLoc EL,
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002290 size_t CondStackDepth)
Rafael Espindolaf43a94e2014-08-17 22:48:55 +00002291 : InstantiationLoc(IL), ExitBuffer(EB), ExitLoc(EL),
Nico Weber155dccd12014-07-24 17:08:39 +00002292 CondStackDepth(CondStackDepth) {}
Daniel Dunbar43235712010-07-18 18:54:11 +00002293
Jim Grosbach4b905842013-09-20 23:08:21 +00002294static bool isOperator(AsmToken::TokenKind kind) {
2295 switch (kind) {
2296 default:
2297 return false;
2298 case AsmToken::Plus:
2299 case AsmToken::Minus:
2300 case AsmToken::Tilde:
2301 case AsmToken::Slash:
2302 case AsmToken::Star:
2303 case AsmToken::Dot:
2304 case AsmToken::Equal:
2305 case AsmToken::EqualEqual:
2306 case AsmToken::Pipe:
2307 case AsmToken::PipePipe:
2308 case AsmToken::Caret:
2309 case AsmToken::Amp:
2310 case AsmToken::AmpAmp:
2311 case AsmToken::Exclaim:
2312 case AsmToken::ExclaimEqual:
Jim Grosbach4b905842013-09-20 23:08:21 +00002313 case AsmToken::Less:
2314 case AsmToken::LessEqual:
2315 case AsmToken::LessLess:
2316 case AsmToken::LessGreater:
2317 case AsmToken::Greater:
2318 case AsmToken::GreaterEqual:
2319 case AsmToken::GreaterGreater:
2320 return true;
Preston Gurd05500642012-09-19 20:36:12 +00002321 }
2322}
2323
David Majnemer16252452014-01-29 00:07:39 +00002324namespace {
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002325
David Majnemer16252452014-01-29 00:07:39 +00002326class AsmLexerSkipSpaceRAII {
2327public:
2328 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
2329 Lexer.setSkipSpace(SkipSpace);
2330 }
2331
2332 ~AsmLexerSkipSpaceRAII() {
2333 Lexer.setSkipSpace(true);
2334 }
2335
2336private:
2337 AsmLexer &Lexer;
2338};
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002339
2340} // end anonymous namespace
David Majnemer16252452014-01-29 00:07:39 +00002341
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002342bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
2343
2344 if (Vararg) {
2345 if (Lexer.isNot(AsmToken::EndOfStatement)) {
2346 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002347 MA.emplace_back(AsmToken::String, Str);
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002348 }
2349 return false;
2350 }
2351
Rafael Espindola768b41c2012-06-15 14:02:34 +00002352 unsigned ParenLevel = 0;
Preston Gurd05500642012-09-19 20:36:12 +00002353
David Majnemer16252452014-01-29 00:07:39 +00002354 // Darwin doesn't use spaces to delmit arguments.
2355 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
Rafael Espindola768b41c2012-06-15 14:02:34 +00002356
Scott Egertona1fa68a2016-02-11 13:48:49 +00002357 bool SpaceEaten;
2358
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002359 while (true) {
Scott Egertona1fa68a2016-02-11 13:48:49 +00002360 SpaceEaten = false;
David Majnemer16252452014-01-29 00:07:39 +00002361 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002362 return TokError("unexpected token in macro instantiation");
Preston Gurd05500642012-09-19 20:36:12 +00002363
Scott Egertona1fa68a2016-02-11 13:48:49 +00002364 if (ParenLevel == 0) {
Preston Gurd05500642012-09-19 20:36:12 +00002365
Scott Egertona1fa68a2016-02-11 13:48:49 +00002366 if (Lexer.is(AsmToken::Comma))
2367 break;
2368
2369 if (Lexer.is(AsmToken::Space)) {
2370 SpaceEaten = true;
Nirav Dave1180e6892016-06-02 17:15:05 +00002371 Lexer.Lex(); // Eat spaces
Scott Egertona1fa68a2016-02-11 13:48:49 +00002372 }
Preston Gurd05500642012-09-19 20:36:12 +00002373
2374 // Spaces can delimit parameters, but could also be part an expression.
2375 // If the token after a space is an operator, add the token and the next
2376 // one into this argument
David Majnemer91fc4c22014-01-29 18:57:46 +00002377 if (!IsDarwin) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002378 if (isOperator(Lexer.getKind())) {
Scott Egertona1fa68a2016-02-11 13:48:49 +00002379 MA.push_back(getTok());
Nirav Dave1180e6892016-06-02 17:15:05 +00002380 Lexer.Lex();
Preston Gurd05500642012-09-19 20:36:12 +00002381
Scott Egertona1fa68a2016-02-11 13:48:49 +00002382 // Whitespace after an operator can be ignored.
2383 if (Lexer.is(AsmToken::Space))
Nirav Dave1180e6892016-06-02 17:15:05 +00002384 Lexer.Lex();
Scott Egertona1fa68a2016-02-11 13:48:49 +00002385
2386 continue;
Preston Gurd05500642012-09-19 20:36:12 +00002387 }
2388 }
Scott Egertona1fa68a2016-02-11 13:48:49 +00002389 if (SpaceEaten)
2390 break;
Preston Gurd05500642012-09-19 20:36:12 +00002391 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002392
Jim Grosbach4b905842013-09-20 23:08:21 +00002393 // handleMacroEntry relies on not advancing the lexer here
Rafael Espindola768b41c2012-06-15 14:02:34 +00002394 // to be able to fill in the remaining default parameter values
2395 if (Lexer.is(AsmToken::EndOfStatement))
2396 break;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002397
2398 // Adjust the current parentheses level.
2399 if (Lexer.is(AsmToken::LParen))
2400 ++ParenLevel;
2401 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
2402 --ParenLevel;
2403
2404 // Append the token to the current argument list.
2405 MA.push_back(getTok());
Nirav Dave1180e6892016-06-02 17:15:05 +00002406 Lexer.Lex();
Rafael Espindola768b41c2012-06-15 14:02:34 +00002407 }
Preston Gurd05500642012-09-19 20:36:12 +00002408
Rafael Espindola768b41c2012-06-15 14:02:34 +00002409 if (ParenLevel != 0)
Rafael Espindola3e5eb422012-08-21 15:55:04 +00002410 return TokError("unbalanced parentheses in macro argument");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002411 return false;
2412}
2413
2414// Parse the macro instantiation arguments.
Jim Grosbach4b905842013-09-20 23:08:21 +00002415bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
Vladimir Medic9bad0d332013-08-20 13:33:18 +00002416 MCAsmMacroArguments &A) {
Rafael Espindola768b41c2012-06-15 14:02:34 +00002417 const unsigned NParameters = M ? M->Parameters.size() : 0;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002418 bool NamedParametersFound = false;
2419 SmallVector<SMLoc, 4> FALocs;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002420
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002421 A.resize(NParameters);
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002422 FALocs.resize(NParameters);
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002423
Rafael Espindola768b41c2012-06-15 14:02:34 +00002424 // Parse two kinds of macro invocations:
2425 // - macros defined without any parameters accept an arbitrary number of them
2426 // - macros defined with parameters accept at most that many of them
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002427 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002428 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
2429 ++Parameter) {
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002430 SMLoc IDLoc = Lexer.getLoc();
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002431 MCAsmMacroParameter FA;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002432
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002433 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00002434 if (parseIdentifier(FA.Name))
2435 return Error(IDLoc, "invalid argument identifier for formal argument");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002436
Nirav Dave2364748a2016-09-16 18:30:20 +00002437 if (Lexer.isNot(AsmToken::Equal))
2438 return TokError("expected '=' after formal parameter identifier");
2439
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002440 Lex();
2441
2442 NamedParametersFound = true;
2443 }
2444
Nirav Dave2364748a2016-09-16 18:30:20 +00002445 if (NamedParametersFound && FA.Name.empty())
2446 return Error(IDLoc, "cannot mix positional and keyword arguments");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002447
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002448 bool Vararg = HasVararg && Parameter == (NParameters - 1);
2449 if (parseMacroArgument(FA.Value, Vararg))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002450 return true;
2451
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002452 unsigned PI = Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002453 if (!FA.Name.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002454 unsigned FAI = 0;
2455 for (FAI = 0; FAI < NParameters; ++FAI)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002456 if (M->Parameters[FAI].Name == FA.Name)
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002457 break;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002458
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002459 if (FAI >= NParameters) {
Nirav Davefd910412016-06-17 16:06:17 +00002460 assert(M && "expected macro to be defined");
Nirav Dave2364748a2016-09-16 18:30:20 +00002461 return Error(IDLoc, "parameter named '" + FA.Name +
2462 "' does not exist for macro '" + M->Name + "'");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002463 }
2464 PI = FAI;
2465 }
2466
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002467 if (!FA.Value.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002468 if (A.size() <= PI)
2469 A.resize(PI + 1);
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002470 A[PI] = FA.Value;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002471
2472 if (FALocs.size() <= PI)
2473 FALocs.resize(PI + 1);
2474
2475 FALocs[PI] = Lexer.getLoc();
Preston Gurd242ed3152012-09-19 20:29:04 +00002476 }
Jim Grosbach206661622012-07-30 22:44:17 +00002477
Preston Gurd242ed3152012-09-19 20:29:04 +00002478 // At the end of the statement, fill in remaining arguments that have
2479 // default values. If there aren't any, then the next argument is
2480 // required but missing
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002481 if (Lexer.is(AsmToken::EndOfStatement)) {
2482 bool Failure = false;
2483 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2484 if (A[FAI].empty()) {
2485 if (M->Parameters[FAI].Required) {
2486 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2487 "missing value for required parameter "
2488 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2489 Failure = true;
2490 }
2491
2492 if (!M->Parameters[FAI].Value.empty())
2493 A[FAI] = M->Parameters[FAI].Value;
2494 }
2495 }
2496 return Failure;
2497 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002498
2499 if (Lexer.is(AsmToken::Comma))
2500 Lex();
2501 }
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002502
2503 return TokError("too many positional arguments");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002504}
2505
Jim Grosbach4b905842013-09-20 23:08:21 +00002506const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002507 StringMap<MCAsmMacro>::iterator I = MacroMap.find(Name);
2508 return (I == MacroMap.end()) ? nullptr : &I->getValue();
Eli Bendersky38274122013-01-14 23:22:36 +00002509}
2510
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002511void AsmParser::defineMacro(StringRef Name, MCAsmMacro Macro) {
2512 MacroMap.insert(std::make_pair(Name, std::move(Macro)));
Eli Bendersky38274122013-01-14 23:22:36 +00002513}
2514
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002515void AsmParser::undefineMacro(StringRef Name) { MacroMap.erase(Name); }
Eli Bendersky38274122013-01-14 23:22:36 +00002516
Jim Grosbach4b905842013-09-20 23:08:21 +00002517bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
Davide Italiano7c9fc732016-07-27 05:51:56 +00002518 // Arbitrarily limit macro nesting depth (default matches 'as'). We can
2519 // eliminate this, although we should protect against infinite loops.
2520 unsigned MaxNestingDepth = AsmMacroMaxNestingDepth;
2521 if (ActiveMacros.size() == MaxNestingDepth) {
2522 std::ostringstream MaxNestingDepthError;
2523 MaxNestingDepthError << "macros cannot be nested more than "
2524 << MaxNestingDepth << " levels deep."
2525 << " Use -asm-macro-max-nesting-depth to increase "
2526 "this limit.";
2527 return TokError(MaxNestingDepthError.str());
2528 }
Daniel Dunbar43235712010-07-18 18:54:11 +00002529
Eli Bendersky38274122013-01-14 23:22:36 +00002530 MCAsmMacroArguments A;
Jim Grosbach4b905842013-09-20 23:08:21 +00002531 if (parseMacroArguments(M, A))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002532 return true;
Daniel Dunbar43235712010-07-18 18:54:11 +00002533
Rafael Espindola1134ab232011-06-05 02:43:45 +00002534 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2535 // to hold the macro body with substitutions.
2536 SmallString<256> Buf;
2537 StringRef Body = M->Body;
Rafael Espindola34b9c512012-06-03 23:57:14 +00002538 raw_svector_ostream OS(Buf);
Rafael Espindola1134ab232011-06-05 02:43:45 +00002539
Toma Tabacu217116e2015-04-27 10:50:29 +00002540 if (expandMacro(OS, Body, M->Parameters, A, true, getTok().getLoc()))
Rafael Espindola1134ab232011-06-05 02:43:45 +00002541 return true;
2542
Eli Bendersky38274122013-01-14 23:22:36 +00002543 // We include the .endmacro in the buffer as our cue to exit the macro
Rafael Espindola34b9c512012-06-03 23:57:14 +00002544 // instantiation.
2545 OS << ".endmacro\n";
2546
Rafael Espindola3560ff22014-08-27 20:03:13 +00002547 std::unique_ptr<MemoryBuffer> Instantiation =
2548 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola1134ab232011-06-05 02:43:45 +00002549
Daniel Dunbar43235712010-07-18 18:54:11 +00002550 // Create the macro instantiation object and add to the current macro
2551 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002552 MacroInstantiation *MI = new MacroInstantiation(
2553 NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Daniel Dunbar43235712010-07-18 18:54:11 +00002554 ActiveMacros.push_back(MI);
2555
Toma Tabacu217116e2015-04-27 10:50:29 +00002556 ++NumOfMacroInstantiations;
2557
Daniel Dunbar43235712010-07-18 18:54:11 +00002558 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00002559 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00002560 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar43235712010-07-18 18:54:11 +00002561 Lex();
2562
2563 return false;
2564}
2565
Jim Grosbach4b905842013-09-20 23:08:21 +00002566void AsmParser::handleMacroExit() {
Daniel Dunbar43235712010-07-18 18:54:11 +00002567 // Jump to the EndOfStatement we should return to, and consume it.
Jim Grosbach4b905842013-09-20 23:08:21 +00002568 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
Daniel Dunbar43235712010-07-18 18:54:11 +00002569 Lex();
2570
2571 // Pop the instantiation entry.
2572 delete ActiveMacros.back();
2573 ActiveMacros.pop_back();
2574}
2575
Jim Grosbach4b905842013-09-20 23:08:21 +00002576bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
Jim Grosbachb7b750d2012-09-13 23:11:31 +00002577 bool NoDeadStrip) {
Pete Cooper80d21cb2015-06-22 19:35:57 +00002578 MCSymbol *Sym;
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002579 const MCExpr *Value;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002580 if (MCParserUtils::parseAssignmentExpression(Name, allow_redef, *this, Sym,
2581 Value))
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002582 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002583
Pete Cooper80d21cb2015-06-22 19:35:57 +00002584 if (!Sym) {
2585 // In the case where we parse an expression starting with a '.', we will
2586 // not generate an error, nor will we create a symbol. In this case we
2587 // should just return out.
Anders Waldenborg84809572014-02-17 20:48:32 +00002588 return false;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002589 }
David Majnemer58cb80c2014-12-24 10:27:50 +00002590
Daniel Dunbarae7ac012009-06-29 23:43:14 +00002591 // Do the assignment.
Daniel Dunbarb7b20972009-08-31 08:09:09 +00002592 Out.EmitAssignment(Sym, Value);
Jim Grosbachb7b750d2012-09-13 23:11:31 +00002593 if (NoDeadStrip)
2594 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2595
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002596 return false;
2597}
2598
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002599/// parseIdentifier:
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002600/// ::= identifier
2601/// ::= string
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002602bool AsmParser::parseIdentifier(StringRef &Res) {
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002603 // The assembler has relaxed rules for accepting identifiers, in particular we
Hans Wennborgce69d772013-10-18 20:46:28 +00002604 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2605 // separate tokens. At this level, we have already lexed so we cannot (currently)
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002606 // handle this as a context dependent token, instead we detect adjacent tokens
2607 // and return the combined identifier.
Hans Wennborgce69d772013-10-18 20:46:28 +00002608 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2609 SMLoc PrefixLoc = getLexer().getLoc();
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002610
Hans Wennborgce69d772013-10-18 20:46:28 +00002611 // Consume the prefix character, and check for a following identifier.
Nirav Daved0463322016-10-12 13:58:07 +00002612
2613 AsmToken Buf[1];
2614 Lexer.peekTokens(Buf, false);
2615
2616 if (Buf[0].isNot(AsmToken::Identifier))
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002617 return true;
2618
Hans Wennborgce69d772013-10-18 20:46:28 +00002619 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
Nirav Daved0463322016-10-12 13:58:07 +00002620 if (PrefixLoc.getPointer() + 1 != Buf[0].getLoc().getPointer())
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002621 return true;
2622
Nirav Daved0463322016-10-12 13:58:07 +00002623 // eat $ or @
2624 Lexer.Lex(); // Lexer's Lex guarantees consecutive token.
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002625 // Construct the joined identifier and consume the token.
Jim Grosbach4b905842013-09-20 23:08:21 +00002626 Res =
Hans Wennborgce69d772013-10-18 20:46:28 +00002627 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
Nirav Davefd910412016-06-17 16:06:17 +00002628 Lex(); // Parser Lex to maintain invariants.
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002629 return false;
2630 }
2631
Jim Grosbach4b905842013-09-20 23:08:21 +00002632 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002633 return true;
2634
Sean Callanan936b0d32010-01-19 21:44:56 +00002635 Res = getTok().getIdentifier();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002636
Sean Callanan686ed8d2010-01-19 20:22:31 +00002637 Lex(); // Consume the identifier token.
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002638
2639 return false;
2640}
2641
Jim Grosbach4b905842013-09-20 23:08:21 +00002642/// parseDirectiveSet:
Nico Weber4ada0d92011-01-28 03:04:41 +00002643/// ::= .equ identifier ',' expression
2644/// ::= .equiv identifier ',' expression
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002645/// ::= .set identifier ',' expression
Jim Grosbach4b905842013-09-20 23:08:21 +00002646bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002647 StringRef Name;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002648 if (check(parseIdentifier(Name), "expected identifier") ||
2649 parseToken(AsmToken::Comma) || parseAssignment(Name, allow_redef, true))
2650 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
2651 return false;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002652}
2653
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002654bool AsmParser::parseEscapedString(std::string &Data) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00002655 if (check(getTok().isNot(AsmToken::String), "expected string"))
2656 return true;
Daniel Dunbaref668c12009-08-14 18:19:52 +00002657
2658 Data = "";
Sean Callanan936b0d32010-01-19 21:44:56 +00002659 StringRef Str = getTok().getStringContents();
Daniel Dunbaref668c12009-08-14 18:19:52 +00002660 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2661 if (Str[i] != '\\') {
2662 Data += Str[i];
2663 continue;
2664 }
2665
2666 // Recognize escaped characters. Note that this escape semantics currently
2667 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2668 ++i;
2669 if (i == e)
2670 return TokError("unexpected backslash at end of string");
2671
2672 // Recognize octal sequences.
Jim Grosbach4b905842013-09-20 23:08:21 +00002673 if ((unsigned)(Str[i] - '0') <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002674 // Consume up to three octal characters.
2675 unsigned Value = Str[i] - '0';
2676
Jim Grosbach4b905842013-09-20 23:08:21 +00002677 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002678 ++i;
2679 Value = Value * 8 + (Str[i] - '0');
2680
Jim Grosbach4b905842013-09-20 23:08:21 +00002681 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002682 ++i;
2683 Value = Value * 8 + (Str[i] - '0');
2684 }
2685 }
2686
2687 if (Value > 255)
2688 return TokError("invalid octal escape sequence (out of range)");
2689
Jim Grosbach4b905842013-09-20 23:08:21 +00002690 Data += (unsigned char)Value;
Daniel Dunbaref668c12009-08-14 18:19:52 +00002691 continue;
2692 }
2693
2694 // Otherwise recognize individual escapes.
2695 switch (Str[i]) {
2696 default:
2697 // Just reject invalid escape sequences for now.
2698 return TokError("invalid escape sequence (unrecognized character)");
2699
2700 case 'b': Data += '\b'; break;
2701 case 'f': Data += '\f'; break;
2702 case 'n': Data += '\n'; break;
2703 case 'r': Data += '\r'; break;
2704 case 't': Data += '\t'; break;
2705 case '"': Data += '"'; break;
2706 case '\\': Data += '\\'; break;
2707 }
2708 }
2709
Nirav Davea645433c2016-07-18 15:24:03 +00002710 Lex();
Daniel Dunbaref668c12009-08-14 18:19:52 +00002711 return false;
2712}
2713
Jim Grosbach4b905842013-09-20 23:08:21 +00002714/// parseDirectiveAscii:
Rafael Espindola63760ba2010-10-28 20:02:27 +00002715/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002716bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00002717 auto parseOp = [&]() -> bool {
2718 std::string Data;
2719 if (checkForValidSection() || parseEscapedString(Data))
Nirav Davef43cc9f2016-10-10 15:24:54 +00002720 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002721 getStreamer().EmitBytes(Data);
2722 if (ZeroTerminated)
2723 getStreamer().EmitBytes(StringRef("\0", 1));
2724 return false;
2725 };
Daniel Dunbare5444a82010-09-09 22:42:59 +00002726
Nirav Dave1a9044b2016-10-24 14:35:29 +00002727 if (parseMany(parseOp))
2728 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbara10e5192009-06-24 23:30:00 +00002729 return false;
2730}
2731
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002732/// parseDirectiveReloc
2733/// ::= .reloc expression , identifier [ , expression ]
2734bool AsmParser::parseDirectiveReloc(SMLoc DirectiveLoc) {
2735 const MCExpr *Offset;
2736 const MCExpr *Expr = nullptr;
2737
2738 SMLoc OffsetLoc = Lexer.getTok().getLoc();
Nirav Dave1a9044b2016-10-24 14:35:29 +00002739 int64_t OffsetValue;
2740 // We can only deal with constant expressions at the moment.
2741
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002742 if (parseExpression(Offset))
2743 return true;
2744
Nirav Davea645433c2016-07-18 15:24:03 +00002745 if (check(!Offset->evaluateAsAbsolute(OffsetValue), OffsetLoc,
2746 "expression is not a constant value") ||
2747 check(OffsetValue < 0, OffsetLoc, "expression is negative") ||
2748 parseToken(AsmToken::Comma, "expected comma") ||
2749 check(getTok().isNot(AsmToken::Identifier), "expected relocation name"))
2750 return true;
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002751
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002752 SMLoc NameLoc = Lexer.getTok().getLoc();
2753 StringRef Name = Lexer.getTok().getIdentifier();
Nirav Davefd910412016-06-17 16:06:17 +00002754 Lex();
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002755
2756 if (Lexer.is(AsmToken::Comma)) {
Nirav Davefd910412016-06-17 16:06:17 +00002757 Lex();
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002758 SMLoc ExprLoc = Lexer.getLoc();
2759 if (parseExpression(Expr))
2760 return true;
2761
2762 MCValue Value;
2763 if (!Expr->evaluateAsRelocatable(Value, nullptr, nullptr))
2764 return Error(ExprLoc, "expression must be relocatable");
2765 }
2766
Nirav Davea645433c2016-07-18 15:24:03 +00002767 if (parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00002768 "unexpected token in .reloc directive"))
2769 return true;
2770
2771 if (getStreamer().EmitRelocDirective(*Offset, Name, Expr, DirectiveLoc))
2772 return Error(NameLoc, "unknown relocation name");
2773
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002774 return false;
2775}
2776
Jim Grosbach4b905842013-09-20 23:08:21 +00002777/// parseDirectiveValue
Daniel Dunbara10e5192009-06-24 23:30:00 +00002778/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00002779bool AsmParser::parseDirectiveValue(StringRef IDVal, unsigned Size) {
2780 auto parseOp = [&]() -> bool {
2781 const MCExpr *Value;
2782 SMLoc ExprLoc = getLexer().getLoc();
2783 if (checkForValidSection() || parseExpression(Value))
Nirav Davef43cc9f2016-10-10 15:24:54 +00002784 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002785 // Special case constant expressions to match code generator.
2786 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2787 assert(Size <= 8 && "Invalid size");
2788 uint64_t IntValue = MCE->getValue();
2789 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2790 return Error(ExprLoc, "out of range literal value");
2791 getStreamer().EmitIntValue(IntValue, Size);
2792 } else
2793 getStreamer().EmitValue(Value, Size, ExprLoc);
2794 return false;
2795 };
Daniel Dunbare5444a82010-09-09 22:42:59 +00002796
Nirav Dave1a9044b2016-10-24 14:35:29 +00002797 if (parseMany(parseOp))
2798 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbara10e5192009-06-24 23:30:00 +00002799 return false;
2800}
2801
David Woodhoused6de0d92014-02-01 16:20:59 +00002802/// ParseDirectiveOctaValue
2803/// ::= .octa [ hexconstant (, hexconstant)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00002804
2805bool AsmParser::parseDirectiveOctaValue(StringRef IDVal) {
2806 auto parseOp = [&]() -> bool {
Nirav Davef43cc9f2016-10-10 15:24:54 +00002807 if (checkForValidSection())
2808 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002809 if (getTok().isNot(AsmToken::Integer) && getTok().isNot(AsmToken::BigNum))
2810 return TokError("unknown token in expression");
2811 SMLoc ExprLoc = getTok().getLoc();
2812 APInt IntValue = getTok().getAPIntVal();
2813 uint64_t hi, lo;
2814 Lex();
2815 if (!IntValue.isIntN(128))
2816 return Error(ExprLoc, "out of range literal value");
2817 if (!IntValue.isIntN(64)) {
2818 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
2819 lo = IntValue.getLoBits(64).getZExtValue();
2820 } else {
2821 hi = 0;
2822 lo = IntValue.getZExtValue();
David Woodhoused6de0d92014-02-01 16:20:59 +00002823 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00002824 if (MAI.isLittleEndian()) {
2825 getStreamer().EmitIntValue(lo, 8);
2826 getStreamer().EmitIntValue(hi, 8);
2827 } else {
2828 getStreamer().EmitIntValue(hi, 8);
2829 getStreamer().EmitIntValue(lo, 8);
2830 }
2831 return false;
2832 };
David Woodhoused6de0d92014-02-01 16:20:59 +00002833
Nirav Dave1a9044b2016-10-24 14:35:29 +00002834 if (parseMany(parseOp))
2835 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
David Woodhoused6de0d92014-02-01 16:20:59 +00002836 return false;
2837}
2838
Petr Hosek4cb08ce2016-09-23 19:25:15 +00002839bool AsmParser::parseRealValue(const fltSemantics &Semantics, APInt &Res) {
2840 // We don't truly support arithmetic on floating point expressions, so we
2841 // have to manually parse unary prefixes.
2842 bool IsNeg = false;
2843 if (getLexer().is(AsmToken::Minus)) {
2844 Lexer.Lex();
2845 IsNeg = true;
2846 } else if (getLexer().is(AsmToken::Plus))
2847 Lexer.Lex();
2848
2849 if (Lexer.is(AsmToken::Error))
2850 return TokError(Lexer.getErr());
2851 if (Lexer.isNot(AsmToken::Integer) && Lexer.isNot(AsmToken::Real) &&
2852 Lexer.isNot(AsmToken::Identifier))
2853 return TokError("unexpected token in directive");
2854
2855 // Convert to an APFloat.
2856 APFloat Value(Semantics);
2857 StringRef IDVal = getTok().getString();
2858 if (getLexer().is(AsmToken::Identifier)) {
2859 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2860 Value = APFloat::getInf(Semantics);
2861 else if (!IDVal.compare_lower("nan"))
2862 Value = APFloat::getNaN(Semantics, false, ~0);
2863 else
2864 return TokError("invalid floating point literal");
2865 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2866 APFloat::opInvalidOp)
2867 return TokError("invalid floating point literal");
2868 if (IsNeg)
2869 Value.changeSign();
2870
2871 // Consume the numeric token.
2872 Lex();
2873
2874 Res = Value.bitcastToAPInt();
2875
2876 return false;
2877}
2878
Jim Grosbach4b905842013-09-20 23:08:21 +00002879/// parseDirectiveRealValue
Daniel Dunbar2af16532010-09-24 01:59:56 +00002880/// ::= (.single | .double) [ expression (, expression)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00002881bool AsmParser::parseDirectiveRealValue(StringRef IDVal,
2882 const fltSemantics &Semantics) {
2883 auto parseOp = [&]() -> bool {
2884 APInt AsInt;
2885 if (checkForValidSection() || parseRealValue(Semantics, AsInt))
Nirav Davef43cc9f2016-10-10 15:24:54 +00002886 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002887 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2888 AsInt.getBitWidth() / 8);
2889 return false;
2890 };
Daniel Dunbar2af16532010-09-24 01:59:56 +00002891
Nirav Dave1a9044b2016-10-24 14:35:29 +00002892 if (parseMany(parseOp))
2893 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbar2af16532010-09-24 01:59:56 +00002894 return false;
2895}
2896
Jim Grosbach4b905842013-09-20 23:08:21 +00002897/// parseDirectiveZero
Rafael Espindola922e3f42010-09-16 15:03:59 +00002898/// ::= .zero expression
Jim Grosbach4b905842013-09-20 23:08:21 +00002899bool AsmParser::parseDirectiveZero() {
Petr Hosek67a94a72016-05-28 05:57:48 +00002900 SMLoc NumBytesLoc = Lexer.getLoc();
2901 const MCExpr *NumBytes;
Nirav Davef43cc9f2016-10-10 15:24:54 +00002902 if (checkForValidSection() || parseExpression(NumBytes))
Rafael Espindola922e3f42010-09-16 15:03:59 +00002903 return true;
2904
Rafael Espindolab91bac62010-10-05 19:42:57 +00002905 int64_t Val = 0;
2906 if (getLexer().is(AsmToken::Comma)) {
2907 Lex();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002908 if (parseAbsoluteExpression(Val))
Rafael Espindolab91bac62010-10-05 19:42:57 +00002909 return true;
2910 }
2911
Nirav Davea645433c2016-07-18 15:24:03 +00002912 if (parseToken(AsmToken::EndOfStatement,
2913 "unexpected token in '.zero' directive"))
2914 return true;
Petr Hosek67a94a72016-05-28 05:57:48 +00002915 getStreamer().emitFill(*NumBytes, Val, NumBytesLoc);
Rafael Espindola922e3f42010-09-16 15:03:59 +00002916
2917 return false;
2918}
2919
Jim Grosbach4b905842013-09-20 23:08:21 +00002920/// parseDirectiveFill
Roman Divackye33098f2013-09-24 17:44:41 +00002921/// ::= .fill expression [ , expression [ , expression ] ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002922bool AsmParser::parseDirectiveFill() {
Petr Hosek67a94a72016-05-28 05:57:48 +00002923 SMLoc NumValuesLoc = Lexer.getLoc();
2924 const MCExpr *NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00002925 if (checkForValidSection() || parseExpression(NumValues))
Daniel Dunbara10e5192009-06-24 23:30:00 +00002926 return true;
2927
Roman Divackye33098f2013-09-24 17:44:41 +00002928 int64_t FillSize = 1;
2929 int64_t FillExpr = 0;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002930
David Majnemer522d3db2014-02-01 07:19:38 +00002931 SMLoc SizeLoc, ExprLoc;
Daniel Dunbara10e5192009-06-24 23:30:00 +00002932
Nirav Dave1a9044b2016-10-24 14:35:29 +00002933 if (parseOptionalToken(AsmToken::Comma)) {
2934 SizeLoc = getTok().getLoc();
2935 if (parseAbsoluteExpression(FillSize))
Roman Divackye33098f2013-09-24 17:44:41 +00002936 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002937 if (parseOptionalToken(AsmToken::Comma)) {
2938 ExprLoc = getTok().getLoc();
2939 if (parseAbsoluteExpression(FillExpr))
Roman Divackye33098f2013-09-24 17:44:41 +00002940 return true;
Roman Divackye33098f2013-09-24 17:44:41 +00002941 }
2942 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00002943 if (parseToken(AsmToken::EndOfStatement,
2944 "unexpected token in '.fill' directive"))
2945 return true;
Daniel Dunbara10e5192009-06-24 23:30:00 +00002946
David Majnemer522d3db2014-02-01 07:19:38 +00002947 if (FillSize < 0) {
2948 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
Petr Hosek6abd38b2016-05-28 08:20:08 +00002949 return false;
David Majnemer522d3db2014-02-01 07:19:38 +00002950 }
2951 if (FillSize > 8) {
2952 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
2953 FillSize = 8;
2954 }
Daniel Dunbara10e5192009-06-24 23:30:00 +00002955
David Majnemer522d3db2014-02-01 07:19:38 +00002956 if (!isUInt<32>(FillExpr) && FillSize > 4)
2957 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
2958
Petr Hosek67a94a72016-05-28 05:57:48 +00002959 getStreamer().emitFill(*NumValues, FillSize, FillExpr, NumValuesLoc);
Daniel Dunbara10e5192009-06-24 23:30:00 +00002960
2961 return false;
2962}
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002963
Jim Grosbach4b905842013-09-20 23:08:21 +00002964/// parseDirectiveOrg
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002965/// ::= .org expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002966bool AsmParser::parseDirectiveOrg() {
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002967 const MCExpr *Offset;
Nirav Davef43cc9f2016-10-10 15:24:54 +00002968 if (checkForValidSection() || parseExpression(Offset))
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002969 return true;
2970
2971 // Parse optional fill expression.
2972 int64_t FillExpr = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002973 if (parseOptionalToken(AsmToken::Comma))
2974 if (parseAbsoluteExpression(FillExpr))
2975 return addErrorSuffix(" in '.org' directive");
2976 if (parseToken(AsmToken::EndOfStatement))
2977 return addErrorSuffix(" in '.org' directive");
Nirav Davea645433c2016-07-18 15:24:03 +00002978
Rafael Espindola7ae65d82015-11-04 23:59:18 +00002979 getStreamer().emitValueToOffset(Offset, FillExpr);
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002980 return false;
2981}
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002982
Jim Grosbach4b905842013-09-20 23:08:21 +00002983/// parseDirectiveAlign
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002984/// ::= {.align, ...} expression [ , expression [ , expression ]]
Jim Grosbach4b905842013-09-20 23:08:21 +00002985bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002986 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002987 int64_t Alignment;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002988 SMLoc MaxBytesLoc;
2989 bool HasFillExpr = false;
2990 int64_t FillExpr = 0;
2991 int64_t MaxBytesToFill = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002992
2993 auto parseAlign = [&]() -> bool {
2994 if (checkForValidSection() || parseAbsoluteExpression(Alignment))
Nirav Davea645433c2016-07-18 15:24:03 +00002995 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002996 if (parseOptionalToken(AsmToken::Comma)) {
2997 // The fill expression can be omitted while specifying a maximum number of
2998 // alignment bytes, e.g:
2999 // .align 3,,4
3000 if (getTok().isNot(AsmToken::Comma)) {
3001 HasFillExpr = true;
3002 if (parseAbsoluteExpression(FillExpr))
3003 return true;
3004 }
3005 if (parseOptionalToken(AsmToken::Comma))
3006 if (parseTokenLoc(MaxBytesLoc) ||
3007 parseAbsoluteExpression(MaxBytesToFill))
3008 return true;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003009 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003010 return parseToken(AsmToken::EndOfStatement);
3011 };
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003012
Nirav Dave1a9044b2016-10-24 14:35:29 +00003013 if (parseAlign())
3014 return addErrorSuffix(" in directive");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003015
Nirav Dave2364748a2016-09-16 18:30:20 +00003016 // Always emit an alignment here even if we thrown an error.
3017 bool ReturnVal = false;
3018
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003019 // Compute alignment in bytes.
3020 if (IsPow2) {
3021 // FIXME: Diagnose overflow.
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003022 if (Alignment >= 32) {
Nirav Dave2364748a2016-09-16 18:30:20 +00003023 ReturnVal |= Error(AlignmentLoc, "invalid alignment value");
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003024 Alignment = 31;
3025 }
3026
Benjamin Kramer63951ad2009-09-06 09:35:10 +00003027 Alignment = 1ULL << Alignment;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00003028 } else {
Davide Italianocb2da712015-09-08 18:59:47 +00003029 // Reject alignments that aren't either a power of two or zero,
3030 // for gas compatibility. Alignment of zero is silently rounded
3031 // up to one.
3032 if (Alignment == 0)
3033 Alignment = 1;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00003034 if (!isPowerOf2_64(Alignment))
Nirav Dave2364748a2016-09-16 18:30:20 +00003035 ReturnVal |= Error(AlignmentLoc, "alignment must be a power of 2");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003036 }
3037
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003038 // Diagnose non-sensical max bytes to align.
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003039 if (MaxBytesLoc.isValid()) {
3040 if (MaxBytesToFill < 1) {
Nirav Dave2364748a2016-09-16 18:30:20 +00003041 ReturnVal |= Error(MaxBytesLoc,
3042 "alignment directive can never be satisfied in this "
Jim Grosbach4b905842013-09-20 23:08:21 +00003043 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar4abcccb2009-08-21 23:01:53 +00003044 MaxBytesToFill = 0;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003045 }
3046
3047 if (MaxBytesToFill >= Alignment) {
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +00003048 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
Jim Grosbach4b905842013-09-20 23:08:21 +00003049 "has no effect");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003050 MaxBytesToFill = 0;
3051 }
3052 }
3053
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003054 // Check whether we should use optimal code alignment for this .align
3055 // directive.
Eric Christopher445c9522016-10-14 05:47:37 +00003056 const MCSection *Section = getStreamer().getCurrentSectionOnly();
Saleem Abdulrasool7f2f9f42014-03-21 05:13:23 +00003057 assert(Section && "must have section to emit alignment");
3058 bool UseCodeAlign = Section->UseCodeAlign();
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003059 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
3060 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003061 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003062 } else {
Kevin Enderby7f993022010-02-25 18:46:04 +00003063 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnerc2b36752010-07-15 21:19:31 +00003064 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
3065 MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003066 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003067
Nirav Dave2364748a2016-09-16 18:30:20 +00003068 return ReturnVal;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003069}
3070
Jim Grosbach4b905842013-09-20 23:08:21 +00003071/// parseDirectiveFile
Eli Bendersky17233942013-01-15 22:59:42 +00003072/// ::= .file [number] filename
3073/// ::= .file number directory filename
Jim Grosbach4b905842013-09-20 23:08:21 +00003074bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003075 // FIXME: I'm not sure what this is.
3076 int64_t FileNumber = -1;
3077 SMLoc FileNumberLoc = getLexer().getLoc();
3078 if (getLexer().is(AsmToken::Integer)) {
3079 FileNumber = getTok().getIntVal();
3080 Lex();
3081
3082 if (FileNumber < 1)
3083 return TokError("file number less than one");
3084 }
3085
Nirav Davea645433c2016-07-18 15:24:03 +00003086 std::string Path = getTok().getString();
Eli Bendersky17233942013-01-15 22:59:42 +00003087
3088 // Usually the directory and filename together, otherwise just the directory.
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003089 // Allow the strings to have escaped octal character sequence.
Nirav Davea645433c2016-07-18 15:24:03 +00003090 if (check(getTok().isNot(AsmToken::String),
3091 "unexpected token in '.file' directive") ||
3092 parseEscapedString(Path))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003093 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003094
3095 StringRef Directory;
3096 StringRef Filename;
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003097 std::string FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00003098 if (getLexer().is(AsmToken::String)) {
Nirav Davea645433c2016-07-18 15:24:03 +00003099 if (check(FileNumber == -1,
3100 "explicit path specified, but no file number") ||
3101 parseEscapedString(FilenameData))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003102 return true;
3103 Filename = FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00003104 Directory = Path;
Eli Bendersky17233942013-01-15 22:59:42 +00003105 } else {
3106 Filename = Path;
3107 }
3108
Nirav Davea645433c2016-07-18 15:24:03 +00003109 if (parseToken(AsmToken::EndOfStatement,
3110 "unexpected token in '.file' directive"))
3111 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003112
3113 if (FileNumber == -1)
3114 getStreamer().EmitFileDirective(Filename);
3115 else {
David Blaikie22748082016-05-26 00:22:26 +00003116 // If there is -g option as well as debug info from directive file,
3117 // we turn off -g option, directly use the existing debug info instead.
David Blaikiedc3f01e2015-03-09 01:57:13 +00003118 if (getContext().getGenDwarfForAssembly())
David Blaikie22748082016-05-26 00:22:26 +00003119 getContext().setGenDwarfForAssembly(false);
3120 else if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename) ==
David Blaikiec714ef42014-03-17 01:52:11 +00003121 0)
Nirav Dave2364748a2016-09-16 18:30:20 +00003122 return Error(FileNumberLoc, "file number already allocated");
Eli Bendersky17233942013-01-15 22:59:42 +00003123 }
3124
3125 return false;
3126}
3127
Jim Grosbach4b905842013-09-20 23:08:21 +00003128/// parseDirectiveLine
Eli Bendersky17233942013-01-15 22:59:42 +00003129/// ::= .line [number]
Jim Grosbach4b905842013-09-20 23:08:21 +00003130bool AsmParser::parseDirectiveLine() {
Nirav Davea645433c2016-07-18 15:24:03 +00003131 int64_t LineNumber;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003132 if (getLexer().is(AsmToken::Integer)) {
Nirav Davea645433c2016-07-18 15:24:03 +00003133 if (parseIntToken(LineNumber, "unexpected token in '.line' directive"))
3134 return true;
Jim Grosbach4b905842013-09-20 23:08:21 +00003135 (void)LineNumber;
Eli Bendersky17233942013-01-15 22:59:42 +00003136 // FIXME: Do something with the .line.
3137 }
Nirav Davea645433c2016-07-18 15:24:03 +00003138 if (parseToken(AsmToken::EndOfStatement,
3139 "unexpected token in '.line' directive"))
3140 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003141
3142 return false;
3143}
3144
Jim Grosbach4b905842013-09-20 23:08:21 +00003145/// parseDirectiveLoc
Eli Bendersky17233942013-01-15 22:59:42 +00003146/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
3147/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
3148/// The first number is a file number, must have been previously assigned with
3149/// a .file directive, the second number is the line number and optionally the
3150/// third number is a column position (zero if not specified). The remaining
3151/// optional items are .loc sub-directives.
Jim Grosbach4b905842013-09-20 23:08:21 +00003152bool AsmParser::parseDirectiveLoc() {
Nirav Davea645433c2016-07-18 15:24:03 +00003153 int64_t FileNumber = 0, LineNumber = 0;
3154 SMLoc Loc = getTok().getLoc();
3155 if (parseIntToken(FileNumber, "unexpected token in '.loc' directive") ||
3156 check(FileNumber < 1, Loc,
3157 "file number less than one in '.loc' directive") ||
3158 check(!getContext().isValidDwarfFileNumber(FileNumber), Loc,
3159 "unassigned file number in '.loc' directive"))
3160 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003161
Nirav Davea645433c2016-07-18 15:24:03 +00003162 // optional
Eli Bendersky17233942013-01-15 22:59:42 +00003163 if (getLexer().is(AsmToken::Integer)) {
3164 LineNumber = getTok().getIntVal();
Adrian Prantl6ac40032013-09-26 23:37:11 +00003165 if (LineNumber < 0)
3166 return TokError("line number less than zero in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003167 Lex();
3168 }
3169
3170 int64_t ColumnPos = 0;
3171 if (getLexer().is(AsmToken::Integer)) {
3172 ColumnPos = getTok().getIntVal();
3173 if (ColumnPos < 0)
3174 return TokError("column position less than zero in '.loc' directive");
3175 Lex();
3176 }
3177
3178 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
3179 unsigned Isa = 0;
3180 int64_t Discriminator = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003181
Nirav Dave1a9044b2016-10-24 14:35:29 +00003182 auto parseLocOp = [&]() -> bool {
3183 StringRef Name;
3184 SMLoc Loc = getTok().getLoc();
3185 if (parseIdentifier(Name))
3186 return TokError("unexpected token in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003187
Nirav Dave1a9044b2016-10-24 14:35:29 +00003188 if (Name == "basic_block")
3189 Flags |= DWARF2_FLAG_BASIC_BLOCK;
3190 else if (Name == "prologue_end")
3191 Flags |= DWARF2_FLAG_PROLOGUE_END;
3192 else if (Name == "epilogue_begin")
3193 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
3194 else if (Name == "is_stmt") {
3195 Loc = getTok().getLoc();
3196 const MCExpr *Value;
3197 if (parseExpression(Value))
3198 return true;
3199 // The expression must be the constant 0 or 1.
3200 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3201 int Value = MCE->getValue();
3202 if (Value == 0)
3203 Flags &= ~DWARF2_FLAG_IS_STMT;
3204 else if (Value == 1)
3205 Flags |= DWARF2_FLAG_IS_STMT;
3206 else
3207 return Error(Loc, "is_stmt value not 0 or 1");
Craig Topperf15655b2013-04-22 04:22:40 +00003208 } else {
Nirav Dave1a9044b2016-10-24 14:35:29 +00003209 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
Eli Bendersky17233942013-01-15 22:59:42 +00003210 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003211 } else if (Name == "isa") {
3212 Loc = getTok().getLoc();
3213 const MCExpr *Value;
3214 if (parseExpression(Value))
3215 return true;
3216 // The expression must be a constant greater or equal to 0.
3217 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3218 int Value = MCE->getValue();
3219 if (Value < 0)
3220 return Error(Loc, "isa number less than zero");
3221 Isa = Value;
3222 } else {
3223 return Error(Loc, "isa number not a constant value");
3224 }
3225 } else if (Name == "discriminator") {
3226 if (parseAbsoluteExpression(Discriminator))
3227 return true;
3228 } else {
3229 return Error(Loc, "unknown sub-directive in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003230 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003231 return false;
3232 };
3233
Nirav Davee2369aa2016-10-26 17:28:58 +00003234 if (parseMany(parseLocOp, false /*hasComma*/))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003235 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003236
3237 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
3238 Isa, Discriminator, StringRef());
3239
3240 return false;
3241}
3242
Jim Grosbach4b905842013-09-20 23:08:21 +00003243/// parseDirectiveStabs
Eli Bendersky17233942013-01-15 22:59:42 +00003244/// ::= .stabs string, number, number, number
Jim Grosbach4b905842013-09-20 23:08:21 +00003245bool AsmParser::parseDirectiveStabs() {
Eli Bendersky17233942013-01-15 22:59:42 +00003246 return TokError("unsupported directive '.stabs'");
3247}
3248
Reid Kleckner2214ed82016-01-29 00:49:42 +00003249/// parseDirectiveCVFile
3250/// ::= .cv_file number filename
3251bool AsmParser::parseDirectiveCVFile() {
Nirav Davea645433c2016-07-18 15:24:03 +00003252 SMLoc FileNumberLoc = getTok().getLoc();
3253 int64_t FileNumber;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003254 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00003255
3256 if (parseIntToken(FileNumber,
3257 "expected file number in '.cv_file' directive") ||
3258 check(FileNumber < 1, FileNumberLoc, "file number less than one") ||
3259 check(getTok().isNot(AsmToken::String),
3260 "unexpected token in '.cv_file' directive") ||
3261 // Usually directory and filename are together, otherwise just
3262 // directory. Allow the strings to have escaped octal character sequence.
3263 parseEscapedString(Filename) ||
3264 parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00003265 "unexpected token in '.cv_file' directive"))
Reid Klecknera5b1eef2016-08-26 17:58:37 +00003266 return true;
Nirav Dave1ab71992016-07-18 19:35:21 +00003267
Reid Klecknera5b1eef2016-08-26 17:58:37 +00003268 if (!getStreamer().EmitCVFileDirective(FileNumber, Filename))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003269 return Error(FileNumberLoc, "file number already allocated");
Reid Kleckner2214ed82016-01-29 00:49:42 +00003270
3271 return false;
3272}
3273
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003274bool AsmParser::parseCVFunctionId(int64_t &FunctionId,
3275 StringRef DirectiveName) {
3276 SMLoc Loc;
3277 return parseTokenLoc(Loc) ||
3278 parseIntToken(FunctionId, "expected function id in '" + DirectiveName +
3279 "' directive") ||
3280 check(FunctionId < 0 || FunctionId >= UINT_MAX, Loc,
3281 "expected function id within range [0, UINT_MAX)");
3282}
3283
3284bool AsmParser::parseCVFileId(int64_t &FileNumber, StringRef DirectiveName) {
3285 SMLoc Loc;
3286 return parseTokenLoc(Loc) ||
3287 parseIntToken(FileNumber, "expected integer in '" + DirectiveName +
3288 "' directive") ||
3289 check(FileNumber < 1, Loc, "file number less than one in '" +
3290 DirectiveName + "' directive") ||
3291 check(!getCVContext().isValidFileNumber(FileNumber), Loc,
3292 "unassigned file number in '" + DirectiveName + "' directive");
3293}
3294
3295/// parseDirectiveCVFuncId
3296/// ::= .cv_func_id FunctionId
3297///
3298/// Introduces a function ID that can be used with .cv_loc.
3299bool AsmParser::parseDirectiveCVFuncId() {
3300 SMLoc FunctionIdLoc = getTok().getLoc();
3301 int64_t FunctionId;
3302
3303 if (parseCVFunctionId(FunctionId, ".cv_func_id") ||
3304 parseToken(AsmToken::EndOfStatement,
3305 "unexpected token in '.cv_func_id' directive"))
3306 return true;
3307
3308 if (!getStreamer().EmitCVFuncIdDirective(FunctionId))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003309 return Error(FunctionIdLoc, "function id already allocated");
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003310
3311 return false;
3312}
3313
3314/// parseDirectiveCVInlineSiteId
3315/// ::= .cv_inline_site_id FunctionId
3316/// "within" IAFunc
3317/// "inlined_at" IAFile IALine [IACol]
3318///
3319/// Introduces a function ID that can be used with .cv_loc. Includes "inlined
3320/// at" source location information for use in the line table of the caller,
3321/// whether the caller is a real function or another inlined call site.
3322bool AsmParser::parseDirectiveCVInlineSiteId() {
3323 SMLoc FunctionIdLoc = getTok().getLoc();
3324 int64_t FunctionId;
3325 int64_t IAFunc;
3326 int64_t IAFile;
3327 int64_t IALine;
3328 int64_t IACol = 0;
3329
3330 // FunctionId
3331 if (parseCVFunctionId(FunctionId, ".cv_inline_site_id"))
3332 return true;
3333
3334 // "within"
3335 if (check((getLexer().isNot(AsmToken::Identifier) ||
3336 getTok().getIdentifier() != "within"),
3337 "expected 'within' identifier in '.cv_inline_site_id' directive"))
3338 return true;
3339 Lex();
3340
3341 // IAFunc
3342 if (parseCVFunctionId(IAFunc, ".cv_inline_site_id"))
3343 return true;
3344
3345 // "inlined_at"
3346 if (check((getLexer().isNot(AsmToken::Identifier) ||
3347 getTok().getIdentifier() != "inlined_at"),
3348 "expected 'inlined_at' identifier in '.cv_inline_site_id' "
3349 "directive") )
3350 return true;
3351 Lex();
3352
3353 // IAFile IALine
3354 if (parseCVFileId(IAFile, ".cv_inline_site_id") ||
3355 parseIntToken(IALine, "expected line number after 'inlined_at'"))
3356 return true;
3357
3358 // [IACol]
3359 if (getLexer().is(AsmToken::Integer)) {
3360 IACol = getTok().getIntVal();
3361 Lex();
3362 }
3363
3364 if (parseToken(AsmToken::EndOfStatement,
3365 "unexpected token in '.cv_inline_site_id' directive"))
3366 return true;
3367
3368 if (!getStreamer().EmitCVInlineSiteIdDirective(FunctionId, IAFunc, IAFile,
3369 IALine, IACol, FunctionIdLoc))
Nirav Dave2364748a2016-09-16 18:30:20 +00003370 return Error(FunctionIdLoc, "function id already allocated");
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003371
3372 return false;
3373}
3374
Reid Kleckner2214ed82016-01-29 00:49:42 +00003375/// parseDirectiveCVLoc
3376/// ::= .cv_loc FunctionId FileNumber [LineNumber] [ColumnPos] [prologue_end]
3377/// [is_stmt VALUE]
3378/// The first number is a file number, must have been previously assigned with
3379/// a .file directive, the second number is the line number and optionally the
3380/// third number is a column position (zero if not specified). The remaining
3381/// optional items are .loc sub-directives.
3382bool AsmParser::parseDirectiveCVLoc() {
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003383 SMLoc DirectiveLoc = getTok().getLoc();
Nirav Davea645433c2016-07-18 15:24:03 +00003384 SMLoc Loc;
3385 int64_t FunctionId, FileNumber;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003386 if (parseCVFunctionId(FunctionId, ".cv_loc") ||
3387 parseCVFileId(FileNumber, ".cv_loc"))
Nirav Davea645433c2016-07-18 15:24:03 +00003388 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003389
3390 int64_t LineNumber = 0;
3391 if (getLexer().is(AsmToken::Integer)) {
3392 LineNumber = getTok().getIntVal();
3393 if (LineNumber < 0)
3394 return TokError("line number less than zero in '.cv_loc' directive");
3395 Lex();
3396 }
3397
3398 int64_t ColumnPos = 0;
3399 if (getLexer().is(AsmToken::Integer)) {
3400 ColumnPos = getTok().getIntVal();
3401 if (ColumnPos < 0)
3402 return TokError("column position less than zero in '.cv_loc' directive");
3403 Lex();
3404 }
3405
3406 bool PrologueEnd = false;
3407 uint64_t IsStmt = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003408
3409 auto parseOp = [&]() -> bool {
Reid Kleckner2214ed82016-01-29 00:49:42 +00003410 StringRef Name;
3411 SMLoc Loc = getTok().getLoc();
3412 if (parseIdentifier(Name))
3413 return TokError("unexpected token in '.cv_loc' directive");
Reid Kleckner2214ed82016-01-29 00:49:42 +00003414 if (Name == "prologue_end")
3415 PrologueEnd = true;
3416 else if (Name == "is_stmt") {
3417 Loc = getTok().getLoc();
3418 const MCExpr *Value;
3419 if (parseExpression(Value))
3420 return true;
3421 // The expression must be the constant 0 or 1.
3422 IsStmt = ~0ULL;
3423 if (const auto *MCE = dyn_cast<MCConstantExpr>(Value))
3424 IsStmt = MCE->getValue();
3425
3426 if (IsStmt > 1)
3427 return Error(Loc, "is_stmt value not 0 or 1");
3428 } else {
3429 return Error(Loc, "unknown sub-directive in '.cv_loc' directive");
3430 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003431 return false;
3432 };
3433
3434 if (parseMany(parseOp, false /*hasComma*/))
3435 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003436
3437 getStreamer().EmitCVLocDirective(FunctionId, FileNumber, LineNumber,
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003438 ColumnPos, PrologueEnd, IsStmt, StringRef(),
3439 DirectiveLoc);
Reid Kleckner2214ed82016-01-29 00:49:42 +00003440 return false;
3441}
3442
3443/// parseDirectiveCVLinetable
3444/// ::= .cv_linetable FunctionId, FnStart, FnEnd
3445bool AsmParser::parseDirectiveCVLinetable() {
Nirav Davea645433c2016-07-18 15:24:03 +00003446 int64_t FunctionId;
3447 StringRef FnStartName, FnEndName;
3448 SMLoc Loc = getTok().getLoc();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003449 if (parseCVFunctionId(FunctionId, ".cv_linetable") ||
Nirav Davea645433c2016-07-18 15:24:03 +00003450 parseToken(AsmToken::Comma,
3451 "unexpected token in '.cv_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003452 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3453 "expected identifier in directive") ||
Nirav Davea645433c2016-07-18 15:24:03 +00003454 parseToken(AsmToken::Comma,
3455 "unexpected token in '.cv_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003456 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3457 "expected identifier in directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00003458 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003459
3460 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3461 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
3462
3463 getStreamer().EmitCVLinetableDirective(FunctionId, FnStartSym, FnEndSym);
3464 return false;
3465}
3466
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003467/// parseDirectiveCVInlineLinetable
David Majnemerc9911f22016-02-02 19:22:34 +00003468/// ::= .cv_inline_linetable PrimaryFunctionId FileId LineNum FnStart FnEnd
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003469bool AsmParser::parseDirectiveCVInlineLinetable() {
Nirav Davea645433c2016-07-18 15:24:03 +00003470 int64_t PrimaryFunctionId, SourceFileId, SourceLineNum;
3471 StringRef FnStartName, FnEndName;
3472 SMLoc Loc = getTok().getLoc();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003473 if (parseCVFunctionId(PrimaryFunctionId, ".cv_inline_linetable") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003474 parseTokenLoc(Loc) ||
Nirav Davea645433c2016-07-18 15:24:03 +00003475 parseIntToken(
3476 SourceFileId,
3477 "expected SourceField in '.cv_inline_linetable' directive") ||
3478 check(SourceFileId <= 0, Loc,
3479 "File id less than zero in '.cv_inline_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003480 parseTokenLoc(Loc) ||
Nirav Davea645433c2016-07-18 15:24:03 +00003481 parseIntToken(
3482 SourceLineNum,
3483 "expected SourceLineNum in '.cv_inline_linetable' directive") ||
3484 check(SourceLineNum < 0, Loc,
3485 "Line number less than zero in '.cv_inline_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003486 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3487 "expected identifier in directive") ||
3488 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3489 "expected identifier in directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00003490 return true;
David Majnemerc9911f22016-02-02 19:22:34 +00003491
Nirav Davea645433c2016-07-18 15:24:03 +00003492 if (parseToken(AsmToken::EndOfStatement, "Expected End of Statement"))
3493 return true;
3494
3495 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3496 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
Reid Kleckner1fcd6102016-02-02 17:41:18 +00003497 getStreamer().EmitCVInlineLinetableDirective(PrimaryFunctionId, SourceFileId,
3498 SourceLineNum, FnStartSym,
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003499 FnEndSym);
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003500 return false;
3501}
3502
David Majnemer408b5e62016-02-05 01:55:49 +00003503/// parseDirectiveCVDefRange
3504/// ::= .cv_def_range RangeStart RangeEnd (GapStart GapEnd)*, bytes*
3505bool AsmParser::parseDirectiveCVDefRange() {
3506 SMLoc Loc;
3507 std::vector<std::pair<const MCSymbol *, const MCSymbol *>> Ranges;
3508 while (getLexer().is(AsmToken::Identifier)) {
3509 Loc = getLexer().getLoc();
3510 StringRef GapStartName;
3511 if (parseIdentifier(GapStartName))
3512 return Error(Loc, "expected identifier in directive");
3513 MCSymbol *GapStartSym = getContext().getOrCreateSymbol(GapStartName);
3514
3515 Loc = getLexer().getLoc();
3516 StringRef GapEndName;
3517 if (parseIdentifier(GapEndName))
3518 return Error(Loc, "expected identifier in directive");
3519 MCSymbol *GapEndSym = getContext().getOrCreateSymbol(GapEndName);
3520
3521 Ranges.push_back({GapStartSym, GapEndSym});
3522 }
3523
David Majnemer408b5e62016-02-05 01:55:49 +00003524 std::string FixedSizePortion;
Nirav Davea645433c2016-07-18 15:24:03 +00003525 if (parseToken(AsmToken::Comma, "unexpected token in directive") ||
3526 parseEscapedString(FixedSizePortion))
David Majnemer408b5e62016-02-05 01:55:49 +00003527 return true;
David Majnemer408b5e62016-02-05 01:55:49 +00003528
3529 getStreamer().EmitCVDefRangeDirective(Ranges, FixedSizePortion);
3530 return false;
3531}
3532
Reid Kleckner2214ed82016-01-29 00:49:42 +00003533/// parseDirectiveCVStringTable
3534/// ::= .cv_stringtable
3535bool AsmParser::parseDirectiveCVStringTable() {
3536 getStreamer().EmitCVStringTableDirective();
3537 return false;
3538}
3539
3540/// parseDirectiveCVFileChecksums
3541/// ::= .cv_filechecksums
3542bool AsmParser::parseDirectiveCVFileChecksums() {
3543 getStreamer().EmitCVFileChecksumsDirective();
3544 return false;
3545}
3546
Jim Grosbach4b905842013-09-20 23:08:21 +00003547/// parseDirectiveCFISections
Eli Bendersky17233942013-01-15 22:59:42 +00003548/// ::= .cfi_sections section [, section]
Jim Grosbach4b905842013-09-20 23:08:21 +00003549bool AsmParser::parseDirectiveCFISections() {
Eli Bendersky17233942013-01-15 22:59:42 +00003550 StringRef Name;
3551 bool EH = false;
3552 bool Debug = false;
3553
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003554 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003555 return TokError("Expected an identifier");
3556
3557 if (Name == ".eh_frame")
3558 EH = true;
3559 else if (Name == ".debug_frame")
3560 Debug = true;
3561
3562 if (getLexer().is(AsmToken::Comma)) {
3563 Lex();
3564
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003565 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003566 return TokError("Expected an identifier");
3567
3568 if (Name == ".eh_frame")
3569 EH = true;
3570 else if (Name == ".debug_frame")
3571 Debug = true;
3572 }
3573
3574 getStreamer().EmitCFISections(EH, Debug);
3575 return false;
3576}
3577
Jim Grosbach4b905842013-09-20 23:08:21 +00003578/// parseDirectiveCFIStartProc
David Majnemere035cf92014-01-27 17:20:25 +00003579/// ::= .cfi_startproc [simple]
Jim Grosbach4b905842013-09-20 23:08:21 +00003580bool AsmParser::parseDirectiveCFIStartProc() {
David Majnemere035cf92014-01-27 17:20:25 +00003581 StringRef Simple;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003582 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
3583 if (check(parseIdentifier(Simple) || Simple != "simple",
3584 "unexpected token") ||
3585 parseToken(AsmToken::EndOfStatement))
3586 return addErrorSuffix(" in '.cfi_startproc' directive");
3587 }
Nirav Davea645433c2016-07-18 15:24:03 +00003588
Oliver Stannardcf6bfb12014-11-03 12:19:03 +00003589 getStreamer().EmitCFIStartProc(!Simple.empty());
Eli Bendersky17233942013-01-15 22:59:42 +00003590 return false;
3591}
3592
Jim Grosbach4b905842013-09-20 23:08:21 +00003593/// parseDirectiveCFIEndProc
Eli Bendersky17233942013-01-15 22:59:42 +00003594/// ::= .cfi_endproc
Jim Grosbach4b905842013-09-20 23:08:21 +00003595bool AsmParser::parseDirectiveCFIEndProc() {
Eli Bendersky17233942013-01-15 22:59:42 +00003596 getStreamer().EmitCFIEndProc();
3597 return false;
3598}
3599
Jim Grosbach4b905842013-09-20 23:08:21 +00003600/// \brief parse register name or number.
3601bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
Eli Bendersky17233942013-01-15 22:59:42 +00003602 SMLoc DirectiveLoc) {
3603 unsigned RegNo;
3604
3605 if (getLexer().isNot(AsmToken::Integer)) {
3606 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
3607 return true;
Bill Wendlingbc07a892013-06-18 07:20:20 +00003608 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
Eli Bendersky17233942013-01-15 22:59:42 +00003609 } else
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003610 return parseAbsoluteExpression(Register);
Eli Bendersky17233942013-01-15 22:59:42 +00003611
3612 return false;
3613}
3614
Jim Grosbach4b905842013-09-20 23:08:21 +00003615/// parseDirectiveCFIDefCfa
Eli Bendersky17233942013-01-15 22:59:42 +00003616/// ::= .cfi_def_cfa register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003617bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003618 int64_t Register = 0, Offset = 0;
3619 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3620 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3621 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003622 return true;
3623
3624 getStreamer().EmitCFIDefCfa(Register, Offset);
3625 return false;
3626}
3627
Jim Grosbach4b905842013-09-20 23:08:21 +00003628/// parseDirectiveCFIDefCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003629/// ::= .cfi_def_cfa_offset offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003630bool AsmParser::parseDirectiveCFIDefCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00003631 int64_t Offset = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003632 if (parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003633 return true;
3634
3635 getStreamer().EmitCFIDefCfaOffset(Offset);
3636 return false;
3637}
3638
Jim Grosbach4b905842013-09-20 23:08:21 +00003639/// parseDirectiveCFIRegister
Eli Bendersky17233942013-01-15 22:59:42 +00003640/// ::= .cfi_register register, register
Jim Grosbach4b905842013-09-20 23:08:21 +00003641bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003642 int64_t Register1 = 0, Register2 = 0;
3643 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc) ||
3644 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3645 parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003646 return true;
3647
3648 getStreamer().EmitCFIRegister(Register1, Register2);
3649 return false;
3650}
3651
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00003652/// parseDirectiveCFIWindowSave
3653/// ::= .cfi_window_save
3654bool AsmParser::parseDirectiveCFIWindowSave() {
3655 getStreamer().EmitCFIWindowSave();
3656 return false;
3657}
3658
Jim Grosbach4b905842013-09-20 23:08:21 +00003659/// parseDirectiveCFIAdjustCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003660/// ::= .cfi_adjust_cfa_offset adjustment
Jim Grosbach4b905842013-09-20 23:08:21 +00003661bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00003662 int64_t Adjustment = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003663 if (parseAbsoluteExpression(Adjustment))
Eli Bendersky17233942013-01-15 22:59:42 +00003664 return true;
3665
3666 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3667 return false;
3668}
3669
Jim Grosbach4b905842013-09-20 23:08:21 +00003670/// parseDirectiveCFIDefCfaRegister
Eli Bendersky17233942013-01-15 22:59:42 +00003671/// ::= .cfi_def_cfa_register register
Jim Grosbach4b905842013-09-20 23:08:21 +00003672bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003673 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003674 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003675 return true;
3676
3677 getStreamer().EmitCFIDefCfaRegister(Register);
3678 return false;
3679}
3680
Jim Grosbach4b905842013-09-20 23:08:21 +00003681/// parseDirectiveCFIOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003682/// ::= .cfi_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003683bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003684 int64_t Register = 0;
3685 int64_t Offset = 0;
3686
Nirav Davea645433c2016-07-18 15:24:03 +00003687 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3688 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3689 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003690 return true;
3691
3692 getStreamer().EmitCFIOffset(Register, Offset);
3693 return false;
3694}
3695
Jim Grosbach4b905842013-09-20 23:08:21 +00003696/// parseDirectiveCFIRelOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003697/// ::= .cfi_rel_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003698bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003699 int64_t Register = 0, Offset = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003700
Nirav Davea645433c2016-07-18 15:24:03 +00003701 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3702 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3703 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003704 return true;
3705
3706 getStreamer().EmitCFIRelOffset(Register, Offset);
3707 return false;
3708}
3709
3710static bool isValidEncoding(int64_t Encoding) {
3711 if (Encoding & ~0xff)
3712 return false;
3713
3714 if (Encoding == dwarf::DW_EH_PE_omit)
3715 return true;
3716
3717 const unsigned Format = Encoding & 0xf;
3718 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3719 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3720 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3721 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3722 return false;
3723
3724 const unsigned Application = Encoding & 0x70;
3725 if (Application != dwarf::DW_EH_PE_absptr &&
3726 Application != dwarf::DW_EH_PE_pcrel)
3727 return false;
3728
3729 return true;
3730}
3731
Jim Grosbach4b905842013-09-20 23:08:21 +00003732/// parseDirectiveCFIPersonalityOrLsda
Eli Bendersky17233942013-01-15 22:59:42 +00003733/// IsPersonality true for cfi_personality, false for cfi_lsda
3734/// ::= .cfi_personality encoding, [symbol_name]
3735/// ::= .cfi_lsda encoding, [symbol_name]
Jim Grosbach4b905842013-09-20 23:08:21 +00003736bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
Eli Bendersky17233942013-01-15 22:59:42 +00003737 int64_t Encoding = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003738 if (parseAbsoluteExpression(Encoding))
Eli Bendersky17233942013-01-15 22:59:42 +00003739 return true;
3740 if (Encoding == dwarf::DW_EH_PE_omit)
3741 return false;
3742
Eli Bendersky17233942013-01-15 22:59:42 +00003743 StringRef Name;
Nirav Davea645433c2016-07-18 15:24:03 +00003744 if (check(!isValidEncoding(Encoding), "unsupported encoding.") ||
3745 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3746 check(parseIdentifier(Name), "expected identifier in directive"))
3747 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003748
Jim Grosbach6f482002015-05-18 18:43:14 +00003749 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Eli Bendersky17233942013-01-15 22:59:42 +00003750
3751 if (IsPersonality)
3752 getStreamer().EmitCFIPersonality(Sym, Encoding);
3753 else
3754 getStreamer().EmitCFILsda(Sym, Encoding);
3755 return false;
3756}
3757
Jim Grosbach4b905842013-09-20 23:08:21 +00003758/// parseDirectiveCFIRememberState
Eli Bendersky17233942013-01-15 22:59:42 +00003759/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00003760bool AsmParser::parseDirectiveCFIRememberState() {
Eli Bendersky17233942013-01-15 22:59:42 +00003761 getStreamer().EmitCFIRememberState();
3762 return false;
3763}
3764
Jim Grosbach4b905842013-09-20 23:08:21 +00003765/// parseDirectiveCFIRestoreState
Eli Bendersky17233942013-01-15 22:59:42 +00003766/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00003767bool AsmParser::parseDirectiveCFIRestoreState() {
Eli Bendersky17233942013-01-15 22:59:42 +00003768 getStreamer().EmitCFIRestoreState();
3769 return false;
3770}
3771
Jim Grosbach4b905842013-09-20 23:08:21 +00003772/// parseDirectiveCFISameValue
Eli Bendersky17233942013-01-15 22:59:42 +00003773/// ::= .cfi_same_value register
Jim Grosbach4b905842013-09-20 23:08:21 +00003774bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003775 int64_t Register = 0;
3776
Jim Grosbach4b905842013-09-20 23:08:21 +00003777 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003778 return true;
3779
3780 getStreamer().EmitCFISameValue(Register);
3781 return false;
3782}
3783
Jim Grosbach4b905842013-09-20 23:08:21 +00003784/// parseDirectiveCFIRestore
Eli Bendersky17233942013-01-15 22:59:42 +00003785/// ::= .cfi_restore register
Jim Grosbach4b905842013-09-20 23:08:21 +00003786bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003787 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003788 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003789 return true;
3790
3791 getStreamer().EmitCFIRestore(Register);
3792 return false;
3793}
3794
Jim Grosbach4b905842013-09-20 23:08:21 +00003795/// parseDirectiveCFIEscape
Eli Bendersky17233942013-01-15 22:59:42 +00003796/// ::= .cfi_escape expression[,...]
Jim Grosbach4b905842013-09-20 23:08:21 +00003797bool AsmParser::parseDirectiveCFIEscape() {
Eli Bendersky17233942013-01-15 22:59:42 +00003798 std::string Values;
3799 int64_t CurrValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003800 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00003801 return true;
3802
3803 Values.push_back((uint8_t)CurrValue);
3804
3805 while (getLexer().is(AsmToken::Comma)) {
3806 Lex();
3807
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003808 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00003809 return true;
3810
3811 Values.push_back((uint8_t)CurrValue);
3812 }
3813
3814 getStreamer().EmitCFIEscape(Values);
3815 return false;
3816}
3817
Jim Grosbach4b905842013-09-20 23:08:21 +00003818/// parseDirectiveCFISignalFrame
Eli Bendersky17233942013-01-15 22:59:42 +00003819/// ::= .cfi_signal_frame
Jim Grosbach4b905842013-09-20 23:08:21 +00003820bool AsmParser::parseDirectiveCFISignalFrame() {
Nirav Davea645433c2016-07-18 15:24:03 +00003821 if (parseToken(AsmToken::EndOfStatement,
3822 "unexpected token in '.cfi_signal_frame'"))
3823 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003824
3825 getStreamer().EmitCFISignalFrame();
3826 return false;
3827}
3828
Jim Grosbach4b905842013-09-20 23:08:21 +00003829/// parseDirectiveCFIUndefined
Eli Bendersky17233942013-01-15 22:59:42 +00003830/// ::= .cfi_undefined register
Jim Grosbach4b905842013-09-20 23:08:21 +00003831bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003832 int64_t Register = 0;
3833
Jim Grosbach4b905842013-09-20 23:08:21 +00003834 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003835 return true;
3836
3837 getStreamer().EmitCFIUndefined(Register);
3838 return false;
3839}
3840
Jim Grosbach4b905842013-09-20 23:08:21 +00003841/// parseDirectiveMacrosOnOff
Eli Bendersky17233942013-01-15 22:59:42 +00003842/// ::= .macros_on
3843/// ::= .macros_off
Jim Grosbach4b905842013-09-20 23:08:21 +00003844bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
Nirav Davea645433c2016-07-18 15:24:03 +00003845 if (parseToken(AsmToken::EndOfStatement,
3846 "unexpected token in '" + Directive + "' directive"))
3847 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003848
Jim Grosbach4b905842013-09-20 23:08:21 +00003849 setMacrosEnabled(Directive == ".macros_on");
Eli Bendersky17233942013-01-15 22:59:42 +00003850 return false;
3851}
3852
Jim Grosbach4b905842013-09-20 23:08:21 +00003853/// parseDirectiveMacro
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00003854/// ::= .macro name[,] [parameters]
Jim Grosbach4b905842013-09-20 23:08:21 +00003855bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003856 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003857 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003858 return TokError("expected identifier in '.macro' directive");
3859
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00003860 if (getLexer().is(AsmToken::Comma))
3861 Lex();
3862
Eli Bendersky17233942013-01-15 22:59:42 +00003863 MCAsmMacroParameters Parameters;
David Majnemer91fc4c22014-01-29 18:57:46 +00003864 while (getLexer().isNot(AsmToken::EndOfStatement)) {
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003865
Alexander Kornienko8c0809c2015-01-15 11:41:30 +00003866 if (!Parameters.empty() && Parameters.back().Vararg)
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003867 return Error(Lexer.getLoc(),
3868 "Vararg parameter '" + Parameters.back().Name +
3869 "' should be last one in the list of parameters.");
3870
David Majnemer91fc4c22014-01-29 18:57:46 +00003871 MCAsmMacroParameter Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00003872 if (parseIdentifier(Parameter.Name))
David Majnemer91fc4c22014-01-29 18:57:46 +00003873 return TokError("expected identifier in '.macro' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003874
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003875 if (Lexer.is(AsmToken::Colon)) {
3876 Lex(); // consume ':'
3877
3878 SMLoc QualLoc;
3879 StringRef Qualifier;
3880
3881 QualLoc = Lexer.getLoc();
3882 if (parseIdentifier(Qualifier))
3883 return Error(QualLoc, "missing parameter qualifier for "
3884 "'" + Parameter.Name + "' in macro '" + Name + "'");
3885
3886 if (Qualifier == "req")
3887 Parameter.Required = true;
Kevin Enderbye3c13462014-08-04 23:14:37 +00003888 else if (Qualifier == "vararg")
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003889 Parameter.Vararg = true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003890 else
3891 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
3892 "for '" + Parameter.Name + "' in macro '" + Name + "'");
3893 }
3894
David Majnemer91fc4c22014-01-29 18:57:46 +00003895 if (getLexer().is(AsmToken::Equal)) {
3896 Lex();
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003897
3898 SMLoc ParamLoc;
3899
3900 ParamLoc = Lexer.getLoc();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003901 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
David Majnemer91fc4c22014-01-29 18:57:46 +00003902 return true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003903
3904 if (Parameter.Required)
3905 Warning(ParamLoc, "pointless default value for required parameter "
3906 "'" + Parameter.Name + "' in macro '" + Name + "'");
Eli Bendersky17233942013-01-15 22:59:42 +00003907 }
David Majnemer91fc4c22014-01-29 18:57:46 +00003908
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00003909 Parameters.push_back(std::move(Parameter));
David Majnemer91fc4c22014-01-29 18:57:46 +00003910
3911 if (getLexer().is(AsmToken::Comma))
3912 Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00003913 }
3914
Nirav Dave1180e6892016-06-02 17:15:05 +00003915 // Eat just the end of statement.
3916 Lexer.Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00003917
Nirav Dave1180e6892016-06-02 17:15:05 +00003918 // Consuming deferred text, so use Lexer.Lex to ignore Lexing Errors
Eli Bendersky17233942013-01-15 22:59:42 +00003919 AsmToken EndToken, StartToken = getTok();
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00003920 unsigned MacroDepth = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003921 // Lex the macro definition.
Eugene Zelenko33d7b762016-08-23 17:14:32 +00003922 while (true) {
Nirav Dave1180e6892016-06-02 17:15:05 +00003923 // Ignore Lexing errors in macros.
3924 while (Lexer.is(AsmToken::Error)) {
3925 Lexer.Lex();
3926 }
3927
Eli Bendersky17233942013-01-15 22:59:42 +00003928 // Check whether we have reached the end of the file.
3929 if (getLexer().is(AsmToken::Eof))
3930 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3931
3932 // Otherwise, check whether we have reach the .endmacro.
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00003933 if (getLexer().is(AsmToken::Identifier)) {
3934 if (getTok().getIdentifier() == ".endm" ||
3935 getTok().getIdentifier() == ".endmacro") {
3936 if (MacroDepth == 0) { // Outermost macro.
3937 EndToken = getTok();
Nirav Dave1180e6892016-06-02 17:15:05 +00003938 Lexer.Lex();
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00003939 if (getLexer().isNot(AsmToken::EndOfStatement))
3940 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3941 "' directive");
3942 break;
3943 } else {
3944 // Otherwise we just found the end of an inner macro.
3945 --MacroDepth;
3946 }
3947 } else if (getTok().getIdentifier() == ".macro") {
3948 // We allow nested macros. Those aren't instantiated until the outermost
3949 // macro is expanded so just ignore them for now.
3950 ++MacroDepth;
3951 }
Eli Bendersky17233942013-01-15 22:59:42 +00003952 }
3953
3954 // Otherwise, scan til the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003955 eatToEndOfStatement();
Eli Bendersky17233942013-01-15 22:59:42 +00003956 }
3957
Jim Grosbach4b905842013-09-20 23:08:21 +00003958 if (lookupMacro(Name)) {
Eli Bendersky17233942013-01-15 22:59:42 +00003959 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3960 }
3961
3962 const char *BodyStart = StartToken.getLoc().getPointer();
3963 const char *BodyEnd = EndToken.getLoc().getPointer();
3964 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Jim Grosbach4b905842013-09-20 23:08:21 +00003965 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00003966 defineMacro(Name, MCAsmMacro(Name, Body, std::move(Parameters)));
Eli Bendersky17233942013-01-15 22:59:42 +00003967 return false;
3968}
3969
Jim Grosbach4b905842013-09-20 23:08:21 +00003970/// checkForBadMacro
Kevin Enderby81c944c2013-01-22 21:44:53 +00003971///
3972/// With the support added for named parameters there may be code out there that
3973/// is transitioning from positional parameters. In versions of gas that did
Alp Tokercb402912014-01-24 17:20:08 +00003974/// not support named parameters they would be ignored on the macro definition.
Kevin Enderby81c944c2013-01-22 21:44:53 +00003975/// But to support both styles of parameters this is not possible so if a macro
Alp Tokercb402912014-01-24 17:20:08 +00003976/// definition has named parameters but does not use them and has what appears
Kevin Enderby81c944c2013-01-22 21:44:53 +00003977/// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3978/// warning that the positional parameter found in body which have no effect.
3979/// Hoping the developer will either remove the named parameters from the macro
Alp Tokercb402912014-01-24 17:20:08 +00003980/// definition so the positional parameters get used if that was what was
Kevin Enderby81c944c2013-01-22 21:44:53 +00003981/// intended or change the macro to use the named parameters. It is possible
3982/// this warning will trigger when the none of the named parameters are used
3983/// and the strings like $1 are infact to simply to be passed trough unchanged.
Jim Grosbach4b905842013-09-20 23:08:21 +00003984void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
Kevin Enderby81c944c2013-01-22 21:44:53 +00003985 StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00003986 ArrayRef<MCAsmMacroParameter> Parameters) {
Kevin Enderby81c944c2013-01-22 21:44:53 +00003987 // If this macro is not defined with named parameters the warning we are
3988 // checking for here doesn't apply.
3989 unsigned NParameters = Parameters.size();
3990 if (NParameters == 0)
3991 return;
3992
3993 bool NamedParametersFound = false;
3994 bool PositionalParametersFound = false;
3995
3996 // Look at the body of the macro for use of both the named parameters and what
3997 // are likely to be positional parameters. This is what expandMacro() is
3998 // doing when it finds the parameters in the body.
3999 while (!Body.empty()) {
4000 // Scan for the next possible parameter.
4001 std::size_t End = Body.size(), Pos = 0;
4002 for (; Pos != End; ++Pos) {
4003 // Check for a substitution or escape.
4004 // This macro is defined with parameters, look for \foo, \bar, etc.
4005 if (Body[Pos] == '\\' && Pos + 1 != End)
4006 break;
4007
4008 // This macro should have parameters, but look for $0, $1, ..., $n too.
4009 if (Body[Pos] != '$' || Pos + 1 == End)
4010 continue;
4011 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00004012 if (Next == '$' || Next == 'n' ||
4013 isdigit(static_cast<unsigned char>(Next)))
Kevin Enderby81c944c2013-01-22 21:44:53 +00004014 break;
4015 }
4016
4017 // Check if we reached the end.
4018 if (Pos == End)
4019 break;
4020
4021 if (Body[Pos] == '$') {
Jim Grosbach4b905842013-09-20 23:08:21 +00004022 switch (Body[Pos + 1]) {
4023 // $$ => $
Kevin Enderby81c944c2013-01-22 21:44:53 +00004024 case '$':
4025 break;
4026
Jim Grosbach4b905842013-09-20 23:08:21 +00004027 // $n => number of arguments
Kevin Enderby81c944c2013-01-22 21:44:53 +00004028 case 'n':
4029 PositionalParametersFound = true;
4030 break;
4031
Jim Grosbach4b905842013-09-20 23:08:21 +00004032 // $[0-9] => argument
Kevin Enderby81c944c2013-01-22 21:44:53 +00004033 default: {
4034 PositionalParametersFound = true;
4035 break;
Jim Grosbach4b905842013-09-20 23:08:21 +00004036 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00004037 }
4038 Pos += 2;
4039 } else {
4040 unsigned I = Pos + 1;
4041 while (isIdentifierChar(Body[I]) && I + 1 != End)
4042 ++I;
4043
Jim Grosbach4b905842013-09-20 23:08:21 +00004044 const char *Begin = Body.data() + Pos + 1;
4045 StringRef Argument(Begin, I - (Pos + 1));
Kevin Enderby81c944c2013-01-22 21:44:53 +00004046 unsigned Index = 0;
4047 for (; Index < NParameters; ++Index)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00004048 if (Parameters[Index].Name == Argument)
Kevin Enderby81c944c2013-01-22 21:44:53 +00004049 break;
4050
4051 if (Index == NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00004052 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
4053 Pos += 3;
4054 else {
4055 Pos = I;
4056 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00004057 } else {
4058 NamedParametersFound = true;
4059 Pos += 1 + Argument.size();
4060 }
4061 }
4062 // Update the scan point.
4063 Body = Body.substr(Pos);
4064 }
4065
4066 if (!NamedParametersFound && PositionalParametersFound)
4067 Warning(DirectiveLoc, "macro defined with named parameters which are not "
4068 "used in macro body, possible positional parameter "
4069 "found in body which will have no effect");
4070}
4071
Nico Weber155dccd12014-07-24 17:08:39 +00004072/// parseDirectiveExitMacro
4073/// ::= .exitm
4074bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
Nirav Davea645433c2016-07-18 15:24:03 +00004075 if (parseToken(AsmToken::EndOfStatement,
4076 "unexpected token in '" + Directive + "' directive"))
4077 return true;
Nico Weber155dccd12014-07-24 17:08:39 +00004078
4079 if (!isInsideMacroInstantiation())
4080 return TokError("unexpected '" + Directive + "' in file, "
4081 "no current macro definition");
4082
4083 // Exit all conditionals that are active in the current macro.
4084 while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
4085 TheCondState = TheCondStack.back();
4086 TheCondStack.pop_back();
4087 }
4088
4089 handleMacroExit();
4090 return false;
4091}
4092
Jim Grosbach4b905842013-09-20 23:08:21 +00004093/// parseDirectiveEndMacro
Eli Bendersky17233942013-01-15 22:59:42 +00004094/// ::= .endm
4095/// ::= .endmacro
Jim Grosbach4b905842013-09-20 23:08:21 +00004096bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
Eli Bendersky17233942013-01-15 22:59:42 +00004097 if (getLexer().isNot(AsmToken::EndOfStatement))
4098 return TokError("unexpected token in '" + Directive + "' directive");
4099
4100 // If we are inside a macro instantiation, terminate the current
4101 // instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00004102 if (isInsideMacroInstantiation()) {
4103 handleMacroExit();
Eli Bendersky17233942013-01-15 22:59:42 +00004104 return false;
4105 }
4106
4107 // Otherwise, this .endmacro is a stray entry in the file; well formed
4108 // .endmacro directives are handled during the macro definition parsing.
4109 return TokError("unexpected '" + Directive + "' in file, "
Jim Grosbach4b905842013-09-20 23:08:21 +00004110 "no current macro definition");
Eli Bendersky17233942013-01-15 22:59:42 +00004111}
4112
Jim Grosbach4b905842013-09-20 23:08:21 +00004113/// parseDirectivePurgeMacro
Eli Bendersky17233942013-01-15 22:59:42 +00004114/// ::= .purgem
Jim Grosbach4b905842013-09-20 23:08:21 +00004115bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004116 StringRef Name;
Nirav Davea645433c2016-07-18 15:24:03 +00004117 SMLoc Loc;
Nirav Daved8858ca2016-08-30 14:15:43 +00004118 if (parseTokenLoc(Loc) ||
4119 check(parseIdentifier(Name), Loc,
4120 "expected identifier in '.purgem' directive") ||
Nirav Davea645433c2016-07-18 15:24:03 +00004121 parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00004122 "unexpected token in '.purgem' directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00004123 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004124
Nirav Dave1ab71992016-07-18 19:35:21 +00004125 if (!lookupMacro(Name))
4126 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
4127
Jim Grosbach4b905842013-09-20 23:08:21 +00004128 undefineMacro(Name);
Eli Bendersky17233942013-01-15 22:59:42 +00004129 return false;
4130}
Eli Benderskyf483ff92012-12-20 19:05:53 +00004131
Jim Grosbach4b905842013-09-20 23:08:21 +00004132/// parseDirectiveBundleAlignMode
Eli Benderskyf483ff92012-12-20 19:05:53 +00004133/// ::= {.bundle_align_mode} expression
Jim Grosbach4b905842013-09-20 23:08:21 +00004134bool AsmParser::parseDirectiveBundleAlignMode() {
Eli Benderskyf483ff92012-12-20 19:05:53 +00004135 // Expect a single argument: an expression that evaluates to a constant
4136 // in the inclusive range 0-30.
4137 SMLoc ExprLoc = getLexer().getLoc();
4138 int64_t AlignSizePow2;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004139 if (checkForValidSection() || parseAbsoluteExpression(AlignSizePow2) ||
Nirav Davea645433c2016-07-18 15:24:03 +00004140 parseToken(AsmToken::EndOfStatement, "unexpected token after expression "
4141 "in '.bundle_align_mode' "
4142 "directive") ||
4143 check(AlignSizePow2 < 0 || AlignSizePow2 > 30, ExprLoc,
4144 "invalid bundle alignment size (expected between 0 and 30)"))
Eli Benderskyf483ff92012-12-20 19:05:53 +00004145 return true;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004146
4147 // Because of AlignSizePow2's verified range we can safely truncate it to
4148 // unsigned.
4149 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
4150 return false;
4151}
4152
Jim Grosbach4b905842013-09-20 23:08:21 +00004153/// parseDirectiveBundleLock
Eli Bendersky802b6282013-01-07 21:51:08 +00004154/// ::= {.bundle_lock} [align_to_end]
Jim Grosbach4b905842013-09-20 23:08:21 +00004155bool AsmParser::parseDirectiveBundleLock() {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004156 if (checkForValidSection())
4157 return true;
Eli Bendersky802b6282013-01-07 21:51:08 +00004158 bool AlignToEnd = false;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004159
Nirav Dave1a9044b2016-10-24 14:35:29 +00004160 StringRef Option;
4161 SMLoc Loc = getTok().getLoc();
4162 const char *kInvalidOptionError =
4163 "invalid option for '.bundle_lock' directive";
Eli Bendersky802b6282013-01-07 21:51:08 +00004164
Nirav Dave1a9044b2016-10-24 14:35:29 +00004165 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
Nirav Davea645433c2016-07-18 15:24:03 +00004166 if (check(parseIdentifier(Option), Loc, kInvalidOptionError) ||
4167 check(Option != "align_to_end", Loc, kInvalidOptionError) ||
Nirav Dave1a9044b2016-10-24 14:35:29 +00004168 parseToken(AsmToken::EndOfStatement,
4169 "unexpected token after '.bundle_lock' directive option"))
Nirav Davea645433c2016-07-18 15:24:03 +00004170 return true;
Eli Bendersky802b6282013-01-07 21:51:08 +00004171 AlignToEnd = true;
4172 }
4173
Eli Bendersky802b6282013-01-07 21:51:08 +00004174 getStreamer().EmitBundleLock(AlignToEnd);
Eli Benderskyf483ff92012-12-20 19:05:53 +00004175 return false;
4176}
4177
Jim Grosbach4b905842013-09-20 23:08:21 +00004178/// parseDirectiveBundleLock
Eli Benderskyf483ff92012-12-20 19:05:53 +00004179/// ::= {.bundle_lock}
Jim Grosbach4b905842013-09-20 23:08:21 +00004180bool AsmParser::parseDirectiveBundleUnlock() {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004181 if (checkForValidSection() ||
4182 parseToken(AsmToken::EndOfStatement,
Nirav Davea645433c2016-07-18 15:24:03 +00004183 "unexpected token in '.bundle_unlock' directive"))
4184 return true;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004185
4186 getStreamer().EmitBundleUnlock();
4187 return false;
4188}
4189
Jim Grosbach4b905842013-09-20 23:08:21 +00004190/// parseDirectiveSpace
Eli Bendersky17233942013-01-15 22:59:42 +00004191/// ::= (.skip | .space) expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004192bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
Eli Bendersky17233942013-01-15 22:59:42 +00004193
Petr Hosek67a94a72016-05-28 05:57:48 +00004194 SMLoc NumBytesLoc = Lexer.getLoc();
4195 const MCExpr *NumBytes;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004196 if (checkForValidSection() || parseExpression(NumBytes))
Eli Bendersky17233942013-01-15 22:59:42 +00004197 return true;
4198
4199 int64_t FillExpr = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00004200 if (parseOptionalToken(AsmToken::Comma))
4201 if (parseAbsoluteExpression(FillExpr))
4202 return addErrorSuffix("in '" + Twine(IDVal) + "' directive");
4203 if (parseToken(AsmToken::EndOfStatement))
4204 return addErrorSuffix("in '" + Twine(IDVal) + "' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00004205
Eli Bendersky17233942013-01-15 22:59:42 +00004206 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
Petr Hosek67a94a72016-05-28 05:57:48 +00004207 getStreamer().emitFill(*NumBytes, FillExpr, NumBytesLoc);
Eli Bendersky17233942013-01-15 22:59:42 +00004208
4209 return false;
4210}
4211
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004212/// parseDirectiveDCB
4213/// ::= .dcb.{b, l, w} expression, expression
4214bool AsmParser::parseDirectiveDCB(StringRef IDVal, unsigned Size) {
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004215 SMLoc NumValuesLoc = Lexer.getLoc();
4216 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004217 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004218 return true;
4219
4220 if (NumValues < 0) {
4221 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4222 return false;
4223 }
4224
4225 if (parseToken(AsmToken::Comma,
4226 "unexpected token in '" + Twine(IDVal) + "' directive"))
4227 return true;
4228
4229 const MCExpr *Value;
4230 SMLoc ExprLoc = getLexer().getLoc();
4231 if (parseExpression(Value))
4232 return true;
4233
4234 // Special case constant expressions to match code generator.
4235 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
4236 assert(Size <= 8 && "Invalid size");
4237 uint64_t IntValue = MCE->getValue();
4238 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
4239 return Error(ExprLoc, "literal value out of range for directive");
4240 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4241 getStreamer().EmitIntValue(IntValue, Size);
4242 } else {
4243 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4244 getStreamer().EmitValue(Value, Size, ExprLoc);
4245 }
4246
4247 if (parseToken(AsmToken::EndOfStatement,
4248 "unexpected token in '" + Twine(IDVal) + "' directive"))
4249 return true;
4250
4251 return false;
4252}
4253
4254/// parseDirectiveRealDCB
4255/// ::= .dcb.{d, s} expression, expression
4256bool AsmParser::parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &Semantics) {
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004257 SMLoc NumValuesLoc = Lexer.getLoc();
4258 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004259 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004260 return true;
4261
4262 if (NumValues < 0) {
4263 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4264 return false;
4265 }
4266
4267 if (parseToken(AsmToken::Comma,
4268 "unexpected token in '" + Twine(IDVal) + "' directive"))
4269 return true;
4270
4271 APInt AsInt;
4272 if (parseRealValue(Semantics, AsInt))
4273 return true;
4274
4275 if (parseToken(AsmToken::EndOfStatement,
4276 "unexpected token in '" + Twine(IDVal) + "' directive"))
4277 return true;
4278
4279 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4280 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
4281 AsInt.getBitWidth() / 8);
4282
4283 return false;
4284}
4285
Petr Hosek85b2f672016-09-23 21:53:36 +00004286/// parseDirectiveDS
4287/// ::= .ds.{b, d, l, p, s, w, x} expression
4288bool AsmParser::parseDirectiveDS(StringRef IDVal, unsigned Size) {
Petr Hosek85b2f672016-09-23 21:53:36 +00004289
4290 SMLoc NumValuesLoc = Lexer.getLoc();
4291 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004292 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek85b2f672016-09-23 21:53:36 +00004293 return true;
4294
4295 if (NumValues < 0) {
4296 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4297 return false;
4298 }
4299
4300 if (parseToken(AsmToken::EndOfStatement,
4301 "unexpected token in '" + Twine(IDVal) + "' directive"))
4302 return true;
4303
4304 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4305 getStreamer().emitFill(Size, 0);
4306
4307 return false;
4308}
4309
Jim Grosbach4b905842013-09-20 23:08:21 +00004310/// parseDirectiveLEB128
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004311/// ::= (.sleb128 | .uleb128) [ expression (, expression)* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004312bool AsmParser::parseDirectiveLEB128(bool Signed) {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004313 if (checkForValidSection())
4314 return true;
4315
Nirav Dave1a9044b2016-10-24 14:35:29 +00004316 auto parseOp = [&]() -> bool {
4317 const MCExpr *Value;
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004318 if (parseExpression(Value))
4319 return true;
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004320 if (Signed)
4321 getStreamer().EmitSLEB128Value(Value);
4322 else
4323 getStreamer().EmitULEB128Value(Value);
Nirav Dave1a9044b2016-10-24 14:35:29 +00004324 return false;
4325 };
Eli Bendersky17233942013-01-15 22:59:42 +00004326
Nirav Dave1a9044b2016-10-24 14:35:29 +00004327 if (parseMany(parseOp))
4328 return addErrorSuffix(" in directive");
Eli Bendersky17233942013-01-15 22:59:42 +00004329
4330 return false;
4331}
4332
Jim Grosbach4b905842013-09-20 23:08:21 +00004333/// parseDirectiveSymbolAttribute
Daniel Dunbara5508c82009-06-30 00:33:19 +00004334/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004335bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00004336 auto parseOp = [&]() -> bool {
4337 StringRef Name;
4338 SMLoc Loc = getTok().getLoc();
4339 if (parseIdentifier(Name))
4340 return Error(Loc, "expected identifier");
4341 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004342
Nirav Dave1a9044b2016-10-24 14:35:29 +00004343 // Assembler local symbols don't make any sense here. Complain loudly.
4344 if (Sym->isTemporary())
4345 return Error(Loc, "non-local symbol required");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004346
Nirav Dave1a9044b2016-10-24 14:35:29 +00004347 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
4348 return Error(Loc, "unable to emit symbol attribute");
4349 return false;
4350 };
Daniel Dunbara5508c82009-06-30 00:33:19 +00004351
Nirav Dave1a9044b2016-10-24 14:35:29 +00004352 if (parseMany(parseOp))
4353 return addErrorSuffix(" in directive");
Jan Wen Voungc7682872010-09-30 01:09:20 +00004354 return false;
Daniel Dunbara5508c82009-06-30 00:33:19 +00004355}
Chris Lattnera1e11f52009-07-07 20:30:46 +00004356
Jim Grosbach4b905842013-09-20 23:08:21 +00004357/// parseDirectiveComm
Chris Lattner28ad7542009-07-09 17:25:12 +00004358/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004359bool AsmParser::parseDirectiveComm(bool IsLocal) {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004360 if (checkForValidSection())
4361 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00004362
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004363 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004364 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004365 if (parseIdentifier(Name))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004366 return TokError("expected identifier in directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004367
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +00004368 // Handle the identifier as the key symbol.
Jim Grosbach6f482002015-05-18 18:43:14 +00004369 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Chris Lattnera1e11f52009-07-07 20:30:46 +00004370
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004371 if (getLexer().isNot(AsmToken::Comma))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004372 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00004373 Lex();
Chris Lattnera1e11f52009-07-07 20:30:46 +00004374
4375 int64_t Size;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004376 SMLoc SizeLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004377 if (parseAbsoluteExpression(Size))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004378 return true;
4379
4380 int64_t Pow2Alignment = 0;
4381 SMLoc Pow2AlignmentLoc;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004382 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan686ed8d2010-01-19 20:22:31 +00004383 Lex();
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004384 Pow2AlignmentLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004385 if (parseAbsoluteExpression(Pow2Alignment))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004386 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00004387
Benjamin Kramer68b9f052012-09-07 21:08:01 +00004388 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
4389 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00004390 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
4391
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00004392 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramer68b9f052012-09-07 21:08:01 +00004393 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
4394 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00004395 if (!isPowerOf2_64(Pow2Alignment))
4396 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
4397 Pow2Alignment = Log2_64(Pow2Alignment);
4398 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00004399 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00004400
Nirav Dave1a9044b2016-10-24 14:35:29 +00004401 if (parseToken(AsmToken::EndOfStatement,
4402 "unexpected token in '.comm' or '.lcomm' directive"))
4403 return true;
Chris Lattnera1e11f52009-07-07 20:30:46 +00004404
Chris Lattner28ad7542009-07-09 17:25:12 +00004405 // NOTE: a size of zero for a .comm should create a undefined symbol
4406 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattnera1e11f52009-07-07 20:30:46 +00004407 if (Size < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00004408 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
Jim Grosbach4b905842013-09-20 23:08:21 +00004409 "be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00004410
Eric Christopherbc818852010-05-14 01:38:54 +00004411 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattnera1e11f52009-07-07 20:30:46 +00004412 // may internally end up wanting an alignment in bytes.
4413 // FIXME: Diagnose overflow.
4414 if (Pow2Alignment < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00004415 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
Jim Grosbach4b905842013-09-20 23:08:21 +00004416 "alignment, can't be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00004417
Daniel Dunbar6860ac72009-08-22 07:22:36 +00004418 if (!Sym->isUndefined())
Chris Lattnera1e11f52009-07-07 20:30:46 +00004419 return Error(IDLoc, "invalid symbol redefinition");
4420
Chris Lattner28ad7542009-07-09 17:25:12 +00004421 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00004422 if (IsLocal) {
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00004423 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00004424 return false;
4425 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00004426
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004427 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattnera1e11f52009-07-07 20:30:46 +00004428 return false;
4429}
Chris Lattner07cadaf2009-07-10 22:20:30 +00004430
Jim Grosbach4b905842013-09-20 23:08:21 +00004431/// parseDirectiveAbort
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004432/// ::= .abort [... message ...]
Jim Grosbach4b905842013-09-20 23:08:21 +00004433bool AsmParser::parseDirectiveAbort() {
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004434 // FIXME: Use loc from directive.
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004435 SMLoc Loc = getLexer().getLoc();
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004436
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004437 StringRef Str = parseStringToEndOfStatement();
Nirav Davea645433c2016-07-18 15:24:03 +00004438 if (parseToken(AsmToken::EndOfStatement,
4439 "unexpected token in '.abort' directive"))
4440 return true;
Kevin Enderby56523ce2009-07-13 23:15:14 +00004441
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004442 if (Str.empty())
Nirav Dave2364748a2016-09-16 18:30:20 +00004443 return Error(Loc, ".abort detected. Assembly stopping.");
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004444 else
Nirav Dave2364748a2016-09-16 18:30:20 +00004445 return Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004446 // FIXME: Actually abort assembly here.
Kevin Enderby56523ce2009-07-13 23:15:14 +00004447
4448 return false;
4449}
Kevin Enderbycbe475d2009-07-14 21:35:03 +00004450
Jim Grosbach4b905842013-09-20 23:08:21 +00004451/// parseDirectiveInclude
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004452/// ::= .include "filename"
Jim Grosbach4b905842013-09-20 23:08:21 +00004453bool AsmParser::parseDirectiveInclude() {
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004454 // Allow the strings to have escaped octal character sequence.
4455 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00004456 SMLoc IncludeLoc = getTok().getLoc();
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004457
Nirav Davea645433c2016-07-18 15:24:03 +00004458 if (check(getTok().isNot(AsmToken::String),
4459 "expected string in '.include' directive") ||
4460 parseEscapedString(Filename) ||
4461 check(getTok().isNot(AsmToken::EndOfStatement),
4462 "unexpected token in '.include' directive") ||
4463 // Attempt to switch the lexer to the included file before consuming the
4464 // end of statement to avoid losing it when we switch.
4465 check(enterIncludeFile(Filename), IncludeLoc,
4466 "Could not find include file '" + Filename + "'"))
Chris Lattner693fbb82009-07-16 06:14:39 +00004467 return true;
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004468
4469 return false;
4470}
Kevin Enderby09ea5702009-07-15 15:30:11 +00004471
Jim Grosbach4b905842013-09-20 23:08:21 +00004472/// parseDirectiveIncbin
Petr Hosek2f4ac442016-09-23 00:41:06 +00004473/// ::= .incbin "filename" [ , skip [ , count ] ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004474bool AsmParser::parseDirectiveIncbin() {
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004475 // Allow the strings to have escaped octal character sequence.
4476 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00004477 SMLoc IncbinLoc = getTok().getLoc();
4478 if (check(getTok().isNot(AsmToken::String),
4479 "expected string in '.incbin' directive") ||
Petr Hosek2f4ac442016-09-23 00:41:06 +00004480 parseEscapedString(Filename))
4481 return true;
4482
4483 int64_t Skip = 0;
4484 const MCExpr *Count = nullptr;
4485 SMLoc SkipLoc, CountLoc;
Nirav Dave1a9044b2016-10-24 14:35:29 +00004486 if (parseOptionalToken(AsmToken::Comma)) {
Petr Hosek2f4ac442016-09-23 00:41:06 +00004487 // The skip expression can be omitted while specifying the count, e.g:
4488 // .incbin "filename",,4
4489 if (getTok().isNot(AsmToken::Comma)) {
4490 if (parseTokenLoc(SkipLoc) || parseAbsoluteExpression(Skip))
4491 return true;
4492 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00004493 if (parseOptionalToken(AsmToken::Comma)) {
4494 CountLoc = getTok().getLoc();
4495 if (parseExpression(Count))
Petr Hosek2f4ac442016-09-23 00:41:06 +00004496 return true;
4497 }
4498 }
4499
4500 if (parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00004501 "unexpected token in '.incbin' directive"))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004502 return true;
Nirav Dave1ab71992016-07-18 19:35:21 +00004503
Petr Hosek2f4ac442016-09-23 00:41:06 +00004504 if (check(Skip < 0, SkipLoc, "skip is negative"))
4505 return true;
4506
Nirav Dave1ab71992016-07-18 19:35:21 +00004507 // Attempt to process the included file.
Petr Hosek2f4ac442016-09-23 00:41:06 +00004508 if (processIncbinFile(Filename, Skip, Count, CountLoc))
Nirav Dave1ab71992016-07-18 19:35:21 +00004509 return Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
Kevin Enderby109f25c2011-12-14 21:47:48 +00004510 return false;
4511}
4512
Jim Grosbach4b905842013-09-20 23:08:21 +00004513/// parseDirectiveIf
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004514/// ::= .if{,eq,ge,gt,le,lt,ne} expression
4515bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004516 TheCondStack.push_back(TheCondState);
4517 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004518 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004519 eatToEndOfStatement();
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004520 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004521 int64_t ExprValue;
Nirav Davea645433c2016-07-18 15:24:03 +00004522 if (parseAbsoluteExpression(ExprValue) ||
4523 parseToken(AsmToken::EndOfStatement,
4524 "unexpected token in '.if' directive"))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004525 return true;
4526
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004527 switch (DirKind) {
4528 default:
4529 llvm_unreachable("unsupported directive");
4530 case DK_IF:
4531 case DK_IFNE:
4532 break;
4533 case DK_IFEQ:
4534 ExprValue = ExprValue == 0;
4535 break;
4536 case DK_IFGE:
4537 ExprValue = ExprValue >= 0;
4538 break;
4539 case DK_IFGT:
4540 ExprValue = ExprValue > 0;
4541 break;
4542 case DK_IFLE:
4543 ExprValue = ExprValue <= 0;
4544 break;
4545 case DK_IFLT:
4546 ExprValue = ExprValue < 0;
4547 break;
4548 }
4549
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004550 TheCondState.CondMet = ExprValue;
4551 TheCondState.Ignore = !TheCondState.CondMet;
4552 }
4553
4554 return false;
4555}
4556
Jim Grosbach4b905842013-09-20 23:08:21 +00004557/// parseDirectiveIfb
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004558/// ::= .ifb string
Jim Grosbach4b905842013-09-20 23:08:21 +00004559bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004560 TheCondStack.push_back(TheCondState);
4561 TheCondState.TheCond = AsmCond::IfCond;
4562
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004563 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004564 eatToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004565 } else {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004566 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004567
Nirav Davea645433c2016-07-18 15:24:03 +00004568 if (parseToken(AsmToken::EndOfStatement,
4569 "unexpected token in '.ifb' directive"))
4570 return true;
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004571
4572 TheCondState.CondMet = ExpectBlank == Str.empty();
4573 TheCondState.Ignore = !TheCondState.CondMet;
4574 }
4575
4576 return false;
4577}
4578
Jim Grosbach4b905842013-09-20 23:08:21 +00004579/// parseDirectiveIfc
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004580/// ::= .ifc string1, string2
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00004581/// ::= .ifnc string1, string2
Jim Grosbach4b905842013-09-20 23:08:21 +00004582bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004583 TheCondStack.push_back(TheCondState);
4584 TheCondState.TheCond = AsmCond::IfCond;
4585
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004586 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004587 eatToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004588 } else {
Jim Grosbach4b905842013-09-20 23:08:21 +00004589 StringRef Str1 = parseStringToComma();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004590
Nirav Davea645433c2016-07-18 15:24:03 +00004591 if (parseToken(AsmToken::Comma, "unexpected token in '.ifc' directive"))
4592 return true;
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004593
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004594 StringRef Str2 = parseStringToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004595
Nirav Davea645433c2016-07-18 15:24:03 +00004596 if (parseToken(AsmToken::EndOfStatement,
4597 "unexpected token in '.ifc' directive"))
4598 return true;
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004599
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00004600 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004601 TheCondState.Ignore = !TheCondState.CondMet;
4602 }
4603
4604 return false;
4605}
4606
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004607/// parseDirectiveIfeqs
4608/// ::= .ifeqs string1, string2
Sid Manning51c35602015-03-18 14:20:54 +00004609bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual) {
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004610 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00004611 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00004612 return TokError("expected string parameter for '.ifeqs' directive");
4613 return TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004614 }
4615
4616 StringRef String1 = getTok().getStringContents();
4617 Lex();
4618
4619 if (Lexer.isNot(AsmToken::Comma)) {
Sid Manning51c35602015-03-18 14:20:54 +00004620 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00004621 return TokError(
4622 "expected comma after first string for '.ifeqs' directive");
4623 return TokError("expected comma after first string for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004624 }
4625
4626 Lex();
4627
4628 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00004629 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00004630 return TokError("expected string parameter for '.ifeqs' directive");
4631 return TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004632 }
4633
4634 StringRef String2 = getTok().getStringContents();
4635 Lex();
4636
4637 TheCondStack.push_back(TheCondState);
4638 TheCondState.TheCond = AsmCond::IfCond;
Sid Manning51c35602015-03-18 14:20:54 +00004639 TheCondState.CondMet = ExpectEqual == (String1 == String2);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004640 TheCondState.Ignore = !TheCondState.CondMet;
4641
4642 return false;
4643}
4644
Jim Grosbach4b905842013-09-20 23:08:21 +00004645/// parseDirectiveIfdef
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004646/// ::= .ifdef symbol
Jim Grosbach4b905842013-09-20 23:08:21 +00004647bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004648 StringRef Name;
4649 TheCondStack.push_back(TheCondState);
4650 TheCondState.TheCond = AsmCond::IfCond;
4651
4652 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004653 eatToEndOfStatement();
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004654 } else {
Nirav Davea645433c2016-07-18 15:24:03 +00004655 if (check(parseIdentifier(Name), "expected identifier after '.ifdef'") ||
4656 parseToken(AsmToken::EndOfStatement, "unexpected token in '.ifdef'"))
4657 return true;
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004658
Jim Grosbach6f482002015-05-18 18:43:14 +00004659 MCSymbol *Sym = getContext().lookupSymbol(Name);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004660
4661 if (expect_defined)
Craig Topper353eda42014-04-24 06:44:33 +00004662 TheCondState.CondMet = (Sym && !Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004663 else
Craig Topper353eda42014-04-24 06:44:33 +00004664 TheCondState.CondMet = (!Sym || Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004665 TheCondState.Ignore = !TheCondState.CondMet;
4666 }
4667
4668 return false;
4669}
4670
Jim Grosbach4b905842013-09-20 23:08:21 +00004671/// parseDirectiveElseIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004672/// ::= .elseif expression
Jim Grosbach4b905842013-09-20 23:08:21 +00004673bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004674 if (TheCondState.TheCond != AsmCond::IfCond &&
4675 TheCondState.TheCond != AsmCond::ElseIfCond)
Nirav Dave2364748a2016-09-16 18:30:20 +00004676 return Error(DirectiveLoc, "Encountered a .elseif that doesn't follow an"
4677 " .if or an .elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004678 TheCondState.TheCond = AsmCond::ElseIfCond;
4679
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004680 bool LastIgnoreState = false;
4681 if (!TheCondStack.empty())
Craig Topper2172ad62013-04-22 04:24:02 +00004682 LastIgnoreState = TheCondStack.back().Ignore;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004683 if (LastIgnoreState || TheCondState.CondMet) {
4684 TheCondState.Ignore = true;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004685 eatToEndOfStatement();
Craig Topperf15655b2013-04-22 04:22:40 +00004686 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004687 int64_t ExprValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004688 if (parseAbsoluteExpression(ExprValue))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004689 return true;
4690
Nirav Dave1a9044b2016-10-24 14:35:29 +00004691 if (parseToken(AsmToken::EndOfStatement,
4692 "unexpected token in '.elseif' directive"))
4693 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00004694
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004695 TheCondState.CondMet = ExprValue;
4696 TheCondState.Ignore = !TheCondState.CondMet;
4697 }
4698
4699 return false;
4700}
4701
Jim Grosbach4b905842013-09-20 23:08:21 +00004702/// parseDirectiveElse
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004703/// ::= .else
Jim Grosbach4b905842013-09-20 23:08:21 +00004704bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00004705 if (parseToken(AsmToken::EndOfStatement,
4706 "unexpected token in '.else' directive"))
4707 return true;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004708
4709 if (TheCondState.TheCond != AsmCond::IfCond &&
4710 TheCondState.TheCond != AsmCond::ElseIfCond)
Nirav Dave2364748a2016-09-16 18:30:20 +00004711 return Error(DirectiveLoc, "Encountered a .else that doesn't follow "
4712 " an .if or an .elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004713 TheCondState.TheCond = AsmCond::ElseCond;
4714 bool LastIgnoreState = false;
4715 if (!TheCondStack.empty())
4716 LastIgnoreState = TheCondStack.back().Ignore;
4717 if (LastIgnoreState || TheCondState.CondMet)
4718 TheCondState.Ignore = true;
4719 else
4720 TheCondState.Ignore = false;
4721
4722 return false;
4723}
4724
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004725/// parseDirectiveEnd
4726/// ::= .end
4727bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00004728 if (parseToken(AsmToken::EndOfStatement,
4729 "unexpected token in '.end' directive"))
4730 return true;
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004731
4732 while (Lexer.isNot(AsmToken::Eof))
Nirav Dave1a9044b2016-10-24 14:35:29 +00004733 Lexer.Lex();
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004734
4735 return false;
4736}
4737
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004738/// parseDirectiveError
4739/// ::= .err
4740/// ::= .error [string]
4741bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
4742 if (!TheCondStack.empty()) {
4743 if (TheCondStack.back().Ignore) {
4744 eatToEndOfStatement();
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004745 return false;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004746 }
4747 }
4748
4749 if (!WithMessage)
4750 return Error(L, ".err encountered");
4751
4752 StringRef Message = ".error directive invoked in source file";
4753 if (Lexer.isNot(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00004754 if (Lexer.isNot(AsmToken::String))
4755 return TokError(".error argument must be a string");
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004756
4757 Message = getTok().getStringContents();
4758 Lex();
4759 }
4760
Nirav Dave2364748a2016-09-16 18:30:20 +00004761 return Error(L, Message);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004762}
4763
Nico Weber404012b2014-07-24 16:26:06 +00004764/// parseDirectiveWarning
4765/// ::= .warning [string]
4766bool AsmParser::parseDirectiveWarning(SMLoc L) {
4767 if (!TheCondStack.empty()) {
4768 if (TheCondStack.back().Ignore) {
4769 eatToEndOfStatement();
4770 return false;
4771 }
4772 }
4773
4774 StringRef Message = ".warning directive invoked in source file";
Nirav Dave1a9044b2016-10-24 14:35:29 +00004775
4776 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00004777 if (Lexer.isNot(AsmToken::String))
4778 return TokError(".warning argument must be a string");
Nico Weber404012b2014-07-24 16:26:06 +00004779
4780 Message = getTok().getStringContents();
4781 Lex();
Nirav Dave1a9044b2016-10-24 14:35:29 +00004782 if (parseToken(AsmToken::EndOfStatement,
4783 "expected end of statement in '.warning' directive"))
4784 return true;
Nico Weber404012b2014-07-24 16:26:06 +00004785 }
4786
Nirav Dave2364748a2016-09-16 18:30:20 +00004787 return Warning(L, Message);
Nico Weber404012b2014-07-24 16:26:06 +00004788}
4789
Jim Grosbach4b905842013-09-20 23:08:21 +00004790/// parseDirectiveEndIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004791/// ::= .endif
Jim Grosbach4b905842013-09-20 23:08:21 +00004792bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00004793 if (parseToken(AsmToken::EndOfStatement,
4794 "unexpected token in '.endif' directive"))
4795 return true;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004796
Jim Grosbach4b905842013-09-20 23:08:21 +00004797 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
Nirav Dave2364748a2016-09-16 18:30:20 +00004798 return Error(DirectiveLoc, "Encountered a .endif that doesn't follow "
4799 "an .if or .else");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004800 if (!TheCondStack.empty()) {
4801 TheCondState = TheCondStack.back();
4802 TheCondStack.pop_back();
4803 }
4804
4805 return false;
4806}
Daniel Dunbara4b069c2009-08-11 04:24:50 +00004807
Eli Bendersky17233942013-01-15 22:59:42 +00004808void AsmParser::initializeDirectiveKindMap() {
4809 DirectiveKindMap[".set"] = DK_SET;
4810 DirectiveKindMap[".equ"] = DK_EQU;
4811 DirectiveKindMap[".equiv"] = DK_EQUIV;
4812 DirectiveKindMap[".ascii"] = DK_ASCII;
4813 DirectiveKindMap[".asciz"] = DK_ASCIZ;
4814 DirectiveKindMap[".string"] = DK_STRING;
4815 DirectiveKindMap[".byte"] = DK_BYTE;
4816 DirectiveKindMap[".short"] = DK_SHORT;
4817 DirectiveKindMap[".value"] = DK_VALUE;
4818 DirectiveKindMap[".2byte"] = DK_2BYTE;
4819 DirectiveKindMap[".long"] = DK_LONG;
4820 DirectiveKindMap[".int"] = DK_INT;
4821 DirectiveKindMap[".4byte"] = DK_4BYTE;
4822 DirectiveKindMap[".quad"] = DK_QUAD;
4823 DirectiveKindMap[".8byte"] = DK_8BYTE;
David Woodhoused6de0d92014-02-01 16:20:59 +00004824 DirectiveKindMap[".octa"] = DK_OCTA;
Eli Bendersky17233942013-01-15 22:59:42 +00004825 DirectiveKindMap[".single"] = DK_SINGLE;
4826 DirectiveKindMap[".float"] = DK_FLOAT;
4827 DirectiveKindMap[".double"] = DK_DOUBLE;
4828 DirectiveKindMap[".align"] = DK_ALIGN;
4829 DirectiveKindMap[".align32"] = DK_ALIGN32;
4830 DirectiveKindMap[".balign"] = DK_BALIGN;
4831 DirectiveKindMap[".balignw"] = DK_BALIGNW;
4832 DirectiveKindMap[".balignl"] = DK_BALIGNL;
4833 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
4834 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
4835 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
4836 DirectiveKindMap[".org"] = DK_ORG;
4837 DirectiveKindMap[".fill"] = DK_FILL;
4838 DirectiveKindMap[".zero"] = DK_ZERO;
4839 DirectiveKindMap[".extern"] = DK_EXTERN;
4840 DirectiveKindMap[".globl"] = DK_GLOBL;
4841 DirectiveKindMap[".global"] = DK_GLOBAL;
Eli Bendersky17233942013-01-15 22:59:42 +00004842 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
4843 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
4844 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
4845 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
4846 DirectiveKindMap[".reference"] = DK_REFERENCE;
4847 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
4848 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
4849 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
4850 DirectiveKindMap[".comm"] = DK_COMM;
4851 DirectiveKindMap[".common"] = DK_COMMON;
4852 DirectiveKindMap[".lcomm"] = DK_LCOMM;
4853 DirectiveKindMap[".abort"] = DK_ABORT;
4854 DirectiveKindMap[".include"] = DK_INCLUDE;
4855 DirectiveKindMap[".incbin"] = DK_INCBIN;
4856 DirectiveKindMap[".code16"] = DK_CODE16;
4857 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
4858 DirectiveKindMap[".rept"] = DK_REPT;
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00004859 DirectiveKindMap[".rep"] = DK_REPT;
Eli Bendersky17233942013-01-15 22:59:42 +00004860 DirectiveKindMap[".irp"] = DK_IRP;
4861 DirectiveKindMap[".irpc"] = DK_IRPC;
4862 DirectiveKindMap[".endr"] = DK_ENDR;
4863 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
4864 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
4865 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
4866 DirectiveKindMap[".if"] = DK_IF;
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004867 DirectiveKindMap[".ifeq"] = DK_IFEQ;
4868 DirectiveKindMap[".ifge"] = DK_IFGE;
4869 DirectiveKindMap[".ifgt"] = DK_IFGT;
4870 DirectiveKindMap[".ifle"] = DK_IFLE;
4871 DirectiveKindMap[".iflt"] = DK_IFLT;
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00004872 DirectiveKindMap[".ifne"] = DK_IFNE;
Eli Bendersky17233942013-01-15 22:59:42 +00004873 DirectiveKindMap[".ifb"] = DK_IFB;
4874 DirectiveKindMap[".ifnb"] = DK_IFNB;
4875 DirectiveKindMap[".ifc"] = DK_IFC;
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004876 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
Eli Bendersky17233942013-01-15 22:59:42 +00004877 DirectiveKindMap[".ifnc"] = DK_IFNC;
Sid Manning51c35602015-03-18 14:20:54 +00004878 DirectiveKindMap[".ifnes"] = DK_IFNES;
Eli Bendersky17233942013-01-15 22:59:42 +00004879 DirectiveKindMap[".ifdef"] = DK_IFDEF;
4880 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
4881 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
4882 DirectiveKindMap[".elseif"] = DK_ELSEIF;
4883 DirectiveKindMap[".else"] = DK_ELSE;
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004884 DirectiveKindMap[".end"] = DK_END;
Eli Bendersky17233942013-01-15 22:59:42 +00004885 DirectiveKindMap[".endif"] = DK_ENDIF;
4886 DirectiveKindMap[".skip"] = DK_SKIP;
4887 DirectiveKindMap[".space"] = DK_SPACE;
4888 DirectiveKindMap[".file"] = DK_FILE;
4889 DirectiveKindMap[".line"] = DK_LINE;
4890 DirectiveKindMap[".loc"] = DK_LOC;
4891 DirectiveKindMap[".stabs"] = DK_STABS;
Reid Kleckner2214ed82016-01-29 00:49:42 +00004892 DirectiveKindMap[".cv_file"] = DK_CV_FILE;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00004893 DirectiveKindMap[".cv_func_id"] = DK_CV_FUNC_ID;
Reid Kleckner2214ed82016-01-29 00:49:42 +00004894 DirectiveKindMap[".cv_loc"] = DK_CV_LOC;
4895 DirectiveKindMap[".cv_linetable"] = DK_CV_LINETABLE;
David Majnemer6fcbd7e2016-01-29 19:24:12 +00004896 DirectiveKindMap[".cv_inline_linetable"] = DK_CV_INLINE_LINETABLE;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00004897 DirectiveKindMap[".cv_inline_site_id"] = DK_CV_INLINE_SITE_ID;
David Majnemer408b5e62016-02-05 01:55:49 +00004898 DirectiveKindMap[".cv_def_range"] = DK_CV_DEF_RANGE;
Reid Kleckner2214ed82016-01-29 00:49:42 +00004899 DirectiveKindMap[".cv_stringtable"] = DK_CV_STRINGTABLE;
4900 DirectiveKindMap[".cv_filechecksums"] = DK_CV_FILECHECKSUMS;
Eli Bendersky17233942013-01-15 22:59:42 +00004901 DirectiveKindMap[".sleb128"] = DK_SLEB128;
4902 DirectiveKindMap[".uleb128"] = DK_ULEB128;
4903 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
4904 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
4905 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
4906 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
4907 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
4908 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
4909 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
4910 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
4911 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
4912 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
4913 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
4914 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
4915 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
4916 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
4917 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
4918 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
4919 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
4920 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
4921 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00004922 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
Eli Bendersky17233942013-01-15 22:59:42 +00004923 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
4924 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
4925 DirectiveKindMap[".macro"] = DK_MACRO;
Nico Weber155dccd12014-07-24 17:08:39 +00004926 DirectiveKindMap[".exitm"] = DK_EXITM;
Eli Bendersky17233942013-01-15 22:59:42 +00004927 DirectiveKindMap[".endm"] = DK_ENDM;
4928 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
4929 DirectiveKindMap[".purgem"] = DK_PURGEM;
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004930 DirectiveKindMap[".err"] = DK_ERR;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004931 DirectiveKindMap[".error"] = DK_ERROR;
Nico Weber404012b2014-07-24 16:26:06 +00004932 DirectiveKindMap[".warning"] = DK_WARNING;
Daniel Sanders9f6ad492015-11-12 13:33:00 +00004933 DirectiveKindMap[".reloc"] = DK_RELOC;
Petr Hosek731bb9c2016-08-23 21:34:53 +00004934 DirectiveKindMap[".dc"] = DK_DC;
4935 DirectiveKindMap[".dc.a"] = DK_DC_A;
4936 DirectiveKindMap[".dc.b"] = DK_DC_B;
4937 DirectiveKindMap[".dc.d"] = DK_DC_D;
4938 DirectiveKindMap[".dc.l"] = DK_DC_L;
4939 DirectiveKindMap[".dc.s"] = DK_DC_S;
4940 DirectiveKindMap[".dc.w"] = DK_DC_W;
4941 DirectiveKindMap[".dc.x"] = DK_DC_X;
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004942 DirectiveKindMap[".dcb"] = DK_DCB;
4943 DirectiveKindMap[".dcb.b"] = DK_DCB_B;
4944 DirectiveKindMap[".dcb.d"] = DK_DCB_D;
4945 DirectiveKindMap[".dcb.l"] = DK_DCB_L;
4946 DirectiveKindMap[".dcb.s"] = DK_DCB_S;
4947 DirectiveKindMap[".dcb.w"] = DK_DCB_W;
4948 DirectiveKindMap[".dcb.x"] = DK_DCB_X;
Petr Hosek85b2f672016-09-23 21:53:36 +00004949 DirectiveKindMap[".ds"] = DK_DS;
4950 DirectiveKindMap[".ds.b"] = DK_DS_B;
4951 DirectiveKindMap[".ds.d"] = DK_DS_D;
4952 DirectiveKindMap[".ds.l"] = DK_DS_L;
4953 DirectiveKindMap[".ds.p"] = DK_DS_P;
4954 DirectiveKindMap[".ds.s"] = DK_DS_S;
4955 DirectiveKindMap[".ds.w"] = DK_DS_W;
4956 DirectiveKindMap[".ds.x"] = DK_DS_X;
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00004957}
4958
Jim Grosbach4b905842013-09-20 23:08:21 +00004959MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004960 AsmToken EndToken, StartToken = getTok();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004961
Rafael Espindola34b9c512012-06-03 23:57:14 +00004962 unsigned NestLevel = 0;
Eugene Zelenko33d7b762016-08-23 17:14:32 +00004963 while (true) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004964 // Check whether we have reached the end of the file.
Rafael Espindola34b9c512012-06-03 23:57:14 +00004965 if (getLexer().is(AsmToken::Eof)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00004966 printError(DirectiveLoc, "no matching '.endr' in definition");
Craig Topper353eda42014-04-24 06:44:33 +00004967 return nullptr;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004968 }
4969
Rafael Espindola34b9c512012-06-03 23:57:14 +00004970 if (Lexer.is(AsmToken::Identifier) &&
Nikolay Haustov95b4fcd2016-03-01 08:18:28 +00004971 (getTok().getIdentifier() == ".rept" ||
4972 getTok().getIdentifier() == ".irp" ||
4973 getTok().getIdentifier() == ".irpc")) {
Rafael Espindola34b9c512012-06-03 23:57:14 +00004974 ++NestLevel;
4975 }
4976
4977 // Otherwise, check whether we have reached the .endr.
Jim Grosbach4b905842013-09-20 23:08:21 +00004978 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
Rafael Espindola34b9c512012-06-03 23:57:14 +00004979 if (NestLevel == 0) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004980 EndToken = getTok();
4981 Lex();
Rafael Espindola34b9c512012-06-03 23:57:14 +00004982 if (Lexer.isNot(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00004983 printError(getTok().getLoc(),
4984 "unexpected token in '.endr' directive");
Craig Topper353eda42014-04-24 06:44:33 +00004985 return nullptr;
Rafael Espindola34b9c512012-06-03 23:57:14 +00004986 }
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004987 break;
4988 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00004989 --NestLevel;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004990 }
4991
Rafael Espindola34b9c512012-06-03 23:57:14 +00004992 // Otherwise, scan till the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004993 eatToEndOfStatement();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004994 }
4995
4996 const char *BodyStart = StartToken.getLoc().getPointer();
4997 const char *BodyEnd = EndToken.getLoc().getPointer();
4998 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
4999
Rafael Espindola34b9c512012-06-03 23:57:14 +00005000 // We Are Anonymous.
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00005001 MacroLikeBodies.emplace_back(StringRef(), Body, MCAsmMacroParameters());
Benjamin Kramer1df3a1f2013-08-04 09:06:29 +00005002 return &MacroLikeBodies.back();
Rafael Espindola34b9c512012-06-03 23:57:14 +00005003}
5004
Jim Grosbach4b905842013-09-20 23:08:21 +00005005void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +00005006 raw_svector_ostream &OS) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005007 OS << ".endr\n";
5008
Rafael Espindola3560ff22014-08-27 20:03:13 +00005009 std::unique_ptr<MemoryBuffer> Instantiation =
5010 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005011
Rafael Espindola34b9c512012-06-03 23:57:14 +00005012 // Create the macro instantiation object and add to the current macro
5013 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00005014 MacroInstantiation *MI = new MacroInstantiation(
5015 DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Rafael Espindola34b9c512012-06-03 23:57:14 +00005016 ActiveMacros.push_back(MI);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005017
Rafael Espindola34b9c512012-06-03 23:57:14 +00005018 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00005019 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00005020 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Rafael Espindola34b9c512012-06-03 23:57:14 +00005021 Lex();
5022}
5023
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00005024/// parseDirectiveRept
5025/// ::= .rep | .rept count
5026bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00005027 const MCExpr *CountExpr;
5028 SMLoc CountLoc = getTok().getLoc();
5029 if (parseExpression(CountExpr))
5030 return true;
5031
Rafael Espindola34b9c512012-06-03 23:57:14 +00005032 int64_t Count;
Jim Grosbach13760bd2015-05-30 01:25:56 +00005033 if (!CountExpr->evaluateAsAbsolute(Count)) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00005034 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
5035 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00005036
Nirav Davea645433c2016-07-18 15:24:03 +00005037 if (check(Count < 0, CountLoc, "Count is negative") ||
5038 parseToken(AsmToken::EndOfStatement,
5039 "unexpected token in '" + Dir + "' directive"))
5040 return true;
Rafael Espindola34b9c512012-06-03 23:57:14 +00005041
5042 // Lex the rept definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005043 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola34b9c512012-06-03 23:57:14 +00005044 if (!M)
5045 return true;
5046
5047 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5048 // to hold the macro body with substitutions.
5049 SmallString<256> Buf;
Rafael Espindola34b9c512012-06-03 23:57:14 +00005050 raw_svector_ostream OS(Buf);
5051 while (Count--) {
Toma Tabacu217116e2015-04-27 10:50:29 +00005052 // Note that the AtPseudoVariable is disabled for instantiations of .rep(t).
5053 if (expandMacro(OS, M->Body, None, None, false, getTok().getLoc()))
Rafael Espindola34b9c512012-06-03 23:57:14 +00005054 return true;
5055 }
Jim Grosbach4b905842013-09-20 23:08:21 +00005056 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005057
5058 return false;
5059}
5060
Jim Grosbach4b905842013-09-20 23:08:21 +00005061/// parseDirectiveIrp
Rafael Espindola768b41c2012-06-15 14:02:34 +00005062/// ::= .irp symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00005063bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00005064 MCAsmMacroParameter Parameter;
Eli Bendersky38274122013-01-14 23:22:36 +00005065 MCAsmMacroArguments A;
Nirav Davea645433c2016-07-18 15:24:03 +00005066 if (check(parseIdentifier(Parameter.Name),
5067 "expected identifier in '.irp' directive") ||
5068 parseToken(AsmToken::Comma, "expected comma in '.irp' directive") ||
5069 parseMacroArguments(nullptr, A) ||
5070 parseToken(AsmToken::EndOfStatement, "expected End of Statement"))
Rafael Espindola768b41c2012-06-15 14:02:34 +00005071 return true;
5072
Rafael Espindola768b41c2012-06-15 14:02:34 +00005073 // Lex the irp definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005074 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola768b41c2012-06-15 14:02:34 +00005075 if (!M)
5076 return true;
5077
5078 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5079 // to hold the macro body with substitutions.
5080 SmallString<256> Buf;
5081 raw_svector_ostream OS(Buf);
5082
Craig Topper84008482015-10-10 05:38:14 +00005083 for (const MCAsmMacroArgument &Arg : A) {
Toma Tabacu217116e2015-04-27 10:50:29 +00005084 // Note that the AtPseudoVariable is enabled for instantiations of .irp.
5085 // This is undocumented, but GAS seems to support it.
Craig Topper84008482015-10-10 05:38:14 +00005086 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindola768b41c2012-06-15 14:02:34 +00005087 return true;
5088 }
5089
Jim Grosbach4b905842013-09-20 23:08:21 +00005090 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola768b41c2012-06-15 14:02:34 +00005091
5092 return false;
5093}
5094
Jim Grosbach4b905842013-09-20 23:08:21 +00005095/// parseDirectiveIrpc
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005096/// ::= .irpc symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00005097bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00005098 MCAsmMacroParameter Parameter;
Eli Bendersky38274122013-01-14 23:22:36 +00005099 MCAsmMacroArguments A;
Nirav Davea645433c2016-07-18 15:24:03 +00005100
5101 if (check(parseIdentifier(Parameter.Name),
5102 "expected identifier in '.irpc' directive") ||
5103 parseToken(AsmToken::Comma, "expected comma in '.irpc' directive") ||
5104 parseMacroArguments(nullptr, A))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005105 return true;
5106
5107 if (A.size() != 1 || A.front().size() != 1)
5108 return TokError("unexpected token in '.irpc' directive");
5109
5110 // Eat the end of statement.
Nirav Davea645433c2016-07-18 15:24:03 +00005111 if (parseToken(AsmToken::EndOfStatement, "expected end of statement"))
5112 return true;
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005113
5114 // Lex the irpc definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005115 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005116 if (!M)
5117 return true;
5118
5119 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5120 // to hold the macro body with substitutions.
5121 SmallString<256> Buf;
5122 raw_svector_ostream OS(Buf);
5123
5124 StringRef Values = A.front().front().getString();
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00005125 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
Eli Benderskya7b905e2013-01-14 19:00:26 +00005126 MCAsmMacroArgument Arg;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00005127 Arg.emplace_back(AsmToken::Identifier, Values.slice(I, I + 1));
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005128
Toma Tabacu217116e2015-04-27 10:50:29 +00005129 // Note that the AtPseudoVariable is enabled for instantiations of .irpc.
5130 // This is undocumented, but GAS seems to support it.
5131 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005132 return true;
5133 }
5134
Jim Grosbach4b905842013-09-20 23:08:21 +00005135 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005136
5137 return false;
5138}
5139
Jim Grosbach4b905842013-09-20 23:08:21 +00005140bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
Rafael Espindola34b9c512012-06-03 23:57:14 +00005141 if (ActiveMacros.empty())
Preston Gurdeb3ebf12012-09-19 20:23:43 +00005142 return TokError("unmatched '.endr' directive");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005143
5144 // The only .repl that should get here are the ones created by
Jim Grosbach4b905842013-09-20 23:08:21 +00005145 // instantiateMacroLikeBody.
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005146 assert(getLexer().is(AsmToken::EndOfStatement));
5147
Jim Grosbach4b905842013-09-20 23:08:21 +00005148 handleMacroExit();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005149 return false;
5150}
Rafael Espindola12d73d12010-09-11 16:45:15 +00005151
Jim Grosbach4b905842013-09-20 23:08:21 +00005152bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
Benjamin Kramer1a136112013-02-15 20:37:21 +00005153 size_t Len) {
Eli Friedman0f4871d2012-10-22 23:58:19 +00005154 const MCExpr *Value;
5155 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005156 if (parseExpression(Value))
Eli Friedman0f4871d2012-10-22 23:58:19 +00005157 return true;
5158 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5159 if (!MCE)
5160 return Error(ExprLoc, "unexpected expression in _emit");
5161 uint64_t IntValue = MCE->getValue();
Craig Topper55b1f292015-10-10 20:17:07 +00005162 if (!isUInt<8>(IntValue) && !isInt<8>(IntValue))
Eli Friedman0f4871d2012-10-22 23:58:19 +00005163 return Error(ExprLoc, "literal value out of range for directive");
5164
Craig Topper7d5b2312015-10-10 05:25:02 +00005165 Info.AsmRewrites->emplace_back(AOK_Emit, IDLoc, Len);
Chad Rosierc7f552c2013-02-12 21:33:51 +00005166 return false;
5167}
5168
Jim Grosbach4b905842013-09-20 23:08:21 +00005169bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
Chad Rosierc7f552c2013-02-12 21:33:51 +00005170 const MCExpr *Value;
5171 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005172 if (parseExpression(Value))
Chad Rosierc7f552c2013-02-12 21:33:51 +00005173 return true;
5174 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5175 if (!MCE)
5176 return Error(ExprLoc, "unexpected expression in align");
5177 uint64_t IntValue = MCE->getValue();
5178 if (!isPowerOf2_64(IntValue))
5179 return Error(ExprLoc, "literal value not a power of two greater then zero");
5180
Craig Topper7d5b2312015-10-10 05:25:02 +00005181 Info.AsmRewrites->emplace_back(AOK_Align, IDLoc, 5, Log2_64(IntValue));
Eli Friedman0f4871d2012-10-22 23:58:19 +00005182 return false;
5183}
5184
Chad Rosierf43fcf52013-02-13 21:27:17 +00005185// We are comparing pointers, but the pointers are relative to a single string.
5186// Thus, this should always be deterministic.
Benjamin Kramer8817cca2013-09-22 14:09:50 +00005187static int rewritesSort(const AsmRewrite *AsmRewriteA,
5188 const AsmRewrite *AsmRewriteB) {
Chad Rosiereb5c1682013-02-13 18:38:58 +00005189 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
5190 return -1;
5191 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
5192 return 1;
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005193
Chad Rosierfce4fab2013-04-08 17:43:47 +00005194 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
5195 // rewrite to the same location. Make sure the SizeDirective rewrite is
5196 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
5197 // ensures the sort algorithm is stable.
Jim Grosbach4b905842013-09-20 23:08:21 +00005198 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
5199 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005200 return -1;
Chad Rosierfce4fab2013-04-08 17:43:47 +00005201
Jim Grosbach4b905842013-09-20 23:08:21 +00005202 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
5203 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005204 return 1;
Jim Grosbach4b905842013-09-20 23:08:21 +00005205 llvm_unreachable("Unstable rewrite sort.");
Chad Rosierb2144ce2013-02-13 01:03:13 +00005206}
5207
Jim Grosbach4b905842013-09-20 23:08:21 +00005208bool AsmParser::parseMSInlineAsm(
5209 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
5210 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
5211 SmallVectorImpl<std::string> &Constraints,
5212 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
5213 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
Chad Rosier37e755c2012-10-23 17:43:43 +00005214 SmallVector<void *, 4> InputDecls;
5215 SmallVector<void *, 4> OutputDecls;
Chad Rosiera4bc9432013-01-10 22:10:27 +00005216 SmallVector<bool, 4> InputDeclsAddressOf;
5217 SmallVector<bool, 4> OutputDeclsAddressOf;
Chad Rosier8bce6642012-10-18 15:49:34 +00005218 SmallVector<std::string, 4> InputConstraints;
5219 SmallVector<std::string, 4> OutputConstraints;
Benjamin Kramer1a136112013-02-15 20:37:21 +00005220 SmallVector<unsigned, 4> ClobberRegs;
Chad Rosier8bce6642012-10-18 15:49:34 +00005221
Benjamin Kramer1a136112013-02-15 20:37:21 +00005222 SmallVector<AsmRewrite, 4> AsmStrRewrites;
Chad Rosier8bce6642012-10-18 15:49:34 +00005223
5224 // Prime the lexer.
5225 Lex();
5226
5227 // While we have input, parse each statement.
5228 unsigned InputIdx = 0;
5229 unsigned OutputIdx = 0;
5230 while (getLexer().isNot(AsmToken::Eof)) {
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00005231 // Parse curly braces marking block start/end
5232 if (parseCurlyBlockScope(AsmStrRewrites))
5233 continue;
5234
Eli Friedman0f4871d2012-10-22 23:58:19 +00005235 ParseStatementInfo Info(&AsmStrRewrites);
Nirav Dave2364748a2016-09-16 18:30:20 +00005236 bool StatementErr = parseStatement(Info, &SI);
Nirav Dave9fa8af22016-09-13 13:55:06 +00005237
Nirav Dave2364748a2016-09-16 18:30:20 +00005238 if (StatementErr || Info.ParseError) {
5239 // Emit pending errors if any exist.
5240 printPendingErrors();
Nico Webere204c482016-09-13 18:17:00 +00005241 return true;
Nirav Dave2364748a2016-09-16 18:30:20 +00005242 }
5243
5244 // No pending error should exist here.
5245 assert(!hasPendingError() && "unexpected error from parseStatement");
Chad Rosier149e8e02012-12-12 22:45:52 +00005246
Benjamin Kramer1a136112013-02-15 20:37:21 +00005247 if (Info.Opcode == ~0U)
5248 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00005249
Benjamin Kramer1a136112013-02-15 20:37:21 +00005250 const MCInstrDesc &Desc = MII->get(Info.Opcode);
Chad Rosier8bce6642012-10-18 15:49:34 +00005251
Benjamin Kramer1a136112013-02-15 20:37:21 +00005252 // Build the list of clobbers, outputs and inputs.
5253 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
David Blaikie960ea3f2014-06-08 16:18:35 +00005254 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005255
Benjamin Kramer1a136112013-02-15 20:37:21 +00005256 // Immediate.
David Blaikie960ea3f2014-06-08 16:18:35 +00005257 if (Operand.isImm())
Benjamin Kramer1a136112013-02-15 20:37:21 +00005258 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00005259
Benjamin Kramer1a136112013-02-15 20:37:21 +00005260 // Register operand.
Nico Weber42f79db2014-07-17 20:24:55 +00005261 if (Operand.isReg() && !Operand.needAddressOf() &&
5262 !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
Benjamin Kramer1a136112013-02-15 20:37:21 +00005263 unsigned NumDefs = Desc.getNumDefs();
5264 // Clobber.
David Blaikie960ea3f2014-06-08 16:18:35 +00005265 if (NumDefs && Operand.getMCOperandNum() < NumDefs)
5266 ClobberRegs.push_back(Operand.getReg());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005267 continue;
5268 }
5269
5270 // Expr/Input or Output.
David Blaikie960ea3f2014-06-08 16:18:35 +00005271 StringRef SymName = Operand.getSymName();
Chad Rosiere81309b2013-04-09 17:53:49 +00005272 if (SymName.empty())
5273 continue;
5274
David Blaikie960ea3f2014-06-08 16:18:35 +00005275 void *OpDecl = Operand.getOpDecl();
Benjamin Kramer1a136112013-02-15 20:37:21 +00005276 if (!OpDecl)
5277 continue;
5278
5279 bool isOutput = (i == 1) && Desc.mayStore();
Chad Rosiere81309b2013-04-09 17:53:49 +00005280 SMLoc Start = SMLoc::getFromPointer(SymName.data());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005281 if (isOutput) {
5282 ++InputIdx;
5283 OutputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00005284 OutputDeclsAddressOf.push_back(Operand.needAddressOf());
Yaron Keren075759a2015-03-30 15:42:36 +00005285 OutputConstraints.push_back(("=" + Operand.getConstraint()).str());
Craig Topper7d5b2312015-10-10 05:25:02 +00005286 AsmStrRewrites.emplace_back(AOK_Output, Start, SymName.size());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005287 } else {
5288 InputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00005289 InputDeclsAddressOf.push_back(Operand.needAddressOf());
5290 InputConstraints.push_back(Operand.getConstraint().str());
Craig Topper7d5b2312015-10-10 05:25:02 +00005291 AsmStrRewrites.emplace_back(AOK_Input, Start, SymName.size());
Chad Rosier8bce6642012-10-18 15:49:34 +00005292 }
Chad Rosier8bce6642012-10-18 15:49:34 +00005293 }
Reid Kleckneree088972013-12-10 18:27:32 +00005294
5295 // Consider implicit defs to be clobbers. Think of cpuid and push.
Craig Toppere5e035a32015-12-05 07:13:35 +00005296 ArrayRef<MCPhysReg> ImpDefs(Desc.getImplicitDefs(),
5297 Desc.getNumImplicitDefs());
David Majnemer8114c1a2014-06-23 02:17:16 +00005298 ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end());
Chad Rosier8bce6642012-10-18 15:49:34 +00005299 }
5300
5301 // Set the number of Outputs and Inputs.
Chad Rosierf641baa2012-10-18 19:39:30 +00005302 NumOutputs = OutputDecls.size();
5303 NumInputs = InputDecls.size();
Chad Rosier8bce6642012-10-18 15:49:34 +00005304
5305 // Set the unique clobbers.
Benjamin Kramer1a136112013-02-15 20:37:21 +00005306 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
5307 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
5308 ClobberRegs.end());
5309 Clobbers.assign(ClobberRegs.size(), std::string());
5310 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
5311 raw_string_ostream OS(Clobbers[I]);
5312 IP->printRegName(OS, ClobberRegs[I]);
5313 }
Chad Rosier8bce6642012-10-18 15:49:34 +00005314
5315 // Merge the various outputs and inputs. Output are expected first.
5316 if (NumOutputs || NumInputs) {
5317 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierf641baa2012-10-18 19:39:30 +00005318 OpDecls.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00005319 Constraints.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00005320 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00005321 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00005322 Constraints[i] = OutputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005323 }
5324 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00005325 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00005326 Constraints[j] = InputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005327 }
5328 }
5329
5330 // Build the IR assembly string.
Alp Tokere69170a2014-06-26 22:52:05 +00005331 std::string AsmStringIR;
5332 raw_string_ostream OS(AsmStringIR);
Alp Tokera55b95b2014-07-06 10:33:31 +00005333 StringRef ASMString =
5334 SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
5335 const char *AsmStart = ASMString.begin();
5336 const char *AsmEnd = ASMString.end();
Jim Grosbach4b905842013-09-20 23:08:21 +00005337 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
David Majnemer8114c1a2014-06-23 02:17:16 +00005338 for (const AsmRewrite &AR : AsmStrRewrites) {
5339 AsmRewriteKind Kind = AR.Kind;
Chad Rosierff10ed12013-04-12 16:26:42 +00005340 if (Kind == AOK_Delete)
5341 continue;
5342
David Majnemer8114c1a2014-06-23 02:17:16 +00005343 const char *Loc = AR.Loc.getPointer();
Chad Rosier17d37992013-03-19 21:12:14 +00005344 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
Chad Rosier0f48c552012-10-19 20:57:14 +00005345
Chad Rosier120eefd2013-03-19 17:32:17 +00005346 // Emit everything up to the immediate/expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00005347 if (unsigned Len = Loc - AsmStart)
Chad Rosier17d37992013-03-19 21:12:14 +00005348 OS << StringRef(AsmStart, Len);
Chad Rosier0f48c552012-10-19 20:57:14 +00005349
Chad Rosier37e755c2012-10-23 17:43:43 +00005350 // Skip the original expression.
5351 if (Kind == AOK_Skip) {
David Majnemer8114c1a2014-06-23 02:17:16 +00005352 AsmStart = Loc + AR.Len;
Chad Rosier37e755c2012-10-23 17:43:43 +00005353 continue;
5354 }
5355
Chad Rosierff10ed12013-04-12 16:26:42 +00005356 unsigned AdditionalSkip = 0;
Chad Rosier8bce6642012-10-18 15:49:34 +00005357 // Rewrite expressions in $N notation.
Chad Rosier0f48c552012-10-19 20:57:14 +00005358 switch (Kind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00005359 default:
5360 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005361 case AOK_Imm:
David Majnemer8114c1a2014-06-23 02:17:16 +00005362 OS << "$$" << AR.Val;
Chad Rosier11c42f22012-10-26 18:04:20 +00005363 break;
5364 case AOK_ImmPrefix:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005365 OS << "$$";
Chad Rosier8bce6642012-10-18 15:49:34 +00005366 break;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005367 case AOK_Label:
Matt Arsenault4e273432014-12-04 00:06:57 +00005368 OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005369 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005370 case AOK_Input:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005371 OS << '$' << InputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00005372 break;
5373 case AOK_Output:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005374 OS << '$' << OutputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00005375 break;
Chad Rosier0f48c552012-10-19 20:57:14 +00005376 case AOK_SizeDirective:
David Majnemer8114c1a2014-06-23 02:17:16 +00005377 switch (AR.Val) {
Chad Rosier0f48c552012-10-19 20:57:14 +00005378 default: break;
5379 case 8: OS << "byte ptr "; break;
5380 case 16: OS << "word ptr "; break;
5381 case 32: OS << "dword ptr "; break;
5382 case 64: OS << "qword ptr "; break;
5383 case 80: OS << "xword ptr "; break;
5384 case 128: OS << "xmmword ptr "; break;
5385 case 256: OS << "ymmword ptr "; break;
5386 }
Eli Friedman0f4871d2012-10-22 23:58:19 +00005387 break;
5388 case AOK_Emit:
5389 OS << ".byte";
5390 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00005391 case AOK_Align: {
Reid Klecknerfb1c1c72015-10-27 17:32:48 +00005392 // MS alignment directives are measured in bytes. If the native assembler
5393 // measures alignment in bytes, we can pass it straight through.
5394 OS << ".align";
5395 if (getContext().getAsmInfo()->getAlignmentIsInBytes())
5396 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00005397
Reid Klecknerfb1c1c72015-10-27 17:32:48 +00005398 // Alignment is in log2 form, so print that instead and skip the original
5399 // immediate.
5400 unsigned Val = AR.Val;
5401 OS << ' ' << Val;
Benjamin Kramer1a136112013-02-15 20:37:21 +00005402 assert(Val < 10 && "Expected alignment less then 2^10.");
Chad Rosierc7f552c2013-02-12 21:33:51 +00005403 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
5404 break;
5405 }
Michael Zuckerman02ecd432015-12-13 17:07:23 +00005406 case AOK_EVEN:
5407 OS << ".even";
5408 break;
Chad Rosierf0e87202012-10-25 20:41:34 +00005409 case AOK_DotOperator:
Reid Kleckner94a1c4d2014-03-06 19:19:12 +00005410 // Insert the dot if the user omitted it.
Alp Tokere69170a2014-06-26 22:52:05 +00005411 OS.flush();
5412 if (AsmStringIR.back() != '.')
Reid Kleckner94a1c4d2014-03-06 19:19:12 +00005413 OS << '.';
David Majnemer8114c1a2014-06-23 02:17:16 +00005414 OS << AR.Val;
Chad Rosierf0e87202012-10-25 20:41:34 +00005415 break;
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00005416 case AOK_EndOfStatement:
5417 OS << "\n\t";
5418 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005419 }
Chad Rosier0f48c552012-10-19 20:57:14 +00005420
Chad Rosier8bce6642012-10-18 15:49:34 +00005421 // Skip the original expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00005422 AsmStart = Loc + AR.Len + AdditionalSkip;
Chad Rosier8bce6642012-10-18 15:49:34 +00005423 }
5424
5425 // Emit the remainder of the asm string.
Chad Rosier17d37992013-03-19 21:12:14 +00005426 if (AsmStart != AsmEnd)
5427 OS << StringRef(AsmStart, AsmEnd - AsmStart);
Chad Rosier8bce6642012-10-18 15:49:34 +00005428
5429 AsmString = OS.str();
5430 return false;
5431}
5432
Pete Cooper80d21cb2015-06-22 19:35:57 +00005433namespace llvm {
5434namespace MCParserUtils {
5435
5436/// Returns whether the given symbol is used anywhere in the given expression,
5437/// or subexpressions.
5438static bool isSymbolUsedInExpression(const MCSymbol *Sym, const MCExpr *Value) {
5439 switch (Value->getKind()) {
5440 case MCExpr::Binary: {
5441 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
5442 return isSymbolUsedInExpression(Sym, BE->getLHS()) ||
5443 isSymbolUsedInExpression(Sym, BE->getRHS());
5444 }
5445 case MCExpr::Target:
5446 case MCExpr::Constant:
5447 return false;
5448 case MCExpr::SymbolRef: {
5449 const MCSymbol &S =
5450 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
5451 if (S.isVariable())
5452 return isSymbolUsedInExpression(Sym, S.getVariableValue());
5453 return &S == Sym;
5454 }
5455 case MCExpr::Unary:
5456 return isSymbolUsedInExpression(
5457 Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
5458 }
5459
5460 llvm_unreachable("Unknown expr kind!");
5461}
5462
5463bool parseAssignmentExpression(StringRef Name, bool allow_redef,
5464 MCAsmParser &Parser, MCSymbol *&Sym,
5465 const MCExpr *&Value) {
Pete Cooper80d21cb2015-06-22 19:35:57 +00005466
5467 // FIXME: Use better location, we should use proper tokens.
Nirav Davefd910412016-06-17 16:06:17 +00005468 SMLoc EqualLoc = Parser.getTok().getLoc();
Pete Cooper80d21cb2015-06-22 19:35:57 +00005469
5470 if (Parser.parseExpression(Value)) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00005471 return Parser.TokError("missing expression");
Pete Cooper80d21cb2015-06-22 19:35:57 +00005472 }
5473
5474 // Note: we don't count b as used in "a = b". This is to allow
5475 // a = b
5476 // b = c
5477
Nirav Dave1a9044b2016-10-24 14:35:29 +00005478 if (Parser.parseToken(AsmToken::EndOfStatement))
5479 return true;
Pete Cooper80d21cb2015-06-22 19:35:57 +00005480
5481 // Validate that the LHS is allowed to be a variable (either it has not been
5482 // used as a symbol, or it is an absolute symbol).
5483 Sym = Parser.getContext().lookupSymbol(Name);
5484 if (Sym) {
5485 // Diagnose assignment to a label.
5486 //
5487 // FIXME: Diagnostics. Note the location of the definition as a label.
5488 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
5489 if (isSymbolUsedInExpression(Sym, Value))
5490 return Parser.Error(EqualLoc, "Recursive use of '" + Name + "'");
Vedant Kumar86dbd922015-08-31 17:44:53 +00005491 else if (Sym->isUndefined(/*SetUsed*/ false) && !Sym->isUsed() &&
5492 !Sym->isVariable())
Pete Cooper80d21cb2015-06-22 19:35:57 +00005493 ; // Allow redefinitions of undefined symbols only used in directives.
5494 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
5495 ; // Allow redefinitions of variables that haven't yet been used.
5496 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
5497 return Parser.Error(EqualLoc, "redefinition of '" + Name + "'");
5498 else if (!Sym->isVariable())
5499 return Parser.Error(EqualLoc, "invalid assignment to '" + Name + "'");
5500 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
5501 return Parser.Error(EqualLoc,
5502 "invalid reassignment of non-absolute variable '" +
5503 Name + "'");
Pete Cooper80d21cb2015-06-22 19:35:57 +00005504 } else if (Name == ".") {
Rafael Espindola7ae65d82015-11-04 23:59:18 +00005505 Parser.getStreamer().emitValueToOffset(Value, 0);
Pete Cooper80d21cb2015-06-22 19:35:57 +00005506 return false;
5507 } else
5508 Sym = Parser.getContext().getOrCreateSymbol(Name);
5509
5510 Sym->setRedefinable(allow_redef);
5511
5512 return false;
5513}
5514
Eugene Zelenko33d7b762016-08-23 17:14:32 +00005515} // end namespace MCParserUtils
5516} // end namespace llvm
Pete Cooper80d21cb2015-06-22 19:35:57 +00005517
Daniel Dunbar01e36072010-07-17 02:26:10 +00005518/// \brief Create an MCAsmParser instance.
Jim Grosbach4b905842013-09-20 23:08:21 +00005519MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
5520 MCStreamer &Out, const MCAsmInfo &MAI) {
Jim Grosbach345768c2011-08-16 18:33:49 +00005521 return new AsmParser(SM, C, Out, MAI);
Daniel Dunbar01e36072010-07-17 02:26:10 +00005522}