blob: 83c845274d8e2fbb89ab17c459654d3152a33b13 [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"
Daniel Dunbarca29e4d2009-06-23 22:01:43 +000025#include "llvm/MC/MCContext.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000026#include "llvm/MC/MCDirectives.h"
Evan Cheng11424442011-07-26 00:24:13 +000027#include "llvm/MC/MCDwarf.h"
Daniel Dunbar115e4d62009-08-31 08:06:59 +000028#include "llvm/MC/MCExpr.h"
Chad Rosier8bce6642012-10-18 15:49:34 +000029#include "llvm/MC/MCInstPrinter.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000030#include "llvm/MC/MCInstrDesc.h"
Chad Rosier8bce6642012-10-18 15:49:34 +000031#include "llvm/MC/MCInstrInfo.h"
Rafael Espindolae28610d2013-12-09 20:26:40 +000032#include "llvm/MC/MCObjectFileInfo.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000033#include "llvm/MC/MCParser/AsmCond.h"
34#include "llvm/MC/MCParser/AsmLexer.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000035#include "llvm/MC/MCParser/MCAsmLexer.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000036#include "llvm/MC/MCParser/MCAsmParser.h"
Pete Cooper80d21cb2015-06-22 19:35:57 +000037#include "llvm/MC/MCParser/MCAsmParserUtils.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000038#include "llvm/MC/MCParser/MCParsedAsmOperand.h"
Benjamin Kramerb3e8a6d2016-01-27 10:01:28 +000039#include "llvm/MC/MCParser/MCTargetAsmParser.h"
Evan Cheng76792992011-07-20 05:58:47 +000040#include "llvm/MC/MCRegisterInfo.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000041#include "llvm/MC/MCSection.h"
Daniel Dunbarca29e4d2009-06-23 22:01:43 +000042#include "llvm/MC/MCStreamer.h"
Daniel Dunbarae7ac012009-06-29 23:43:14 +000043#include "llvm/MC/MCSymbol.h"
Daniel Sanders9f6ad492015-11-12 13:33:00 +000044#include "llvm/MC/MCValue.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000045#include "llvm/Support/Casting.h"
Davide Italiano7c9fc732016-07-27 05:51:56 +000046#include "llvm/Support/CommandLine.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000047#include "llvm/Support/Dwarf.h"
Benjamin Kramer4efe5062012-01-28 15:28:41 +000048#include "llvm/Support/ErrorHandling.h"
Jim Grosbach76346c32011-06-29 16:05:14 +000049#include "llvm/Support/MathExtras.h"
Kevin Enderbye233dda2010-06-28 21:45:58 +000050#include "llvm/Support/MemoryBuffer.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000051#include "llvm/Support/SMLoc.h"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000052#include "llvm/Support/SourceMgr.h"
Chris Lattner36e02122009-06-21 20:54:55 +000053#include "llvm/Support/raw_ostream.h"
Eugene Zelenko33d7b762016-08-23 17:14:32 +000054#include <algorithm>
55#include <cassert>
Nick Lewycky0de20af2010-12-19 20:43:38 +000056#include <cctype>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000057#include <cstddef>
58#include <cstdint>
Benjamin Kramerd59664f2014-04-29 23:26:49 +000059#include <deque>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000060#include <memory>
Davide Italiano7c9fc732016-07-27 05:51:56 +000061#include <sstream>
Chad Rosier8bce6642012-10-18 15:49:34 +000062#include <string>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000063#include <tuple>
64#include <utility>
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +000065#include <vector>
Eugene Zelenko33d7b762016-08-23 17:14:32 +000066
Chris Lattnerb0133452009-06-21 20:16:42 +000067using namespace llvm;
68
Eric Christophera7c32732012-12-18 00:30:54 +000069MCAsmParserSemaCallback::~MCAsmParserSemaCallback() {}
Nick Lewyckyac612272012-10-19 07:00:09 +000070
Davide Italiano7c9fc732016-07-27 05:51:56 +000071static cl::opt<unsigned> AsmMacroMaxNestingDepth(
72 "asm-macro-max-nesting-depth", cl::init(20), cl::Hidden,
73 cl::desc("The maximum nesting depth allowed for assembly macros."));
74
Daniel Dunbar86033402010-07-12 17:54:38 +000075namespace {
Eugene Zelenko33d7b762016-08-23 17:14:32 +000076
Eli Benderskya313ae62013-01-16 18:56:50 +000077/// \brief Helper types for tracking macro definitions.
78typedef std::vector<AsmToken> MCAsmMacroArgument;
79typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +000080
81struct MCAsmMacroParameter {
82 StringRef Name;
83 MCAsmMacroArgument Value;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +000084 bool Required;
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +000085 bool Vararg;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +000086
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +000087 MCAsmMacroParameter() : Required(false), Vararg(false) {}
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +000088};
89
Eli Benderskya313ae62013-01-16 18:56:50 +000090typedef std::vector<MCAsmMacroParameter> MCAsmMacroParameters;
91
92struct MCAsmMacro {
93 StringRef Name;
94 StringRef Body;
95 MCAsmMacroParameters Parameters;
96
97public:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +000098 MCAsmMacro(StringRef N, StringRef B, MCAsmMacroParameters P)
99 : Name(N), Body(B), Parameters(std::move(P)) {}
Eli Benderskya313ae62013-01-16 18:56:50 +0000100};
101
Daniel Dunbar43235712010-07-18 18:54:11 +0000102/// \brief Helper class for storing information about an active macro
103/// instantiation.
104struct MacroInstantiation {
Daniel Dunbar43235712010-07-18 18:54:11 +0000105 /// The location of the instantiation.
106 SMLoc InstantiationLoc;
107
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000108 /// The buffer where parsing should resume upon instantiation completion.
109 int ExitBuffer;
110
Daniel Dunbar43235712010-07-18 18:54:11 +0000111 /// The location where parsing should resume upon instantiation completion.
112 SMLoc ExitLoc;
113
Nico Weber155dccd12014-07-24 17:08:39 +0000114 /// The depth of TheCondStack at the start of the instantiation.
115 size_t CondStackDepth;
116
Daniel Dunbar43235712010-07-18 18:54:11 +0000117public:
Rafael Espindola9eef18c2014-08-27 19:49:03 +0000118 MacroInstantiation(SMLoc IL, int EB, SMLoc EL, size_t CondStackDepth);
Daniel Dunbar43235712010-07-18 18:54:11 +0000119};
120
Eli Friedman0f4871d2012-10-22 23:58:19 +0000121struct ParseStatementInfo {
Jim Grosbach4b905842013-09-20 23:08:21 +0000122 /// \brief The parsed operands from the last parsed statement.
David Blaikie960ea3f2014-06-08 16:18:35 +0000123 SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> ParsedOperands;
Eli Friedman0f4871d2012-10-22 23:58:19 +0000124
Jim Grosbach4b905842013-09-20 23:08:21 +0000125 /// \brief The opcode from the last parsed instruction.
Eli Friedman0f4871d2012-10-22 23:58:19 +0000126 unsigned Opcode;
127
Jim Grosbach4b905842013-09-20 23:08:21 +0000128 /// \brief Was there an error parsing the inline assembly?
Chad Rosier149e8e02012-12-12 22:45:52 +0000129 bool ParseError;
130
Eli Friedman0f4871d2012-10-22 23:58:19 +0000131 SmallVectorImpl<AsmRewrite> *AsmRewrites;
132
Craig Topper353eda42014-04-24 06:44:33 +0000133 ParseStatementInfo() : Opcode(~0U), ParseError(false), AsmRewrites(nullptr) {}
Eli Friedman0f4871d2012-10-22 23:58:19 +0000134 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
Chad Rosier149e8e02012-12-12 22:45:52 +0000135 : Opcode(~0), ParseError(false), AsmRewrites(rewrites) {}
Eli Friedman0f4871d2012-10-22 23:58:19 +0000136};
137
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000138/// \brief The concrete assembly parser instance.
139class AsmParser : public MCAsmParser {
Aaron Ballmanf9a18972015-02-15 22:54:22 +0000140 AsmParser(const AsmParser &) = delete;
141 void operator=(const AsmParser &) = delete;
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000142
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000143private:
144 AsmLexer Lexer;
145 MCContext &Ctx;
146 MCStreamer &Out;
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000147 const MCAsmInfo &MAI;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000148 SourceMgr &SrcMgr;
Benjamin Kramer47f5e302011-10-16 10:48:29 +0000149 SourceMgr::DiagHandlerTy SavedDiagHandler;
150 void *SavedDiagContext;
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000151 std::unique_ptr<MCAsmParserExtension> PlatformParser;
Rafael Espindola82065cb2011-04-11 21:49:50 +0000152
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000153 /// This is the current buffer index we're lexing from as managed by the
154 /// SourceMgr object.
Alp Tokera55b95b2014-07-06 10:33:31 +0000155 unsigned CurBuffer;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000156
157 AsmCond TheCondState;
158 std::vector<AsmCond> TheCondStack;
159
Jim Grosbach4b905842013-09-20 23:08:21 +0000160 /// \brief maps directive names to handler methods in parser
Eli Bendersky17233942013-01-15 22:59:42 +0000161 /// extensions. Extensions register themselves in this map by calling
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000162 /// addDirectiveHandler.
Eli Bendersky17233942013-01-15 22:59:42 +0000163 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
Daniel Dunbar828984f2010-07-18 18:38:02 +0000164
Jim Grosbach4b905842013-09-20 23:08:21 +0000165 /// \brief Map of currently defined macros.
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000166 StringMap<MCAsmMacro> MacroMap;
Daniel Dunbarc1f58ec2010-07-18 18:47:21 +0000167
Jim Grosbach4b905842013-09-20 23:08:21 +0000168 /// \brief Stack of active macro instantiations.
Daniel Dunbar43235712010-07-18 18:54:11 +0000169 std::vector<MacroInstantiation*> ActiveMacros;
170
Jim Grosbach4b905842013-09-20 23:08:21 +0000171 /// \brief List of bodies of anonymous macros.
Benjamin Kramer1df3a1f2013-08-04 09:06:29 +0000172 std::deque<MCAsmMacro> MacroLikeBodies;
173
Daniel Dunbar828984f2010-07-18 18:38:02 +0000174 /// Boolean tracking whether macro substitution is enabled.
Eli Benderskyc2f6f922013-01-14 18:08:41 +0000175 unsigned MacrosEnabledFlag : 1;
Daniel Dunbar828984f2010-07-18 18:38:02 +0000176
Toma Tabacu217116e2015-04-27 10:50:29 +0000177 /// \brief Keeps track of how many .macro's have been instantiated.
178 unsigned NumOfMacroInstantiations;
179
Daniel Dunbar43325c42010-09-09 22:42:56 +0000180 /// Flag tracking whether any errors have been encountered.
181 unsigned HadError : 1;
182
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000183 /// The values from the last parsed cpp hash file line comment if any.
Tim Northoverc0bef992016-04-13 19:46:54 +0000184 struct CppHashInfoTy {
185 StringRef Filename;
Andrew Kaylorca196472016-04-21 20:09:35 +0000186 int64_t LineNumber = 0;
Tim Northoverc0bef992016-04-13 19:46:54 +0000187 SMLoc Loc;
Andrew Kaylorca196472016-04-21 20:09:35 +0000188 unsigned Buf = 0;
Tim Northoverc0bef992016-04-13 19:46:54 +0000189 };
190 CppHashInfoTy CppHashInfo;
191
192 /// \brief List of forward directional labels for diagnosis at the end.
193 SmallVector<std::tuple<SMLoc, CppHashInfoTy, MCSymbol *>, 4> DirLabels;
194
Kevin Enderby0fd064c2013-06-21 20:51:39 +0000195 /// When generating dwarf for assembly source files we need to calculate the
196 /// logical line number based on the last parsed cpp hash file line comment
Vladimir Medic9bad0d332013-08-20 13:33:18 +0000197 /// and current line. Since this is slow and messes up the SourceMgr's
Kevin Enderby0fd064c2013-06-21 20:51:39 +0000198 /// cache we save the last info we queried with SrcMgr.FindLineNumber().
199 SMLoc LastQueryIDLoc;
Alp Tokera55b95b2014-07-06 10:33:31 +0000200 unsigned LastQueryBuffer;
Kevin Enderby0fd064c2013-06-21 20:51:39 +0000201 unsigned LastQueryLine;
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000202
Devang Patela173ee52012-01-31 18:14:05 +0000203 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
204 unsigned AssemblerDialect;
205
Jim Grosbach4b905842013-09-20 23:08:21 +0000206 /// \brief is Darwin compatibility enabled?
Preston Gurd05500642012-09-19 20:36:12 +0000207 bool IsDarwin;
208
Jim Grosbach4b905842013-09-20 23:08:21 +0000209 /// \brief Are we parsing ms-style inline assembly?
Chad Rosier49963552012-10-13 00:26:04 +0000210 bool ParsingInlineAsm;
211
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000212public:
Jim Grosbach345768c2011-08-16 18:33:49 +0000213 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000214 const MCAsmInfo &MAI);
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000215 ~AsmParser() override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000216
Craig Topper59be68f2014-03-08 07:14:16 +0000217 bool Run(bool NoInitialTextSection, bool NoFinalize = false) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000218
Craig Topper59be68f2014-03-08 07:14:16 +0000219 void addDirectiveHandler(StringRef Directive,
220 ExtensionDirectiveHandler Handler) override {
Eli Bendersky29b9f472013-01-16 00:50:52 +0000221 ExtensionDirectiveMap[Directive] = Handler;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000222 }
223
Toma Tabacu11e14a92015-04-21 11:50:52 +0000224 void addAliasForDirective(StringRef Directive, StringRef Alias) override {
225 DirectiveKindMap[Directive] = DirectiveKindMap[Alias];
226 }
227
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000228public:
229 /// @name MCAsmParser Interface
230 /// {
231
Craig Topper59be68f2014-03-08 07:14:16 +0000232 SourceMgr &getSourceManager() override { return SrcMgr; }
233 MCAsmLexer &getLexer() override { return Lexer; }
234 MCContext &getContext() override { return Ctx; }
235 MCStreamer &getStreamer() override { return Out; }
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000236
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
Craig Topper59be68f2014-03-08 07:14:16 +0000247 void Note(SMLoc L, const Twine &Msg,
248 ArrayRef<SMRange> Ranges = None) override;
249 bool Warning(SMLoc L, const Twine &Msg,
250 ArrayRef<SMRange> Ranges = None) override;
251 bool Error(SMLoc L, const Twine &Msg,
252 ArrayRef<SMRange> Ranges = None) override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000253
Craig Topper59be68f2014-03-08 07:14:16 +0000254 const AsmToken &Lex() override;
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000255
Craig Topper59be68f2014-03-08 07:14:16 +0000256 void setParsingInlineAsm(bool V) override { ParsingInlineAsm = V; }
257 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
Jim Grosbach4b905842013-09-20 23:08:21 +0000275 /// \brief Parse an identifier or string (as a quoted identifier)
Eli Bendersky0cf0cb92013-01-12 00:05:00 +0000276 /// and set \p Res to the identifier contents.
Craig Topper59be68f2014-03-08 07:14:16 +0000277 bool parseIdentifier(StringRef &Res) override;
278 void eatToEndOfStatement() override;
Eli Bendersky0cf0cb92013-01-12 00:05:00 +0000279
Craig Topper59be68f2014-03-08 07:14:16 +0000280 void checkForValidSection() override;
Nirav Davea645433c2016-07-18 15:24:03 +0000281
282 bool getTokenLoc(SMLoc &Loc) {
283 Loc = getTok().getLoc();
284 return false;
285 }
286
Nirav Dave9263ae32016-08-02 19:17:54 +0000287 bool parseEOL(const Twine &ErrMsg) {
288 if (getTok().getKind() == AsmToken::Hash) {
289 StringRef CommentStr = parseStringToEndOfStatement();
290 Lexer.Lex();
291 Lexer.UnLex(AsmToken(AsmToken::EndOfStatement, CommentStr));
292 }
293 if (getTok().getKind() != AsmToken::EndOfStatement)
294 return TokError(ErrMsg);
295 Lex();
296 return false;
297 }
298
Nirav Davea645433c2016-07-18 15:24:03 +0000299 /// parseToken - If current token has the specified kind, eat it and
300 /// return success. Otherwise, emit the specified error and return failure.
301 bool parseToken(AsmToken::TokenKind T, const Twine &ErrMsg) {
Nirav Dave9263ae32016-08-02 19:17:54 +0000302 if (T == AsmToken::EndOfStatement)
303 return parseEOL(ErrMsg);
Nirav Davea645433c2016-07-18 15:24:03 +0000304 if (getTok().getKind() != T)
305 return TokError(ErrMsg);
306 Lex();
307 return false;
308 }
309
310 bool parseIntToken(int64_t &V, const Twine &ErrMsg) {
311 if (getTok().getKind() != AsmToken::Integer)
312 return TokError(ErrMsg);
313 V = getTok().getIntVal();
314 Lex();
315 return false;
316 }
317
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000318 /// }
319
320private:
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +0000321 bool parseStatement(ParseStatementInfo &Info,
322 MCAsmParserSemaCallback *SI);
Marina Yatsina5f5de9f2016-03-07 18:11:16 +0000323 bool parseCurlyBlockScope(SmallVectorImpl<AsmRewrite>& AsmStrRewrites);
Craig Topper3c76c522015-09-20 23:35:59 +0000324 bool parseCppHashLineFilenameComment(SMLoc L);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000325
Jim Grosbach4b905842013-09-20 23:08:21 +0000326 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +0000327 ArrayRef<MCAsmMacroParameter> Parameters);
Rafael Espindola34b9c512012-06-03 23:57:14 +0000328 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +0000329 ArrayRef<MCAsmMacroParameter> Parameters,
Toma Tabacu217116e2015-04-27 10:50:29 +0000330 ArrayRef<MCAsmMacroArgument> A, bool EnableAtPseudoVariable,
Craig Topper3c76c522015-09-20 23:35:59 +0000331 SMLoc L);
Daniel Dunbar43235712010-07-18 18:54:11 +0000332
Eli Benderskya313ae62013-01-16 18:56:50 +0000333 /// \brief Are macros enabled in the parser?
Jim Grosbach4b905842013-09-20 23:08:21 +0000334 bool areMacrosEnabled() {return MacrosEnabledFlag;}
Eli Benderskya313ae62013-01-16 18:56:50 +0000335
336 /// \brief Control a flag in the parser that enables or disables macros.
Jim Grosbach4b905842013-09-20 23:08:21 +0000337 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
Eli Benderskya313ae62013-01-16 18:56:50 +0000338
339 /// \brief Lookup a previously defined macro.
340 /// \param Name Macro name.
341 /// \returns Pointer to macro. NULL if no such macro was defined.
Jim Grosbach4b905842013-09-20 23:08:21 +0000342 const MCAsmMacro* lookupMacro(StringRef Name);
Eli Benderskya313ae62013-01-16 18:56:50 +0000343
344 /// \brief Define a new macro with the given name and information.
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000345 void defineMacro(StringRef Name, MCAsmMacro Macro);
Eli Benderskya313ae62013-01-16 18:56:50 +0000346
347 /// \brief Undefine a macro. If no such macro was defined, it's a no-op.
Jim Grosbach4b905842013-09-20 23:08:21 +0000348 void undefineMacro(StringRef Name);
Eli Benderskya313ae62013-01-16 18:56:50 +0000349
350 /// \brief Are we inside a macro instantiation?
Jim Grosbach4b905842013-09-20 23:08:21 +0000351 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
Eli Benderskya313ae62013-01-16 18:56:50 +0000352
Vladimir Medic9bad0d332013-08-20 13:33:18 +0000353 /// \brief Handle entry to macro instantiation.
Eli Benderskya313ae62013-01-16 18:56:50 +0000354 ///
355 /// \param M The macro.
356 /// \param NameLoc Instantiation location.
Jim Grosbach4b905842013-09-20 23:08:21 +0000357 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
Eli Benderskya313ae62013-01-16 18:56:50 +0000358
359 /// \brief Handle exit from macro instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +0000360 void handleMacroExit();
Eli Benderskya313ae62013-01-16 18:56:50 +0000361
David Majnemer91fc4c22014-01-29 18:57:46 +0000362 /// \brief Extract AsmTokens for a macro argument.
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +0000363 bool parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg);
Eli Benderskya313ae62013-01-16 18:56:50 +0000364
365 /// \brief Parse all macro arguments for a given macro.
Jim Grosbach4b905842013-09-20 23:08:21 +0000366 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
Eli Benderskya313ae62013-01-16 18:56:50 +0000367
Jim Grosbach4b905842013-09-20 23:08:21 +0000368 void printMacroInstantiations();
369 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
Dmitri Gribenko3238fb72013-05-05 00:40:33 +0000370 ArrayRef<SMRange> Ranges = None) const {
Chris Lattner72845262011-10-16 05:47:55 +0000371 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
Benjamin Kramerc7583112010-09-27 17:42:11 +0000372 }
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000373 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
Benjamin Kramerc7583112010-09-27 17:42:11 +0000374
Nirav Davea645433c2016-07-18 15:24:03 +0000375 bool check(bool P, SMLoc Loc, const Twine &Msg) {
376 if (P)
377 return Error(Loc, Msg);
378 return false;
379 }
380
381 bool check(bool P, const Twine &Msg) {
382 if (P)
383 return TokError(Msg);
384 return false;
385 }
386
Jim Grosbach4b905842013-09-20 23:08:21 +0000387 /// \brief Enter the specified file. This returns true on failure.
388 bool enterIncludeFile(const std::string &Filename);
389
390 /// \brief Process the specified file for the .incbin directive.
Kevin Enderby109f25c2011-12-14 21:47:48 +0000391 /// This returns true on failure.
Jim Grosbach4b905842013-09-20 23:08:21 +0000392 bool processIncbinFile(const std::string &Filename);
Daniel Dunbar43235712010-07-18 18:54:11 +0000393
Dmitri Gribenko5485acd2012-09-14 14:57:36 +0000394 /// \brief Reset the current lexer position to that given by \p Loc. The
Daniel Dunbar43235712010-07-18 18:54:11 +0000395 /// current token is not set; clients should ensure Lex() is called
396 /// subsequently.
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000397 ///
Alp Tokera55b95b2014-07-06 10:33:31 +0000398 /// \param InBuffer If not 0, should be the known buffer id that contains the
Daniel Dunbar40f1d852012-12-01 01:38:48 +0000399 /// location.
Alp Tokera55b95b2014-07-06 10:33:31 +0000400 void jumpToLoc(SMLoc Loc, unsigned InBuffer = 0);
Daniel Dunbar43235712010-07-18 18:54:11 +0000401
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000402 /// \brief Parse up to the end of statement and a return the contents from the
403 /// current token until the end of the statement; the current token on exit
404 /// will be either the EndOfStatement or EOF.
Craig Topper59be68f2014-03-08 07:14:16 +0000405 StringRef parseStringToEndOfStatement() override;
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000406
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000407 /// \brief Parse until the end of a statement or a comma is encountered,
408 /// return the contents from the current token up to the end or comma.
Jim Grosbach4b905842013-09-20 23:08:21 +0000409 StringRef parseStringToComma();
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000410
Jim Grosbach4b905842013-09-20 23:08:21 +0000411 bool parseAssignment(StringRef Name, bool allow_redef,
Jim Grosbachb7b750d2012-09-13 23:11:31 +0000412 bool NoDeadStrip = false);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000413
Ahmed Bougacha457852f2015-04-28 00:17:39 +0000414 unsigned getBinOpPrecedence(AsmToken::TokenKind K,
415 MCBinaryExpr::Opcode &Kind);
416
Jim Grosbach4b905842013-09-20 23:08:21 +0000417 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
418 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
419 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000420
Jim Grosbach4b905842013-09-20 23:08:21 +0000421 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
Rafael Espindola63760ba2010-10-28 20:02:27 +0000422
Eli Bendersky17233942013-01-15 22:59:42 +0000423 // Generic (target and platform independent) directive parsing.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000424 enum DirectiveKind {
Eli Bendersky4d21fa02013-01-10 23:40:56 +0000425 DK_NO_DIRECTIVE, // Placeholder
426 DK_SET, DK_EQU, DK_EQUIV, DK_ASCII, DK_ASCIZ, DK_STRING, DK_BYTE, DK_SHORT,
Daniel Sanders9f6ad492015-11-12 13:33:00 +0000427 DK_RELOC,
David Woodhoused6de0d92014-02-01 16:20:59 +0000428 DK_VALUE, DK_2BYTE, DK_LONG, DK_INT, DK_4BYTE, DK_QUAD, DK_8BYTE, DK_OCTA,
Petr Hosek731bb9c2016-08-23 21:34:53 +0000429 DK_DC, DK_DC_A, DK_DC_B, DK_DC_D, DK_DC_L, DK_DC_S, DK_DC_W, DK_DC_X,
David Woodhoused6de0d92014-02-01 16:20:59 +0000430 DK_SINGLE, DK_FLOAT, DK_DOUBLE, DK_ALIGN, DK_ALIGN32, DK_BALIGN, DK_BALIGNW,
Eli Bendersky96522722013-01-11 22:55:28 +0000431 DK_BALIGNL, DK_P2ALIGN, DK_P2ALIGNW, DK_P2ALIGNL, DK_ORG, DK_FILL, DK_ENDR,
Eli Bendersky4d21fa02013-01-10 23:40:56 +0000432 DK_BUNDLE_ALIGN_MODE, DK_BUNDLE_LOCK, DK_BUNDLE_UNLOCK,
Kevin Enderby3aeada22013-08-28 17:50:59 +0000433 DK_ZERO, DK_EXTERN, DK_GLOBL, DK_GLOBAL,
Lang Hamesf9033bb2016-04-11 18:33:45 +0000434 DK_LAZY_REFERENCE, DK_NO_DEAD_STRIP, DK_SYMBOL_RESOLVER,
Lang Hames1b640e02016-03-15 01:43:05 +0000435 DK_PRIVATE_EXTERN, DK_REFERENCE, DK_WEAK_DEFINITION, DK_WEAK_REFERENCE,
Eli Bendersky4d21fa02013-01-10 23:40:56 +0000436 DK_WEAK_DEF_CAN_BE_HIDDEN, DK_COMM, DK_COMMON, DK_LCOMM, DK_ABORT,
437 DK_INCLUDE, DK_INCBIN, DK_CODE16, DK_CODE16GCC, DK_REPT, DK_IRP, DK_IRPC,
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +0000438 DK_IF, DK_IFEQ, DK_IFGE, DK_IFGT, DK_IFLE, DK_IFLT, DK_IFNE, DK_IFB,
Sid Manning51c35602015-03-18 14:20:54 +0000439 DK_IFNB, DK_IFC, DK_IFEQS, DK_IFNC, DK_IFNES, DK_IFDEF, DK_IFNDEF,
440 DK_IFNOTDEF, DK_ELSEIF, DK_ELSE, DK_ENDIF,
Eli Bendersky17233942013-01-15 22:59:42 +0000441 DK_SPACE, DK_SKIP, DK_FILE, DK_LINE, DK_LOC, DK_STABS,
David Majnemer6fcbd7e2016-01-29 19:24:12 +0000442 DK_CV_FILE, DK_CV_LOC, DK_CV_LINETABLE, DK_CV_INLINE_LINETABLE,
David Majnemer408b5e62016-02-05 01:55:49 +0000443 DK_CV_DEF_RANGE, DK_CV_STRINGTABLE, DK_CV_FILECHECKSUMS,
Eli Bendersky17233942013-01-15 22:59:42 +0000444 DK_CFI_SECTIONS, DK_CFI_STARTPROC, DK_CFI_ENDPROC, DK_CFI_DEF_CFA,
445 DK_CFI_DEF_CFA_OFFSET, DK_CFI_ADJUST_CFA_OFFSET, DK_CFI_DEF_CFA_REGISTER,
446 DK_CFI_OFFSET, DK_CFI_REL_OFFSET, DK_CFI_PERSONALITY, DK_CFI_LSDA,
447 DK_CFI_REMEMBER_STATE, DK_CFI_RESTORE_STATE, DK_CFI_SAME_VALUE,
448 DK_CFI_RESTORE, DK_CFI_ESCAPE, DK_CFI_SIGNAL_FRAME, DK_CFI_UNDEFINED,
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +0000449 DK_CFI_REGISTER, DK_CFI_WINDOW_SAVE,
Nico Weber155dccd12014-07-24 17:08:39 +0000450 DK_MACROS_ON, DK_MACROS_OFF,
451 DK_MACRO, DK_EXITM, DK_ENDM, DK_ENDMACRO, DK_PURGEM,
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000452 DK_SLEB128, DK_ULEB128,
Nico Weber404012b2014-07-24 16:26:06 +0000453 DK_ERR, DK_ERROR, DK_WARNING,
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000454 DK_END
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000455 };
456
Jim Grosbach4b905842013-09-20 23:08:21 +0000457 /// \brief Maps directive name --> DirectiveKind enum, for
Eli Bendersky17233942013-01-15 22:59:42 +0000458 /// directives parsed by this class.
459 StringMap<DirectiveKind> DirectiveKindMap;
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000460
461 // ".ascii", ".asciz", ".string"
Jim Grosbach4b905842013-09-20 23:08:21 +0000462 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
Daniel Sanders9f6ad492015-11-12 13:33:00 +0000463 bool parseDirectiveReloc(SMLoc DirectiveLoc); // ".reloc"
Jim Grosbach4b905842013-09-20 23:08:21 +0000464 bool parseDirectiveValue(unsigned Size); // ".byte", ".long", ...
David Woodhoused6de0d92014-02-01 16:20:59 +0000465 bool parseDirectiveOctaValue(); // ".octa"
Jim Grosbach4b905842013-09-20 23:08:21 +0000466 bool parseDirectiveRealValue(const fltSemantics &); // ".single", ...
467 bool parseDirectiveFill(); // ".fill"
468 bool parseDirectiveZero(); // ".zero"
Eric Christophera7c32732012-12-18 00:30:54 +0000469 // ".set", ".equ", ".equiv"
Jim Grosbach4b905842013-09-20 23:08:21 +0000470 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
471 bool parseDirectiveOrg(); // ".org"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000472 // ".align{,32}", ".p2align{,w,l}"
Jim Grosbach4b905842013-09-20 23:08:21 +0000473 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000474
Eli Bendersky17233942013-01-15 22:59:42 +0000475 // ".file", ".line", ".loc", ".stabs"
Jim Grosbach4b905842013-09-20 23:08:21 +0000476 bool parseDirectiveFile(SMLoc DirectiveLoc);
477 bool parseDirectiveLine();
478 bool parseDirectiveLoc();
479 bool parseDirectiveStabs();
Eli Bendersky17233942013-01-15 22:59:42 +0000480
David Majnemer408b5e62016-02-05 01:55:49 +0000481 // ".cv_file", ".cv_loc", ".cv_linetable", "cv_inline_linetable",
482 // ".cv_def_range"
Reid Kleckner2214ed82016-01-29 00:49:42 +0000483 bool parseDirectiveCVFile();
484 bool parseDirectiveCVLoc();
485 bool parseDirectiveCVLinetable();
David Majnemer6fcbd7e2016-01-29 19:24:12 +0000486 bool parseDirectiveCVInlineLinetable();
David Majnemer408b5e62016-02-05 01:55:49 +0000487 bool parseDirectiveCVDefRange();
Reid Kleckner2214ed82016-01-29 00:49:42 +0000488 bool parseDirectiveCVStringTable();
489 bool parseDirectiveCVFileChecksums();
490
Eli Bendersky17233942013-01-15 22:59:42 +0000491 // .cfi directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000492 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +0000493 bool parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +0000494 bool parseDirectiveCFISections();
495 bool parseDirectiveCFIStartProc();
496 bool parseDirectiveCFIEndProc();
497 bool parseDirectiveCFIDefCfaOffset();
498 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
499 bool parseDirectiveCFIAdjustCfaOffset();
500 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
501 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
502 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
503 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
504 bool parseDirectiveCFIRememberState();
505 bool parseDirectiveCFIRestoreState();
506 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
507 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
508 bool parseDirectiveCFIEscape();
509 bool parseDirectiveCFISignalFrame();
510 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
Eli Bendersky17233942013-01-15 22:59:42 +0000511
512 // macro directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000513 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
Nico Weber155dccd12014-07-24 17:08:39 +0000514 bool parseDirectiveExitMacro(StringRef Directive);
Jim Grosbach4b905842013-09-20 23:08:21 +0000515 bool parseDirectiveEndMacro(StringRef Directive);
516 bool parseDirectiveMacro(SMLoc DirectiveLoc);
517 bool parseDirectiveMacrosOnOff(StringRef Directive);
Eli Bendersky17233942013-01-15 22:59:42 +0000518
Eli Benderskyf483ff92012-12-20 19:05:53 +0000519 // ".bundle_align_mode"
Jim Grosbach4b905842013-09-20 23:08:21 +0000520 bool parseDirectiveBundleAlignMode();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000521 // ".bundle_lock"
Jim Grosbach4b905842013-09-20 23:08:21 +0000522 bool parseDirectiveBundleLock();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000523 // ".bundle_unlock"
Jim Grosbach4b905842013-09-20 23:08:21 +0000524 bool parseDirectiveBundleUnlock();
Eli Benderskyf483ff92012-12-20 19:05:53 +0000525
Eli Bendersky17233942013-01-15 22:59:42 +0000526 // ".space", ".skip"
Jim Grosbach4b905842013-09-20 23:08:21 +0000527 bool parseDirectiveSpace(StringRef IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +0000528
529 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
Jim Grosbach4b905842013-09-20 23:08:21 +0000530 bool parseDirectiveLEB128(bool Signed);
Eli Bendersky17233942013-01-15 22:59:42 +0000531
Jim Grosbach4b905842013-09-20 23:08:21 +0000532 /// \brief Parse a directive like ".globl" which
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000533 /// accepts a single symbol (which should be a label or an external).
Jim Grosbach4b905842013-09-20 23:08:21 +0000534 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000535
Jim Grosbach4b905842013-09-20 23:08:21 +0000536 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000537
Jim Grosbach4b905842013-09-20 23:08:21 +0000538 bool parseDirectiveAbort(); // ".abort"
539 bool parseDirectiveInclude(); // ".include"
540 bool parseDirectiveIncbin(); // ".incbin"
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000541
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +0000542 // ".if", ".ifeq", ".ifge", ".ifgt" , ".ifle", ".iflt" or ".ifne"
543 bool parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind);
Benjamin Kramer62c18b02012-05-12 11:18:42 +0000544 // ".ifb" or ".ifnb", depending on ExpectBlank.
Jim Grosbach4b905842013-09-20 23:08:21 +0000545 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000546 // ".ifc" or ".ifnc", depending on ExpectEqual.
Jim Grosbach4b905842013-09-20 23:08:21 +0000547 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
Sid Manning51c35602015-03-18 14:20:54 +0000548 // ".ifeqs" or ".ifnes", depending on ExpectEqual.
549 bool parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +0000550 // ".ifdef" or ".ifndef", depending on expect_defined
Jim Grosbach4b905842013-09-20 23:08:21 +0000551 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
552 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
553 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
554 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
Craig Topper59be68f2014-03-08 07:14:16 +0000555 bool parseEscapedString(std::string &Data) override;
Daniel Dunbar55f16672010-09-17 02:47:07 +0000556
Jim Grosbach4b905842013-09-20 23:08:21 +0000557 const MCExpr *applyModifierToExpr(const MCExpr *E,
Daniel Dunbar55f16672010-09-17 02:47:07 +0000558 MCSymbolRefExpr::VariantKind Variant);
Rafael Espindola47b7dac2012-05-12 16:31:10 +0000559
Rafael Espindola34b9c512012-06-03 23:57:14 +0000560 // Macro-like directives
Jim Grosbach4b905842013-09-20 23:08:21 +0000561 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
562 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +0000563 raw_svector_ostream &OS);
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +0000564 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
Jim Grosbach4b905842013-09-20 23:08:21 +0000565 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
566 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
567 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
Chad Rosier8bce6642012-10-18 15:49:34 +0000568
Chad Rosierc7f552c2013-02-12 21:33:51 +0000569 // "_emit" or "__emit"
Jim Grosbach4b905842013-09-20 23:08:21 +0000570 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
Chad Rosierc7f552c2013-02-12 21:33:51 +0000571 size_t Len);
572
573 // "align"
Jim Grosbach4b905842013-09-20 23:08:21 +0000574 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000575
Saleem Abdulrasool88186c42013-12-18 02:53:03 +0000576 // "end"
577 bool parseDirectiveEnd(SMLoc DirectiveLoc);
578
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +0000579 // ".err" or ".error"
580 bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +0000581
Nico Weber404012b2014-07-24 16:26:06 +0000582 // ".warning"
583 bool parseDirectiveWarning(SMLoc DirectiveLoc);
584
Eli Bendersky17233942013-01-15 22:59:42 +0000585 void initializeDirectiveKindMap();
Daniel Dunbar2a2c6cf2010-07-18 18:31:38 +0000586};
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000587
588} // end anonymous namespace
Daniel Dunbar86033402010-07-12 17:54:38 +0000589
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000590namespace llvm {
591
592extern MCAsmParserExtension *createDarwinAsmParser();
Daniel Dunbarab058b82010-07-12 21:23:32 +0000593extern MCAsmParserExtension *createELFAsmParser();
Michael J. Spencerc8dbdfd2010-10-09 11:01:07 +0000594extern MCAsmParserExtension *createCOFFAsmParser();
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000595
Eugene Zelenko33d7b762016-08-23 17:14:32 +0000596} // end namespace llvm
Daniel Dunbar0cb91cf2010-07-12 20:51:51 +0000597
Chris Lattnerc35681b2010-01-19 19:46:13 +0000598enum { DEFAULT_ADDRSPACE = 0 };
599
David Blaikie9f380a32015-03-16 18:06:57 +0000600AsmParser::AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
601 const MCAsmInfo &MAI)
602 : Lexer(MAI), Ctx(Ctx), Out(Out), MAI(MAI), SrcMgr(SM),
603 PlatformParser(nullptr), CurBuffer(SM.getMainFileID()),
Tim Northoverc0bef992016-04-13 19:46:54 +0000604 MacrosEnabledFlag(true), HadError(false), CppHashInfo(),
Oliver Stannardcf6bfb12014-11-03 12:19:03 +0000605 AssemblerDialect(~0U), IsDarwin(false), ParsingInlineAsm(false) {
Benjamin Kramer47f5e302011-10-16 10:48:29 +0000606 // Save the old handler.
607 SavedDiagHandler = SrcMgr.getDiagHandler();
608 SavedDiagContext = SrcMgr.getDiagContext();
609 // Set our own handler which calls the saved handler.
Kevin Enderbye7c0c492011-10-12 21:38:39 +0000610 SrcMgr.setDiagHandler(DiagHandler, this);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000611 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar86033402010-07-12 17:54:38 +0000612
Daniel Dunbarc5011082010-07-12 18:12:02 +0000613 // Initialize the platform / file format parser.
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000614 switch (Ctx.getObjectFileInfo()->getObjectFileType()) {
615 case MCObjectFileInfo::IsCOFF:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000616 PlatformParser.reset(createCOFFAsmParser());
617 break;
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000618 case MCObjectFileInfo::IsMachO:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000619 PlatformParser.reset(createDarwinAsmParser());
620 IsDarwin = true;
621 break;
Rafael Espindoladbaf0492015-08-14 15:48:41 +0000622 case MCObjectFileInfo::IsELF:
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000623 PlatformParser.reset(createELFAsmParser());
624 break;
Daniel Dunbarc5011082010-07-12 18:12:02 +0000625 }
Eli Benderskyec9e3cf2013-01-10 22:44:57 +0000626
Benjamin Kramercb3e06b2014-10-03 18:32:55 +0000627 PlatformParser->Initialize(*this);
Eli Bendersky17233942013-01-15 22:59:42 +0000628 initializeDirectiveKindMap();
Toma Tabacu217116e2015-04-27 10:50:29 +0000629
630 NumOfMacroInstantiations = 0;
Chris Lattner351a7ef2009-09-27 21:16:52 +0000631}
632
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000633AsmParser::~AsmParser() {
Saleem Abdulrasool6eae1e62014-05-21 17:53:18 +0000634 assert((HadError || ActiveMacros.empty()) &&
635 "Unexpected active macro instantiation!");
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000636}
637
Jim Grosbach4b905842013-09-20 23:08:21 +0000638void AsmParser::printMacroInstantiations() {
Daniel Dunbar43235712010-07-18 18:54:11 +0000639 // Print the active macro instantiation stack.
Jim Grosbach4b905842013-09-20 23:08:21 +0000640 for (std::vector<MacroInstantiation *>::const_reverse_iterator
641 it = ActiveMacros.rbegin(),
642 ie = ActiveMacros.rend();
643 it != ie; ++it)
644 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
Chris Lattner03b80a42011-10-16 05:43:57 +0000645 "while in macro instantiation");
Daniel Dunbar43235712010-07-18 18:54:11 +0000646}
647
Saleem Abdulrasool69c7caf2014-01-07 02:28:31 +0000648void AsmParser::Note(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
649 printMessage(L, SourceMgr::DK_Note, Msg, Ranges);
650 printMacroInstantiations();
651}
652
Chris Lattnera3a06812011-10-16 04:47:35 +0000653bool AsmParser::Warning(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Colin LeMahieufe36f832015-07-27 22:39:14 +0000654 if(getTargetParser().getTargetOptions().MCNoWarn)
655 return false;
Joerg Sonnenberger29815912014-08-26 18:39:50 +0000656 if (getTargetParser().getTargetOptions().MCFatalWarnings)
Chris Lattnera3a06812011-10-16 04:47:35 +0000657 return Error(L, Msg, Ranges);
Jim Grosbach4b905842013-09-20 23:08:21 +0000658 printMessage(L, SourceMgr::DK_Warning, Msg, Ranges);
659 printMacroInstantiations();
Joerg Sonnenberger74ba2622011-05-19 18:00:13 +0000660 return false;
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +0000661}
662
Chris Lattnera3a06812011-10-16 04:47:35 +0000663bool AsmParser::Error(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges) {
Daniel Dunbar43325c42010-09-09 22:42:56 +0000664 HadError = true;
Jim Grosbach4b905842013-09-20 23:08:21 +0000665 printMessage(L, SourceMgr::DK_Error, Msg, Ranges);
666 printMacroInstantiations();
Chris Lattner2adc9e72009-06-21 21:22:11 +0000667 return true;
668}
669
Jim Grosbach4b905842013-09-20 23:08:21 +0000670bool AsmParser::enterIncludeFile(const std::string &Filename) {
Joerg Sonnenbergeraf5f23e2011-06-01 13:10:15 +0000671 std::string IncludedFile;
Alp Tokera55b95b2014-07-06 10:33:31 +0000672 unsigned NewBuf =
673 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
674 if (!NewBuf)
Sean Callanan7a77eae2010-01-21 00:19:58 +0000675 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +0000676
Sean Callanan7a77eae2010-01-21 00:19:58 +0000677 CurBuffer = NewBuf;
Rafael Espindola8026bd02014-07-06 14:17:29 +0000678 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Sean Callanan7a77eae2010-01-21 00:19:58 +0000679 return false;
680}
Daniel Dunbar43235712010-07-18 18:54:11 +0000681
Sylvestre Ledru149e2812013-05-14 23:36:24 +0000682/// Process the specified .incbin file by searching for it in the include paths
Benjamin Kramerbde91762012-06-02 10:20:22 +0000683/// then just emitting the byte contents of the file to the streamer. This
Kevin Enderby109f25c2011-12-14 21:47:48 +0000684/// returns true on failure.
Jim Grosbach4b905842013-09-20 23:08:21 +0000685bool AsmParser::processIncbinFile(const std::string &Filename) {
Kevin Enderby109f25c2011-12-14 21:47:48 +0000686 std::string IncludedFile;
Alp Tokera55b95b2014-07-06 10:33:31 +0000687 unsigned NewBuf =
688 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
689 if (!NewBuf)
Kevin Enderby109f25c2011-12-14 21:47:48 +0000690 return true;
691
Kevin Enderbyad41ab52011-12-14 22:34:45 +0000692 // Pick up the bytes from the file and emit them.
Rafael Espindola64e1af82013-07-02 15:49:13 +0000693 getStreamer().EmitBytes(SrcMgr.getMemoryBuffer(NewBuf)->getBuffer());
Kevin Enderby109f25c2011-12-14 21:47:48 +0000694 return false;
695}
696
Alp Tokera55b95b2014-07-06 10:33:31 +0000697void AsmParser::jumpToLoc(SMLoc Loc, unsigned InBuffer) {
698 CurBuffer = InBuffer ? InBuffer : SrcMgr.FindBufferContainingLoc(Loc);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000699 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(),
700 Loc.getPointer());
Daniel Dunbar43235712010-07-18 18:54:11 +0000701}
702
Sean Callanan7a77eae2010-01-21 00:19:58 +0000703const AsmToken &AsmParser::Lex() {
Nirav Dave1180e6892016-06-02 17:15:05 +0000704 if (Lexer.getTok().is(AsmToken::Error))
705 Error(Lexer.getErrLoc(), Lexer.getErr());
706
Nirav Dave53a72f42016-07-11 12:42:14 +0000707 // if it's a end of statement with a comment in it
708 if (getTok().is(AsmToken::EndOfStatement)) {
709 // if this is a line comment output it.
710 if (getTok().getString().front() != '\n' &&
711 getTok().getString().front() != '\r' && MAI.preserveAsmComments())
712 Out.addExplicitComment(Twine(getTok().getString()));
713 }
714
Sean Callanan7a77eae2010-01-21 00:19:58 +0000715 const AsmToken *tok = &Lexer.Lex();
Nirav Dave53a72f42016-07-11 12:42:14 +0000716
717 // Parse comments here to be deferred until end of next statement.
Nirav Davefd910412016-06-17 16:06:17 +0000718 while (tok->is(AsmToken::Comment)) {
Nirav Dave53a72f42016-07-11 12:42:14 +0000719 if (MAI.preserveAsmComments())
720 Out.addExplicitComment(Twine(tok->getString()));
Nirav Davefd910412016-06-17 16:06:17 +0000721 tok = &Lexer.Lex();
722 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000723
Sean Callanan7a77eae2010-01-21 00:19:58 +0000724 if (tok->is(AsmToken::Eof)) {
725 // If this is the end of an included file, pop the parent file off the
726 // include stack.
727 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
728 if (ParentIncludeLoc != SMLoc()) {
Jim Grosbach4b905842013-09-20 23:08:21 +0000729 jumpToLoc(ParentIncludeLoc);
Nirav Davefd910412016-06-17 16:06:17 +0000730 return Lex();
Sean Callanan7a77eae2010-01-21 00:19:58 +0000731 }
732 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000733
Sean Callanan7a77eae2010-01-21 00:19:58 +0000734 return *tok;
Sean Callanan686ed8d2010-01-19 20:22:31 +0000735}
736
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000737bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
Daniel Dunbar322fec62010-03-13 02:20:57 +0000738 // Create the initial section, if requested.
Daniel Dunbar322fec62010-03-13 02:20:57 +0000739 if (!NoInitialTextSection)
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000740 Out.InitSections(false);
Daniel Dunbar4d7b2e32009-08-26 22:49:51 +0000741
Chris Lattner36e02122009-06-21 20:54:55 +0000742 // Prime the lexer.
Sean Callanan686ed8d2010-01-19 20:22:31 +0000743 Lex();
Daniel Dunbar43325c42010-09-09 22:42:56 +0000744
745 HadError = false;
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000746 AsmCond StartingCondState = TheCondState;
747
Kevin Enderby6469fc22011-11-01 22:27:22 +0000748 // If we are generating dwarf for assembly source files save the initial text
749 // section and generate a .file directive.
750 if (getContext().getGenDwarfForAssembly()) {
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000751 MCSection *Sec = getStreamer().getCurrentSection().first;
Rafael Espindola2f9bdd82015-05-27 20:52:32 +0000752 if (!Sec->getBeginSymbol()) {
753 MCSymbol *SectionStartSym = getContext().createTempSymbol();
754 getStreamer().EmitLabel(SectionStartSym);
755 Sec->setBeginSymbol(SectionStartSym);
756 }
Rafael Espindolae0746792015-05-21 16:52:32 +0000757 bool InsertResult = getContext().addGenDwarfSection(Sec);
758 assert(InsertResult && ".text section should not have debug info yet");
Rafael Espindolafa160c72015-05-21 17:09:22 +0000759 (void)InsertResult;
David Blaikiec714ef42014-03-17 01:52:11 +0000760 getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective(
761 0, StringRef(), getContext().getMainFileName()));
Kevin Enderby6469fc22011-11-01 22:27:22 +0000762 }
763
Chris Lattner73f36112009-07-02 21:53:43 +0000764 // While we have input, parse each statement.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000765 while (Lexer.isNot(AsmToken::Eof)) {
Eli Friedman0f4871d2012-10-22 23:58:19 +0000766 ParseStatementInfo Info;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +0000767 if (!parseStatement(Info, nullptr))
Jim Grosbach4b905842013-09-20 23:08:21 +0000768 continue;
Michael J. Spencer530ce852010-10-09 11:00:50 +0000769
Nirav Dave1180e6892016-06-02 17:15:05 +0000770 // If we've failed, but on a Error Token, but did not consume it in
771 // favor of a better message, emit it now.
772 if (Lexer.getTok().is(AsmToken::Error)) {
773 Lex();
774 }
775
Daniel Dunbar43325c42010-09-09 22:42:56 +0000776 // We had an error, validate that one was emitted and recover by skipping to
777 // the next line.
778 assert(HadError && "Parse statement returned an error, but none emitted!");
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000779 eatToEndOfStatement();
Chris Lattner73f36112009-07-02 21:53:43 +0000780 }
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000781
Oliver Stannard21718282016-07-26 14:19:47 +0000782 getTargetParser().flushPendingInstructions(getStreamer());
783
Kevin Enderbyd9f95292009-08-07 22:46:00 +0000784 if (TheCondState.TheCond != StartingCondState.TheCond ||
785 TheCondState.Ignore != StartingCondState.Ignore)
786 return TokError("unmatched .ifs or .elses");
Kevin Enderbye5930f12010-07-28 20:55:35 +0000787
788 // Check to see there are no empty DwarfFile slots.
David Blaikie8bf66c42014-04-01 07:35:52 +0000789 const auto &LineTables = getContext().getMCDwarfLineTables();
790 if (!LineTables.empty()) {
791 unsigned Index = 0;
792 for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) {
793 if (File.Name.empty() && Index != 0)
794 TokError("unassigned file number: " + Twine(Index) +
795 " for .file directives");
796 ++Index;
797 }
Kevin Enderbye5930f12010-07-28 20:55:35 +0000798 }
Michael J. Spencer530ce852010-10-09 11:00:50 +0000799
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000800 // Check to see that all assembler local symbols were actually defined.
801 // Targets that don't do subsections via symbols may not want this, though,
802 // so conservatively exclude them. Only do this if we're finalizing, though,
803 // as otherwise we won't necessarilly have seen everything yet.
Tim Northover6b3169b2016-04-11 19:50:46 +0000804 if (!NoFinalize) {
805 if (MAI.hasSubsectionsViaSymbols()) {
806 for (const auto &TableEntry : getContext().getSymbols()) {
807 MCSymbol *Sym = TableEntry.getValue();
808 // Variable symbols may not be marked as defined, so check those
809 // explicitly. If we know it's a variable, we have a definition for
810 // the purposes of this check.
811 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
812 // FIXME: We would really like to refer back to where the symbol was
813 // first referenced for a source location. We need to add something
814 // to track that. Currently, we just point to the end of the file.
815 HadError |=
Nirav Davefd910412016-06-17 16:06:17 +0000816 Error(getTok().getLoc(), "assembler local symbol '" +
817 Sym->getName() + "' not defined");
Tim Northover6b3169b2016-04-11 19:50:46 +0000818 }
819 }
820
821 // Temporary symbols like the ones for directional jumps don't go in the
822 // symbol table. They also need to be diagnosed in all (final) cases.
Tim Northoverc0bef992016-04-13 19:46:54 +0000823 for (std::tuple<SMLoc, CppHashInfoTy, MCSymbol *> &LocSym : DirLabels) {
824 if (std::get<2>(LocSym)->isUndefined()) {
825 // Reset the state of any "# line file" directives we've seen to the
826 // context as it was at the diagnostic site.
827 CppHashInfo = std::get<1>(LocSym);
828 HadError |= Error(std::get<0>(LocSym), "directional label undefined");
829 }
Jim Grosbachc7e6b8f2011-06-15 18:33:28 +0000830 }
831 }
832
Chris Lattner3b21e4d2010-04-05 23:15:42 +0000833 // Finalize the output stream if there are no errors and if the client wants
834 // us to.
Jack Carter13d5f752013-10-04 22:52:31 +0000835 if (!HadError && !NoFinalize)
Daniel Dunbar9df5f332009-08-21 08:34:18 +0000836 Out.Finish();
837
Oliver Stannard07b43d32015-11-17 09:58:07 +0000838 return HadError || getContext().hadError();
Chris Lattner36e02122009-06-21 20:54:55 +0000839}
840
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000841void AsmParser::checkForValidSection() {
Peter Collingbourne2f495b92013-04-17 21:18:16 +0000842 if (!ParsingInlineAsm && !getStreamer().getCurrentSection().first) {
Daniel Dunbare5444a82010-09-09 22:42:59 +0000843 TokError("expected section directive before assembly directive");
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000844 Out.InitSections(false);
Daniel Dunbare5444a82010-09-09 22:42:59 +0000845 }
846}
847
Jim Grosbach4b905842013-09-20 23:08:21 +0000848/// \brief Throw away the rest of the line for testing purposes.
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000849void AsmParser::eatToEndOfStatement() {
Jim Grosbach4b905842013-09-20 23:08:21 +0000850 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Nirav Dave1180e6892016-06-02 17:15:05 +0000851 Lexer.Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +0000852
Chris Lattnere5074c42009-06-22 01:29:09 +0000853 // Eat EOL.
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000854 if (Lexer.is(AsmToken::EndOfStatement))
Nirav Dave1180e6892016-06-02 17:15:05 +0000855 Lexer.Lex();
Chris Lattnere5074c42009-06-22 01:29:09 +0000856}
857
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000858StringRef AsmParser::parseStringToEndOfStatement() {
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000859 const char *Start = getTok().getLoc().getPointer();
860
Jim Grosbach4b905842013-09-20 23:08:21 +0000861 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
Nirav Davefd910412016-06-17 16:06:17 +0000862 Lexer.Lex();
Daniel Dunbar40a564f2010-07-18 20:15:59 +0000863
864 const char *End = getTok().getLoc().getPointer();
865 return StringRef(Start, End - Start);
866}
Chris Lattner78db3622009-06-22 05:51:26 +0000867
Jim Grosbach4b905842013-09-20 23:08:21 +0000868StringRef AsmParser::parseStringToComma() {
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000869 const char *Start = getTok().getLoc().getPointer();
870
871 while (Lexer.isNot(AsmToken::EndOfStatement) &&
Jim Grosbach4b905842013-09-20 23:08:21 +0000872 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
Nirav Davefd910412016-06-17 16:06:17 +0000873 Lexer.Lex();
Benjamin Kramere297b9f2012-05-12 11:18:51 +0000874
875 const char *End = getTok().getLoc().getPointer();
876 return StringRef(Start, End - Start);
877}
878
Jim Grosbach4b905842013-09-20 23:08:21 +0000879/// \brief Parse a paren expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +0000880/// NOTE: This assumes the leading '(' has already been consumed.
881///
882/// parenexpr ::= expr)
883///
Jim Grosbach4b905842013-09-20 23:08:21 +0000884bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
885 if (parseExpression(Res))
886 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000887 if (Lexer.isNot(AsmToken::RParen))
Chris Lattner7fdbce72009-06-22 06:32:03 +0000888 return TokError("expected ')' in parentheses expression");
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000889 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +0000890 Lex();
Chris Lattner7fdbce72009-06-22 06:32:03 +0000891 return false;
892}
Chris Lattner78db3622009-06-22 05:51:26 +0000893
Jim Grosbach4b905842013-09-20 23:08:21 +0000894/// \brief Parse a bracket expression and return it.
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +0000895/// NOTE: This assumes the leading '[' has already been consumed.
896///
897/// bracketexpr ::= expr]
898///
Jim Grosbach4b905842013-09-20 23:08:21 +0000899bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
900 if (parseExpression(Res))
901 return true;
Nirav Davea645433c2016-07-18 15:24:03 +0000902 EndLoc = getTok().getEndLoc();
903 if (parseToken(AsmToken::RBrac, "expected ']' in brackets expression"))
904 return true;
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +0000905 return false;
906}
907
Jim Grosbach4b905842013-09-20 23:08:21 +0000908/// \brief Parse a primary expression and return it.
Chris Lattner7fdbce72009-06-22 06:32:03 +0000909/// primaryexpr ::= (parenexpr
910/// primaryexpr ::= symbol
911/// primaryexpr ::= number
Chris Lattner6b55cb92010-04-14 04:40:28 +0000912/// primaryexpr ::= '.'
Chris Lattner7fdbce72009-06-22 06:32:03 +0000913/// primaryexpr ::= ~,+,- primaryexpr
Jim Grosbach4b905842013-09-20 23:08:21 +0000914bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
Kevin Enderby0017d8a2013-01-22 21:09:20 +0000915 SMLoc FirstTokenLoc = getLexer().getLoc();
916 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
917 switch (FirstTokenKind) {
Chris Lattner78db3622009-06-22 05:51:26 +0000918 default:
919 return TokError("unknown token in expression");
Eric Christopher104af062011-04-12 00:03:13 +0000920 // If we have an error assume that we've already handled it.
921 case AsmToken::Error:
922 return true;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000923 case AsmToken::Exclaim:
Sean Callanan686ed8d2010-01-19 20:22:31 +0000924 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +0000925 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000926 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +0000927 Res = MCUnaryExpr::createLNot(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +0000928 return false;
Daniel Dunbar24764322010-08-24 19:13:42 +0000929 case AsmToken::Dollar:
Hans Wennborgce69d772013-10-18 20:46:28 +0000930 case AsmToken::At:
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +0000931 case AsmToken::String:
Daniel Dunbard20cda02009-10-16 01:34:54 +0000932 case AsmToken::Identifier: {
Daniel Dunbar24764322010-08-24 19:13:42 +0000933 StringRef Identifier;
Jim Grosbachd2037eb2013-02-20 22:21:35 +0000934 if (parseIdentifier(Identifier)) {
David Majnemer0c58bc62013-09-25 10:47:21 +0000935 if (FirstTokenKind == AsmToken::Dollar) {
936 if (Lexer.getMAI().getDollarIsPC()) {
937 // 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;
980 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Hans Wennborg69918bc2013-10-17 01:13:02 +0000981
Hans Wennborg7ddcdc82013-10-18 02:14:40 +0000982 // Lookup the symbol variant if used.
David Peixotto8ad70b32013-12-04 22:43:20 +0000983 if (Split.second.size()) {
Hans Wennborg7ddcdc82013-10-18 02:14:40 +0000984 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Hans Wennborgce69d772013-10-18 20:46:28 +0000985 if (Variant != MCSymbolRefExpr::VK_Invalid) {
986 SymbolName = Split.first;
David Peixotto8ad70b32013-12-04 22:43:20 +0000987 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
Hans Wennborgce69d772013-10-18 20:46:28 +0000988 Variant = MCSymbolRefExpr::VK_None;
989 } else {
Saleem Abdulrasoola25e1e42014-01-26 22:29:43 +0000990 return Error(SMLoc::getFromPointer(Split.second.begin()),
991 "invalid variant '" + Split.second + "'");
Daniel Dunbar55f16672010-09-17 02:47:07 +0000992 }
993 }
Daniel Dunbar55992562010-03-15 23:51:06 +0000994
Jim Grosbach6f482002015-05-18 18:43:14 +0000995 MCSymbol *Sym = getContext().getOrCreateSymbol(SymbolName);
Hans Wennborgce69d772013-10-18 20:46:28 +0000996
Daniel Dunbard20cda02009-10-16 01:34:54 +0000997 // If this is an absolute variable reference, substitute it now to preserve
998 // semantics in the face of reassignment.
Vedant Kumar86dbd922015-08-31 17:44:53 +0000999 if (Sym->isVariable() &&
1000 isa<MCConstantExpr>(Sym->getVariableValue(/*SetUsed*/ false))) {
Daniel Dunbar55992562010-03-15 23:51:06 +00001001 if (Variant)
Daniel Dunbar8a3c3f22010-11-08 17:53:02 +00001002 return Error(EndLoc, "unexpected modifier on variable reference");
Daniel Dunbar55992562010-03-15 23:51:06 +00001003
Vedant Kumar86dbd922015-08-31 17:44:53 +00001004 Res = Sym->getVariableValue(/*SetUsed*/ false);
Daniel Dunbard20cda02009-10-16 01:34:54 +00001005 return false;
1006 }
1007
1008 // Otherwise create a symbol ref.
Jim Grosbach13760bd2015-05-30 01:25:56 +00001009 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
Chris Lattner78db3622009-06-22 05:51:26 +00001010 return false;
Daniel Dunbard20cda02009-10-16 01:34:54 +00001011 }
David Woodhousef42a6662014-02-01 16:20:54 +00001012 case AsmToken::BigNum:
1013 return TokError("literal value out of range for directive");
Kevin Enderby0510b482010-05-17 23:08:19 +00001014 case AsmToken::Integer: {
1015 SMLoc Loc = getTok().getLoc();
1016 int64_t IntVal = getTok().getIntVal();
Jim Grosbach13760bd2015-05-30 01:25:56 +00001017 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001018 EndLoc = Lexer.getTok().getEndLoc();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001019 Lex(); // Eat token.
Kevin Enderby0510b482010-05-17 23:08:19 +00001020 // Look for 'b' or 'f' following an Integer as a directional label
1021 if (Lexer.getKind() == AsmToken::Identifier) {
1022 StringRef IDVal = getTok().getString();
Ulrich Weigandd4120982013-06-20 16:24:17 +00001023 // Lookup the symbol variant if used.
1024 std::pair<StringRef, StringRef> Split = IDVal.split('@');
1025 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
1026 if (Split.first.size() != IDVal.size()) {
1027 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
Arnaud A. de Grandmaisonc97727a2014-03-21 21:54:46 +00001028 if (Variant == MCSymbolRefExpr::VK_Invalid)
Ulrich Weigandd4120982013-06-20 16:24:17 +00001029 return TokError("invalid variant '" + Split.second + "'");
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001030 IDVal = Split.first;
Ulrich Weigandd4120982013-06-20 16:24:17 +00001031 }
Jim Grosbach4b905842013-09-20 23:08:21 +00001032 if (IDVal == "f" || IDVal == "b") {
1033 MCSymbol *Sym =
Jim Grosbach6f482002015-05-18 18:43:14 +00001034 Ctx.getDirectionalLocalSymbol(IntVal, IDVal == "b");
Jim Grosbach13760bd2015-05-30 01:25:56 +00001035 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00001036 if (IDVal == "b" && Sym->isUndefined())
Tim Northover6b3169b2016-04-11 19:50:46 +00001037 return Error(Loc, "directional label undefined");
Tim Northoverc0bef992016-04-13 19:46:54 +00001038 DirLabels.push_back(std::make_tuple(Loc, CppHashInfo, Sym));
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001039 EndLoc = Lexer.getTok().getEndLoc();
Kevin Enderby0510b482010-05-17 23:08:19 +00001040 Lex(); // Eat identifier.
1041 }
1042 }
Chris Lattner78db3622009-06-22 05:51:26 +00001043 return false;
Kevin Enderby0510b482010-05-17 23:08:19 +00001044 }
Bill Wendlingcdbf17b2011-01-25 21:26:41 +00001045 case AsmToken::Real: {
1046 APFloat RealVal(APFloat::IEEEdouble, getTok().getString());
Bob Wilson813bdf62011-02-03 23:17:47 +00001047 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
Jim Grosbach13760bd2015-05-30 01:25:56 +00001048 Res = MCConstantExpr::create(IntVal, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001049 EndLoc = Lexer.getTok().getEndLoc();
Bill Wendlingcdbf17b2011-01-25 21:26:41 +00001050 Lex(); // Eat token.
1051 return false;
1052 }
Chris Lattner6b55cb92010-04-14 04:40:28 +00001053 case AsmToken::Dot: {
1054 // This is a '.' reference, which references the current PC. Emit a
1055 // temporary label to the streamer and refer to it.
Jim Grosbach6f482002015-05-18 18:43:14 +00001056 MCSymbol *Sym = Ctx.createTempSymbol();
Chris Lattner6b55cb92010-04-14 04:40:28 +00001057 Out.EmitLabel(Sym);
Jim Grosbach13760bd2015-05-30 01:25:56 +00001058 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001059 EndLoc = Lexer.getTok().getEndLoc();
Chris Lattner6b55cb92010-04-14 04:40:28 +00001060 Lex(); // Eat identifier.
1061 return false;
1062 }
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001063 case AsmToken::LParen:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001064 Lex(); // Eat the '('.
Jim Grosbach4b905842013-09-20 23:08:21 +00001065 return parseParenExpr(Res, EndLoc);
Joerg Sonnenbergerafb36fa2011-02-24 21:59:22 +00001066 case AsmToken::LBrac:
1067 if (!PlatformParser->HasBracketExpressions())
1068 return TokError("brackets expression not supported on this target");
1069 Lex(); // Eat the '['.
Jim Grosbach4b905842013-09-20 23:08:21 +00001070 return parseBracketExpr(Res, EndLoc);
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001071 case AsmToken::Minus:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001072 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001073 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001074 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001075 Res = MCUnaryExpr::createMinus(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001076 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001077 case AsmToken::Plus:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001078 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001079 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001080 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001081 Res = MCUnaryExpr::createPlus(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001082 return false;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001083 case AsmToken::Tilde:
Sean Callanan686ed8d2010-01-19 20:22:31 +00001084 Lex(); // Eat the operator.
Jim Grosbach4b905842013-09-20 23:08:21 +00001085 if (parsePrimaryExpr(Res, EndLoc))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001086 return true;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001087 Res = MCUnaryExpr::createNot(Res, getContext());
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001088 return false;
Daniel Sanders3feeb9c2016-08-08 11:50:25 +00001089 // MIPS unary expression operators. The lexer won't generate these tokens if
1090 // MCAsmInfo::HasMipsExpressions is false for the target.
1091 case AsmToken::PercentCall16:
1092 case AsmToken::PercentCall_Hi:
1093 case AsmToken::PercentCall_Lo:
1094 case AsmToken::PercentDtprel_Hi:
1095 case AsmToken::PercentDtprel_Lo:
1096 case AsmToken::PercentGot:
1097 case AsmToken::PercentGot_Disp:
1098 case AsmToken::PercentGot_Hi:
1099 case AsmToken::PercentGot_Lo:
1100 case AsmToken::PercentGot_Ofst:
1101 case AsmToken::PercentGot_Page:
1102 case AsmToken::PercentGottprel:
1103 case AsmToken::PercentGp_Rel:
1104 case AsmToken::PercentHi:
1105 case AsmToken::PercentHigher:
1106 case AsmToken::PercentHighest:
1107 case AsmToken::PercentLo:
1108 case AsmToken::PercentNeg:
1109 case AsmToken::PercentPcrel_Hi:
1110 case AsmToken::PercentPcrel_Lo:
1111 case AsmToken::PercentTlsgd:
1112 case AsmToken::PercentTlsldm:
1113 case AsmToken::PercentTprel_Hi:
1114 case AsmToken::PercentTprel_Lo:
1115 Lex(); // Eat the operator.
1116 if (Lexer.isNot(AsmToken::LParen))
1117 return TokError("expected '(' after operator");
1118 Lex(); // Eat the operator.
1119 if (parseExpression(Res, EndLoc))
1120 return true;
1121 if (Lexer.isNot(AsmToken::RParen))
1122 return TokError("expected ')'");
1123 Lex(); // Eat the operator.
1124 Res = getTargetParser().createTargetUnaryExpr(Res, FirstTokenKind, Ctx);
1125 return !Res;
Chris Lattner78db3622009-06-22 05:51:26 +00001126 }
1127}
Chris Lattner7fdbce72009-06-22 06:32:03 +00001128
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001129bool AsmParser::parseExpression(const MCExpr *&Res) {
Chris Lattnere17df0b2010-01-15 19:39:23 +00001130 SMLoc EndLoc;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001131 return parseExpression(Res, EndLoc);
Chris Lattner528d00b2010-01-15 19:28:38 +00001132}
1133
Daniel Dunbar55f16672010-09-17 02:47:07 +00001134const MCExpr *
Jim Grosbach4b905842013-09-20 23:08:21 +00001135AsmParser::applyModifierToExpr(const MCExpr *E,
Daniel Dunbar55f16672010-09-17 02:47:07 +00001136 MCSymbolRefExpr::VariantKind Variant) {
Joerg Sonnenbergerb822af42013-08-27 20:23:19 +00001137 // Ask the target implementation about this expression first.
1138 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
1139 if (NewE)
1140 return NewE;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001141 // Recurse over the given expression, rebuilding it to apply the given variant
1142 // if there is exactly one symbol.
1143 switch (E->getKind()) {
1144 case MCExpr::Target:
1145 case MCExpr::Constant:
Craig Topper353eda42014-04-24 06:44:33 +00001146 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001147
1148 case MCExpr::SymbolRef: {
1149 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
1150
1151 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001152 TokError("invalid variant on expression '" + getTok().getIdentifier() +
1153 "' (already modified)");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001154 return E;
1155 }
1156
Jim Grosbach13760bd2015-05-30 01:25:56 +00001157 return MCSymbolRefExpr::create(&SRE->getSymbol(), Variant, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001158 }
1159
1160 case MCExpr::Unary: {
1161 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +00001162 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001163 if (!Sub)
Craig Topper353eda42014-04-24 06:44:33 +00001164 return nullptr;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001165 return MCUnaryExpr::create(UE->getOpcode(), Sub, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001166 }
1167
1168 case MCExpr::Binary: {
1169 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
Jim Grosbach4b905842013-09-20 23:08:21 +00001170 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
1171 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001172
1173 if (!LHS && !RHS)
Craig Topper353eda42014-04-24 06:44:33 +00001174 return nullptr;
Daniel Dunbar55f16672010-09-17 02:47:07 +00001175
Jim Grosbach4b905842013-09-20 23:08:21 +00001176 if (!LHS)
1177 LHS = BE->getLHS();
1178 if (!RHS)
1179 RHS = BE->getRHS();
Daniel Dunbar55f16672010-09-17 02:47:07 +00001180
Jim Grosbach13760bd2015-05-30 01:25:56 +00001181 return MCBinaryExpr::create(BE->getOpcode(), LHS, RHS, getContext());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001182 }
1183 }
Daniel Dunbarbaad46c2010-09-17 16:34:24 +00001184
Craig Toppera2886c22012-02-07 05:05:23 +00001185 llvm_unreachable("Invalid expression kind!");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001186}
1187
Jim Grosbach4b905842013-09-20 23:08:21 +00001188/// \brief Parse an expression and return it.
Michael J. Spencer530ce852010-10-09 11:00:50 +00001189///
Jim Grosbachbd164242011-08-20 16:24:13 +00001190/// expr ::= expr &&,|| expr -> lowest.
1191/// expr ::= expr |,^,&,! expr
1192/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1193/// expr ::= expr <<,>> expr
1194/// expr ::= expr +,- expr
1195/// expr ::= expr *,/,% expr -> highest.
Chris Lattner7fdbce72009-06-22 06:32:03 +00001196/// expr ::= primaryexpr
1197///
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001198bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001199 // Parse the expression.
Craig Topper353eda42014-04-24 06:44:33 +00001200 Res = nullptr;
Jim Grosbach4b905842013-09-20 23:08:21 +00001201 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001202 return true;
1203
Daniel Dunbar55f16672010-09-17 02:47:07 +00001204 // As a special case, we support 'a op b @ modifier' by rewriting the
1205 // expression to include the modifier. This is inefficient, but in general we
1206 // expect users to use 'a@modifier op b'.
1207 if (Lexer.getKind() == AsmToken::At) {
1208 Lex();
1209
1210 if (Lexer.isNot(AsmToken::Identifier))
1211 return TokError("unexpected symbol modifier following '@'");
1212
1213 MCSymbolRefExpr::VariantKind Variant =
Jim Grosbach4b905842013-09-20 23:08:21 +00001214 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
Daniel Dunbar55f16672010-09-17 02:47:07 +00001215 if (Variant == MCSymbolRefExpr::VK_Invalid)
1216 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1217
Jim Grosbach4b905842013-09-20 23:08:21 +00001218 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
Daniel Dunbar55f16672010-09-17 02:47:07 +00001219 if (!ModifiedRes) {
1220 return TokError("invalid modifier '" + getTok().getIdentifier() +
1221 "' (no symbols present)");
Daniel Dunbar55f16672010-09-17 02:47:07 +00001222 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001223
Daniel Dunbar55f16672010-09-17 02:47:07 +00001224 Res = ModifiedRes;
1225 Lex();
1226 }
1227
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001228 // Try to constant fold it up front, if possible.
1229 int64_t Value;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001230 if (Res->evaluateAsAbsolute(Value))
1231 Res = MCConstantExpr::create(Value, getContext());
Daniel Dunbard0c6d362010-02-13 01:28:07 +00001232
1233 return false;
Chris Lattner7fdbce72009-06-22 06:32:03 +00001234}
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001235
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001236bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
Craig Topper353eda42014-04-24 06:44:33 +00001237 Res = nullptr;
Jim Grosbach4b905842013-09-20 23:08:21 +00001238 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
Daniel Dunbar7c82d562009-08-31 08:08:17 +00001239}
1240
Toma Tabacu7bc44dc2015-06-25 09:52:02 +00001241bool AsmParser::parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
1242 SMLoc &EndLoc) {
1243 if (parseParenExpr(Res, EndLoc))
1244 return true;
1245
1246 for (; ParenDepth > 0; --ParenDepth) {
1247 if (parseBinOpRHS(1, Res, EndLoc))
1248 return true;
1249
1250 // We don't Lex() the last RParen.
1251 // This is the same behavior as parseParenExpression().
1252 if (ParenDepth - 1 > 0) {
Nirav Davea645433c2016-07-18 15:24:03 +00001253 EndLoc = getTok().getEndLoc();
1254 if (parseToken(AsmToken::RParen,
1255 "expected ')' in parentheses expression"))
1256 return true;
Toma Tabacu7bc44dc2015-06-25 09:52:02 +00001257 }
1258 }
1259 return false;
1260}
1261
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001262bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
Daniel Dunbarf3636452009-08-31 08:07:22 +00001263 const MCExpr *Expr;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001264
Daniel Dunbar75630b32009-06-30 02:10:03 +00001265 SMLoc StartLoc = Lexer.getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001266 if (parseExpression(Expr))
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001267 return true;
1268
Jim Grosbach13760bd2015-05-30 01:25:56 +00001269 if (!Expr->evaluateAsAbsolute(Res))
Daniel Dunbar75630b32009-06-30 02:10:03 +00001270 return Error(StartLoc, "expected absolute expression");
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001271
1272 return false;
1273}
1274
David Majnemer0993e0b2015-10-26 03:15:34 +00001275static unsigned getDarwinBinOpPrecedence(AsmToken::TokenKind K,
1276 MCBinaryExpr::Opcode &Kind,
1277 bool ShouldUseLogicalShr) {
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001278 switch (K) {
Daniel Dunbar940cda22009-08-31 08:07:44 +00001279 default:
Jim Grosbach4b905842013-09-20 23:08:21 +00001280 return 0; // not a binop.
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001281
Jim Grosbach4b905842013-09-20 23:08:21 +00001282 // Lowest Precedence: &&, ||
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001283 case AsmToken::AmpAmp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001284 Kind = MCBinaryExpr::LAnd;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001285 return 1;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001286 case AsmToken::PipePipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001287 Kind = MCBinaryExpr::LOr;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001288 return 1;
1289
Jim Grosbach4b905842013-09-20 23:08:21 +00001290 // Low Precedence: |, &, ^
1291 //
1292 // FIXME: gas seems to support '!' as an infix operator?
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001293 case AsmToken::Pipe:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001294 Kind = MCBinaryExpr::Or;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001295 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001296 case AsmToken::Caret:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001297 Kind = MCBinaryExpr::Xor;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001298 return 2;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001299 case AsmToken::Amp:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001300 Kind = MCBinaryExpr::And;
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001301 return 2;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001302
Jim Grosbach4b905842013-09-20 23:08:21 +00001303 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
Chris Lattner2bb9504d2010-09-22 05:05:16 +00001304 case AsmToken::EqualEqual:
1305 Kind = MCBinaryExpr::EQ;
1306 return 3;
1307 case AsmToken::ExclaimEqual:
1308 case AsmToken::LessGreater:
1309 Kind = MCBinaryExpr::NE;
1310 return 3;
1311 case AsmToken::Less:
1312 Kind = MCBinaryExpr::LT;
1313 return 3;
1314 case AsmToken::LessEqual:
1315 Kind = MCBinaryExpr::LTE;
1316 return 3;
1317 case AsmToken::Greater:
1318 Kind = MCBinaryExpr::GT;
1319 return 3;
1320 case AsmToken::GreaterEqual:
1321 Kind = MCBinaryExpr::GTE;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001322 return 3;
1323
Jim Grosbach4b905842013-09-20 23:08:21 +00001324 // Intermediate Precedence: <<, >>
Jim Grosbachbd164242011-08-20 16:24:13 +00001325 case AsmToken::LessLess:
1326 Kind = MCBinaryExpr::Shl;
1327 return 4;
1328 case AsmToken::GreaterGreater:
David Majnemer0993e0b2015-10-26 03:15:34 +00001329 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
Jim Grosbachbd164242011-08-20 16:24:13 +00001330 return 4;
1331
Jim Grosbach4b905842013-09-20 23:08:21 +00001332 // High Intermediate Precedence: +, -
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001333 case AsmToken::Plus:
1334 Kind = MCBinaryExpr::Add;
Jim Grosbachbd164242011-08-20 16:24:13 +00001335 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001336 case AsmToken::Minus:
1337 Kind = MCBinaryExpr::Sub;
Jim Grosbachbd164242011-08-20 16:24:13 +00001338 return 5;
Daniel Dunbarb3a48f32010-10-25 20:18:56 +00001339
Jim Grosbach4b905842013-09-20 23:08:21 +00001340 // Highest Precedence: *, /, %
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001341 case AsmToken::Star:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001342 Kind = MCBinaryExpr::Mul;
Jim Grosbachbd164242011-08-20 16:24:13 +00001343 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001344 case AsmToken::Slash:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001345 Kind = MCBinaryExpr::Div;
Jim Grosbachbd164242011-08-20 16:24:13 +00001346 return 6;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001347 case AsmToken::Percent:
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001348 Kind = MCBinaryExpr::Mod;
Jim Grosbachbd164242011-08-20 16:24:13 +00001349 return 6;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001350 }
1351}
1352
David Majnemer0993e0b2015-10-26 03:15:34 +00001353static unsigned getGNUBinOpPrecedence(AsmToken::TokenKind K,
1354 MCBinaryExpr::Opcode &Kind,
1355 bool ShouldUseLogicalShr) {
1356 switch (K) {
1357 default:
1358 return 0; // not a binop.
1359
1360 // Lowest Precedence: &&, ||
1361 case AsmToken::AmpAmp:
1362 Kind = MCBinaryExpr::LAnd;
1363 return 2;
1364 case AsmToken::PipePipe:
1365 Kind = MCBinaryExpr::LOr;
1366 return 1;
1367
1368 // Low Precedence: ==, !=, <>, <, <=, >, >=
1369 case AsmToken::EqualEqual:
1370 Kind = MCBinaryExpr::EQ;
1371 return 3;
1372 case AsmToken::ExclaimEqual:
1373 case AsmToken::LessGreater:
1374 Kind = MCBinaryExpr::NE;
1375 return 3;
1376 case AsmToken::Less:
1377 Kind = MCBinaryExpr::LT;
1378 return 3;
1379 case AsmToken::LessEqual:
1380 Kind = MCBinaryExpr::LTE;
1381 return 3;
1382 case AsmToken::Greater:
1383 Kind = MCBinaryExpr::GT;
1384 return 3;
1385 case AsmToken::GreaterEqual:
1386 Kind = MCBinaryExpr::GTE;
1387 return 3;
1388
1389 // Low Intermediate Precedence: +, -
1390 case AsmToken::Plus:
1391 Kind = MCBinaryExpr::Add;
1392 return 4;
1393 case AsmToken::Minus:
1394 Kind = MCBinaryExpr::Sub;
1395 return 4;
1396
1397 // High Intermediate Precedence: |, &, ^
1398 //
1399 // FIXME: gas seems to support '!' as an infix operator?
1400 case AsmToken::Pipe:
1401 Kind = MCBinaryExpr::Or;
1402 return 5;
1403 case AsmToken::Caret:
1404 Kind = MCBinaryExpr::Xor;
1405 return 5;
1406 case AsmToken::Amp:
1407 Kind = MCBinaryExpr::And;
1408 return 5;
1409
1410 // Highest Precedence: *, /, %, <<, >>
1411 case AsmToken::Star:
1412 Kind = MCBinaryExpr::Mul;
1413 return 6;
1414 case AsmToken::Slash:
1415 Kind = MCBinaryExpr::Div;
1416 return 6;
1417 case AsmToken::Percent:
1418 Kind = MCBinaryExpr::Mod;
1419 return 6;
1420 case AsmToken::LessLess:
1421 Kind = MCBinaryExpr::Shl;
1422 return 6;
1423 case AsmToken::GreaterGreater:
1424 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1425 return 6;
1426 }
1427}
1428
1429unsigned AsmParser::getBinOpPrecedence(AsmToken::TokenKind K,
1430 MCBinaryExpr::Opcode &Kind) {
1431 bool ShouldUseLogicalShr = MAI.shouldUseLogicalShr();
1432 return IsDarwin ? getDarwinBinOpPrecedence(K, Kind, ShouldUseLogicalShr)
1433 : getGNUBinOpPrecedence(K, Kind, ShouldUseLogicalShr);
1434}
1435
Jim Grosbach4b905842013-09-20 23:08:21 +00001436/// \brief Parse all binary operators with precedence >= 'Precedence'.
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001437/// Res contains the LHS of the expression on input.
Jim Grosbach4b905842013-09-20 23:08:21 +00001438bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
Chris Lattner528d00b2010-01-15 19:28:38 +00001439 SMLoc &EndLoc) {
Eugene Zelenko33d7b762016-08-23 17:14:32 +00001440 while (true) {
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001441 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001442 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001443
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001444 // If the next token is lower precedence than we are allowed to eat, return
1445 // successfully with what we ate already.
1446 if (TokPrec < Precedence)
1447 return false;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001448
Sean Callanan686ed8d2010-01-19 20:22:31 +00001449 Lex();
Michael J. Spencer530ce852010-10-09 11:00:50 +00001450
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001451 // Eat the next primary expression.
Daniel Dunbarf3636452009-08-31 08:07:22 +00001452 const MCExpr *RHS;
Jim Grosbach4b905842013-09-20 23:08:21 +00001453 if (parsePrimaryExpr(RHS, EndLoc))
1454 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00001455
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001456 // If BinOp binds less tightly with RHS than the operator after RHS, let
1457 // the pending operator take RHS as its LHS.
Daniel Dunbar115e4d62009-08-31 08:06:59 +00001458 MCBinaryExpr::Opcode Dummy;
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001459 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
Jim Grosbach4b905842013-09-20 23:08:21 +00001460 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1461 return true;
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001462
Daniel Dunbar7e8d6c72009-06-29 20:37:27 +00001463 // Merge LHS and RHS according to operator.
Jim Grosbach13760bd2015-05-30 01:25:56 +00001464 Res = MCBinaryExpr::create(Kind, Res, RHS, getContext());
Chris Lattnerf97d8bb2009-06-23 05:57:07 +00001465 }
1466}
1467
Chris Lattner36e02122009-06-21 20:54:55 +00001468/// ParseStatement:
1469/// ::= EndOfStatement
Chris Lattnere5074c42009-06-22 01:29:09 +00001470/// ::= Label* Directive ...Operands... EndOfStatement
1471/// ::= Label* Identifier OperandList* EndOfStatement
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001472bool AsmParser::parseStatement(ParseStatementInfo &Info,
1473 MCAsmParserSemaCallback *SI) {
Nirav Davefd910412016-06-17 16:06:17 +00001474 // Eat initial spaces and comments
1475 while (Lexer.is(AsmToken::Space))
1476 Lex();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001477 if (Lexer.is(AsmToken::EndOfStatement)) {
Nirav Davefd910412016-06-17 16:06:17 +00001478 // if this is a line comment we can drop it safely
1479 if (getTok().getString().front() == '\r' ||
1480 getTok().getString().front() == '\n')
1481 Out.AddBlankLine();
Sean Callanan686ed8d2010-01-19 20:22:31 +00001482 Lex();
Chris Lattner36e02122009-06-21 20:54:55 +00001483 return false;
Chris Lattner36e02122009-06-21 20:54:55 +00001484 }
Nirav Dave9263ae32016-08-02 19:17:54 +00001485 if (Lexer.is(AsmToken::Hash)) {
1486 // Seeing a hash here means that it was an end-of-line comment in
1487 // an asm syntax where hash's are not comment and the previous
1488 // statement parser did not check the end of statement. Relex as
1489 // EndOfStatement.
1490 StringRef CommentStr = parseStringToEndOfStatement();
1491 Lexer.Lex();
1492 Lexer.UnLex(AsmToken(AsmToken::EndOfStatement, CommentStr));
1493 return false;
1494 }
Nirav Davefd910412016-06-17 16:06:17 +00001495 // Statements always start with an identifier.
Sean Callanan936b0d32010-01-19 21:44:56 +00001496 AsmToken ID = getTok();
Daniel Dunbaree4465c2009-07-28 16:38:40 +00001497 SMLoc IDLoc = ID.getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001498 StringRef IDVal;
Kevin Enderby0510b482010-05-17 23:08:19 +00001499 int64_t LocalLabelVal = -1;
Nirav Davefd910412016-06-17 16:06:17 +00001500 if (Lexer.is(AsmToken::HashDirective))
Jim Grosbach4b905842013-09-20 23:08:21 +00001501 return parseCppHashLineFilenameComment(IDLoc);
Kevin Enderbyfa3c6f12010-12-24 00:12:02 +00001502 // Allow an integer followed by a ':' as a directional local label.
Kevin Enderby0510b482010-05-17 23:08:19 +00001503 if (Lexer.is(AsmToken::Integer)) {
1504 LocalLabelVal = getTok().getIntVal();
1505 if (LocalLabelVal < 0) {
1506 if (!TheCondState.Ignore)
1507 return TokError("unexpected token at start of statement");
1508 IDVal = "";
Eli Bendersky88024712013-01-16 19:32:36 +00001509 } else {
Kevin Enderby0510b482010-05-17 23:08:19 +00001510 IDVal = getTok().getString();
1511 Lex(); // Consume the integer token to be used as an identifier token.
1512 if (Lexer.getKind() != AsmToken::Colon) {
Duncan Sands41b4a6b2010-07-12 08:16:59 +00001513 if (!TheCondState.Ignore)
1514 return TokError("unexpected token at start of statement");
Kevin Enderby0510b482010-05-17 23:08:19 +00001515 }
1516 }
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001517 } else if (Lexer.is(AsmToken::Dot)) {
1518 // Treat '.' as a valid identifier in this context.
1519 Lex();
1520 IDVal = ".";
Colin LeMahieu8a0453e2015-11-09 00:31:07 +00001521 } else if (Lexer.is(AsmToken::LCurly)) {
1522 // Treat '{' as a valid identifier in this context.
1523 Lex();
1524 IDVal = "{";
1525
1526 } else if (Lexer.is(AsmToken::RCurly)) {
1527 // Treat '}' as a valid identifier in this context.
1528 Lex();
1529 IDVal = "}";
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001530 } else if (parseIdentifier(IDVal)) {
Chris Lattner926885c2010-04-17 18:14:27 +00001531 if (!TheCondState.Ignore)
1532 return TokError("unexpected token at start of statement");
1533 IDVal = "";
1534 }
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001535
Chris Lattner926885c2010-04-17 18:14:27 +00001536 // Handle conditional assembly here before checking for skipping. We
1537 // have to do this so that .endif isn't skipped in a ".if 0" block for
1538 // example.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001539 StringMap<DirectiveKind>::const_iterator DirKindIt =
Jim Grosbach4b905842013-09-20 23:08:21 +00001540 DirectiveKindMap.find(IDVal);
1541 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1542 ? DK_NO_DIRECTIVE
1543 : DirKindIt->getValue();
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001544 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001545 default:
1546 break;
1547 case DK_IF:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001548 case DK_IFEQ:
1549 case DK_IFGE:
1550 case DK_IFGT:
1551 case DK_IFLE:
1552 case DK_IFLT:
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00001553 case DK_IFNE:
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00001554 return parseDirectiveIf(IDLoc, DirKind);
Jim Grosbach4b905842013-09-20 23:08:21 +00001555 case DK_IFB:
1556 return parseDirectiveIfb(IDLoc, true);
1557 case DK_IFNB:
1558 return parseDirectiveIfb(IDLoc, false);
1559 case DK_IFC:
1560 return parseDirectiveIfc(IDLoc, true);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00001561 case DK_IFEQS:
Sid Manning51c35602015-03-18 14:20:54 +00001562 return parseDirectiveIfeqs(IDLoc, true);
Jim Grosbach4b905842013-09-20 23:08:21 +00001563 case DK_IFNC:
1564 return parseDirectiveIfc(IDLoc, false);
Sid Manning51c35602015-03-18 14:20:54 +00001565 case DK_IFNES:
1566 return parseDirectiveIfeqs(IDLoc, false);
Jim Grosbach4b905842013-09-20 23:08:21 +00001567 case DK_IFDEF:
1568 return parseDirectiveIfdef(IDLoc, true);
1569 case DK_IFNDEF:
1570 case DK_IFNOTDEF:
1571 return parseDirectiveIfdef(IDLoc, false);
1572 case DK_ELSEIF:
1573 return parseDirectiveElseIf(IDLoc);
1574 case DK_ELSE:
1575 return parseDirectiveElse(IDLoc);
1576 case DK_ENDIF:
1577 return parseDirectiveEndIf(IDLoc);
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001578 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001579
Eli Bendersky88024712013-01-16 19:32:36 +00001580 // Ignore the statement if in the middle of inactive conditional
1581 // (e.g. ".if 0").
Chad Rosiereda70b32012-10-20 00:47:08 +00001582 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001583 eatToEndOfStatement();
Chris Lattner926885c2010-04-17 18:14:27 +00001584 return false;
1585 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00001586
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00001587 // FIXME: Recurse on local labels?
1588
1589 // See what kind of statement we have.
1590 switch (Lexer.getKind()) {
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001591 case AsmToken::Colon: {
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001592 if (!getTargetParser().isLabel(ID))
1593 break;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001594 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00001595
Chris Lattner36e02122009-06-21 20:54:55 +00001596 // identifier ':' -> Label.
Sean Callanan686ed8d2010-01-19 20:22:31 +00001597 Lex();
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001598
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001599 // Diagnose attempt to use '.' as a label.
1600 if (IDVal == ".")
1601 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1602
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001603 // Diagnose attempt to use a variable as a label.
1604 //
1605 // FIXME: Diagnostics. Note the location of the definition as a label.
1606 // FIXME: This doesn't diagnose assignment to a symbol which has been
1607 // implicitly marked as external.
Kevin Enderby0510b482010-05-17 23:08:19 +00001608 MCSymbol *Sym;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001609 if (LocalLabelVal == -1) {
1610 if (ParsingInlineAsm && SI) {
Nico Weber67e715f2015-06-19 23:43:47 +00001611 StringRef RewrittenLabel =
1612 SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true);
1613 assert(RewrittenLabel.size() &&
1614 "We should have an internal name here.");
Craig Topper7d5b2312015-10-10 05:25:02 +00001615 Info.AsmRewrites->emplace_back(AOK_Label, IDLoc, IDVal.size(),
1616 RewrittenLabel);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001617 IDVal = RewrittenLabel;
1618 }
Jim Grosbach6f482002015-05-18 18:43:14 +00001619 Sym = getContext().getOrCreateSymbol(IDVal);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001620 } else
Jim Grosbach6f482002015-05-18 18:43:14 +00001621 Sym = Ctx.createDirectionalLocalSymbol(LocalLabelVal);
David Majnemer58cb80c2014-12-24 10:27:50 +00001622
1623 Sym->redefineIfPossible();
1624
Daniel Dunbardeb7ba92010-05-05 19:01:00 +00001625 if (!Sym->isUndefined() || Sym->isVariable())
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001626 return Error(IDLoc, "invalid symbol redefinition");
Michael J. Spencer530ce852010-10-09 11:00:50 +00001627
Nirav Dave9263ae32016-08-02 19:17:54 +00001628 // End of Labels should be treated as end of line for lexing
1629 // purposes but that information is not available to the Lexer who
1630 // does not understand Labels. This may cause us to see a Hash
1631 // here instead of a preprocessor line comment.
1632 if (getTok().is(AsmToken::Hash)) {
1633 StringRef CommentStr = parseStringToEndOfStatement();
1634 Lexer.Lex();
1635 Lexer.UnLex(AsmToken(AsmToken::EndOfStatement, CommentStr));
1636 }
1637
Nirav Dave8ea792d2016-07-13 14:03:12 +00001638 // Consume any end of statement token, if present, to avoid spurious
1639 // AddBlankLine calls().
1640 if (getTok().is(AsmToken::EndOfStatement)) {
1641 Lex();
1642 }
1643
Daniel Dunbare73b2672009-08-26 22:13:22 +00001644 // Emit the label.
Chad Rosierf3feab32013-01-07 20:34:12 +00001645 if (!ParsingInlineAsm)
1646 Out.EmitLabel(Sym);
Michael J. Spencer530ce852010-10-09 11:00:50 +00001647
Kevin Enderbye7739d42011-12-09 18:09:40 +00001648 // If we are generating dwarf for assembly source files then gather the
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001649 // info to make a dwarf label entry for this label if needed.
Kevin Enderbye7739d42011-12-09 18:09:40 +00001650 if (getContext().getGenDwarfForAssembly())
Kevin Enderbyf7d77062012-01-10 21:12:34 +00001651 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1652 IDLoc);
Kevin Enderbye7739d42011-12-09 18:09:40 +00001653
Tim Northover1744d0a2013-10-25 12:49:50 +00001654 getTargetParser().onLabelParsed(Sym);
1655
Eli Friedman0f4871d2012-10-22 23:58:19 +00001656 return false;
Daniel Dunbarae7ac012009-06-29 23:43:14 +00001657 }
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001658
Daniel Dunbarf2dcd772009-07-28 16:08:33 +00001659 case AsmToken::Equal:
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001660 if (!getTargetParser().equalIsAsmAssignment())
1661 break;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001662 // identifier '=' ... -> assignment statement
Sean Callanan686ed8d2010-01-19 20:22:31 +00001663 Lex();
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001664
Jim Grosbach4b905842013-09-20 23:08:21 +00001665 return parseAssignment(IDVal, true);
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00001666
1667 default: // Normal instruction or directive.
1668 break;
Chris Lattner36e02122009-06-21 20:54:55 +00001669 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001670
1671 // If macros are enabled, check to see if this is a macro instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00001672 if (areMacrosEnabled())
1673 if (const MCAsmMacro *M = lookupMacro(IDVal)) {
1674 return handleMacroEntry(M, IDLoc);
Eli Bendersky38274122013-01-14 23:22:36 +00001675 }
Daniel Dunbar43235712010-07-18 18:54:11 +00001676
Michael J. Spencer530ce852010-10-09 11:00:50 +00001677 // Otherwise, we have a normal instruction or directive.
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001678
Eli Bendersky17233942013-01-15 22:59:42 +00001679 // Directives start with "."
Daniel Dunbar6f4c9422011-03-25 17:47:17 +00001680 if (IDVal[0] == '.' && IDVal != ".") {
Eli Bendersky17233942013-01-15 22:59:42 +00001681 // There are several entities interested in parsing directives:
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001682 //
Eli Bendersky17233942013-01-15 22:59:42 +00001683 // 1. The target-specific assembly parser. Some directives are target
1684 // specific or may potentially behave differently on certain targets.
1685 // 2. Asm parser extensions. For example, platform-specific parsers
1686 // (like the ELF parser) register themselves as extensions.
1687 // 3. The generic directive parser implemented by this class. These are
1688 // all the directives that behave in a target and platform independent
1689 // manner, or at least have a default behavior that's shared between
1690 // all targets and platforms.
Akira Hatanakad3590752012-07-05 19:09:33 +00001691
Oliver Stannard21718282016-07-26 14:19:47 +00001692 getTargetParser().flushPendingInstructions(getStreamer());
1693
Eli Bendersky17233942013-01-15 22:59:42 +00001694 // First query the target-specific parser. It will return 'true' if it
1695 // isn't interested in this directive.
Akira Hatanakad3590752012-07-05 19:09:33 +00001696 if (!getTargetParser().ParseDirective(ID))
1697 return false;
1698
Alp Tokercb402912014-01-24 17:20:08 +00001699 // Next, check the extension directive map to see if any extension has
Eli Bendersky17233942013-01-15 22:59:42 +00001700 // registered itself to parse this directive.
Jim Grosbach4b905842013-09-20 23:08:21 +00001701 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1702 ExtensionDirectiveMap.lookup(IDVal);
Eli Bendersky17233942013-01-15 22:59:42 +00001703 if (Handler.first)
1704 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1705
1706 // Finally, if no one else is interested in this directive, it must be
1707 // generic and familiar to this class.
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00001708 switch (DirKind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00001709 default:
1710 break;
1711 case DK_SET:
1712 case DK_EQU:
1713 return parseDirectiveSet(IDVal, true);
1714 case DK_EQUIV:
1715 return parseDirectiveSet(IDVal, false);
1716 case DK_ASCII:
1717 return parseDirectiveAscii(IDVal, false);
1718 case DK_ASCIZ:
1719 case DK_STRING:
1720 return parseDirectiveAscii(IDVal, true);
1721 case DK_BYTE:
1722 return parseDirectiveValue(1);
1723 case DK_SHORT:
1724 case DK_VALUE:
1725 case DK_2BYTE:
1726 return parseDirectiveValue(2);
1727 case DK_LONG:
1728 case DK_INT:
1729 case DK_4BYTE:
1730 return parseDirectiveValue(4);
1731 case DK_QUAD:
1732 case DK_8BYTE:
1733 return parseDirectiveValue(8);
David Woodhoused6de0d92014-02-01 16:20:59 +00001734 case DK_OCTA:
1735 return parseDirectiveOctaValue();
Jim Grosbach4b905842013-09-20 23:08:21 +00001736 case DK_SINGLE:
1737 case DK_FLOAT:
1738 return parseDirectiveRealValue(APFloat::IEEEsingle);
1739 case DK_DOUBLE:
1740 return parseDirectiveRealValue(APFloat::IEEEdouble);
1741 case DK_ALIGN: {
1742 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1743 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1744 }
1745 case DK_ALIGN32: {
1746 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1747 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1748 }
1749 case DK_BALIGN:
1750 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1751 case DK_BALIGNW:
1752 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1753 case DK_BALIGNL:
1754 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1755 case DK_P2ALIGN:
1756 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1757 case DK_P2ALIGNW:
1758 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1759 case DK_P2ALIGNL:
1760 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1761 case DK_ORG:
1762 return parseDirectiveOrg();
1763 case DK_FILL:
1764 return parseDirectiveFill();
1765 case DK_ZERO:
1766 return parseDirectiveZero();
1767 case DK_EXTERN:
1768 eatToEndOfStatement(); // .extern is the default, ignore it.
1769 return false;
1770 case DK_GLOBL:
1771 case DK_GLOBAL:
1772 return parseDirectiveSymbolAttribute(MCSA_Global);
1773 case DK_LAZY_REFERENCE:
1774 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1775 case DK_NO_DEAD_STRIP:
1776 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1777 case DK_SYMBOL_RESOLVER:
1778 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1779 case DK_PRIVATE_EXTERN:
1780 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1781 case DK_REFERENCE:
1782 return parseDirectiveSymbolAttribute(MCSA_Reference);
1783 case DK_WEAK_DEFINITION:
1784 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1785 case DK_WEAK_REFERENCE:
1786 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1787 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1788 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1789 case DK_COMM:
1790 case DK_COMMON:
1791 return parseDirectiveComm(/*IsLocal=*/false);
1792 case DK_LCOMM:
1793 return parseDirectiveComm(/*IsLocal=*/true);
1794 case DK_ABORT:
1795 return parseDirectiveAbort();
1796 case DK_INCLUDE:
1797 return parseDirectiveInclude();
1798 case DK_INCBIN:
1799 return parseDirectiveIncbin();
1800 case DK_CODE16:
1801 case DK_CODE16GCC:
Nirav Davefd910412016-06-17 16:06:17 +00001802 return TokError(Twine(IDVal) +
1803 " not currently supported for this target");
Jim Grosbach4b905842013-09-20 23:08:21 +00001804 case DK_REPT:
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00001805 return parseDirectiveRept(IDLoc, IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001806 case DK_IRP:
1807 return parseDirectiveIrp(IDLoc);
1808 case DK_IRPC:
1809 return parseDirectiveIrpc(IDLoc);
1810 case DK_ENDR:
1811 return parseDirectiveEndr(IDLoc);
1812 case DK_BUNDLE_ALIGN_MODE:
1813 return parseDirectiveBundleAlignMode();
1814 case DK_BUNDLE_LOCK:
1815 return parseDirectiveBundleLock();
1816 case DK_BUNDLE_UNLOCK:
1817 return parseDirectiveBundleUnlock();
1818 case DK_SLEB128:
1819 return parseDirectiveLEB128(true);
1820 case DK_ULEB128:
1821 return parseDirectiveLEB128(false);
1822 case DK_SPACE:
1823 case DK_SKIP:
1824 return parseDirectiveSpace(IDVal);
1825 case DK_FILE:
1826 return parseDirectiveFile(IDLoc);
1827 case DK_LINE:
1828 return parseDirectiveLine();
1829 case DK_LOC:
1830 return parseDirectiveLoc();
1831 case DK_STABS:
1832 return parseDirectiveStabs();
Reid Kleckner2214ed82016-01-29 00:49:42 +00001833 case DK_CV_FILE:
1834 return parseDirectiveCVFile();
1835 case DK_CV_LOC:
1836 return parseDirectiveCVLoc();
1837 case DK_CV_LINETABLE:
1838 return parseDirectiveCVLinetable();
David Majnemer6fcbd7e2016-01-29 19:24:12 +00001839 case DK_CV_INLINE_LINETABLE:
1840 return parseDirectiveCVInlineLinetable();
David Majnemer408b5e62016-02-05 01:55:49 +00001841 case DK_CV_DEF_RANGE:
1842 return parseDirectiveCVDefRange();
Reid Kleckner2214ed82016-01-29 00:49:42 +00001843 case DK_CV_STRINGTABLE:
1844 return parseDirectiveCVStringTable();
1845 case DK_CV_FILECHECKSUMS:
1846 return parseDirectiveCVFileChecksums();
Jim Grosbach4b905842013-09-20 23:08:21 +00001847 case DK_CFI_SECTIONS:
1848 return parseDirectiveCFISections();
1849 case DK_CFI_STARTPROC:
1850 return parseDirectiveCFIStartProc();
1851 case DK_CFI_ENDPROC:
1852 return parseDirectiveCFIEndProc();
1853 case DK_CFI_DEF_CFA:
1854 return parseDirectiveCFIDefCfa(IDLoc);
1855 case DK_CFI_DEF_CFA_OFFSET:
1856 return parseDirectiveCFIDefCfaOffset();
1857 case DK_CFI_ADJUST_CFA_OFFSET:
1858 return parseDirectiveCFIAdjustCfaOffset();
1859 case DK_CFI_DEF_CFA_REGISTER:
1860 return parseDirectiveCFIDefCfaRegister(IDLoc);
1861 case DK_CFI_OFFSET:
1862 return parseDirectiveCFIOffset(IDLoc);
1863 case DK_CFI_REL_OFFSET:
1864 return parseDirectiveCFIRelOffset(IDLoc);
1865 case DK_CFI_PERSONALITY:
1866 return parseDirectiveCFIPersonalityOrLsda(true);
1867 case DK_CFI_LSDA:
1868 return parseDirectiveCFIPersonalityOrLsda(false);
1869 case DK_CFI_REMEMBER_STATE:
1870 return parseDirectiveCFIRememberState();
1871 case DK_CFI_RESTORE_STATE:
1872 return parseDirectiveCFIRestoreState();
1873 case DK_CFI_SAME_VALUE:
1874 return parseDirectiveCFISameValue(IDLoc);
1875 case DK_CFI_RESTORE:
1876 return parseDirectiveCFIRestore(IDLoc);
1877 case DK_CFI_ESCAPE:
1878 return parseDirectiveCFIEscape();
1879 case DK_CFI_SIGNAL_FRAME:
1880 return parseDirectiveCFISignalFrame();
1881 case DK_CFI_UNDEFINED:
1882 return parseDirectiveCFIUndefined(IDLoc);
1883 case DK_CFI_REGISTER:
1884 return parseDirectiveCFIRegister(IDLoc);
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00001885 case DK_CFI_WINDOW_SAVE:
1886 return parseDirectiveCFIWindowSave();
Jim Grosbach4b905842013-09-20 23:08:21 +00001887 case DK_MACROS_ON:
1888 case DK_MACROS_OFF:
1889 return parseDirectiveMacrosOnOff(IDVal);
1890 case DK_MACRO:
1891 return parseDirectiveMacro(IDLoc);
Nico Weber155dccd12014-07-24 17:08:39 +00001892 case DK_EXITM:
1893 return parseDirectiveExitMacro(IDVal);
Jim Grosbach4b905842013-09-20 23:08:21 +00001894 case DK_ENDM:
1895 case DK_ENDMACRO:
1896 return parseDirectiveEndMacro(IDVal);
1897 case DK_PURGEM:
1898 return parseDirectivePurgeMacro(IDLoc);
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00001899 case DK_END:
1900 return parseDirectiveEnd(IDLoc);
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00001901 case DK_ERR:
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00001902 return parseDirectiveError(IDLoc, false);
1903 case DK_ERROR:
1904 return parseDirectiveError(IDLoc, true);
Nico Weber404012b2014-07-24 16:26:06 +00001905 case DK_WARNING:
1906 return parseDirectiveWarning(IDLoc);
Daniel Sanders9f6ad492015-11-12 13:33:00 +00001907 case DK_RELOC:
1908 return parseDirectiveReloc(IDLoc);
Petr Hosek731bb9c2016-08-23 21:34:53 +00001909 case DK_DC:
1910 return parseDirectiveValue(2);
1911 case DK_DC_A:
1912 return parseDirectiveValue(getContext().getAsmInfo()->getPointerSize());
1913 case DK_DC_B:
1914 return parseDirectiveValue(1);
1915 case DK_DC_D:
1916 return parseDirectiveRealValue(APFloat::IEEEdouble);
1917 case DK_DC_L:
1918 return parseDirectiveValue(4);
1919 case DK_DC_S:
1920 return parseDirectiveRealValue(APFloat::IEEEsingle);
1921 case DK_DC_W:
1922 return parseDirectiveValue(2);
1923 case DK_DC_X:
1924 return TokError(Twine(IDVal) +
1925 " not currently supported for this target");
Eli Friedman20b02642010-07-19 04:17:25 +00001926 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00001927
Jim Grosbach758e0cc2012-05-01 18:38:27 +00001928 return Error(IDLoc, "unknown directive");
Chris Lattnere5074c42009-06-22 01:29:09 +00001929 }
Chris Lattner36e02122009-06-21 20:54:55 +00001930
Chad Rosierc7f552c2013-02-12 21:33:51 +00001931 // __asm _emit or __asm __emit
1932 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
1933 IDVal == "_EMIT" || IDVal == "__EMIT"))
Jim Grosbach4b905842013-09-20 23:08:21 +00001934 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
Chad Rosierc7f552c2013-02-12 21:33:51 +00001935
1936 // __asm align
1937 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
Jim Grosbach4b905842013-09-20 23:08:21 +00001938 return parseDirectiveMSAlign(IDLoc, Info);
Eli Friedman0f4871d2012-10-22 23:58:19 +00001939
Michael Zuckerman02ecd432015-12-13 17:07:23 +00001940 if (ParsingInlineAsm && (IDVal == "even"))
1941 Info.AsmRewrites->emplace_back(AOK_EVEN, IDLoc, 4);
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001942 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00001943
Chris Lattner7cbfa442010-05-19 23:34:33 +00001944 // Canonicalize the opcode to lower case.
Eli Bendersky88024712013-01-16 19:32:36 +00001945 std::string OpcodeStr = IDVal.lower();
Chad Rosierf0e87202012-10-25 20:41:34 +00001946 ParseInstructionInfo IInfo(Info.AsmRewrites);
Colin LeMahieu7820dff2015-11-09 00:15:45 +00001947 bool HadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, ID,
Vladimir Medic9bad0d332013-08-20 13:33:18 +00001948 Info.ParsedOperands);
Chad Rosier149e8e02012-12-12 22:45:52 +00001949 Info.ParseError = HadError;
Chris Lattnere5074c42009-06-22 01:29:09 +00001950
Daniel Dunbar2eca0252010-08-11 06:37:09 +00001951 // Dump the parsed representation, if requested.
1952 if (getShowParsedOperands()) {
1953 SmallString<256> Str;
1954 raw_svector_ostream OS(Str);
1955 OS << "parsed instruction: [";
Eli Friedman0f4871d2012-10-22 23:58:19 +00001956 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
Daniel Dunbar2eca0252010-08-11 06:37:09 +00001957 if (i != 0)
1958 OS << ", ";
Eli Friedman0f4871d2012-10-22 23:58:19 +00001959 Info.ParsedOperands[i]->print(OS);
Daniel Dunbar2eca0252010-08-11 06:37:09 +00001960 }
1961 OS << "]";
1962
Jim Grosbach4b905842013-09-20 23:08:21 +00001963 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
Daniel Dunbar2eca0252010-08-11 06:37:09 +00001964 }
1965
Oliver Stannard8b273082014-06-19 15:52:37 +00001966 // If we are generating dwarf for the current section then generate a .loc
1967 // directive for the instruction.
Kevin Enderby6469fc22011-11-01 22:27:22 +00001968 if (!HadError && getContext().getGenDwarfForAssembly() &&
Oliver Stannard8b273082014-06-19 15:52:37 +00001969 getContext().getGenDwarfSectionSyms().count(
Saleem Abdulrasool4d6ed7c2014-12-24 06:32:43 +00001970 getStreamer().getCurrentSection().first)) {
1971 unsigned Line;
1972 if (ActiveMacros.empty())
1973 Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
1974 else
Frederic Riss16238d92015-06-25 21:57:33 +00001975 Line = SrcMgr.FindLineNumber(ActiveMacros.front()->InstantiationLoc,
1976 ActiveMacros.front()->ExitBuffer);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00001977
Eli Bendersky88024712013-01-16 19:32:36 +00001978 // If we previously parsed a cpp hash file line comment then make sure the
1979 // current Dwarf File is for the CppHashFilename if not then emit the
1980 // Dwarf File table for it and adjust the line number for the .loc.
Tim Northoverc0bef992016-04-13 19:46:54 +00001981 if (CppHashInfo.Filename.size()) {
David Blaikiec714ef42014-03-17 01:52:11 +00001982 unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
Tim Northoverc0bef992016-04-13 19:46:54 +00001983 0, StringRef(), CppHashInfo.Filename);
David Blaikiec714ef42014-03-17 01:52:11 +00001984 getContext().setGenDwarfFileNumber(FileNumber);
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00001985
Jim Grosbach4b905842013-09-20 23:08:21 +00001986 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
1987 // cache with the different Loc from the call above we save the last
1988 // info we queried here with SrcMgr.FindLineNumber().
1989 unsigned CppHashLocLineNo;
Tim Northoverc0bef992016-04-13 19:46:54 +00001990 if (LastQueryIDLoc == CppHashInfo.Loc &&
1991 LastQueryBuffer == CppHashInfo.Buf)
Jim Grosbach4b905842013-09-20 23:08:21 +00001992 CppHashLocLineNo = LastQueryLine;
1993 else {
Tim Northoverc0bef992016-04-13 19:46:54 +00001994 CppHashLocLineNo =
1995 SrcMgr.FindLineNumber(CppHashInfo.Loc, CppHashInfo.Buf);
Jim Grosbach4b905842013-09-20 23:08:21 +00001996 LastQueryLine = CppHashLocLineNo;
Tim Northoverc0bef992016-04-13 19:46:54 +00001997 LastQueryIDLoc = CppHashInfo.Loc;
1998 LastQueryBuffer = CppHashInfo.Buf;
Jim Grosbach4b905842013-09-20 23:08:21 +00001999 }
Tim Northoverc0bef992016-04-13 19:46:54 +00002000 Line = CppHashInfo.LineNumber - 1 + (Line - CppHashLocLineNo);
Eli Bendersky88024712013-01-16 19:32:36 +00002001 }
Kevin Enderby4eaf8ef2012-11-01 17:31:35 +00002002
Jim Grosbach4b905842013-09-20 23:08:21 +00002003 getStreamer().EmitDwarfLocDirective(
2004 getContext().getGenDwarfFileNumber(), Line, 0,
2005 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0, 0, 0,
2006 StringRef());
Kevin Enderby6469fc22011-11-01 22:27:22 +00002007 }
2008
Daniel Dunbarce0c1e12010-05-04 00:33:07 +00002009 // If parsing succeeded, match the instruction.
Chad Rosier49963552012-10-13 00:26:04 +00002010 if (!HadError) {
Tim Northover26bb14e2014-08-18 11:49:42 +00002011 uint64_t ErrorInfo;
Arnaud A. de Grandmaisonc97727a2014-03-21 21:54:46 +00002012 getTargetParser().MatchAndEmitInstruction(IDLoc, Info.Opcode,
2013 Info.ParsedOperands, Out,
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002014 ErrorInfo, ParsingInlineAsm);
Chad Rosier49963552012-10-13 00:26:04 +00002015 }
Chris Lattnerf29c0b62010-01-14 22:21:20 +00002016
Chris Lattnera2a9d162010-09-11 16:18:25 +00002017 // Don't skip the rest of the line, the instruction parser is responsible for
2018 // that.
2019 return false;
Chris Lattnerb0133452009-06-21 20:16:42 +00002020}
Chris Lattnerbedf6c22009-06-24 04:43:34 +00002021
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00002022// Parse and erase curly braces marking block start/end
2023bool
2024AsmParser::parseCurlyBlockScope(SmallVectorImpl<AsmRewrite> &AsmStrRewrites) {
2025 // Identify curly brace marking block start/end
2026 if (Lexer.isNot(AsmToken::LCurly) && Lexer.isNot(AsmToken::RCurly))
2027 return false;
2028
2029 SMLoc StartLoc = Lexer.getLoc();
2030 Lex(); // Eat the brace
2031 if (Lexer.is(AsmToken::EndOfStatement))
2032 Lex(); // Eat EndOfStatement following the brace
2033
2034 // Erase the block start/end brace from the output asm string
2035 AsmStrRewrites.emplace_back(AOK_Skip, StartLoc, Lexer.getLoc().getPointer() -
2036 StartLoc.getPointer());
2037 return true;
2038}
2039
Jim Grosbach4b905842013-09-20 23:08:21 +00002040/// parseCppHashLineFilenameComment as this:
Kevin Enderby72553612011-09-13 23:45:18 +00002041/// ::= # number "filename"
Craig Topper3c76c522015-09-20 23:35:59 +00002042bool AsmParser::parseCppHashLineFilenameComment(SMLoc L) {
Kevin Enderby72553612011-09-13 23:45:18 +00002043 Lex(); // Eat the hash token.
Nirav Davefd910412016-06-17 16:06:17 +00002044 // Lexer only ever emits HashDirective if it fully formed if it's
2045 // done the checking already so this is an internal error.
2046 assert(getTok().is(AsmToken::Integer) &&
2047 "Lexing Cpp line comment: Expected Integer");
Kevin Enderby72553612011-09-13 23:45:18 +00002048 int64_t LineNumber = getTok().getIntVal();
Kevin Enderby72553612011-09-13 23:45:18 +00002049 Lex();
Nirav Davefd910412016-06-17 16:06:17 +00002050 assert(getTok().is(AsmToken::String) &&
2051 "Lexing Cpp line comment: Expected String");
Kevin Enderby72553612011-09-13 23:45:18 +00002052 StringRef Filename = getTok().getString();
Nirav Davefd910412016-06-17 16:06:17 +00002053 Lex();
Kevin Enderby72553612011-09-13 23:45:18 +00002054 // Get rid of the enclosing quotes.
Jim Grosbach4b905842013-09-20 23:08:21 +00002055 Filename = Filename.substr(1, Filename.size() - 2);
Kevin Enderby72553612011-09-13 23:45:18 +00002056
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002057 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
Tim Northoverc0bef992016-04-13 19:46:54 +00002058 CppHashInfo.Loc = L;
2059 CppHashInfo.Filename = Filename;
2060 CppHashInfo.LineNumber = LineNumber;
2061 CppHashInfo.Buf = CurBuffer;
Kevin Enderby72553612011-09-13 23:45:18 +00002062 return false;
2063}
2064
Jim Grosbach4b905842013-09-20 23:08:21 +00002065/// \brief will use the last parsed cpp hash line filename comment
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002066/// for the Filename and LineNo if any in the diagnostic.
2067void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002068 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002069 raw_ostream &OS = errs();
2070
2071 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
Craig Topper3c76c522015-09-20 23:35:59 +00002072 SMLoc DiagLoc = Diag.getLoc();
Alp Tokera55b95b2014-07-06 10:33:31 +00002073 unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2074 unsigned CppHashBuf =
Tim Northoverc0bef992016-04-13 19:46:54 +00002075 Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashInfo.Loc);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002076
Jim Grosbach4b905842013-09-20 23:08:21 +00002077 // Like SourceMgr::printMessage() we need to print the include stack if any
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002078 // before printing the message.
Alp Tokera55b95b2014-07-06 10:33:31 +00002079 unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2080 if (!Parser->SavedDiagHandler && DiagCurBuffer &&
2081 DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002082 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
2083 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002084 }
2085
Eric Christophera7c32732012-12-18 00:30:54 +00002086 // If we have not parsed a cpp hash line filename comment or the source
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002087 // manager changed or buffer changed (like in a nested include) then just
2088 // print the normal diagnostic using its Filename and LineNo.
Tim Northoverc0bef992016-04-13 19:46:54 +00002089 if (!Parser->CppHashInfo.LineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002090 DiagBuf != CppHashBuf) {
Benjamin Kramer47f5e302011-10-16 10:48:29 +00002091 if (Parser->SavedDiagHandler)
2092 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
2093 else
Craig Topper353eda42014-04-24 06:44:33 +00002094 Diag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002095 return;
2096 }
2097
Eric Christophera7c32732012-12-18 00:30:54 +00002098 // Use the CppHashFilename and calculate a line number based on the
Tim Northoverc0bef992016-04-13 19:46:54 +00002099 // CppHashInfo.Loc and CppHashInfo.LineNumber relative to this Diag's SMLoc
2100 // for the diagnostic.
2101 const std::string &Filename = Parser->CppHashInfo.Filename;
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002102
2103 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
2104 int CppHashLocLineNo =
Tim Northoverc0bef992016-04-13 19:46:54 +00002105 Parser->SrcMgr.FindLineNumber(Parser->CppHashInfo.Loc, CppHashBuf);
Jim Grosbach4b905842013-09-20 23:08:21 +00002106 int LineNo =
Tim Northoverc0bef992016-04-13 19:46:54 +00002107 Parser->CppHashInfo.LineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002108
Jim Grosbach4b905842013-09-20 23:08:21 +00002109 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
2110 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
Chris Lattner72845262011-10-16 05:47:55 +00002111 Diag.getLineContents(), Diag.getRanges());
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002112
Benjamin Kramer47f5e302011-10-16 10:48:29 +00002113 if (Parser->SavedDiagHandler)
2114 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
2115 else
Craig Topper353eda42014-04-24 06:44:33 +00002116 NewDiag.print(nullptr, OS);
Kevin Enderbye7c0c492011-10-12 21:38:39 +00002117}
2118
Rafael Espindola2c064482012-08-21 18:29:30 +00002119// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
2120// difference being that that function accepts '@' as part of identifiers and
2121// we can't do that. AsmLexer.cpp should probably be changed to handle
2122// '@' as a special case when needed.
2123static bool isIdentifierChar(char c) {
Guy Benyei83c74e92013-02-12 21:21:59 +00002124 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
2125 c == '.';
Rafael Espindola2c064482012-08-21 18:29:30 +00002126}
2127
Rafael Espindola34b9c512012-06-03 23:57:14 +00002128bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00002129 ArrayRef<MCAsmMacroParameter> Parameters,
Toma Tabacu217116e2015-04-27 10:50:29 +00002130 ArrayRef<MCAsmMacroArgument> A,
Craig Topper3c76c522015-09-20 23:35:59 +00002131 bool EnableAtPseudoVariable, SMLoc L) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00002132 unsigned NParameters = Parameters.size();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002133 bool HasVararg = NParameters ? Parameters.back().Vararg : false;
Benjamin Kramer513e7442014-02-20 13:36:32 +00002134 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
Rafael Espindola1134ab232011-06-05 02:43:45 +00002135 return Error(L, "Wrong number of arguments");
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002136
Preston Gurd05500642012-09-19 20:36:12 +00002137 // A macro without parameters is handled differently on Darwin:
2138 // gas accepts no arguments and does no substitutions
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002139 while (!Body.empty()) {
2140 // Scan for the next substitution.
2141 std::size_t End = Body.size(), Pos = 0;
2142 for (; Pos != End; ++Pos) {
2143 // Check for a substitution or escape.
Benjamin Kramer513e7442014-02-20 13:36:32 +00002144 if (IsDarwin && !NParameters) {
Rafael Espindola1134ab232011-06-05 02:43:45 +00002145 // This macro has no parameters, look for $0, $1, etc.
2146 if (Body[Pos] != '$' || Pos + 1 == End)
2147 continue;
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002148
Rafael Espindola1134ab232011-06-05 02:43:45 +00002149 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00002150 if (Next == '$' || Next == 'n' ||
2151 isdigit(static_cast<unsigned char>(Next)))
Rafael Espindola1134ab232011-06-05 02:43:45 +00002152 break;
2153 } else {
2154 // This macro has parameters, look for \foo, \bar, etc.
2155 if (Body[Pos] == '\\' && Pos + 1 != End)
2156 break;
2157 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002158 }
2159
2160 // Add the prefix.
2161 OS << Body.slice(0, Pos);
2162
2163 // Check if we reached the end.
2164 if (Pos == End)
2165 break;
2166
Benjamin Kramer513e7442014-02-20 13:36:32 +00002167 if (IsDarwin && !NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002168 switch (Body[Pos + 1]) {
2169 // $$ => $
Rafael Espindola1134ab232011-06-05 02:43:45 +00002170 case '$':
2171 OS << '$';
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002172 break;
2173
Jim Grosbach4b905842013-09-20 23:08:21 +00002174 // $n => number of arguments
Rafael Espindola1134ab232011-06-05 02:43:45 +00002175 case 'n':
2176 OS << A.size();
2177 break;
2178
Jim Grosbach4b905842013-09-20 23:08:21 +00002179 // $[0-9] => argument
Rafael Espindola1134ab232011-06-05 02:43:45 +00002180 default: {
2181 // Missing arguments are ignored.
Jim Grosbach4b905842013-09-20 23:08:21 +00002182 unsigned Index = Body[Pos + 1] - '0';
Rafael Espindola1134ab232011-06-05 02:43:45 +00002183 if (Index >= A.size())
2184 break;
2185
2186 // Otherwise substitute with the token values, with spaces eliminated.
Craig Topper84008482015-10-10 05:38:14 +00002187 for (const AsmToken &Token : A[Index])
2188 OS << Token.getString();
Rafael Espindola1134ab232011-06-05 02:43:45 +00002189 break;
2190 }
2191 }
2192 Pos += 2;
2193 } else {
2194 unsigned I = Pos + 1;
Toma Tabacu217116e2015-04-27 10:50:29 +00002195
2196 // Check for the \@ pseudo-variable.
2197 if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End)
Rafael Espindola1134ab232011-06-05 02:43:45 +00002198 ++I;
Toma Tabacu217116e2015-04-27 10:50:29 +00002199 else
2200 while (isIdentifierChar(Body[I]) && I + 1 != End)
2201 ++I;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002202
Jim Grosbach4b905842013-09-20 23:08:21 +00002203 const char *Begin = Body.data() + Pos + 1;
2204 StringRef Argument(Begin, I - (Pos + 1));
Rafael Espindola1134ab232011-06-05 02:43:45 +00002205 unsigned Index = 0;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002206
Toma Tabacu217116e2015-04-27 10:50:29 +00002207 if (Argument == "@") {
2208 OS << NumOfMacroInstantiations;
2209 Pos += 2;
Preston Gurd05500642012-09-19 20:36:12 +00002210 } else {
Toma Tabacu217116e2015-04-27 10:50:29 +00002211 for (; Index < NParameters; ++Index)
2212 if (Parameters[Index].Name == Argument)
2213 break;
Rafael Espindola1134ab232011-06-05 02:43:45 +00002214
Toma Tabacu217116e2015-04-27 10:50:29 +00002215 if (Index == NParameters) {
2216 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
2217 Pos += 3;
2218 else {
2219 OS << '\\' << Argument;
2220 Pos = I;
2221 }
2222 } else {
2223 bool VarargParameter = HasVararg && Index == (NParameters - 1);
Craig Topper84008482015-10-10 05:38:14 +00002224 for (const AsmToken &Token : A[Index])
Toma Tabacu217116e2015-04-27 10:50:29 +00002225 // We expect no quotes around the string's contents when
2226 // parsing for varargs.
Craig Topper84008482015-10-10 05:38:14 +00002227 if (Token.getKind() != AsmToken::String || VarargParameter)
2228 OS << Token.getString();
Toma Tabacu217116e2015-04-27 10:50:29 +00002229 else
Craig Topper84008482015-10-10 05:38:14 +00002230 OS << Token.getStringContents();
Toma Tabacu217116e2015-04-27 10:50:29 +00002231
2232 Pos += 1 + Argument.size();
2233 }
Preston Gurd05500642012-09-19 20:36:12 +00002234 }
Rafael Espindola1134ab232011-06-05 02:43:45 +00002235 }
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002236 // Update the scan point.
Rafael Espindola1134ab232011-06-05 02:43:45 +00002237 Body = Body.substr(Pos);
Daniel Dunbar6fb1c3a2010-07-18 19:00:10 +00002238 }
Daniel Dunbar43235712010-07-18 18:54:11 +00002239
Rafael Espindola1134ab232011-06-05 02:43:45 +00002240 return false;
2241}
Daniel Dunbar43235712010-07-18 18:54:11 +00002242
Nico Weber2a8f9222014-07-24 16:29:04 +00002243MacroInstantiation::MacroInstantiation(SMLoc IL, int EB, SMLoc EL,
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002244 size_t CondStackDepth)
Rafael Espindolaf43a94e2014-08-17 22:48:55 +00002245 : InstantiationLoc(IL), ExitBuffer(EB), ExitLoc(EL),
Nico Weber155dccd12014-07-24 17:08:39 +00002246 CondStackDepth(CondStackDepth) {}
Daniel Dunbar43235712010-07-18 18:54:11 +00002247
Jim Grosbach4b905842013-09-20 23:08:21 +00002248static bool isOperator(AsmToken::TokenKind kind) {
2249 switch (kind) {
2250 default:
2251 return false;
2252 case AsmToken::Plus:
2253 case AsmToken::Minus:
2254 case AsmToken::Tilde:
2255 case AsmToken::Slash:
2256 case AsmToken::Star:
2257 case AsmToken::Dot:
2258 case AsmToken::Equal:
2259 case AsmToken::EqualEqual:
2260 case AsmToken::Pipe:
2261 case AsmToken::PipePipe:
2262 case AsmToken::Caret:
2263 case AsmToken::Amp:
2264 case AsmToken::AmpAmp:
2265 case AsmToken::Exclaim:
2266 case AsmToken::ExclaimEqual:
Jim Grosbach4b905842013-09-20 23:08:21 +00002267 case AsmToken::Less:
2268 case AsmToken::LessEqual:
2269 case AsmToken::LessLess:
2270 case AsmToken::LessGreater:
2271 case AsmToken::Greater:
2272 case AsmToken::GreaterEqual:
2273 case AsmToken::GreaterGreater:
2274 return true;
Preston Gurd05500642012-09-19 20:36:12 +00002275 }
2276}
2277
David Majnemer16252452014-01-29 00:07:39 +00002278namespace {
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002279
David Majnemer16252452014-01-29 00:07:39 +00002280class AsmLexerSkipSpaceRAII {
2281public:
2282 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
2283 Lexer.setSkipSpace(SkipSpace);
2284 }
2285
2286 ~AsmLexerSkipSpaceRAII() {
2287 Lexer.setSkipSpace(true);
2288 }
2289
2290private:
2291 AsmLexer &Lexer;
2292};
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002293
2294} // end anonymous namespace
David Majnemer16252452014-01-29 00:07:39 +00002295
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002296bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
2297
2298 if (Vararg) {
2299 if (Lexer.isNot(AsmToken::EndOfStatement)) {
2300 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00002301 MA.emplace_back(AsmToken::String, Str);
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002302 }
2303 return false;
2304 }
2305
Rafael Espindola768b41c2012-06-15 14:02:34 +00002306 unsigned ParenLevel = 0;
Preston Gurd05500642012-09-19 20:36:12 +00002307
David Majnemer16252452014-01-29 00:07:39 +00002308 // Darwin doesn't use spaces to delmit arguments.
2309 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
Rafael Espindola768b41c2012-06-15 14:02:34 +00002310
Scott Egertona1fa68a2016-02-11 13:48:49 +00002311 bool SpaceEaten;
2312
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002313 while (true) {
Scott Egertona1fa68a2016-02-11 13:48:49 +00002314 SpaceEaten = false;
David Majnemer16252452014-01-29 00:07:39 +00002315 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002316 return TokError("unexpected token in macro instantiation");
Preston Gurd05500642012-09-19 20:36:12 +00002317
Scott Egertona1fa68a2016-02-11 13:48:49 +00002318 if (ParenLevel == 0) {
Preston Gurd05500642012-09-19 20:36:12 +00002319
Scott Egertona1fa68a2016-02-11 13:48:49 +00002320 if (Lexer.is(AsmToken::Comma))
2321 break;
2322
2323 if (Lexer.is(AsmToken::Space)) {
2324 SpaceEaten = true;
Nirav Dave1180e6892016-06-02 17:15:05 +00002325 Lexer.Lex(); // Eat spaces
Scott Egertona1fa68a2016-02-11 13:48:49 +00002326 }
Preston Gurd05500642012-09-19 20:36:12 +00002327
2328 // Spaces can delimit parameters, but could also be part an expression.
2329 // If the token after a space is an operator, add the token and the next
2330 // one into this argument
David Majnemer91fc4c22014-01-29 18:57:46 +00002331 if (!IsDarwin) {
Jim Grosbach4b905842013-09-20 23:08:21 +00002332 if (isOperator(Lexer.getKind())) {
Scott Egertona1fa68a2016-02-11 13:48:49 +00002333 MA.push_back(getTok());
Nirav Dave1180e6892016-06-02 17:15:05 +00002334 Lexer.Lex();
Preston Gurd05500642012-09-19 20:36:12 +00002335
Scott Egertona1fa68a2016-02-11 13:48:49 +00002336 // Whitespace after an operator can be ignored.
2337 if (Lexer.is(AsmToken::Space))
Nirav Dave1180e6892016-06-02 17:15:05 +00002338 Lexer.Lex();
Scott Egertona1fa68a2016-02-11 13:48:49 +00002339
2340 continue;
Preston Gurd05500642012-09-19 20:36:12 +00002341 }
2342 }
Scott Egertona1fa68a2016-02-11 13:48:49 +00002343 if (SpaceEaten)
2344 break;
Preston Gurd05500642012-09-19 20:36:12 +00002345 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002346
Jim Grosbach4b905842013-09-20 23:08:21 +00002347 // handleMacroEntry relies on not advancing the lexer here
Rafael Espindola768b41c2012-06-15 14:02:34 +00002348 // to be able to fill in the remaining default parameter values
2349 if (Lexer.is(AsmToken::EndOfStatement))
2350 break;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002351
2352 // Adjust the current parentheses level.
2353 if (Lexer.is(AsmToken::LParen))
2354 ++ParenLevel;
2355 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
2356 --ParenLevel;
2357
2358 // Append the token to the current argument list.
2359 MA.push_back(getTok());
Nirav Dave1180e6892016-06-02 17:15:05 +00002360 Lexer.Lex();
Rafael Espindola768b41c2012-06-15 14:02:34 +00002361 }
Preston Gurd05500642012-09-19 20:36:12 +00002362
Rafael Espindola768b41c2012-06-15 14:02:34 +00002363 if (ParenLevel != 0)
Rafael Espindola3e5eb422012-08-21 15:55:04 +00002364 return TokError("unbalanced parentheses in macro argument");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002365 return false;
2366}
2367
2368// Parse the macro instantiation arguments.
Jim Grosbach4b905842013-09-20 23:08:21 +00002369bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
Vladimir Medic9bad0d332013-08-20 13:33:18 +00002370 MCAsmMacroArguments &A) {
Rafael Espindola768b41c2012-06-15 14:02:34 +00002371 const unsigned NParameters = M ? M->Parameters.size() : 0;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002372 bool NamedParametersFound = false;
2373 SmallVector<SMLoc, 4> FALocs;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002374
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002375 A.resize(NParameters);
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002376 FALocs.resize(NParameters);
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002377
Rafael Espindola768b41c2012-06-15 14:02:34 +00002378 // Parse two kinds of macro invocations:
2379 // - macros defined without any parameters accept an arbitrary number of them
2380 // - macros defined with parameters accept at most that many of them
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002381 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002382 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
2383 ++Parameter) {
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002384 SMLoc IDLoc = Lexer.getLoc();
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002385 MCAsmMacroParameter FA;
Rafael Espindola768b41c2012-06-15 14:02:34 +00002386
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002387 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002388 if (parseIdentifier(FA.Name)) {
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002389 Error(IDLoc, "invalid argument identifier for formal argument");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002390 eatToEndOfStatement();
2391 return true;
2392 }
2393
Nirav Davea645433c2016-07-18 15:24:03 +00002394 if (Lexer.isNot(AsmToken::Equal)) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002395 TokError("expected '=' after formal parameter identifier");
2396 eatToEndOfStatement();
2397 return true;
2398 }
2399 Lex();
2400
2401 NamedParametersFound = true;
2402 }
2403
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002404 if (NamedParametersFound && FA.Name.empty()) {
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002405 Error(IDLoc, "cannot mix positional and keyword arguments");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002406 eatToEndOfStatement();
2407 return true;
2408 }
2409
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00002410 bool Vararg = HasVararg && Parameter == (NParameters - 1);
2411 if (parseMacroArgument(FA.Value, Vararg))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002412 return true;
2413
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002414 unsigned PI = Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002415 if (!FA.Name.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002416 unsigned FAI = 0;
2417 for (FAI = 0; FAI < NParameters; ++FAI)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002418 if (M->Parameters[FAI].Name == FA.Name)
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002419 break;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002420
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002421 if (FAI >= NParameters) {
Nirav Davefd910412016-06-17 16:06:17 +00002422 assert(M && "expected macro to be defined");
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002423 Error(IDLoc,
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002424 "parameter named '" + FA.Name + "' does not exist for macro '" +
Saleem Abdulrasool3f44cd72014-03-17 17:13:57 +00002425 M->Name + "'");
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002426 return true;
2427 }
2428 PI = FAI;
2429 }
2430
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002431 if (!FA.Value.empty()) {
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002432 if (A.size() <= PI)
2433 A.resize(PI + 1);
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00002434 A[PI] = FA.Value;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002435
2436 if (FALocs.size() <= PI)
2437 FALocs.resize(PI + 1);
2438
2439 FALocs[PI] = Lexer.getLoc();
Preston Gurd242ed3152012-09-19 20:29:04 +00002440 }
Jim Grosbach206661622012-07-30 22:44:17 +00002441
Preston Gurd242ed3152012-09-19 20:29:04 +00002442 // At the end of the statement, fill in remaining arguments that have
2443 // default values. If there aren't any, then the next argument is
2444 // required but missing
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00002445 if (Lexer.is(AsmToken::EndOfStatement)) {
2446 bool Failure = false;
2447 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2448 if (A[FAI].empty()) {
2449 if (M->Parameters[FAI].Required) {
2450 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2451 "missing value for required parameter "
2452 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2453 Failure = true;
2454 }
2455
2456 if (!M->Parameters[FAI].Value.empty())
2457 A[FAI] = M->Parameters[FAI].Value;
2458 }
2459 }
2460 return Failure;
2461 }
Rafael Espindola768b41c2012-06-15 14:02:34 +00002462
2463 if (Lexer.is(AsmToken::Comma))
2464 Lex();
2465 }
Saleem Abdulrasool6d7c0c22014-02-17 00:40:17 +00002466
2467 return TokError("too many positional arguments");
Rafael Espindola768b41c2012-06-15 14:02:34 +00002468}
2469
Jim Grosbach4b905842013-09-20 23:08:21 +00002470const MCAsmMacro *AsmParser::lookupMacro(StringRef Name) {
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002471 StringMap<MCAsmMacro>::iterator I = MacroMap.find(Name);
2472 return (I == MacroMap.end()) ? nullptr : &I->getValue();
Eli Bendersky38274122013-01-14 23:22:36 +00002473}
2474
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002475void AsmParser::defineMacro(StringRef Name, MCAsmMacro Macro) {
2476 MacroMap.insert(std::make_pair(Name, std::move(Macro)));
Eli Bendersky38274122013-01-14 23:22:36 +00002477}
2478
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00002479void AsmParser::undefineMacro(StringRef Name) { MacroMap.erase(Name); }
Eli Bendersky38274122013-01-14 23:22:36 +00002480
Jim Grosbach4b905842013-09-20 23:08:21 +00002481bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
Davide Italiano7c9fc732016-07-27 05:51:56 +00002482 // Arbitrarily limit macro nesting depth (default matches 'as'). We can
2483 // eliminate this, although we should protect against infinite loops.
2484 unsigned MaxNestingDepth = AsmMacroMaxNestingDepth;
2485 if (ActiveMacros.size() == MaxNestingDepth) {
2486 std::ostringstream MaxNestingDepthError;
2487 MaxNestingDepthError << "macros cannot be nested more than "
2488 << MaxNestingDepth << " levels deep."
2489 << " Use -asm-macro-max-nesting-depth to increase "
2490 "this limit.";
2491 return TokError(MaxNestingDepthError.str());
2492 }
Daniel Dunbar43235712010-07-18 18:54:11 +00002493
Eli Bendersky38274122013-01-14 23:22:36 +00002494 MCAsmMacroArguments A;
Jim Grosbach4b905842013-09-20 23:08:21 +00002495 if (parseMacroArguments(M, A))
Rafael Espindola768b41c2012-06-15 14:02:34 +00002496 return true;
Daniel Dunbar43235712010-07-18 18:54:11 +00002497
Rafael Espindola1134ab232011-06-05 02:43:45 +00002498 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2499 // to hold the macro body with substitutions.
2500 SmallString<256> Buf;
2501 StringRef Body = M->Body;
Rafael Espindola34b9c512012-06-03 23:57:14 +00002502 raw_svector_ostream OS(Buf);
Rafael Espindola1134ab232011-06-05 02:43:45 +00002503
Toma Tabacu217116e2015-04-27 10:50:29 +00002504 if (expandMacro(OS, Body, M->Parameters, A, true, getTok().getLoc()))
Rafael Espindola1134ab232011-06-05 02:43:45 +00002505 return true;
2506
Eli Bendersky38274122013-01-14 23:22:36 +00002507 // We include the .endmacro in the buffer as our cue to exit the macro
Rafael Espindola34b9c512012-06-03 23:57:14 +00002508 // instantiation.
2509 OS << ".endmacro\n";
2510
Rafael Espindola3560ff22014-08-27 20:03:13 +00002511 std::unique_ptr<MemoryBuffer> Instantiation =
2512 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola1134ab232011-06-05 02:43:45 +00002513
Daniel Dunbar43235712010-07-18 18:54:11 +00002514 // Create the macro instantiation object and add to the current macro
2515 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00002516 MacroInstantiation *MI = new MacroInstantiation(
2517 NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Daniel Dunbar43235712010-07-18 18:54:11 +00002518 ActiveMacros.push_back(MI);
2519
Toma Tabacu217116e2015-04-27 10:50:29 +00002520 ++NumOfMacroInstantiations;
2521
Daniel Dunbar43235712010-07-18 18:54:11 +00002522 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00002523 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00002524 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Daniel Dunbar43235712010-07-18 18:54:11 +00002525 Lex();
2526
2527 return false;
2528}
2529
Jim Grosbach4b905842013-09-20 23:08:21 +00002530void AsmParser::handleMacroExit() {
Daniel Dunbar43235712010-07-18 18:54:11 +00002531 // Jump to the EndOfStatement we should return to, and consume it.
Jim Grosbach4b905842013-09-20 23:08:21 +00002532 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
Daniel Dunbar43235712010-07-18 18:54:11 +00002533 Lex();
2534
2535 // Pop the instantiation entry.
2536 delete ActiveMacros.back();
2537 ActiveMacros.pop_back();
2538}
2539
Jim Grosbach4b905842013-09-20 23:08:21 +00002540bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
Jim Grosbachb7b750d2012-09-13 23:11:31 +00002541 bool NoDeadStrip) {
Pete Cooper80d21cb2015-06-22 19:35:57 +00002542 MCSymbol *Sym;
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002543 const MCExpr *Value;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002544 if (MCParserUtils::parseAssignmentExpression(Name, allow_redef, *this, Sym,
2545 Value))
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002546 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002547
Pete Cooper80d21cb2015-06-22 19:35:57 +00002548 if (!Sym) {
2549 // In the case where we parse an expression starting with a '.', we will
2550 // not generate an error, nor will we create a symbol. In this case we
2551 // should just return out.
Anders Waldenborg84809572014-02-17 20:48:32 +00002552 return false;
Pete Cooper80d21cb2015-06-22 19:35:57 +00002553 }
David Majnemer58cb80c2014-12-24 10:27:50 +00002554
Daniel Dunbarae7ac012009-06-29 23:43:14 +00002555 // Do the assignment.
Daniel Dunbarb7b20972009-08-31 08:09:09 +00002556 Out.EmitAssignment(Sym, Value);
Jim Grosbachb7b750d2012-09-13 23:11:31 +00002557 if (NoDeadStrip)
2558 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2559
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002560 return false;
2561}
2562
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002563/// parseIdentifier:
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002564/// ::= identifier
2565/// ::= string
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002566bool AsmParser::parseIdentifier(StringRef &Res) {
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002567 // The assembler has relaxed rules for accepting identifiers, in particular we
Hans Wennborgce69d772013-10-18 20:46:28 +00002568 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2569 // separate tokens. At this level, we have already lexed so we cannot (currently)
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002570 // handle this as a context dependent token, instead we detect adjacent tokens
2571 // and return the combined identifier.
Hans Wennborgce69d772013-10-18 20:46:28 +00002572 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2573 SMLoc PrefixLoc = getLexer().getLoc();
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002574
Hans Wennborgce69d772013-10-18 20:46:28 +00002575 // Consume the prefix character, and check for a following identifier.
Nirav Dave1180e6892016-06-02 17:15:05 +00002576 Lexer.Lex(); // Lexer's Lex guarantees consecutive token.
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002577 if (Lexer.isNot(AsmToken::Identifier))
2578 return true;
2579
Hans Wennborgce69d772013-10-18 20:46:28 +00002580 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
2581 if (PrefixLoc.getPointer() + 1 != getTok().getLoc().getPointer())
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002582 return true;
2583
2584 // Construct the joined identifier and consume the token.
Jim Grosbach4b905842013-09-20 23:08:21 +00002585 Res =
Hans Wennborgce69d772013-10-18 20:46:28 +00002586 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
Nirav Davefd910412016-06-17 16:06:17 +00002587 Lex(); // Parser Lex to maintain invariants.
Daniel Dunbar3b96ffd2010-08-24 18:12:12 +00002588 return false;
2589 }
2590
Jim Grosbach4b905842013-09-20 23:08:21 +00002591 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002592 return true;
2593
Sean Callanan936b0d32010-01-19 21:44:56 +00002594 Res = getTok().getIdentifier();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002595
Sean Callanan686ed8d2010-01-19 20:22:31 +00002596 Lex(); // Consume the identifier token.
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002597
2598 return false;
2599}
2600
Jim Grosbach4b905842013-09-20 23:08:21 +00002601/// parseDirectiveSet:
Nico Weber4ada0d92011-01-28 03:04:41 +00002602/// ::= .equ identifier ',' expression
2603/// ::= .equiv identifier ',' expression
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002604/// ::= .set identifier ',' expression
Jim Grosbach4b905842013-09-20 23:08:21 +00002605bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00002606 StringRef Name;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002607
Nirav Davea645433c2016-07-18 15:24:03 +00002608 if (check(parseIdentifier(Name),
2609 "expected identifier after '" + Twine(IDVal) + "'") ||
2610 parseToken(AsmToken::Comma, "unexpected token in '" + Twine(IDVal) + "'"))
2611 return true;
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002612
Jim Grosbach4b905842013-09-20 23:08:21 +00002613 return parseAssignment(Name, allow_redef, true);
Daniel Dunbar2d2ee152009-06-25 21:56:11 +00002614}
2615
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002616bool AsmParser::parseEscapedString(std::string &Data) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002617 assert(getLexer().is(AsmToken::String) && "Unexpected current token!");
Daniel Dunbaref668c12009-08-14 18:19:52 +00002618
2619 Data = "";
Sean Callanan936b0d32010-01-19 21:44:56 +00002620 StringRef Str = getTok().getStringContents();
Daniel Dunbaref668c12009-08-14 18:19:52 +00002621 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2622 if (Str[i] != '\\') {
2623 Data += Str[i];
2624 continue;
2625 }
2626
2627 // Recognize escaped characters. Note that this escape semantics currently
2628 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2629 ++i;
2630 if (i == e)
2631 return TokError("unexpected backslash at end of string");
2632
2633 // Recognize octal sequences.
Jim Grosbach4b905842013-09-20 23:08:21 +00002634 if ((unsigned)(Str[i] - '0') <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002635 // Consume up to three octal characters.
2636 unsigned Value = Str[i] - '0';
2637
Jim Grosbach4b905842013-09-20 23:08:21 +00002638 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002639 ++i;
2640 Value = Value * 8 + (Str[i] - '0');
2641
Jim Grosbach4b905842013-09-20 23:08:21 +00002642 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002643 ++i;
2644 Value = Value * 8 + (Str[i] - '0');
2645 }
2646 }
2647
2648 if (Value > 255)
2649 return TokError("invalid octal escape sequence (out of range)");
2650
Jim Grosbach4b905842013-09-20 23:08:21 +00002651 Data += (unsigned char)Value;
Daniel Dunbaref668c12009-08-14 18:19:52 +00002652 continue;
2653 }
2654
2655 // Otherwise recognize individual escapes.
2656 switch (Str[i]) {
2657 default:
2658 // Just reject invalid escape sequences for now.
2659 return TokError("invalid escape sequence (unrecognized character)");
2660
2661 case 'b': Data += '\b'; break;
2662 case 'f': Data += '\f'; break;
2663 case 'n': Data += '\n'; break;
2664 case 'r': Data += '\r'; break;
2665 case 't': Data += '\t'; break;
2666 case '"': Data += '"'; break;
2667 case '\\': Data += '\\'; break;
2668 }
2669 }
2670
Nirav Davea645433c2016-07-18 15:24:03 +00002671 Lex();
Daniel Dunbaref668c12009-08-14 18:19:52 +00002672 return false;
2673}
2674
Jim Grosbach4b905842013-09-20 23:08:21 +00002675/// parseDirectiveAscii:
Rafael Espindola63760ba2010-10-28 20:02:27 +00002676/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002677bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002678 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002679 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00002680
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002681 while (true) {
Daniel Dunbaref668c12009-08-14 18:19:52 +00002682 std::string Data;
Nirav Davea645433c2016-07-18 15:24:03 +00002683 if (check(getTok().isNot(AsmToken::String),
2684 "expected string in '" + Twine(IDVal) + "' directive") ||
2685 parseEscapedString(Data))
Daniel Dunbaref668c12009-08-14 18:19:52 +00002686 return true;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002687
Rafael Espindola64e1af82013-07-02 15:49:13 +00002688 getStreamer().EmitBytes(Data);
Daniel Dunbara10e5192009-06-24 23:30:00 +00002689 if (ZeroTerminated)
Rafael Espindola64e1af82013-07-02 15:49:13 +00002690 getStreamer().EmitBytes(StringRef("\0", 1));
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002691
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002692 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara10e5192009-06-24 23:30:00 +00002693 break;
2694
Nirav Davea645433c2016-07-18 15:24:03 +00002695 if (parseToken(AsmToken::Comma,
2696 "unexpected token in '" + Twine(IDVal) + "' directive"))
2697 return true;
Daniel Dunbara10e5192009-06-24 23:30:00 +00002698 }
2699 }
2700
Sean Callanan686ed8d2010-01-19 20:22:31 +00002701 Lex();
Daniel Dunbara10e5192009-06-24 23:30:00 +00002702 return false;
2703}
2704
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002705/// parseDirectiveReloc
2706/// ::= .reloc expression , identifier [ , expression ]
2707bool AsmParser::parseDirectiveReloc(SMLoc DirectiveLoc) {
2708 const MCExpr *Offset;
2709 const MCExpr *Expr = nullptr;
2710
2711 SMLoc OffsetLoc = Lexer.getTok().getLoc();
2712 if (parseExpression(Offset))
2713 return true;
2714
2715 // We can only deal with constant expressions at the moment.
2716 int64_t OffsetValue;
Nirav Davea645433c2016-07-18 15:24:03 +00002717 if (check(!Offset->evaluateAsAbsolute(OffsetValue), OffsetLoc,
2718 "expression is not a constant value") ||
2719 check(OffsetValue < 0, OffsetLoc, "expression is negative") ||
2720 parseToken(AsmToken::Comma, "expected comma") ||
2721 check(getTok().isNot(AsmToken::Identifier), "expected relocation name"))
2722 return true;
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002723
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002724 SMLoc NameLoc = Lexer.getTok().getLoc();
2725 StringRef Name = Lexer.getTok().getIdentifier();
Nirav Davefd910412016-06-17 16:06:17 +00002726 Lex();
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002727
2728 if (Lexer.is(AsmToken::Comma)) {
Nirav Davefd910412016-06-17 16:06:17 +00002729 Lex();
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002730 SMLoc ExprLoc = Lexer.getLoc();
2731 if (parseExpression(Expr))
2732 return true;
2733
2734 MCValue Value;
2735 if (!Expr->evaluateAsRelocatable(Value, nullptr, nullptr))
2736 return Error(ExprLoc, "expression must be relocatable");
2737 }
2738
Nirav Davea645433c2016-07-18 15:24:03 +00002739 if (parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00002740 "unexpected token in .reloc directive"))
2741 return true;
2742
2743 if (getStreamer().EmitRelocDirective(*Offset, Name, Expr, DirectiveLoc))
2744 return Error(NameLoc, "unknown relocation name");
2745
Daniel Sanders9f6ad492015-11-12 13:33:00 +00002746 return false;
2747}
2748
Jim Grosbach4b905842013-09-20 23:08:21 +00002749/// parseDirectiveValue
Daniel Dunbara10e5192009-06-24 23:30:00 +00002750/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002751bool AsmParser::parseDirectiveValue(unsigned Size) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002752 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002753 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00002754
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002755 while (true) {
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002756 const MCExpr *Value;
Jim Grosbach76346c32011-06-29 16:05:14 +00002757 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002758 if (parseExpression(Value))
Daniel Dunbara10e5192009-06-24 23:30:00 +00002759 return true;
2760
Daniel Dunbar6738a2e2010-05-23 18:36:38 +00002761 // Special case constant expressions to match code generator.
Jim Grosbach76346c32011-06-29 16:05:14 +00002762 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2763 assert(Size <= 8 && "Invalid size");
2764 uint64_t IntValue = MCE->getValue();
2765 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2766 return Error(ExprLoc, "literal value out of range for directive");
Rafael Espindola64e1af82013-07-02 15:49:13 +00002767 getStreamer().EmitIntValue(IntValue, Size);
Jim Grosbach76346c32011-06-29 16:05:14 +00002768 } else
Kevin Enderby96918bc2014-04-22 17:27:29 +00002769 getStreamer().EmitValue(Value, Size, ExprLoc);
Daniel Dunbara10e5192009-06-24 23:30:00 +00002770
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002771 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara10e5192009-06-24 23:30:00 +00002772 break;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002773
Daniel Dunbara10e5192009-06-24 23:30:00 +00002774 // FIXME: Improve diagnostic.
Nirav Davea645433c2016-07-18 15:24:03 +00002775 if (parseToken(AsmToken::Comma, "unexpected token in directive"))
2776 return true;
Daniel Dunbara10e5192009-06-24 23:30:00 +00002777 }
2778 }
2779
Sean Callanan686ed8d2010-01-19 20:22:31 +00002780 Lex();
Daniel Dunbara10e5192009-06-24 23:30:00 +00002781 return false;
2782}
2783
David Woodhoused6de0d92014-02-01 16:20:59 +00002784/// ParseDirectiveOctaValue
2785/// ::= .octa [ hexconstant (, hexconstant)* ]
2786bool AsmParser::parseDirectiveOctaValue() {
2787 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2788 checkForValidSection();
2789
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002790 while (true) {
Nirav Davea645433c2016-07-18 15:24:03 +00002791 if (getTok().is(AsmToken::Error))
David Woodhoused6de0d92014-02-01 16:20:59 +00002792 return true;
Nirav Davea645433c2016-07-18 15:24:03 +00002793 if (getTok().isNot(AsmToken::Integer) && getTok().isNot(AsmToken::BigNum))
David Woodhoused6de0d92014-02-01 16:20:59 +00002794 return TokError("unknown token in expression");
2795
2796 SMLoc ExprLoc = getLexer().getLoc();
2797 APInt IntValue = getTok().getAPIntVal();
2798 Lex();
2799
2800 uint64_t hi, lo;
2801 if (IntValue.isIntN(64)) {
2802 hi = 0;
2803 lo = IntValue.getZExtValue();
2804 } else if (IntValue.isIntN(128)) {
David Woodhouse6c9a6f92014-02-01 16:52:33 +00002805 // It might actually have more than 128 bits, but the top ones are zero.
2806 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
David Woodhoused6de0d92014-02-01 16:20:59 +00002807 lo = IntValue.getLoBits(64).getZExtValue();
2808 } else
2809 return Error(ExprLoc, "literal value out of range for directive");
2810
2811 if (MAI.isLittleEndian()) {
2812 getStreamer().EmitIntValue(lo, 8);
2813 getStreamer().EmitIntValue(hi, 8);
2814 } else {
2815 getStreamer().EmitIntValue(hi, 8);
2816 getStreamer().EmitIntValue(lo, 8);
2817 }
2818
2819 if (getLexer().is(AsmToken::EndOfStatement))
2820 break;
2821
2822 // FIXME: Improve diagnostic.
Nirav Davea645433c2016-07-18 15:24:03 +00002823 if (parseToken(AsmToken::Comma, "unexpected token in directive"))
2824 return true;
David Woodhoused6de0d92014-02-01 16:20:59 +00002825 }
2826 }
2827
2828 Lex();
2829 return false;
2830}
2831
Jim Grosbach4b905842013-09-20 23:08:21 +00002832/// parseDirectiveRealValue
Daniel Dunbar2af16532010-09-24 01:59:56 +00002833/// ::= (.single | .double) [ expression (, expression)* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002834bool AsmParser::parseDirectiveRealValue(const fltSemantics &Semantics) {
Daniel Dunbar2af16532010-09-24 01:59:56 +00002835 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002836 checkForValidSection();
Daniel Dunbar2af16532010-09-24 01:59:56 +00002837
Eugene Zelenko33d7b762016-08-23 17:14:32 +00002838 while (true) {
Daniel Dunbar2af16532010-09-24 01:59:56 +00002839 // We don't truly support arithmetic on floating point expressions, so we
2840 // have to manually parse unary prefixes.
2841 bool IsNeg = false;
2842 if (getLexer().is(AsmToken::Minus)) {
Nirav Dave1180e6892016-06-02 17:15:05 +00002843 Lexer.Lex();
Daniel Dunbar2af16532010-09-24 01:59:56 +00002844 IsNeg = true;
2845 } else if (getLexer().is(AsmToken::Plus))
Nirav Dave1180e6892016-06-02 17:15:05 +00002846 Lexer.Lex();
Daniel Dunbar2af16532010-09-24 01:59:56 +00002847
Nirav Dave1180e6892016-06-02 17:15:05 +00002848 if (Lexer.is(AsmToken::Error))
2849 return TokError(Lexer.getErr());
2850 if (Lexer.isNot(AsmToken::Integer) && Lexer.isNot(AsmToken::Real) &&
2851 Lexer.isNot(AsmToken::Identifier))
Daniel Dunbar2af16532010-09-24 01:59:56 +00002852 return TokError("unexpected token in directive");
2853
2854 // Convert to an APFloat.
2855 APFloat Value(Semantics);
Kevin Enderby5bbe9572011-03-29 21:11:52 +00002856 StringRef IDVal = getTok().getString();
2857 if (getLexer().is(AsmToken::Identifier)) {
2858 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
2859 Value = APFloat::getInf(Semantics);
2860 else if (!IDVal.compare_lower("nan"))
2861 Value = APFloat::getNaN(Semantics, false, ~0);
2862 else
2863 return TokError("invalid floating point literal");
2864 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
Jim Grosbach4b905842013-09-20 23:08:21 +00002865 APFloat::opInvalidOp)
Daniel Dunbar2af16532010-09-24 01:59:56 +00002866 return TokError("invalid floating point literal");
2867 if (IsNeg)
2868 Value.changeSign();
2869
2870 // Consume the numeric token.
2871 Lex();
2872
2873 // Emit the value as an integer.
2874 APInt AsInt = Value.bitcastToAPInt();
2875 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
Rafael Espindola64e1af82013-07-02 15:49:13 +00002876 AsInt.getBitWidth() / 8);
Daniel Dunbar2af16532010-09-24 01:59:56 +00002877
Nirav Dave1180e6892016-06-02 17:15:05 +00002878 if (Lexer.is(AsmToken::EndOfStatement))
Daniel Dunbar2af16532010-09-24 01:59:56 +00002879 break;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002880
Nirav Davea645433c2016-07-18 15:24:03 +00002881 if (parseToken(AsmToken::Comma, "unexpected token in directive"))
2882 return true;
Daniel Dunbar2af16532010-09-24 01:59:56 +00002883 }
2884 }
2885
2886 Lex();
2887 return false;
2888}
2889
Jim Grosbach4b905842013-09-20 23:08:21 +00002890/// parseDirectiveZero
Rafael Espindola922e3f42010-09-16 15:03:59 +00002891/// ::= .zero expression
Jim Grosbach4b905842013-09-20 23:08:21 +00002892bool AsmParser::parseDirectiveZero() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002893 checkForValidSection();
Rafael Espindola922e3f42010-09-16 15:03:59 +00002894
Petr Hosek67a94a72016-05-28 05:57:48 +00002895 SMLoc NumBytesLoc = Lexer.getLoc();
2896 const MCExpr *NumBytes;
2897 if (parseExpression(NumBytes))
Rafael Espindola922e3f42010-09-16 15:03:59 +00002898 return true;
2899
Rafael Espindolab91bac62010-10-05 19:42:57 +00002900 int64_t Val = 0;
2901 if (getLexer().is(AsmToken::Comma)) {
2902 Lex();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002903 if (parseAbsoluteExpression(Val))
Rafael Espindolab91bac62010-10-05 19:42:57 +00002904 return true;
2905 }
2906
Nirav Davea645433c2016-07-18 15:24:03 +00002907 if (parseToken(AsmToken::EndOfStatement,
2908 "unexpected token in '.zero' directive"))
2909 return true;
Petr Hosek67a94a72016-05-28 05:57:48 +00002910 getStreamer().emitFill(*NumBytes, Val, NumBytesLoc);
Rafael Espindola922e3f42010-09-16 15:03:59 +00002911
2912 return false;
2913}
2914
Jim Grosbach4b905842013-09-20 23:08:21 +00002915/// parseDirectiveFill
Roman Divackye33098f2013-09-24 17:44:41 +00002916/// ::= .fill expression [ , expression [ , expression ] ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002917bool AsmParser::parseDirectiveFill() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002918 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00002919
Petr Hosek67a94a72016-05-28 05:57:48 +00002920 SMLoc NumValuesLoc = Lexer.getLoc();
2921 const MCExpr *NumValues;
2922 if (parseExpression(NumValues))
Daniel Dunbara10e5192009-06-24 23:30:00 +00002923 return true;
2924
Roman Divackye33098f2013-09-24 17:44:41 +00002925 int64_t FillSize = 1;
2926 int64_t FillExpr = 0;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002927
David Majnemer522d3db2014-02-01 07:19:38 +00002928 SMLoc SizeLoc, ExprLoc;
Roman Divackye33098f2013-09-24 17:44:41 +00002929 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Daniel Dunbara10e5192009-06-24 23:30:00 +00002930
Nirav Davea645433c2016-07-18 15:24:03 +00002931 if (parseToken(AsmToken::Comma, "unexpected token in '.fill' directive") ||
2932 getTokenLoc(SizeLoc) || parseAbsoluteExpression(FillSize))
Roman Divackye33098f2013-09-24 17:44:41 +00002933 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002934
Roman Divackye33098f2013-09-24 17:44:41 +00002935 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Nirav Davea645433c2016-07-18 15:24:03 +00002936 if (parseToken(AsmToken::Comma,
2937 "unexpected token in '.fill' directive") ||
2938 getTokenLoc(ExprLoc) || parseAbsoluteExpression(FillExpr) ||
2939 parseToken(AsmToken::EndOfStatement,
2940 "unexpected token in '.fill' directive"))
Roman Divackye33098f2013-09-24 17:44:41 +00002941 return true;
Roman Divackye33098f2013-09-24 17:44:41 +00002942 }
2943 }
Daniel Dunbara10e5192009-06-24 23:30:00 +00002944
David Majnemer522d3db2014-02-01 07:19:38 +00002945 if (FillSize < 0) {
2946 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
Petr Hosek6abd38b2016-05-28 08:20:08 +00002947 return false;
David Majnemer522d3db2014-02-01 07:19:38 +00002948 }
2949 if (FillSize > 8) {
2950 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
2951 FillSize = 8;
2952 }
Daniel Dunbara10e5192009-06-24 23:30:00 +00002953
David Majnemer522d3db2014-02-01 07:19:38 +00002954 if (!isUInt<32>(FillExpr) && FillSize > 4)
2955 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
2956
Petr Hosek67a94a72016-05-28 05:57:48 +00002957 getStreamer().emitFill(*NumValues, FillSize, FillExpr, NumValuesLoc);
Daniel Dunbara10e5192009-06-24 23:30:00 +00002958
2959 return false;
2960}
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002961
Jim Grosbach4b905842013-09-20 23:08:21 +00002962/// parseDirectiveOrg
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002963/// ::= .org expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00002964bool AsmParser::parseDirectiveOrg() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002965 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00002966
Daniel Dunbar897ffad2009-08-31 08:09:28 +00002967 const MCExpr *Offset;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002968 if (parseExpression(Offset))
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002969 return true;
2970
2971 // Parse optional fill expression.
2972 int64_t FillExpr = 0;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002973 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Nirav Davea645433c2016-07-18 15:24:03 +00002974 if (parseToken(AsmToken::Comma, "unexpected token in '.org' directive") ||
2975 parseAbsoluteExpression(FillExpr))
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002976 return true;
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002977 }
2978
Nirav Davea645433c2016-07-18 15:24:03 +00002979 if (parseToken(AsmToken::EndOfStatement,
2980 "unexpected token in '.org' directive"))
2981 return true;
2982
Rafael Espindola7ae65d82015-11-04 23:59:18 +00002983 getStreamer().emitValueToOffset(Offset, FillExpr);
Daniel Dunbar4a5a5612009-06-25 22:44:51 +00002984 return false;
2985}
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002986
Jim Grosbach4b905842013-09-20 23:08:21 +00002987/// parseDirectiveAlign
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002988/// ::= {.align, ...} expression [ , expression [ , expression ]]
Jim Grosbach4b905842013-09-20 23:08:21 +00002989bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002990 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00002991
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00002992 SMLoc AlignmentLoc = getLexer().getLoc();
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002993 int64_t Alignment;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002994 if (parseAbsoluteExpression(Alignment))
Daniel Dunbarcc566a712009-06-29 23:46:59 +00002995 return true;
2996
2997 SMLoc MaxBytesLoc;
2998 bool HasFillExpr = false;
2999 int64_t FillExpr = 0;
3000 int64_t MaxBytesToFill = 0;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003001 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Nirav Davea645433c2016-07-18 15:24:03 +00003002 if (parseToken(AsmToken::Comma, "unexpected token in directive"))
3003 return true;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003004
3005 // The fill expression can be omitted while specifying a maximum number of
3006 // alignment bytes, e.g:
3007 // .align 3,,4
Nirav Davea645433c2016-07-18 15:24:03 +00003008 if (getTok().isNot(AsmToken::Comma)) {
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003009 HasFillExpr = true;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003010 if (parseAbsoluteExpression(FillExpr))
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003011 return true;
3012 }
3013
Nirav Davea645433c2016-07-18 15:24:03 +00003014 if (getTok().isNot(AsmToken::EndOfStatement)) {
3015 if (parseToken(AsmToken::Comma, "unexpected token in directive") ||
3016 getTokenLoc(MaxBytesLoc) || parseAbsoluteExpression(MaxBytesToFill))
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003017 return true;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003018 }
3019 }
3020
Nirav Davea645433c2016-07-18 15:24:03 +00003021 if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
3022 return true;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003023
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003024 if (!HasFillExpr)
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003025 FillExpr = 0;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003026
3027 // Compute alignment in bytes.
3028 if (IsPow2) {
3029 // FIXME: Diagnose overflow.
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003030 if (Alignment >= 32) {
3031 Error(AlignmentLoc, "invalid alignment value");
3032 Alignment = 31;
3033 }
3034
Benjamin Kramer63951ad2009-09-06 09:35:10 +00003035 Alignment = 1ULL << Alignment;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00003036 } else {
Davide Italianocb2da712015-09-08 18:59:47 +00003037 // Reject alignments that aren't either a power of two or zero,
3038 // for gas compatibility. Alignment of zero is silently rounded
3039 // up to one.
3040 if (Alignment == 0)
3041 Alignment = 1;
Benjamin Kramer64bf7802013-02-16 15:00:16 +00003042 if (!isPowerOf2_64(Alignment))
3043 Error(AlignmentLoc, "alignment must be a power of 2");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003044 }
3045
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003046 // Diagnose non-sensical max bytes to align.
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003047 if (MaxBytesLoc.isValid()) {
3048 if (MaxBytesToFill < 1) {
Daniel Dunbar18f3c9b2009-08-26 09:16:34 +00003049 Error(MaxBytesLoc, "alignment directive can never be satisfied in this "
Jim Grosbach4b905842013-09-20 23:08:21 +00003050 "many bytes, ignoring maximum bytes expression");
Daniel Dunbar4abcccb2009-08-21 23:01:53 +00003051 MaxBytesToFill = 0;
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003052 }
3053
3054 if (MaxBytesToFill >= Alignment) {
Daniel Dunbarc9dc78a2009-06-30 00:49:23 +00003055 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
Jim Grosbach4b905842013-09-20 23:08:21 +00003056 "has no effect");
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003057 MaxBytesToFill = 0;
3058 }
3059 }
3060
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003061 // Check whether we should use optimal code alignment for this .align
3062 // directive.
Saleem Abdulrasool7f2f9f42014-03-21 05:13:23 +00003063 const MCSection *Section = getStreamer().getCurrentSection().first;
3064 assert(Section && "must have section to emit alignment");
3065 bool UseCodeAlign = Section->UseCodeAlign();
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003066 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
3067 ValueSize == 1 && UseCodeAlign) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00003068 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003069 } else {
Kevin Enderby7f993022010-02-25 18:46:04 +00003070 // FIXME: Target specific behavior about how the "extra" bytes are filled.
Chris Lattnerc2b36752010-07-15 21:19:31 +00003071 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
3072 MaxBytesToFill);
Daniel Dunbarbb166be2010-05-17 21:54:30 +00003073 }
Daniel Dunbarcc566a712009-06-29 23:46:59 +00003074
3075 return false;
3076}
3077
Jim Grosbach4b905842013-09-20 23:08:21 +00003078/// parseDirectiveFile
Eli Bendersky17233942013-01-15 22:59:42 +00003079/// ::= .file [number] filename
3080/// ::= .file number directory filename
Jim Grosbach4b905842013-09-20 23:08:21 +00003081bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003082 // FIXME: I'm not sure what this is.
3083 int64_t FileNumber = -1;
3084 SMLoc FileNumberLoc = getLexer().getLoc();
3085 if (getLexer().is(AsmToken::Integer)) {
3086 FileNumber = getTok().getIntVal();
3087 Lex();
3088
3089 if (FileNumber < 1)
3090 return TokError("file number less than one");
3091 }
3092
Nirav Davea645433c2016-07-18 15:24:03 +00003093 std::string Path = getTok().getString();
Eli Bendersky17233942013-01-15 22:59:42 +00003094
3095 // Usually the directory and filename together, otherwise just the directory.
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003096 // Allow the strings to have escaped octal character sequence.
Nirav Davea645433c2016-07-18 15:24:03 +00003097 if (check(getTok().isNot(AsmToken::String),
3098 "unexpected token in '.file' directive") ||
3099 parseEscapedString(Path))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003100 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003101
3102 StringRef Directory;
3103 StringRef Filename;
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003104 std::string FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00003105 if (getLexer().is(AsmToken::String)) {
Nirav Davea645433c2016-07-18 15:24:03 +00003106 if (check(FileNumber == -1,
3107 "explicit path specified, but no file number") ||
3108 parseEscapedString(FilenameData))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00003109 return true;
3110 Filename = FilenameData;
Eli Bendersky17233942013-01-15 22:59:42 +00003111 Directory = Path;
Eli Bendersky17233942013-01-15 22:59:42 +00003112 } else {
3113 Filename = Path;
3114 }
3115
Nirav Davea645433c2016-07-18 15:24:03 +00003116 if (parseToken(AsmToken::EndOfStatement,
3117 "unexpected token in '.file' directive"))
3118 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003119
3120 if (FileNumber == -1)
3121 getStreamer().EmitFileDirective(Filename);
3122 else {
David Blaikie22748082016-05-26 00:22:26 +00003123 // If there is -g option as well as debug info from directive file,
3124 // we turn off -g option, directly use the existing debug info instead.
David Blaikiedc3f01e2015-03-09 01:57:13 +00003125 if (getContext().getGenDwarfForAssembly())
David Blaikie22748082016-05-26 00:22:26 +00003126 getContext().setGenDwarfForAssembly(false);
3127 else if (getStreamer().EmitDwarfFileDirective(FileNumber, Directory, Filename) ==
David Blaikiec714ef42014-03-17 01:52:11 +00003128 0)
Eli Bendersky17233942013-01-15 22:59:42 +00003129 Error(FileNumberLoc, "file number already allocated");
3130 }
3131
3132 return false;
3133}
3134
Jim Grosbach4b905842013-09-20 23:08:21 +00003135/// parseDirectiveLine
Eli Bendersky17233942013-01-15 22:59:42 +00003136/// ::= .line [number]
Jim Grosbach4b905842013-09-20 23:08:21 +00003137bool AsmParser::parseDirectiveLine() {
Nirav Davea645433c2016-07-18 15:24:03 +00003138 int64_t LineNumber;
Eli Bendersky17233942013-01-15 22:59:42 +00003139 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Nirav Davea645433c2016-07-18 15:24:03 +00003140 if (parseIntToken(LineNumber, "unexpected token in '.line' directive"))
3141 return true;
Jim Grosbach4b905842013-09-20 23:08:21 +00003142 (void)LineNumber;
Eli Bendersky17233942013-01-15 22:59:42 +00003143 // FIXME: Do something with the .line.
3144 }
Nirav Davea645433c2016-07-18 15:24:03 +00003145 if (parseToken(AsmToken::EndOfStatement,
3146 "unexpected token in '.line' directive"))
3147 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003148
3149 return false;
3150}
3151
Jim Grosbach4b905842013-09-20 23:08:21 +00003152/// parseDirectiveLoc
Eli Bendersky17233942013-01-15 22:59:42 +00003153/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
3154/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
3155/// The first number is a file number, must have been previously assigned with
3156/// a .file directive, the second number is the line number and optionally the
3157/// third number is a column position (zero if not specified). The remaining
3158/// optional items are .loc sub-directives.
Jim Grosbach4b905842013-09-20 23:08:21 +00003159bool AsmParser::parseDirectiveLoc() {
Nirav Davea645433c2016-07-18 15:24:03 +00003160 int64_t FileNumber = 0, LineNumber = 0;
3161 SMLoc Loc = getTok().getLoc();
3162 if (parseIntToken(FileNumber, "unexpected token in '.loc' directive") ||
3163 check(FileNumber < 1, Loc,
3164 "file number less than one in '.loc' directive") ||
3165 check(!getContext().isValidDwarfFileNumber(FileNumber), Loc,
3166 "unassigned file number in '.loc' directive"))
3167 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003168
Nirav Davea645433c2016-07-18 15:24:03 +00003169 // optional
Eli Bendersky17233942013-01-15 22:59:42 +00003170 if (getLexer().is(AsmToken::Integer)) {
3171 LineNumber = getTok().getIntVal();
Adrian Prantl6ac40032013-09-26 23:37:11 +00003172 if (LineNumber < 0)
3173 return TokError("line number less than zero in '.loc' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003174 Lex();
3175 }
3176
3177 int64_t ColumnPos = 0;
3178 if (getLexer().is(AsmToken::Integer)) {
3179 ColumnPos = getTok().getIntVal();
3180 if (ColumnPos < 0)
3181 return TokError("column position less than zero in '.loc' directive");
3182 Lex();
3183 }
3184
3185 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
3186 unsigned Isa = 0;
3187 int64_t Discriminator = 0;
3188 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Eugene Zelenko33d7b762016-08-23 17:14:32 +00003189 while (true) {
Eli Bendersky17233942013-01-15 22:59:42 +00003190 if (getLexer().is(AsmToken::EndOfStatement))
3191 break;
3192
3193 StringRef Name;
3194 SMLoc Loc = getTok().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003195 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003196 return TokError("unexpected token in '.loc' directive");
3197
3198 if (Name == "basic_block")
3199 Flags |= DWARF2_FLAG_BASIC_BLOCK;
3200 else if (Name == "prologue_end")
3201 Flags |= DWARF2_FLAG_PROLOGUE_END;
3202 else if (Name == "epilogue_begin")
3203 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN;
3204 else if (Name == "is_stmt") {
3205 Loc = getTok().getLoc();
3206 const MCExpr *Value;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003207 if (parseExpression(Value))
Eli Bendersky17233942013-01-15 22:59:42 +00003208 return true;
3209 // The expression must be the constant 0 or 1.
3210 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3211 int Value = MCE->getValue();
3212 if (Value == 0)
3213 Flags &= ~DWARF2_FLAG_IS_STMT;
3214 else if (Value == 1)
3215 Flags |= DWARF2_FLAG_IS_STMT;
3216 else
3217 return Error(Loc, "is_stmt value not 0 or 1");
Craig Topperf15655b2013-04-22 04:22:40 +00003218 } else {
Eli Bendersky17233942013-01-15 22:59:42 +00003219 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
3220 }
Craig Topperf15655b2013-04-22 04:22:40 +00003221 } else if (Name == "isa") {
Eli Bendersky17233942013-01-15 22:59:42 +00003222 Loc = getTok().getLoc();
3223 const MCExpr *Value;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003224 if (parseExpression(Value))
Eli Bendersky17233942013-01-15 22:59:42 +00003225 return true;
3226 // The expression must be a constant greater or equal to 0.
3227 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3228 int Value = MCE->getValue();
3229 if (Value < 0)
3230 return Error(Loc, "isa number less than zero");
3231 Isa = Value;
Craig Topperf15655b2013-04-22 04:22:40 +00003232 } else {
Eli Bendersky17233942013-01-15 22:59:42 +00003233 return Error(Loc, "isa number not a constant value");
3234 }
Craig Topperf15655b2013-04-22 04:22:40 +00003235 } else if (Name == "discriminator") {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003236 if (parseAbsoluteExpression(Discriminator))
Eli Bendersky17233942013-01-15 22:59:42 +00003237 return true;
Craig Topperf15655b2013-04-22 04:22:40 +00003238 } else {
Eli Bendersky17233942013-01-15 22:59:42 +00003239 return Error(Loc, "unknown sub-directive in '.loc' directive");
3240 }
3241
3242 if (getLexer().is(AsmToken::EndOfStatement))
3243 break;
3244 }
3245 }
Nirav Davea645433c2016-07-18 15:24:03 +00003246 Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00003247
3248 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
3249 Isa, Discriminator, StringRef());
3250
3251 return false;
3252}
3253
Jim Grosbach4b905842013-09-20 23:08:21 +00003254/// parseDirectiveStabs
Eli Bendersky17233942013-01-15 22:59:42 +00003255/// ::= .stabs string, number, number, number
Jim Grosbach4b905842013-09-20 23:08:21 +00003256bool AsmParser::parseDirectiveStabs() {
Eli Bendersky17233942013-01-15 22:59:42 +00003257 return TokError("unsupported directive '.stabs'");
3258}
3259
Reid Kleckner2214ed82016-01-29 00:49:42 +00003260/// parseDirectiveCVFile
3261/// ::= .cv_file number filename
3262bool AsmParser::parseDirectiveCVFile() {
Nirav Davea645433c2016-07-18 15:24:03 +00003263 SMLoc FileNumberLoc = getTok().getLoc();
3264 int64_t FileNumber;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003265 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00003266
3267 if (parseIntToken(FileNumber,
3268 "expected file number in '.cv_file' directive") ||
3269 check(FileNumber < 1, FileNumberLoc, "file number less than one") ||
3270 check(getTok().isNot(AsmToken::String),
3271 "unexpected token in '.cv_file' directive") ||
3272 // Usually directory and filename are together, otherwise just
3273 // directory. Allow the strings to have escaped octal character sequence.
3274 parseEscapedString(Filename) ||
3275 parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00003276 "unexpected token in '.cv_file' directive"))
3277 return true;
3278
3279 if (getStreamer().EmitCVFileDirective(FileNumber, Filename) == 0)
3280 Error(FileNumberLoc, "file number already allocated");
Reid Kleckner2214ed82016-01-29 00:49:42 +00003281
3282 return false;
3283}
3284
3285/// parseDirectiveCVLoc
3286/// ::= .cv_loc FunctionId FileNumber [LineNumber] [ColumnPos] [prologue_end]
3287/// [is_stmt VALUE]
3288/// The first number is a file number, must have been previously assigned with
3289/// a .file directive, the second number is the line number and optionally the
3290/// third number is a column position (zero if not specified). The remaining
3291/// optional items are .loc sub-directives.
3292bool AsmParser::parseDirectiveCVLoc() {
Nirav Davea645433c2016-07-18 15:24:03 +00003293 SMLoc Loc;
3294 int64_t FunctionId, FileNumber;
3295 if (getTokenLoc(Loc) ||
3296 parseIntToken(FunctionId, "unexpected token in '.cv_loc' directive") ||
3297 check(FunctionId < 0, Loc,
3298 "function id less than zero in '.cv_loc' directive") ||
3299 getTokenLoc(Loc) ||
3300 parseIntToken(FileNumber, "expected integer in '.cv_loc' directive") ||
3301 check(FileNumber < 1, Loc,
3302 "file number less than one in '.cv_loc' directive") ||
3303 check(!getContext().isValidCVFileNumber(FileNumber), Loc,
3304 "unassigned file number in '.cv_loc' directive"))
3305 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003306
3307 int64_t LineNumber = 0;
3308 if (getLexer().is(AsmToken::Integer)) {
3309 LineNumber = getTok().getIntVal();
3310 if (LineNumber < 0)
3311 return TokError("line number less than zero in '.cv_loc' directive");
3312 Lex();
3313 }
3314
3315 int64_t ColumnPos = 0;
3316 if (getLexer().is(AsmToken::Integer)) {
3317 ColumnPos = getTok().getIntVal();
3318 if (ColumnPos < 0)
3319 return TokError("column position less than zero in '.cv_loc' directive");
3320 Lex();
3321 }
3322
3323 bool PrologueEnd = false;
3324 uint64_t IsStmt = 0;
3325 while (getLexer().isNot(AsmToken::EndOfStatement)) {
3326 StringRef Name;
3327 SMLoc Loc = getTok().getLoc();
3328 if (parseIdentifier(Name))
3329 return TokError("unexpected token in '.cv_loc' directive");
3330
3331 if (Name == "prologue_end")
3332 PrologueEnd = true;
3333 else if (Name == "is_stmt") {
3334 Loc = getTok().getLoc();
3335 const MCExpr *Value;
3336 if (parseExpression(Value))
3337 return true;
3338 // The expression must be the constant 0 or 1.
3339 IsStmt = ~0ULL;
3340 if (const auto *MCE = dyn_cast<MCConstantExpr>(Value))
3341 IsStmt = MCE->getValue();
3342
3343 if (IsStmt > 1)
3344 return Error(Loc, "is_stmt value not 0 or 1");
3345 } else {
3346 return Error(Loc, "unknown sub-directive in '.cv_loc' directive");
3347 }
3348 }
Nirav Davea645433c2016-07-18 15:24:03 +00003349 Lex();
Reid Kleckner2214ed82016-01-29 00:49:42 +00003350
3351 getStreamer().EmitCVLocDirective(FunctionId, FileNumber, LineNumber,
3352 ColumnPos, PrologueEnd, IsStmt, StringRef());
3353 return false;
3354}
3355
3356/// parseDirectiveCVLinetable
3357/// ::= .cv_linetable FunctionId, FnStart, FnEnd
3358bool AsmParser::parseDirectiveCVLinetable() {
Nirav Davea645433c2016-07-18 15:24:03 +00003359 int64_t FunctionId;
3360 StringRef FnStartName, FnEndName;
3361 SMLoc Loc = getTok().getLoc();
3362 if (parseIntToken(FunctionId,
3363 "expected Integer in '.cv_linetable' directive") ||
3364 check(FunctionId < 0, Loc,
3365 "function id less than zero in '.cv_linetable' directive") ||
3366 parseToken(AsmToken::Comma,
3367 "unexpected token in '.cv_linetable' directive") ||
3368 getTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3369 "expected identifier in directive") ||
3370 parseToken(AsmToken::Comma,
3371 "unexpected token in '.cv_linetable' directive") ||
3372 getTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3373 "expected identifier in directive"))
3374 return true;
Reid Kleckner2214ed82016-01-29 00:49:42 +00003375
3376 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3377 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
3378
3379 getStreamer().EmitCVLinetableDirective(FunctionId, FnStartSym, FnEndSym);
3380 return false;
3381}
3382
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003383/// parseDirectiveCVInlineLinetable
David Majnemerc9911f22016-02-02 19:22:34 +00003384/// ::= .cv_inline_linetable PrimaryFunctionId FileId LineNum FnStart FnEnd
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003385/// ("contains" SecondaryFunctionId+)?
3386bool AsmParser::parseDirectiveCVInlineLinetable() {
Nirav Davea645433c2016-07-18 15:24:03 +00003387 int64_t PrimaryFunctionId, SourceFileId, SourceLineNum;
3388 StringRef FnStartName, FnEndName;
3389 SMLoc Loc = getTok().getLoc();
3390 if (parseIntToken(
3391 PrimaryFunctionId,
3392 "expected PrimaryFunctionId in '.cv_inline_linetable' directive") ||
3393 check(PrimaryFunctionId < 0, Loc,
3394 "function id less than zero in '.cv_inline_linetable' directive") ||
3395 getTokenLoc(Loc) ||
3396 parseIntToken(
3397 SourceFileId,
3398 "expected SourceField in '.cv_inline_linetable' directive") ||
3399 check(SourceFileId <= 0, Loc,
3400 "File id less than zero in '.cv_inline_linetable' directive") ||
3401 getTokenLoc(Loc) ||
3402 parseIntToken(
3403 SourceLineNum,
3404 "expected SourceLineNum in '.cv_inline_linetable' directive") ||
3405 check(SourceLineNum < 0, Loc,
3406 "Line number less than zero in '.cv_inline_linetable' directive") ||
3407 getTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3408 "expected identifier in directive") ||
3409 getTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3410 "expected identifier in directive"))
3411 return true;
David Majnemerc9911f22016-02-02 19:22:34 +00003412
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003413 SmallVector<unsigned, 8> SecondaryFunctionIds;
3414 if (getLexer().is(AsmToken::Identifier)) {
3415 if (getTok().getIdentifier() != "contains")
3416 return TokError(
3417 "unexpected identifier in '.cv_inline_linetable' directive");
3418 Lex();
3419
3420 while (getLexer().isNot(AsmToken::EndOfStatement)) {
3421 int64_t SecondaryFunctionId = getTok().getIntVal();
3422 if (SecondaryFunctionId < 0)
3423 return TokError(
3424 "function id less than zero in '.cv_inline_linetable' directive");
3425 Lex();
3426
3427 SecondaryFunctionIds.push_back(SecondaryFunctionId);
3428 }
3429 }
3430
Nirav Davea645433c2016-07-18 15:24:03 +00003431 if (parseToken(AsmToken::EndOfStatement, "Expected End of Statement"))
3432 return true;
3433
3434 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3435 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
Reid Kleckner1fcd6102016-02-02 17:41:18 +00003436 getStreamer().EmitCVInlineLinetableDirective(PrimaryFunctionId, SourceFileId,
3437 SourceLineNum, FnStartSym,
David Majnemerc9911f22016-02-02 19:22:34 +00003438 FnEndSym, SecondaryFunctionIds);
David Majnemer6fcbd7e2016-01-29 19:24:12 +00003439 return false;
3440}
3441
David Majnemer408b5e62016-02-05 01:55:49 +00003442/// parseDirectiveCVDefRange
3443/// ::= .cv_def_range RangeStart RangeEnd (GapStart GapEnd)*, bytes*
3444bool AsmParser::parseDirectiveCVDefRange() {
3445 SMLoc Loc;
3446 std::vector<std::pair<const MCSymbol *, const MCSymbol *>> Ranges;
3447 while (getLexer().is(AsmToken::Identifier)) {
3448 Loc = getLexer().getLoc();
3449 StringRef GapStartName;
3450 if (parseIdentifier(GapStartName))
3451 return Error(Loc, "expected identifier in directive");
3452 MCSymbol *GapStartSym = getContext().getOrCreateSymbol(GapStartName);
3453
3454 Loc = getLexer().getLoc();
3455 StringRef GapEndName;
3456 if (parseIdentifier(GapEndName))
3457 return Error(Loc, "expected identifier in directive");
3458 MCSymbol *GapEndSym = getContext().getOrCreateSymbol(GapEndName);
3459
3460 Ranges.push_back({GapStartSym, GapEndSym});
3461 }
3462
David Majnemer408b5e62016-02-05 01:55:49 +00003463 std::string FixedSizePortion;
Nirav Davea645433c2016-07-18 15:24:03 +00003464 if (parseToken(AsmToken::Comma, "unexpected token in directive") ||
3465 parseEscapedString(FixedSizePortion))
David Majnemer408b5e62016-02-05 01:55:49 +00003466 return true;
David Majnemer408b5e62016-02-05 01:55:49 +00003467
3468 getStreamer().EmitCVDefRangeDirective(Ranges, FixedSizePortion);
3469 return false;
3470}
3471
Reid Kleckner2214ed82016-01-29 00:49:42 +00003472/// parseDirectiveCVStringTable
3473/// ::= .cv_stringtable
3474bool AsmParser::parseDirectiveCVStringTable() {
3475 getStreamer().EmitCVStringTableDirective();
3476 return false;
3477}
3478
3479/// parseDirectiveCVFileChecksums
3480/// ::= .cv_filechecksums
3481bool AsmParser::parseDirectiveCVFileChecksums() {
3482 getStreamer().EmitCVFileChecksumsDirective();
3483 return false;
3484}
3485
Jim Grosbach4b905842013-09-20 23:08:21 +00003486/// parseDirectiveCFISections
Eli Bendersky17233942013-01-15 22:59:42 +00003487/// ::= .cfi_sections section [, section]
Jim Grosbach4b905842013-09-20 23:08:21 +00003488bool AsmParser::parseDirectiveCFISections() {
Eli Bendersky17233942013-01-15 22:59:42 +00003489 StringRef Name;
3490 bool EH = false;
3491 bool Debug = false;
3492
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003493 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003494 return TokError("Expected an identifier");
3495
3496 if (Name == ".eh_frame")
3497 EH = true;
3498 else if (Name == ".debug_frame")
3499 Debug = true;
3500
3501 if (getLexer().is(AsmToken::Comma)) {
3502 Lex();
3503
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003504 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003505 return TokError("Expected an identifier");
3506
3507 if (Name == ".eh_frame")
3508 EH = true;
3509 else if (Name == ".debug_frame")
3510 Debug = true;
3511 }
3512
3513 getStreamer().EmitCFISections(EH, Debug);
3514 return false;
3515}
3516
Jim Grosbach4b905842013-09-20 23:08:21 +00003517/// parseDirectiveCFIStartProc
David Majnemere035cf92014-01-27 17:20:25 +00003518/// ::= .cfi_startproc [simple]
Jim Grosbach4b905842013-09-20 23:08:21 +00003519bool AsmParser::parseDirectiveCFIStartProc() {
David Majnemere035cf92014-01-27 17:20:25 +00003520 StringRef Simple;
3521 if (getLexer().isNot(AsmToken::EndOfStatement))
3522 if (parseIdentifier(Simple) || Simple != "simple")
3523 return TokError("unexpected token in .cfi_startproc directive");
3524
Nirav Davea645433c2016-07-18 15:24:03 +00003525 if (parseToken(AsmToken::EndOfStatement, "Expected end of statement"))
3526 return true;
3527
Oliver Stannardcf6bfb12014-11-03 12:19:03 +00003528 getStreamer().EmitCFIStartProc(!Simple.empty());
Eli Bendersky17233942013-01-15 22:59:42 +00003529 return false;
3530}
3531
Jim Grosbach4b905842013-09-20 23:08:21 +00003532/// parseDirectiveCFIEndProc
Eli Bendersky17233942013-01-15 22:59:42 +00003533/// ::= .cfi_endproc
Jim Grosbach4b905842013-09-20 23:08:21 +00003534bool AsmParser::parseDirectiveCFIEndProc() {
Eli Bendersky17233942013-01-15 22:59:42 +00003535 getStreamer().EmitCFIEndProc();
3536 return false;
3537}
3538
Jim Grosbach4b905842013-09-20 23:08:21 +00003539/// \brief parse register name or number.
3540bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
Eli Bendersky17233942013-01-15 22:59:42 +00003541 SMLoc DirectiveLoc) {
3542 unsigned RegNo;
3543
3544 if (getLexer().isNot(AsmToken::Integer)) {
3545 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
3546 return true;
Bill Wendlingbc07a892013-06-18 07:20:20 +00003547 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
Eli Bendersky17233942013-01-15 22:59:42 +00003548 } else
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003549 return parseAbsoluteExpression(Register);
Eli Bendersky17233942013-01-15 22:59:42 +00003550
3551 return false;
3552}
3553
Jim Grosbach4b905842013-09-20 23:08:21 +00003554/// parseDirectiveCFIDefCfa
Eli Bendersky17233942013-01-15 22:59:42 +00003555/// ::= .cfi_def_cfa register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003556bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003557 int64_t Register = 0, Offset = 0;
3558 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3559 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3560 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003561 return true;
3562
3563 getStreamer().EmitCFIDefCfa(Register, Offset);
3564 return false;
3565}
3566
Jim Grosbach4b905842013-09-20 23:08:21 +00003567/// parseDirectiveCFIDefCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003568/// ::= .cfi_def_cfa_offset offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003569bool AsmParser::parseDirectiveCFIDefCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00003570 int64_t Offset = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003571 if (parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003572 return true;
3573
3574 getStreamer().EmitCFIDefCfaOffset(Offset);
3575 return false;
3576}
3577
Jim Grosbach4b905842013-09-20 23:08:21 +00003578/// parseDirectiveCFIRegister
Eli Bendersky17233942013-01-15 22:59:42 +00003579/// ::= .cfi_register register, register
Jim Grosbach4b905842013-09-20 23:08:21 +00003580bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003581 int64_t Register1 = 0, Register2 = 0;
3582 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc) ||
3583 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3584 parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003585 return true;
3586
3587 getStreamer().EmitCFIRegister(Register1, Register2);
3588 return false;
3589}
3590
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00003591/// parseDirectiveCFIWindowSave
3592/// ::= .cfi_window_save
3593bool AsmParser::parseDirectiveCFIWindowSave() {
3594 getStreamer().EmitCFIWindowSave();
3595 return false;
3596}
3597
Jim Grosbach4b905842013-09-20 23:08:21 +00003598/// parseDirectiveCFIAdjustCfaOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003599/// ::= .cfi_adjust_cfa_offset adjustment
Jim Grosbach4b905842013-09-20 23:08:21 +00003600bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
Eli Bendersky17233942013-01-15 22:59:42 +00003601 int64_t Adjustment = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003602 if (parseAbsoluteExpression(Adjustment))
Eli Bendersky17233942013-01-15 22:59:42 +00003603 return true;
3604
3605 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3606 return false;
3607}
3608
Jim Grosbach4b905842013-09-20 23:08:21 +00003609/// parseDirectiveCFIDefCfaRegister
Eli Bendersky17233942013-01-15 22:59:42 +00003610/// ::= .cfi_def_cfa_register register
Jim Grosbach4b905842013-09-20 23:08:21 +00003611bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003612 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003613 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003614 return true;
3615
3616 getStreamer().EmitCFIDefCfaRegister(Register);
3617 return false;
3618}
3619
Jim Grosbach4b905842013-09-20 23:08:21 +00003620/// parseDirectiveCFIOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003621/// ::= .cfi_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003622bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003623 int64_t Register = 0;
3624 int64_t Offset = 0;
3625
Nirav Davea645433c2016-07-18 15:24:03 +00003626 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3627 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3628 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003629 return true;
3630
3631 getStreamer().EmitCFIOffset(Register, Offset);
3632 return false;
3633}
3634
Jim Grosbach4b905842013-09-20 23:08:21 +00003635/// parseDirectiveCFIRelOffset
Eli Bendersky17233942013-01-15 22:59:42 +00003636/// ::= .cfi_rel_offset register, offset
Jim Grosbach4b905842013-09-20 23:08:21 +00003637bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00003638 int64_t Register = 0, Offset = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003639
Nirav Davea645433c2016-07-18 15:24:03 +00003640 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3641 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3642 parseAbsoluteExpression(Offset))
Eli Bendersky17233942013-01-15 22:59:42 +00003643 return true;
3644
3645 getStreamer().EmitCFIRelOffset(Register, Offset);
3646 return false;
3647}
3648
3649static bool isValidEncoding(int64_t Encoding) {
3650 if (Encoding & ~0xff)
3651 return false;
3652
3653 if (Encoding == dwarf::DW_EH_PE_omit)
3654 return true;
3655
3656 const unsigned Format = Encoding & 0xf;
3657 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3658 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3659 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3660 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3661 return false;
3662
3663 const unsigned Application = Encoding & 0x70;
3664 if (Application != dwarf::DW_EH_PE_absptr &&
3665 Application != dwarf::DW_EH_PE_pcrel)
3666 return false;
3667
3668 return true;
3669}
3670
Jim Grosbach4b905842013-09-20 23:08:21 +00003671/// parseDirectiveCFIPersonalityOrLsda
Eli Bendersky17233942013-01-15 22:59:42 +00003672/// IsPersonality true for cfi_personality, false for cfi_lsda
3673/// ::= .cfi_personality encoding, [symbol_name]
3674/// ::= .cfi_lsda encoding, [symbol_name]
Jim Grosbach4b905842013-09-20 23:08:21 +00003675bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
Eli Bendersky17233942013-01-15 22:59:42 +00003676 int64_t Encoding = 0;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003677 if (parseAbsoluteExpression(Encoding))
Eli Bendersky17233942013-01-15 22:59:42 +00003678 return true;
3679 if (Encoding == dwarf::DW_EH_PE_omit)
3680 return false;
3681
Eli Bendersky17233942013-01-15 22:59:42 +00003682 StringRef Name;
Nirav Davea645433c2016-07-18 15:24:03 +00003683 if (check(!isValidEncoding(Encoding), "unsupported encoding.") ||
3684 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3685 check(parseIdentifier(Name), "expected identifier in directive"))
3686 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003687
Jim Grosbach6f482002015-05-18 18:43:14 +00003688 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Eli Bendersky17233942013-01-15 22:59:42 +00003689
3690 if (IsPersonality)
3691 getStreamer().EmitCFIPersonality(Sym, Encoding);
3692 else
3693 getStreamer().EmitCFILsda(Sym, Encoding);
3694 return false;
3695}
3696
Jim Grosbach4b905842013-09-20 23:08:21 +00003697/// parseDirectiveCFIRememberState
Eli Bendersky17233942013-01-15 22:59:42 +00003698/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00003699bool AsmParser::parseDirectiveCFIRememberState() {
Eli Bendersky17233942013-01-15 22:59:42 +00003700 getStreamer().EmitCFIRememberState();
3701 return false;
3702}
3703
Jim Grosbach4b905842013-09-20 23:08:21 +00003704/// parseDirectiveCFIRestoreState
Eli Bendersky17233942013-01-15 22:59:42 +00003705/// ::= .cfi_remember_state
Jim Grosbach4b905842013-09-20 23:08:21 +00003706bool AsmParser::parseDirectiveCFIRestoreState() {
Eli Bendersky17233942013-01-15 22:59:42 +00003707 getStreamer().EmitCFIRestoreState();
3708 return false;
3709}
3710
Jim Grosbach4b905842013-09-20 23:08:21 +00003711/// parseDirectiveCFISameValue
Eli Bendersky17233942013-01-15 22:59:42 +00003712/// ::= .cfi_same_value register
Jim Grosbach4b905842013-09-20 23:08:21 +00003713bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003714 int64_t Register = 0;
3715
Jim Grosbach4b905842013-09-20 23:08:21 +00003716 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003717 return true;
3718
3719 getStreamer().EmitCFISameValue(Register);
3720 return false;
3721}
3722
Jim Grosbach4b905842013-09-20 23:08:21 +00003723/// parseDirectiveCFIRestore
Eli Bendersky17233942013-01-15 22:59:42 +00003724/// ::= .cfi_restore register
Jim Grosbach4b905842013-09-20 23:08:21 +00003725bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003726 int64_t Register = 0;
Jim Grosbach4b905842013-09-20 23:08:21 +00003727 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003728 return true;
3729
3730 getStreamer().EmitCFIRestore(Register);
3731 return false;
3732}
3733
Jim Grosbach4b905842013-09-20 23:08:21 +00003734/// parseDirectiveCFIEscape
Eli Bendersky17233942013-01-15 22:59:42 +00003735/// ::= .cfi_escape expression[,...]
Jim Grosbach4b905842013-09-20 23:08:21 +00003736bool AsmParser::parseDirectiveCFIEscape() {
Eli Bendersky17233942013-01-15 22:59:42 +00003737 std::string Values;
3738 int64_t CurrValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003739 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00003740 return true;
3741
3742 Values.push_back((uint8_t)CurrValue);
3743
3744 while (getLexer().is(AsmToken::Comma)) {
3745 Lex();
3746
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003747 if (parseAbsoluteExpression(CurrValue))
Eli Bendersky17233942013-01-15 22:59:42 +00003748 return true;
3749
3750 Values.push_back((uint8_t)CurrValue);
3751 }
3752
3753 getStreamer().EmitCFIEscape(Values);
3754 return false;
3755}
3756
Jim Grosbach4b905842013-09-20 23:08:21 +00003757/// parseDirectiveCFISignalFrame
Eli Bendersky17233942013-01-15 22:59:42 +00003758/// ::= .cfi_signal_frame
Jim Grosbach4b905842013-09-20 23:08:21 +00003759bool AsmParser::parseDirectiveCFISignalFrame() {
Nirav Davea645433c2016-07-18 15:24:03 +00003760 if (parseToken(AsmToken::EndOfStatement,
3761 "unexpected token in '.cfi_signal_frame'"))
3762 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003763
3764 getStreamer().EmitCFISignalFrame();
3765 return false;
3766}
3767
Jim Grosbach4b905842013-09-20 23:08:21 +00003768/// parseDirectiveCFIUndefined
Eli Bendersky17233942013-01-15 22:59:42 +00003769/// ::= .cfi_undefined register
Jim Grosbach4b905842013-09-20 23:08:21 +00003770bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003771 int64_t Register = 0;
3772
Jim Grosbach4b905842013-09-20 23:08:21 +00003773 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
Eli Bendersky17233942013-01-15 22:59:42 +00003774 return true;
3775
3776 getStreamer().EmitCFIUndefined(Register);
3777 return false;
3778}
3779
Jim Grosbach4b905842013-09-20 23:08:21 +00003780/// parseDirectiveMacrosOnOff
Eli Bendersky17233942013-01-15 22:59:42 +00003781/// ::= .macros_on
3782/// ::= .macros_off
Jim Grosbach4b905842013-09-20 23:08:21 +00003783bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
Nirav Davea645433c2016-07-18 15:24:03 +00003784 if (parseToken(AsmToken::EndOfStatement,
3785 "unexpected token in '" + Directive + "' directive"))
3786 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00003787
Jim Grosbach4b905842013-09-20 23:08:21 +00003788 setMacrosEnabled(Directive == ".macros_on");
Eli Bendersky17233942013-01-15 22:59:42 +00003789 return false;
3790}
3791
Jim Grosbach4b905842013-09-20 23:08:21 +00003792/// parseDirectiveMacro
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00003793/// ::= .macro name[,] [parameters]
Jim Grosbach4b905842013-09-20 23:08:21 +00003794bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00003795 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003796 if (parseIdentifier(Name))
Eli Bendersky17233942013-01-15 22:59:42 +00003797 return TokError("expected identifier in '.macro' directive");
3798
Saleem Abdulrasool27304cb2014-02-16 04:56:31 +00003799 if (getLexer().is(AsmToken::Comma))
3800 Lex();
3801
Eli Bendersky17233942013-01-15 22:59:42 +00003802 MCAsmMacroParameters Parameters;
David Majnemer91fc4c22014-01-29 18:57:46 +00003803 while (getLexer().isNot(AsmToken::EndOfStatement)) {
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003804
Alexander Kornienko8c0809c2015-01-15 11:41:30 +00003805 if (!Parameters.empty() && Parameters.back().Vararg)
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003806 return Error(Lexer.getLoc(),
3807 "Vararg parameter '" + Parameters.back().Name +
3808 "' should be last one in the list of parameters.");
3809
David Majnemer91fc4c22014-01-29 18:57:46 +00003810 MCAsmMacroParameter Parameter;
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00003811 if (parseIdentifier(Parameter.Name))
David Majnemer91fc4c22014-01-29 18:57:46 +00003812 return TokError("expected identifier in '.macro' directive");
Eli Bendersky17233942013-01-15 22:59:42 +00003813
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003814 if (Lexer.is(AsmToken::Colon)) {
3815 Lex(); // consume ':'
3816
3817 SMLoc QualLoc;
3818 StringRef Qualifier;
3819
3820 QualLoc = Lexer.getLoc();
3821 if (parseIdentifier(Qualifier))
3822 return Error(QualLoc, "missing parameter qualifier for "
3823 "'" + Parameter.Name + "' in macro '" + Name + "'");
3824
3825 if (Qualifier == "req")
3826 Parameter.Required = true;
Kevin Enderbye3c13462014-08-04 23:14:37 +00003827 else if (Qualifier == "vararg")
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003828 Parameter.Vararg = true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003829 else
3830 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
3831 "for '" + Parameter.Name + "' in macro '" + Name + "'");
3832 }
3833
David Majnemer91fc4c22014-01-29 18:57:46 +00003834 if (getLexer().is(AsmToken::Equal)) {
3835 Lex();
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003836
3837 SMLoc ParamLoc;
3838
3839 ParamLoc = Lexer.getLoc();
Stepan Dyatkovskiyafc364b2014-04-23 06:56:28 +00003840 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
David Majnemer91fc4c22014-01-29 18:57:46 +00003841 return true;
Saleem Abdulrasoolf903a442014-02-19 03:00:29 +00003842
3843 if (Parameter.Required)
3844 Warning(ParamLoc, "pointless default value for required parameter "
3845 "'" + Parameter.Name + "' in macro '" + Name + "'");
Eli Bendersky17233942013-01-15 22:59:42 +00003846 }
David Majnemer91fc4c22014-01-29 18:57:46 +00003847
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00003848 Parameters.push_back(std::move(Parameter));
David Majnemer91fc4c22014-01-29 18:57:46 +00003849
3850 if (getLexer().is(AsmToken::Comma))
3851 Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00003852 }
3853
Nirav Dave1180e6892016-06-02 17:15:05 +00003854 // Eat just the end of statement.
3855 Lexer.Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00003856
Nirav Dave1180e6892016-06-02 17:15:05 +00003857 // Consuming deferred text, so use Lexer.Lex to ignore Lexing Errors
Eli Bendersky17233942013-01-15 22:59:42 +00003858 AsmToken EndToken, StartToken = getTok();
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00003859 unsigned MacroDepth = 0;
Eli Bendersky17233942013-01-15 22:59:42 +00003860 // Lex the macro definition.
Eugene Zelenko33d7b762016-08-23 17:14:32 +00003861 while (true) {
Nirav Dave1180e6892016-06-02 17:15:05 +00003862 // Ignore Lexing errors in macros.
3863 while (Lexer.is(AsmToken::Error)) {
3864 Lexer.Lex();
3865 }
3866
Eli Bendersky17233942013-01-15 22:59:42 +00003867 // Check whether we have reached the end of the file.
3868 if (getLexer().is(AsmToken::Eof))
3869 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
3870
3871 // Otherwise, check whether we have reach the .endmacro.
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00003872 if (getLexer().is(AsmToken::Identifier)) {
3873 if (getTok().getIdentifier() == ".endm" ||
3874 getTok().getIdentifier() == ".endmacro") {
3875 if (MacroDepth == 0) { // Outermost macro.
3876 EndToken = getTok();
Nirav Dave1180e6892016-06-02 17:15:05 +00003877 Lexer.Lex();
Benjamin Kramer9d94a4e2014-02-09 16:22:00 +00003878 if (getLexer().isNot(AsmToken::EndOfStatement))
3879 return TokError("unexpected token in '" + EndToken.getIdentifier() +
3880 "' directive");
3881 break;
3882 } else {
3883 // Otherwise we just found the end of an inner macro.
3884 --MacroDepth;
3885 }
3886 } else if (getTok().getIdentifier() == ".macro") {
3887 // We allow nested macros. Those aren't instantiated until the outermost
3888 // macro is expanded so just ignore them for now.
3889 ++MacroDepth;
3890 }
Eli Bendersky17233942013-01-15 22:59:42 +00003891 }
3892
3893 // Otherwise, scan til the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003894 eatToEndOfStatement();
Eli Bendersky17233942013-01-15 22:59:42 +00003895 }
3896
Jim Grosbach4b905842013-09-20 23:08:21 +00003897 if (lookupMacro(Name)) {
Eli Bendersky17233942013-01-15 22:59:42 +00003898 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
3899 }
3900
3901 const char *BodyStart = StartToken.getLoc().getPointer();
3902 const char *BodyEnd = EndToken.getLoc().getPointer();
3903 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
Jim Grosbach4b905842013-09-20 23:08:21 +00003904 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
Benjamin Kramercb3e06b2014-10-03 18:32:55 +00003905 defineMacro(Name, MCAsmMacro(Name, Body, std::move(Parameters)));
Eli Bendersky17233942013-01-15 22:59:42 +00003906 return false;
3907}
3908
Jim Grosbach4b905842013-09-20 23:08:21 +00003909/// checkForBadMacro
Kevin Enderby81c944c2013-01-22 21:44:53 +00003910///
3911/// With the support added for named parameters there may be code out there that
3912/// is transitioning from positional parameters. In versions of gas that did
Alp Tokercb402912014-01-24 17:20:08 +00003913/// not support named parameters they would be ignored on the macro definition.
Kevin Enderby81c944c2013-01-22 21:44:53 +00003914/// But to support both styles of parameters this is not possible so if a macro
Alp Tokercb402912014-01-24 17:20:08 +00003915/// definition has named parameters but does not use them and has what appears
Kevin Enderby81c944c2013-01-22 21:44:53 +00003916/// to be positional parameters, strings like $1, $2, ... and $n, then issue a
3917/// warning that the positional parameter found in body which have no effect.
3918/// Hoping the developer will either remove the named parameters from the macro
Alp Tokercb402912014-01-24 17:20:08 +00003919/// definition so the positional parameters get used if that was what was
Kevin Enderby81c944c2013-01-22 21:44:53 +00003920/// intended or change the macro to use the named parameters. It is possible
3921/// this warning will trigger when the none of the named parameters are used
3922/// and the strings like $1 are infact to simply to be passed trough unchanged.
Jim Grosbach4b905842013-09-20 23:08:21 +00003923void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
Kevin Enderby81c944c2013-01-22 21:44:53 +00003924 StringRef Body,
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00003925 ArrayRef<MCAsmMacroParameter> Parameters) {
Kevin Enderby81c944c2013-01-22 21:44:53 +00003926 // If this macro is not defined with named parameters the warning we are
3927 // checking for here doesn't apply.
3928 unsigned NParameters = Parameters.size();
3929 if (NParameters == 0)
3930 return;
3931
3932 bool NamedParametersFound = false;
3933 bool PositionalParametersFound = false;
3934
3935 // Look at the body of the macro for use of both the named parameters and what
3936 // are likely to be positional parameters. This is what expandMacro() is
3937 // doing when it finds the parameters in the body.
3938 while (!Body.empty()) {
3939 // Scan for the next possible parameter.
3940 std::size_t End = Body.size(), Pos = 0;
3941 for (; Pos != End; ++Pos) {
3942 // Check for a substitution or escape.
3943 // This macro is defined with parameters, look for \foo, \bar, etc.
3944 if (Body[Pos] == '\\' && Pos + 1 != End)
3945 break;
3946
3947 // This macro should have parameters, but look for $0, $1, ..., $n too.
3948 if (Body[Pos] != '$' || Pos + 1 == End)
3949 continue;
3950 char Next = Body[Pos + 1];
Guy Benyei83c74e92013-02-12 21:21:59 +00003951 if (Next == '$' || Next == 'n' ||
3952 isdigit(static_cast<unsigned char>(Next)))
Kevin Enderby81c944c2013-01-22 21:44:53 +00003953 break;
3954 }
3955
3956 // Check if we reached the end.
3957 if (Pos == End)
3958 break;
3959
3960 if (Body[Pos] == '$') {
Jim Grosbach4b905842013-09-20 23:08:21 +00003961 switch (Body[Pos + 1]) {
3962 // $$ => $
Kevin Enderby81c944c2013-01-22 21:44:53 +00003963 case '$':
3964 break;
3965
Jim Grosbach4b905842013-09-20 23:08:21 +00003966 // $n => number of arguments
Kevin Enderby81c944c2013-01-22 21:44:53 +00003967 case 'n':
3968 PositionalParametersFound = true;
3969 break;
3970
Jim Grosbach4b905842013-09-20 23:08:21 +00003971 // $[0-9] => argument
Kevin Enderby81c944c2013-01-22 21:44:53 +00003972 default: {
3973 PositionalParametersFound = true;
3974 break;
Jim Grosbach4b905842013-09-20 23:08:21 +00003975 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00003976 }
3977 Pos += 2;
3978 } else {
3979 unsigned I = Pos + 1;
3980 while (isIdentifierChar(Body[I]) && I + 1 != End)
3981 ++I;
3982
Jim Grosbach4b905842013-09-20 23:08:21 +00003983 const char *Begin = Body.data() + Pos + 1;
3984 StringRef Argument(Begin, I - (Pos + 1));
Kevin Enderby81c944c2013-01-22 21:44:53 +00003985 unsigned Index = 0;
3986 for (; Index < NParameters; ++Index)
Saleem Abdulrasoola08585b2014-02-19 03:00:23 +00003987 if (Parameters[Index].Name == Argument)
Kevin Enderby81c944c2013-01-22 21:44:53 +00003988 break;
3989
3990 if (Index == NParameters) {
Jim Grosbach4b905842013-09-20 23:08:21 +00003991 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
3992 Pos += 3;
3993 else {
3994 Pos = I;
3995 }
Kevin Enderby81c944c2013-01-22 21:44:53 +00003996 } else {
3997 NamedParametersFound = true;
3998 Pos += 1 + Argument.size();
3999 }
4000 }
4001 // Update the scan point.
4002 Body = Body.substr(Pos);
4003 }
4004
4005 if (!NamedParametersFound && PositionalParametersFound)
4006 Warning(DirectiveLoc, "macro defined with named parameters which are not "
4007 "used in macro body, possible positional parameter "
4008 "found in body which will have no effect");
4009}
4010
Nico Weber155dccd12014-07-24 17:08:39 +00004011/// parseDirectiveExitMacro
4012/// ::= .exitm
4013bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
Nirav Davea645433c2016-07-18 15:24:03 +00004014 if (parseToken(AsmToken::EndOfStatement,
4015 "unexpected token in '" + Directive + "' directive"))
4016 return true;
Nico Weber155dccd12014-07-24 17:08:39 +00004017
4018 if (!isInsideMacroInstantiation())
4019 return TokError("unexpected '" + Directive + "' in file, "
4020 "no current macro definition");
4021
4022 // Exit all conditionals that are active in the current macro.
4023 while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
4024 TheCondState = TheCondStack.back();
4025 TheCondStack.pop_back();
4026 }
4027
4028 handleMacroExit();
4029 return false;
4030}
4031
Jim Grosbach4b905842013-09-20 23:08:21 +00004032/// parseDirectiveEndMacro
Eli Bendersky17233942013-01-15 22:59:42 +00004033/// ::= .endm
4034/// ::= .endmacro
Jim Grosbach4b905842013-09-20 23:08:21 +00004035bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
Eli Bendersky17233942013-01-15 22:59:42 +00004036 if (getLexer().isNot(AsmToken::EndOfStatement))
4037 return TokError("unexpected token in '" + Directive + "' directive");
4038
4039 // If we are inside a macro instantiation, terminate the current
4040 // instantiation.
Jim Grosbach4b905842013-09-20 23:08:21 +00004041 if (isInsideMacroInstantiation()) {
4042 handleMacroExit();
Eli Bendersky17233942013-01-15 22:59:42 +00004043 return false;
4044 }
4045
4046 // Otherwise, this .endmacro is a stray entry in the file; well formed
4047 // .endmacro directives are handled during the macro definition parsing.
4048 return TokError("unexpected '" + Directive + "' in file, "
Jim Grosbach4b905842013-09-20 23:08:21 +00004049 "no current macro definition");
Eli Bendersky17233942013-01-15 22:59:42 +00004050}
4051
Jim Grosbach4b905842013-09-20 23:08:21 +00004052/// parseDirectivePurgeMacro
Eli Bendersky17233942013-01-15 22:59:42 +00004053/// ::= .purgem
Jim Grosbach4b905842013-09-20 23:08:21 +00004054bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
Eli Bendersky17233942013-01-15 22:59:42 +00004055 StringRef Name;
Nirav Davea645433c2016-07-18 15:24:03 +00004056 SMLoc Loc;
4057 if (getTokenLoc(Loc) || check(parseIdentifier(Name), Loc,
4058 "expected identifier in '.purgem' directive") ||
4059 parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00004060 "unexpected token in '.purgem' directive"))
Nirav Davea645433c2016-07-18 15:24:03 +00004061 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004062
Nirav Dave1ab71992016-07-18 19:35:21 +00004063 if (!lookupMacro(Name))
4064 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
4065
Jim Grosbach4b905842013-09-20 23:08:21 +00004066 undefineMacro(Name);
Eli Bendersky17233942013-01-15 22:59:42 +00004067 return false;
4068}
Eli Benderskyf483ff92012-12-20 19:05:53 +00004069
Jim Grosbach4b905842013-09-20 23:08:21 +00004070/// parseDirectiveBundleAlignMode
Eli Benderskyf483ff92012-12-20 19:05:53 +00004071/// ::= {.bundle_align_mode} expression
Jim Grosbach4b905842013-09-20 23:08:21 +00004072bool AsmParser::parseDirectiveBundleAlignMode() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004073 checkForValidSection();
Eli Benderskyf483ff92012-12-20 19:05:53 +00004074
4075 // Expect a single argument: an expression that evaluates to a constant
4076 // in the inclusive range 0-30.
4077 SMLoc ExprLoc = getLexer().getLoc();
4078 int64_t AlignSizePow2;
Nirav Davea645433c2016-07-18 15:24:03 +00004079 if (parseAbsoluteExpression(AlignSizePow2) ||
4080 parseToken(AsmToken::EndOfStatement, "unexpected token after expression "
4081 "in '.bundle_align_mode' "
4082 "directive") ||
4083 check(AlignSizePow2 < 0 || AlignSizePow2 > 30, ExprLoc,
4084 "invalid bundle alignment size (expected between 0 and 30)"))
Eli Benderskyf483ff92012-12-20 19:05:53 +00004085 return true;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004086
4087 // Because of AlignSizePow2's verified range we can safely truncate it to
4088 // unsigned.
4089 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
4090 return false;
4091}
4092
Jim Grosbach4b905842013-09-20 23:08:21 +00004093/// parseDirectiveBundleLock
Eli Bendersky802b6282013-01-07 21:51:08 +00004094/// ::= {.bundle_lock} [align_to_end]
Jim Grosbach4b905842013-09-20 23:08:21 +00004095bool AsmParser::parseDirectiveBundleLock() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004096 checkForValidSection();
Eli Bendersky802b6282013-01-07 21:51:08 +00004097 bool AlignToEnd = false;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004098
Eli Bendersky802b6282013-01-07 21:51:08 +00004099 if (getLexer().isNot(AsmToken::EndOfStatement)) {
4100 StringRef Option;
4101 SMLoc Loc = getTok().getLoc();
4102 const char *kInvalidOptionError =
Jim Grosbach4b905842013-09-20 23:08:21 +00004103 "invalid option for '.bundle_lock' directive";
Eli Bendersky802b6282013-01-07 21:51:08 +00004104
Nirav Davea645433c2016-07-18 15:24:03 +00004105 if (check(parseIdentifier(Option), Loc, kInvalidOptionError) ||
4106 check(Option != "align_to_end", Loc, kInvalidOptionError) ||
4107 check(getTok().isNot(AsmToken::EndOfStatement), Loc,
4108 "unexpected token after '.bundle_lock' directive option"))
4109 return true;
Eli Bendersky802b6282013-01-07 21:51:08 +00004110 AlignToEnd = true;
4111 }
4112
Eli Benderskyf483ff92012-12-20 19:05:53 +00004113 Lex();
4114
Eli Bendersky802b6282013-01-07 21:51:08 +00004115 getStreamer().EmitBundleLock(AlignToEnd);
Eli Benderskyf483ff92012-12-20 19:05:53 +00004116 return false;
4117}
4118
Jim Grosbach4b905842013-09-20 23:08:21 +00004119/// parseDirectiveBundleLock
Eli Benderskyf483ff92012-12-20 19:05:53 +00004120/// ::= {.bundle_lock}
Jim Grosbach4b905842013-09-20 23:08:21 +00004121bool AsmParser::parseDirectiveBundleUnlock() {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004122 checkForValidSection();
Eli Benderskyf483ff92012-12-20 19:05:53 +00004123
Nirav Davea645433c2016-07-18 15:24:03 +00004124 if (parseToken(AsmToken::EndOfStatement,
4125 "unexpected token in '.bundle_unlock' directive"))
4126 return true;
Eli Benderskyf483ff92012-12-20 19:05:53 +00004127
4128 getStreamer().EmitBundleUnlock();
4129 return false;
4130}
4131
Jim Grosbach4b905842013-09-20 23:08:21 +00004132/// parseDirectiveSpace
Eli Bendersky17233942013-01-15 22:59:42 +00004133/// ::= (.skip | .space) expression [ , expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004134bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004135 checkForValidSection();
Eli Bendersky17233942013-01-15 22:59:42 +00004136
Petr Hosek67a94a72016-05-28 05:57:48 +00004137 SMLoc NumBytesLoc = Lexer.getLoc();
4138 const MCExpr *NumBytes;
4139 if (parseExpression(NumBytes))
Eli Bendersky17233942013-01-15 22:59:42 +00004140 return true;
4141
4142 int64_t FillExpr = 0;
4143 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Eli Bendersky17233942013-01-15 22:59:42 +00004144
Nirav Davea645433c2016-07-18 15:24:03 +00004145 if (parseToken(AsmToken::Comma,
4146 "unexpected token in '" + Twine(IDVal) + "' directive") ||
4147 parseAbsoluteExpression(FillExpr))
Eli Bendersky17233942013-01-15 22:59:42 +00004148 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004149 }
4150
Nirav Davea645433c2016-07-18 15:24:03 +00004151 if (parseToken(AsmToken::EndOfStatement,
4152 "unexpected token in '" + Twine(IDVal) + "' directive"))
4153 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004154
Eli Bendersky17233942013-01-15 22:59:42 +00004155 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
Petr Hosek67a94a72016-05-28 05:57:48 +00004156 getStreamer().emitFill(*NumBytes, FillExpr, NumBytesLoc);
Eli Bendersky17233942013-01-15 22:59:42 +00004157
4158 return false;
4159}
4160
Jim Grosbach4b905842013-09-20 23:08:21 +00004161/// parseDirectiveLEB128
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004162/// ::= (.sleb128 | .uleb128) [ expression (, expression)* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004163bool AsmParser::parseDirectiveLEB128(bool Signed) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004164 checkForValidSection();
Eli Bendersky17233942013-01-15 22:59:42 +00004165 const MCExpr *Value;
4166
Eugene Zelenko33d7b762016-08-23 17:14:32 +00004167 while (true) {
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004168 if (parseExpression(Value))
4169 return true;
Eli Bendersky17233942013-01-15 22:59:42 +00004170
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004171 if (Signed)
4172 getStreamer().EmitSLEB128Value(Value);
4173 else
4174 getStreamer().EmitULEB128Value(Value);
Eli Bendersky17233942013-01-15 22:59:42 +00004175
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004176 if (getLexer().is(AsmToken::EndOfStatement))
4177 break;
4178
Nirav Davea645433c2016-07-18 15:24:03 +00004179 if (parseToken(AsmToken::Comma, "unexpected token in directive"))
4180 return true;
Benjamin Kramer68ca67b2015-02-19 20:24:04 +00004181 }
Nirav Davea645433c2016-07-18 15:24:03 +00004182 Lex();
Eli Bendersky17233942013-01-15 22:59:42 +00004183
4184 return false;
4185}
4186
Jim Grosbach4b905842013-09-20 23:08:21 +00004187/// parseDirectiveSymbolAttribute
Daniel Dunbara5508c82009-06-30 00:33:19 +00004188/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004189bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004190 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Eugene Zelenko33d7b762016-08-23 17:14:32 +00004191 while (true) {
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004192 StringRef Name;
Jim Grosbachebdf32f2011-09-15 17:56:49 +00004193 SMLoc Loc = getTok().getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004194
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004195 if (parseIdentifier(Name))
Jim Grosbachebdf32f2011-09-15 17:56:49 +00004196 return Error(Loc, "expected identifier in directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004197
Jim Grosbach6f482002015-05-18 18:43:14 +00004198 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Daniel Dunbara5508c82009-06-30 00:33:19 +00004199
Jim Grosbachebdf32f2011-09-15 17:56:49 +00004200 // Assembler local symbols don't make any sense here. Complain loudly.
4201 if (Sym->isTemporary())
4202 return Error(Loc, "non-local symbol required in directive");
4203
Saleem Abdulrasool4208b612013-08-09 01:52:03 +00004204 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
4205 return Error(Loc, "unable to emit symbol attribute");
Daniel Dunbara5508c82009-06-30 00:33:19 +00004206
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004207 if (getLexer().is(AsmToken::EndOfStatement))
Daniel Dunbara5508c82009-06-30 00:33:19 +00004208 break;
4209
Nirav Davea645433c2016-07-18 15:24:03 +00004210 if (parseToken(AsmToken::Comma, "unexpected token in directive"))
4211 return true;
Daniel Dunbara5508c82009-06-30 00:33:19 +00004212 }
4213 }
4214
Sean Callanan686ed8d2010-01-19 20:22:31 +00004215 Lex();
Jan Wen Voungc7682872010-09-30 01:09:20 +00004216 return false;
Daniel Dunbara5508c82009-06-30 00:33:19 +00004217}
Chris Lattnera1e11f52009-07-07 20:30:46 +00004218
Jim Grosbach4b905842013-09-20 23:08:21 +00004219/// parseDirectiveComm
Chris Lattner28ad7542009-07-09 17:25:12 +00004220/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
Jim Grosbach4b905842013-09-20 23:08:21 +00004221bool AsmParser::parseDirectiveComm(bool IsLocal) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004222 checkForValidSection();
Daniel Dunbare5444a82010-09-09 22:42:59 +00004223
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004224 SMLoc IDLoc = getLexer().getLoc();
Daniel Dunbarc54ecb32009-08-01 00:48:30 +00004225 StringRef Name;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004226 if (parseIdentifier(Name))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004227 return TokError("expected identifier in directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004228
Daniel Dunbar9ee33ca2009-07-31 21:55:09 +00004229 // Handle the identifier as the key symbol.
Jim Grosbach6f482002015-05-18 18:43:14 +00004230 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
Chris Lattnera1e11f52009-07-07 20:30:46 +00004231
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004232 if (getLexer().isNot(AsmToken::Comma))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004233 return TokError("unexpected token in directive");
Sean Callanan686ed8d2010-01-19 20:22:31 +00004234 Lex();
Chris Lattnera1e11f52009-07-07 20:30:46 +00004235
4236 int64_t Size;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004237 SMLoc SizeLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004238 if (parseAbsoluteExpression(Size))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004239 return true;
4240
4241 int64_t Pow2Alignment = 0;
4242 SMLoc Pow2AlignmentLoc;
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004243 if (getLexer().is(AsmToken::Comma)) {
Sean Callanan686ed8d2010-01-19 20:22:31 +00004244 Lex();
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004245 Pow2AlignmentLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004246 if (parseAbsoluteExpression(Pow2Alignment))
Chris Lattnera1e11f52009-07-07 20:30:46 +00004247 return true;
Michael J. Spencer530ce852010-10-09 11:00:50 +00004248
Benjamin Kramer68b9f052012-09-07 21:08:01 +00004249 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
4250 if (IsLocal && LCOMM == LCOMM::NoAlignment)
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00004251 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
4252
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00004253 // If this target takes alignments in bytes (not log) validate and convert.
Benjamin Kramer68b9f052012-09-07 21:08:01 +00004254 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
4255 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
Chris Lattnerab9cd3e2010-01-19 06:22:22 +00004256 if (!isPowerOf2_64(Pow2Alignment))
4257 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
4258 Pow2Alignment = Log2_64(Pow2Alignment);
4259 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00004260 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00004261
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004262 if (getLexer().isNot(AsmToken::EndOfStatement))
Chris Lattner28ad7542009-07-09 17:25:12 +00004263 return TokError("unexpected token in '.comm' or '.lcomm' directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004264
Sean Callanan686ed8d2010-01-19 20:22:31 +00004265 Lex();
Chris Lattnera1e11f52009-07-07 20:30:46 +00004266
Chris Lattner28ad7542009-07-09 17:25:12 +00004267 // NOTE: a size of zero for a .comm should create a undefined symbol
4268 // but a size of .lcomm creates a bss symbol of size zero.
Chris Lattnera1e11f52009-07-07 20:30:46 +00004269 if (Size < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00004270 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
Jim Grosbach4b905842013-09-20 23:08:21 +00004271 "be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00004272
Eric Christopherbc818852010-05-14 01:38:54 +00004273 // NOTE: The alignment in the directive is a power of 2 value, the assembler
Chris Lattnera1e11f52009-07-07 20:30:46 +00004274 // may internally end up wanting an alignment in bytes.
4275 // FIXME: Diagnose overflow.
4276 if (Pow2Alignment < 0)
Chris Lattner28ad7542009-07-09 17:25:12 +00004277 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
Jim Grosbach4b905842013-09-20 23:08:21 +00004278 "alignment, can't be less than zero");
Chris Lattnera1e11f52009-07-07 20:30:46 +00004279
Daniel Dunbar6860ac72009-08-22 07:22:36 +00004280 if (!Sym->isUndefined())
Chris Lattnera1e11f52009-07-07 20:30:46 +00004281 return Error(IDLoc, "invalid symbol redefinition");
4282
Chris Lattner28ad7542009-07-09 17:25:12 +00004283 // Create the Symbol as a common or local common with Size and Pow2Alignment
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00004284 if (IsLocal) {
Benjamin Kramer47f9ec92012-09-07 17:25:13 +00004285 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Daniel Dunbar6a715dc2009-08-30 06:17:16 +00004286 return false;
4287 }
Chris Lattnera1e11f52009-07-07 20:30:46 +00004288
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004289 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
Chris Lattnera1e11f52009-07-07 20:30:46 +00004290 return false;
4291}
Chris Lattner07cadaf2009-07-10 22:20:30 +00004292
Jim Grosbach4b905842013-09-20 23:08:21 +00004293/// parseDirectiveAbort
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004294/// ::= .abort [... message ...]
Jim Grosbach4b905842013-09-20 23:08:21 +00004295bool AsmParser::parseDirectiveAbort() {
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004296 // FIXME: Use loc from directive.
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004297 SMLoc Loc = getLexer().getLoc();
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004298
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004299 StringRef Str = parseStringToEndOfStatement();
Nirav Davea645433c2016-07-18 15:24:03 +00004300 if (parseToken(AsmToken::EndOfStatement,
4301 "unexpected token in '.abort' directive"))
4302 return true;
Kevin Enderby56523ce2009-07-13 23:15:14 +00004303
Daniel Dunbareb6bb322009-07-27 23:20:52 +00004304 if (Str.empty())
4305 Error(Loc, ".abort detected. Assembly stopping.");
4306 else
4307 Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
Daniel Dunbar40a564f2010-07-18 20:15:59 +00004308 // FIXME: Actually abort assembly here.
Kevin Enderby56523ce2009-07-13 23:15:14 +00004309
4310 return false;
4311}
Kevin Enderbycbe475d2009-07-14 21:35:03 +00004312
Jim Grosbach4b905842013-09-20 23:08:21 +00004313/// parseDirectiveInclude
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004314/// ::= .include "filename"
Jim Grosbach4b905842013-09-20 23:08:21 +00004315bool AsmParser::parseDirectiveInclude() {
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004316 // Allow the strings to have escaped octal character sequence.
4317 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00004318 SMLoc IncludeLoc = getTok().getLoc();
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004319
Nirav Davea645433c2016-07-18 15:24:03 +00004320 if (check(getTok().isNot(AsmToken::String),
4321 "expected string in '.include' directive") ||
4322 parseEscapedString(Filename) ||
4323 check(getTok().isNot(AsmToken::EndOfStatement),
4324 "unexpected token in '.include' directive") ||
4325 // Attempt to switch the lexer to the included file before consuming the
4326 // end of statement to avoid losing it when we switch.
4327 check(enterIncludeFile(Filename), IncludeLoc,
4328 "Could not find include file '" + Filename + "'"))
Chris Lattner693fbb82009-07-16 06:14:39 +00004329 return true;
Kevin Enderbyd1ea5392009-07-14 23:21:55 +00004330
4331 return false;
4332}
Kevin Enderby09ea5702009-07-15 15:30:11 +00004333
Jim Grosbach4b905842013-09-20 23:08:21 +00004334/// parseDirectiveIncbin
Kevin Enderby109f25c2011-12-14 21:47:48 +00004335/// ::= .incbin "filename"
Jim Grosbach4b905842013-09-20 23:08:21 +00004336bool AsmParser::parseDirectiveIncbin() {
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004337 // Allow the strings to have escaped octal character sequence.
4338 std::string Filename;
Nirav Davea645433c2016-07-18 15:24:03 +00004339 SMLoc IncbinLoc = getTok().getLoc();
4340 if (check(getTok().isNot(AsmToken::String),
4341 "expected string in '.incbin' directive") ||
4342 parseEscapedString(Filename) ||
4343 parseToken(AsmToken::EndOfStatement,
Nirav Dave1ab71992016-07-18 19:35:21 +00004344 "unexpected token in '.incbin' directive"))
Yunzhong Gao8c0f5062013-09-05 19:14:26 +00004345 return true;
Nirav Dave1ab71992016-07-18 19:35:21 +00004346
4347 // Attempt to process the included file.
4348 if (processIncbinFile(Filename))
4349 return Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
Kevin Enderby109f25c2011-12-14 21:47:48 +00004350 return false;
4351}
4352
Jim Grosbach4b905842013-09-20 23:08:21 +00004353/// parseDirectiveIf
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004354/// ::= .if{,eq,ge,gt,le,lt,ne} expression
4355bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004356 TheCondStack.push_back(TheCondState);
4357 TheCondState.TheCond = AsmCond::IfCond;
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004358 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004359 eatToEndOfStatement();
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004360 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004361 int64_t ExprValue;
Nirav Davea645433c2016-07-18 15:24:03 +00004362 if (parseAbsoluteExpression(ExprValue) ||
4363 parseToken(AsmToken::EndOfStatement,
4364 "unexpected token in '.if' directive"))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004365 return true;
4366
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004367 switch (DirKind) {
4368 default:
4369 llvm_unreachable("unsupported directive");
4370 case DK_IF:
4371 case DK_IFNE:
4372 break;
4373 case DK_IFEQ:
4374 ExprValue = ExprValue == 0;
4375 break;
4376 case DK_IFGE:
4377 ExprValue = ExprValue >= 0;
4378 break;
4379 case DK_IFGT:
4380 ExprValue = ExprValue > 0;
4381 break;
4382 case DK_IFLE:
4383 ExprValue = ExprValue <= 0;
4384 break;
4385 case DK_IFLT:
4386 ExprValue = ExprValue < 0;
4387 break;
4388 }
4389
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004390 TheCondState.CondMet = ExprValue;
4391 TheCondState.Ignore = !TheCondState.CondMet;
4392 }
4393
4394 return false;
4395}
4396
Jim Grosbach4b905842013-09-20 23:08:21 +00004397/// parseDirectiveIfb
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004398/// ::= .ifb string
Jim Grosbach4b905842013-09-20 23:08:21 +00004399bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004400 TheCondStack.push_back(TheCondState);
4401 TheCondState.TheCond = AsmCond::IfCond;
4402
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004403 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004404 eatToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004405 } else {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004406 StringRef Str = parseStringToEndOfStatement();
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004407
Nirav Davea645433c2016-07-18 15:24:03 +00004408 if (parseToken(AsmToken::EndOfStatement,
4409 "unexpected token in '.ifb' directive"))
4410 return true;
Benjamin Kramer62c18b02012-05-12 11:18:42 +00004411
4412 TheCondState.CondMet = ExpectBlank == Str.empty();
4413 TheCondState.Ignore = !TheCondState.CondMet;
4414 }
4415
4416 return false;
4417}
4418
Jim Grosbach4b905842013-09-20 23:08:21 +00004419/// parseDirectiveIfc
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004420/// ::= .ifc string1, string2
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00004421/// ::= .ifnc string1, string2
Jim Grosbach4b905842013-09-20 23:08:21 +00004422bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004423 TheCondStack.push_back(TheCondState);
4424 TheCondState.TheCond = AsmCond::IfCond;
4425
Benjamin Kramerc7eda3e2012-05-12 16:52:21 +00004426 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004427 eatToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004428 } else {
Jim Grosbach4b905842013-09-20 23:08:21 +00004429 StringRef Str1 = parseStringToComma();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004430
Nirav Davea645433c2016-07-18 15:24:03 +00004431 if (parseToken(AsmToken::Comma, "unexpected token in '.ifc' directive"))
4432 return true;
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004433
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004434 StringRef Str2 = parseStringToEndOfStatement();
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004435
Nirav Davea645433c2016-07-18 15:24:03 +00004436 if (parseToken(AsmToken::EndOfStatement,
4437 "unexpected token in '.ifc' directive"))
4438 return true;
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004439
Saleem Abdulrasool5db52982014-02-23 15:53:36 +00004440 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004441 TheCondState.Ignore = !TheCondState.CondMet;
4442 }
4443
4444 return false;
4445}
4446
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004447/// parseDirectiveIfeqs
4448/// ::= .ifeqs string1, string2
Sid Manning51c35602015-03-18 14:20:54 +00004449bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual) {
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004450 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00004451 if (ExpectEqual)
4452 TokError("expected string parameter for '.ifeqs' directive");
4453 else
4454 TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004455 eatToEndOfStatement();
4456 return true;
4457 }
4458
4459 StringRef String1 = getTok().getStringContents();
4460 Lex();
4461
4462 if (Lexer.isNot(AsmToken::Comma)) {
Sid Manning51c35602015-03-18 14:20:54 +00004463 if (ExpectEqual)
4464 TokError("expected comma after first string for '.ifeqs' directive");
4465 else
4466 TokError("expected comma after first string for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004467 eatToEndOfStatement();
4468 return true;
4469 }
4470
4471 Lex();
4472
4473 if (Lexer.isNot(AsmToken::String)) {
Sid Manning51c35602015-03-18 14:20:54 +00004474 if (ExpectEqual)
4475 TokError("expected string parameter for '.ifeqs' directive");
4476 else
4477 TokError("expected string parameter for '.ifnes' directive");
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004478 eatToEndOfStatement();
4479 return true;
4480 }
4481
4482 StringRef String2 = getTok().getStringContents();
4483 Lex();
4484
4485 TheCondStack.push_back(TheCondState);
4486 TheCondState.TheCond = AsmCond::IfCond;
Sid Manning51c35602015-03-18 14:20:54 +00004487 TheCondState.CondMet = ExpectEqual == (String1 == String2);
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004488 TheCondState.Ignore = !TheCondState.CondMet;
4489
4490 return false;
4491}
4492
Jim Grosbach4b905842013-09-20 23:08:21 +00004493/// parseDirectiveIfdef
Benjamin Kramere297b9f2012-05-12 11:18:51 +00004494/// ::= .ifdef symbol
Jim Grosbach4b905842013-09-20 23:08:21 +00004495bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004496 StringRef Name;
4497 TheCondStack.push_back(TheCondState);
4498 TheCondState.TheCond = AsmCond::IfCond;
4499
4500 if (TheCondState.Ignore) {
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004501 eatToEndOfStatement();
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004502 } else {
Nirav Davea645433c2016-07-18 15:24:03 +00004503 if (check(parseIdentifier(Name), "expected identifier after '.ifdef'") ||
4504 parseToken(AsmToken::EndOfStatement, "unexpected token in '.ifdef'"))
4505 return true;
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004506
Jim Grosbach6f482002015-05-18 18:43:14 +00004507 MCSymbol *Sym = getContext().lookupSymbol(Name);
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004508
4509 if (expect_defined)
Craig Topper353eda42014-04-24 06:44:33 +00004510 TheCondState.CondMet = (Sym && !Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004511 else
Craig Topper353eda42014-04-24 06:44:33 +00004512 TheCondState.CondMet = (!Sym || Sym->isUndefined());
Benjamin Kramer7b7caf52011-02-08 22:29:56 +00004513 TheCondState.Ignore = !TheCondState.CondMet;
4514 }
4515
4516 return false;
4517}
4518
Jim Grosbach4b905842013-09-20 23:08:21 +00004519/// parseDirectiveElseIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004520/// ::= .elseif expression
Jim Grosbach4b905842013-09-20 23:08:21 +00004521bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004522 if (TheCondState.TheCond != AsmCond::IfCond &&
4523 TheCondState.TheCond != AsmCond::ElseIfCond)
Craig Topper2172ad62013-04-22 04:24:02 +00004524 Error(DirectiveLoc, "Encountered a .elseif that doesn't follow a .if or "
4525 " an .elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004526 TheCondState.TheCond = AsmCond::ElseIfCond;
4527
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004528 bool LastIgnoreState = false;
4529 if (!TheCondStack.empty())
Craig Topper2172ad62013-04-22 04:24:02 +00004530 LastIgnoreState = TheCondStack.back().Ignore;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004531 if (LastIgnoreState || TheCondState.CondMet) {
4532 TheCondState.Ignore = true;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004533 eatToEndOfStatement();
Craig Topperf15655b2013-04-22 04:22:40 +00004534 } else {
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004535 int64_t ExprValue;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004536 if (parseAbsoluteExpression(ExprValue))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004537 return true;
4538
Daniel Dunbardd41dcf2010-07-12 18:03:11 +00004539 if (getLexer().isNot(AsmToken::EndOfStatement))
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004540 return TokError("unexpected token in '.elseif' directive");
Michael J. Spencer530ce852010-10-09 11:00:50 +00004541
Sean Callanan686ed8d2010-01-19 20:22:31 +00004542 Lex();
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004543 TheCondState.CondMet = ExprValue;
4544 TheCondState.Ignore = !TheCondState.CondMet;
4545 }
4546
4547 return false;
4548}
4549
Jim Grosbach4b905842013-09-20 23:08:21 +00004550/// parseDirectiveElse
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004551/// ::= .else
Jim Grosbach4b905842013-09-20 23:08:21 +00004552bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00004553 if (parseToken(AsmToken::EndOfStatement,
4554 "unexpected token in '.else' directive"))
4555 return true;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004556
4557 if (TheCondState.TheCond != AsmCond::IfCond &&
4558 TheCondState.TheCond != AsmCond::ElseIfCond)
Craig Topper2172ad62013-04-22 04:24:02 +00004559 Error(DirectiveLoc, "Encountered a .else that doesn't follow a .if or an "
4560 ".elseif");
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004561 TheCondState.TheCond = AsmCond::ElseCond;
4562 bool LastIgnoreState = false;
4563 if (!TheCondStack.empty())
4564 LastIgnoreState = TheCondStack.back().Ignore;
4565 if (LastIgnoreState || TheCondState.CondMet)
4566 TheCondState.Ignore = true;
4567 else
4568 TheCondState.Ignore = false;
4569
4570 return false;
4571}
4572
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004573/// parseDirectiveEnd
4574/// ::= .end
4575bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00004576 if (parseToken(AsmToken::EndOfStatement,
4577 "unexpected token in '.end' directive"))
4578 return true;
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004579
4580 while (Lexer.isNot(AsmToken::Eof))
4581 Lex();
4582
4583 return false;
4584}
4585
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004586/// parseDirectiveError
4587/// ::= .err
4588/// ::= .error [string]
4589bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
4590 if (!TheCondStack.empty()) {
4591 if (TheCondStack.back().Ignore) {
4592 eatToEndOfStatement();
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004593 return false;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004594 }
4595 }
4596
4597 if (!WithMessage)
4598 return Error(L, ".err encountered");
4599
4600 StringRef Message = ".error directive invoked in source file";
4601 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4602 if (Lexer.isNot(AsmToken::String)) {
4603 TokError(".error argument must be a string");
4604 eatToEndOfStatement();
4605 return true;
4606 }
4607
4608 Message = getTok().getStringContents();
4609 Lex();
4610 }
4611
4612 Error(L, Message);
4613 return true;
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004614}
4615
Nico Weber404012b2014-07-24 16:26:06 +00004616/// parseDirectiveWarning
4617/// ::= .warning [string]
4618bool AsmParser::parseDirectiveWarning(SMLoc L) {
4619 if (!TheCondStack.empty()) {
4620 if (TheCondStack.back().Ignore) {
4621 eatToEndOfStatement();
4622 return false;
4623 }
4624 }
4625
4626 StringRef Message = ".warning directive invoked in source file";
4627 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4628 if (Lexer.isNot(AsmToken::String)) {
4629 TokError(".warning argument must be a string");
4630 eatToEndOfStatement();
4631 return true;
4632 }
4633
4634 Message = getTok().getStringContents();
4635 Lex();
4636 }
4637
4638 Warning(L, Message);
4639 return false;
4640}
4641
Jim Grosbach4b905842013-09-20 23:08:21 +00004642/// parseDirectiveEndIf
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004643/// ::= .endif
Jim Grosbach4b905842013-09-20 23:08:21 +00004644bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
Nirav Davea645433c2016-07-18 15:24:03 +00004645 if (parseToken(AsmToken::EndOfStatement,
4646 "unexpected token in '.endif' directive"))
4647 return true;
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004648
Jim Grosbach4b905842013-09-20 23:08:21 +00004649 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
Kevin Enderbyd9f95292009-08-07 22:46:00 +00004650 Error(DirectiveLoc, "Encountered a .endif that doesn't follow a .if or "
4651 ".else");
4652 if (!TheCondStack.empty()) {
4653 TheCondState = TheCondStack.back();
4654 TheCondStack.pop_back();
4655 }
4656
4657 return false;
4658}
Daniel Dunbara4b069c2009-08-11 04:24:50 +00004659
Eli Bendersky17233942013-01-15 22:59:42 +00004660void AsmParser::initializeDirectiveKindMap() {
4661 DirectiveKindMap[".set"] = DK_SET;
4662 DirectiveKindMap[".equ"] = DK_EQU;
4663 DirectiveKindMap[".equiv"] = DK_EQUIV;
4664 DirectiveKindMap[".ascii"] = DK_ASCII;
4665 DirectiveKindMap[".asciz"] = DK_ASCIZ;
4666 DirectiveKindMap[".string"] = DK_STRING;
4667 DirectiveKindMap[".byte"] = DK_BYTE;
4668 DirectiveKindMap[".short"] = DK_SHORT;
4669 DirectiveKindMap[".value"] = DK_VALUE;
4670 DirectiveKindMap[".2byte"] = DK_2BYTE;
4671 DirectiveKindMap[".long"] = DK_LONG;
4672 DirectiveKindMap[".int"] = DK_INT;
4673 DirectiveKindMap[".4byte"] = DK_4BYTE;
4674 DirectiveKindMap[".quad"] = DK_QUAD;
4675 DirectiveKindMap[".8byte"] = DK_8BYTE;
David Woodhoused6de0d92014-02-01 16:20:59 +00004676 DirectiveKindMap[".octa"] = DK_OCTA;
Eli Bendersky17233942013-01-15 22:59:42 +00004677 DirectiveKindMap[".single"] = DK_SINGLE;
4678 DirectiveKindMap[".float"] = DK_FLOAT;
4679 DirectiveKindMap[".double"] = DK_DOUBLE;
4680 DirectiveKindMap[".align"] = DK_ALIGN;
4681 DirectiveKindMap[".align32"] = DK_ALIGN32;
4682 DirectiveKindMap[".balign"] = DK_BALIGN;
4683 DirectiveKindMap[".balignw"] = DK_BALIGNW;
4684 DirectiveKindMap[".balignl"] = DK_BALIGNL;
4685 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
4686 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
4687 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
4688 DirectiveKindMap[".org"] = DK_ORG;
4689 DirectiveKindMap[".fill"] = DK_FILL;
4690 DirectiveKindMap[".zero"] = DK_ZERO;
4691 DirectiveKindMap[".extern"] = DK_EXTERN;
4692 DirectiveKindMap[".globl"] = DK_GLOBL;
4693 DirectiveKindMap[".global"] = DK_GLOBAL;
Eli Bendersky17233942013-01-15 22:59:42 +00004694 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
4695 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
4696 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
4697 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
4698 DirectiveKindMap[".reference"] = DK_REFERENCE;
4699 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
4700 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
4701 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
4702 DirectiveKindMap[".comm"] = DK_COMM;
4703 DirectiveKindMap[".common"] = DK_COMMON;
4704 DirectiveKindMap[".lcomm"] = DK_LCOMM;
4705 DirectiveKindMap[".abort"] = DK_ABORT;
4706 DirectiveKindMap[".include"] = DK_INCLUDE;
4707 DirectiveKindMap[".incbin"] = DK_INCBIN;
4708 DirectiveKindMap[".code16"] = DK_CODE16;
4709 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
4710 DirectiveKindMap[".rept"] = DK_REPT;
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00004711 DirectiveKindMap[".rep"] = DK_REPT;
Eli Bendersky17233942013-01-15 22:59:42 +00004712 DirectiveKindMap[".irp"] = DK_IRP;
4713 DirectiveKindMap[".irpc"] = DK_IRPC;
4714 DirectiveKindMap[".endr"] = DK_ENDR;
4715 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
4716 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
4717 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
4718 DirectiveKindMap[".if"] = DK_IF;
Saleem Abdulrasool763e2cb2014-06-18 20:57:28 +00004719 DirectiveKindMap[".ifeq"] = DK_IFEQ;
4720 DirectiveKindMap[".ifge"] = DK_IFGE;
4721 DirectiveKindMap[".ifgt"] = DK_IFGT;
4722 DirectiveKindMap[".ifle"] = DK_IFLE;
4723 DirectiveKindMap[".iflt"] = DK_IFLT;
Saleem Abdulrasool5852d6b2014-02-23 15:53:41 +00004724 DirectiveKindMap[".ifne"] = DK_IFNE;
Eli Bendersky17233942013-01-15 22:59:42 +00004725 DirectiveKindMap[".ifb"] = DK_IFB;
4726 DirectiveKindMap[".ifnb"] = DK_IFNB;
4727 DirectiveKindMap[".ifc"] = DK_IFC;
Saleem Abdulrasool00f53c12014-02-23 23:02:18 +00004728 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
Eli Bendersky17233942013-01-15 22:59:42 +00004729 DirectiveKindMap[".ifnc"] = DK_IFNC;
Sid Manning51c35602015-03-18 14:20:54 +00004730 DirectiveKindMap[".ifnes"] = DK_IFNES;
Eli Bendersky17233942013-01-15 22:59:42 +00004731 DirectiveKindMap[".ifdef"] = DK_IFDEF;
4732 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
4733 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
4734 DirectiveKindMap[".elseif"] = DK_ELSEIF;
4735 DirectiveKindMap[".else"] = DK_ELSE;
Saleem Abdulrasool88186c42013-12-18 02:53:03 +00004736 DirectiveKindMap[".end"] = DK_END;
Eli Bendersky17233942013-01-15 22:59:42 +00004737 DirectiveKindMap[".endif"] = DK_ENDIF;
4738 DirectiveKindMap[".skip"] = DK_SKIP;
4739 DirectiveKindMap[".space"] = DK_SPACE;
4740 DirectiveKindMap[".file"] = DK_FILE;
4741 DirectiveKindMap[".line"] = DK_LINE;
4742 DirectiveKindMap[".loc"] = DK_LOC;
4743 DirectiveKindMap[".stabs"] = DK_STABS;
Reid Kleckner2214ed82016-01-29 00:49:42 +00004744 DirectiveKindMap[".cv_file"] = DK_CV_FILE;
4745 DirectiveKindMap[".cv_loc"] = DK_CV_LOC;
4746 DirectiveKindMap[".cv_linetable"] = DK_CV_LINETABLE;
David Majnemer6fcbd7e2016-01-29 19:24:12 +00004747 DirectiveKindMap[".cv_inline_linetable"] = DK_CV_INLINE_LINETABLE;
David Majnemer408b5e62016-02-05 01:55:49 +00004748 DirectiveKindMap[".cv_def_range"] = DK_CV_DEF_RANGE;
Reid Kleckner2214ed82016-01-29 00:49:42 +00004749 DirectiveKindMap[".cv_stringtable"] = DK_CV_STRINGTABLE;
4750 DirectiveKindMap[".cv_filechecksums"] = DK_CV_FILECHECKSUMS;
Eli Bendersky17233942013-01-15 22:59:42 +00004751 DirectiveKindMap[".sleb128"] = DK_SLEB128;
4752 DirectiveKindMap[".uleb128"] = DK_ULEB128;
4753 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
4754 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
4755 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
4756 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
4757 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
4758 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
4759 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
4760 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
4761 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
4762 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
4763 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
4764 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
4765 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
4766 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
4767 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
4768 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
4769 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
4770 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
4771 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
Venkatraman Govindaraju3816d432013-09-26 14:49:40 +00004772 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
Eli Bendersky17233942013-01-15 22:59:42 +00004773 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
4774 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
4775 DirectiveKindMap[".macro"] = DK_MACRO;
Nico Weber155dccd12014-07-24 17:08:39 +00004776 DirectiveKindMap[".exitm"] = DK_EXITM;
Eli Bendersky17233942013-01-15 22:59:42 +00004777 DirectiveKindMap[".endm"] = DK_ENDM;
4778 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
4779 DirectiveKindMap[".purgem"] = DK_PURGEM;
Saleem Abdulrasoolb2ae2c02014-02-23 15:53:30 +00004780 DirectiveKindMap[".err"] = DK_ERR;
Saleem Abdulrasool7ecc5492014-02-23 23:02:23 +00004781 DirectiveKindMap[".error"] = DK_ERROR;
Nico Weber404012b2014-07-24 16:26:06 +00004782 DirectiveKindMap[".warning"] = DK_WARNING;
Daniel Sanders9f6ad492015-11-12 13:33:00 +00004783 DirectiveKindMap[".reloc"] = DK_RELOC;
Petr Hosek731bb9c2016-08-23 21:34:53 +00004784 DirectiveKindMap[".dc"] = DK_DC;
4785 DirectiveKindMap[".dc.a"] = DK_DC_A;
4786 DirectiveKindMap[".dc.b"] = DK_DC_B;
4787 DirectiveKindMap[".dc.d"] = DK_DC_D;
4788 DirectiveKindMap[".dc.l"] = DK_DC_L;
4789 DirectiveKindMap[".dc.s"] = DK_DC_S;
4790 DirectiveKindMap[".dc.w"] = DK_DC_W;
4791 DirectiveKindMap[".dc.x"] = DK_DC_X;
Eli Benderskyec9e3cf2013-01-10 22:44:57 +00004792}
4793
Jim Grosbach4b905842013-09-20 23:08:21 +00004794MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004795 AsmToken EndToken, StartToken = getTok();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004796
Rafael Espindola34b9c512012-06-03 23:57:14 +00004797 unsigned NestLevel = 0;
Eugene Zelenko33d7b762016-08-23 17:14:32 +00004798 while (true) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004799 // Check whether we have reached the end of the file.
Rafael Espindola34b9c512012-06-03 23:57:14 +00004800 if (getLexer().is(AsmToken::Eof)) {
4801 Error(DirectiveLoc, "no matching '.endr' in definition");
Craig Topper353eda42014-04-24 06:44:33 +00004802 return nullptr;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004803 }
4804
Rafael Espindola34b9c512012-06-03 23:57:14 +00004805 if (Lexer.is(AsmToken::Identifier) &&
Nikolay Haustov95b4fcd2016-03-01 08:18:28 +00004806 (getTok().getIdentifier() == ".rept" ||
4807 getTok().getIdentifier() == ".irp" ||
4808 getTok().getIdentifier() == ".irpc")) {
Rafael Espindola34b9c512012-06-03 23:57:14 +00004809 ++NestLevel;
4810 }
4811
4812 // Otherwise, check whether we have reached the .endr.
Jim Grosbach4b905842013-09-20 23:08:21 +00004813 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
Rafael Espindola34b9c512012-06-03 23:57:14 +00004814 if (NestLevel == 0) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004815 EndToken = getTok();
4816 Lex();
Rafael Espindola34b9c512012-06-03 23:57:14 +00004817 if (Lexer.isNot(AsmToken::EndOfStatement)) {
4818 TokError("unexpected token in '.endr' directive");
Craig Topper353eda42014-04-24 06:44:33 +00004819 return nullptr;
Rafael Espindola34b9c512012-06-03 23:57:14 +00004820 }
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004821 break;
4822 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00004823 --NestLevel;
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004824 }
4825
Rafael Espindola34b9c512012-06-03 23:57:14 +00004826 // Otherwise, scan till the end of the statement.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004827 eatToEndOfStatement();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004828 }
4829
4830 const char *BodyStart = StartToken.getLoc().getPointer();
4831 const char *BodyEnd = EndToken.getLoc().getPointer();
4832 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
4833
Rafael Espindola34b9c512012-06-03 23:57:14 +00004834 // We Are Anonymous.
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00004835 MacroLikeBodies.emplace_back(StringRef(), Body, MCAsmMacroParameters());
Benjamin Kramer1df3a1f2013-08-04 09:06:29 +00004836 return &MacroLikeBodies.back();
Rafael Espindola34b9c512012-06-03 23:57:14 +00004837}
4838
Jim Grosbach4b905842013-09-20 23:08:21 +00004839void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
Rafael Espindola34b9c512012-06-03 23:57:14 +00004840 raw_svector_ostream &OS) {
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004841 OS << ".endr\n";
4842
Rafael Espindola3560ff22014-08-27 20:03:13 +00004843 std::unique_ptr<MemoryBuffer> Instantiation =
4844 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004845
Rafael Espindola34b9c512012-06-03 23:57:14 +00004846 // Create the macro instantiation object and add to the current macro
4847 // instantiation stack.
Rafael Espindola9eef18c2014-08-27 19:49:03 +00004848 MacroInstantiation *MI = new MacroInstantiation(
4849 DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
Rafael Espindola34b9c512012-06-03 23:57:14 +00004850 ActiveMacros.push_back(MI);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004851
Rafael Espindola34b9c512012-06-03 23:57:14 +00004852 // Jump to the macro instantiation and prime the lexer.
David Blaikie1961f142014-08-21 20:44:56 +00004853 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
Rafael Espindola8026bd02014-07-06 14:17:29 +00004854 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
Rafael Espindola34b9c512012-06-03 23:57:14 +00004855 Lex();
4856}
4857
Saleem Abdulrasoold743d0a2013-12-28 05:54:33 +00004858/// parseDirectiveRept
4859/// ::= .rep | .rept count
4860bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00004861 const MCExpr *CountExpr;
4862 SMLoc CountLoc = getTok().getLoc();
4863 if (parseExpression(CountExpr))
4864 return true;
4865
Rafael Espindola34b9c512012-06-03 23:57:14 +00004866 int64_t Count;
Jim Grosbach13760bd2015-05-30 01:25:56 +00004867 if (!CountExpr->evaluateAsAbsolute(Count)) {
Saleem Abdulrasool51cff712013-12-28 06:39:29 +00004868 eatToEndOfStatement();
4869 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
4870 }
Rafael Espindola34b9c512012-06-03 23:57:14 +00004871
Nirav Davea645433c2016-07-18 15:24:03 +00004872 if (check(Count < 0, CountLoc, "Count is negative") ||
4873 parseToken(AsmToken::EndOfStatement,
4874 "unexpected token in '" + Dir + "' directive"))
4875 return true;
Rafael Espindola34b9c512012-06-03 23:57:14 +00004876
4877 // Lex the rept definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00004878 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola34b9c512012-06-03 23:57:14 +00004879 if (!M)
4880 return true;
4881
4882 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4883 // to hold the macro body with substitutions.
4884 SmallString<256> Buf;
Rafael Espindola34b9c512012-06-03 23:57:14 +00004885 raw_svector_ostream OS(Buf);
4886 while (Count--) {
Toma Tabacu217116e2015-04-27 10:50:29 +00004887 // Note that the AtPseudoVariable is disabled for instantiations of .rep(t).
4888 if (expandMacro(OS, M->Body, None, None, false, getTok().getLoc()))
Rafael Espindola34b9c512012-06-03 23:57:14 +00004889 return true;
4890 }
Jim Grosbach4b905842013-09-20 23:08:21 +00004891 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004892
4893 return false;
4894}
4895
Jim Grosbach4b905842013-09-20 23:08:21 +00004896/// parseDirectiveIrp
Rafael Espindola768b41c2012-06-15 14:02:34 +00004897/// ::= .irp symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00004898bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00004899 MCAsmMacroParameter Parameter;
Eli Bendersky38274122013-01-14 23:22:36 +00004900 MCAsmMacroArguments A;
Nirav Davea645433c2016-07-18 15:24:03 +00004901 if (check(parseIdentifier(Parameter.Name),
4902 "expected identifier in '.irp' directive") ||
4903 parseToken(AsmToken::Comma, "expected comma in '.irp' directive") ||
4904 parseMacroArguments(nullptr, A) ||
4905 parseToken(AsmToken::EndOfStatement, "expected End of Statement"))
Rafael Espindola768b41c2012-06-15 14:02:34 +00004906 return true;
4907
Rafael Espindola768b41c2012-06-15 14:02:34 +00004908 // Lex the irp definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00004909 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindola768b41c2012-06-15 14:02:34 +00004910 if (!M)
4911 return true;
4912
4913 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4914 // to hold the macro body with substitutions.
4915 SmallString<256> Buf;
4916 raw_svector_ostream OS(Buf);
4917
Craig Topper84008482015-10-10 05:38:14 +00004918 for (const MCAsmMacroArgument &Arg : A) {
Toma Tabacu217116e2015-04-27 10:50:29 +00004919 // Note that the AtPseudoVariable is enabled for instantiations of .irp.
4920 // This is undocumented, but GAS seems to support it.
Craig Topper84008482015-10-10 05:38:14 +00004921 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindola768b41c2012-06-15 14:02:34 +00004922 return true;
4923 }
4924
Jim Grosbach4b905842013-09-20 23:08:21 +00004925 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindola768b41c2012-06-15 14:02:34 +00004926
4927 return false;
4928}
4929
Jim Grosbach4b905842013-09-20 23:08:21 +00004930/// parseDirectiveIrpc
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004931/// ::= .irpc symbol,values
Jim Grosbach4b905842013-09-20 23:08:21 +00004932bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
Eli Bendersky38274122013-01-14 23:22:36 +00004933 MCAsmMacroParameter Parameter;
Eli Bendersky38274122013-01-14 23:22:36 +00004934 MCAsmMacroArguments A;
Nirav Davea645433c2016-07-18 15:24:03 +00004935
4936 if (check(parseIdentifier(Parameter.Name),
4937 "expected identifier in '.irpc' directive") ||
4938 parseToken(AsmToken::Comma, "expected comma in '.irpc' directive") ||
4939 parseMacroArguments(nullptr, A))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004940 return true;
4941
4942 if (A.size() != 1 || A.front().size() != 1)
4943 return TokError("unexpected token in '.irpc' directive");
4944
4945 // Eat the end of statement.
Nirav Davea645433c2016-07-18 15:24:03 +00004946 if (parseToken(AsmToken::EndOfStatement, "expected end of statement"))
4947 return true;
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004948
4949 // Lex the irpc definition.
Jim Grosbach4b905842013-09-20 23:08:21 +00004950 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004951 if (!M)
4952 return true;
4953
4954 // Macro instantiation is lexical, unfortunately. We construct a new buffer
4955 // to hold the macro body with substitutions.
4956 SmallString<256> Buf;
4957 raw_svector_ostream OS(Buf);
4958
4959 StringRef Values = A.front().front().getString();
Benjamin Kramerd31aaf12014-02-09 17:13:11 +00004960 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
Eli Benderskya7b905e2013-01-14 19:00:26 +00004961 MCAsmMacroArgument Arg;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +00004962 Arg.emplace_back(AsmToken::Identifier, Values.slice(I, I + 1));
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004963
Toma Tabacu217116e2015-04-27 10:50:29 +00004964 // Note that the AtPseudoVariable is enabled for instantiations of .irpc.
4965 // This is undocumented, but GAS seems to support it.
4966 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004967 return true;
4968 }
4969
Jim Grosbach4b905842013-09-20 23:08:21 +00004970 instantiateMacroLikeBody(M, DirectiveLoc, OS);
Rafael Espindolaf70bea92012-06-16 18:03:25 +00004971
4972 return false;
4973}
4974
Jim Grosbach4b905842013-09-20 23:08:21 +00004975bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
Rafael Espindola34b9c512012-06-03 23:57:14 +00004976 if (ActiveMacros.empty())
Preston Gurdeb3ebf12012-09-19 20:23:43 +00004977 return TokError("unmatched '.endr' directive");
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004978
4979 // The only .repl that should get here are the ones created by
Jim Grosbach4b905842013-09-20 23:08:21 +00004980 // instantiateMacroLikeBody.
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004981 assert(getLexer().is(AsmToken::EndOfStatement));
4982
Jim Grosbach4b905842013-09-20 23:08:21 +00004983 handleMacroExit();
Rafael Espindola47b7dac2012-05-12 16:31:10 +00004984 return false;
4985}
Rafael Espindola12d73d12010-09-11 16:45:15 +00004986
Jim Grosbach4b905842013-09-20 23:08:21 +00004987bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
Benjamin Kramer1a136112013-02-15 20:37:21 +00004988 size_t Len) {
Eli Friedman0f4871d2012-10-22 23:58:19 +00004989 const MCExpr *Value;
4990 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00004991 if (parseExpression(Value))
Eli Friedman0f4871d2012-10-22 23:58:19 +00004992 return true;
4993 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
4994 if (!MCE)
4995 return Error(ExprLoc, "unexpected expression in _emit");
4996 uint64_t IntValue = MCE->getValue();
Craig Topper55b1f292015-10-10 20:17:07 +00004997 if (!isUInt<8>(IntValue) && !isInt<8>(IntValue))
Eli Friedman0f4871d2012-10-22 23:58:19 +00004998 return Error(ExprLoc, "literal value out of range for directive");
4999
Craig Topper7d5b2312015-10-10 05:25:02 +00005000 Info.AsmRewrites->emplace_back(AOK_Emit, IDLoc, Len);
Chad Rosierc7f552c2013-02-12 21:33:51 +00005001 return false;
5002}
5003
Jim Grosbach4b905842013-09-20 23:08:21 +00005004bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
Chad Rosierc7f552c2013-02-12 21:33:51 +00005005 const MCExpr *Value;
5006 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00005007 if (parseExpression(Value))
Chad Rosierc7f552c2013-02-12 21:33:51 +00005008 return true;
5009 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5010 if (!MCE)
5011 return Error(ExprLoc, "unexpected expression in align");
5012 uint64_t IntValue = MCE->getValue();
5013 if (!isPowerOf2_64(IntValue))
5014 return Error(ExprLoc, "literal value not a power of two greater then zero");
5015
Craig Topper7d5b2312015-10-10 05:25:02 +00005016 Info.AsmRewrites->emplace_back(AOK_Align, IDLoc, 5, Log2_64(IntValue));
Eli Friedman0f4871d2012-10-22 23:58:19 +00005017 return false;
5018}
5019
Chad Rosierf43fcf52013-02-13 21:27:17 +00005020// We are comparing pointers, but the pointers are relative to a single string.
5021// Thus, this should always be deterministic.
Benjamin Kramer8817cca2013-09-22 14:09:50 +00005022static int rewritesSort(const AsmRewrite *AsmRewriteA,
5023 const AsmRewrite *AsmRewriteB) {
Chad Rosiereb5c1682013-02-13 18:38:58 +00005024 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
5025 return -1;
5026 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
5027 return 1;
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005028
Chad Rosierfce4fab2013-04-08 17:43:47 +00005029 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
5030 // rewrite to the same location. Make sure the SizeDirective rewrite is
5031 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
5032 // ensures the sort algorithm is stable.
Jim Grosbach4b905842013-09-20 23:08:21 +00005033 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
5034 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005035 return -1;
Chad Rosierfce4fab2013-04-08 17:43:47 +00005036
Jim Grosbach4b905842013-09-20 23:08:21 +00005037 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
5038 AsmRewritePrecedence[AsmRewriteB->Kind])
Chad Rosier42d4e2e2013-02-15 22:54:16 +00005039 return 1;
Jim Grosbach4b905842013-09-20 23:08:21 +00005040 llvm_unreachable("Unstable rewrite sort.");
Chad Rosierb2144ce2013-02-13 01:03:13 +00005041}
5042
Jim Grosbach4b905842013-09-20 23:08:21 +00005043bool AsmParser::parseMSInlineAsm(
5044 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
5045 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool> > &OpDecls,
5046 SmallVectorImpl<std::string> &Constraints,
5047 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
5048 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
Chad Rosier37e755c2012-10-23 17:43:43 +00005049 SmallVector<void *, 4> InputDecls;
5050 SmallVector<void *, 4> OutputDecls;
Chad Rosiera4bc9432013-01-10 22:10:27 +00005051 SmallVector<bool, 4> InputDeclsAddressOf;
5052 SmallVector<bool, 4> OutputDeclsAddressOf;
Chad Rosier8bce6642012-10-18 15:49:34 +00005053 SmallVector<std::string, 4> InputConstraints;
5054 SmallVector<std::string, 4> OutputConstraints;
Benjamin Kramer1a136112013-02-15 20:37:21 +00005055 SmallVector<unsigned, 4> ClobberRegs;
Chad Rosier8bce6642012-10-18 15:49:34 +00005056
Benjamin Kramer1a136112013-02-15 20:37:21 +00005057 SmallVector<AsmRewrite, 4> AsmStrRewrites;
Chad Rosier8bce6642012-10-18 15:49:34 +00005058
5059 // Prime the lexer.
5060 Lex();
5061
5062 // While we have input, parse each statement.
5063 unsigned InputIdx = 0;
5064 unsigned OutputIdx = 0;
5065 while (getLexer().isNot(AsmToken::Eof)) {
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00005066 // Parse curly braces marking block start/end
5067 if (parseCurlyBlockScope(AsmStrRewrites))
5068 continue;
5069
Eli Friedman0f4871d2012-10-22 23:58:19 +00005070 ParseStatementInfo Info(&AsmStrRewrites);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005071 if (parseStatement(Info, &SI))
Chad Rosierf1f6a722012-10-19 22:57:33 +00005072 return true;
Chad Rosier8bce6642012-10-18 15:49:34 +00005073
Chad Rosier149e8e02012-12-12 22:45:52 +00005074 if (Info.ParseError)
5075 return true;
5076
Benjamin Kramer1a136112013-02-15 20:37:21 +00005077 if (Info.Opcode == ~0U)
5078 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00005079
Benjamin Kramer1a136112013-02-15 20:37:21 +00005080 const MCInstrDesc &Desc = MII->get(Info.Opcode);
Chad Rosier8bce6642012-10-18 15:49:34 +00005081
Benjamin Kramer1a136112013-02-15 20:37:21 +00005082 // Build the list of clobbers, outputs and inputs.
5083 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
David Blaikie960ea3f2014-06-08 16:18:35 +00005084 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005085
Benjamin Kramer1a136112013-02-15 20:37:21 +00005086 // Immediate.
David Blaikie960ea3f2014-06-08 16:18:35 +00005087 if (Operand.isImm())
Benjamin Kramer1a136112013-02-15 20:37:21 +00005088 continue;
Chad Rosier8bce6642012-10-18 15:49:34 +00005089
Benjamin Kramer1a136112013-02-15 20:37:21 +00005090 // Register operand.
Nico Weber42f79db2014-07-17 20:24:55 +00005091 if (Operand.isReg() && !Operand.needAddressOf() &&
5092 !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
Benjamin Kramer1a136112013-02-15 20:37:21 +00005093 unsigned NumDefs = Desc.getNumDefs();
5094 // Clobber.
David Blaikie960ea3f2014-06-08 16:18:35 +00005095 if (NumDefs && Operand.getMCOperandNum() < NumDefs)
5096 ClobberRegs.push_back(Operand.getReg());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005097 continue;
5098 }
5099
5100 // Expr/Input or Output.
David Blaikie960ea3f2014-06-08 16:18:35 +00005101 StringRef SymName = Operand.getSymName();
Chad Rosiere81309b2013-04-09 17:53:49 +00005102 if (SymName.empty())
5103 continue;
5104
David Blaikie960ea3f2014-06-08 16:18:35 +00005105 void *OpDecl = Operand.getOpDecl();
Benjamin Kramer1a136112013-02-15 20:37:21 +00005106 if (!OpDecl)
5107 continue;
5108
5109 bool isOutput = (i == 1) && Desc.mayStore();
Chad Rosiere81309b2013-04-09 17:53:49 +00005110 SMLoc Start = SMLoc::getFromPointer(SymName.data());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005111 if (isOutput) {
5112 ++InputIdx;
5113 OutputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00005114 OutputDeclsAddressOf.push_back(Operand.needAddressOf());
Yaron Keren075759a2015-03-30 15:42:36 +00005115 OutputConstraints.push_back(("=" + Operand.getConstraint()).str());
Craig Topper7d5b2312015-10-10 05:25:02 +00005116 AsmStrRewrites.emplace_back(AOK_Output, Start, SymName.size());
Benjamin Kramer1a136112013-02-15 20:37:21 +00005117 } else {
5118 InputDecls.push_back(OpDecl);
David Blaikie960ea3f2014-06-08 16:18:35 +00005119 InputDeclsAddressOf.push_back(Operand.needAddressOf());
5120 InputConstraints.push_back(Operand.getConstraint().str());
Craig Topper7d5b2312015-10-10 05:25:02 +00005121 AsmStrRewrites.emplace_back(AOK_Input, Start, SymName.size());
Chad Rosier8bce6642012-10-18 15:49:34 +00005122 }
Chad Rosier8bce6642012-10-18 15:49:34 +00005123 }
Reid Kleckneree088972013-12-10 18:27:32 +00005124
5125 // Consider implicit defs to be clobbers. Think of cpuid and push.
Craig Toppere5e035a32015-12-05 07:13:35 +00005126 ArrayRef<MCPhysReg> ImpDefs(Desc.getImplicitDefs(),
5127 Desc.getNumImplicitDefs());
David Majnemer8114c1a2014-06-23 02:17:16 +00005128 ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end());
Chad Rosier8bce6642012-10-18 15:49:34 +00005129 }
5130
5131 // Set the number of Outputs and Inputs.
Chad Rosierf641baa2012-10-18 19:39:30 +00005132 NumOutputs = OutputDecls.size();
5133 NumInputs = InputDecls.size();
Chad Rosier8bce6642012-10-18 15:49:34 +00005134
5135 // Set the unique clobbers.
Benjamin Kramer1a136112013-02-15 20:37:21 +00005136 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
5137 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
5138 ClobberRegs.end());
5139 Clobbers.assign(ClobberRegs.size(), std::string());
5140 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
5141 raw_string_ostream OS(Clobbers[I]);
5142 IP->printRegName(OS, ClobberRegs[I]);
5143 }
Chad Rosier8bce6642012-10-18 15:49:34 +00005144
5145 // Merge the various outputs and inputs. Output are expected first.
5146 if (NumOutputs || NumInputs) {
5147 unsigned NumExprs = NumOutputs + NumInputs;
Chad Rosierf641baa2012-10-18 19:39:30 +00005148 OpDecls.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00005149 Constraints.resize(NumExprs);
Chad Rosier8bce6642012-10-18 15:49:34 +00005150 for (unsigned i = 0; i < NumOutputs; ++i) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00005151 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00005152 Constraints[i] = OutputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005153 }
5154 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
Chad Rosiera4bc9432013-01-10 22:10:27 +00005155 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
Chad Rosier72450332013-01-15 23:07:53 +00005156 Constraints[j] = InputConstraints[i];
Chad Rosier8bce6642012-10-18 15:49:34 +00005157 }
5158 }
5159
5160 // Build the IR assembly string.
Alp Tokere69170a2014-06-26 22:52:05 +00005161 std::string AsmStringIR;
5162 raw_string_ostream OS(AsmStringIR);
Alp Tokera55b95b2014-07-06 10:33:31 +00005163 StringRef ASMString =
5164 SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
5165 const char *AsmStart = ASMString.begin();
5166 const char *AsmEnd = ASMString.end();
Jim Grosbach4b905842013-09-20 23:08:21 +00005167 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
David Majnemer8114c1a2014-06-23 02:17:16 +00005168 for (const AsmRewrite &AR : AsmStrRewrites) {
5169 AsmRewriteKind Kind = AR.Kind;
Chad Rosierff10ed12013-04-12 16:26:42 +00005170 if (Kind == AOK_Delete)
5171 continue;
5172
David Majnemer8114c1a2014-06-23 02:17:16 +00005173 const char *Loc = AR.Loc.getPointer();
Chad Rosier17d37992013-03-19 21:12:14 +00005174 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!");
Chad Rosier0f48c552012-10-19 20:57:14 +00005175
Chad Rosier120eefd2013-03-19 17:32:17 +00005176 // Emit everything up to the immediate/expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00005177 if (unsigned Len = Loc - AsmStart)
Chad Rosier17d37992013-03-19 21:12:14 +00005178 OS << StringRef(AsmStart, Len);
Chad Rosier0f48c552012-10-19 20:57:14 +00005179
Chad Rosier37e755c2012-10-23 17:43:43 +00005180 // Skip the original expression.
5181 if (Kind == AOK_Skip) {
David Majnemer8114c1a2014-06-23 02:17:16 +00005182 AsmStart = Loc + AR.Len;
Chad Rosier37e755c2012-10-23 17:43:43 +00005183 continue;
5184 }
5185
Chad Rosierff10ed12013-04-12 16:26:42 +00005186 unsigned AdditionalSkip = 0;
Chad Rosier8bce6642012-10-18 15:49:34 +00005187 // Rewrite expressions in $N notation.
Chad Rosier0f48c552012-10-19 20:57:14 +00005188 switch (Kind) {
Jim Grosbach4b905842013-09-20 23:08:21 +00005189 default:
5190 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005191 case AOK_Imm:
David Majnemer8114c1a2014-06-23 02:17:16 +00005192 OS << "$$" << AR.Val;
Chad Rosier11c42f22012-10-26 18:04:20 +00005193 break;
5194 case AOK_ImmPrefix:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005195 OS << "$$";
Chad Rosier8bce6642012-10-18 15:49:34 +00005196 break;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005197 case AOK_Label:
Matt Arsenault4e273432014-12-04 00:06:57 +00005198 OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label;
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00005199 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005200 case AOK_Input:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005201 OS << '$' << InputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00005202 break;
5203 case AOK_Output:
Benjamin Kramer1a136112013-02-15 20:37:21 +00005204 OS << '$' << OutputIdx++;
Chad Rosier8bce6642012-10-18 15:49:34 +00005205 break;
Chad Rosier0f48c552012-10-19 20:57:14 +00005206 case AOK_SizeDirective:
David Majnemer8114c1a2014-06-23 02:17:16 +00005207 switch (AR.Val) {
Chad Rosier0f48c552012-10-19 20:57:14 +00005208 default: break;
5209 case 8: OS << "byte ptr "; break;
5210 case 16: OS << "word ptr "; break;
5211 case 32: OS << "dword ptr "; break;
5212 case 64: OS << "qword ptr "; break;
5213 case 80: OS << "xword ptr "; break;
5214 case 128: OS << "xmmword ptr "; break;
5215 case 256: OS << "ymmword ptr "; break;
5216 }
Eli Friedman0f4871d2012-10-22 23:58:19 +00005217 break;
5218 case AOK_Emit:
5219 OS << ".byte";
5220 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00005221 case AOK_Align: {
Reid Klecknerfb1c1c72015-10-27 17:32:48 +00005222 // MS alignment directives are measured in bytes. If the native assembler
5223 // measures alignment in bytes, we can pass it straight through.
5224 OS << ".align";
5225 if (getContext().getAsmInfo()->getAlignmentIsInBytes())
5226 break;
Chad Rosierc7f552c2013-02-12 21:33:51 +00005227
Reid Klecknerfb1c1c72015-10-27 17:32:48 +00005228 // Alignment is in log2 form, so print that instead and skip the original
5229 // immediate.
5230 unsigned Val = AR.Val;
5231 OS << ' ' << Val;
Benjamin Kramer1a136112013-02-15 20:37:21 +00005232 assert(Val < 10 && "Expected alignment less then 2^10.");
Chad Rosierc7f552c2013-02-12 21:33:51 +00005233 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
5234 break;
5235 }
Michael Zuckerman02ecd432015-12-13 17:07:23 +00005236 case AOK_EVEN:
5237 OS << ".even";
5238 break;
Chad Rosierf0e87202012-10-25 20:41:34 +00005239 case AOK_DotOperator:
Reid Kleckner94a1c4d2014-03-06 19:19:12 +00005240 // Insert the dot if the user omitted it.
Alp Tokere69170a2014-06-26 22:52:05 +00005241 OS.flush();
5242 if (AsmStringIR.back() != '.')
Reid Kleckner94a1c4d2014-03-06 19:19:12 +00005243 OS << '.';
David Majnemer8114c1a2014-06-23 02:17:16 +00005244 OS << AR.Val;
Chad Rosierf0e87202012-10-25 20:41:34 +00005245 break;
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00005246 case AOK_EndOfStatement:
5247 OS << "\n\t";
5248 break;
Chad Rosier8bce6642012-10-18 15:49:34 +00005249 }
Chad Rosier0f48c552012-10-19 20:57:14 +00005250
Chad Rosier8bce6642012-10-18 15:49:34 +00005251 // Skip the original expression.
David Majnemer8114c1a2014-06-23 02:17:16 +00005252 AsmStart = Loc + AR.Len + AdditionalSkip;
Chad Rosier8bce6642012-10-18 15:49:34 +00005253 }
5254
5255 // Emit the remainder of the asm string.
Chad Rosier17d37992013-03-19 21:12:14 +00005256 if (AsmStart != AsmEnd)
5257 OS << StringRef(AsmStart, AsmEnd - AsmStart);
Chad Rosier8bce6642012-10-18 15:49:34 +00005258
5259 AsmString = OS.str();
5260 return false;
5261}
5262
Pete Cooper80d21cb2015-06-22 19:35:57 +00005263namespace llvm {
5264namespace MCParserUtils {
5265
5266/// Returns whether the given symbol is used anywhere in the given expression,
5267/// or subexpressions.
5268static bool isSymbolUsedInExpression(const MCSymbol *Sym, const MCExpr *Value) {
5269 switch (Value->getKind()) {
5270 case MCExpr::Binary: {
5271 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
5272 return isSymbolUsedInExpression(Sym, BE->getLHS()) ||
5273 isSymbolUsedInExpression(Sym, BE->getRHS());
5274 }
5275 case MCExpr::Target:
5276 case MCExpr::Constant:
5277 return false;
5278 case MCExpr::SymbolRef: {
5279 const MCSymbol &S =
5280 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
5281 if (S.isVariable())
5282 return isSymbolUsedInExpression(Sym, S.getVariableValue());
5283 return &S == Sym;
5284 }
5285 case MCExpr::Unary:
5286 return isSymbolUsedInExpression(
5287 Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
5288 }
5289
5290 llvm_unreachable("Unknown expr kind!");
5291}
5292
5293bool parseAssignmentExpression(StringRef Name, bool allow_redef,
5294 MCAsmParser &Parser, MCSymbol *&Sym,
5295 const MCExpr *&Value) {
Pete Cooper80d21cb2015-06-22 19:35:57 +00005296
5297 // FIXME: Use better location, we should use proper tokens.
Nirav Davefd910412016-06-17 16:06:17 +00005298 SMLoc EqualLoc = Parser.getTok().getLoc();
Pete Cooper80d21cb2015-06-22 19:35:57 +00005299
5300 if (Parser.parseExpression(Value)) {
5301 Parser.TokError("missing expression");
5302 Parser.eatToEndOfStatement();
5303 return true;
5304 }
5305
5306 // Note: we don't count b as used in "a = b". This is to allow
5307 // a = b
5308 // b = c
5309
Nirav Davefd910412016-06-17 16:06:17 +00005310 if (Parser.getTok().isNot(AsmToken::EndOfStatement))
Pete Cooper80d21cb2015-06-22 19:35:57 +00005311 return Parser.TokError("unexpected token in assignment");
5312
5313 // Eat the end of statement marker.
5314 Parser.Lex();
5315
5316 // Validate that the LHS is allowed to be a variable (either it has not been
5317 // used as a symbol, or it is an absolute symbol).
5318 Sym = Parser.getContext().lookupSymbol(Name);
5319 if (Sym) {
5320 // Diagnose assignment to a label.
5321 //
5322 // FIXME: Diagnostics. Note the location of the definition as a label.
5323 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
5324 if (isSymbolUsedInExpression(Sym, Value))
5325 return Parser.Error(EqualLoc, "Recursive use of '" + Name + "'");
Vedant Kumar86dbd922015-08-31 17:44:53 +00005326 else if (Sym->isUndefined(/*SetUsed*/ false) && !Sym->isUsed() &&
5327 !Sym->isVariable())
Pete Cooper80d21cb2015-06-22 19:35:57 +00005328 ; // Allow redefinitions of undefined symbols only used in directives.
5329 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
5330 ; // Allow redefinitions of variables that haven't yet been used.
5331 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
5332 return Parser.Error(EqualLoc, "redefinition of '" + Name + "'");
5333 else if (!Sym->isVariable())
5334 return Parser.Error(EqualLoc, "invalid assignment to '" + Name + "'");
5335 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
5336 return Parser.Error(EqualLoc,
5337 "invalid reassignment of non-absolute variable '" +
5338 Name + "'");
Pete Cooper80d21cb2015-06-22 19:35:57 +00005339 } else if (Name == ".") {
Rafael Espindola7ae65d82015-11-04 23:59:18 +00005340 Parser.getStreamer().emitValueToOffset(Value, 0);
Pete Cooper80d21cb2015-06-22 19:35:57 +00005341 return false;
5342 } else
5343 Sym = Parser.getContext().getOrCreateSymbol(Name);
5344
5345 Sym->setRedefinable(allow_redef);
5346
5347 return false;
5348}
5349
Eugene Zelenko33d7b762016-08-23 17:14:32 +00005350} // end namespace MCParserUtils
5351} // end namespace llvm
Pete Cooper80d21cb2015-06-22 19:35:57 +00005352
Daniel Dunbar01e36072010-07-17 02:26:10 +00005353/// \brief Create an MCAsmParser instance.
Jim Grosbach4b905842013-09-20 23:08:21 +00005354MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
5355 MCStreamer &Out, const MCAsmInfo &MAI) {
Jim Grosbach345768c2011-08-16 18:33:49 +00005356 return new AsmParser(SM, C, Out, MAI);
Daniel Dunbar01e36072010-07-17 02:26:10 +00005357}