blob: f71e05107d7ac1e9fd5d27fb108972819e35b4d8 [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,
Sanne Wouda09adc242017-02-08 10:20:07 +0000212 const MCAsmInfo &MAI, unsigned CB);
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,
Sanne Wouda09adc242017-02-08 10:20:07 +0000575 const MCAsmInfo &MAI, unsigned CB = 0)
David Blaikie9f380a32015-03-16 18:06:57 +0000576 : Lexer(MAI), Ctx(Ctx), Out(Out), MAI(MAI), SrcMgr(SM),
Sanne Wouda09adc242017-02-08 10:20:07 +0000577 PlatformParser(nullptr), CurBuffer(CB ? CB : 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!");
Sanne Wouda09adc242017-02-08 10:20:07 +0000611
612 // Restore the saved diagnostics handler and context for use during
613 // finalization.
614 SrcMgr.setDiagHandler(SavedDiagHandler, SavedDiagContext);
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000615}
616
Jim Grosbach4b905842013-09-20 23:08:21 +0000617void AsmParser::printMacroInstantiations() {
Daniel Dunbar43235712010-07-18 18:54:11 +0000618 // Print the active macro instantiation stack.
Jim Grosbach4b905842013-09-20 23:08:21 +0000619 for (std::vector<MacroInstantiation *>::const_reverse_iterator
620 it = ActiveMacros.rbegin(),
621 ie = ActiveMacros.rend();
622 it != ie; ++it)
623 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
Chris Lattner03b80a42011-10-16 05:43:57 +0000624 "while in macro instantiation");
Daniel Dunbar43235712010-07-18 18:54:11 +0000625}
626
Nirav Dave2364748a2016-09-16 18:30:20 +0000627void AsmParser::Note(SMLoc L, const Twine &Msg, SMRange Range) {
628 printPendingErrors();
629 printMessage(L, SourceMgr::DK_Note, Msg, Range);
Saleem Abdulrasool69c7caf2014-01-07 02:28:31 +0000630 printMacroInstantiations();
631}
632
Nirav Dave2364748a2016-09-16 18:30:20 +0000633bool AsmParser::Warning(SMLoc L, const Twine &Msg, SMRange Range) {
Colin LeMahieufe36f832015-07-27 22:39:14 +0000634 if(getTargetParser().getTargetOptions().MCNoWarn)
635 return false;
Joerg Sonnenberger29815912014-08-26 18:39:50 +0000636 if (getTargetParser().getTargetOptions().MCFatalWarnings)
Nirav Dave2364748a2016-09-16 18:30:20 +0000637 return Error(L, Msg, Range);
638 printMessage(L, SourceMgr::DK_Warning, Msg, Range);
Jim Grosbach4b905842013-09-20 23:08:21 +0000639 printMacroInstantiations();
Joerg Sonnenberger74ba2622011-05-19 18:00:13 +0000640 return false;
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +0000641}
642
Nirav Dave2364748a2016-09-16 18:30:20 +0000643bool AsmParser::printError(SMLoc L, const Twine &Msg, SMRange Range) {
Daniel Dunbar43325c42010-09-09 22:42:56 +0000644 HadError = true;
Nirav Dave2364748a2016-09-16 18:30:20 +0000645 printMessage(L, SourceMgr::DK_Error, Msg, Range);
Jim Grosbach4b905842013-09-20 23:08:21 +0000646 printMacroInstantiations();
Chris Lattner2adc9e72009-06-21 21:22:11 +0000647 return true;
648}
649
Jim Grosbach4b905842013-09-20 23:08:21 +0000650bool AsmParser::enterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergeraf5f23e2011-06-01 13:10:15 +0000651 std::string IncludedFile;
Alp Tokera55b95b2014-07-06 10:33:31 +0000652 unsigned NewBuf =
653 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
654 if (!NewBuf)
Sean Callanan7a77eae2010-01-21 00:19:58 +0000655 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +0000656
Sean Callanan7a77eae2010-01-21 00:19:58 +0000657 CurBuffer = NewBuf;
Rafael Espindola8026bd02014-07-06 14:17:29 +0000658 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Sean Callanan7a77eae2010-01-21 00:19:58 +0000659 return false;
660}
Daniel Dunbar43235712010-07-18 18:54:11 +0000661
Sylvestre Ledru149e2812013-05-14 23:36:24 +0000662/// Process the specified .incbin file by searching for it in the include paths
Benjamin Kramerbde91762012-06-02 10:20:22 +0000663/// then just emitting the byte contents of the file to the streamer. This
Kevin Enderby109f25c2011-12-14 21:47:48 +0000664/// returns true on failure.
Petr Hosek2f4ac442016-09-23 00:41:06 +0000665bool AsmParser::processIncbinFile(const std::string &Filename, int64_t Skip,
666 const MCExpr *Count, SMLoc Loc) {
Kevin Enderby109f25c2011-12-14 21:47:48 +0000667 std::string IncludedFile;
Alp Tokera55b95b2014-07-06 10:33:31 +0000668 unsigned NewBuf =
669 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
670 if (!NewBuf)
Kevin Enderby109f25c2011-12-14 21:47:48 +0000671 return true;
672
Kevin Enderbyad41ab52011-12-14 22:34:45 +0000673 // Pick up the bytes from the file and emit them.
Petr Hosek2f4ac442016-09-23 00:41:06 +0000674 StringRef Bytes = SrcMgr.getMemoryBuffer(NewBuf)->getBuffer();
675 Bytes = Bytes.drop_front(Skip);
676 if (Count) {
677 int64_t Res;
678 if (!Count->evaluateAsAbsolute(Res))
679 return Error(Loc, "expected absolute expression");
680 if (Res < 0)
681 return Warning(Loc, "negative count has no effect");
682 Bytes = Bytes.take_front(Res);
683 }
684 getStreamer().EmitBytes(Bytes);
Kevin Enderby109f25c2011-12-14 21:47:48 +0000685 return false;
686}
687
Alp Tokera55b95b2014-07-06 10:33:31 +0000688void AsmParser::jumpToLoc(SMLoc Loc, unsigned InBuffer) {
689 CurBuffer = InBuffer ? InBuffer : SrcMgr.FindBufferContainingLoc(Loc);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000690 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(),
691 Loc.getPointer());
Daniel Dunbar43235712010-07-18 18:54:11 +0000692}
693
Sean Callanan7a77eae2010-01-21 00:19:58 +0000694const AsmToken &AsmParser::Lex() {
Nirav Dave1180e6892016-06-02 17:15:05 +0000695 if (Lexer.getTok().is(AsmToken::Error))
696 Error(Lexer.getErrLoc(), Lexer.getErr());
697
Nirav Dave53a72f42016-07-11 12:42:14 +0000698 // if it's a end of statement with a comment in it
699 if (getTok().is(AsmToken::EndOfStatement)) {
700 // if this is a line comment output it.
701 if (getTok().getString().front() != '\n' &&
702 getTok().getString().front() != '\r' && MAI.preserveAsmComments())
703 Out.addExplicitComment(Twine(getTok().getString()));
704 }
705
Sean Callanan7a77eae2010-01-21 00:19:58 +0000706 const AsmToken *tok = &Lexer.Lex();
Nirav Dave53a72f42016-07-11 12:42:14 +0000707
708 // Parse comments here to be deferred until end of next statement.
Nirav Davefd910412016-06-17 16:06:17 +0000709 while (tok->is(AsmToken::Comment)) {
Nirav Dave53a72f42016-07-11 12:42:14 +0000710 if (MAI.preserveAsmComments())
711 Out.addExplicitComment(Twine(tok->getString()));
Nirav Davefd910412016-06-17 16:06:17 +0000712 tok = &Lexer.Lex();
713 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000714
Sean Callanan7a77eae2010-01-21 00:19:58 +0000715 if (tok->is(AsmToken::Eof)) {
716 // If this is the end of an included file, pop the parent file off the
717 // include stack.
718 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
719 if (ParentIncludeLoc != SMLoc()) {
Jim Grosbach4b905842013-09-20 23:08:21 +0000720 jumpToLoc(ParentIncludeLoc);
Nirav Davefd910412016-06-17 16:06:17 +0000721 return Lex();
Sean Callanan7a77eae2010-01-21 00:19:58 +0000722 }
723 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000724
Sean Callanan7a77eae2010-01-21 00:19:58 +0000725 return *tok;
Sean Callanan686ed8d2010-01-19 20:22:31 +0000726}
727
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000728bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar322fec62010-03-13 02:20:57 +0000729 // Create the initial section, if requested.
Daniel Dunbar322fec62010-03-13 02:20:57 +0000730 if (!NoInitialTextSection)
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000731 Out.InitSections(false);
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000732
Chris Lattner36e02122009-06-21 20:54:55 +0000733 // Prime the lexer.
Sean Callanan686ed8d2010-01-19 20:22:31 +0000734 Lex();
Daniel Dunbar43325c42010-09-09 22:42:56 +0000735
736 HadError = false;
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000737 AsmCond StartingCondState = TheCondState;
738
Kevin Enderby6469fc22011-11-01 22:27:22 +0000739 // If we are generating dwarf for assembly source files save the initial text
740 // section and generate a .file directive.
741 if (getContext().getGenDwarfForAssembly()) {
Eric Christopher445c9522016-10-14 05:47:37 +0000742 MCSection *Sec = getStreamer().getCurrentSectionOnly();
Rafael Espindola2f9bdd82015-05-27 20:52:32 +0000743 if (!Sec->getBeginSymbol()) {
744 MCSymbol *SectionStartSym = getContext().createTempSymbol();
745 getStreamer().EmitLabel(SectionStartSym);
746 Sec->setBeginSymbol(SectionStartSym);
747 }
Rafael Espindolae0746792015-05-21 16:52:32 +0000748 bool InsertResult = getContext().addGenDwarfSection(Sec);
749 assert(InsertResult && ".text section should not have debug info yet");
Rafael Espindolafa160c72015-05-21 17:09:22 +0000750 (void)InsertResult;
David Blaikiec714ef42014-03-17 01:52:11 +0000751 getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective(
752 0, StringRef(), getContext().getMainFileName()));
Kevin Enderby6469fc22011-11-01 22:27:22 +0000753 }
754
Chris Lattner73f36112009-07-02 21:53:43 +0000755 // While we have input, parse each statement.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000756 while (Lexer.isNot(AsmToken::Eof)) {
Eli Friedman0f4871d2012-10-22 23:58:19 +0000757 ParseStatementInfo Info;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +0000758 if (!parseStatement(Info, nullptr))
Jim Grosbach4b905842013-09-20 23:08:21 +0000759 continue;
Michael J. Spencer530ce852010-10-09 11:00:50 +0000760
Nirav Dave2364748a2016-09-16 18:30:20 +0000761 // If we have a Lexer Error we are on an Error Token. Load in Lexer Error
762 // for printing ErrMsg via Lex() only if no (presumably better) parser error
763 // exists.
764 if (!hasPendingError() && Lexer.getTok().is(AsmToken::Error)) {
Nirav Dave1180e6892016-06-02 17:15:05 +0000765 Lex();
766 }
767
Nirav Dave2364748a2016-09-16 18:30:20 +0000768 // parseStatement returned true so may need to emit an error.
769 printPendingErrors();
770
771 // Skipping to the next line if needed.
772 if (!getLexer().isAtStartOfStatement())
773 eatToEndOfStatement();
Chris Lattner73f36112009-07-02 21:53:43 +0000774 }
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000775
Nirav Dave2364748a2016-09-16 18:30:20 +0000776 // All errors should have been emitted.
777 assert(!hasPendingError() && "unexpected error from parseStatement");
778
Oliver Stannard21718282016-07-26 14:19:47 +0000779 getTargetParser().flushPendingInstructions(getStreamer());
780
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000781 if (TheCondState.TheCond != StartingCondState.TheCond ||
782 TheCondState.Ignore != StartingCondState.Ignore)
Nirav Dave2364748a2016-09-16 18:30:20 +0000783 printError(getTok().getLoc(), "unmatched .ifs or .elses");
Kevin Enderbye5930f12010-07-28 20:55:35 +0000784 // Check to see there are no empty DwarfFile slots.
David Blaikie8bf66c42014-04-01 07:35:52 +0000785 const auto &LineTables = getContext().getMCDwarfLineTables();
786 if (!LineTables.empty()) {
787 unsigned Index = 0;
788 for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) {
789 if (File.Name.empty() && Index != 0)
Nirav Dave2364748a2016-09-16 18:30:20 +0000790 printError(getTok().getLoc(), "unassigned file number: " +
791 Twine(Index) +
792 " for .file directives");
David Blaikie8bf66c42014-04-01 07:35:52 +0000793 ++Index;
794 }
Kevin Enderbye5930f12010-07-28 20:55:35 +0000795 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000796
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000797 // Check to see that all assembler local symbols were actually defined.
798 // Targets that don't do subsections via symbols may not want this, though,
799 // so conservatively exclude them. Only do this if we're finalizing, though,
800 // as otherwise we won't necessarilly have seen everything yet.
Tim Northover6b3169b2016-04-11 19:50:46 +0000801 if (!NoFinalize) {
802 if (MAI.hasSubsectionsViaSymbols()) {
803 for (const auto &TableEntry : getContext().getSymbols()) {
804 MCSymbol *Sym = TableEntry.getValue();
805 // Variable symbols may not be marked as defined, so check those
806 // explicitly. If we know it's a variable, we have a definition for
807 // the purposes of this check.
808 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
809 // FIXME: We would really like to refer back to where the symbol was
810 // first referenced for a source location. We need to add something
811 // to track that. Currently, we just point to the end of the file.
Nirav Dave2364748a2016-09-16 18:30:20 +0000812 printError(getTok().getLoc(), "assembler local symbol '" +
813 Sym->getName() + "' not defined");
Tim Northover6b3169b2016-04-11 19:50:46 +0000814 }
815 }
816
817 // Temporary symbols like the ones for directional jumps don't go in the
818 // symbol table. They also need to be diagnosed in all (final) cases.
Tim Northoverc0bef992016-04-13 19:46:54 +0000819 for (std::tuple<SMLoc, CppHashInfoTy, MCSymbol *> &LocSym : DirLabels) {
820 if (std::get<2>(LocSym)->isUndefined()) {
821 // Reset the state of any "# line file" directives we've seen to the
822 // context as it was at the diagnostic site.
823 CppHashInfo = std::get<1>(LocSym);
Nirav Dave2364748a2016-09-16 18:30:20 +0000824 printError(std::get<0>(LocSym), "directional label undefined");
Tim Northoverc0bef992016-04-13 19:46:54 +0000825 }
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000826 }
827 }
828
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000829 // Finalize the output stream if there are no errors and if the client wants
830 // us to.
Jack Carter13d5f752013-10-04 22:52:31 +0000831 if (!HadError && !NoFinalize)
Daniel Dunbar9df5f332009-08-21 08:34:18 +0000832 Out.Finish();
833
Oliver Stannard07b43d32015-11-17 09:58:07 +0000834 return HadError || getContext().hadError();
Chris Lattner36e02122009-06-21 20:54:55 +0000835}
836
Nirav Davef43cc9f2016-10-10 15:24:54 +0000837bool AsmParser::checkForValidSection() {
Eric Christopher445c9522016-10-14 05:47:37 +0000838 if (!ParsingInlineAsm && !getStreamer().getCurrentSectionOnly()) {
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000839 Out.InitSections(false);
Nirav Davef43cc9f2016-10-10 15:24:54 +0000840 return Error(getTok().getLoc(),
841 "expected section directive before assembly directive");
Daniel Dunbare5444a82010-09-09 22:42:59 +0000842 }
Nirav Davef43cc9f2016-10-10 15:24:54 +0000843 return false;
Daniel Dunbare5444a82010-09-09 22:42:59 +0000844}
845
Jim Grosbach4b905842013-09-20 23:08:21 +0000846/// \brief Throw away the rest of the line for testing purposes.
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000847void AsmParser::eatToEndOfStatement() {
Jim Grosbach4b905842013-09-20 23:08:21 +0000848 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Nirav Dave1180e6892016-06-02 17:15:05 +0000849 Lexer.Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +0000850
Chris Lattnere5074c42009-06-22 01:29:09 +0000851 // Eat EOL.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000852 if (Lexer.is(AsmToken::EndOfStatement))
Nirav Dave1180e6892016-06-02 17:15:05 +0000853 Lexer.Lex();
Chris Lattnere5074c42009-06-22 01:29:09 +0000854}
855
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000856StringRef AsmParser::parseStringToEndOfStatement() {
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000857 const char *Start = getTok().getLoc().getPointer();
858
Jim Grosbach4b905842013-09-20 23:08:21 +0000859 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Nirav Davefd910412016-06-17 16:06:17 +0000860 Lexer.Lex();
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000861
862 const char *End = getTok().getLoc().getPointer();
863 return StringRef(Start, End - Start);
864}
Chris Lattner78db3622009-06-22 05:51:26 +0000865
Jim Grosbach4b905842013-09-20 23:08:21 +0000866StringRef AsmParser::parseStringToComma() {
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000867 const char *Start = getTok().getLoc().getPointer();
868
869 while (Lexer.isNot(AsmToken::EndOfStatement) &&
Jim Grosbach4b905842013-09-20 23:08:21 +0000870 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
Nirav Davefd910412016-06-17 16:06:17 +0000871 Lexer.Lex();
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000872
873 const char *End = getTok().getLoc().getPointer();
874 return StringRef(Start, End - Start);
875}
876
Jim Grosbach4b905842013-09-20 23:08:21 +0000877/// \brief Parse a paren expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +0000878/// NOTE: This assumes the leading '(' has already been consumed.
879///
880/// parenexpr ::= expr)
881///
Jim Grosbach4b905842013-09-20 23:08:21 +0000882bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
883 if (parseExpression(Res))
884 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000885 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner7fdbce72009-06-22 06:32:03 +0000886 return TokError("expected ')' in parentheses expression");
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000887 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +0000888 Lex();
Chris Lattner7fdbce72009-06-22 06:32:03 +0000889 return false;
890}
Chris Lattner78db3622009-06-22 05:51:26 +0000891
Jim Grosbach4b905842013-09-20 23:08:21 +0000892/// \brief Parse a bracket expression and return it.
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +0000893/// NOTE: This assumes the leading '[' has already been consumed.
894///
895/// bracketexpr ::= expr]
896///
Jim Grosbach4b905842013-09-20 23:08:21 +0000897bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
898 if (parseExpression(Res))
899 return true;
Nirav Davea645433c2016-07-18 15:24:03 +0000900 EndLoc = getTok().getEndLoc();
901 if (parseToken(AsmToken::RBrac, "expected ']' in brackets expression"))
902 return true;
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +0000903 return false;
904}
905
Jim Grosbach4b905842013-09-20 23:08:21 +0000906/// \brief Parse a primary expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +0000907/// primaryexpr ::= (parenexpr
908/// primaryexpr ::= symbol
909/// primaryexpr ::= number
Chris Lattner6b55cb92010-04-14 04:40:28 +0000910/// primaryexpr ::= '.'
Chris Lattner7fdbce72009-06-22 06:32:03 +0000911/// primaryexpr ::= ~,+,- primaryexpr
Jim Grosbach4b905842013-09-20 23:08:21 +0000912bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Kevin Enderby0017d8a2013-01-22 21:09:20 +0000913 SMLoc FirstTokenLoc = getLexer().getLoc();
914 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
915 switch (FirstTokenKind) {
Chris Lattner78db3622009-06-22 05:51:26 +0000916 default:
917 return TokError("unknown token in expression");
Eric Christopher104af062011-04-12 00:03:13 +0000918 // If we have an error assume that we've already handled it.
919 case AsmToken::Error:
920 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000921 case AsmToken::Exclaim:
Sean Callanan686ed8d2010-01-19 20:22:31 +0000922 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +0000923 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000924 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +0000925 Res = MCUnaryExpr::createLNot(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000926 return false;
Daniel Dunbar24764322010-08-24 19:13:42 +0000927 case AsmToken::Dollar:
Hans Wennborgce69d772013-10-18 20:46:28 +0000928 case AsmToken::At:
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +0000929 case AsmToken::String:
Daniel Dunbard20cda02009-10-16 01:34:54 +0000930 case AsmToken::Identifier: {
Daniel Dunbar24764322010-08-24 19:13:42 +0000931 StringRef Identifier;
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000932 if (parseIdentifier(Identifier)) {
Nirav Daved0463322016-10-12 13:58:07 +0000933 // We may have failed but $ may be a valid token.
934 if (getTok().is(AsmToken::Dollar)) {
David Majnemer0c58bc62013-09-25 10:47:21 +0000935 if (Lexer.getMAI().getDollarIsPC()) {
Nirav Daved0463322016-10-12 13:58:07 +0000936 Lex();
David Majnemer0c58bc62013-09-25 10:47:21 +0000937 // This is a '$' reference, which references the current PC. Emit a
938 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +0000939 MCSymbol *Sym = Ctx.createTempSymbol();
David Majnemer0c58bc62013-09-25 10:47:21 +0000940 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +0000941 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None,
Jack Carter721726a2013-10-04 21:26:15 +0000942 getContext());
David Majnemer0c58bc62013-09-25 10:47:21 +0000943 EndLoc = FirstTokenLoc;
944 return false;
Ted Kremenek297febe2014-03-06 22:13:17 +0000945 }
946 return Error(FirstTokenLoc, "invalid token in expression");
David Majnemer0c58bc62013-09-25 10:47:21 +0000947 }
Kevin Enderby0017d8a2013-01-22 21:09:20 +0000948 }
David Peixotto8ad70b32013-12-04 22:43:20 +0000949 // Parse symbol variant
950 std::pair<StringRef, StringRef> Split;
951 if (!MAI.useParensForSymbolVariant()) {
David Majnemer6a5b8122014-06-19 01:25:43 +0000952 if (FirstTokenKind == AsmToken::String) {
953 if (Lexer.is(AsmToken::At)) {
Nirav Davefd910412016-06-17 16:06:17 +0000954 Lex(); // eat @
David Majnemer6a5b8122014-06-19 01:25:43 +0000955 SMLoc AtLoc = getLexer().getLoc();
956 StringRef VName;
957 if (parseIdentifier(VName))
958 return Error(AtLoc, "expected symbol variant after '@'");
959
960 Split = std::make_pair(Identifier, VName);
961 }
962 } else {
963 Split = Identifier.split('@');
964 }
David Peixotto8ad70b32013-12-04 22:43:20 +0000965 } else if (Lexer.is(AsmToken::LParen)) {
Nirav Davefd910412016-06-17 16:06:17 +0000966 Lex(); // eat '('.
David Peixotto8ad70b32013-12-04 22:43:20 +0000967 StringRef VName;
968 parseIdentifier(VName);
Nirav Davea645433c2016-07-18 15:24:03 +0000969 // eat ')'.
970 if (parseToken(AsmToken::RParen,
971 "unexpected token in variant, expected ')'"))
972 return true;
David Peixotto8ad70b32013-12-04 22:43:20 +0000973 Split = std::make_pair(Identifier, VName);
974 }
Daniel Dunbar24764322010-08-24 19:13:42 +0000975
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000976 EndLoc = SMLoc::getFromPointer(Identifier.end());
977
Daniel Dunbard20cda02009-10-16 01:34:54 +0000978 // This is a symbol reference.
Hans Wennborgce69d772013-10-18 20:46:28 +0000979 StringRef SymbolName = Identifier;
Weiming Zhaocf26d562016-12-01 18:00:36 +0000980 if (SymbolName.empty())
981 return true;
982
Hans Wennborgce69d772013-10-18 20:46:28 +0000983 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Hans Wennborg69918bc2013-10-17 01:13:02 +0000984
Hans Wennborg7ddcdc82013-10-18 02:14:40 +0000985 // Lookup the symbol variant if used.
David Peixotto8ad70b32013-12-04 22:43:20 +0000986 if (Split.second.size()) {
Hans Wennborg7ddcdc82013-10-18 02:14:40 +0000987 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Hans Wennborgce69d772013-10-18 20:46:28 +0000988 if (Variant != MCSymbolRefExpr::VK_Invalid) {
989 SymbolName = Split.first;
David Peixotto8ad70b32013-12-04 22:43:20 +0000990 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
Hans Wennborgce69d772013-10-18 20:46:28 +0000991 Variant = MCSymbolRefExpr::VK_None;
992 } else {
Saleem Abdulrasoola25e1e42014-01-26 22:29:43 +0000993 return Error(SMLoc::getFromPointer(Split.second.begin()),
994 "invalid variant '" + Split.second + "'");
Daniel Dunbar55f16672010-09-17 02:47:07 +0000995 }
996 }
Daniel Dunbar55992562010-03-15 23:51:06 +0000997
Jim Grosbach6f482002015-05-18 18:43:14 +0000998 MCSymbol *Sym = getContext().getOrCreateSymbol(SymbolName);
Hans Wennborgce69d772013-10-18 20:46:28 +0000999
Daniel Dunbard20cda02009-10-16 01:34:54 +00001000 // If this is an absolute variable reference, substitute it now to preserve
1001 // semantics in the face of reassignment.
Vedant Kumar86dbd922015-08-31 17:44:53 +00001002 if (Sym->isVariable() &&
1003 isa<MCConstantExpr>(Sym->getVariableValue(/*SetUsed*/ false))) {
Daniel Dunbar55992562010-03-15 23:51:06 +00001004 if (Variant)
Daniel Dunbar8a3c3f22010-11-08 17:53:02 +00001005 return Error(EndLoc, "unexpected modifier on variable reference");
Daniel Dunbar55992562010-03-15 23:51:06 +00001006
Vedant Kumar86dbd922015-08-31 17:44:53 +00001007 Res = Sym->getVariableValue(/*SetUsed*/ false);
Daniel Dunbard20cda02009-10-16 01:34:54 +00001008 return false;
1009 }
1010
1011 // Otherwise create a symbol ref.
Chad Rosier9245e122017-01-19 20:06:32 +00001012 Res = MCSymbolRefExpr::create(Sym, Variant, getContext(), FirstTokenLoc);
Chris Lattner78db3622009-06-22 05:51:26 +00001013 return false;
Daniel Dunbard20cda02009-10-16 01:34:54 +00001014 }
David Woodhousef42a6662014-02-01 16:20:54 +00001015 case AsmToken::BigNum:
1016 return TokError("literal value out of range for directive");
Kevin Enderby0510b482010-05-17 23:08:19 +00001017 case AsmToken::Integer: {
1018 SMLoc Loc = getTok().getLoc();
1019 int64_t IntVal = getTok().getIntVal();
Jim Grosbach13760bd2015-05-30 01:25:56 +00001020 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001021 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001022 Lex(); // Eat token.
Kevin Enderby0510b482010-05-17 23:08:19 +00001023 // Look for 'b' or 'f' following an Integer as a directional label
1024 if (Lexer.getKind() == AsmToken::Identifier) {
1025 StringRef IDVal = getTok().getString();
Ulrich Weigandd4120982013-06-20 16:24:17 +00001026 // Lookup the symbol variant if used.
1027 std::pair<StringRef, StringRef> Split = IDVal.split('@');
1028 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
1029 if (Split.first.size() != IDVal.size()) {
1030 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Arnaud A. de Grandmaisonc97727a2014-03-21 21:54:46 +00001031 if (Variant == MCSymbolRefExpr::VK_Invalid)
Ulrich Weigandd4120982013-06-20 16:24:17 +00001032 return TokError("invalid variant '" + Split.second + "'");
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001033 IDVal = Split.first;
Ulrich Weigandd4120982013-06-20 16:24:17 +00001034 }
Jim Grosbach4b905842013-09-20 23:08:21 +00001035 if (IDVal == "f" || IDVal == "b") {
1036 MCSymbol *Sym =
Jim Grosbach6f482002015-05-18 18:43:14 +00001037 Ctx.getDirectionalLocalSymbol(IntVal, IDVal == "b");
Jim Grosbach13760bd2015-05-30 01:25:56 +00001038 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00001039 if (IDVal == "b" && Sym->isUndefined())
Tim Northover6b3169b2016-04-11 19:50:46 +00001040 return Error(Loc, "directional label undefined");
Tim Northoverc0bef992016-04-13 19:46:54 +00001041 DirLabels.push_back(std::make_tuple(Loc, CppHashInfo, Sym));
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001042 EndLoc = Lexer.getTok().getEndLoc();
Kevin Enderby0510b482010-05-17 23:08:19 +00001043 Lex(); // Eat identifier.
1044 }
1045 }
Chris Lattner78db3622009-06-22 05:51:26 +00001046 return false;
Kevin Enderby0510b482010-05-17 23:08:19 +00001047 }
Bill Wendlingcdbf17b2011-01-25 21:26:41 +00001048 case AsmToken::Real: {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001049 APFloat RealVal(APFloat::IEEEdouble(), getTok().getString());
Bob Wilson813bdf62011-02-03 23:17:47 +00001050 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Jim Grosbach13760bd2015-05-30 01:25:56 +00001051 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001052 EndLoc = Lexer.getTok().getEndLoc();
Bill Wendlingcdbf17b2011-01-25 21:26:41 +00001053 Lex(); // Eat token.
1054 return false;
1055 }
Chris Lattner6b55cb92010-04-14 04:40:28 +00001056 case AsmToken::Dot: {
1057 // This is a '.' reference, which references the current PC. Emit a
1058 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +00001059 MCSymbol *Sym = Ctx.createTempSymbol();
Chris Lattner6b55cb92010-04-14 04:40:28 +00001060 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +00001061 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001062 EndLoc = Lexer.getTok().getEndLoc();
Chris Lattner6b55cb92010-04-14 04:40:28 +00001063 Lex(); // Eat identifier.
1064 return false;
1065 }
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001066 case AsmToken::LParen:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001067 Lex(); // Eat the '('.
Jim Grosbach4b905842013-09-20 23:08:21 +00001068 return parseParenExpr(Res, EndLoc);
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +00001069 case AsmToken::LBrac:
1070 if (!PlatformParser->HasBracketExpressions())
1071 return TokError("brackets expression not supported on this target");
1072 Lex(); // Eat the '['.
Jim Grosbach4b905842013-09-20 23:08:21 +00001073 return parseBracketExpr(Res, EndLoc);
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001074 case AsmToken::Minus:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001075 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001076 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001077 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001078 Res = MCUnaryExpr::createMinus(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001079 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001080 case AsmToken::Plus:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001081 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001082 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001083 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001084 Res = MCUnaryExpr::createPlus(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001085 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001086 case AsmToken::Tilde:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001087 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001088 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001089 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001090 Res = MCUnaryExpr::createNot(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001091 return false;
Daniel Sanders3feeb9c2016-08-08 11:50:25 +00001092 // MIPS unary expression operators. The lexer won't generate these tokens if
1093 // MCAsmInfo::HasMipsExpressions is false for the target.
1094 case AsmToken::PercentCall16:
1095 case AsmToken::PercentCall_Hi:
1096 case AsmToken::PercentCall_Lo:
1097 case AsmToken::PercentDtprel_Hi:
1098 case AsmToken::PercentDtprel_Lo:
1099 case AsmToken::PercentGot:
1100 case AsmToken::PercentGot_Disp:
1101 case AsmToken::PercentGot_Hi:
1102 case AsmToken::PercentGot_Lo:
1103 case AsmToken::PercentGot_Ofst:
1104 case AsmToken::PercentGot_Page:
1105 case AsmToken::PercentGottprel:
1106 case AsmToken::PercentGp_Rel:
1107 case AsmToken::PercentHi:
1108 case AsmToken::PercentHigher:
1109 case AsmToken::PercentHighest:
1110 case AsmToken::PercentLo:
1111 case AsmToken::PercentNeg:
1112 case AsmToken::PercentPcrel_Hi:
1113 case AsmToken::PercentPcrel_Lo:
1114 case AsmToken::PercentTlsgd:
1115 case AsmToken::PercentTlsldm:
1116 case AsmToken::PercentTprel_Hi:
1117 case AsmToken::PercentTprel_Lo:
1118 Lex(); // Eat the operator.
1119 if (Lexer.isNot(AsmToken::LParen))
1120 return TokError("expected '(' after operator");
1121 Lex(); // Eat the operator.
1122 if (parseExpression(Res, EndLoc))
1123 return true;
1124 if (Lexer.isNot(AsmToken::RParen))
1125 return TokError("expected ')'");
1126 Lex(); // Eat the operator.
1127 Res = getTargetParser().createTargetUnaryExpr(Res, FirstTokenKind, Ctx);
1128 return !Res;
Chris Lattner78db3622009-06-22 05:51:26 +00001129 }
1130}
Chris Lattner7fdbce72009-06-22 06:32:03 +00001131
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001132bool AsmParser::parseExpression(const MCExpr *&Res) {
Chris Lattnere17df0b2010-01-15 19:39:23 +00001133 SMLoc EndLoc;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001134 return parseExpression(Res, EndLoc);
Chris Lattner528d00b2010-01-15 19:28:38 +00001135}
1136
Daniel Dunbar55f16672010-09-17 02:47:07 +00001137const MCExpr *
Jim Grosbach4b905842013-09-20 23:08:21 +00001138AsmParser::applyModifierToExpr(const MCExpr *E,
Daniel Dunbar55f16672010-09-17 02:47:07 +00001139 MCSymbolRefExpr::VariantKind Variant) {
Joerg Sonnenbergerb822af42013-08-27 20:23:19 +00001140 // Ask the target implementation about this expression first.
1141 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
1142 if (NewE)
1143 return NewE;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001144 // Recurse over the given expression, rebuilding it to apply the given variant
1145 // if there is exactly one symbol.
1146 switch (E->getKind()) {
1147 case MCExpr::Target:
1148 case MCExpr::Constant:
Craig Topper353eda42014-04-24 06:44:33 +00001149 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001150
1151 case MCExpr::SymbolRef: {
1152 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
1153
1154 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001155 TokError("invalid variant on expression '" + getTok().getIdentifier() +
1156 "' (already modified)");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001157 return E;
1158 }
1159
Jim Grosbach13760bd2015-05-30 01:25:56 +00001160 return MCSymbolRefExpr::create(&SRE->getSymbol(), Variant, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001161 }
1162
1163 case MCExpr::Unary: {
1164 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +00001165 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001166 if (!Sub)
Craig Topper353eda42014-04-24 06:44:33 +00001167 return nullptr;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001168 return MCUnaryExpr::create(UE->getOpcode(), Sub, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001169 }
1170
1171 case MCExpr::Binary: {
1172 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +00001173 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
1174 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001175
1176 if (!LHS && !RHS)
Craig Topper353eda42014-04-24 06:44:33 +00001177 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001178
Jim Grosbach4b905842013-09-20 23:08:21 +00001179 if (!LHS)
1180 LHS = BE->getLHS();
1181 if (!RHS)
1182 RHS = BE->getRHS();
Daniel Dunbar55f16672010-09-17 02:47:07 +00001183
Jim Grosbach13760bd2015-05-30 01:25:56 +00001184 return MCBinaryExpr::create(BE->getOpcode(), LHS, RHS, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001185 }
1186 }
Daniel Dunbarbaad46c2010-09-17 16:34:24 +00001187
Craig Toppera2886c22012-02-07 05:05:23 +00001188 llvm_unreachable("Invalid expression kind!");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001189}
1190
Jim Grosbach4b905842013-09-20 23:08:21 +00001191/// \brief Parse an expression and return it.
Michael J. Spencer530ce852010-10-09 11:00:50 +00001192///
Jim Grosbachbd164242011-08-20 16:24:13 +00001193/// expr ::= expr &&,|| expr -> lowest.
1194/// expr ::= expr |,^,&,! expr
1195/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1196/// expr ::= expr <<,>> expr
1197/// expr ::= expr +,- expr
1198/// expr ::= expr *,/,% expr -> highest.
Chris Lattner7fdbce72009-06-22 06:32:03 +00001199/// expr ::= primaryexpr
1200///
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001201bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001202 // Parse the expression.
Craig Topper353eda42014-04-24 06:44:33 +00001203 Res = nullptr;
Jim Grosbach4b905842013-09-20 23:08:21 +00001204 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001205 return true;
1206
Daniel Dunbar55f16672010-09-17 02:47:07 +00001207 // As a special case, we support 'a op b @ modifier' by rewriting the
1208 // expression to include the modifier. This is inefficient, but in general we
1209 // expect users to use 'a@modifier op b'.
1210 if (Lexer.getKind() == AsmToken::At) {
1211 Lex();
1212
1213 if (Lexer.isNot(AsmToken::Identifier))
1214 return TokError("unexpected symbol modifier following '@'");
1215
1216 MCSymbolRefExpr::VariantKind Variant =
Jim Grosbach4b905842013-09-20 23:08:21 +00001217 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001218 if (Variant == MCSymbolRefExpr::VK_Invalid)
1219 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1220
Jim Grosbach4b905842013-09-20 23:08:21 +00001221 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001222 if (!ModifiedRes) {
1223 return TokError("invalid modifier '" + getTok().getIdentifier() +
1224 "' (no symbols present)");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001225 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001226
Daniel Dunbar55f16672010-09-17 02:47:07 +00001227 Res = ModifiedRes;
1228 Lex();
1229 }
1230
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001231 // Try to constant fold it up front, if possible.
1232 int64_t Value;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001233 if (Res->evaluateAsAbsolute(Value))
1234 Res = MCConstantExpr::create(Value, getContext());
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001235
1236 return false;
Chris Lattner7fdbce72009-06-22 06:32:03 +00001237}
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001238
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001239bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Craig Topper353eda42014-04-24 06:44:33 +00001240 Res = nullptr;
Jim Grosbach4b905842013-09-20 23:08:21 +00001241 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
Daniel Dunbar7c82d562009-08-31 08:08:17 +00001242}
1243
Toma Tabacu7bc44dc2015-06-25 09:52:02 +00001244bool AsmParser::parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
1245 SMLoc &EndLoc) {
1246 if (parseParenExpr(Res, EndLoc))
1247 return true;
1248
1249 for (; ParenDepth > 0; --ParenDepth) {
1250 if (parseBinOpRHS(1, Res, EndLoc))
1251 return true;
1252
1253 // We don't Lex() the last RParen.
1254 // This is the same behavior as parseParenExpression().
1255 if (ParenDepth - 1 > 0) {
Nirav Davea645433c2016-07-18 15:24:03 +00001256 EndLoc = getTok().getEndLoc();
1257 if (parseToken(AsmToken::RParen,
1258 "expected ')' in parentheses expression"))
1259 return true;
Toma Tabacu7bc44dc2015-06-25 09:52:02 +00001260 }
1261 }
1262 return false;
1263}
1264
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001265bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
Daniel Dunbarf3636452009-08-31 08:07:22 +00001266 const MCExpr *Expr;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001267
Daniel Dunbar75630b32009-06-30 02:10:03 +00001268 SMLoc StartLoc = Lexer.getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001269 if (parseExpression(Expr))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001270 return true;
1271
Jim Grosbach13760bd2015-05-30 01:25:56 +00001272 if (!Expr->evaluateAsAbsolute(Res))
Daniel Dunbar75630b32009-06-30 02:10:03 +00001273 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001274
1275 return false;
1276}
1277
David Majnemer0993e0b2015-10-26 03:15:34 +00001278static unsigned getDarwinBinOpPrecedence(AsmToken::TokenKind K,
1279 MCBinaryExpr::Opcode &Kind,
1280 bool ShouldUseLogicalShr) {
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001281 switch (K) {
Daniel Dunbar940cda22009-08-31 08:07:44 +00001282 default:
Jim Grosbach4b905842013-09-20 23:08:21 +00001283 return 0; // not a binop.
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001284
Jim Grosbach4b905842013-09-20 23:08:21 +00001285 // Lowest Precedence: &&, ||
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001286 case AsmToken::AmpAmp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001287 Kind = MCBinaryExpr::LAnd;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001288 return 1;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001289 case AsmToken::PipePipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001290 Kind = MCBinaryExpr::LOr;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001291 return 1;
1292
Jim Grosbach4b905842013-09-20 23:08:21 +00001293 // Low Precedence: |, &, ^
1294 //
1295 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001296 case AsmToken::Pipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001297 Kind = MCBinaryExpr::Or;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001298 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001299 case AsmToken::Caret:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001300 Kind = MCBinaryExpr::Xor;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001301 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001302 case AsmToken::Amp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001303 Kind = MCBinaryExpr::And;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001304 return 2;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001305
Jim Grosbach4b905842013-09-20 23:08:21 +00001306 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001307 case AsmToken::EqualEqual:
1308 Kind = MCBinaryExpr::EQ;
1309 return 3;
1310 case AsmToken::ExclaimEqual:
1311 case AsmToken::LessGreater:
1312 Kind = MCBinaryExpr::NE;
1313 return 3;
1314 case AsmToken::Less:
1315 Kind = MCBinaryExpr::LT;
1316 return 3;
1317 case AsmToken::LessEqual:
1318 Kind = MCBinaryExpr::LTE;
1319 return 3;
1320 case AsmToken::Greater:
1321 Kind = MCBinaryExpr::GT;
1322 return 3;
1323 case AsmToken::GreaterEqual:
1324 Kind = MCBinaryExpr::GTE;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001325 return 3;
1326
Jim Grosbach4b905842013-09-20 23:08:21 +00001327 // Intermediate Precedence: <<, >>
Jim Grosbachbd164242011-08-20 16:24:13 +00001328 case AsmToken::LessLess:
1329 Kind = MCBinaryExpr::Shl;
1330 return 4;
1331 case AsmToken::GreaterGreater:
David Majnemer0993e0b2015-10-26 03:15:34 +00001332 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
Jim Grosbachbd164242011-08-20 16:24:13 +00001333 return 4;
1334
Jim Grosbach4b905842013-09-20 23:08:21 +00001335 // High Intermediate Precedence: +, -
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001336 case AsmToken::Plus:
1337 Kind = MCBinaryExpr::Add;
Jim Grosbachbd164242011-08-20 16:24:13 +00001338 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001339 case AsmToken::Minus:
1340 Kind = MCBinaryExpr::Sub;
Jim Grosbachbd164242011-08-20 16:24:13 +00001341 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001342
Jim Grosbach4b905842013-09-20 23:08:21 +00001343 // Highest Precedence: *, /, %
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001344 case AsmToken::Star:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001345 Kind = MCBinaryExpr::Mul;
Jim Grosbachbd164242011-08-20 16:24:13 +00001346 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001347 case AsmToken::Slash:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001348 Kind = MCBinaryExpr::Div;
Jim Grosbachbd164242011-08-20 16:24:13 +00001349 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001350 case AsmToken::Percent:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001351 Kind = MCBinaryExpr::Mod;
Jim Grosbachbd164242011-08-20 16:24:13 +00001352 return 6;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001353 }
1354}
1355
David Majnemer0993e0b2015-10-26 03:15:34 +00001356static unsigned getGNUBinOpPrecedence(AsmToken::TokenKind K,
1357 MCBinaryExpr::Opcode &Kind,
1358 bool ShouldUseLogicalShr) {
1359 switch (K) {
1360 default:
1361 return 0; // not a binop.
1362
1363 // Lowest Precedence: &&, ||
1364 case AsmToken::AmpAmp:
1365 Kind = MCBinaryExpr::LAnd;
1366 return 2;
1367 case AsmToken::PipePipe:
1368 Kind = MCBinaryExpr::LOr;
1369 return 1;
1370
1371 // Low Precedence: ==, !=, <>, <, <=, >, >=
1372 case AsmToken::EqualEqual:
1373 Kind = MCBinaryExpr::EQ;
1374 return 3;
1375 case AsmToken::ExclaimEqual:
1376 case AsmToken::LessGreater:
1377 Kind = MCBinaryExpr::NE;
1378 return 3;
1379 case AsmToken::Less:
1380 Kind = MCBinaryExpr::LT;
1381 return 3;
1382 case AsmToken::LessEqual:
1383 Kind = MCBinaryExpr::LTE;
1384 return 3;
1385 case AsmToken::Greater:
1386 Kind = MCBinaryExpr::GT;
1387 return 3;
1388 case AsmToken::GreaterEqual:
1389 Kind = MCBinaryExpr::GTE;
1390 return 3;
1391
1392 // Low Intermediate Precedence: +, -
1393 case AsmToken::Plus:
1394 Kind = MCBinaryExpr::Add;
1395 return 4;
1396 case AsmToken::Minus:
1397 Kind = MCBinaryExpr::Sub;
1398 return 4;
1399
1400 // High Intermediate Precedence: |, &, ^
1401 //
1402 // FIXME: gas seems to support '!' as an infix operator?
1403 case AsmToken::Pipe:
1404 Kind = MCBinaryExpr::Or;
1405 return 5;
1406 case AsmToken::Caret:
1407 Kind = MCBinaryExpr::Xor;
1408 return 5;
1409 case AsmToken::Amp:
1410 Kind = MCBinaryExpr::And;
1411 return 5;
1412
1413 // Highest Precedence: *, /, %, <<, >>
1414 case AsmToken::Star:
1415 Kind = MCBinaryExpr::Mul;
1416 return 6;
1417 case AsmToken::Slash:
1418 Kind = MCBinaryExpr::Div;
1419 return 6;
1420 case AsmToken::Percent:
1421 Kind = MCBinaryExpr::Mod;
1422 return 6;
1423 case AsmToken::LessLess:
1424 Kind = MCBinaryExpr::Shl;
1425 return 6;
1426 case AsmToken::GreaterGreater:
1427 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1428 return 6;
1429 }
1430}
1431
1432unsigned AsmParser::getBinOpPrecedence(AsmToken::TokenKind K,
1433 MCBinaryExpr::Opcode &Kind) {
1434 bool ShouldUseLogicalShr = MAI.shouldUseLogicalShr();
1435 return IsDarwin ? getDarwinBinOpPrecedence(K, Kind, ShouldUseLogicalShr)
1436 : getGNUBinOpPrecedence(K, Kind, ShouldUseLogicalShr);
1437}
1438
Jim Grosbach4b905842013-09-20 23:08:21 +00001439/// \brief Parse all binary operators with precedence >= 'Precedence'.
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001440/// Res contains the LHS of the expression on input.
Jim Grosbach4b905842013-09-20 23:08:21 +00001441bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
Chris Lattner528d00b2010-01-15 19:28:38 +00001442 SMLoc &EndLoc) {
Chad Rosier9245e122017-01-19 20:06:32 +00001443 SMLoc StartLoc = Lexer.getLoc();
Eugene Zelenko33d7b762016-08-23 17:14:32 +00001444 while (true) {
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001445 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001446 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001447
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001448 // If the next token is lower precedence than we are allowed to eat, return
1449 // successfully with what we ate already.
1450 if (TokPrec < Precedence)
1451 return false;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001452
Sean Callanan686ed8d2010-01-19 20:22:31 +00001453 Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +00001454
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001455 // Eat the next primary expression.
Daniel Dunbarf3636452009-08-31 08:07:22 +00001456 const MCExpr *RHS;
Jim Grosbach4b905842013-09-20 23:08:21 +00001457 if (parsePrimaryExpr(RHS, EndLoc))
1458 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001459
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001460 // If BinOp binds less tightly with RHS than the operator after RHS, let
1461 // the pending operator take RHS as its LHS.
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001462 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001463 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Jim Grosbach4b905842013-09-20 23:08:21 +00001464 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1465 return true;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001466
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001467 // Merge LHS and RHS according to operator.
Chad Rosier9245e122017-01-19 20:06:32 +00001468 Res = MCBinaryExpr::create(Kind, Res, RHS, getContext(), StartLoc);
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001469 }
1470}
1471
Chris Lattner36e02122009-06-21 20:54:55 +00001472/// ParseStatement:
1473/// ::= EndOfStatement
Chris Lattnere5074c42009-06-22 01:29:09 +00001474/// ::= Label* Directive ...Operands... EndOfStatement
1475/// ::= Label* Identifier OperandList* EndOfStatement
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001476bool AsmParser::parseStatement(ParseStatementInfo &Info,
1477 MCAsmParserSemaCallback *SI) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001478 assert(!hasPendingError() && "parseStatement started with pending error");
Nirav Davefd910412016-06-17 16:06:17 +00001479 // Eat initial spaces and comments
1480 while (Lexer.is(AsmToken::Space))
1481 Lex();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001482 if (Lexer.is(AsmToken::EndOfStatement)) {
Nirav Davefd910412016-06-17 16:06:17 +00001483 // if this is a line comment we can drop it safely
1484 if (getTok().getString().front() == '\r' ||
1485 getTok().getString().front() == '\n')
1486 Out.AddBlankLine();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001487 Lex();
Chris Lattner36e02122009-06-21 20:54:55 +00001488 return false;
Chris Lattner36e02122009-06-21 20:54:55 +00001489 }
Nirav Dave9263ae32016-08-02 19:17:54 +00001490 if (Lexer.is(AsmToken::Hash)) {
1491 // Seeing a hash here means that it was an end-of-line comment in
1492 // an asm syntax where hash's are not comment and the previous
1493 // statement parser did not check the end of statement. Relex as
1494 // EndOfStatement.
1495 StringRef CommentStr = parseStringToEndOfStatement();
1496 Lexer.Lex();
1497 Lexer.UnLex(AsmToken(AsmToken::EndOfStatement, CommentStr));
1498 return false;
1499 }
Nirav Davefd910412016-06-17 16:06:17 +00001500 // Statements always start with an identifier.
Sean Callanan936b0d32010-01-19 21:44:56 +00001501 AsmToken ID = getTok();
Daniel Dunbaree4465c2009-07-28 16:38:40 +00001502 SMLoc IDLoc = ID.getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001503 StringRef IDVal;
Kevin Enderby0510b482010-05-17 23:08:19 +00001504 int64_t LocalLabelVal = -1;
Nirav Davefd910412016-06-17 16:06:17 +00001505 if (Lexer.is(AsmToken::HashDirective))
Jim Grosbach4b905842013-09-20 23:08:21 +00001506 return parseCppHashLineFilenameComment(IDLoc);
Kevin Enderbyfa3c6f12010-12-24 00:12:02 +00001507 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderby0510b482010-05-17 23:08:19 +00001508 if (Lexer.is(AsmToken::Integer)) {
1509 LocalLabelVal = getTok().getIntVal();
1510 if (LocalLabelVal < 0) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001511 if (!TheCondState.Ignore) {
1512 Lex(); // always eat a token
1513 return Error(IDLoc, "unexpected token at start of statement");
1514 }
Kevin Enderby0510b482010-05-17 23:08:19 +00001515 IDVal = "";
Eli Bendersky88024712013-01-16 19:32:36 +00001516 } else {
Kevin Enderby0510b482010-05-17 23:08:19 +00001517 IDVal = getTok().getString();
1518 Lex(); // Consume the integer token to be used as an identifier token.
1519 if (Lexer.getKind() != AsmToken::Colon) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001520 if (!TheCondState.Ignore) {
1521 Lex(); // always eat a token
1522 return Error(IDLoc, "unexpected token at start of statement");
1523 }
Kevin Enderby0510b482010-05-17 23:08:19 +00001524 }
1525 }
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001526 } else if (Lexer.is(AsmToken::Dot)) {
1527 // Treat '.' as a valid identifier in this context.
1528 Lex();
1529 IDVal = ".";
Colin LeMahieu8a0453e2015-11-09 00:31:07 +00001530 } else if (Lexer.is(AsmToken::LCurly)) {
1531 // Treat '{' as a valid identifier in this context.
1532 Lex();
1533 IDVal = "{";
1534
1535 } else if (Lexer.is(AsmToken::RCurly)) {
1536 // Treat '}' as a valid identifier in this context.
1537 Lex();
1538 IDVal = "}";
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001539 } else if (parseIdentifier(IDVal)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00001540 if (!TheCondState.Ignore) {
1541 Lex(); // always eat a token
1542 return Error(IDLoc, "unexpected token at start of statement");
1543 }
Chris Lattner926885c2010-04-17 18:14:27 +00001544 IDVal = "";
1545 }
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001546
Chris Lattner926885c2010-04-17 18:14:27 +00001547 // Handle conditional assembly here before checking for skipping. We
1548 // have to do this so that .endif isn't skipped in a ".if 0" block for
1549 // example.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001550 StringMap<DirectiveKind>::const_iterator DirKindIt =
Jim Grosbach4b905842013-09-20 23:08:21 +00001551 DirectiveKindMap.find(IDVal);
1552 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1553 ? DK_NO_DIRECTIVE
1554 : DirKindIt->getValue();
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001555 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001556 default:
1557 break;
1558 case DK_IF:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001559 case DK_IFEQ:
1560 case DK_IFGE:
1561 case DK_IFGT:
1562 case DK_IFLE:
1563 case DK_IFLT:
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00001564 case DK_IFNE:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001565 return parseDirectiveIf(IDLoc, DirKind);
Jim Grosbach4b905842013-09-20 23:08:21 +00001566 case DK_IFB:
1567 return parseDirectiveIfb(IDLoc, true);
1568 case DK_IFNB:
1569 return parseDirectiveIfb(IDLoc, false);
1570 case DK_IFC:
1571 return parseDirectiveIfc(IDLoc, true);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00001572 case DK_IFEQS:
Sid Manning51c35602015-03-18 14:20:54 +00001573 return parseDirectiveIfeqs(IDLoc, true);
Jim Grosbach4b905842013-09-20 23:08:21 +00001574 case DK_IFNC:
1575 return parseDirectiveIfc(IDLoc, false);
Sid Manning51c35602015-03-18 14:20:54 +00001576 case DK_IFNES:
1577 return parseDirectiveIfeqs(IDLoc, false);
Jim Grosbach4b905842013-09-20 23:08:21 +00001578 case DK_IFDEF:
1579 return parseDirectiveIfdef(IDLoc, true);
1580 case DK_IFNDEF:
1581 case DK_IFNOTDEF:
1582 return parseDirectiveIfdef(IDLoc, false);
1583 case DK_ELSEIF:
1584 return parseDirectiveElseIf(IDLoc);
1585 case DK_ELSE:
1586 return parseDirectiveElse(IDLoc);
1587 case DK_ENDIF:
1588 return parseDirectiveEndIf(IDLoc);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001589 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001590
Eli Bendersky88024712013-01-16 19:32:36 +00001591 // Ignore the statement if in the middle of inactive conditional
1592 // (e.g. ".if 0").
Chad Rosiereda70b32012-10-20 00:47:08 +00001593 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001594 eatToEndOfStatement();
Chris Lattner926885c2010-04-17 18:14:27 +00001595 return false;
1596 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001597
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001598 // FIXME: Recurse on local labels?
1599
1600 // See what kind of statement we have.
1601 switch (Lexer.getKind()) {
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001602 case AsmToken::Colon: {
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001603 if (!getTargetParser().isLabel(ID))
1604 break;
Nirav Davef43cc9f2016-10-10 15:24:54 +00001605 if (checkForValidSection())
1606 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00001607
Chris Lattner36e02122009-06-21 20:54:55 +00001608 // identifier ':' -> Label.
Sean Callanan686ed8d2010-01-19 20:22:31 +00001609 Lex();
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001610
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001611 // Diagnose attempt to use '.' as a label.
1612 if (IDVal == ".")
1613 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1614
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001615 // Diagnose attempt to use a variable as a label.
1616 //
1617 // FIXME: Diagnostics. Note the location of the definition as a label.
1618 // FIXME: This doesn't diagnose assignment to a symbol which has been
1619 // implicitly marked as external.
Kevin Enderby0510b482010-05-17 23:08:19 +00001620 MCSymbol *Sym;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001621 if (LocalLabelVal == -1) {
1622 if (ParsingInlineAsm && SI) {
Nico Weber67e715f2015-06-19 23:43:47 +00001623 StringRef RewrittenLabel =
1624 SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true);
1625 assert(RewrittenLabel.size() &&
1626 "We should have an internal name here.");
Craig Topper7d5b2312015-10-10 05:25:02 +00001627 Info.AsmRewrites->emplace_back(AOK_Label, IDLoc, IDVal.size(),
1628 RewrittenLabel);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001629 IDVal = RewrittenLabel;
1630 }
Jim Grosbach6f482002015-05-18 18:43:14 +00001631 Sym = getContext().getOrCreateSymbol(IDVal);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001632 } else
Jim Grosbach6f482002015-05-18 18:43:14 +00001633 Sym = Ctx.createDirectionalLocalSymbol(LocalLabelVal);
David Majnemer58cb80c2014-12-24 10:27:50 +00001634
1635 Sym->redefineIfPossible();
1636
Daniel Dunbardeb7ba92010-05-05 19:01:00 +00001637 if (!Sym->isUndefined() || Sym->isVariable())
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001638 return Error(IDLoc, "invalid symbol redefinition");
Michael J. Spencer530ce852010-10-09 11:00:50 +00001639
Nirav Dave9263ae32016-08-02 19:17:54 +00001640 // End of Labels should be treated as end of line for lexing
1641 // purposes but that information is not available to the Lexer who
1642 // does not understand Labels. This may cause us to see a Hash
1643 // here instead of a preprocessor line comment.
1644 if (getTok().is(AsmToken::Hash)) {
1645 StringRef CommentStr = parseStringToEndOfStatement();
1646 Lexer.Lex();
1647 Lexer.UnLex(AsmToken(AsmToken::EndOfStatement, CommentStr));
1648 }
1649
Nirav Dave8ea792d2016-07-13 14:03:12 +00001650 // Consume any end of statement token, if present, to avoid spurious
1651 // AddBlankLine calls().
1652 if (getTok().is(AsmToken::EndOfStatement)) {
1653 Lex();
1654 }
1655
Daniel Dunbare73b2672009-08-26 22:13:22 +00001656 // Emit the label.
Chad Rosierf3feab32013-01-07 20:34:12 +00001657 if (!ParsingInlineAsm)
1658 Out.EmitLabel(Sym);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001659
Kevin Enderbye7739d42011-12-09 18:09:40 +00001660 // If we are generating dwarf for assembly source files then gather the
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001661 // info to make a dwarf label entry for this label if needed.
Kevin Enderbye7739d42011-12-09 18:09:40 +00001662 if (getContext().getGenDwarfForAssembly())
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001663 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1664 IDLoc);
Kevin Enderbye7739d42011-12-09 18:09:40 +00001665
Tim Northover1744d0a2013-10-25 12:49:50 +00001666 getTargetParser().onLabelParsed(Sym);
1667
Eli Friedman0f4871d2012-10-22 23:58:19 +00001668 return false;
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001669 }
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001670
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001671 case AsmToken::Equal:
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001672 if (!getTargetParser().equalIsAsmAssignment())
1673 break;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001674 // identifier '=' ... -> assignment statement
Sean Callanan686ed8d2010-01-19 20:22:31 +00001675 Lex();
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001676
Jim Grosbach4b905842013-09-20 23:08:21 +00001677 return parseAssignment(IDVal, true);
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001678
1679 default: // Normal instruction or directive.
1680 break;
Chris Lattner36e02122009-06-21 20:54:55 +00001681 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001682
1683 // If macros are enabled, check to see if this is a macro instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00001684 if (areMacrosEnabled())
1685 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1686 return handleMacroEntry(M, IDLoc);
Eli Bendersky38274122013-01-14 23:22:36 +00001687 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001688
Michael J. Spencer530ce852010-10-09 11:00:50 +00001689 // Otherwise, we have a normal instruction or directive.
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001690
Eli Bendersky17233942013-01-15 22:59:42 +00001691 // Directives start with "."
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001692 if (IDVal[0] == '.' && IDVal != ".") {
Eli Bendersky17233942013-01-15 22:59:42 +00001693 // There are several entities interested in parsing directives:
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001694 //
Eli Bendersky17233942013-01-15 22:59:42 +00001695 // 1. The target-specific assembly parser. Some directives are target
1696 // specific or may potentially behave differently on certain targets.
1697 // 2. Asm parser extensions. For example, platform-specific parsers
1698 // (like the ELF parser) register themselves as extensions.
1699 // 3. The generic directive parser implemented by this class. These are
1700 // all the directives that behave in a target and platform independent
1701 // manner, or at least have a default behavior that's shared between
1702 // all targets and platforms.
Akira Hatanakad3590752012-07-05 19:09:33 +00001703
Oliver Stannard21718282016-07-26 14:19:47 +00001704 getTargetParser().flushPendingInstructions(getStreamer());
1705
Nirav Dave2364748a2016-09-16 18:30:20 +00001706 SMLoc StartTokLoc = getTok().getLoc();
1707 bool TPDirectiveReturn = getTargetParser().ParseDirective(ID);
1708
1709 if (hasPendingError())
1710 return true;
1711 // Currently the return value should be true if we are
1712 // uninterested but as this is at odds with the standard parsing
1713 // convention (return true = error) we have instances of a parsed
1714 // directive that fails returning true as an error. Catch these
1715 // cases as best as possible errors here.
1716 if (TPDirectiveReturn && StartTokLoc != getTok().getLoc())
1717 return true;
1718 // Return if we did some parsing or believe we succeeded.
1719 if (!TPDirectiveReturn || StartTokLoc != getTok().getLoc())
Akira Hatanakad3590752012-07-05 19:09:33 +00001720 return false;
1721
Alp Tokercb402912014-01-24 17:20:08 +00001722 // Next, check the extension directive map to see if any extension has
Eli Bendersky17233942013-01-15 22:59:42 +00001723 // registered itself to parse this directive.
Jim Grosbach4b905842013-09-20 23:08:21 +00001724 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1725 ExtensionDirectiveMap.lookup(IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +00001726 if (Handler.first)
1727 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1728
1729 // Finally, if no one else is interested in this directive, it must be
1730 // generic and familiar to this class.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001731 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001732 default:
1733 break;
1734 case DK_SET:
1735 case DK_EQU:
1736 return parseDirectiveSet(IDVal, true);
1737 case DK_EQUIV:
1738 return parseDirectiveSet(IDVal, false);
1739 case DK_ASCII:
1740 return parseDirectiveAscii(IDVal, false);
1741 case DK_ASCIZ:
1742 case DK_STRING:
1743 return parseDirectiveAscii(IDVal, true);
1744 case DK_BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001745 case DK_DC_B:
1746 return parseDirectiveValue(IDVal, 1);
1747 case DK_DC:
1748 case DK_DC_W:
Jim Grosbach4b905842013-09-20 23:08:21 +00001749 case DK_SHORT:
1750 case DK_VALUE:
1751 case DK_2BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001752 return parseDirectiveValue(IDVal, 2);
Jim Grosbach4b905842013-09-20 23:08:21 +00001753 case DK_LONG:
1754 case DK_INT:
1755 case DK_4BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001756 case DK_DC_L:
1757 return parseDirectiveValue(IDVal, 4);
Jim Grosbach4b905842013-09-20 23:08:21 +00001758 case DK_QUAD:
1759 case DK_8BYTE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001760 return parseDirectiveValue(IDVal, 8);
1761 case DK_DC_A:
1762 return parseDirectiveValue(IDVal,
1763 getContext().getAsmInfo()->getPointerSize());
David Woodhoused6de0d92014-02-01 16:20:59 +00001764 case DK_OCTA:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001765 return parseDirectiveOctaValue(IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001766 case DK_SINGLE:
1767 case DK_FLOAT:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001768 case DK_DC_S:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001769 return parseDirectiveRealValue(IDVal, APFloat::IEEEsingle());
Jim Grosbach4b905842013-09-20 23:08:21 +00001770 case DK_DOUBLE:
Nirav Dave1a9044b2016-10-24 14:35:29 +00001771 case DK_DC_D:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001772 return parseDirectiveRealValue(IDVal, APFloat::IEEEdouble());
Jim Grosbach4b905842013-09-20 23:08:21 +00001773 case DK_ALIGN: {
1774 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1775 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1776 }
1777 case DK_ALIGN32: {
1778 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1779 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1780 }
1781 case DK_BALIGN:
1782 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1783 case DK_BALIGNW:
1784 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1785 case DK_BALIGNL:
1786 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1787 case DK_P2ALIGN:
1788 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1789 case DK_P2ALIGNW:
1790 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1791 case DK_P2ALIGNL:
1792 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1793 case DK_ORG:
1794 return parseDirectiveOrg();
1795 case DK_FILL:
1796 return parseDirectiveFill();
1797 case DK_ZERO:
1798 return parseDirectiveZero();
1799 case DK_EXTERN:
1800 eatToEndOfStatement(); // .extern is the default, ignore it.
1801 return false;
1802 case DK_GLOBL:
1803 case DK_GLOBAL:
1804 return parseDirectiveSymbolAttribute(MCSA_Global);
1805 case DK_LAZY_REFERENCE:
1806 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1807 case DK_NO_DEAD_STRIP:
1808 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1809 case DK_SYMBOL_RESOLVER:
1810 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1811 case DK_PRIVATE_EXTERN:
1812 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1813 case DK_REFERENCE:
1814 return parseDirectiveSymbolAttribute(MCSA_Reference);
1815 case DK_WEAK_DEFINITION:
1816 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1817 case DK_WEAK_REFERENCE:
1818 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1819 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1820 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1821 case DK_COMM:
1822 case DK_COMMON:
1823 return parseDirectiveComm(/*IsLocal=*/false);
1824 case DK_LCOMM:
1825 return parseDirectiveComm(/*IsLocal=*/true);
1826 case DK_ABORT:
1827 return parseDirectiveAbort();
1828 case DK_INCLUDE:
1829 return parseDirectiveInclude();
1830 case DK_INCBIN:
1831 return parseDirectiveIncbin();
1832 case DK_CODE16:
1833 case DK_CODE16GCC:
Nirav Davefd910412016-06-17 16:06:17 +00001834 return TokError(Twine(IDVal) +
1835 " not currently supported for this target");
Jim Grosbach4b905842013-09-20 23:08:21 +00001836 case DK_REPT:
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00001837 return parseDirectiveRept(IDLoc, IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001838 case DK_IRP:
1839 return parseDirectiveIrp(IDLoc);
1840 case DK_IRPC:
1841 return parseDirectiveIrpc(IDLoc);
1842 case DK_ENDR:
1843 return parseDirectiveEndr(IDLoc);
1844 case DK_BUNDLE_ALIGN_MODE:
1845 return parseDirectiveBundleAlignMode();
1846 case DK_BUNDLE_LOCK:
1847 return parseDirectiveBundleLock();
1848 case DK_BUNDLE_UNLOCK:
1849 return parseDirectiveBundleUnlock();
1850 case DK_SLEB128:
1851 return parseDirectiveLEB128(true);
1852 case DK_ULEB128:
1853 return parseDirectiveLEB128(false);
1854 case DK_SPACE:
1855 case DK_SKIP:
1856 return parseDirectiveSpace(IDVal);
1857 case DK_FILE:
1858 return parseDirectiveFile(IDLoc);
1859 case DK_LINE:
1860 return parseDirectiveLine();
1861 case DK_LOC:
1862 return parseDirectiveLoc();
1863 case DK_STABS:
1864 return parseDirectiveStabs();
Reid Kleckner2214ed82016-01-29 00:49:42 +00001865 case DK_CV_FILE:
1866 return parseDirectiveCVFile();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00001867 case DK_CV_FUNC_ID:
1868 return parseDirectiveCVFuncId();
1869 case DK_CV_INLINE_SITE_ID:
1870 return parseDirectiveCVInlineSiteId();
Reid Kleckner2214ed82016-01-29 00:49:42 +00001871 case DK_CV_LOC:
1872 return parseDirectiveCVLoc();
1873 case DK_CV_LINETABLE:
1874 return parseDirectiveCVLinetable();
David Majnemer6fcbd7e2016-01-29 19:24:12 +00001875 case DK_CV_INLINE_LINETABLE:
1876 return parseDirectiveCVInlineLinetable();
David Majnemer408b5e62016-02-05 01:55:49 +00001877 case DK_CV_DEF_RANGE:
1878 return parseDirectiveCVDefRange();
Reid Kleckner2214ed82016-01-29 00:49:42 +00001879 case DK_CV_STRINGTABLE:
1880 return parseDirectiveCVStringTable();
1881 case DK_CV_FILECHECKSUMS:
1882 return parseDirectiveCVFileChecksums();
Jim Grosbach4b905842013-09-20 23:08:21 +00001883 case DK_CFI_SECTIONS:
1884 return parseDirectiveCFISections();
1885 case DK_CFI_STARTPROC:
1886 return parseDirectiveCFIStartProc();
1887 case DK_CFI_ENDPROC:
1888 return parseDirectiveCFIEndProc();
1889 case DK_CFI_DEF_CFA:
1890 return parseDirectiveCFIDefCfa(IDLoc);
1891 case DK_CFI_DEF_CFA_OFFSET:
1892 return parseDirectiveCFIDefCfaOffset();
1893 case DK_CFI_ADJUST_CFA_OFFSET:
1894 return parseDirectiveCFIAdjustCfaOffset();
1895 case DK_CFI_DEF_CFA_REGISTER:
1896 return parseDirectiveCFIDefCfaRegister(IDLoc);
1897 case DK_CFI_OFFSET:
1898 return parseDirectiveCFIOffset(IDLoc);
1899 case DK_CFI_REL_OFFSET:
1900 return parseDirectiveCFIRelOffset(IDLoc);
1901 case DK_CFI_PERSONALITY:
1902 return parseDirectiveCFIPersonalityOrLsda(true);
1903 case DK_CFI_LSDA:
1904 return parseDirectiveCFIPersonalityOrLsda(false);
1905 case DK_CFI_REMEMBER_STATE:
1906 return parseDirectiveCFIRememberState();
1907 case DK_CFI_RESTORE_STATE:
1908 return parseDirectiveCFIRestoreState();
1909 case DK_CFI_SAME_VALUE:
1910 return parseDirectiveCFISameValue(IDLoc);
1911 case DK_CFI_RESTORE:
1912 return parseDirectiveCFIRestore(IDLoc);
1913 case DK_CFI_ESCAPE:
1914 return parseDirectiveCFIEscape();
1915 case DK_CFI_SIGNAL_FRAME:
1916 return parseDirectiveCFISignalFrame();
1917 case DK_CFI_UNDEFINED:
1918 return parseDirectiveCFIUndefined(IDLoc);
1919 case DK_CFI_REGISTER:
1920 return parseDirectiveCFIRegister(IDLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00001921 case DK_CFI_WINDOW_SAVE:
1922 return parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +00001923 case DK_MACROS_ON:
1924 case DK_MACROS_OFF:
1925 return parseDirectiveMacrosOnOff(IDVal);
1926 case DK_MACRO:
1927 return parseDirectiveMacro(IDLoc);
Nico Weber155dccd12014-07-24 17:08:39 +00001928 case DK_EXITM:
1929 return parseDirectiveExitMacro(IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001930 case DK_ENDM:
1931 case DK_ENDMACRO:
1932 return parseDirectiveEndMacro(IDVal);
1933 case DK_PURGEM:
1934 return parseDirectivePurgeMacro(IDLoc);
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00001935 case DK_END:
1936 return parseDirectiveEnd(IDLoc);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00001937 case DK_ERR:
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00001938 return parseDirectiveError(IDLoc, false);
1939 case DK_ERROR:
1940 return parseDirectiveError(IDLoc, true);
Nico Weber404012b2014-07-24 16:26:06 +00001941 case DK_WARNING:
1942 return parseDirectiveWarning(IDLoc);
Daniel Sanders9f6ad492015-11-12 13:33:00 +00001943 case DK_RELOC:
1944 return parseDirectiveReloc(IDLoc);
Petr Hosek4cb08ce2016-09-23 19:25:15 +00001945 case DK_DCB:
1946 case DK_DCB_W:
1947 return parseDirectiveDCB(IDVal, 2);
1948 case DK_DCB_B:
1949 return parseDirectiveDCB(IDVal, 1);
1950 case DK_DCB_D:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001951 return parseDirectiveRealDCB(IDVal, APFloat::IEEEdouble());
Petr Hosek4cb08ce2016-09-23 19:25:15 +00001952 case DK_DCB_L:
1953 return parseDirectiveDCB(IDVal, 4);
1954 case DK_DCB_S:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001955 return parseDirectiveRealDCB(IDVal, APFloat::IEEEsingle());
Petr Hosek731bb9c2016-08-23 21:34:53 +00001956 case DK_DC_X:
Petr Hosek4cb08ce2016-09-23 19:25:15 +00001957 case DK_DCB_X:
Petr Hosek731bb9c2016-08-23 21:34:53 +00001958 return TokError(Twine(IDVal) +
1959 " not currently supported for this target");
Petr Hosek85b2f672016-09-23 21:53:36 +00001960 case DK_DS:
1961 case DK_DS_W:
1962 return parseDirectiveDS(IDVal, 2);
1963 case DK_DS_B:
1964 return parseDirectiveDS(IDVal, 1);
1965 case DK_DS_D:
1966 return parseDirectiveDS(IDVal, 8);
1967 case DK_DS_L:
1968 case DK_DS_S:
1969 return parseDirectiveDS(IDVal, 4);
1970 case DK_DS_P:
1971 case DK_DS_X:
1972 return parseDirectiveDS(IDVal, 12);
Eli Friedman20b02642010-07-19 04:17:25 +00001973 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00001974
Jim Grosbach758e0cc2012-05-01 18:38:27 +00001975 return Error(IDLoc, "unknown directive");
Chris Lattnere5074c42009-06-22 01:29:09 +00001976 }
Chris Lattner36e02122009-06-21 20:54:55 +00001977
Chad Rosierc7f552c2013-02-12 21:33:51 +00001978 // __asm _emit or __asm __emit
1979 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1980 IDVal == "_EMIT" || IDVal == "__EMIT"))
Jim Grosbach4b905842013-09-20 23:08:21 +00001981 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
Chad Rosierc7f552c2013-02-12 21:33:51 +00001982
1983 // __asm align
1984 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
Jim Grosbach4b905842013-09-20 23:08:21 +00001985 return parseDirectiveMSAlign(IDLoc, Info);
Eli Friedman0f4871d2012-10-22 23:58:19 +00001986
Michael Zuckerman02ecd432015-12-13 17:07:23 +00001987 if (ParsingInlineAsm && (IDVal == "even"))
1988 Info.AsmRewrites->emplace_back(AOK_EVEN, IDLoc, 4);
Nirav Davef43cc9f2016-10-10 15:24:54 +00001989 if (checkForValidSection())
1990 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00001991
Chris Lattner7cbfa442010-05-19 23:34:33 +00001992 // Canonicalize the opcode to lower case.
Eli Bendersky88024712013-01-16 19:32:36 +00001993 std::string OpcodeStr = IDVal.lower();
Chad Rosierf0e87202012-10-25 20:41:34 +00001994 ParseInstructionInfo IInfo(Info.AsmRewrites);
Nirav Dave2364748a2016-09-16 18:30:20 +00001995 bool ParseHadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, ID,
1996 Info.ParsedOperands);
1997 Info.ParseError = ParseHadError;
Chris Lattnere5074c42009-06-22 01:29:09 +00001998
Daniel Dunbar2eca0252010-08-11 06:37:09 +00001999 // Dump the parsed representation, if requested.
2000 if (getShowParsedOperands()) {
2001 SmallString<256> Str;
2002 raw_svector_ostream OS(Str);
2003 OS << "parsed instruction: [";
Eli Friedman0f4871d2012-10-22 23:58:19 +00002004 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002005 if (i != 0)
2006 OS << ", ";
Eli Friedman0f4871d2012-10-22 23:58:19 +00002007 Info.ParsedOperands[i]->print(OS);
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002008 }
2009 OS << "]";
2010
Jim Grosbach4b905842013-09-20 23:08:21 +00002011 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar2eca0252010-08-11 06:37:09 +00002012 }
2013
Nirav Dave2364748a2016-09-16 18:30:20 +00002014 // Fail even if ParseInstruction erroneously returns false.
2015 if (hasPendingError() || ParseHadError)
2016 return true;
2017
Oliver Stannard8b273082014-06-19 15:52:37 +00002018 // If we are generating dwarf for the current section then generate a .loc
2019 // directive for the instruction.
Nirav Dave2364748a2016-09-16 18:30:20 +00002020 if (!ParseHadError && getContext().getGenDwarfForAssembly() &&
Oliver Stannard8b273082014-06-19 15:52:37 +00002021 getContext().getGenDwarfSectionSyms().count(
Eric Christopher445c9522016-10-14 05:47:37 +00002022 getStreamer().getCurrentSectionOnly())) {
Saleem Abdulrasool4d6ed7c2014-12-24 06:32:43 +00002023 unsigned Line;
2024 if (ActiveMacros.empty())
2025 Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
2026 else
Frederic Riss16238d92015-06-25 21:57:33 +00002027 Line = SrcMgr.FindLineNumber(ActiveMacros.front()->InstantiationLoc,
2028 ActiveMacros.front()->ExitBuffer);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002029
Eli Bendersky88024712013-01-16 19:32:36 +00002030 // If we previously parsed a cpp hash file line comment then make sure the
2031 // current Dwarf File is for the CppHashFilename if not then emit the
2032 // Dwarf File table for it and adjust the line number for the .loc.
Tim Northoverc0bef992016-04-13 19:46:54 +00002033 if (CppHashInfo.Filename.size()) {
David Blaikiec714ef42014-03-17 01:52:11 +00002034 unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
Tim Northoverc0bef992016-04-13 19:46:54 +00002035 0, StringRef(), CppHashInfo.Filename);
David Blaikiec714ef42014-03-17 01:52:11 +00002036 getContext().setGenDwarfFileNumber(FileNumber);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002037
Jim Grosbach4b905842013-09-20 23:08:21 +00002038 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
2039 // cache with the different Loc from the call above we save the last
2040 // info we queried here with SrcMgr.FindLineNumber().
2041 unsigned CppHashLocLineNo;
Tim Northoverc0bef992016-04-13 19:46:54 +00002042 if (LastQueryIDLoc == CppHashInfo.Loc &&
2043 LastQueryBuffer == CppHashInfo.Buf)
Jim Grosbach4b905842013-09-20 23:08:21 +00002044 CppHashLocLineNo = LastQueryLine;
2045 else {
Tim Northoverc0bef992016-04-13 19:46:54 +00002046 CppHashLocLineNo =
2047 SrcMgr.FindLineNumber(CppHashInfo.Loc, CppHashInfo.Buf);
Jim Grosbach4b905842013-09-20 23:08:21 +00002048 LastQueryLine = CppHashLocLineNo;
Tim Northoverc0bef992016-04-13 19:46:54 +00002049 LastQueryIDLoc = CppHashInfo.Loc;
2050 LastQueryBuffer = CppHashInfo.Buf;
Jim Grosbach4b905842013-09-20 23:08:21 +00002051 }
Tim Northoverc0bef992016-04-13 19:46:54 +00002052 Line = CppHashInfo.LineNumber - 1 + (Line - CppHashLocLineNo);
Eli Bendersky88024712013-01-16 19:32:36 +00002053 }
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002054
Jim Grosbach4b905842013-09-20 23:08:21 +00002055 getStreamer().EmitDwarfLocDirective(
2056 getContext().getGenDwarfFileNumber(), Line, 0,
2057 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
2058 StringRef());
Kevin Enderby6469fc22011-11-01 22:27:22 +00002059 }
2060
Daniel Dunbarce0c1e12010-05-04 00:33:07 +00002061 // If parsing succeeded, match the instruction.
Nirav Dave2364748a2016-09-16 18:30:20 +00002062 if (!ParseHadError) {
Tim Northover26bb14e2014-08-18 11:49:42 +00002063 uint64_t ErrorInfo;
Nirav Dave2364748a2016-09-16 18:30:20 +00002064 if (getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
2065 Info.ParsedOperands, Out,
2066 ErrorInfo, ParsingInlineAsm))
2067 return true;
Chad Rosier49963552012-10-13 00:26:04 +00002068 }
Chris Lattnera2a9d162010-09-11 16:18:25 +00002069 return false;
Chris Lattnerb0133452009-06-21 20:16:42 +00002070}
Chris Lattnerbedf6c22009-06-24 04:43:34 +00002071
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00002072// Parse and erase curly braces marking block start/end
2073bool
2074AsmParser::parseCurlyBlockScope(SmallVectorImpl<AsmRewrite> &AsmStrRewrites) {
2075 // Identify curly brace marking block start/end
2076 if (Lexer.isNot(AsmToken::LCurly) && Lexer.isNot(AsmToken::RCurly))
2077 return false;
2078
2079 SMLoc StartLoc = Lexer.getLoc();
2080 Lex(); // Eat the brace
2081 if (Lexer.is(AsmToken::EndOfStatement))
2082 Lex(); // Eat EndOfStatement following the brace
2083
2084 // Erase the block start/end brace from the output asm string
2085 AsmStrRewrites.emplace_back(AOK_Skip, StartLoc, Lexer.getLoc().getPointer() -
2086 StartLoc.getPointer());
2087 return true;
2088}
2089
Jim Grosbach4b905842013-09-20 23:08:21 +00002090/// parseCppHashLineFilenameComment as this:
Kevin Enderby72553612011-09-13 23:45:18 +00002091/// ::= # number "filename"
Craig Topper3c76c522015-09-20 23:35:59 +00002092bool AsmParser::parseCppHashLineFilenameComment(SMLoc L) {
Kevin Enderby72553612011-09-13 23:45:18 +00002093 Lex(); // Eat the hash token.
Nirav Davefd910412016-06-17 16:06:17 +00002094 // Lexer only ever emits HashDirective if it fully formed if it's
2095 // done the checking already so this is an internal error.
2096 assert(getTok().is(AsmToken::Integer) &&
2097 "Lexing Cpp line comment: Expected Integer");
Kevin Enderby72553612011-09-13 23:45:18 +00002098 int64_t LineNumber = getTok().getIntVal();
Kevin Enderby72553612011-09-13 23:45:18 +00002099 Lex();
Nirav Davefd910412016-06-17 16:06:17 +00002100 assert(getTok().is(AsmToken::String) &&
2101 "Lexing Cpp line comment: Expected String");
Kevin Enderby72553612011-09-13 23:45:18 +00002102 StringRef Filename = getTok().getString();
Nirav Davefd910412016-06-17 16:06:17 +00002103 Lex();
Nirav Dave2364748a2016-09-16 18:30:20 +00002104
Kevin Enderby72553612011-09-13 23:45:18 +00002105 // Get rid of the enclosing quotes.
Jim Grosbach4b905842013-09-20 23:08:21 +00002106 Filename = Filename.substr(1, Filename.size() - 2);
Kevin Enderby72553612011-09-13 23:45:18 +00002107
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002108 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
Tim Northoverc0bef992016-04-13 19:46:54 +00002109 CppHashInfo.Loc = L;
2110 CppHashInfo.Filename = Filename;
2111 CppHashInfo.LineNumber = LineNumber;
2112 CppHashInfo.Buf = CurBuffer;
Kevin Enderby72553612011-09-13 23:45:18 +00002113 return false;
2114}
2115
Jim Grosbach4b905842013-09-20 23:08:21 +00002116/// \brief will use the last parsed cpp hash line filename comment
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002117/// for the Filename and LineNo if any in the diagnostic.
2118void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002119 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002120 raw_ostream &OS = errs();
2121
2122 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
Craig Topper3c76c522015-09-20 23:35:59 +00002123 SMLoc DiagLoc = Diag.getLoc();
Alp Tokera55b95b2014-07-06 10:33:31 +00002124 unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2125 unsigned CppHashBuf =
Tim Northoverc0bef992016-04-13 19:46:54 +00002126 Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashInfo.Loc);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002127
Jim Grosbach4b905842013-09-20 23:08:21 +00002128 // Like SourceMgr::printMessage() we need to print the include stack if any
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002129 // before printing the message.
Alp Tokera55b95b2014-07-06 10:33:31 +00002130 unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2131 if (!Parser->SavedDiagHandler && DiagCurBuffer &&
2132 DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002133 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
2134 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002135 }
2136
Eric Christophera7c32732012-12-18 00:30:54 +00002137 // If we have not parsed a cpp hash line filename comment or the source
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002138 // manager changed or buffer changed (like in a nested include) then just
2139 // print the normal diagnostic using its Filename and LineNo.
Tim Northoverc0bef992016-04-13 19:46:54 +00002140 if (!Parser->CppHashInfo.LineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002141 DiagBuf != CppHashBuf) {
Benjamin Kramer47f5e302011-10-16 10:48:29 +00002142 if (Parser->SavedDiagHandler)
2143 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
2144 else
Craig Topper353eda42014-04-24 06:44:33 +00002145 Diag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002146 return;
2147 }
2148
Eric Christophera7c32732012-12-18 00:30:54 +00002149 // Use the CppHashFilename and calculate a line number based on the
Tim Northoverc0bef992016-04-13 19:46:54 +00002150 // CppHashInfo.Loc and CppHashInfo.LineNumber relative to this Diag's SMLoc
2151 // for the diagnostic.
2152 const std::string &Filename = Parser->CppHashInfo.Filename;
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002153
2154 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
2155 int CppHashLocLineNo =
Tim Northoverc0bef992016-04-13 19:46:54 +00002156 Parser->SrcMgr.FindLineNumber(Parser->CppHashInfo.Loc, CppHashBuf);
Jim Grosbach4b905842013-09-20 23:08:21 +00002157 int LineNo =
Tim Northoverc0bef992016-04-13 19:46:54 +00002158 Parser->CppHashInfo.LineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002159
Jim Grosbach4b905842013-09-20 23:08:21 +00002160 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
2161 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
Chris Lattner72845262011-10-16 05:47:55 +00002162 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002163
Benjamin Kramer47f5e302011-10-16 10:48:29 +00002164 if (Parser->SavedDiagHandler)
2165 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
2166 else
Craig Topper353eda42014-04-24 06:44:33 +00002167 NewDiag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002168}
2169
Rafael Espindola2c064482012-08-21 18:29:30 +00002170// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
2171// difference being that that function accepts '@' as part of identifiers and
2172// we can't do that. AsmLexer.cpp should probably be changed to handle
2173// '@' as a special case when needed.
2174static bool isIdentifierChar(char c) {
Guy Benyei83c74e92013-02-12 21:21:59 +00002175 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
2176 c == '.';
Rafael Espindola2c064482012-08-21 18:29:30 +00002177}
2178
Rafael Espindola34b9c512012-06-03 23:57:14 +00002179bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00002180 ArrayRef<MCAsmMacroParameter> Parameters,
Toma Tabacu217116e2015-04-27 10:50:29 +00002181 ArrayRef<MCAsmMacroArgument> A,
Craig Topper3c76c522015-09-20 23:35:59 +00002182 bool EnableAtPseudoVariable, SMLoc L) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00002183 unsigned NParameters = Parameters.size();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002184 bool HasVararg = NParameters ? Parameters.back().Vararg : false;
Benjamin Kramer513e7442014-02-20 13:36:32 +00002185 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
Rafael Espindola1134ab232011-06-05 02:43:45 +00002186 return Error(L, "Wrong number of arguments");
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002187
Preston Gurd05500642012-09-19 20:36:12 +00002188 // A macro without parameters is handled differently on Darwin:
2189 // gas accepts no arguments and does no substitutions
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002190 while (!Body.empty()) {
2191 // Scan for the next substitution.
2192 std::size_t End = Body.size(), Pos = 0;
2193 for (; Pos != End; ++Pos) {
2194 // Check for a substitution or escape.
Benjamin Kramer513e7442014-02-20 13:36:32 +00002195 if (IsDarwin && !NParameters) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00002196 // This macro has no parameters, look for $0, $1, etc.
2197 if (Body[Pos] != '$' || Pos + 1 == End)
2198 continue;
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002199
Rafael Espindola1134ab232011-06-05 02:43:45 +00002200 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00002201 if (Next == '$' || Next == 'n' ||
2202 isdigit(static_cast<unsigned char>(Next)))
Rafael Espindola1134ab232011-06-05 02:43:45 +00002203 break;
2204 } else {
2205 // This macro has parameters, look for \foo, \bar, etc.
2206 if (Body[Pos] == '\\' && Pos + 1 != End)
2207 break;
2208 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002209 }
2210
2211 // Add the prefix.
2212 OS << Body.slice(0, Pos);
2213
2214 // Check if we reached the end.
2215 if (Pos == End)
2216 break;
2217
Benjamin Kramer513e7442014-02-20 13:36:32 +00002218 if (IsDarwin && !NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002219 switch (Body[Pos + 1]) {
2220 // $$ => $
Rafael Espindola1134ab232011-06-05 02:43:45 +00002221 case '$':
2222 OS << '$';
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002223 break;
2224
Jim Grosbach4b905842013-09-20 23:08:21 +00002225 // $n => number of arguments
Rafael Espindola1134ab232011-06-05 02:43:45 +00002226 case 'n':
2227 OS << A.size();
2228 break;
2229
Jim Grosbach4b905842013-09-20 23:08:21 +00002230 // $[0-9] => argument
Rafael Espindola1134ab232011-06-05 02:43:45 +00002231 default: {
2232 // Missing arguments are ignored.
Jim Grosbach4b905842013-09-20 23:08:21 +00002233 unsigned Index = Body[Pos + 1] - '0';
Rafael Espindola1134ab232011-06-05 02:43:45 +00002234 if (Index >= A.size())
2235 break;
2236
2237 // Otherwise substitute with the token values, with spaces eliminated.
Craig Topper84008482015-10-10 05:38:14 +00002238 for (const AsmToken &Token : A[Index])
2239 OS << Token.getString();
Rafael Espindola1134ab232011-06-05 02:43:45 +00002240 break;
2241 }
2242 }
2243 Pos += 2;
2244 } else {
2245 unsigned I = Pos + 1;
Toma Tabacu217116e2015-04-27 10:50:29 +00002246
2247 // Check for the \@ pseudo-variable.
2248 if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End)
Rafael Espindola1134ab232011-06-05 02:43:45 +00002249 ++I;
Toma Tabacu217116e2015-04-27 10:50:29 +00002250 else
2251 while (isIdentifierChar(Body[I]) && I + 1 != End)
2252 ++I;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002253
Jim Grosbach4b905842013-09-20 23:08:21 +00002254 const char *Begin = Body.data() + Pos + 1;
2255 StringRef Argument(Begin, I - (Pos + 1));
Rafael Espindola1134ab232011-06-05 02:43:45 +00002256 unsigned Index = 0;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002257
Toma Tabacu217116e2015-04-27 10:50:29 +00002258 if (Argument == "@") {
2259 OS << NumOfMacroInstantiations;
2260 Pos += 2;
Preston Gurd05500642012-09-19 20:36:12 +00002261 } else {
Toma Tabacu217116e2015-04-27 10:50:29 +00002262 for (; Index < NParameters; ++Index)
2263 if (Parameters[Index].Name == Argument)
2264 break;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002265
Toma Tabacu217116e2015-04-27 10:50:29 +00002266 if (Index == NParameters) {
2267 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
2268 Pos += 3;
2269 else {
2270 OS << '\\' << Argument;
2271 Pos = I;
2272 }
2273 } else {
2274 bool VarargParameter = HasVararg && Index == (NParameters - 1);
Craig Topper84008482015-10-10 05:38:14 +00002275 for (const AsmToken &Token : A[Index])
Toma Tabacu217116e2015-04-27 10:50:29 +00002276 // We expect no quotes around the string's contents when
2277 // parsing for varargs.
Craig Topper84008482015-10-10 05:38:14 +00002278 if (Token.getKind() != AsmToken::String || VarargParameter)
2279 OS << Token.getString();
Toma Tabacu217116e2015-04-27 10:50:29 +00002280 else
Craig Topper84008482015-10-10 05:38:14 +00002281 OS << Token.getStringContents();
Toma Tabacu217116e2015-04-27 10:50:29 +00002282
2283 Pos += 1 + Argument.size();
2284 }
Preston Gurd05500642012-09-19 20:36:12 +00002285 }
Rafael Espindola1134ab232011-06-05 02:43:45 +00002286 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002287 // Update the scan point.
Rafael Espindola1134ab232011-06-05 02:43:45 +00002288 Body = Body.substr(Pos);
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002289 }
Daniel Dunbar43235712010-07-18 18:54:11 +00002290
Rafael Espindola1134ab232011-06-05 02:43:45 +00002291 return false;
2292}
Daniel Dunbar43235712010-07-18 18:54:11 +00002293
Nico Weber2a8f9222014-07-24 16:29:04 +00002294MacroInstantiation::MacroInstantiation(SMLoc IL, int EB, SMLoc EL,
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002295 size_t CondStackDepth)
Rafael Espindolaf43a94e2014-08-17 22:48:55 +00002296 : InstantiationLoc(IL), ExitBuffer(EB), ExitLoc(EL),
Nico Weber155dccd12014-07-24 17:08:39 +00002297 CondStackDepth(CondStackDepth) {}
Daniel Dunbar43235712010-07-18 18:54:11 +00002298
Jim Grosbach4b905842013-09-20 23:08:21 +00002299static bool isOperator(AsmToken::TokenKind kind) {
2300 switch (kind) {
2301 default:
2302 return false;
2303 case AsmToken::Plus:
2304 case AsmToken::Minus:
2305 case AsmToken::Tilde:
2306 case AsmToken::Slash:
2307 case AsmToken::Star:
2308 case AsmToken::Dot:
2309 case AsmToken::Equal:
2310 case AsmToken::EqualEqual:
2311 case AsmToken::Pipe:
2312 case AsmToken::PipePipe:
2313 case AsmToken::Caret:
2314 case AsmToken::Amp:
2315 case AsmToken::AmpAmp:
2316 case AsmToken::Exclaim:
2317 case AsmToken::ExclaimEqual:
Jim Grosbach4b905842013-09-20 23:08:21 +00002318 case AsmToken::Less:
2319 case AsmToken::LessEqual:
2320 case AsmToken::LessLess:
2321 case AsmToken::LessGreater:
2322 case AsmToken::Greater:
2323 case AsmToken::GreaterEqual:
2324 case AsmToken::GreaterGreater:
2325 return true;
Preston Gurd05500642012-09-19 20:36:12 +00002326 }
2327}
2328
David Majnemer16252452014-01-29 00:07:39 +00002329namespace {
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002330
David Majnemer16252452014-01-29 00:07:39 +00002331class AsmLexerSkipSpaceRAII {
2332public:
2333 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
2334 Lexer.setSkipSpace(SkipSpace);
2335 }
2336
2337 ~AsmLexerSkipSpaceRAII() {
2338 Lexer.setSkipSpace(true);
2339 }
2340
2341private:
2342 AsmLexer &Lexer;
2343};
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002344
2345} // end anonymous namespace
David Majnemer16252452014-01-29 00:07:39 +00002346
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002347bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
2348
2349 if (Vararg) {
2350 if (Lexer.isNot(AsmToken::EndOfStatement)) {
2351 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002352 MA.emplace_back(AsmToken::String, Str);
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002353 }
2354 return false;
2355 }
2356
Rafael Espindola768b41c2012-06-15 14:02:34 +00002357 unsigned ParenLevel = 0;
Preston Gurd05500642012-09-19 20:36:12 +00002358
David Majnemer16252452014-01-29 00:07:39 +00002359 // Darwin doesn't use spaces to delmit arguments.
2360 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
Rafael Espindola768b41c2012-06-15 14:02:34 +00002361
Scott Egertona1fa68a2016-02-11 13:48:49 +00002362 bool SpaceEaten;
2363
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002364 while (true) {
Scott Egertona1fa68a2016-02-11 13:48:49 +00002365 SpaceEaten = false;
David Majnemer16252452014-01-29 00:07:39 +00002366 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002367 return TokError("unexpected token in macro instantiation");
Preston Gurd05500642012-09-19 20:36:12 +00002368
Scott Egertona1fa68a2016-02-11 13:48:49 +00002369 if (ParenLevel == 0) {
Preston Gurd05500642012-09-19 20:36:12 +00002370
Scott Egertona1fa68a2016-02-11 13:48:49 +00002371 if (Lexer.is(AsmToken::Comma))
2372 break;
2373
2374 if (Lexer.is(AsmToken::Space)) {
2375 SpaceEaten = true;
Nirav Dave1180e6892016-06-02 17:15:05 +00002376 Lexer.Lex(); // Eat spaces
Scott Egertona1fa68a2016-02-11 13:48:49 +00002377 }
Preston Gurd05500642012-09-19 20:36:12 +00002378
2379 // Spaces can delimit parameters, but could also be part an expression.
2380 // If the token after a space is an operator, add the token and the next
2381 // one into this argument
David Majnemer91fc4c22014-01-29 18:57:46 +00002382 if (!IsDarwin) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002383 if (isOperator(Lexer.getKind())) {
Scott Egertona1fa68a2016-02-11 13:48:49 +00002384 MA.push_back(getTok());
Nirav Dave1180e6892016-06-02 17:15:05 +00002385 Lexer.Lex();
Preston Gurd05500642012-09-19 20:36:12 +00002386
Scott Egertona1fa68a2016-02-11 13:48:49 +00002387 // Whitespace after an operator can be ignored.
2388 if (Lexer.is(AsmToken::Space))
Nirav Dave1180e6892016-06-02 17:15:05 +00002389 Lexer.Lex();
Scott Egertona1fa68a2016-02-11 13:48:49 +00002390
2391 continue;
Preston Gurd05500642012-09-19 20:36:12 +00002392 }
2393 }
Scott Egertona1fa68a2016-02-11 13:48:49 +00002394 if (SpaceEaten)
2395 break;
Preston Gurd05500642012-09-19 20:36:12 +00002396 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002397
Jim Grosbach4b905842013-09-20 23:08:21 +00002398 // handleMacroEntry relies on not advancing the lexer here
Rafael Espindola768b41c2012-06-15 14:02:34 +00002399 // to be able to fill in the remaining default parameter values
2400 if (Lexer.is(AsmToken::EndOfStatement))
2401 break;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002402
2403 // Adjust the current parentheses level.
2404 if (Lexer.is(AsmToken::LParen))
2405 ++ParenLevel;
2406 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
2407 --ParenLevel;
2408
2409 // Append the token to the current argument list.
2410 MA.push_back(getTok());
Nirav Dave1180e6892016-06-02 17:15:05 +00002411 Lexer.Lex();
Rafael Espindola768b41c2012-06-15 14:02:34 +00002412 }
Preston Gurd05500642012-09-19 20:36:12 +00002413
Rafael Espindola768b41c2012-06-15 14:02:34 +00002414 if (ParenLevel != 0)
Rafael Espindola3e5eb422012-08-21 15:55:04 +00002415 return TokError("unbalanced parentheses in macro argument");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002416 return false;
2417}
2418
2419// Parse the macro instantiation arguments.
Jim Grosbach4b905842013-09-20 23:08:21 +00002420bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
Vladimir Medic9bad0d332013-08-20 13:33:18 +00002421 MCAsmMacroArguments &A) {
Rafael Espindola768b41c2012-06-15 14:02:34 +00002422 const unsigned NParameters = M ? M->Parameters.size() : 0;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002423 bool NamedParametersFound = false;
2424 SmallVector<SMLoc, 4> FALocs;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002425
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002426 A.resize(NParameters);
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002427 FALocs.resize(NParameters);
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002428
Rafael Espindola768b41c2012-06-15 14:02:34 +00002429 // Parse two kinds of macro invocations:
2430 // - macros defined without any parameters accept an arbitrary number of them
2431 // - macros defined with parameters accept at most that many of them
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002432 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002433 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
2434 ++Parameter) {
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002435 SMLoc IDLoc = Lexer.getLoc();
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002436 MCAsmMacroParameter FA;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002437
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002438 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00002439 if (parseIdentifier(FA.Name))
2440 return Error(IDLoc, "invalid argument identifier for formal argument");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002441
Nirav Dave2364748a2016-09-16 18:30:20 +00002442 if (Lexer.isNot(AsmToken::Equal))
2443 return TokError("expected '=' after formal parameter identifier");
2444
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002445 Lex();
2446
2447 NamedParametersFound = true;
2448 }
2449
Nirav Dave2364748a2016-09-16 18:30:20 +00002450 if (NamedParametersFound && FA.Name.empty())
2451 return Error(IDLoc, "cannot mix positional and keyword arguments");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002452
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002453 bool Vararg = HasVararg && Parameter == (NParameters - 1);
2454 if (parseMacroArgument(FA.Value, Vararg))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002455 return true;
2456
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002457 unsigned PI = Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002458 if (!FA.Name.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002459 unsigned FAI = 0;
2460 for (FAI = 0; FAI < NParameters; ++FAI)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002461 if (M->Parameters[FAI].Name == FA.Name)
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002462 break;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002463
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002464 if (FAI >= NParameters) {
Nirav Davefd910412016-06-17 16:06:17 +00002465 assert(M && "expected macro to be defined");
Nirav Dave2364748a2016-09-16 18:30:20 +00002466 return Error(IDLoc, "parameter named '" + FA.Name +
2467 "' does not exist for macro '" + M->Name + "'");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002468 }
2469 PI = FAI;
2470 }
2471
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002472 if (!FA.Value.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002473 if (A.size() <= PI)
2474 A.resize(PI + 1);
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002475 A[PI] = FA.Value;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002476
2477 if (FALocs.size() <= PI)
2478 FALocs.resize(PI + 1);
2479
2480 FALocs[PI] = Lexer.getLoc();
Preston Gurd242ed3152012-09-19 20:29:04 +00002481 }
Jim Grosbach206661622012-07-30 22:44:17 +00002482
Preston Gurd242ed3152012-09-19 20:29:04 +00002483 // At the end of the statement, fill in remaining arguments that have
2484 // default values. If there aren't any, then the next argument is
2485 // required but missing
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002486 if (Lexer.is(AsmToken::EndOfStatement)) {
2487 bool Failure = false;
2488 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2489 if (A[FAI].empty()) {
2490 if (M->Parameters[FAI].Required) {
2491 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2492 "missing value for required parameter "
2493 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2494 Failure = true;
2495 }
2496
2497 if (!M->Parameters[FAI].Value.empty())
2498 A[FAI] = M->Parameters[FAI].Value;
2499 }
2500 }
2501 return Failure;
2502 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002503
2504 if (Lexer.is(AsmToken::Comma))
2505 Lex();
2506 }
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002507
2508 return TokError("too many positional arguments");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002509}
2510
Jim Grosbach4b905842013-09-20 23:08:21 +00002511const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002512 StringMap<MCAsmMacro>::iterator I = MacroMap.find(Name);
2513 return (I == MacroMap.end()) ? nullptr : &I->getValue();
Eli Bendersky38274122013-01-14 23:22:36 +00002514}
2515
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002516void AsmParser::defineMacro(StringRef Name, MCAsmMacro Macro) {
2517 MacroMap.insert(std::make_pair(Name, std::move(Macro)));
Eli Bendersky38274122013-01-14 23:22:36 +00002518}
2519
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002520void AsmParser::undefineMacro(StringRef Name) { MacroMap.erase(Name); }
Eli Bendersky38274122013-01-14 23:22:36 +00002521
Jim Grosbach4b905842013-09-20 23:08:21 +00002522bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
Davide Italiano7c9fc732016-07-27 05:51:56 +00002523 // Arbitrarily limit macro nesting depth (default matches 'as'). We can
2524 // eliminate this, although we should protect against infinite loops.
2525 unsigned MaxNestingDepth = AsmMacroMaxNestingDepth;
2526 if (ActiveMacros.size() == MaxNestingDepth) {
2527 std::ostringstream MaxNestingDepthError;
2528 MaxNestingDepthError << "macros cannot be nested more than "
2529 << MaxNestingDepth << " levels deep."
2530 << " Use -asm-macro-max-nesting-depth to increase "
2531 "this limit.";
2532 return TokError(MaxNestingDepthError.str());
2533 }
Daniel Dunbar43235712010-07-18 18:54:11 +00002534
Eli Bendersky38274122013-01-14 23:22:36 +00002535 MCAsmMacroArguments A;
Jim Grosbach4b905842013-09-20 23:08:21 +00002536 if (parseMacroArguments(M, A))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002537 return true;
Daniel Dunbar43235712010-07-18 18:54:11 +00002538
Rafael Espindola1134ab232011-06-05 02:43:45 +00002539 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2540 // to hold the macro body with substitutions.
2541 SmallString<256> Buf;
2542 StringRef Body = M->Body;
Rafael Espindola34b9c512012-06-03 23:57:14 +00002543 raw_svector_ostream OS(Buf);
Rafael Espindola1134ab232011-06-05 02:43:45 +00002544
Toma Tabacu217116e2015-04-27 10:50:29 +00002545 if (expandMacro(OS, Body, M->Parameters, A, true, getTok().getLoc()))
Rafael Espindola1134ab232011-06-05 02:43:45 +00002546 return true;
2547
Eli Bendersky38274122013-01-14 23:22:36 +00002548 // We include the .endmacro in the buffer as our cue to exit the macro
Rafael Espindola34b9c512012-06-03 23:57:14 +00002549 // instantiation.
2550 OS << ".endmacro\n";
2551
Rafael Espindola3560ff22014-08-27 20:03:13 +00002552 std::unique_ptr<MemoryBuffer> Instantiation =
2553 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola1134ab232011-06-05 02:43:45 +00002554
Daniel Dunbar43235712010-07-18 18:54:11 +00002555 // Create the macro instantiation object and add to the current macro
2556 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002557 MacroInstantiation *MI = new MacroInstantiation(
2558 NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Daniel Dunbar43235712010-07-18 18:54:11 +00002559 ActiveMacros.push_back(MI);
2560
Toma Tabacu217116e2015-04-27 10:50:29 +00002561 ++NumOfMacroInstantiations;
2562
Daniel Dunbar43235712010-07-18 18:54:11 +00002563 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00002564 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00002565 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar43235712010-07-18 18:54:11 +00002566 Lex();
2567
2568 return false;
2569}
2570
Jim Grosbach4b905842013-09-20 23:08:21 +00002571void AsmParser::handleMacroExit() {
Daniel Dunbar43235712010-07-18 18:54:11 +00002572 // Jump to the EndOfStatement we should return to, and consume it.
Jim Grosbach4b905842013-09-20 23:08:21 +00002573 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
Daniel Dunbar43235712010-07-18 18:54:11 +00002574 Lex();
2575
2576 // Pop the instantiation entry.
2577 delete ActiveMacros.back();
2578 ActiveMacros.pop_back();
2579}
2580
Jim Grosbach4b905842013-09-20 23:08:21 +00002581bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
Jim Grosbachb7b750d2012-09-13 23:11:31 +00002582 bool NoDeadStrip) {
Pete Cooper80d21cb2015-06-22 19:35:57 +00002583 MCSymbol *Sym;
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002584 const MCExpr *Value;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002585 if (MCParserUtils::parseAssignmentExpression(Name, allow_redef, *this, Sym,
2586 Value))
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002587 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002588
Pete Cooper80d21cb2015-06-22 19:35:57 +00002589 if (!Sym) {
2590 // In the case where we parse an expression starting with a '.', we will
2591 // not generate an error, nor will we create a symbol. In this case we
2592 // should just return out.
Anders Waldenborg84809572014-02-17 20:48:32 +00002593 return false;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002594 }
David Majnemer58cb80c2014-12-24 10:27:50 +00002595
Daniel Dunbarae7ac012009-06-29 23:43:14 +00002596 // Do the assignment.
Daniel Dunbarb7b20972009-08-31 08:09:09 +00002597 Out.EmitAssignment(Sym, Value);
Jim Grosbachb7b750d2012-09-13 23:11:31 +00002598 if (NoDeadStrip)
2599 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2600
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002601 return false;
2602}
2603
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002604/// parseIdentifier:
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002605/// ::= identifier
2606/// ::= string
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002607bool AsmParser::parseIdentifier(StringRef &Res) {
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002608 // The assembler has relaxed rules for accepting identifiers, in particular we
Hans Wennborgce69d772013-10-18 20:46:28 +00002609 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2610 // separate tokens. At this level, we have already lexed so we cannot (currently)
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002611 // handle this as a context dependent token, instead we detect adjacent tokens
2612 // and return the combined identifier.
Hans Wennborgce69d772013-10-18 20:46:28 +00002613 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2614 SMLoc PrefixLoc = getLexer().getLoc();
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002615
Hans Wennborgce69d772013-10-18 20:46:28 +00002616 // Consume the prefix character, and check for a following identifier.
Nirav Daved0463322016-10-12 13:58:07 +00002617
2618 AsmToken Buf[1];
2619 Lexer.peekTokens(Buf, false);
2620
2621 if (Buf[0].isNot(AsmToken::Identifier))
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002622 return true;
2623
Hans Wennborgce69d772013-10-18 20:46:28 +00002624 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
Nirav Daved0463322016-10-12 13:58:07 +00002625 if (PrefixLoc.getPointer() + 1 != Buf[0].getLoc().getPointer())
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002626 return true;
2627
Nirav Daved0463322016-10-12 13:58:07 +00002628 // eat $ or @
2629 Lexer.Lex(); // Lexer's Lex guarantees consecutive token.
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002630 // Construct the joined identifier and consume the token.
Jim Grosbach4b905842013-09-20 23:08:21 +00002631 Res =
Hans Wennborgce69d772013-10-18 20:46:28 +00002632 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
Nirav Davefd910412016-06-17 16:06:17 +00002633 Lex(); // Parser Lex to maintain invariants.
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002634 return false;
2635 }
2636
Jim Grosbach4b905842013-09-20 23:08:21 +00002637 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002638 return true;
2639
Sean Callanan936b0d32010-01-19 21:44:56 +00002640 Res = getTok().getIdentifier();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002641
Sean Callanan686ed8d2010-01-19 20:22:31 +00002642 Lex(); // Consume the identifier token.
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002643
2644 return false;
2645}
2646
Jim Grosbach4b905842013-09-20 23:08:21 +00002647/// parseDirectiveSet:
Nico Weber4ada0d92011-01-28 03:04:41 +00002648/// ::= .equ identifier ',' expression
2649/// ::= .equiv identifier ',' expression
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002650/// ::= .set identifier ',' expression
Jim Grosbach4b905842013-09-20 23:08:21 +00002651bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002652 StringRef Name;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002653 if (check(parseIdentifier(Name), "expected identifier") ||
2654 parseToken(AsmToken::Comma) || parseAssignment(Name, allow_redef, true))
2655 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
2656 return false;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002657}
2658
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002659bool AsmParser::parseEscapedString(std::string &Data) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00002660 if (check(getTok().isNot(AsmToken::String), "expected string"))
2661 return true;
Daniel Dunbaref668c12009-08-14 18:19:52 +00002662
2663 Data = "";
Sean Callanan936b0d32010-01-19 21:44:56 +00002664 StringRef Str = getTok().getStringContents();
Daniel Dunbaref668c12009-08-14 18:19:52 +00002665 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2666 if (Str[i] != '\\') {
2667 Data += Str[i];
2668 continue;
2669 }
2670
2671 // Recognize escaped characters. Note that this escape semantics currently
2672 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2673 ++i;
2674 if (i == e)
2675 return TokError("unexpected backslash at end of string");
2676
2677 // Recognize octal sequences.
Jim Grosbach4b905842013-09-20 23:08:21 +00002678 if ((unsigned)(Str[i] - '0') <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002679 // Consume up to three octal characters.
2680 unsigned Value = Str[i] - '0';
2681
Jim Grosbach4b905842013-09-20 23:08:21 +00002682 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002683 ++i;
2684 Value = Value * 8 + (Str[i] - '0');
2685
Jim Grosbach4b905842013-09-20 23:08:21 +00002686 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002687 ++i;
2688 Value = Value * 8 + (Str[i] - '0');
2689 }
2690 }
2691
2692 if (Value > 255)
2693 return TokError("invalid octal escape sequence (out of range)");
2694
Jim Grosbach4b905842013-09-20 23:08:21 +00002695 Data += (unsigned char)Value;
Daniel Dunbaref668c12009-08-14 18:19:52 +00002696 continue;
2697 }
2698
2699 // Otherwise recognize individual escapes.
2700 switch (Str[i]) {
2701 default:
2702 // Just reject invalid escape sequences for now.
2703 return TokError("invalid escape sequence (unrecognized character)");
2704
2705 case 'b': Data += '\b'; break;
2706 case 'f': Data += '\f'; break;
2707 case 'n': Data += '\n'; break;
2708 case 'r': Data += '\r'; break;
2709 case 't': Data += '\t'; break;
2710 case '"': Data += '"'; break;
2711 case '\\': Data += '\\'; break;
2712 }
2713 }
2714
Nirav Davea645433c2016-07-18 15:24:03 +00002715 Lex();
Daniel Dunbaref668c12009-08-14 18:19:52 +00002716 return false;
2717}
2718
Jim Grosbach4b905842013-09-20 23:08:21 +00002719/// parseDirectiveAscii:
Rafael Espindola63760ba2010-10-28 20:02:27 +00002720/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002721bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00002722 auto parseOp = [&]() -> bool {
2723 std::string Data;
2724 if (checkForValidSection() || parseEscapedString(Data))
Nirav Davef43cc9f2016-10-10 15:24:54 +00002725 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002726 getStreamer().EmitBytes(Data);
2727 if (ZeroTerminated)
2728 getStreamer().EmitBytes(StringRef("\0", 1));
2729 return false;
2730 };
Daniel Dunbare5444a82010-09-09 22:42:59 +00002731
Nirav Dave1a9044b2016-10-24 14:35:29 +00002732 if (parseMany(parseOp))
2733 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbara10e5192009-06-24 23:30:00 +00002734 return false;
2735}
2736
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002737/// parseDirectiveReloc
2738/// ::= .reloc expression , identifier [ , expression ]
2739bool AsmParser::parseDirectiveReloc(SMLoc DirectiveLoc) {
2740 const MCExpr *Offset;
2741 const MCExpr *Expr = nullptr;
2742
2743 SMLoc OffsetLoc = Lexer.getTok().getLoc();
Nirav Dave1a9044b2016-10-24 14:35:29 +00002744 int64_t OffsetValue;
2745 // We can only deal with constant expressions at the moment.
2746
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002747 if (parseExpression(Offset))
2748 return true;
2749
Nirav Davea645433c2016-07-18 15:24:03 +00002750 if (check(!Offset->evaluateAsAbsolute(OffsetValue), OffsetLoc,
2751 "expression is not a constant value") ||
2752 check(OffsetValue < 0, OffsetLoc, "expression is negative") ||
2753 parseToken(AsmToken::Comma, "expected comma") ||
2754 check(getTok().isNot(AsmToken::Identifier), "expected relocation name"))
2755 return true;
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002756
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002757 SMLoc NameLoc = Lexer.getTok().getLoc();
2758 StringRef Name = Lexer.getTok().getIdentifier();
Nirav Davefd910412016-06-17 16:06:17 +00002759 Lex();
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002760
2761 if (Lexer.is(AsmToken::Comma)) {
Nirav Davefd910412016-06-17 16:06:17 +00002762 Lex();
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002763 SMLoc ExprLoc = Lexer.getLoc();
2764 if (parseExpression(Expr))
2765 return true;
2766
2767 MCValue Value;
2768 if (!Expr->evaluateAsRelocatable(Value, nullptr, nullptr))
2769 return Error(ExprLoc, "expression must be relocatable");
2770 }
2771
Nirav Davea645433c2016-07-18 15:24:03 +00002772 if (parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00002773 "unexpected token in .reloc directive"))
2774 return true;
2775
2776 if (getStreamer().EmitRelocDirective(*Offset, Name, Expr, DirectiveLoc))
2777 return Error(NameLoc, "unknown relocation name");
2778
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002779 return false;
2780}
2781
Jim Grosbach4b905842013-09-20 23:08:21 +00002782/// parseDirectiveValue
Daniel Dunbara10e5192009-06-24 23:30:00 +00002783/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00002784bool AsmParser::parseDirectiveValue(StringRef IDVal, unsigned Size) {
2785 auto parseOp = [&]() -> bool {
2786 const MCExpr *Value;
2787 SMLoc ExprLoc = getLexer().getLoc();
2788 if (checkForValidSection() || parseExpression(Value))
Nirav Davef43cc9f2016-10-10 15:24:54 +00002789 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002790 // Special case constant expressions to match code generator.
2791 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2792 assert(Size <= 8 && "Invalid size");
2793 uint64_t IntValue = MCE->getValue();
2794 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2795 return Error(ExprLoc, "out of range literal value");
2796 getStreamer().EmitIntValue(IntValue, Size);
2797 } else
2798 getStreamer().EmitValue(Value, Size, ExprLoc);
2799 return false;
2800 };
Daniel Dunbare5444a82010-09-09 22:42:59 +00002801
Nirav Dave1a9044b2016-10-24 14:35:29 +00002802 if (parseMany(parseOp))
2803 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbara10e5192009-06-24 23:30:00 +00002804 return false;
2805}
2806
David Woodhoused6de0d92014-02-01 16:20:59 +00002807/// ParseDirectiveOctaValue
2808/// ::= .octa [ hexconstant (, hexconstant)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00002809
2810bool AsmParser::parseDirectiveOctaValue(StringRef IDVal) {
2811 auto parseOp = [&]() -> bool {
Nirav Davef43cc9f2016-10-10 15:24:54 +00002812 if (checkForValidSection())
2813 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002814 if (getTok().isNot(AsmToken::Integer) && getTok().isNot(AsmToken::BigNum))
2815 return TokError("unknown token in expression");
2816 SMLoc ExprLoc = getTok().getLoc();
2817 APInt IntValue = getTok().getAPIntVal();
2818 uint64_t hi, lo;
2819 Lex();
2820 if (!IntValue.isIntN(128))
2821 return Error(ExprLoc, "out of range literal value");
2822 if (!IntValue.isIntN(64)) {
2823 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
2824 lo = IntValue.getLoBits(64).getZExtValue();
2825 } else {
2826 hi = 0;
2827 lo = IntValue.getZExtValue();
David Woodhoused6de0d92014-02-01 16:20:59 +00002828 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00002829 if (MAI.isLittleEndian()) {
2830 getStreamer().EmitIntValue(lo, 8);
2831 getStreamer().EmitIntValue(hi, 8);
2832 } else {
2833 getStreamer().EmitIntValue(hi, 8);
2834 getStreamer().EmitIntValue(lo, 8);
2835 }
2836 return false;
2837 };
David Woodhoused6de0d92014-02-01 16:20:59 +00002838
Nirav Dave1a9044b2016-10-24 14:35:29 +00002839 if (parseMany(parseOp))
2840 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
David Woodhoused6de0d92014-02-01 16:20:59 +00002841 return false;
2842}
2843
Petr Hosek4cb08ce2016-09-23 19:25:15 +00002844bool AsmParser::parseRealValue(const fltSemantics &Semantics, APInt &Res) {
2845 // We don't truly support arithmetic on floating point expressions, so we
2846 // have to manually parse unary prefixes.
2847 bool IsNeg = false;
2848 if (getLexer().is(AsmToken::Minus)) {
2849 Lexer.Lex();
2850 IsNeg = true;
2851 } else if (getLexer().is(AsmToken::Plus))
2852 Lexer.Lex();
2853
2854 if (Lexer.is(AsmToken::Error))
2855 return TokError(Lexer.getErr());
2856 if (Lexer.isNot(AsmToken::Integer) && Lexer.isNot(AsmToken::Real) &&
2857 Lexer.isNot(AsmToken::Identifier))
2858 return TokError("unexpected token in directive");
2859
2860 // Convert to an APFloat.
2861 APFloat Value(Semantics);
2862 StringRef IDVal = getTok().getString();
2863 if (getLexer().is(AsmToken::Identifier)) {
2864 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2865 Value = APFloat::getInf(Semantics);
2866 else if (!IDVal.compare_lower("nan"))
2867 Value = APFloat::getNaN(Semantics, false, ~0);
2868 else
2869 return TokError("invalid floating point literal");
2870 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
2871 APFloat::opInvalidOp)
2872 return TokError("invalid floating point literal");
2873 if (IsNeg)
2874 Value.changeSign();
2875
2876 // Consume the numeric token.
2877 Lex();
2878
2879 Res = Value.bitcastToAPInt();
2880
2881 return false;
2882}
2883
Jim Grosbach4b905842013-09-20 23:08:21 +00002884/// parseDirectiveRealValue
Daniel Dunbar2af16532010-09-24 01:59:56 +00002885/// ::= (.single | .double) [ expression (, expression)* ]
Nirav Dave1a9044b2016-10-24 14:35:29 +00002886bool AsmParser::parseDirectiveRealValue(StringRef IDVal,
2887 const fltSemantics &Semantics) {
2888 auto parseOp = [&]() -> bool {
2889 APInt AsInt;
2890 if (checkForValidSection() || parseRealValue(Semantics, AsInt))
Nirav Davef43cc9f2016-10-10 15:24:54 +00002891 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002892 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
2893 AsInt.getBitWidth() / 8);
2894 return false;
2895 };
Daniel Dunbar2af16532010-09-24 01:59:56 +00002896
Nirav Dave1a9044b2016-10-24 14:35:29 +00002897 if (parseMany(parseOp))
2898 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
Daniel Dunbar2af16532010-09-24 01:59:56 +00002899 return false;
2900}
2901
Jim Grosbach4b905842013-09-20 23:08:21 +00002902/// parseDirectiveZero
Rafael Espindola922e3f42010-09-16 15:03:59 +00002903/// ::= .zero expression
Jim Grosbach4b905842013-09-20 23:08:21 +00002904bool AsmParser::parseDirectiveZero() {
Petr Hosek67a94a72016-05-28 05:57:48 +00002905 SMLoc NumBytesLoc = Lexer.getLoc();
2906 const MCExpr *NumBytes;
Nirav Davef43cc9f2016-10-10 15:24:54 +00002907 if (checkForValidSection() || parseExpression(NumBytes))
Rafael Espindola922e3f42010-09-16 15:03:59 +00002908 return true;
2909
Rafael Espindolab91bac62010-10-05 19:42:57 +00002910 int64_t Val = 0;
2911 if (getLexer().is(AsmToken::Comma)) {
2912 Lex();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002913 if (parseAbsoluteExpression(Val))
Rafael Espindolab91bac62010-10-05 19:42:57 +00002914 return true;
2915 }
2916
Nirav Davea645433c2016-07-18 15:24:03 +00002917 if (parseToken(AsmToken::EndOfStatement,
2918 "unexpected token in '.zero' directive"))
2919 return true;
Petr Hosek67a94a72016-05-28 05:57:48 +00002920 getStreamer().emitFill(*NumBytes, Val, NumBytesLoc);
Rafael Espindola922e3f42010-09-16 15:03:59 +00002921
2922 return false;
2923}
2924
Jim Grosbach4b905842013-09-20 23:08:21 +00002925/// parseDirectiveFill
Roman Divackye33098f2013-09-24 17:44:41 +00002926/// ::= .fill expression [ , expression [ , expression ] ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002927bool AsmParser::parseDirectiveFill() {
Petr Hosek67a94a72016-05-28 05:57:48 +00002928 SMLoc NumValuesLoc = Lexer.getLoc();
2929 const MCExpr *NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00002930 if (checkForValidSection() || parseExpression(NumValues))
Daniel Dunbara10e5192009-06-24 23:30:00 +00002931 return true;
2932
Roman Divackye33098f2013-09-24 17:44:41 +00002933 int64_t FillSize = 1;
2934 int64_t FillExpr = 0;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002935
David Majnemer522d3db2014-02-01 07:19:38 +00002936 SMLoc SizeLoc, ExprLoc;
Daniel Dunbara10e5192009-06-24 23:30:00 +00002937
Nirav Dave1a9044b2016-10-24 14:35:29 +00002938 if (parseOptionalToken(AsmToken::Comma)) {
2939 SizeLoc = getTok().getLoc();
2940 if (parseAbsoluteExpression(FillSize))
Roman Divackye33098f2013-09-24 17:44:41 +00002941 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002942 if (parseOptionalToken(AsmToken::Comma)) {
2943 ExprLoc = getTok().getLoc();
2944 if (parseAbsoluteExpression(FillExpr))
Roman Divackye33098f2013-09-24 17:44:41 +00002945 return true;
Roman Divackye33098f2013-09-24 17:44:41 +00002946 }
2947 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00002948 if (parseToken(AsmToken::EndOfStatement,
2949 "unexpected token in '.fill' directive"))
2950 return true;
Daniel Dunbara10e5192009-06-24 23:30:00 +00002951
David Majnemer522d3db2014-02-01 07:19:38 +00002952 if (FillSize < 0) {
2953 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
Petr Hosek6abd38b2016-05-28 08:20:08 +00002954 return false;
David Majnemer522d3db2014-02-01 07:19:38 +00002955 }
2956 if (FillSize > 8) {
2957 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
2958 FillSize = 8;
2959 }
Daniel Dunbara10e5192009-06-24 23:30:00 +00002960
David Majnemer522d3db2014-02-01 07:19:38 +00002961 if (!isUInt<32>(FillExpr) && FillSize > 4)
2962 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
2963
Petr Hosek67a94a72016-05-28 05:57:48 +00002964 getStreamer().emitFill(*NumValues, FillSize, FillExpr, NumValuesLoc);
Daniel Dunbara10e5192009-06-24 23:30:00 +00002965
2966 return false;
2967}
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002968
Jim Grosbach4b905842013-09-20 23:08:21 +00002969/// parseDirectiveOrg
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002970/// ::= .org expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002971bool AsmParser::parseDirectiveOrg() {
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002972 const MCExpr *Offset;
Oliver Stannard268f42f2016-12-14 10:43:58 +00002973 SMLoc OffsetLoc = Lexer.getLoc();
Nirav Davef43cc9f2016-10-10 15:24:54 +00002974 if (checkForValidSection() || parseExpression(Offset))
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002975 return true;
2976
2977 // Parse optional fill expression.
2978 int64_t FillExpr = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002979 if (parseOptionalToken(AsmToken::Comma))
2980 if (parseAbsoluteExpression(FillExpr))
2981 return addErrorSuffix(" in '.org' directive");
2982 if (parseToken(AsmToken::EndOfStatement))
2983 return addErrorSuffix(" in '.org' directive");
Nirav Davea645433c2016-07-18 15:24:03 +00002984
Oliver Stannard268f42f2016-12-14 10:43:58 +00002985 getStreamer().emitValueToOffset(Offset, FillExpr, OffsetLoc);
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002986 return false;
2987}
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002988
Jim Grosbach4b905842013-09-20 23:08:21 +00002989/// parseDirectiveAlign
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002990/// ::= {.align, ...} expression [ , expression [ , expression ]]
Jim Grosbach4b905842013-09-20 23:08:21 +00002991bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002992 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002993 int64_t Alignment;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002994 SMLoc MaxBytesLoc;
2995 bool HasFillExpr = false;
2996 int64_t FillExpr = 0;
2997 int64_t MaxBytesToFill = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00002998
2999 auto parseAlign = [&]() -> bool {
3000 if (checkForValidSection() || parseAbsoluteExpression(Alignment))
Nirav Davea645433c2016-07-18 15:24:03 +00003001 return true;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003002 if (parseOptionalToken(AsmToken::Comma)) {
3003 // The fill expression can be omitted while specifying a maximum number of
3004 // alignment bytes, e.g:
3005 // .align 3,,4
3006 if (getTok().isNot(AsmToken::Comma)) {
3007 HasFillExpr = true;
3008 if (parseAbsoluteExpression(FillExpr))
3009 return true;
3010 }
3011 if (parseOptionalToken(AsmToken::Comma))
3012 if (parseTokenLoc(MaxBytesLoc) ||
3013 parseAbsoluteExpression(MaxBytesToFill))
3014 return true;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003015 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003016 return parseToken(AsmToken::EndOfStatement);
3017 };
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003018
Nirav Dave1a9044b2016-10-24 14:35:29 +00003019 if (parseAlign())
3020 return addErrorSuffix(" in directive");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003021
Nirav Dave2364748a2016-09-16 18:30:20 +00003022 // Always emit an alignment here even if we thrown an error.
3023 bool ReturnVal = false;
3024
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003025 // Compute alignment in bytes.
3026 if (IsPow2) {
3027 // FIXME: Diagnose overflow.
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003028 if (Alignment >= 32) {
Nirav Dave2364748a2016-09-16 18:30:20 +00003029 ReturnVal |= Error(AlignmentLoc, "invalid alignment value");
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003030 Alignment = 31;
3031 }
3032
Benjamin Kramer63951ad2009-09-06 09:35:10 +00003033 Alignment = 1ULL << Alignment;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00003034 } else {
Davide Italianocb2da712015-09-08 18:59:47 +00003035 // Reject alignments that aren't either a power of two or zero,
3036 // for gas compatibility. Alignment of zero is silently rounded
3037 // up to one.
3038 if (Alignment == 0)
3039 Alignment = 1;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00003040 if (!isPowerOf2_64(Alignment))
Nirav Dave2364748a2016-09-16 18:30:20 +00003041 ReturnVal |= Error(AlignmentLoc, "alignment must be a power of 2");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003042 }
3043
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003044 // Diagnose non-sensical max bytes to align.
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003045 if (MaxBytesLoc.isValid()) {
3046 if (MaxBytesToFill < 1) {
Nirav Dave2364748a2016-09-16 18:30:20 +00003047 ReturnVal |= Error(MaxBytesLoc,
3048 "alignment directive can never be satisfied in this "
Jim Grosbach4b905842013-09-20 23:08:21 +00003049 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar4abcccb2009-08-21 23:01:53 +00003050 MaxBytesToFill = 0;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003051 }
3052
3053 if (MaxBytesToFill >= Alignment) {
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +00003054 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
Jim Grosbach4b905842013-09-20 23:08:21 +00003055 "has no effect");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003056 MaxBytesToFill = 0;
3057 }
3058 }
3059
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003060 // Check whether we should use optimal code alignment for this .align
3061 // directive.
Eric Christopher445c9522016-10-14 05:47:37 +00003062 const MCSection *Section = getStreamer().getCurrentSectionOnly();
Saleem Abdulrasool7f2f9f42014-03-21 05:13:23 +00003063 assert(Section && "must have section to emit alignment");
3064 bool UseCodeAlign = Section->UseCodeAlign();
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003065 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
3066 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003067 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003068 } else {
Kevin Enderby7f993022010-02-25 18:46:04 +00003069 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnerc2b36752010-07-15 21:19:31 +00003070 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
3071 MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003072 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003073
Nirav Dave2364748a2016-09-16 18:30:20 +00003074 return ReturnVal;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003075}
3076
Jim Grosbach4b905842013-09-20 23:08:21 +00003077/// parseDirectiveFile
Eli Bendersky17233942013-01-15 22:59:42 +00003078/// ::= .file [number] filename
3079/// ::= .file number directory filename
Jim Grosbach4b905842013-09-20 23:08:21 +00003080bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003081 // FIXME: I'm not sure what this is.
3082 int64_t FileNumber = -1;
3083 SMLoc FileNumberLoc = getLexer().getLoc();
3084 if (getLexer().is(AsmToken::Integer)) {
3085 FileNumber = getTok().getIntVal();
3086 Lex();
3087
3088 if (FileNumber < 1)
3089 return TokError("file number less than one");
3090 }
3091
Nirav Davea645433c2016-07-18 15:24:03 +00003092 std::string Path = getTok().getString();
Eli Bendersky17233942013-01-15 22:59:42 +00003093
3094 // Usually the directory and filename together, otherwise just the directory.
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003095 // Allow the strings to have escaped octal character sequence.
Nirav Davea645433c2016-07-18 15:24:03 +00003096 if (check(getTok().isNot(AsmToken::String),
3097 "unexpected token in '.file' directive") ||
3098 parseEscapedString(Path))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003099 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003100
3101 StringRef Directory;
3102 StringRef Filename;
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003103 std::string FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00003104 if (getLexer().is(AsmToken::String)) {
Nirav Davea645433c2016-07-18 15:24:03 +00003105 if (check(FileNumber == -1,
3106 "explicit path specified, but no file number") ||
3107 parseEscapedString(FilenameData))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003108 return true;
3109 Filename = FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00003110 Directory = Path;
Eli Bendersky17233942013-01-15 22:59:42 +00003111 } else {
3112 Filename = Path;
3113 }
3114
Nirav Davea645433c2016-07-18 15:24:03 +00003115 if (parseToken(AsmToken::EndOfStatement,
3116 "unexpected token in '.file' directive"))
3117 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003118
3119 if (FileNumber == -1)
3120 getStreamer().EmitFileDirective(Filename);
3121 else {
David Blaikie22748082016-05-26 00:22:26 +00003122 // If there is -g option as well as debug info from directive file,
3123 // we turn off -g option, directly use the existing debug info instead.
David Blaikiedc3f01e2015-03-09 01:57:13 +00003124 if (getContext().getGenDwarfForAssembly())
David Blaikie22748082016-05-26 00:22:26 +00003125 getContext().setGenDwarfForAssembly(false);
3126 else if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename) ==
David Blaikiec714ef42014-03-17 01:52:11 +00003127 0)
Nirav Dave2364748a2016-09-16 18:30:20 +00003128 return Error(FileNumberLoc, "file number already allocated");
Eli Bendersky17233942013-01-15 22:59:42 +00003129 }
3130
3131 return false;
3132}
3133
Jim Grosbach4b905842013-09-20 23:08:21 +00003134/// parseDirectiveLine
Eli Bendersky17233942013-01-15 22:59:42 +00003135/// ::= .line [number]
Jim Grosbach4b905842013-09-20 23:08:21 +00003136bool AsmParser::parseDirectiveLine() {
Nirav Davea645433c2016-07-18 15:24:03 +00003137 int64_t LineNumber;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003138 if (getLexer().is(AsmToken::Integer)) {
Nirav Davea645433c2016-07-18 15:24:03 +00003139 if (parseIntToken(LineNumber, "unexpected token in '.line' directive"))
3140 return true;
Jim Grosbach4b905842013-09-20 23:08:21 +00003141 (void)LineNumber;
Eli Bendersky17233942013-01-15 22:59:42 +00003142 // FIXME: Do something with the .line.
3143 }
Nirav Davea645433c2016-07-18 15:24:03 +00003144 if (parseToken(AsmToken::EndOfStatement,
3145 "unexpected token in '.line' directive"))
3146 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003147
3148 return false;
3149}
3150
Jim Grosbach4b905842013-09-20 23:08:21 +00003151/// parseDirectiveLoc
Eli Bendersky17233942013-01-15 22:59:42 +00003152/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
3153/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
3154/// The first number is a file number, must have been previously assigned with
3155/// a .file directive, the second number is the line number and optionally the
3156/// third number is a column position (zero if not specified). The remaining
3157/// optional items are .loc sub-directives.
Jim Grosbach4b905842013-09-20 23:08:21 +00003158bool AsmParser::parseDirectiveLoc() {
Nirav Davea645433c2016-07-18 15:24:03 +00003159 int64_t FileNumber = 0, LineNumber = 0;
3160 SMLoc Loc = getTok().getLoc();
3161 if (parseIntToken(FileNumber, "unexpected token in '.loc' directive") ||
3162 check(FileNumber < 1, Loc,
3163 "file number less than one in '.loc' directive") ||
3164 check(!getContext().isValidDwarfFileNumber(FileNumber), Loc,
3165 "unassigned file number in '.loc' directive"))
3166 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003167
Nirav Davea645433c2016-07-18 15:24:03 +00003168 // optional
Eli Bendersky17233942013-01-15 22:59:42 +00003169 if (getLexer().is(AsmToken::Integer)) {
3170 LineNumber = getTok().getIntVal();
Adrian Prantl6ac40032013-09-26 23:37:11 +00003171 if (LineNumber < 0)
3172 return TokError("line number less than zero in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003173 Lex();
3174 }
3175
3176 int64_t ColumnPos = 0;
3177 if (getLexer().is(AsmToken::Integer)) {
3178 ColumnPos = getTok().getIntVal();
3179 if (ColumnPos < 0)
3180 return TokError("column position less than zero in '.loc' directive");
3181 Lex();
3182 }
3183
3184 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
3185 unsigned Isa = 0;
3186 int64_t Discriminator = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003187
Nirav Dave1a9044b2016-10-24 14:35:29 +00003188 auto parseLocOp = [&]() -> bool {
3189 StringRef Name;
3190 SMLoc Loc = getTok().getLoc();
3191 if (parseIdentifier(Name))
3192 return TokError("unexpected token in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003193
Nirav Dave1a9044b2016-10-24 14:35:29 +00003194 if (Name == "basic_block")
3195 Flags |= DWARF2_FLAG_BASIC_BLOCK;
3196 else if (Name == "prologue_end")
3197 Flags |= DWARF2_FLAG_PROLOGUE_END;
3198 else if (Name == "epilogue_begin")
3199 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
3200 else if (Name == "is_stmt") {
3201 Loc = getTok().getLoc();
3202 const MCExpr *Value;
3203 if (parseExpression(Value))
3204 return true;
3205 // The expression must be the constant 0 or 1.
3206 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3207 int Value = MCE->getValue();
3208 if (Value == 0)
3209 Flags &= ~DWARF2_FLAG_IS_STMT;
3210 else if (Value == 1)
3211 Flags |= DWARF2_FLAG_IS_STMT;
3212 else
3213 return Error(Loc, "is_stmt value not 0 or 1");
Craig Topperf15655b2013-04-22 04:22:40 +00003214 } else {
Nirav Dave1a9044b2016-10-24 14:35:29 +00003215 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
Eli Bendersky17233942013-01-15 22:59:42 +00003216 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003217 } else if (Name == "isa") {
3218 Loc = getTok().getLoc();
3219 const MCExpr *Value;
3220 if (parseExpression(Value))
3221 return true;
3222 // The expression must be a constant greater or equal to 0.
3223 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3224 int Value = MCE->getValue();
3225 if (Value < 0)
3226 return Error(Loc, "isa number less than zero");
3227 Isa = Value;
3228 } else {
3229 return Error(Loc, "isa number not a constant value");
3230 }
3231 } else if (Name == "discriminator") {
3232 if (parseAbsoluteExpression(Discriminator))
3233 return true;
3234 } else {
3235 return Error(Loc, "unknown sub-directive in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003236 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003237 return false;
3238 };
3239
Nirav Davee2369aa2016-10-26 17:28:58 +00003240 if (parseMany(parseLocOp, false /*hasComma*/))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003241 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003242
3243 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
3244 Isa, Discriminator, StringRef());
3245
3246 return false;
3247}
3248
Jim Grosbach4b905842013-09-20 23:08:21 +00003249/// parseDirectiveStabs
Eli Bendersky17233942013-01-15 22:59:42 +00003250/// ::= .stabs string, number, number, number
Jim Grosbach4b905842013-09-20 23:08:21 +00003251bool AsmParser::parseDirectiveStabs() {
Eli Bendersky17233942013-01-15 22:59:42 +00003252 return TokError("unsupported directive '.stabs'");
3253}
3254
Reid Kleckner2214ed82016-01-29 00:49:42 +00003255/// parseDirectiveCVFile
3256/// ::= .cv_file number filename
3257bool AsmParser::parseDirectiveCVFile() {
Nirav Davea645433c2016-07-18 15:24:03 +00003258 SMLoc FileNumberLoc = getTok().getLoc();
3259 int64_t FileNumber;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003260 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00003261
3262 if (parseIntToken(FileNumber,
3263 "expected file number in '.cv_file' directive") ||
3264 check(FileNumber < 1, FileNumberLoc, "file number less than one") ||
3265 check(getTok().isNot(AsmToken::String),
3266 "unexpected token in '.cv_file' directive") ||
3267 // Usually directory and filename are together, otherwise just
3268 // directory. Allow the strings to have escaped octal character sequence.
3269 parseEscapedString(Filename) ||
3270 parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00003271 "unexpected token in '.cv_file' directive"))
Reid Klecknera5b1eef2016-08-26 17:58:37 +00003272 return true;
Nirav Dave1ab71992016-07-18 19:35:21 +00003273
Reid Klecknera5b1eef2016-08-26 17:58:37 +00003274 if (!getStreamer().EmitCVFileDirective(FileNumber, Filename))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003275 return Error(FileNumberLoc, "file number already allocated");
Reid Kleckner2214ed82016-01-29 00:49:42 +00003276
3277 return false;
3278}
3279
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003280bool AsmParser::parseCVFunctionId(int64_t &FunctionId,
3281 StringRef DirectiveName) {
3282 SMLoc Loc;
3283 return parseTokenLoc(Loc) ||
3284 parseIntToken(FunctionId, "expected function id in '" + DirectiveName +
3285 "' directive") ||
3286 check(FunctionId < 0 || FunctionId >= UINT_MAX, Loc,
3287 "expected function id within range [0, UINT_MAX)");
3288}
3289
3290bool AsmParser::parseCVFileId(int64_t &FileNumber, StringRef DirectiveName) {
3291 SMLoc Loc;
3292 return parseTokenLoc(Loc) ||
3293 parseIntToken(FileNumber, "expected integer in '" + DirectiveName +
3294 "' directive") ||
3295 check(FileNumber < 1, Loc, "file number less than one in '" +
3296 DirectiveName + "' directive") ||
3297 check(!getCVContext().isValidFileNumber(FileNumber), Loc,
3298 "unassigned file number in '" + DirectiveName + "' directive");
3299}
3300
3301/// parseDirectiveCVFuncId
3302/// ::= .cv_func_id FunctionId
3303///
3304/// Introduces a function ID that can be used with .cv_loc.
3305bool AsmParser::parseDirectiveCVFuncId() {
3306 SMLoc FunctionIdLoc = getTok().getLoc();
3307 int64_t FunctionId;
3308
3309 if (parseCVFunctionId(FunctionId, ".cv_func_id") ||
3310 parseToken(AsmToken::EndOfStatement,
3311 "unexpected token in '.cv_func_id' directive"))
3312 return true;
3313
3314 if (!getStreamer().EmitCVFuncIdDirective(FunctionId))
Nirav Dave1a9044b2016-10-24 14:35:29 +00003315 return Error(FunctionIdLoc, "function id already allocated");
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003316
3317 return false;
3318}
3319
3320/// parseDirectiveCVInlineSiteId
3321/// ::= .cv_inline_site_id FunctionId
3322/// "within" IAFunc
3323/// "inlined_at" IAFile IALine [IACol]
3324///
3325/// Introduces a function ID that can be used with .cv_loc. Includes "inlined
3326/// at" source location information for use in the line table of the caller,
3327/// whether the caller is a real function or another inlined call site.
3328bool AsmParser::parseDirectiveCVInlineSiteId() {
3329 SMLoc FunctionIdLoc = getTok().getLoc();
3330 int64_t FunctionId;
3331 int64_t IAFunc;
3332 int64_t IAFile;
3333 int64_t IALine;
3334 int64_t IACol = 0;
3335
3336 // FunctionId
3337 if (parseCVFunctionId(FunctionId, ".cv_inline_site_id"))
3338 return true;
3339
3340 // "within"
3341 if (check((getLexer().isNot(AsmToken::Identifier) ||
3342 getTok().getIdentifier() != "within"),
3343 "expected 'within' identifier in '.cv_inline_site_id' directive"))
3344 return true;
3345 Lex();
3346
3347 // IAFunc
3348 if (parseCVFunctionId(IAFunc, ".cv_inline_site_id"))
3349 return true;
3350
3351 // "inlined_at"
3352 if (check((getLexer().isNot(AsmToken::Identifier) ||
3353 getTok().getIdentifier() != "inlined_at"),
3354 "expected 'inlined_at' identifier in '.cv_inline_site_id' "
3355 "directive") )
3356 return true;
3357 Lex();
3358
3359 // IAFile IALine
3360 if (parseCVFileId(IAFile, ".cv_inline_site_id") ||
3361 parseIntToken(IALine, "expected line number after 'inlined_at'"))
3362 return true;
3363
3364 // [IACol]
3365 if (getLexer().is(AsmToken::Integer)) {
3366 IACol = getTok().getIntVal();
3367 Lex();
3368 }
3369
3370 if (parseToken(AsmToken::EndOfStatement,
3371 "unexpected token in '.cv_inline_site_id' directive"))
3372 return true;
3373
3374 if (!getStreamer().EmitCVInlineSiteIdDirective(FunctionId, IAFunc, IAFile,
3375 IALine, IACol, FunctionIdLoc))
Nirav Dave2364748a2016-09-16 18:30:20 +00003376 return Error(FunctionIdLoc, "function id already allocated");
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003377
3378 return false;
3379}
3380
Reid Kleckner2214ed82016-01-29 00:49:42 +00003381/// parseDirectiveCVLoc
3382/// ::= .cv_loc FunctionId FileNumber [LineNumber] [ColumnPos] [prologue_end]
3383/// [is_stmt VALUE]
3384/// The first number is a file number, must have been previously assigned with
3385/// a .file directive, the second number is the line number and optionally the
3386/// third number is a column position (zero if not specified). The remaining
3387/// optional items are .loc sub-directives.
3388bool AsmParser::parseDirectiveCVLoc() {
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003389 SMLoc DirectiveLoc = getTok().getLoc();
Nirav Davea645433c2016-07-18 15:24:03 +00003390 SMLoc Loc;
3391 int64_t FunctionId, FileNumber;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003392 if (parseCVFunctionId(FunctionId, ".cv_loc") ||
3393 parseCVFileId(FileNumber, ".cv_loc"))
Nirav Davea645433c2016-07-18 15:24:03 +00003394 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003395
3396 int64_t LineNumber = 0;
3397 if (getLexer().is(AsmToken::Integer)) {
3398 LineNumber = getTok().getIntVal();
3399 if (LineNumber < 0)
3400 return TokError("line number less than zero in '.cv_loc' directive");
3401 Lex();
3402 }
3403
3404 int64_t ColumnPos = 0;
3405 if (getLexer().is(AsmToken::Integer)) {
3406 ColumnPos = getTok().getIntVal();
3407 if (ColumnPos < 0)
3408 return TokError("column position less than zero in '.cv_loc' directive");
3409 Lex();
3410 }
3411
3412 bool PrologueEnd = false;
3413 uint64_t IsStmt = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003414
3415 auto parseOp = [&]() -> bool {
Reid Kleckner2214ed82016-01-29 00:49:42 +00003416 StringRef Name;
3417 SMLoc Loc = getTok().getLoc();
3418 if (parseIdentifier(Name))
3419 return TokError("unexpected token in '.cv_loc' directive");
Reid Kleckner2214ed82016-01-29 00:49:42 +00003420 if (Name == "prologue_end")
3421 PrologueEnd = true;
3422 else if (Name == "is_stmt") {
3423 Loc = getTok().getLoc();
3424 const MCExpr *Value;
3425 if (parseExpression(Value))
3426 return true;
3427 // The expression must be the constant 0 or 1.
3428 IsStmt = ~0ULL;
3429 if (const auto *MCE = dyn_cast<MCConstantExpr>(Value))
3430 IsStmt = MCE->getValue();
3431
3432 if (IsStmt > 1)
3433 return Error(Loc, "is_stmt value not 0 or 1");
3434 } else {
3435 return Error(Loc, "unknown sub-directive in '.cv_loc' directive");
3436 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00003437 return false;
3438 };
3439
3440 if (parseMany(parseOp, false /*hasComma*/))
3441 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003442
3443 getStreamer().EmitCVLocDirective(FunctionId, FileNumber, LineNumber,
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003444 ColumnPos, PrologueEnd, IsStmt, StringRef(),
3445 DirectiveLoc);
Reid Kleckner2214ed82016-01-29 00:49:42 +00003446 return false;
3447}
3448
3449/// parseDirectiveCVLinetable
3450/// ::= .cv_linetable FunctionId, FnStart, FnEnd
3451bool AsmParser::parseDirectiveCVLinetable() {
Nirav Davea645433c2016-07-18 15:24:03 +00003452 int64_t FunctionId;
3453 StringRef FnStartName, FnEndName;
3454 SMLoc Loc = getTok().getLoc();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003455 if (parseCVFunctionId(FunctionId, ".cv_linetable") ||
Nirav Davea645433c2016-07-18 15:24:03 +00003456 parseToken(AsmToken::Comma,
3457 "unexpected token in '.cv_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003458 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3459 "expected identifier in directive") ||
Nirav Davea645433c2016-07-18 15:24:03 +00003460 parseToken(AsmToken::Comma,
3461 "unexpected token in '.cv_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003462 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3463 "expected identifier in directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00003464 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003465
3466 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3467 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
3468
3469 getStreamer().EmitCVLinetableDirective(FunctionId, FnStartSym, FnEndSym);
3470 return false;
3471}
3472
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003473/// parseDirectiveCVInlineLinetable
David Majnemerc9911f22016-02-02 19:22:34 +00003474/// ::= .cv_inline_linetable PrimaryFunctionId FileId LineNum FnStart FnEnd
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003475bool AsmParser::parseDirectiveCVInlineLinetable() {
Nirav Davea645433c2016-07-18 15:24:03 +00003476 int64_t PrimaryFunctionId, SourceFileId, SourceLineNum;
3477 StringRef FnStartName, FnEndName;
3478 SMLoc Loc = getTok().getLoc();
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003479 if (parseCVFunctionId(PrimaryFunctionId, ".cv_inline_linetable") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003480 parseTokenLoc(Loc) ||
Nirav Davea645433c2016-07-18 15:24:03 +00003481 parseIntToken(
3482 SourceFileId,
3483 "expected SourceField in '.cv_inline_linetable' directive") ||
3484 check(SourceFileId <= 0, Loc,
3485 "File id less than zero in '.cv_inline_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003486 parseTokenLoc(Loc) ||
Nirav Davea645433c2016-07-18 15:24:03 +00003487 parseIntToken(
3488 SourceLineNum,
3489 "expected SourceLineNum in '.cv_inline_linetable' directive") ||
3490 check(SourceLineNum < 0, Loc,
3491 "Line number less than zero in '.cv_inline_linetable' directive") ||
Nirav Daved8858ca2016-08-30 14:15:43 +00003492 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3493 "expected identifier in directive") ||
3494 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3495 "expected identifier in directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00003496 return true;
David Majnemerc9911f22016-02-02 19:22:34 +00003497
Nirav Davea645433c2016-07-18 15:24:03 +00003498 if (parseToken(AsmToken::EndOfStatement, "Expected End of Statement"))
3499 return true;
3500
3501 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3502 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
Reid Kleckner1fcd6102016-02-02 17:41:18 +00003503 getStreamer().EmitCVInlineLinetableDirective(PrimaryFunctionId, SourceFileId,
3504 SourceLineNum, FnStartSym,
Reid Klecknera9f4cc92016-09-07 16:15:31 +00003505 FnEndSym);
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003506 return false;
3507}
3508
David Majnemer408b5e62016-02-05 01:55:49 +00003509/// parseDirectiveCVDefRange
3510/// ::= .cv_def_range RangeStart RangeEnd (GapStart GapEnd)*, bytes*
3511bool AsmParser::parseDirectiveCVDefRange() {
3512 SMLoc Loc;
3513 std::vector<std::pair<const MCSymbol *, const MCSymbol *>> Ranges;
3514 while (getLexer().is(AsmToken::Identifier)) {
3515 Loc = getLexer().getLoc();
3516 StringRef GapStartName;
3517 if (parseIdentifier(GapStartName))
3518 return Error(Loc, "expected identifier in directive");
3519 MCSymbol *GapStartSym = getContext().getOrCreateSymbol(GapStartName);
3520
3521 Loc = getLexer().getLoc();
3522 StringRef GapEndName;
3523 if (parseIdentifier(GapEndName))
3524 return Error(Loc, "expected identifier in directive");
3525 MCSymbol *GapEndSym = getContext().getOrCreateSymbol(GapEndName);
3526
3527 Ranges.push_back({GapStartSym, GapEndSym});
3528 }
3529
David Majnemer408b5e62016-02-05 01:55:49 +00003530 std::string FixedSizePortion;
Nirav Davea645433c2016-07-18 15:24:03 +00003531 if (parseToken(AsmToken::Comma, "unexpected token in directive") ||
3532 parseEscapedString(FixedSizePortion))
David Majnemer408b5e62016-02-05 01:55:49 +00003533 return true;
David Majnemer408b5e62016-02-05 01:55:49 +00003534
3535 getStreamer().EmitCVDefRangeDirective(Ranges, FixedSizePortion);
3536 return false;
3537}
3538
Reid Kleckner2214ed82016-01-29 00:49:42 +00003539/// parseDirectiveCVStringTable
3540/// ::= .cv_stringtable
3541bool AsmParser::parseDirectiveCVStringTable() {
3542 getStreamer().EmitCVStringTableDirective();
3543 return false;
3544}
3545
3546/// parseDirectiveCVFileChecksums
3547/// ::= .cv_filechecksums
3548bool AsmParser::parseDirectiveCVFileChecksums() {
3549 getStreamer().EmitCVFileChecksumsDirective();
3550 return false;
3551}
3552
Jim Grosbach4b905842013-09-20 23:08:21 +00003553/// parseDirectiveCFISections
Eli Bendersky17233942013-01-15 22:59:42 +00003554/// ::= .cfi_sections section [, section]
Jim Grosbach4b905842013-09-20 23:08:21 +00003555bool AsmParser::parseDirectiveCFISections() {
Eli Bendersky17233942013-01-15 22:59:42 +00003556 StringRef Name;
3557 bool EH = false;
3558 bool Debug = false;
3559
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003560 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003561 return TokError("Expected an identifier");
3562
3563 if (Name == ".eh_frame")
3564 EH = true;
3565 else if (Name == ".debug_frame")
3566 Debug = true;
3567
3568 if (getLexer().is(AsmToken::Comma)) {
3569 Lex();
3570
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003571 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003572 return TokError("Expected an identifier");
3573
3574 if (Name == ".eh_frame")
3575 EH = true;
3576 else if (Name == ".debug_frame")
3577 Debug = true;
3578 }
3579
3580 getStreamer().EmitCFISections(EH, Debug);
3581 return false;
3582}
3583
Jim Grosbach4b905842013-09-20 23:08:21 +00003584/// parseDirectiveCFIStartProc
David Majnemere035cf92014-01-27 17:20:25 +00003585/// ::= .cfi_startproc [simple]
Jim Grosbach4b905842013-09-20 23:08:21 +00003586bool AsmParser::parseDirectiveCFIStartProc() {
David Majnemere035cf92014-01-27 17:20:25 +00003587 StringRef Simple;
Nirav Dave1a9044b2016-10-24 14:35:29 +00003588 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
3589 if (check(parseIdentifier(Simple) || Simple != "simple",
3590 "unexpected token") ||
3591 parseToken(AsmToken::EndOfStatement))
3592 return addErrorSuffix(" in '.cfi_startproc' directive");
3593 }
Nirav Davea645433c2016-07-18 15:24:03 +00003594
Oliver Stannardcf6bfb12014-11-03 12:19:03 +00003595 getStreamer().EmitCFIStartProc(!Simple.empty());
Eli Bendersky17233942013-01-15 22:59:42 +00003596 return false;
3597}
3598
Jim Grosbach4b905842013-09-20 23:08:21 +00003599/// parseDirectiveCFIEndProc
Eli Bendersky17233942013-01-15 22:59:42 +00003600/// ::= .cfi_endproc
Jim Grosbach4b905842013-09-20 23:08:21 +00003601bool AsmParser::parseDirectiveCFIEndProc() {
Eli Bendersky17233942013-01-15 22:59:42 +00003602 getStreamer().EmitCFIEndProc();
3603 return false;
3604}
3605
Jim Grosbach4b905842013-09-20 23:08:21 +00003606/// \brief parse register name or number.
3607bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
Eli Bendersky17233942013-01-15 22:59:42 +00003608 SMLoc DirectiveLoc) {
3609 unsigned RegNo;
3610
3611 if (getLexer().isNot(AsmToken::Integer)) {
3612 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
3613 return true;
Bill Wendlingbc07a892013-06-18 07:20:20 +00003614 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
Eli Bendersky17233942013-01-15 22:59:42 +00003615 } else
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003616 return parseAbsoluteExpression(Register);
Eli Bendersky17233942013-01-15 22:59:42 +00003617
3618 return false;
3619}
3620
Jim Grosbach4b905842013-09-20 23:08:21 +00003621/// parseDirectiveCFIDefCfa
Eli Bendersky17233942013-01-15 22:59:42 +00003622/// ::= .cfi_def_cfa register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003623bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003624 int64_t Register = 0, Offset = 0;
3625 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3626 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3627 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003628 return true;
3629
3630 getStreamer().EmitCFIDefCfa(Register, Offset);
3631 return false;
3632}
3633
Jim Grosbach4b905842013-09-20 23:08:21 +00003634/// parseDirectiveCFIDefCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003635/// ::= .cfi_def_cfa_offset offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003636bool AsmParser::parseDirectiveCFIDefCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00003637 int64_t Offset = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003638 if (parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003639 return true;
3640
3641 getStreamer().EmitCFIDefCfaOffset(Offset);
3642 return false;
3643}
3644
Jim Grosbach4b905842013-09-20 23:08:21 +00003645/// parseDirectiveCFIRegister
Eli Bendersky17233942013-01-15 22:59:42 +00003646/// ::= .cfi_register register, register
Jim Grosbach4b905842013-09-20 23:08:21 +00003647bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003648 int64_t Register1 = 0, Register2 = 0;
3649 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc) ||
3650 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3651 parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003652 return true;
3653
3654 getStreamer().EmitCFIRegister(Register1, Register2);
3655 return false;
3656}
3657
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00003658/// parseDirectiveCFIWindowSave
3659/// ::= .cfi_window_save
3660bool AsmParser::parseDirectiveCFIWindowSave() {
3661 getStreamer().EmitCFIWindowSave();
3662 return false;
3663}
3664
Jim Grosbach4b905842013-09-20 23:08:21 +00003665/// parseDirectiveCFIAdjustCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003666/// ::= .cfi_adjust_cfa_offset adjustment
Jim Grosbach4b905842013-09-20 23:08:21 +00003667bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00003668 int64_t Adjustment = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003669 if (parseAbsoluteExpression(Adjustment))
Eli Bendersky17233942013-01-15 22:59:42 +00003670 return true;
3671
3672 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3673 return false;
3674}
3675
Jim Grosbach4b905842013-09-20 23:08:21 +00003676/// parseDirectiveCFIDefCfaRegister
Eli Bendersky17233942013-01-15 22:59:42 +00003677/// ::= .cfi_def_cfa_register register
Jim Grosbach4b905842013-09-20 23:08:21 +00003678bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003679 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003680 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003681 return true;
3682
3683 getStreamer().EmitCFIDefCfaRegister(Register);
3684 return false;
3685}
3686
Jim Grosbach4b905842013-09-20 23:08:21 +00003687/// parseDirectiveCFIOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003688/// ::= .cfi_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003689bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003690 int64_t Register = 0;
3691 int64_t Offset = 0;
3692
Nirav Davea645433c2016-07-18 15:24:03 +00003693 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3694 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3695 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003696 return true;
3697
3698 getStreamer().EmitCFIOffset(Register, Offset);
3699 return false;
3700}
3701
Jim Grosbach4b905842013-09-20 23:08:21 +00003702/// parseDirectiveCFIRelOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003703/// ::= .cfi_rel_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003704bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003705 int64_t Register = 0, Offset = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003706
Nirav Davea645433c2016-07-18 15:24:03 +00003707 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3708 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3709 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003710 return true;
3711
3712 getStreamer().EmitCFIRelOffset(Register, Offset);
3713 return false;
3714}
3715
3716static bool isValidEncoding(int64_t Encoding) {
3717 if (Encoding & ~0xff)
3718 return false;
3719
3720 if (Encoding == dwarf::DW_EH_PE_omit)
3721 return true;
3722
3723 const unsigned Format = Encoding & 0xf;
3724 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3725 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3726 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3727 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3728 return false;
3729
3730 const unsigned Application = Encoding & 0x70;
3731 if (Application != dwarf::DW_EH_PE_absptr &&
3732 Application != dwarf::DW_EH_PE_pcrel)
3733 return false;
3734
3735 return true;
3736}
3737
Jim Grosbach4b905842013-09-20 23:08:21 +00003738/// parseDirectiveCFIPersonalityOrLsda
Eli Bendersky17233942013-01-15 22:59:42 +00003739/// IsPersonality true for cfi_personality, false for cfi_lsda
3740/// ::= .cfi_personality encoding, [symbol_name]
3741/// ::= .cfi_lsda encoding, [symbol_name]
Jim Grosbach4b905842013-09-20 23:08:21 +00003742bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
Eli Bendersky17233942013-01-15 22:59:42 +00003743 int64_t Encoding = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003744 if (parseAbsoluteExpression(Encoding))
Eli Bendersky17233942013-01-15 22:59:42 +00003745 return true;
3746 if (Encoding == dwarf::DW_EH_PE_omit)
3747 return false;
3748
Eli Bendersky17233942013-01-15 22:59:42 +00003749 StringRef Name;
Nirav Davea645433c2016-07-18 15:24:03 +00003750 if (check(!isValidEncoding(Encoding), "unsupported encoding.") ||
3751 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3752 check(parseIdentifier(Name), "expected identifier in directive"))
3753 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003754
Jim Grosbach6f482002015-05-18 18:43:14 +00003755 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Eli Bendersky17233942013-01-15 22:59:42 +00003756
3757 if (IsPersonality)
3758 getStreamer().EmitCFIPersonality(Sym, Encoding);
3759 else
3760 getStreamer().EmitCFILsda(Sym, Encoding);
3761 return false;
3762}
3763
Jim Grosbach4b905842013-09-20 23:08:21 +00003764/// parseDirectiveCFIRememberState
Eli Bendersky17233942013-01-15 22:59:42 +00003765/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00003766bool AsmParser::parseDirectiveCFIRememberState() {
Eli Bendersky17233942013-01-15 22:59:42 +00003767 getStreamer().EmitCFIRememberState();
3768 return false;
3769}
3770
Jim Grosbach4b905842013-09-20 23:08:21 +00003771/// parseDirectiveCFIRestoreState
Eli Bendersky17233942013-01-15 22:59:42 +00003772/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00003773bool AsmParser::parseDirectiveCFIRestoreState() {
Eli Bendersky17233942013-01-15 22:59:42 +00003774 getStreamer().EmitCFIRestoreState();
3775 return false;
3776}
3777
Jim Grosbach4b905842013-09-20 23:08:21 +00003778/// parseDirectiveCFISameValue
Eli Bendersky17233942013-01-15 22:59:42 +00003779/// ::= .cfi_same_value register
Jim Grosbach4b905842013-09-20 23:08:21 +00003780bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003781 int64_t Register = 0;
3782
Jim Grosbach4b905842013-09-20 23:08:21 +00003783 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003784 return true;
3785
3786 getStreamer().EmitCFISameValue(Register);
3787 return false;
3788}
3789
Jim Grosbach4b905842013-09-20 23:08:21 +00003790/// parseDirectiveCFIRestore
Eli Bendersky17233942013-01-15 22:59:42 +00003791/// ::= .cfi_restore register
Jim Grosbach4b905842013-09-20 23:08:21 +00003792bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003793 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003794 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003795 return true;
3796
3797 getStreamer().EmitCFIRestore(Register);
3798 return false;
3799}
3800
Jim Grosbach4b905842013-09-20 23:08:21 +00003801/// parseDirectiveCFIEscape
Eli Bendersky17233942013-01-15 22:59:42 +00003802/// ::= .cfi_escape expression[,...]
Jim Grosbach4b905842013-09-20 23:08:21 +00003803bool AsmParser::parseDirectiveCFIEscape() {
Eli Bendersky17233942013-01-15 22:59:42 +00003804 std::string Values;
3805 int64_t CurrValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003806 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00003807 return true;
3808
3809 Values.push_back((uint8_t)CurrValue);
3810
3811 while (getLexer().is(AsmToken::Comma)) {
3812 Lex();
3813
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003814 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00003815 return true;
3816
3817 Values.push_back((uint8_t)CurrValue);
3818 }
3819
3820 getStreamer().EmitCFIEscape(Values);
3821 return false;
3822}
3823
Jim Grosbach4b905842013-09-20 23:08:21 +00003824/// parseDirectiveCFISignalFrame
Eli Bendersky17233942013-01-15 22:59:42 +00003825/// ::= .cfi_signal_frame
Jim Grosbach4b905842013-09-20 23:08:21 +00003826bool AsmParser::parseDirectiveCFISignalFrame() {
Nirav Davea645433c2016-07-18 15:24:03 +00003827 if (parseToken(AsmToken::EndOfStatement,
3828 "unexpected token in '.cfi_signal_frame'"))
3829 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003830
3831 getStreamer().EmitCFISignalFrame();
3832 return false;
3833}
3834
Jim Grosbach4b905842013-09-20 23:08:21 +00003835/// parseDirectiveCFIUndefined
Eli Bendersky17233942013-01-15 22:59:42 +00003836/// ::= .cfi_undefined register
Jim Grosbach4b905842013-09-20 23:08:21 +00003837bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003838 int64_t Register = 0;
3839
Jim Grosbach4b905842013-09-20 23:08:21 +00003840 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003841 return true;
3842
3843 getStreamer().EmitCFIUndefined(Register);
3844 return false;
3845}
3846
Jim Grosbach4b905842013-09-20 23:08:21 +00003847/// parseDirectiveMacrosOnOff
Eli Bendersky17233942013-01-15 22:59:42 +00003848/// ::= .macros_on
3849/// ::= .macros_off
Jim Grosbach4b905842013-09-20 23:08:21 +00003850bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
Nirav Davea645433c2016-07-18 15:24:03 +00003851 if (parseToken(AsmToken::EndOfStatement,
3852 "unexpected token in '" + Directive + "' directive"))
3853 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003854
Jim Grosbach4b905842013-09-20 23:08:21 +00003855 setMacrosEnabled(Directive == ".macros_on");
Eli Bendersky17233942013-01-15 22:59:42 +00003856 return false;
3857}
3858
Jim Grosbach4b905842013-09-20 23:08:21 +00003859/// parseDirectiveMacro
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00003860/// ::= .macro name[,] [parameters]
Jim Grosbach4b905842013-09-20 23:08:21 +00003861bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003862 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003863 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003864 return TokError("expected identifier in '.macro' directive");
3865
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00003866 if (getLexer().is(AsmToken::Comma))
3867 Lex();
3868
Eli Bendersky17233942013-01-15 22:59:42 +00003869 MCAsmMacroParameters Parameters;
David Majnemer91fc4c22014-01-29 18:57:46 +00003870 while (getLexer().isNot(AsmToken::EndOfStatement)) {
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003871
Alexander Kornienko8c0809c2015-01-15 11:41:30 +00003872 if (!Parameters.empty() && Parameters.back().Vararg)
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003873 return Error(Lexer.getLoc(),
3874 "Vararg parameter '" + Parameters.back().Name +
3875 "' should be last one in the list of parameters.");
3876
David Majnemer91fc4c22014-01-29 18:57:46 +00003877 MCAsmMacroParameter Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00003878 if (parseIdentifier(Parameter.Name))
David Majnemer91fc4c22014-01-29 18:57:46 +00003879 return TokError("expected identifier in '.macro' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003880
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003881 if (Lexer.is(AsmToken::Colon)) {
3882 Lex(); // consume ':'
3883
3884 SMLoc QualLoc;
3885 StringRef Qualifier;
3886
3887 QualLoc = Lexer.getLoc();
3888 if (parseIdentifier(Qualifier))
3889 return Error(QualLoc, "missing parameter qualifier for "
3890 "'" + Parameter.Name + "' in macro '" + Name + "'");
3891
3892 if (Qualifier == "req")
3893 Parameter.Required = true;
Kevin Enderbye3c13462014-08-04 23:14:37 +00003894 else if (Qualifier == "vararg")
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003895 Parameter.Vararg = true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003896 else
3897 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
3898 "for '" + Parameter.Name + "' in macro '" + Name + "'");
3899 }
3900
David Majnemer91fc4c22014-01-29 18:57:46 +00003901 if (getLexer().is(AsmToken::Equal)) {
3902 Lex();
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003903
3904 SMLoc ParamLoc;
3905
3906 ParamLoc = Lexer.getLoc();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003907 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
David Majnemer91fc4c22014-01-29 18:57:46 +00003908 return true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003909
3910 if (Parameter.Required)
3911 Warning(ParamLoc, "pointless default value for required parameter "
3912 "'" + Parameter.Name + "' in macro '" + Name + "'");
Eli Bendersky17233942013-01-15 22:59:42 +00003913 }
David Majnemer91fc4c22014-01-29 18:57:46 +00003914
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00003915 Parameters.push_back(std::move(Parameter));
David Majnemer91fc4c22014-01-29 18:57:46 +00003916
3917 if (getLexer().is(AsmToken::Comma))
3918 Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00003919 }
3920
Nirav Dave1180e6892016-06-02 17:15:05 +00003921 // Eat just the end of statement.
3922 Lexer.Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00003923
Nirav Dave1180e6892016-06-02 17:15:05 +00003924 // Consuming deferred text, so use Lexer.Lex to ignore Lexing Errors
Eli Bendersky17233942013-01-15 22:59:42 +00003925 AsmToken EndToken, StartToken = getTok();
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00003926 unsigned MacroDepth = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003927 // Lex the macro definition.
Eugene Zelenko33d7b762016-08-23 17:14:32 +00003928 while (true) {
Nirav Dave1180e6892016-06-02 17:15:05 +00003929 // Ignore Lexing errors in macros.
3930 while (Lexer.is(AsmToken::Error)) {
3931 Lexer.Lex();
3932 }
3933
Eli Bendersky17233942013-01-15 22:59:42 +00003934 // Check whether we have reached the end of the file.
3935 if (getLexer().is(AsmToken::Eof))
3936 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3937
3938 // Otherwise, check whether we have reach the .endmacro.
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00003939 if (getLexer().is(AsmToken::Identifier)) {
3940 if (getTok().getIdentifier() == ".endm" ||
3941 getTok().getIdentifier() == ".endmacro") {
3942 if (MacroDepth == 0) { // Outermost macro.
3943 EndToken = getTok();
Nirav Dave1180e6892016-06-02 17:15:05 +00003944 Lexer.Lex();
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00003945 if (getLexer().isNot(AsmToken::EndOfStatement))
3946 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3947 "' directive");
3948 break;
3949 } else {
3950 // Otherwise we just found the end of an inner macro.
3951 --MacroDepth;
3952 }
3953 } else if (getTok().getIdentifier() == ".macro") {
3954 // We allow nested macros. Those aren't instantiated until the outermost
3955 // macro is expanded so just ignore them for now.
3956 ++MacroDepth;
3957 }
Eli Bendersky17233942013-01-15 22:59:42 +00003958 }
3959
3960 // Otherwise, scan til the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003961 eatToEndOfStatement();
Eli Bendersky17233942013-01-15 22:59:42 +00003962 }
3963
Jim Grosbach4b905842013-09-20 23:08:21 +00003964 if (lookupMacro(Name)) {
Eli Bendersky17233942013-01-15 22:59:42 +00003965 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3966 }
3967
3968 const char *BodyStart = StartToken.getLoc().getPointer();
3969 const char *BodyEnd = EndToken.getLoc().getPointer();
3970 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Jim Grosbach4b905842013-09-20 23:08:21 +00003971 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00003972 defineMacro(Name, MCAsmMacro(Name, Body, std::move(Parameters)));
Eli Bendersky17233942013-01-15 22:59:42 +00003973 return false;
3974}
3975
Jim Grosbach4b905842013-09-20 23:08:21 +00003976/// checkForBadMacro
Kevin Enderby81c944c2013-01-22 21:44:53 +00003977///
3978/// With the support added for named parameters there may be code out there that
3979/// is transitioning from positional parameters. In versions of gas that did
Alp Tokercb402912014-01-24 17:20:08 +00003980/// not support named parameters they would be ignored on the macro definition.
Kevin Enderby81c944c2013-01-22 21:44:53 +00003981/// But to support both styles of parameters this is not possible so if a macro
Alp Tokercb402912014-01-24 17:20:08 +00003982/// definition has named parameters but does not use them and has what appears
Kevin Enderby81c944c2013-01-22 21:44:53 +00003983/// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3984/// warning that the positional parameter found in body which have no effect.
3985/// Hoping the developer will either remove the named parameters from the macro
Alp Tokercb402912014-01-24 17:20:08 +00003986/// definition so the positional parameters get used if that was what was
Kevin Enderby81c944c2013-01-22 21:44:53 +00003987/// intended or change the macro to use the named parameters. It is possible
3988/// this warning will trigger when the none of the named parameters are used
3989/// and the strings like $1 are infact to simply to be passed trough unchanged.
Jim Grosbach4b905842013-09-20 23:08:21 +00003990void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
Kevin Enderby81c944c2013-01-22 21:44:53 +00003991 StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00003992 ArrayRef<MCAsmMacroParameter> Parameters) {
Kevin Enderby81c944c2013-01-22 21:44:53 +00003993 // If this macro is not defined with named parameters the warning we are
3994 // checking for here doesn't apply.
3995 unsigned NParameters = Parameters.size();
3996 if (NParameters == 0)
3997 return;
3998
3999 bool NamedParametersFound = false;
4000 bool PositionalParametersFound = false;
4001
4002 // Look at the body of the macro for use of both the named parameters and what
4003 // are likely to be positional parameters. This is what expandMacro() is
4004 // doing when it finds the parameters in the body.
4005 while (!Body.empty()) {
4006 // Scan for the next possible parameter.
4007 std::size_t End = Body.size(), Pos = 0;
4008 for (; Pos != End; ++Pos) {
4009 // Check for a substitution or escape.
4010 // This macro is defined with parameters, look for \foo, \bar, etc.
4011 if (Body[Pos] == '\\' && Pos + 1 != End)
4012 break;
4013
4014 // This macro should have parameters, but look for $0, $1, ..., $n too.
4015 if (Body[Pos] != '$' || Pos + 1 == End)
4016 continue;
4017 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00004018 if (Next == '$' || Next == 'n' ||
4019 isdigit(static_cast<unsigned char>(Next)))
Kevin Enderby81c944c2013-01-22 21:44:53 +00004020 break;
4021 }
4022
4023 // Check if we reached the end.
4024 if (Pos == End)
4025 break;
4026
4027 if (Body[Pos] == '$') {
Jim Grosbach4b905842013-09-20 23:08:21 +00004028 switch (Body[Pos + 1]) {
4029 // $$ => $
Kevin Enderby81c944c2013-01-22 21:44:53 +00004030 case '$':
4031 break;
4032
Jim Grosbach4b905842013-09-20 23:08:21 +00004033 // $n => number of arguments
Kevin Enderby81c944c2013-01-22 21:44:53 +00004034 case 'n':
4035 PositionalParametersFound = true;
4036 break;
4037
Jim Grosbach4b905842013-09-20 23:08:21 +00004038 // $[0-9] => argument
Kevin Enderby81c944c2013-01-22 21:44:53 +00004039 default: {
4040 PositionalParametersFound = true;
4041 break;
Jim Grosbach4b905842013-09-20 23:08:21 +00004042 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00004043 }
4044 Pos += 2;
4045 } else {
4046 unsigned I = Pos + 1;
4047 while (isIdentifierChar(Body[I]) && I + 1 != End)
4048 ++I;
4049
Jim Grosbach4b905842013-09-20 23:08:21 +00004050 const char *Begin = Body.data() + Pos + 1;
4051 StringRef Argument(Begin, I - (Pos + 1));
Kevin Enderby81c944c2013-01-22 21:44:53 +00004052 unsigned Index = 0;
4053 for (; Index < NParameters; ++Index)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00004054 if (Parameters[Index].Name == Argument)
Kevin Enderby81c944c2013-01-22 21:44:53 +00004055 break;
4056
4057 if (Index == NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00004058 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
4059 Pos += 3;
4060 else {
4061 Pos = I;
4062 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00004063 } else {
4064 NamedParametersFound = true;
4065 Pos += 1 + Argument.size();
4066 }
4067 }
4068 // Update the scan point.
4069 Body = Body.substr(Pos);
4070 }
4071
4072 if (!NamedParametersFound && PositionalParametersFound)
4073 Warning(DirectiveLoc, "macro defined with named parameters which are not "
4074 "used in macro body, possible positional parameter "
4075 "found in body which will have no effect");
4076}
4077
Nico Weber155dccd12014-07-24 17:08:39 +00004078/// parseDirectiveExitMacro
4079/// ::= .exitm
4080bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
Nirav Davea645433c2016-07-18 15:24:03 +00004081 if (parseToken(AsmToken::EndOfStatement,
4082 "unexpected token in '" + Directive + "' directive"))
4083 return true;
Nico Weber155dccd12014-07-24 17:08:39 +00004084
4085 if (!isInsideMacroInstantiation())
4086 return TokError("unexpected '" + Directive + "' in file, "
4087 "no current macro definition");
4088
4089 // Exit all conditionals that are active in the current macro.
4090 while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
4091 TheCondState = TheCondStack.back();
4092 TheCondStack.pop_back();
4093 }
4094
4095 handleMacroExit();
4096 return false;
4097}
4098
Jim Grosbach4b905842013-09-20 23:08:21 +00004099/// parseDirectiveEndMacro
Eli Bendersky17233942013-01-15 22:59:42 +00004100/// ::= .endm
4101/// ::= .endmacro
Jim Grosbach4b905842013-09-20 23:08:21 +00004102bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
Eli Bendersky17233942013-01-15 22:59:42 +00004103 if (getLexer().isNot(AsmToken::EndOfStatement))
4104 return TokError("unexpected token in '" + Directive + "' directive");
4105
4106 // If we are inside a macro instantiation, terminate the current
4107 // instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00004108 if (isInsideMacroInstantiation()) {
4109 handleMacroExit();
Eli Bendersky17233942013-01-15 22:59:42 +00004110 return false;
4111 }
4112
4113 // Otherwise, this .endmacro is a stray entry in the file; well formed
4114 // .endmacro directives are handled during the macro definition parsing.
4115 return TokError("unexpected '" + Directive + "' in file, "
Jim Grosbach4b905842013-09-20 23:08:21 +00004116 "no current macro definition");
Eli Bendersky17233942013-01-15 22:59:42 +00004117}
4118
Jim Grosbach4b905842013-09-20 23:08:21 +00004119/// parseDirectivePurgeMacro
Eli Bendersky17233942013-01-15 22:59:42 +00004120/// ::= .purgem
Jim Grosbach4b905842013-09-20 23:08:21 +00004121bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004122 StringRef Name;
Nirav Davea645433c2016-07-18 15:24:03 +00004123 SMLoc Loc;
Nirav Daved8858ca2016-08-30 14:15:43 +00004124 if (parseTokenLoc(Loc) ||
4125 check(parseIdentifier(Name), Loc,
4126 "expected identifier in '.purgem' directive") ||
Nirav Davea645433c2016-07-18 15:24:03 +00004127 parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00004128 "unexpected token in '.purgem' directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00004129 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004130
Nirav Dave1ab71992016-07-18 19:35:21 +00004131 if (!lookupMacro(Name))
4132 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
4133
Jim Grosbach4b905842013-09-20 23:08:21 +00004134 undefineMacro(Name);
Eli Bendersky17233942013-01-15 22:59:42 +00004135 return false;
4136}
Eli Benderskyf483ff92012-12-20 19:05:53 +00004137
Jim Grosbach4b905842013-09-20 23:08:21 +00004138/// parseDirectiveBundleAlignMode
Eli Benderskyf483ff92012-12-20 19:05:53 +00004139/// ::= {.bundle_align_mode} expression
Jim Grosbach4b905842013-09-20 23:08:21 +00004140bool AsmParser::parseDirectiveBundleAlignMode() {
Eli Benderskyf483ff92012-12-20 19:05:53 +00004141 // Expect a single argument: an expression that evaluates to a constant
4142 // in the inclusive range 0-30.
4143 SMLoc ExprLoc = getLexer().getLoc();
4144 int64_t AlignSizePow2;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004145 if (checkForValidSection() || parseAbsoluteExpression(AlignSizePow2) ||
Nirav Davea645433c2016-07-18 15:24:03 +00004146 parseToken(AsmToken::EndOfStatement, "unexpected token after expression "
4147 "in '.bundle_align_mode' "
4148 "directive") ||
4149 check(AlignSizePow2 < 0 || AlignSizePow2 > 30, ExprLoc,
4150 "invalid bundle alignment size (expected between 0 and 30)"))
Eli Benderskyf483ff92012-12-20 19:05:53 +00004151 return true;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004152
4153 // Because of AlignSizePow2's verified range we can safely truncate it to
4154 // unsigned.
4155 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
4156 return false;
4157}
4158
Jim Grosbach4b905842013-09-20 23:08:21 +00004159/// parseDirectiveBundleLock
Eli Bendersky802b6282013-01-07 21:51:08 +00004160/// ::= {.bundle_lock} [align_to_end]
Jim Grosbach4b905842013-09-20 23:08:21 +00004161bool AsmParser::parseDirectiveBundleLock() {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004162 if (checkForValidSection())
4163 return true;
Eli Bendersky802b6282013-01-07 21:51:08 +00004164 bool AlignToEnd = false;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004165
Nirav Dave1a9044b2016-10-24 14:35:29 +00004166 StringRef Option;
4167 SMLoc Loc = getTok().getLoc();
4168 const char *kInvalidOptionError =
4169 "invalid option for '.bundle_lock' directive";
Eli Bendersky802b6282013-01-07 21:51:08 +00004170
Nirav Dave1a9044b2016-10-24 14:35:29 +00004171 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
Nirav Davea645433c2016-07-18 15:24:03 +00004172 if (check(parseIdentifier(Option), Loc, kInvalidOptionError) ||
4173 check(Option != "align_to_end", Loc, kInvalidOptionError) ||
Nirav Dave1a9044b2016-10-24 14:35:29 +00004174 parseToken(AsmToken::EndOfStatement,
4175 "unexpected token after '.bundle_lock' directive option"))
Nirav Davea645433c2016-07-18 15:24:03 +00004176 return true;
Eli Bendersky802b6282013-01-07 21:51:08 +00004177 AlignToEnd = true;
4178 }
4179
Eli Bendersky802b6282013-01-07 21:51:08 +00004180 getStreamer().EmitBundleLock(AlignToEnd);
Eli Benderskyf483ff92012-12-20 19:05:53 +00004181 return false;
4182}
4183
Jim Grosbach4b905842013-09-20 23:08:21 +00004184/// parseDirectiveBundleLock
Eli Benderskyf483ff92012-12-20 19:05:53 +00004185/// ::= {.bundle_lock}
Jim Grosbach4b905842013-09-20 23:08:21 +00004186bool AsmParser::parseDirectiveBundleUnlock() {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004187 if (checkForValidSection() ||
4188 parseToken(AsmToken::EndOfStatement,
Nirav Davea645433c2016-07-18 15:24:03 +00004189 "unexpected token in '.bundle_unlock' directive"))
4190 return true;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004191
4192 getStreamer().EmitBundleUnlock();
4193 return false;
4194}
4195
Jim Grosbach4b905842013-09-20 23:08:21 +00004196/// parseDirectiveSpace
Eli Bendersky17233942013-01-15 22:59:42 +00004197/// ::= (.skip | .space) expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004198bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
Eli Bendersky17233942013-01-15 22:59:42 +00004199
Petr Hosek67a94a72016-05-28 05:57:48 +00004200 SMLoc NumBytesLoc = Lexer.getLoc();
4201 const MCExpr *NumBytes;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004202 if (checkForValidSection() || parseExpression(NumBytes))
Eli Bendersky17233942013-01-15 22:59:42 +00004203 return true;
4204
4205 int64_t FillExpr = 0;
Nirav Dave1a9044b2016-10-24 14:35:29 +00004206 if (parseOptionalToken(AsmToken::Comma))
4207 if (parseAbsoluteExpression(FillExpr))
4208 return addErrorSuffix("in '" + Twine(IDVal) + "' directive");
4209 if (parseToken(AsmToken::EndOfStatement))
4210 return addErrorSuffix("in '" + Twine(IDVal) + "' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00004211
Eli Bendersky17233942013-01-15 22:59:42 +00004212 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
Petr Hosek67a94a72016-05-28 05:57:48 +00004213 getStreamer().emitFill(*NumBytes, FillExpr, NumBytesLoc);
Eli Bendersky17233942013-01-15 22:59:42 +00004214
4215 return false;
4216}
4217
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004218/// parseDirectiveDCB
4219/// ::= .dcb.{b, l, w} expression, expression
4220bool AsmParser::parseDirectiveDCB(StringRef IDVal, unsigned Size) {
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004221 SMLoc NumValuesLoc = Lexer.getLoc();
4222 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004223 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004224 return true;
4225
4226 if (NumValues < 0) {
4227 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4228 return false;
4229 }
4230
4231 if (parseToken(AsmToken::Comma,
4232 "unexpected token in '" + Twine(IDVal) + "' directive"))
4233 return true;
4234
4235 const MCExpr *Value;
4236 SMLoc ExprLoc = getLexer().getLoc();
4237 if (parseExpression(Value))
4238 return true;
4239
4240 // Special case constant expressions to match code generator.
4241 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
4242 assert(Size <= 8 && "Invalid size");
4243 uint64_t IntValue = MCE->getValue();
4244 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
4245 return Error(ExprLoc, "literal value out of range for directive");
4246 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4247 getStreamer().EmitIntValue(IntValue, Size);
4248 } else {
4249 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4250 getStreamer().EmitValue(Value, Size, ExprLoc);
4251 }
4252
4253 if (parseToken(AsmToken::EndOfStatement,
4254 "unexpected token in '" + Twine(IDVal) + "' directive"))
4255 return true;
4256
4257 return false;
4258}
4259
4260/// parseDirectiveRealDCB
4261/// ::= .dcb.{d, s} expression, expression
4262bool AsmParser::parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &Semantics) {
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004263 SMLoc NumValuesLoc = Lexer.getLoc();
4264 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004265 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004266 return true;
4267
4268 if (NumValues < 0) {
4269 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4270 return false;
4271 }
4272
4273 if (parseToken(AsmToken::Comma,
4274 "unexpected token in '" + Twine(IDVal) + "' directive"))
4275 return true;
4276
4277 APInt AsInt;
4278 if (parseRealValue(Semantics, AsInt))
4279 return true;
4280
4281 if (parseToken(AsmToken::EndOfStatement,
4282 "unexpected token in '" + Twine(IDVal) + "' directive"))
4283 return true;
4284
4285 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4286 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
4287 AsInt.getBitWidth() / 8);
4288
4289 return false;
4290}
4291
Petr Hosek85b2f672016-09-23 21:53:36 +00004292/// parseDirectiveDS
4293/// ::= .ds.{b, d, l, p, s, w, x} expression
4294bool AsmParser::parseDirectiveDS(StringRef IDVal, unsigned Size) {
Petr Hosek85b2f672016-09-23 21:53:36 +00004295
4296 SMLoc NumValuesLoc = Lexer.getLoc();
4297 int64_t NumValues;
Nirav Davef43cc9f2016-10-10 15:24:54 +00004298 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
Petr Hosek85b2f672016-09-23 21:53:36 +00004299 return true;
4300
4301 if (NumValues < 0) {
4302 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4303 return false;
4304 }
4305
4306 if (parseToken(AsmToken::EndOfStatement,
4307 "unexpected token in '" + Twine(IDVal) + "' directive"))
4308 return true;
4309
4310 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4311 getStreamer().emitFill(Size, 0);
4312
4313 return false;
4314}
4315
Jim Grosbach4b905842013-09-20 23:08:21 +00004316/// parseDirectiveLEB128
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004317/// ::= (.sleb128 | .uleb128) [ expression (, expression)* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004318bool AsmParser::parseDirectiveLEB128(bool Signed) {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004319 if (checkForValidSection())
4320 return true;
4321
Nirav Dave1a9044b2016-10-24 14:35:29 +00004322 auto parseOp = [&]() -> bool {
4323 const MCExpr *Value;
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004324 if (parseExpression(Value))
4325 return true;
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004326 if (Signed)
4327 getStreamer().EmitSLEB128Value(Value);
4328 else
4329 getStreamer().EmitULEB128Value(Value);
Nirav Dave1a9044b2016-10-24 14:35:29 +00004330 return false;
4331 };
Eli Bendersky17233942013-01-15 22:59:42 +00004332
Nirav Dave1a9044b2016-10-24 14:35:29 +00004333 if (parseMany(parseOp))
4334 return addErrorSuffix(" in directive");
Eli Bendersky17233942013-01-15 22:59:42 +00004335
4336 return false;
4337}
4338
Jim Grosbach4b905842013-09-20 23:08:21 +00004339/// parseDirectiveSymbolAttribute
Daniel Dunbara5508c82009-06-30 00:33:19 +00004340/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004341bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00004342 auto parseOp = [&]() -> bool {
4343 StringRef Name;
4344 SMLoc Loc = getTok().getLoc();
4345 if (parseIdentifier(Name))
4346 return Error(Loc, "expected identifier");
4347 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004348
Nirav Dave1a9044b2016-10-24 14:35:29 +00004349 // Assembler local symbols don't make any sense here. Complain loudly.
4350 if (Sym->isTemporary())
4351 return Error(Loc, "non-local symbol required");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004352
Nirav Dave1a9044b2016-10-24 14:35:29 +00004353 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
4354 return Error(Loc, "unable to emit symbol attribute");
4355 return false;
4356 };
Daniel Dunbara5508c82009-06-30 00:33:19 +00004357
Nirav Dave1a9044b2016-10-24 14:35:29 +00004358 if (parseMany(parseOp))
4359 return addErrorSuffix(" in directive");
Jan Wen Voungc7682872010-09-30 01:09:20 +00004360 return false;
Daniel Dunbara5508c82009-06-30 00:33:19 +00004361}
Chris Lattnera1e11f52009-07-07 20:30:46 +00004362
Jim Grosbach4b905842013-09-20 23:08:21 +00004363/// parseDirectiveComm
Chris Lattner28ad7542009-07-09 17:25:12 +00004364/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004365bool AsmParser::parseDirectiveComm(bool IsLocal) {
Nirav Davef43cc9f2016-10-10 15:24:54 +00004366 if (checkForValidSection())
4367 return true;
Daniel Dunbare5444a82010-09-09 22:42:59 +00004368
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004369 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004370 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004371 if (parseIdentifier(Name))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004372 return TokError("expected identifier in directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004373
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +00004374 // Handle the identifier as the key symbol.
Jim Grosbach6f482002015-05-18 18:43:14 +00004375 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Chris Lattnera1e11f52009-07-07 20:30:46 +00004376
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004377 if (getLexer().isNot(AsmToken::Comma))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004378 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00004379 Lex();
Chris Lattnera1e11f52009-07-07 20:30:46 +00004380
4381 int64_t Size;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004382 SMLoc SizeLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004383 if (parseAbsoluteExpression(Size))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004384 return true;
4385
4386 int64_t Pow2Alignment = 0;
4387 SMLoc Pow2AlignmentLoc;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004388 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan686ed8d2010-01-19 20:22:31 +00004389 Lex();
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004390 Pow2AlignmentLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004391 if (parseAbsoluteExpression(Pow2Alignment))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004392 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00004393
Benjamin Kramer68b9f052012-09-07 21:08:01 +00004394 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
4395 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00004396 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
4397
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00004398 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramer68b9f052012-09-07 21:08:01 +00004399 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
4400 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00004401 if (!isPowerOf2_64(Pow2Alignment))
4402 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
4403 Pow2Alignment = Log2_64(Pow2Alignment);
4404 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00004405 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00004406
Nirav Dave1a9044b2016-10-24 14:35:29 +00004407 if (parseToken(AsmToken::EndOfStatement,
4408 "unexpected token in '.comm' or '.lcomm' directive"))
4409 return true;
Chris Lattnera1e11f52009-07-07 20:30:46 +00004410
Chris Lattner28ad7542009-07-09 17:25:12 +00004411 // NOTE: a size of zero for a .comm should create a undefined symbol
4412 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattnera1e11f52009-07-07 20:30:46 +00004413 if (Size < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00004414 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
Jim Grosbach4b905842013-09-20 23:08:21 +00004415 "be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00004416
Eric Christopherbc818852010-05-14 01:38:54 +00004417 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattnera1e11f52009-07-07 20:30:46 +00004418 // may internally end up wanting an alignment in bytes.
4419 // FIXME: Diagnose overflow.
4420 if (Pow2Alignment < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00004421 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
Jim Grosbach4b905842013-09-20 23:08:21 +00004422 "alignment, can't be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00004423
Rafael Espindola13a79bb2017-02-02 21:26:06 +00004424 Sym->redefineIfPossible();
Daniel Dunbar6860ac72009-08-22 07:22:36 +00004425 if (!Sym->isUndefined())
Chris Lattnera1e11f52009-07-07 20:30:46 +00004426 return Error(IDLoc, "invalid symbol redefinition");
4427
Chris Lattner28ad7542009-07-09 17:25:12 +00004428 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00004429 if (IsLocal) {
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00004430 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00004431 return false;
4432 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00004433
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004434 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattnera1e11f52009-07-07 20:30:46 +00004435 return false;
4436}
Chris Lattner07cadaf2009-07-10 22:20:30 +00004437
Jim Grosbach4b905842013-09-20 23:08:21 +00004438/// parseDirectiveAbort
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004439/// ::= .abort [... message ...]
Jim Grosbach4b905842013-09-20 23:08:21 +00004440bool AsmParser::parseDirectiveAbort() {
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004441 // FIXME: Use loc from directive.
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004442 SMLoc Loc = getLexer().getLoc();
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004443
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004444 StringRef Str = parseStringToEndOfStatement();
Nirav Davea645433c2016-07-18 15:24:03 +00004445 if (parseToken(AsmToken::EndOfStatement,
4446 "unexpected token in '.abort' directive"))
4447 return true;
Kevin Enderby56523ce2009-07-13 23:15:14 +00004448
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004449 if (Str.empty())
Nirav Dave2364748a2016-09-16 18:30:20 +00004450 return Error(Loc, ".abort detected. Assembly stopping.");
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004451 else
Nirav Dave2364748a2016-09-16 18:30:20 +00004452 return Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004453 // FIXME: Actually abort assembly here.
Kevin Enderby56523ce2009-07-13 23:15:14 +00004454
4455 return false;
4456}
Kevin Enderbycbe475d2009-07-14 21:35:03 +00004457
Jim Grosbach4b905842013-09-20 23:08:21 +00004458/// parseDirectiveInclude
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004459/// ::= .include "filename"
Jim Grosbach4b905842013-09-20 23:08:21 +00004460bool AsmParser::parseDirectiveInclude() {
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004461 // Allow the strings to have escaped octal character sequence.
4462 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00004463 SMLoc IncludeLoc = getTok().getLoc();
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004464
Nirav Davea645433c2016-07-18 15:24:03 +00004465 if (check(getTok().isNot(AsmToken::String),
4466 "expected string in '.include' directive") ||
4467 parseEscapedString(Filename) ||
4468 check(getTok().isNot(AsmToken::EndOfStatement),
4469 "unexpected token in '.include' directive") ||
4470 // Attempt to switch the lexer to the included file before consuming the
4471 // end of statement to avoid losing it when we switch.
4472 check(enterIncludeFile(Filename), IncludeLoc,
4473 "Could not find include file '" + Filename + "'"))
Chris Lattner693fbb82009-07-16 06:14:39 +00004474 return true;
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004475
4476 return false;
4477}
Kevin Enderby09ea5702009-07-15 15:30:11 +00004478
Jim Grosbach4b905842013-09-20 23:08:21 +00004479/// parseDirectiveIncbin
Petr Hosek2f4ac442016-09-23 00:41:06 +00004480/// ::= .incbin "filename" [ , skip [ , count ] ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004481bool AsmParser::parseDirectiveIncbin() {
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004482 // Allow the strings to have escaped octal character sequence.
4483 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00004484 SMLoc IncbinLoc = getTok().getLoc();
4485 if (check(getTok().isNot(AsmToken::String),
4486 "expected string in '.incbin' directive") ||
Petr Hosek2f4ac442016-09-23 00:41:06 +00004487 parseEscapedString(Filename))
4488 return true;
4489
4490 int64_t Skip = 0;
4491 const MCExpr *Count = nullptr;
4492 SMLoc SkipLoc, CountLoc;
Nirav Dave1a9044b2016-10-24 14:35:29 +00004493 if (parseOptionalToken(AsmToken::Comma)) {
Petr Hosek2f4ac442016-09-23 00:41:06 +00004494 // The skip expression can be omitted while specifying the count, e.g:
4495 // .incbin "filename",,4
4496 if (getTok().isNot(AsmToken::Comma)) {
4497 if (parseTokenLoc(SkipLoc) || parseAbsoluteExpression(Skip))
4498 return true;
4499 }
Nirav Dave1a9044b2016-10-24 14:35:29 +00004500 if (parseOptionalToken(AsmToken::Comma)) {
4501 CountLoc = getTok().getLoc();
4502 if (parseExpression(Count))
Petr Hosek2f4ac442016-09-23 00:41:06 +00004503 return true;
4504 }
4505 }
4506
4507 if (parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00004508 "unexpected token in '.incbin' directive"))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004509 return true;
Nirav Dave1ab71992016-07-18 19:35:21 +00004510
Petr Hosek2f4ac442016-09-23 00:41:06 +00004511 if (check(Skip < 0, SkipLoc, "skip is negative"))
4512 return true;
4513
Nirav Dave1ab71992016-07-18 19:35:21 +00004514 // Attempt to process the included file.
Petr Hosek2f4ac442016-09-23 00:41:06 +00004515 if (processIncbinFile(Filename, Skip, Count, CountLoc))
Nirav Dave1ab71992016-07-18 19:35:21 +00004516 return Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
Kevin Enderby109f25c2011-12-14 21:47:48 +00004517 return false;
4518}
4519
Jim Grosbach4b905842013-09-20 23:08:21 +00004520/// parseDirectiveIf
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004521/// ::= .if{,eq,ge,gt,le,lt,ne} expression
4522bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004523 TheCondStack.push_back(TheCondState);
4524 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004525 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004526 eatToEndOfStatement();
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004527 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004528 int64_t ExprValue;
Nirav Davea645433c2016-07-18 15:24:03 +00004529 if (parseAbsoluteExpression(ExprValue) ||
4530 parseToken(AsmToken::EndOfStatement,
4531 "unexpected token in '.if' directive"))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004532 return true;
4533
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004534 switch (DirKind) {
4535 default:
4536 llvm_unreachable("unsupported directive");
4537 case DK_IF:
4538 case DK_IFNE:
4539 break;
4540 case DK_IFEQ:
4541 ExprValue = ExprValue == 0;
4542 break;
4543 case DK_IFGE:
4544 ExprValue = ExprValue >= 0;
4545 break;
4546 case DK_IFGT:
4547 ExprValue = ExprValue > 0;
4548 break;
4549 case DK_IFLE:
4550 ExprValue = ExprValue <= 0;
4551 break;
4552 case DK_IFLT:
4553 ExprValue = ExprValue < 0;
4554 break;
4555 }
4556
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004557 TheCondState.CondMet = ExprValue;
4558 TheCondState.Ignore = !TheCondState.CondMet;
4559 }
4560
4561 return false;
4562}
4563
Jim Grosbach4b905842013-09-20 23:08:21 +00004564/// parseDirectiveIfb
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004565/// ::= .ifb string
Jim Grosbach4b905842013-09-20 23:08:21 +00004566bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004567 TheCondStack.push_back(TheCondState);
4568 TheCondState.TheCond = AsmCond::IfCond;
4569
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004570 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004571 eatToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004572 } else {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004573 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004574
Nirav Davea645433c2016-07-18 15:24:03 +00004575 if (parseToken(AsmToken::EndOfStatement,
4576 "unexpected token in '.ifb' directive"))
4577 return true;
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004578
4579 TheCondState.CondMet = ExpectBlank == Str.empty();
4580 TheCondState.Ignore = !TheCondState.CondMet;
4581 }
4582
4583 return false;
4584}
4585
Jim Grosbach4b905842013-09-20 23:08:21 +00004586/// parseDirectiveIfc
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004587/// ::= .ifc string1, string2
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00004588/// ::= .ifnc string1, string2
Jim Grosbach4b905842013-09-20 23:08:21 +00004589bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004590 TheCondStack.push_back(TheCondState);
4591 TheCondState.TheCond = AsmCond::IfCond;
4592
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004593 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004594 eatToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004595 } else {
Jim Grosbach4b905842013-09-20 23:08:21 +00004596 StringRef Str1 = parseStringToComma();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004597
Nirav Davea645433c2016-07-18 15:24:03 +00004598 if (parseToken(AsmToken::Comma, "unexpected token in '.ifc' directive"))
4599 return true;
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004600
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004601 StringRef Str2 = parseStringToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004602
Nirav Davea645433c2016-07-18 15:24:03 +00004603 if (parseToken(AsmToken::EndOfStatement,
4604 "unexpected token in '.ifc' directive"))
4605 return true;
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004606
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00004607 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004608 TheCondState.Ignore = !TheCondState.CondMet;
4609 }
4610
4611 return false;
4612}
4613
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004614/// parseDirectiveIfeqs
4615/// ::= .ifeqs string1, string2
Sid Manning51c35602015-03-18 14:20:54 +00004616bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual) {
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004617 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00004618 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00004619 return TokError("expected string parameter for '.ifeqs' directive");
4620 return TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004621 }
4622
4623 StringRef String1 = getTok().getStringContents();
4624 Lex();
4625
4626 if (Lexer.isNot(AsmToken::Comma)) {
Sid Manning51c35602015-03-18 14:20:54 +00004627 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00004628 return TokError(
4629 "expected comma after first string for '.ifeqs' directive");
4630 return TokError("expected comma after first string for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004631 }
4632
4633 Lex();
4634
4635 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00004636 if (ExpectEqual)
Nirav Dave2364748a2016-09-16 18:30:20 +00004637 return TokError("expected string parameter for '.ifeqs' directive");
4638 return TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004639 }
4640
4641 StringRef String2 = getTok().getStringContents();
4642 Lex();
4643
4644 TheCondStack.push_back(TheCondState);
4645 TheCondState.TheCond = AsmCond::IfCond;
Sid Manning51c35602015-03-18 14:20:54 +00004646 TheCondState.CondMet = ExpectEqual == (String1 == String2);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004647 TheCondState.Ignore = !TheCondState.CondMet;
4648
4649 return false;
4650}
4651
Jim Grosbach4b905842013-09-20 23:08:21 +00004652/// parseDirectiveIfdef
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004653/// ::= .ifdef symbol
Jim Grosbach4b905842013-09-20 23:08:21 +00004654bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004655 StringRef Name;
4656 TheCondStack.push_back(TheCondState);
4657 TheCondState.TheCond = AsmCond::IfCond;
4658
4659 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004660 eatToEndOfStatement();
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004661 } else {
Nirav Davea645433c2016-07-18 15:24:03 +00004662 if (check(parseIdentifier(Name), "expected identifier after '.ifdef'") ||
4663 parseToken(AsmToken::EndOfStatement, "unexpected token in '.ifdef'"))
4664 return true;
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004665
Jim Grosbach6f482002015-05-18 18:43:14 +00004666 MCSymbol *Sym = getContext().lookupSymbol(Name);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004667
4668 if (expect_defined)
Craig Topper353eda42014-04-24 06:44:33 +00004669 TheCondState.CondMet = (Sym && !Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004670 else
Craig Topper353eda42014-04-24 06:44:33 +00004671 TheCondState.CondMet = (!Sym || Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004672 TheCondState.Ignore = !TheCondState.CondMet;
4673 }
4674
4675 return false;
4676}
4677
Jim Grosbach4b905842013-09-20 23:08:21 +00004678/// parseDirectiveElseIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004679/// ::= .elseif expression
Jim Grosbach4b905842013-09-20 23:08:21 +00004680bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004681 if (TheCondState.TheCond != AsmCond::IfCond &&
4682 TheCondState.TheCond != AsmCond::ElseIfCond)
Nirav Dave2364748a2016-09-16 18:30:20 +00004683 return Error(DirectiveLoc, "Encountered a .elseif that doesn't follow an"
4684 " .if or an .elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004685 TheCondState.TheCond = AsmCond::ElseIfCond;
4686
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004687 bool LastIgnoreState = false;
4688 if (!TheCondStack.empty())
Craig Topper2172ad62013-04-22 04:24:02 +00004689 LastIgnoreState = TheCondStack.back().Ignore;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004690 if (LastIgnoreState || TheCondState.CondMet) {
4691 TheCondState.Ignore = true;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004692 eatToEndOfStatement();
Craig Topperf15655b2013-04-22 04:22:40 +00004693 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004694 int64_t ExprValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004695 if (parseAbsoluteExpression(ExprValue))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004696 return true;
4697
Nirav Dave1a9044b2016-10-24 14:35:29 +00004698 if (parseToken(AsmToken::EndOfStatement,
4699 "unexpected token in '.elseif' directive"))
4700 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00004701
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004702 TheCondState.CondMet = ExprValue;
4703 TheCondState.Ignore = !TheCondState.CondMet;
4704 }
4705
4706 return false;
4707}
4708
Jim Grosbach4b905842013-09-20 23:08:21 +00004709/// parseDirectiveElse
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004710/// ::= .else
Jim Grosbach4b905842013-09-20 23:08:21 +00004711bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00004712 if (parseToken(AsmToken::EndOfStatement,
4713 "unexpected token in '.else' directive"))
4714 return true;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004715
4716 if (TheCondState.TheCond != AsmCond::IfCond &&
4717 TheCondState.TheCond != AsmCond::ElseIfCond)
Nirav Dave2364748a2016-09-16 18:30:20 +00004718 return Error(DirectiveLoc, "Encountered a .else that doesn't follow "
4719 " an .if or an .elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004720 TheCondState.TheCond = AsmCond::ElseCond;
4721 bool LastIgnoreState = false;
4722 if (!TheCondStack.empty())
4723 LastIgnoreState = TheCondStack.back().Ignore;
4724 if (LastIgnoreState || TheCondState.CondMet)
4725 TheCondState.Ignore = true;
4726 else
4727 TheCondState.Ignore = false;
4728
4729 return false;
4730}
4731
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004732/// parseDirectiveEnd
4733/// ::= .end
4734bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00004735 if (parseToken(AsmToken::EndOfStatement,
4736 "unexpected token in '.end' directive"))
4737 return true;
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004738
4739 while (Lexer.isNot(AsmToken::Eof))
Nirav Dave1a9044b2016-10-24 14:35:29 +00004740 Lexer.Lex();
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004741
4742 return false;
4743}
4744
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004745/// parseDirectiveError
4746/// ::= .err
4747/// ::= .error [string]
4748bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
4749 if (!TheCondStack.empty()) {
4750 if (TheCondStack.back().Ignore) {
4751 eatToEndOfStatement();
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004752 return false;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004753 }
4754 }
4755
4756 if (!WithMessage)
4757 return Error(L, ".err encountered");
4758
4759 StringRef Message = ".error directive invoked in source file";
4760 if (Lexer.isNot(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00004761 if (Lexer.isNot(AsmToken::String))
4762 return TokError(".error argument must be a string");
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004763
4764 Message = getTok().getStringContents();
4765 Lex();
4766 }
4767
Nirav Dave2364748a2016-09-16 18:30:20 +00004768 return Error(L, Message);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004769}
4770
Nico Weber404012b2014-07-24 16:26:06 +00004771/// parseDirectiveWarning
4772/// ::= .warning [string]
4773bool AsmParser::parseDirectiveWarning(SMLoc L) {
4774 if (!TheCondStack.empty()) {
4775 if (TheCondStack.back().Ignore) {
4776 eatToEndOfStatement();
4777 return false;
4778 }
4779 }
4780
4781 StringRef Message = ".warning directive invoked in source file";
Nirav Dave1a9044b2016-10-24 14:35:29 +00004782
4783 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00004784 if (Lexer.isNot(AsmToken::String))
4785 return TokError(".warning argument must be a string");
Nico Weber404012b2014-07-24 16:26:06 +00004786
4787 Message = getTok().getStringContents();
4788 Lex();
Nirav Dave1a9044b2016-10-24 14:35:29 +00004789 if (parseToken(AsmToken::EndOfStatement,
4790 "expected end of statement in '.warning' directive"))
4791 return true;
Nico Weber404012b2014-07-24 16:26:06 +00004792 }
4793
Nirav Dave2364748a2016-09-16 18:30:20 +00004794 return Warning(L, Message);
Nico Weber404012b2014-07-24 16:26:06 +00004795}
4796
Jim Grosbach4b905842013-09-20 23:08:21 +00004797/// parseDirectiveEndIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004798/// ::= .endif
Jim Grosbach4b905842013-09-20 23:08:21 +00004799bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00004800 if (parseToken(AsmToken::EndOfStatement,
4801 "unexpected token in '.endif' directive"))
4802 return true;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004803
Jim Grosbach4b905842013-09-20 23:08:21 +00004804 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
Nirav Dave2364748a2016-09-16 18:30:20 +00004805 return Error(DirectiveLoc, "Encountered a .endif that doesn't follow "
4806 "an .if or .else");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004807 if (!TheCondStack.empty()) {
4808 TheCondState = TheCondStack.back();
4809 TheCondStack.pop_back();
4810 }
4811
4812 return false;
4813}
Daniel Dunbara4b069c2009-08-11 04:24:50 +00004814
Eli Bendersky17233942013-01-15 22:59:42 +00004815void AsmParser::initializeDirectiveKindMap() {
4816 DirectiveKindMap[".set"] = DK_SET;
4817 DirectiveKindMap[".equ"] = DK_EQU;
4818 DirectiveKindMap[".equiv"] = DK_EQUIV;
4819 DirectiveKindMap[".ascii"] = DK_ASCII;
4820 DirectiveKindMap[".asciz"] = DK_ASCIZ;
4821 DirectiveKindMap[".string"] = DK_STRING;
4822 DirectiveKindMap[".byte"] = DK_BYTE;
4823 DirectiveKindMap[".short"] = DK_SHORT;
4824 DirectiveKindMap[".value"] = DK_VALUE;
4825 DirectiveKindMap[".2byte"] = DK_2BYTE;
4826 DirectiveKindMap[".long"] = DK_LONG;
4827 DirectiveKindMap[".int"] = DK_INT;
4828 DirectiveKindMap[".4byte"] = DK_4BYTE;
4829 DirectiveKindMap[".quad"] = DK_QUAD;
4830 DirectiveKindMap[".8byte"] = DK_8BYTE;
David Woodhoused6de0d92014-02-01 16:20:59 +00004831 DirectiveKindMap[".octa"] = DK_OCTA;
Eli Bendersky17233942013-01-15 22:59:42 +00004832 DirectiveKindMap[".single"] = DK_SINGLE;
4833 DirectiveKindMap[".float"] = DK_FLOAT;
4834 DirectiveKindMap[".double"] = DK_DOUBLE;
4835 DirectiveKindMap[".align"] = DK_ALIGN;
4836 DirectiveKindMap[".align32"] = DK_ALIGN32;
4837 DirectiveKindMap[".balign"] = DK_BALIGN;
4838 DirectiveKindMap[".balignw"] = DK_BALIGNW;
4839 DirectiveKindMap[".balignl"] = DK_BALIGNL;
4840 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
4841 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
4842 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
4843 DirectiveKindMap[".org"] = DK_ORG;
4844 DirectiveKindMap[".fill"] = DK_FILL;
4845 DirectiveKindMap[".zero"] = DK_ZERO;
4846 DirectiveKindMap[".extern"] = DK_EXTERN;
4847 DirectiveKindMap[".globl"] = DK_GLOBL;
4848 DirectiveKindMap[".global"] = DK_GLOBAL;
Eli Bendersky17233942013-01-15 22:59:42 +00004849 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
4850 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
4851 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
4852 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
4853 DirectiveKindMap[".reference"] = DK_REFERENCE;
4854 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
4855 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
4856 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
4857 DirectiveKindMap[".comm"] = DK_COMM;
4858 DirectiveKindMap[".common"] = DK_COMMON;
4859 DirectiveKindMap[".lcomm"] = DK_LCOMM;
4860 DirectiveKindMap[".abort"] = DK_ABORT;
4861 DirectiveKindMap[".include"] = DK_INCLUDE;
4862 DirectiveKindMap[".incbin"] = DK_INCBIN;
4863 DirectiveKindMap[".code16"] = DK_CODE16;
4864 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
4865 DirectiveKindMap[".rept"] = DK_REPT;
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00004866 DirectiveKindMap[".rep"] = DK_REPT;
Eli Bendersky17233942013-01-15 22:59:42 +00004867 DirectiveKindMap[".irp"] = DK_IRP;
4868 DirectiveKindMap[".irpc"] = DK_IRPC;
4869 DirectiveKindMap[".endr"] = DK_ENDR;
4870 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
4871 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
4872 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
4873 DirectiveKindMap[".if"] = DK_IF;
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004874 DirectiveKindMap[".ifeq"] = DK_IFEQ;
4875 DirectiveKindMap[".ifge"] = DK_IFGE;
4876 DirectiveKindMap[".ifgt"] = DK_IFGT;
4877 DirectiveKindMap[".ifle"] = DK_IFLE;
4878 DirectiveKindMap[".iflt"] = DK_IFLT;
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00004879 DirectiveKindMap[".ifne"] = DK_IFNE;
Eli Bendersky17233942013-01-15 22:59:42 +00004880 DirectiveKindMap[".ifb"] = DK_IFB;
4881 DirectiveKindMap[".ifnb"] = DK_IFNB;
4882 DirectiveKindMap[".ifc"] = DK_IFC;
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004883 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
Eli Bendersky17233942013-01-15 22:59:42 +00004884 DirectiveKindMap[".ifnc"] = DK_IFNC;
Sid Manning51c35602015-03-18 14:20:54 +00004885 DirectiveKindMap[".ifnes"] = DK_IFNES;
Eli Bendersky17233942013-01-15 22:59:42 +00004886 DirectiveKindMap[".ifdef"] = DK_IFDEF;
4887 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
4888 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
4889 DirectiveKindMap[".elseif"] = DK_ELSEIF;
4890 DirectiveKindMap[".else"] = DK_ELSE;
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004891 DirectiveKindMap[".end"] = DK_END;
Eli Bendersky17233942013-01-15 22:59:42 +00004892 DirectiveKindMap[".endif"] = DK_ENDIF;
4893 DirectiveKindMap[".skip"] = DK_SKIP;
4894 DirectiveKindMap[".space"] = DK_SPACE;
4895 DirectiveKindMap[".file"] = DK_FILE;
4896 DirectiveKindMap[".line"] = DK_LINE;
4897 DirectiveKindMap[".loc"] = DK_LOC;
4898 DirectiveKindMap[".stabs"] = DK_STABS;
Reid Kleckner2214ed82016-01-29 00:49:42 +00004899 DirectiveKindMap[".cv_file"] = DK_CV_FILE;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00004900 DirectiveKindMap[".cv_func_id"] = DK_CV_FUNC_ID;
Reid Kleckner2214ed82016-01-29 00:49:42 +00004901 DirectiveKindMap[".cv_loc"] = DK_CV_LOC;
4902 DirectiveKindMap[".cv_linetable"] = DK_CV_LINETABLE;
David Majnemer6fcbd7e2016-01-29 19:24:12 +00004903 DirectiveKindMap[".cv_inline_linetable"] = DK_CV_INLINE_LINETABLE;
Reid Klecknera9f4cc92016-09-07 16:15:31 +00004904 DirectiveKindMap[".cv_inline_site_id"] = DK_CV_INLINE_SITE_ID;
David Majnemer408b5e62016-02-05 01:55:49 +00004905 DirectiveKindMap[".cv_def_range"] = DK_CV_DEF_RANGE;
Reid Kleckner2214ed82016-01-29 00:49:42 +00004906 DirectiveKindMap[".cv_stringtable"] = DK_CV_STRINGTABLE;
4907 DirectiveKindMap[".cv_filechecksums"] = DK_CV_FILECHECKSUMS;
Eli Bendersky17233942013-01-15 22:59:42 +00004908 DirectiveKindMap[".sleb128"] = DK_SLEB128;
4909 DirectiveKindMap[".uleb128"] = DK_ULEB128;
4910 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
4911 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
4912 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
4913 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
4914 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
4915 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
4916 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
4917 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
4918 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
4919 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
4920 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
4921 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
4922 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
4923 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
4924 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
4925 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
4926 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
4927 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
4928 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00004929 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
Eli Bendersky17233942013-01-15 22:59:42 +00004930 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
4931 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
4932 DirectiveKindMap[".macro"] = DK_MACRO;
Nico Weber155dccd12014-07-24 17:08:39 +00004933 DirectiveKindMap[".exitm"] = DK_EXITM;
Eli Bendersky17233942013-01-15 22:59:42 +00004934 DirectiveKindMap[".endm"] = DK_ENDM;
4935 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
4936 DirectiveKindMap[".purgem"] = DK_PURGEM;
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004937 DirectiveKindMap[".err"] = DK_ERR;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004938 DirectiveKindMap[".error"] = DK_ERROR;
Nico Weber404012b2014-07-24 16:26:06 +00004939 DirectiveKindMap[".warning"] = DK_WARNING;
Daniel Sanders9f6ad492015-11-12 13:33:00 +00004940 DirectiveKindMap[".reloc"] = DK_RELOC;
Petr Hosek731bb9c2016-08-23 21:34:53 +00004941 DirectiveKindMap[".dc"] = DK_DC;
4942 DirectiveKindMap[".dc.a"] = DK_DC_A;
4943 DirectiveKindMap[".dc.b"] = DK_DC_B;
4944 DirectiveKindMap[".dc.d"] = DK_DC_D;
4945 DirectiveKindMap[".dc.l"] = DK_DC_L;
4946 DirectiveKindMap[".dc.s"] = DK_DC_S;
4947 DirectiveKindMap[".dc.w"] = DK_DC_W;
4948 DirectiveKindMap[".dc.x"] = DK_DC_X;
Petr Hosek4cb08ce2016-09-23 19:25:15 +00004949 DirectiveKindMap[".dcb"] = DK_DCB;
4950 DirectiveKindMap[".dcb.b"] = DK_DCB_B;
4951 DirectiveKindMap[".dcb.d"] = DK_DCB_D;
4952 DirectiveKindMap[".dcb.l"] = DK_DCB_L;
4953 DirectiveKindMap[".dcb.s"] = DK_DCB_S;
4954 DirectiveKindMap[".dcb.w"] = DK_DCB_W;
4955 DirectiveKindMap[".dcb.x"] = DK_DCB_X;
Petr Hosek85b2f672016-09-23 21:53:36 +00004956 DirectiveKindMap[".ds"] = DK_DS;
4957 DirectiveKindMap[".ds.b"] = DK_DS_B;
4958 DirectiveKindMap[".ds.d"] = DK_DS_D;
4959 DirectiveKindMap[".ds.l"] = DK_DS_L;
4960 DirectiveKindMap[".ds.p"] = DK_DS_P;
4961 DirectiveKindMap[".ds.s"] = DK_DS_S;
4962 DirectiveKindMap[".ds.w"] = DK_DS_W;
4963 DirectiveKindMap[".ds.x"] = DK_DS_X;
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00004964}
4965
Jim Grosbach4b905842013-09-20 23:08:21 +00004966MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004967 AsmToken EndToken, StartToken = getTok();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004968
Rafael Espindola34b9c512012-06-03 23:57:14 +00004969 unsigned NestLevel = 0;
Eugene Zelenko33d7b762016-08-23 17:14:32 +00004970 while (true) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004971 // Check whether we have reached the end of the file.
Rafael Espindola34b9c512012-06-03 23:57:14 +00004972 if (getLexer().is(AsmToken::Eof)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00004973 printError(DirectiveLoc, "no matching '.endr' in definition");
Craig Topper353eda42014-04-24 06:44:33 +00004974 return nullptr;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004975 }
4976
Rafael Espindola34b9c512012-06-03 23:57:14 +00004977 if (Lexer.is(AsmToken::Identifier) &&
Nikolay Haustov95b4fcd2016-03-01 08:18:28 +00004978 (getTok().getIdentifier() == ".rept" ||
4979 getTok().getIdentifier() == ".irp" ||
4980 getTok().getIdentifier() == ".irpc")) {
Rafael Espindola34b9c512012-06-03 23:57:14 +00004981 ++NestLevel;
4982 }
4983
4984 // Otherwise, check whether we have reached the .endr.
Jim Grosbach4b905842013-09-20 23:08:21 +00004985 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
Rafael Espindola34b9c512012-06-03 23:57:14 +00004986 if (NestLevel == 0) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004987 EndToken = getTok();
4988 Lex();
Rafael Espindola34b9c512012-06-03 23:57:14 +00004989 if (Lexer.isNot(AsmToken::EndOfStatement)) {
Nirav Dave2364748a2016-09-16 18:30:20 +00004990 printError(getTok().getLoc(),
4991 "unexpected token in '.endr' directive");
Craig Topper353eda42014-04-24 06:44:33 +00004992 return nullptr;
Rafael Espindola34b9c512012-06-03 23:57:14 +00004993 }
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004994 break;
4995 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00004996 --NestLevel;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004997 }
4998
Rafael Espindola34b9c512012-06-03 23:57:14 +00004999 // Otherwise, scan till the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005000 eatToEndOfStatement();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005001 }
5002
5003 const char *BodyStart = StartToken.getLoc().getPointer();
5004 const char *BodyEnd = EndToken.getLoc().getPointer();
5005 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
5006
Rafael Espindola34b9c512012-06-03 23:57:14 +00005007 // We Are Anonymous.
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00005008 MacroLikeBodies.emplace_back(StringRef(), Body, MCAsmMacroParameters());
Benjamin Kramer1df3a1f2013-08-04 09:06:29 +00005009 return &MacroLikeBodies.back();
Rafael Espindola34b9c512012-06-03 23:57:14 +00005010}
5011
Jim Grosbach4b905842013-09-20 23:08:21 +00005012void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +00005013 raw_svector_ostream &OS) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005014 OS << ".endr\n";
5015
Rafael Espindola3560ff22014-08-27 20:03:13 +00005016 std::unique_ptr<MemoryBuffer> Instantiation =
5017 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005018
Rafael Espindola34b9c512012-06-03 23:57:14 +00005019 // Create the macro instantiation object and add to the current macro
5020 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00005021 MacroInstantiation *MI = new MacroInstantiation(
5022 DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Rafael Espindola34b9c512012-06-03 23:57:14 +00005023 ActiveMacros.push_back(MI);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005024
Rafael Espindola34b9c512012-06-03 23:57:14 +00005025 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00005026 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00005027 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Rafael Espindola34b9c512012-06-03 23:57:14 +00005028 Lex();
5029}
5030
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00005031/// parseDirectiveRept
5032/// ::= .rep | .rept count
5033bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00005034 const MCExpr *CountExpr;
5035 SMLoc CountLoc = getTok().getLoc();
5036 if (parseExpression(CountExpr))
5037 return true;
5038
Rafael Espindola34b9c512012-06-03 23:57:14 +00005039 int64_t Count;
Jim Grosbach13760bd2015-05-30 01:25:56 +00005040 if (!CountExpr->evaluateAsAbsolute(Count)) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00005041 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
5042 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00005043
Nirav Davea645433c2016-07-18 15:24:03 +00005044 if (check(Count < 0, CountLoc, "Count is negative") ||
5045 parseToken(AsmToken::EndOfStatement,
5046 "unexpected token in '" + Dir + "' directive"))
5047 return true;
Rafael Espindola34b9c512012-06-03 23:57:14 +00005048
5049 // Lex the rept definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005050 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola34b9c512012-06-03 23:57:14 +00005051 if (!M)
5052 return true;
5053
5054 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5055 // to hold the macro body with substitutions.
5056 SmallString<256> Buf;
Rafael Espindola34b9c512012-06-03 23:57:14 +00005057 raw_svector_ostream OS(Buf);
5058 while (Count--) {
Toma Tabacu217116e2015-04-27 10:50:29 +00005059 // Note that the AtPseudoVariable is disabled for instantiations of .rep(t).
5060 if (expandMacro(OS, M->Body, None, None, false, getTok().getLoc()))
Rafael Espindola34b9c512012-06-03 23:57:14 +00005061 return true;
5062 }
Jim Grosbach4b905842013-09-20 23:08:21 +00005063 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005064
5065 return false;
5066}
5067
Jim Grosbach4b905842013-09-20 23:08:21 +00005068/// parseDirectiveIrp
Rafael Espindola768b41c2012-06-15 14:02:34 +00005069/// ::= .irp symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00005070bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00005071 MCAsmMacroParameter Parameter;
Eli Bendersky38274122013-01-14 23:22:36 +00005072 MCAsmMacroArguments A;
Nirav Davea645433c2016-07-18 15:24:03 +00005073 if (check(parseIdentifier(Parameter.Name),
5074 "expected identifier in '.irp' directive") ||
5075 parseToken(AsmToken::Comma, "expected comma in '.irp' directive") ||
5076 parseMacroArguments(nullptr, A) ||
5077 parseToken(AsmToken::EndOfStatement, "expected End of Statement"))
Rafael Espindola768b41c2012-06-15 14:02:34 +00005078 return true;
5079
Rafael Espindola768b41c2012-06-15 14:02:34 +00005080 // Lex the irp definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005081 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola768b41c2012-06-15 14:02:34 +00005082 if (!M)
5083 return true;
5084
5085 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5086 // to hold the macro body with substitutions.
5087 SmallString<256> Buf;
5088 raw_svector_ostream OS(Buf);
5089
Craig Topper84008482015-10-10 05:38:14 +00005090 for (const MCAsmMacroArgument &Arg : A) {
Toma Tabacu217116e2015-04-27 10:50:29 +00005091 // Note that the AtPseudoVariable is enabled for instantiations of .irp.
5092 // This is undocumented, but GAS seems to support it.
Craig Topper84008482015-10-10 05:38:14 +00005093 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindola768b41c2012-06-15 14:02:34 +00005094 return true;
5095 }
5096
Jim Grosbach4b905842013-09-20 23:08:21 +00005097 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola768b41c2012-06-15 14:02:34 +00005098
5099 return false;
5100}
5101
Jim Grosbach4b905842013-09-20 23:08:21 +00005102/// parseDirectiveIrpc
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005103/// ::= .irpc symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00005104bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00005105 MCAsmMacroParameter Parameter;
Eli Bendersky38274122013-01-14 23:22:36 +00005106 MCAsmMacroArguments A;
Nirav Davea645433c2016-07-18 15:24:03 +00005107
5108 if (check(parseIdentifier(Parameter.Name),
5109 "expected identifier in '.irpc' directive") ||
5110 parseToken(AsmToken::Comma, "expected comma in '.irpc' directive") ||
5111 parseMacroArguments(nullptr, A))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005112 return true;
5113
5114 if (A.size() != 1 || A.front().size() != 1)
5115 return TokError("unexpected token in '.irpc' directive");
5116
5117 // Eat the end of statement.
Nirav Davea645433c2016-07-18 15:24:03 +00005118 if (parseToken(AsmToken::EndOfStatement, "expected end of statement"))
5119 return true;
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005120
5121 // Lex the irpc definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00005122 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005123 if (!M)
5124 return true;
5125
5126 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5127 // to hold the macro body with substitutions.
5128 SmallString<256> Buf;
5129 raw_svector_ostream OS(Buf);
5130
5131 StringRef Values = A.front().front().getString();
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00005132 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
Eli Benderskya7b905e2013-01-14 19:00:26 +00005133 MCAsmMacroArgument Arg;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00005134 Arg.emplace_back(AsmToken::Identifier, Values.slice(I, I + 1));
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005135
Toma Tabacu217116e2015-04-27 10:50:29 +00005136 // Note that the AtPseudoVariable is enabled for instantiations of .irpc.
5137 // This is undocumented, but GAS seems to support it.
5138 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005139 return true;
5140 }
5141
Jim Grosbach4b905842013-09-20 23:08:21 +00005142 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00005143
5144 return false;
5145}
5146
Jim Grosbach4b905842013-09-20 23:08:21 +00005147bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
Rafael Espindola34b9c512012-06-03 23:57:14 +00005148 if (ActiveMacros.empty())
Preston Gurdeb3ebf12012-09-19 20:23:43 +00005149 return TokError("unmatched '.endr' directive");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005150
5151 // The only .repl that should get here are the ones created by
Jim Grosbach4b905842013-09-20 23:08:21 +00005152 // instantiateMacroLikeBody.
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005153 assert(getLexer().is(AsmToken::EndOfStatement));
5154
Jim Grosbach4b905842013-09-20 23:08:21 +00005155 handleMacroExit();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00005156 return false;
5157}
Rafael Espindola12d73d12010-09-11 16:45:15 +00005158
Jim Grosbach4b905842013-09-20 23:08:21 +00005159bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
Benjamin Kramer1a136112013-02-15 20:37:21 +00005160 size_t Len) {
Eli Friedman0f4871d2012-10-22 23:58:19 +00005161 const MCExpr *Value;
5162 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005163 if (parseExpression(Value))
Eli Friedman0f4871d2012-10-22 23:58:19 +00005164 return true;
5165 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5166 if (!MCE)
5167 return Error(ExprLoc, "unexpected expression in _emit");
5168 uint64_t IntValue = MCE->getValue();
Craig Topper55b1f292015-10-10 20:17:07 +00005169 if (!isUInt<8>(IntValue) && !isInt<8>(IntValue))
Eli Friedman0f4871d2012-10-22 23:58:19 +00005170 return Error(ExprLoc, "literal value out of range for directive");
5171
Craig Topper7d5b2312015-10-10 05:25:02 +00005172 Info.AsmRewrites->emplace_back(AOK_Emit, IDLoc, Len);
Chad Rosierc7f552c2013-02-12 21:33:51 +00005173 return false;
5174}
5175
Jim Grosbach4b905842013-09-20 23:08:21 +00005176bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
Chad Rosierc7f552c2013-02-12 21:33:51 +00005177 const MCExpr *Value;
5178 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005179 if (parseExpression(Value))
Chad Rosierc7f552c2013-02-12 21:33:51 +00005180 return true;
5181 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5182 if (!MCE)
5183 return Error(ExprLoc, "unexpected expression in align");
5184 uint64_t IntValue = MCE->getValue();
5185 if (!isPowerOf2_64(IntValue))
5186 return Error(ExprLoc, "literal value not a power of two greater then zero");
5187
Craig Topper7d5b2312015-10-10 05:25:02 +00005188 Info.AsmRewrites->emplace_back(AOK_Align, IDLoc, 5, Log2_64(IntValue));
Eli Friedman0f4871d2012-10-22 23:58:19 +00005189 return false;
5190}
5191
Chad Rosierf43fcf52013-02-13 21:27:17 +00005192// We are comparing pointers, but the pointers are relative to a single string.
5193// Thus, this should always be deterministic.
Benjamin Kramer8817cca2013-09-22 14:09:50 +00005194static int rewritesSort(const AsmRewrite *AsmRewriteA,
5195 const AsmRewrite *AsmRewriteB) {
Chad Rosiereb5c1682013-02-13 18:38:58 +00005196 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
5197 return -1;
5198 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
5199 return 1;
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005200
Chad Rosierfce4fab2013-04-08 17:43:47 +00005201 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
5202 // rewrite to the same location. Make sure the SizeDirective rewrite is
5203 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
5204 // ensures the sort algorithm is stable.
Jim Grosbach4b905842013-09-20 23:08:21 +00005205 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
5206 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005207 return -1;
Chad Rosierfce4fab2013-04-08 17:43:47 +00005208
Jim Grosbach4b905842013-09-20 23:08:21 +00005209 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
5210 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005211 return 1;
Jim Grosbach4b905842013-09-20 23:08:21 +00005212 llvm_unreachable("Unstable rewrite sort.");
Chad Rosierb2144ce2013-02-13 01:03:13 +00005213}
5214
Jim Grosbach4b905842013-09-20 23:08:21 +00005215bool AsmParser::parseMSInlineAsm(
5216 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
5217 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
5218 SmallVectorImpl<std::string> &Constraints,
5219 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
5220 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
Chad Rosier37e755c2012-10-23 17:43:43 +00005221 SmallVector<void *, 4> InputDecls;
5222 SmallVector<void *, 4> OutputDecls;
Chad Rosiera4bc9432013-01-10 22:10:27 +00005223 SmallVector<bool, 4> InputDeclsAddressOf;
5224 SmallVector<bool, 4> OutputDeclsAddressOf;
Chad Rosier8bce6642012-10-18 15:49:34 +00005225 SmallVector<std::string, 4> InputConstraints;
5226 SmallVector<std::string, 4> OutputConstraints;
Benjamin Kramer1a136112013-02-15 20:37:21 +00005227 SmallVector<unsigned, 4> ClobberRegs;
Chad Rosier8bce6642012-10-18 15:49:34 +00005228
Benjamin Kramer1a136112013-02-15 20:37:21 +00005229 SmallVector<AsmRewrite, 4> AsmStrRewrites;
Chad Rosier8bce6642012-10-18 15:49:34 +00005230
5231 // Prime the lexer.
5232 Lex();
5233
5234 // While we have input, parse each statement.
5235 unsigned InputIdx = 0;
5236 unsigned OutputIdx = 0;
5237 while (getLexer().isNot(AsmToken::Eof)) {
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00005238 // Parse curly braces marking block start/end
5239 if (parseCurlyBlockScope(AsmStrRewrites))
5240 continue;
5241
Eli Friedman0f4871d2012-10-22 23:58:19 +00005242 ParseStatementInfo Info(&AsmStrRewrites);
Nirav Dave2364748a2016-09-16 18:30:20 +00005243 bool StatementErr = parseStatement(Info, &SI);
Nirav Dave9fa8af22016-09-13 13:55:06 +00005244
Nirav Dave2364748a2016-09-16 18:30:20 +00005245 if (StatementErr || Info.ParseError) {
5246 // Emit pending errors if any exist.
5247 printPendingErrors();
Nico Webere204c482016-09-13 18:17:00 +00005248 return true;
Nirav Dave2364748a2016-09-16 18:30:20 +00005249 }
5250
5251 // No pending error should exist here.
5252 assert(!hasPendingError() && "unexpected error from parseStatement");
Chad Rosier149e8e02012-12-12 22:45:52 +00005253
Benjamin Kramer1a136112013-02-15 20:37:21 +00005254 if (Info.Opcode == ~0U)
5255 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00005256
Benjamin Kramer1a136112013-02-15 20:37:21 +00005257 const MCInstrDesc &Desc = MII->get(Info.Opcode);
Chad Rosier8bce6642012-10-18 15:49:34 +00005258
Benjamin Kramer1a136112013-02-15 20:37:21 +00005259 // Build the list of clobbers, outputs and inputs.
5260 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
David Blaikie960ea3f2014-06-08 16:18:35 +00005261 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005262
Benjamin Kramer1a136112013-02-15 20:37:21 +00005263 // Immediate.
David Blaikie960ea3f2014-06-08 16:18:35 +00005264 if (Operand.isImm())
Benjamin Kramer1a136112013-02-15 20:37:21 +00005265 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00005266
Benjamin Kramer1a136112013-02-15 20:37:21 +00005267 // Register operand.
Nico Weber42f79db2014-07-17 20:24:55 +00005268 if (Operand.isReg() && !Operand.needAddressOf() &&
5269 !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
Benjamin Kramer1a136112013-02-15 20:37:21 +00005270 unsigned NumDefs = Desc.getNumDefs();
5271 // Clobber.
David Blaikie960ea3f2014-06-08 16:18:35 +00005272 if (NumDefs && Operand.getMCOperandNum() < NumDefs)
5273 ClobberRegs.push_back(Operand.getReg());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005274 continue;
5275 }
5276
5277 // Expr/Input or Output.
David Blaikie960ea3f2014-06-08 16:18:35 +00005278 StringRef SymName = Operand.getSymName();
Chad Rosiere81309b2013-04-09 17:53:49 +00005279 if (SymName.empty())
5280 continue;
5281
David Blaikie960ea3f2014-06-08 16:18:35 +00005282 void *OpDecl = Operand.getOpDecl();
Benjamin Kramer1a136112013-02-15 20:37:21 +00005283 if (!OpDecl)
5284 continue;
5285
5286 bool isOutput = (i == 1) && Desc.mayStore();
Chad Rosiere81309b2013-04-09 17:53:49 +00005287 SMLoc Start = SMLoc::getFromPointer(SymName.data());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005288 if (isOutput) {
5289 ++InputIdx;
5290 OutputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00005291 OutputDeclsAddressOf.push_back(Operand.needAddressOf());
Yaron Keren075759a2015-03-30 15:42:36 +00005292 OutputConstraints.push_back(("=" + Operand.getConstraint()).str());
Craig Topper7d5b2312015-10-10 05:25:02 +00005293 AsmStrRewrites.emplace_back(AOK_Output, Start, SymName.size());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005294 } else {
5295 InputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00005296 InputDeclsAddressOf.push_back(Operand.needAddressOf());
5297 InputConstraints.push_back(Operand.getConstraint().str());
Craig Topper7d5b2312015-10-10 05:25:02 +00005298 AsmStrRewrites.emplace_back(AOK_Input, Start, SymName.size());
Chad Rosier8bce6642012-10-18 15:49:34 +00005299 }
Chad Rosier8bce6642012-10-18 15:49:34 +00005300 }
Reid Kleckneree088972013-12-10 18:27:32 +00005301
5302 // Consider implicit defs to be clobbers. Think of cpuid and push.
Craig Toppere5e035a32015-12-05 07:13:35 +00005303 ArrayRef<MCPhysReg> ImpDefs(Desc.getImplicitDefs(),
5304 Desc.getNumImplicitDefs());
David Majnemer8114c1a2014-06-23 02:17:16 +00005305 ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end());
Chad Rosier8bce6642012-10-18 15:49:34 +00005306 }
5307
5308 // Set the number of Outputs and Inputs.
Chad Rosierf641baa2012-10-18 19:39:30 +00005309 NumOutputs = OutputDecls.size();
5310 NumInputs = InputDecls.size();
Chad Rosier8bce6642012-10-18 15:49:34 +00005311
5312 // Set the unique clobbers.
Benjamin Kramer1a136112013-02-15 20:37:21 +00005313 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
5314 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
5315 ClobberRegs.end());
5316 Clobbers.assign(ClobberRegs.size(), std::string());
5317 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
5318 raw_string_ostream OS(Clobbers[I]);
5319 IP->printRegName(OS, ClobberRegs[I]);
5320 }
Chad Rosier8bce6642012-10-18 15:49:34 +00005321
5322 // Merge the various outputs and inputs. Output are expected first.
5323 if (NumOutputs || NumInputs) {
5324 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierf641baa2012-10-18 19:39:30 +00005325 OpDecls.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00005326 Constraints.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00005327 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00005328 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00005329 Constraints[i] = OutputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005330 }
5331 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00005332 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00005333 Constraints[j] = InputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005334 }
5335 }
5336
5337 // Build the IR assembly string.
Alp Tokere69170a2014-06-26 22:52:05 +00005338 std::string AsmStringIR;
5339 raw_string_ostream OS(AsmStringIR);
Alp Tokera55b95b2014-07-06 10:33:31 +00005340 StringRef ASMString =
5341 SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
5342 const char *AsmStart = ASMString.begin();
5343 const char *AsmEnd = ASMString.end();
Jim Grosbach4b905842013-09-20 23:08:21 +00005344 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
David Majnemer8114c1a2014-06-23 02:17:16 +00005345 for (const AsmRewrite &AR : AsmStrRewrites) {
5346 AsmRewriteKind Kind = AR.Kind;
Chad Rosierff10ed12013-04-12 16:26:42 +00005347 if (Kind == AOK_Delete)
5348 continue;
5349
David Majnemer8114c1a2014-06-23 02:17:16 +00005350 const char *Loc = AR.Loc.getPointer();
Chad Rosier17d37992013-03-19 21:12:14 +00005351 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
Chad Rosier0f48c552012-10-19 20:57:14 +00005352
Chad Rosier120eefd2013-03-19 17:32:17 +00005353 // Emit everything up to the immediate/expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00005354 if (unsigned Len = Loc - AsmStart)
Chad Rosier17d37992013-03-19 21:12:14 +00005355 OS << StringRef(AsmStart, Len);
Chad Rosier0f48c552012-10-19 20:57:14 +00005356
Chad Rosier37e755c2012-10-23 17:43:43 +00005357 // Skip the original expression.
5358 if (Kind == AOK_Skip) {
David Majnemer8114c1a2014-06-23 02:17:16 +00005359 AsmStart = Loc + AR.Len;
Chad Rosier37e755c2012-10-23 17:43:43 +00005360 continue;
5361 }
5362
Chad Rosierff10ed12013-04-12 16:26:42 +00005363 unsigned AdditionalSkip = 0;
Chad Rosier8bce6642012-10-18 15:49:34 +00005364 // Rewrite expressions in $N notation.
Chad Rosier0f48c552012-10-19 20:57:14 +00005365 switch (Kind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00005366 default:
5367 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005368 case AOK_Imm:
David Majnemer8114c1a2014-06-23 02:17:16 +00005369 OS << "$$" << AR.Val;
Chad Rosier11c42f22012-10-26 18:04:20 +00005370 break;
5371 case AOK_ImmPrefix:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005372 OS << "$$";
Chad Rosier8bce6642012-10-18 15:49:34 +00005373 break;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005374 case AOK_Label:
Matt Arsenault4e273432014-12-04 00:06:57 +00005375 OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005376 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005377 case AOK_Input:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005378 OS << '$' << InputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00005379 break;
5380 case AOK_Output:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005381 OS << '$' << OutputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00005382 break;
Chad Rosier0f48c552012-10-19 20:57:14 +00005383 case AOK_SizeDirective:
David Majnemer8114c1a2014-06-23 02:17:16 +00005384 switch (AR.Val) {
Chad Rosier0f48c552012-10-19 20:57:14 +00005385 default: break;
5386 case 8: OS << "byte ptr "; break;
5387 case 16: OS << "word ptr "; break;
5388 case 32: OS << "dword ptr "; break;
5389 case 64: OS << "qword ptr "; break;
5390 case 80: OS << "xword ptr "; break;
5391 case 128: OS << "xmmword ptr "; break;
5392 case 256: OS << "ymmword ptr "; break;
5393 }
Eli Friedman0f4871d2012-10-22 23:58:19 +00005394 break;
5395 case AOK_Emit:
5396 OS << ".byte";
5397 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00005398 case AOK_Align: {
Reid Klecknerfb1c1c72015-10-27 17:32:48 +00005399 // MS alignment directives are measured in bytes. If the native assembler
5400 // measures alignment in bytes, we can pass it straight through.
5401 OS << ".align";
5402 if (getContext().getAsmInfo()->getAlignmentIsInBytes())
5403 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00005404
Reid Klecknerfb1c1c72015-10-27 17:32:48 +00005405 // Alignment is in log2 form, so print that instead and skip the original
5406 // immediate.
5407 unsigned Val = AR.Val;
5408 OS << ' ' << Val;
Benjamin Kramer1a136112013-02-15 20:37:21 +00005409 assert(Val < 10 && "Expected alignment less then 2^10.");
Chad Rosierc7f552c2013-02-12 21:33:51 +00005410 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
5411 break;
5412 }
Michael Zuckerman02ecd432015-12-13 17:07:23 +00005413 case AOK_EVEN:
5414 OS << ".even";
5415 break;
Chad Rosierf0e87202012-10-25 20:41:34 +00005416 case AOK_DotOperator:
Reid Kleckner94a1c4d2014-03-06 19:19:12 +00005417 // Insert the dot if the user omitted it.
Alp Tokere69170a2014-06-26 22:52:05 +00005418 OS.flush();
5419 if (AsmStringIR.back() != '.')
Reid Kleckner94a1c4d2014-03-06 19:19:12 +00005420 OS << '.';
David Majnemer8114c1a2014-06-23 02:17:16 +00005421 OS << AR.Val;
Chad Rosierf0e87202012-10-25 20:41:34 +00005422 break;
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00005423 case AOK_EndOfStatement:
5424 OS << "\n\t";
5425 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005426 }
Chad Rosier0f48c552012-10-19 20:57:14 +00005427
Chad Rosier8bce6642012-10-18 15:49:34 +00005428 // Skip the original expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00005429 AsmStart = Loc + AR.Len + AdditionalSkip;
Chad Rosier8bce6642012-10-18 15:49:34 +00005430 }
5431
5432 // Emit the remainder of the asm string.
Chad Rosier17d37992013-03-19 21:12:14 +00005433 if (AsmStart != AsmEnd)
5434 OS << StringRef(AsmStart, AsmEnd - AsmStart);
Chad Rosier8bce6642012-10-18 15:49:34 +00005435
5436 AsmString = OS.str();
5437 return false;
5438}
5439
Pete Cooper80d21cb2015-06-22 19:35:57 +00005440namespace llvm {
5441namespace MCParserUtils {
5442
5443/// Returns whether the given symbol is used anywhere in the given expression,
5444/// or subexpressions.
5445static bool isSymbolUsedInExpression(const MCSymbol *Sym, const MCExpr *Value) {
5446 switch (Value->getKind()) {
5447 case MCExpr::Binary: {
5448 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
5449 return isSymbolUsedInExpression(Sym, BE->getLHS()) ||
5450 isSymbolUsedInExpression(Sym, BE->getRHS());
5451 }
5452 case MCExpr::Target:
5453 case MCExpr::Constant:
5454 return false;
5455 case MCExpr::SymbolRef: {
5456 const MCSymbol &S =
5457 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
5458 if (S.isVariable())
5459 return isSymbolUsedInExpression(Sym, S.getVariableValue());
5460 return &S == Sym;
5461 }
5462 case MCExpr::Unary:
5463 return isSymbolUsedInExpression(
5464 Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
5465 }
5466
5467 llvm_unreachable("Unknown expr kind!");
5468}
5469
5470bool parseAssignmentExpression(StringRef Name, bool allow_redef,
5471 MCAsmParser &Parser, MCSymbol *&Sym,
5472 const MCExpr *&Value) {
Pete Cooper80d21cb2015-06-22 19:35:57 +00005473
5474 // FIXME: Use better location, we should use proper tokens.
Nirav Davefd910412016-06-17 16:06:17 +00005475 SMLoc EqualLoc = Parser.getTok().getLoc();
Pete Cooper80d21cb2015-06-22 19:35:57 +00005476
5477 if (Parser.parseExpression(Value)) {
Nirav Dave1a9044b2016-10-24 14:35:29 +00005478 return Parser.TokError("missing expression");
Pete Cooper80d21cb2015-06-22 19:35:57 +00005479 }
5480
5481 // Note: we don't count b as used in "a = b". This is to allow
5482 // a = b
5483 // b = c
5484
Nirav Dave1a9044b2016-10-24 14:35:29 +00005485 if (Parser.parseToken(AsmToken::EndOfStatement))
5486 return true;
Pete Cooper80d21cb2015-06-22 19:35:57 +00005487
5488 // Validate that the LHS is allowed to be a variable (either it has not been
5489 // used as a symbol, or it is an absolute symbol).
5490 Sym = Parser.getContext().lookupSymbol(Name);
5491 if (Sym) {
5492 // Diagnose assignment to a label.
5493 //
5494 // FIXME: Diagnostics. Note the location of the definition as a label.
5495 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
5496 if (isSymbolUsedInExpression(Sym, Value))
5497 return Parser.Error(EqualLoc, "Recursive use of '" + Name + "'");
Vedant Kumar86dbd922015-08-31 17:44:53 +00005498 else if (Sym->isUndefined(/*SetUsed*/ false) && !Sym->isUsed() &&
5499 !Sym->isVariable())
Pete Cooper80d21cb2015-06-22 19:35:57 +00005500 ; // Allow redefinitions of undefined symbols only used in directives.
5501 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
5502 ; // Allow redefinitions of variables that haven't yet been used.
5503 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
5504 return Parser.Error(EqualLoc, "redefinition of '" + Name + "'");
5505 else if (!Sym->isVariable())
5506 return Parser.Error(EqualLoc, "invalid assignment to '" + Name + "'");
5507 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
5508 return Parser.Error(EqualLoc,
5509 "invalid reassignment of non-absolute variable '" +
5510 Name + "'");
Pete Cooper80d21cb2015-06-22 19:35:57 +00005511 } else if (Name == ".") {
Oliver Stannard268f42f2016-12-14 10:43:58 +00005512 Parser.getStreamer().emitValueToOffset(Value, 0, EqualLoc);
Pete Cooper80d21cb2015-06-22 19:35:57 +00005513 return false;
5514 } else
5515 Sym = Parser.getContext().getOrCreateSymbol(Name);
5516
5517 Sym->setRedefinable(allow_redef);
5518
5519 return false;
5520}
5521
Eugene Zelenko33d7b762016-08-23 17:14:32 +00005522} // end namespace MCParserUtils
5523} // end namespace llvm
Pete Cooper80d21cb2015-06-22 19:35:57 +00005524
Daniel Dunbar01e36072010-07-17 02:26:10 +00005525/// \brief Create an MCAsmParser instance.
Jim Grosbach4b905842013-09-20 23:08:21 +00005526MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
Sanne Wouda09adc242017-02-08 10:20:07 +00005527 MCStreamer &Out, const MCAsmInfo &MAI,
5528 unsigned CB) {
5529 return new AsmParser(SM, C, Out, MAI, CB);
Daniel Dunbar01e36072010-07-17 02:26:10 +00005530}