blob: 6985d356af62636470602a19adf84a999357d0c1 [file] [log] [blame]
Daniel Dunbar71475772009-07-17 20:42:00 +00001//===-- X86AsmParser.cpp - Parse X86 assembly to MCInst instructions ------===//
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
Reid Kleckner9cdd4df2017-10-11 21:24:33 +000010#include "InstPrinter/X86IntelInstPrinter.h"
Evan Cheng11424442011-07-26 00:24:13 +000011#include "MCTargetDesc/X86BaseInfo.h"
Reid Kleckner9cdd4df2017-10-11 21:24:33 +000012#include "MCTargetDesc/X86TargetStreamer.h"
Evgeniy Stepanov49e26252014-03-14 08:58:04 +000013#include "X86AsmInstrumentation.h"
Evgeniy Stepanove3804d42014-02-28 12:28:07 +000014#include "X86AsmParserCommon.h"
15#include "X86Operand.h"
Craig Topper690d8ea2013-07-24 07:33:14 +000016#include "llvm/ADT/STLExtras.h"
Chris Lattner1261b812010-09-22 04:11:10 +000017#include "llvm/ADT/SmallString.h"
18#include "llvm/ADT/SmallVector.h"
Chris Lattner1261b812010-09-22 04:11:10 +000019#include "llvm/ADT/StringSwitch.h"
20#include "llvm/ADT/Twine.h"
Chad Rosier8a244662013-04-02 20:02:33 +000021#include "llvm/MC/MCContext.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000022#include "llvm/MC/MCExpr.h"
23#include "llvm/MC/MCInst.h"
Evgeniy Stepanovf4a36992014-04-24 13:29:34 +000024#include "llvm/MC/MCInstrInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000025#include "llvm/MC/MCParser/MCAsmLexer.h"
26#include "llvm/MC/MCParser/MCAsmParser.h"
27#include "llvm/MC/MCParser/MCParsedAsmOperand.h"
Benjamin Kramerb3e8a6d2016-01-27 10:01:28 +000028#include "llvm/MC/MCParser/MCTargetAsmParser.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000029#include "llvm/MC/MCRegisterInfo.h"
Michael Zuckerman02ecd432015-12-13 17:07:23 +000030#include "llvm/MC/MCSection.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000031#include "llvm/MC/MCStreamer.h"
32#include "llvm/MC/MCSubtargetInfo.h"
33#include "llvm/MC/MCSymbol.h"
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +000034#include "llvm/Support/SourceMgr.h"
Evan Cheng2bb40352011-08-24 18:08:43 +000035#include "llvm/Support/TargetRegistry.h"
Daniel Dunbar7d7b4d12010-08-12 00:55:42 +000036#include "llvm/Support/raw_ostream.h"
Reid Kleckner7b1e1a02014-07-30 22:23:11 +000037#include <algorithm>
Evgeniy Stepanov49e26252014-03-14 08:58:04 +000038#include <memory>
Evan Cheng4d1ca962011-07-08 01:53:10 +000039
Daniel Dunbar71475772009-07-17 20:42:00 +000040using namespace llvm;
41
Andrew V. Tischenko32e9b1a2017-07-25 13:05:12 +000042static bool checkScale(unsigned Scale, StringRef &ErrMsg) {
43 if (Scale != 1 && Scale != 2 && Scale != 4 && Scale != 8) {
44 ErrMsg = "scale factor in address must be 1, 2, 4 or 8";
45 return true;
46 }
47 return false;
48}
49
Daniel Dunbar71475772009-07-17 20:42:00 +000050namespace {
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +000051
Chad Rosier5362af92013-04-16 18:15:40 +000052static const char OpPrecedence[] = {
Kevin Enderby2e13b1c2014-01-15 19:05:24 +000053 0, // IC_OR
Michael Kupersteine3de07a2015-06-14 12:59:45 +000054 1, // IC_XOR
55 2, // IC_AND
56 3, // IC_LSHIFT
57 3, // IC_RSHIFT
58 4, // IC_PLUS
59 4, // IC_MINUS
60 5, // IC_MULTIPLY
61 5, // IC_DIVIDE
Coby Tayree41a5b552017-06-27 16:58:27 +000062 5, // IC_MOD
63 6, // IC_NOT
64 7, // IC_NEG
65 8, // IC_RPAREN
66 9, // IC_LPAREN
Chad Rosier5362af92013-04-16 18:15:40 +000067 0, // IC_IMM
68 0 // IC_REGISTER
69};
70
Devang Patel4a6e7782012-01-12 18:03:40 +000071class X86AsmParser : public MCTargetAsmParser {
Chad Rosierf0e87202012-10-25 20:41:34 +000072 ParseInstructionInfo *InstInfo;
Evgeniy Stepanov49e26252014-03-14 08:58:04 +000073 std::unique_ptr<X86AsmInstrumentation> Instrumentation;
Nirav Dave6477ce22016-09-26 19:33:36 +000074 bool Code16GCC;
NAKAMURA Takumia9cb5382015-09-22 11:14:39 +000075
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +000076private:
Alp Tokera5b88a52013-12-02 16:06:06 +000077 SMLoc consumeToken() {
Rafael Espindola961d4692014-11-11 05:18:41 +000078 MCAsmParser &Parser = getParser();
Alp Tokera5b88a52013-12-02 16:06:06 +000079 SMLoc Result = Parser.getTok().getLoc();
80 Parser.Lex();
81 return Result;
82 }
83
Reid Kleckner9cdd4df2017-10-11 21:24:33 +000084 X86TargetStreamer &getTargetStreamer() {
85 assert(getParser().getStreamer().getTargetStreamer() &&
86 "do not have a target streamer");
87 MCTargetStreamer &TS = *getParser().getStreamer().getTargetStreamer();
88 return static_cast<X86TargetStreamer &>(TS);
89 }
90
Nirav Dave6477ce22016-09-26 19:33:36 +000091 unsigned MatchInstruction(const OperandVector &Operands, MCInst &Inst,
92 uint64_t &ErrorInfo, bool matchingInlineAsm,
93 unsigned VariantID = 0) {
94 // In Code16GCC mode, match as 32-bit.
95 if (Code16GCC)
96 SwitchMode(X86::Mode32Bit);
97 unsigned rv = MatchInstructionImpl(Operands, Inst, ErrorInfo,
98 matchingInlineAsm, VariantID);
99 if (Code16GCC)
100 SwitchMode(X86::Mode16Bit);
101 return rv;
102 }
103
Chad Rosier5362af92013-04-16 18:15:40 +0000104 enum InfixCalculatorTok {
Kevin Enderby2e13b1c2014-01-15 19:05:24 +0000105 IC_OR = 0,
Michael Kupersteine3de07a2015-06-14 12:59:45 +0000106 IC_XOR,
Kevin Enderby2e13b1c2014-01-15 19:05:24 +0000107 IC_AND,
Kevin Enderbyd6b10712014-02-06 01:21:15 +0000108 IC_LSHIFT,
109 IC_RSHIFT,
Kevin Enderby2e13b1c2014-01-15 19:05:24 +0000110 IC_PLUS,
Chad Rosier5362af92013-04-16 18:15:40 +0000111 IC_MINUS,
112 IC_MULTIPLY,
113 IC_DIVIDE,
Coby Tayree41a5b552017-06-27 16:58:27 +0000114 IC_MOD,
115 IC_NOT,
116 IC_NEG,
Chad Rosier5362af92013-04-16 18:15:40 +0000117 IC_RPAREN,
118 IC_LPAREN,
119 IC_IMM,
120 IC_REGISTER
121 };
122
Coby Tayree07a89742017-03-21 19:31:55 +0000123 enum IntelOperatorKind {
124 IOK_INVALID = 0,
125 IOK_LENGTH,
126 IOK_SIZE,
127 IOK_TYPE,
128 IOK_OFFSET
129 };
130
Chad Rosier5362af92013-04-16 18:15:40 +0000131 class InfixCalculator {
132 typedef std::pair< InfixCalculatorTok, int64_t > ICToken;
133 SmallVector<InfixCalculatorTok, 4> InfixOperatorStack;
134 SmallVector<ICToken, 4> PostfixStack;
Michael Liao5bf95782014-12-04 05:20:33 +0000135
Coby Tayree41a5b552017-06-27 16:58:27 +0000136 bool isUnaryOperator(const InfixCalculatorTok Op) {
137 return Op == IC_NEG || Op == IC_NOT;
138 }
139
Chad Rosier5362af92013-04-16 18:15:40 +0000140 public:
141 int64_t popOperand() {
142 assert (!PostfixStack.empty() && "Poped an empty stack!");
143 ICToken Op = PostfixStack.pop_back_val();
Andrew V. Tischenko32e9b1a2017-07-25 13:05:12 +0000144 if (!(Op.first == IC_IMM || Op.first == IC_REGISTER))
145 return -1; // The invalid Scale value will be caught later by checkScale
Chad Rosier5362af92013-04-16 18:15:40 +0000146 return Op.second;
147 }
148 void pushOperand(InfixCalculatorTok Op, int64_t Val = 0) {
149 assert ((Op == IC_IMM || Op == IC_REGISTER) &&
150 "Unexpected operand!");
151 PostfixStack.push_back(std::make_pair(Op, Val));
152 }
Michael Liao5bf95782014-12-04 05:20:33 +0000153
Jakub Staszak9c349222013-08-08 15:48:46 +0000154 void popOperator() { InfixOperatorStack.pop_back(); }
Chad Rosier5362af92013-04-16 18:15:40 +0000155 void pushOperator(InfixCalculatorTok Op) {
156 // Push the new operator if the stack is empty.
157 if (InfixOperatorStack.empty()) {
158 InfixOperatorStack.push_back(Op);
159 return;
160 }
Michael Liao5bf95782014-12-04 05:20:33 +0000161
Chad Rosier5362af92013-04-16 18:15:40 +0000162 // Push the new operator if it has a higher precedence than the operator
163 // on the top of the stack or the operator on the top of the stack is a
164 // left parentheses.
165 unsigned Idx = InfixOperatorStack.size() - 1;
166 InfixCalculatorTok StackOp = InfixOperatorStack[Idx];
167 if (OpPrecedence[Op] > OpPrecedence[StackOp] || StackOp == IC_LPAREN) {
168 InfixOperatorStack.push_back(Op);
169 return;
170 }
Michael Liao5bf95782014-12-04 05:20:33 +0000171
Chad Rosier5362af92013-04-16 18:15:40 +0000172 // The operator on the top of the stack has higher precedence than the
173 // new operator.
174 unsigned ParenCount = 0;
Kirill Bobyrev6afbaf02017-01-18 16:34:25 +0000175 while (1) {
Chad Rosier5362af92013-04-16 18:15:40 +0000176 // Nothing to process.
177 if (InfixOperatorStack.empty())
178 break;
Michael Liao5bf95782014-12-04 05:20:33 +0000179
Chad Rosier5362af92013-04-16 18:15:40 +0000180 Idx = InfixOperatorStack.size() - 1;
181 StackOp = InfixOperatorStack[Idx];
182 if (!(OpPrecedence[StackOp] >= OpPrecedence[Op] || ParenCount))
183 break;
Michael Liao5bf95782014-12-04 05:20:33 +0000184
Chad Rosier5362af92013-04-16 18:15:40 +0000185 // If we have an even parentheses count and we see a left parentheses,
186 // then stop processing.
187 if (!ParenCount && StackOp == IC_LPAREN)
188 break;
Michael Liao5bf95782014-12-04 05:20:33 +0000189
Chad Rosier5362af92013-04-16 18:15:40 +0000190 if (StackOp == IC_RPAREN) {
191 ++ParenCount;
Jakub Staszak9c349222013-08-08 15:48:46 +0000192 InfixOperatorStack.pop_back();
Chad Rosier5362af92013-04-16 18:15:40 +0000193 } else if (StackOp == IC_LPAREN) {
194 --ParenCount;
Jakub Staszak9c349222013-08-08 15:48:46 +0000195 InfixOperatorStack.pop_back();
Chad Rosier5362af92013-04-16 18:15:40 +0000196 } else {
Jakub Staszak9c349222013-08-08 15:48:46 +0000197 InfixOperatorStack.pop_back();
Chad Rosier5362af92013-04-16 18:15:40 +0000198 PostfixStack.push_back(std::make_pair(StackOp, 0));
199 }
200 }
201 // Push the new operator.
202 InfixOperatorStack.push_back(Op);
203 }
Marina Yatsinaa0e02412015-08-10 11:33:10 +0000204
Chad Rosier5362af92013-04-16 18:15:40 +0000205 int64_t execute() {
206 // Push any remaining operators onto the postfix stack.
207 while (!InfixOperatorStack.empty()) {
208 InfixCalculatorTok StackOp = InfixOperatorStack.pop_back_val();
209 if (StackOp != IC_LPAREN && StackOp != IC_RPAREN)
210 PostfixStack.push_back(std::make_pair(StackOp, 0));
211 }
Michael Liao5bf95782014-12-04 05:20:33 +0000212
Chad Rosier5362af92013-04-16 18:15:40 +0000213 if (PostfixStack.empty())
214 return 0;
Michael Liao5bf95782014-12-04 05:20:33 +0000215
Chad Rosier5362af92013-04-16 18:15:40 +0000216 SmallVector<ICToken, 16> OperandStack;
217 for (unsigned i = 0, e = PostfixStack.size(); i != e; ++i) {
218 ICToken Op = PostfixStack[i];
219 if (Op.first == IC_IMM || Op.first == IC_REGISTER) {
220 OperandStack.push_back(Op);
Coby Tayree41a5b552017-06-27 16:58:27 +0000221 } else if (isUnaryOperator(Op.first)) {
222 assert (OperandStack.size() > 0 && "Too few operands.");
223 ICToken Operand = OperandStack.pop_back_val();
224 assert (Operand.first == IC_IMM &&
225 "Unary operation with a register!");
226 switch (Op.first) {
227 default:
228 report_fatal_error("Unexpected operator!");
229 break;
230 case IC_NEG:
231 OperandStack.push_back(std::make_pair(IC_IMM, -Operand.second));
232 break;
233 case IC_NOT:
234 OperandStack.push_back(std::make_pair(IC_IMM, ~Operand.second));
235 break;
236 }
Chad Rosier5362af92013-04-16 18:15:40 +0000237 } else {
238 assert (OperandStack.size() > 1 && "Too few operands.");
239 int64_t Val;
240 ICToken Op2 = OperandStack.pop_back_val();
241 ICToken Op1 = OperandStack.pop_back_val();
242 switch (Op.first) {
243 default:
244 report_fatal_error("Unexpected operator!");
245 break;
246 case IC_PLUS:
247 Val = Op1.second + Op2.second;
248 OperandStack.push_back(std::make_pair(IC_IMM, Val));
249 break;
250 case IC_MINUS:
251 Val = Op1.second - Op2.second;
252 OperandStack.push_back(std::make_pair(IC_IMM, Val));
253 break;
254 case IC_MULTIPLY:
255 assert (Op1.first == IC_IMM && Op2.first == IC_IMM &&
256 "Multiply operation with an immediate and a register!");
257 Val = Op1.second * Op2.second;
258 OperandStack.push_back(std::make_pair(IC_IMM, Val));
259 break;
260 case IC_DIVIDE:
261 assert (Op1.first == IC_IMM && Op2.first == IC_IMM &&
262 "Divide operation with an immediate and a register!");
263 assert (Op2.second != 0 && "Division by zero!");
264 Val = Op1.second / Op2.second;
265 OperandStack.push_back(std::make_pair(IC_IMM, Val));
266 break;
Coby Tayree41a5b552017-06-27 16:58:27 +0000267 case IC_MOD:
268 assert (Op1.first == IC_IMM && Op2.first == IC_IMM &&
269 "Modulo operation with an immediate and a register!");
270 Val = Op1.second % Op2.second;
271 OperandStack.push_back(std::make_pair(IC_IMM, Val));
272 break;
Kevin Enderby2e13b1c2014-01-15 19:05:24 +0000273 case IC_OR:
274 assert (Op1.first == IC_IMM && Op2.first == IC_IMM &&
275 "Or operation with an immediate and a register!");
276 Val = Op1.second | Op2.second;
277 OperandStack.push_back(std::make_pair(IC_IMM, Val));
278 break;
Michael Kupersteine3de07a2015-06-14 12:59:45 +0000279 case IC_XOR:
280 assert(Op1.first == IC_IMM && Op2.first == IC_IMM &&
281 "Xor operation with an immediate and a register!");
282 Val = Op1.second ^ Op2.second;
283 OperandStack.push_back(std::make_pair(IC_IMM, Val));
284 break;
Kevin Enderby2e13b1c2014-01-15 19:05:24 +0000285 case IC_AND:
286 assert (Op1.first == IC_IMM && Op2.first == IC_IMM &&
287 "And operation with an immediate and a register!");
288 Val = Op1.second & Op2.second;
289 OperandStack.push_back(std::make_pair(IC_IMM, Val));
290 break;
Kevin Enderbyd6b10712014-02-06 01:21:15 +0000291 case IC_LSHIFT:
292 assert (Op1.first == IC_IMM && Op2.first == IC_IMM &&
293 "Left shift operation with an immediate and a register!");
294 Val = Op1.second << Op2.second;
295 OperandStack.push_back(std::make_pair(IC_IMM, Val));
296 break;
297 case IC_RSHIFT:
298 assert (Op1.first == IC_IMM && Op2.first == IC_IMM &&
299 "Right shift operation with an immediate and a register!");
300 Val = Op1.second >> Op2.second;
301 OperandStack.push_back(std::make_pair(IC_IMM, Val));
302 break;
Chad Rosier5362af92013-04-16 18:15:40 +0000303 }
304 }
305 }
306 assert (OperandStack.size() == 1 && "Expected a single result.");
307 return OperandStack.pop_back_val().second;
308 }
309 };
310
311 enum IntelExprState {
Coby Tayreed8912892017-08-24 08:46:25 +0000312 IES_INIT,
Kevin Enderby2e13b1c2014-01-15 19:05:24 +0000313 IES_OR,
Michael Kupersteine3de07a2015-06-14 12:59:45 +0000314 IES_XOR,
Kevin Enderby2e13b1c2014-01-15 19:05:24 +0000315 IES_AND,
Kevin Enderbyd6b10712014-02-06 01:21:15 +0000316 IES_LSHIFT,
317 IES_RSHIFT,
Chad Rosier5362af92013-04-16 18:15:40 +0000318 IES_PLUS,
319 IES_MINUS,
Ehsan Akhgari4103da62014-07-04 19:13:05 +0000320 IES_NOT,
Chad Rosier5362af92013-04-16 18:15:40 +0000321 IES_MULTIPLY,
322 IES_DIVIDE,
Coby Tayree41a5b552017-06-27 16:58:27 +0000323 IES_MOD,
Chad Rosier5362af92013-04-16 18:15:40 +0000324 IES_LBRAC,
325 IES_RBRAC,
326 IES_LPAREN,
327 IES_RPAREN,
328 IES_REGISTER,
Chad Rosier5362af92013-04-16 18:15:40 +0000329 IES_INTEGER,
Chad Rosier5362af92013-04-16 18:15:40 +0000330 IES_IDENTIFIER,
331 IES_ERROR
332 };
333
334 class IntelExprStateMachine {
Chad Rosier31246272013-04-17 21:01:45 +0000335 IntelExprState State, PrevState;
Chad Rosier5362af92013-04-16 18:15:40 +0000336 unsigned BaseReg, IndexReg, TmpReg, Scale;
Chad Rosierbfb70992013-04-17 00:11:46 +0000337 int64_t Imm;
Chad Rosier5362af92013-04-16 18:15:40 +0000338 const MCExpr *Sym;
339 StringRef SymName;
340 InfixCalculator IC;
Chad Rosiercb78f0d2013-04-22 19:42:15 +0000341 InlineAsmIdentifierInfo Info;
Coby Tayreed8912892017-08-24 08:46:25 +0000342 short BracCount;
343 bool MemExpr;
NAKAMURA Takumia9cb5382015-09-22 11:14:39 +0000344
Chad Rosier5362af92013-04-16 18:15:40 +0000345 public:
Coby Tayreed8912892017-08-24 08:46:25 +0000346 IntelExprStateMachine()
347 : State(IES_INIT), PrevState(IES_ERROR), BaseReg(0), IndexReg(0),
348 TmpReg(0), Scale(1), Imm(0), Sym(nullptr), BracCount(0),
Coby Tayreec3d24112017-09-29 07:02:46 +0000349 MemExpr(false) {}
Michael Liao5bf95782014-12-04 05:20:33 +0000350
Coby Tayreed8912892017-08-24 08:46:25 +0000351 void addImm(int64_t imm) { Imm += imm; }
352 short getBracCount() { return BracCount; }
353 bool isMemExpr() { return MemExpr; }
Chad Rosier5362af92013-04-16 18:15:40 +0000354 unsigned getBaseReg() { return BaseReg; }
355 unsigned getIndexReg() { return IndexReg; }
356 unsigned getScale() { return Scale; }
357 const MCExpr *getSym() { return Sym; }
358 StringRef getSymName() { return SymName; }
Chad Rosierbfb70992013-04-17 00:11:46 +0000359 int64_t getImm() { return Imm + IC.execute(); }
Chad Rosieredb1dc82013-05-09 23:48:53 +0000360 bool isValidEndState() {
361 return State == IES_RBRAC || State == IES_INTEGER;
362 }
Chad Rosier31246272013-04-17 21:01:45 +0000363 bool hadError() { return State == IES_ERROR; }
Coby Tayreed8912892017-08-24 08:46:25 +0000364 InlineAsmIdentifierInfo &getIdentifierInfo() { return Info; }
Chad Rosiercb78f0d2013-04-22 19:42:15 +0000365
Kevin Enderby2e13b1c2014-01-15 19:05:24 +0000366 void onOr() {
367 IntelExprState CurrState = State;
368 switch (State) {
369 default:
370 State = IES_ERROR;
371 break;
372 case IES_INTEGER:
373 case IES_RPAREN:
374 case IES_REGISTER:
375 State = IES_OR;
376 IC.pushOperator(IC_OR);
377 break;
378 }
379 PrevState = CurrState;
380 }
Michael Kupersteine3de07a2015-06-14 12:59:45 +0000381 void onXor() {
382 IntelExprState CurrState = State;
383 switch (State) {
384 default:
385 State = IES_ERROR;
386 break;
387 case IES_INTEGER:
388 case IES_RPAREN:
389 case IES_REGISTER:
390 State = IES_XOR;
391 IC.pushOperator(IC_XOR);
392 break;
393 }
394 PrevState = CurrState;
395 }
Kevin Enderby2e13b1c2014-01-15 19:05:24 +0000396 void onAnd() {
397 IntelExprState CurrState = State;
398 switch (State) {
399 default:
400 State = IES_ERROR;
401 break;
402 case IES_INTEGER:
403 case IES_RPAREN:
404 case IES_REGISTER:
405 State = IES_AND;
406 IC.pushOperator(IC_AND);
407 break;
408 }
409 PrevState = CurrState;
410 }
Kevin Enderbyd6b10712014-02-06 01:21:15 +0000411 void onLShift() {
412 IntelExprState CurrState = State;
413 switch (State) {
414 default:
415 State = IES_ERROR;
416 break;
417 case IES_INTEGER:
418 case IES_RPAREN:
419 case IES_REGISTER:
420 State = IES_LSHIFT;
421 IC.pushOperator(IC_LSHIFT);
422 break;
423 }
424 PrevState = CurrState;
425 }
426 void onRShift() {
427 IntelExprState CurrState = State;
428 switch (State) {
429 default:
430 State = IES_ERROR;
431 break;
432 case IES_INTEGER:
433 case IES_RPAREN:
434 case IES_REGISTER:
435 State = IES_RSHIFT;
436 IC.pushOperator(IC_RSHIFT);
437 break;
438 }
439 PrevState = CurrState;
440 }
Andrew V. Tischenko32e9b1a2017-07-25 13:05:12 +0000441 bool onPlus(StringRef &ErrMsg) {
Chad Rosier31246272013-04-17 21:01:45 +0000442 IntelExprState CurrState = State;
Chad Rosier5362af92013-04-16 18:15:40 +0000443 switch (State) {
444 default:
445 State = IES_ERROR;
446 break;
447 case IES_INTEGER:
448 case IES_RPAREN:
Chad Rosier5362af92013-04-16 18:15:40 +0000449 case IES_REGISTER:
450 State = IES_PLUS;
Chad Rosier5362af92013-04-16 18:15:40 +0000451 IC.pushOperator(IC_PLUS);
Chad Rosier31246272013-04-17 21:01:45 +0000452 if (CurrState == IES_REGISTER && PrevState != IES_MULTIPLY) {
453 // If we already have a BaseReg, then assume this is the IndexReg with
454 // a scale of 1.
455 if (!BaseReg) {
456 BaseReg = TmpReg;
457 } else {
Andrew V. Tischenko32e9b1a2017-07-25 13:05:12 +0000458 if (IndexReg) {
459 ErrMsg = "BaseReg/IndexReg already set!";
460 return true;
461 }
Chad Rosier31246272013-04-17 21:01:45 +0000462 IndexReg = TmpReg;
463 Scale = 1;
464 }
465 }
Chad Rosier5362af92013-04-16 18:15:40 +0000466 break;
467 }
Chad Rosier31246272013-04-17 21:01:45 +0000468 PrevState = CurrState;
Andrew V. Tischenko32e9b1a2017-07-25 13:05:12 +0000469 return false;
Chad Rosier5362af92013-04-16 18:15:40 +0000470 }
Andrew V. Tischenko32e9b1a2017-07-25 13:05:12 +0000471 bool onMinus(StringRef &ErrMsg) {
Chad Rosier31246272013-04-17 21:01:45 +0000472 IntelExprState CurrState = State;
Chad Rosier5362af92013-04-16 18:15:40 +0000473 switch (State) {
474 default:
475 State = IES_ERROR;
476 break;
Coby Tayree41a5b552017-06-27 16:58:27 +0000477 case IES_OR:
478 case IES_XOR:
479 case IES_AND:
480 case IES_LSHIFT:
481 case IES_RSHIFT:
Chad Rosier5362af92013-04-16 18:15:40 +0000482 case IES_PLUS:
Ehsan Akhgari4103da62014-07-04 19:13:05 +0000483 case IES_NOT:
Chad Rosier31246272013-04-17 21:01:45 +0000484 case IES_MULTIPLY:
485 case IES_DIVIDE:
Coby Tayree41a5b552017-06-27 16:58:27 +0000486 case IES_MOD:
Chad Rosier5362af92013-04-16 18:15:40 +0000487 case IES_LPAREN:
Chad Rosier5362af92013-04-16 18:15:40 +0000488 case IES_RPAREN:
Chad Rosier31246272013-04-17 21:01:45 +0000489 case IES_LBRAC:
490 case IES_RBRAC:
491 case IES_INTEGER:
Chad Rosier5362af92013-04-16 18:15:40 +0000492 case IES_REGISTER:
Coby Tayreed8912892017-08-24 08:46:25 +0000493 case IES_INIT:
Chad Rosier5362af92013-04-16 18:15:40 +0000494 State = IES_MINUS;
Coby Tayree41a5b552017-06-27 16:58:27 +0000495 // push minus operator if it is not a negate operator
496 if (CurrState == IES_REGISTER || CurrState == IES_RPAREN ||
497 CurrState == IES_INTEGER || CurrState == IES_RBRAC)
Chad Rosier31246272013-04-17 21:01:45 +0000498 IC.pushOperator(IC_MINUS);
Andrew V. Tischenko32e9b1a2017-07-25 13:05:12 +0000499 else if (PrevState == IES_REGISTER && CurrState == IES_MULTIPLY) {
500 // We have negate operator for Scale: it's illegal
501 ErrMsg = "Scale can't be negative";
502 return true;
503 } else
Coby Tayree41a5b552017-06-27 16:58:27 +0000504 IC.pushOperator(IC_NEG);
Chad Rosier31246272013-04-17 21:01:45 +0000505 if (CurrState == IES_REGISTER && PrevState != IES_MULTIPLY) {
506 // If we already have a BaseReg, then assume this is the IndexReg with
507 // a scale of 1.
508 if (!BaseReg) {
509 BaseReg = TmpReg;
510 } else {
Andrew V. Tischenko32e9b1a2017-07-25 13:05:12 +0000511 if (IndexReg) {
512 ErrMsg = "BaseReg/IndexReg already set!";
513 return true;
514 }
Chad Rosier31246272013-04-17 21:01:45 +0000515 IndexReg = TmpReg;
516 Scale = 1;
517 }
Chad Rosier5362af92013-04-16 18:15:40 +0000518 }
Chad Rosier5362af92013-04-16 18:15:40 +0000519 break;
520 }
Chad Rosier31246272013-04-17 21:01:45 +0000521 PrevState = CurrState;
Andrew V. Tischenko32e9b1a2017-07-25 13:05:12 +0000522 return false;
Chad Rosier5362af92013-04-16 18:15:40 +0000523 }
Ehsan Akhgari4103da62014-07-04 19:13:05 +0000524 void onNot() {
525 IntelExprState CurrState = State;
526 switch (State) {
527 default:
528 State = IES_ERROR;
529 break;
Coby Tayree41a5b552017-06-27 16:58:27 +0000530 case IES_OR:
531 case IES_XOR:
532 case IES_AND:
533 case IES_LSHIFT:
534 case IES_RSHIFT:
Ehsan Akhgari4103da62014-07-04 19:13:05 +0000535 case IES_PLUS:
Coby Tayree41a5b552017-06-27 16:58:27 +0000536 case IES_MINUS:
Ehsan Akhgari4103da62014-07-04 19:13:05 +0000537 case IES_NOT:
Coby Tayree41a5b552017-06-27 16:58:27 +0000538 case IES_MULTIPLY:
539 case IES_DIVIDE:
540 case IES_MOD:
541 case IES_LPAREN:
542 case IES_LBRAC:
Coby Tayreed8912892017-08-24 08:46:25 +0000543 case IES_INIT:
Ehsan Akhgari4103da62014-07-04 19:13:05 +0000544 State = IES_NOT;
Coby Tayree41a5b552017-06-27 16:58:27 +0000545 IC.pushOperator(IC_NOT);
Ehsan Akhgari4103da62014-07-04 19:13:05 +0000546 break;
547 }
548 PrevState = CurrState;
549 }
Andrew V. Tischenko32e9b1a2017-07-25 13:05:12 +0000550
551 bool onRegister(unsigned Reg, StringRef &ErrMsg) {
Chad Rosier31246272013-04-17 21:01:45 +0000552 IntelExprState CurrState = State;
Chad Rosier5362af92013-04-16 18:15:40 +0000553 switch (State) {
554 default:
555 State = IES_ERROR;
556 break;
557 case IES_PLUS:
558 case IES_LPAREN:
Coby Tayreed8912892017-08-24 08:46:25 +0000559 case IES_LBRAC:
Chad Rosier5362af92013-04-16 18:15:40 +0000560 State = IES_REGISTER;
561 TmpReg = Reg;
562 IC.pushOperand(IC_REGISTER);
563 break;
Chad Rosier31246272013-04-17 21:01:45 +0000564 case IES_MULTIPLY:
565 // Index Register - Scale * Register
566 if (PrevState == IES_INTEGER) {
Andrew V. Tischenko32e9b1a2017-07-25 13:05:12 +0000567 if (IndexReg) {
568 ErrMsg = "BaseReg/IndexReg already set!";
569 return true;
570 }
Chad Rosier31246272013-04-17 21:01:45 +0000571 State = IES_REGISTER;
572 IndexReg = Reg;
573 // Get the scale and replace the 'Scale * Register' with '0'.
574 Scale = IC.popOperand();
Andrew V. Tischenko32e9b1a2017-07-25 13:05:12 +0000575 if (checkScale(Scale, ErrMsg))
576 return true;
Chad Rosier31246272013-04-17 21:01:45 +0000577 IC.pushOperand(IC_IMM);
578 IC.popOperator();
579 } else {
580 State = IES_ERROR;
581 }
Chad Rosier5362af92013-04-16 18:15:40 +0000582 break;
583 }
Chad Rosier31246272013-04-17 21:01:45 +0000584 PrevState = CurrState;
Andrew V. Tischenko32e9b1a2017-07-25 13:05:12 +0000585 return false;
Chad Rosier5362af92013-04-16 18:15:40 +0000586 }
Coby Tayreed8912892017-08-24 08:46:25 +0000587 bool onIdentifierExpr(const MCExpr *SymRef, StringRef SymRefName,
Coby Tayreec3d24112017-09-29 07:02:46 +0000588 const InlineAsmIdentifierInfo &IDInfo,
589 bool ParsingInlineAsm, StringRef &ErrMsg) {
590 // InlineAsm: Treat an enum value as an integer
591 if (ParsingInlineAsm)
592 if (IDInfo.isKind(InlineAsmIdentifierInfo::IK_EnumVal))
593 return onInteger(IDInfo.Enum.EnumVal, ErrMsg);
594 // Treat a symbolic constant like an integer
595 if (auto *CE = dyn_cast<MCConstantExpr>(SymRef))
596 return onInteger(CE->getValue(), ErrMsg);
Chad Rosierdb003992013-04-18 16:28:19 +0000597 PrevState = State;
Coby Tayreed8912892017-08-24 08:46:25 +0000598 bool HasSymbol = Sym != nullptr;
Chad Rosier5362af92013-04-16 18:15:40 +0000599 switch (State) {
600 default:
601 State = IES_ERROR;
602 break;
603 case IES_PLUS:
604 case IES_MINUS:
Ehsan Akhgari4103da62014-07-04 19:13:05 +0000605 case IES_NOT:
Coby Tayreed8912892017-08-24 08:46:25 +0000606 case IES_INIT:
607 case IES_LBRAC:
Coby Tayreec3d24112017-09-29 07:02:46 +0000608 MemExpr = true;
Chad Rosier5362af92013-04-16 18:15:40 +0000609 State = IES_INTEGER;
610 Sym = SymRef;
611 SymName = SymRefName;
612 IC.pushOperand(IC_IMM);
Coby Tayreec3d24112017-09-29 07:02:46 +0000613 if (ParsingInlineAsm)
614 Info = IDInfo;
Chad Rosier5362af92013-04-16 18:15:40 +0000615 break;
616 }
Coby Tayreed8912892017-08-24 08:46:25 +0000617 if (HasSymbol)
618 ErrMsg = "cannot use more than one symbol in memory operand";
619 return HasSymbol;
Chad Rosier5362af92013-04-16 18:15:40 +0000620 }
Kevin Enderby9d117022014-01-23 21:52:41 +0000621 bool onInteger(int64_t TmpInt, StringRef &ErrMsg) {
Chad Rosier31246272013-04-17 21:01:45 +0000622 IntelExprState CurrState = State;
Chad Rosier5362af92013-04-16 18:15:40 +0000623 switch (State) {
624 default:
625 State = IES_ERROR;
626 break;
627 case IES_PLUS:
628 case IES_MINUS:
Ehsan Akhgari4103da62014-07-04 19:13:05 +0000629 case IES_NOT:
Kevin Enderby2e13b1c2014-01-15 19:05:24 +0000630 case IES_OR:
Michael Kupersteine3de07a2015-06-14 12:59:45 +0000631 case IES_XOR:
Kevin Enderby2e13b1c2014-01-15 19:05:24 +0000632 case IES_AND:
Kevin Enderbyd6b10712014-02-06 01:21:15 +0000633 case IES_LSHIFT:
634 case IES_RSHIFT:
Chad Rosier5362af92013-04-16 18:15:40 +0000635 case IES_DIVIDE:
Coby Tayree41a5b552017-06-27 16:58:27 +0000636 case IES_MOD:
Chad Rosier31246272013-04-17 21:01:45 +0000637 case IES_MULTIPLY:
Chad Rosier5362af92013-04-16 18:15:40 +0000638 case IES_LPAREN:
Coby Tayreed8912892017-08-24 08:46:25 +0000639 case IES_INIT:
640 case IES_LBRAC:
Chad Rosier5362af92013-04-16 18:15:40 +0000641 State = IES_INTEGER;
Chad Rosier31246272013-04-17 21:01:45 +0000642 if (PrevState == IES_REGISTER && CurrState == IES_MULTIPLY) {
643 // Index Register - Register * Scale
Andrew V. Tischenko32e9b1a2017-07-25 13:05:12 +0000644 if (IndexReg) {
645 ErrMsg = "BaseReg/IndexReg already set!";
Kevin Enderby9d117022014-01-23 21:52:41 +0000646 return true;
647 }
Andrew V. Tischenko32e9b1a2017-07-25 13:05:12 +0000648 IndexReg = TmpReg;
649 Scale = TmpInt;
650 if (checkScale(Scale, ErrMsg))
651 return true;
Chad Rosier31246272013-04-17 21:01:45 +0000652 // Get the scale and replace the 'Register * Scale' with '0'.
653 IC.popOperator();
Chad Rosier31246272013-04-17 21:01:45 +0000654 } else {
655 IC.pushOperand(IC_IMM, TmpInt);
656 }
Chad Rosier5362af92013-04-16 18:15:40 +0000657 break;
658 }
Chad Rosier31246272013-04-17 21:01:45 +0000659 PrevState = CurrState;
Kevin Enderby9d117022014-01-23 21:52:41 +0000660 return false;
Chad Rosier5362af92013-04-16 18:15:40 +0000661 }
662 void onStar() {
Chad Rosierdb003992013-04-18 16:28:19 +0000663 PrevState = State;
Chad Rosier5362af92013-04-16 18:15:40 +0000664 switch (State) {
665 default:
666 State = IES_ERROR;
667 break;
668 case IES_INTEGER:
Chad Rosier5362af92013-04-16 18:15:40 +0000669 case IES_REGISTER:
Chad Rosier5362af92013-04-16 18:15:40 +0000670 case IES_RPAREN:
671 State = IES_MULTIPLY;
672 IC.pushOperator(IC_MULTIPLY);
673 break;
674 }
675 }
676 void onDivide() {
Chad Rosierdb003992013-04-18 16:28:19 +0000677 PrevState = State;
Chad Rosier5362af92013-04-16 18:15:40 +0000678 switch (State) {
679 default:
680 State = IES_ERROR;
681 break;
682 case IES_INTEGER:
Chad Rosier31246272013-04-17 21:01:45 +0000683 case IES_RPAREN:
Chad Rosier5362af92013-04-16 18:15:40 +0000684 State = IES_DIVIDE;
685 IC.pushOperator(IC_DIVIDE);
686 break;
687 }
688 }
Coby Tayree41a5b552017-06-27 16:58:27 +0000689 void onMod() {
690 PrevState = State;
691 switch (State) {
692 default:
693 State = IES_ERROR;
694 break;
695 case IES_INTEGER:
696 case IES_RPAREN:
697 State = IES_MOD;
698 IC.pushOperator(IC_MOD);
699 break;
700 }
701 }
Coby Tayreed8912892017-08-24 08:46:25 +0000702 bool onLBrac() {
703 if (BracCount)
704 return true;
Chad Rosierdb003992013-04-18 16:28:19 +0000705 PrevState = State;
Chad Rosier5362af92013-04-16 18:15:40 +0000706 switch (State) {
707 default:
708 State = IES_ERROR;
709 break;
710 case IES_RBRAC:
Coby Tayreed8912892017-08-24 08:46:25 +0000711 case IES_INTEGER:
712 case IES_RPAREN:
Chad Rosier5362af92013-04-16 18:15:40 +0000713 State = IES_PLUS;
714 IC.pushOperator(IC_PLUS);
715 break;
Coby Tayreed8912892017-08-24 08:46:25 +0000716 case IES_INIT:
717 assert(!BracCount && "BracCount should be zero on parsing's start");
718 State = IES_LBRAC;
719 break;
Chad Rosier5362af92013-04-16 18:15:40 +0000720 }
Coby Tayreed8912892017-08-24 08:46:25 +0000721 MemExpr = true;
722 BracCount++;
723 return false;
Chad Rosier5362af92013-04-16 18:15:40 +0000724 }
Coby Tayreed8912892017-08-24 08:46:25 +0000725 bool onRBrac() {
Chad Rosier31246272013-04-17 21:01:45 +0000726 IntelExprState CurrState = State;
Chad Rosier5362af92013-04-16 18:15:40 +0000727 switch (State) {
728 default:
729 State = IES_ERROR;
730 break;
Chad Rosier5362af92013-04-16 18:15:40 +0000731 case IES_INTEGER:
Chad Rosier5362af92013-04-16 18:15:40 +0000732 case IES_REGISTER:
Chad Rosier31246272013-04-17 21:01:45 +0000733 case IES_RPAREN:
Coby Tayreed8912892017-08-24 08:46:25 +0000734 if (BracCount-- != 1)
735 return true;
Chad Rosier5362af92013-04-16 18:15:40 +0000736 State = IES_RBRAC;
Chad Rosier31246272013-04-17 21:01:45 +0000737 if (CurrState == IES_REGISTER && PrevState != IES_MULTIPLY) {
738 // If we already have a BaseReg, then assume this is the IndexReg with
739 // a scale of 1.
740 if (!BaseReg) {
741 BaseReg = TmpReg;
742 } else {
743 assert (!IndexReg && "BaseReg/IndexReg already set!");
744 IndexReg = TmpReg;
745 Scale = 1;
746 }
Chad Rosier5362af92013-04-16 18:15:40 +0000747 }
748 break;
749 }
Chad Rosier31246272013-04-17 21:01:45 +0000750 PrevState = CurrState;
Coby Tayreed8912892017-08-24 08:46:25 +0000751 return false;
Chad Rosier5362af92013-04-16 18:15:40 +0000752 }
753 void onLParen() {
Chad Rosier31246272013-04-17 21:01:45 +0000754 IntelExprState CurrState = State;
Chad Rosier5362af92013-04-16 18:15:40 +0000755 switch (State) {
756 default:
757 State = IES_ERROR;
758 break;
759 case IES_PLUS:
760 case IES_MINUS:
Ehsan Akhgari4103da62014-07-04 19:13:05 +0000761 case IES_NOT:
Kevin Enderby2e13b1c2014-01-15 19:05:24 +0000762 case IES_OR:
Michael Kupersteine3de07a2015-06-14 12:59:45 +0000763 case IES_XOR:
Kevin Enderby2e13b1c2014-01-15 19:05:24 +0000764 case IES_AND:
Kevin Enderbyd6b10712014-02-06 01:21:15 +0000765 case IES_LSHIFT:
766 case IES_RSHIFT:
Chad Rosier5362af92013-04-16 18:15:40 +0000767 case IES_MULTIPLY:
768 case IES_DIVIDE:
Coby Tayree41a5b552017-06-27 16:58:27 +0000769 case IES_MOD:
Chad Rosier5362af92013-04-16 18:15:40 +0000770 case IES_LPAREN:
Coby Tayreed8912892017-08-24 08:46:25 +0000771 case IES_INIT:
772 case IES_LBRAC:
Chad Rosier5362af92013-04-16 18:15:40 +0000773 State = IES_LPAREN;
774 IC.pushOperator(IC_LPAREN);
775 break;
776 }
Chad Rosier31246272013-04-17 21:01:45 +0000777 PrevState = CurrState;
Chad Rosier5362af92013-04-16 18:15:40 +0000778 }
779 void onRParen() {
Chad Rosierdb003992013-04-18 16:28:19 +0000780 PrevState = State;
Chad Rosier5362af92013-04-16 18:15:40 +0000781 switch (State) {
782 default:
783 State = IES_ERROR;
784 break;
Chad Rosier5362af92013-04-16 18:15:40 +0000785 case IES_INTEGER:
Chad Rosier31246272013-04-17 21:01:45 +0000786 case IES_REGISTER:
Chad Rosier5362af92013-04-16 18:15:40 +0000787 case IES_RPAREN:
788 State = IES_RPAREN;
789 IC.pushOperator(IC_RPAREN);
790 break;
791 }
792 }
793 };
794
Nirav Dave2364748a2016-09-16 18:30:20 +0000795 bool Error(SMLoc L, const Twine &Msg, SMRange Range = None,
Chad Rosier4453e842012-10-12 23:09:25 +0000796 bool MatchingInlineAsm = false) {
Rafael Espindola961d4692014-11-11 05:18:41 +0000797 MCAsmParser &Parser = getParser();
Nirav Dave2364748a2016-09-16 18:30:20 +0000798 if (MatchingInlineAsm) {
799 if (!getLexer().isAtStartOfStatement())
800 Parser.eatToEndOfStatement();
801 return false;
802 }
803 return Parser.Error(L, Msg, Range);
Elena Demikhovskyc9657012014-02-20 06:34:39 +0000804 }
805
David Blaikie960ea3f2014-06-08 16:18:35 +0000806 std::nullptr_t ErrorOperand(SMLoc Loc, StringRef Msg) {
Devang Patel41b9dde2012-01-17 18:00:18 +0000807 Error(Loc, Msg);
Craig Topper062a2ba2014-04-25 05:30:21 +0000808 return nullptr;
Devang Patel41b9dde2012-01-17 18:00:18 +0000809 }
810
David Blaikie960ea3f2014-06-08 16:18:35 +0000811 std::unique_ptr<X86Operand> DefaultMemSIOperand(SMLoc Loc);
812 std::unique_ptr<X86Operand> DefaultMemDIOperand(SMLoc Loc);
Marina Yatsinab9f4f622016-01-19 15:37:56 +0000813 bool IsSIReg(unsigned Reg);
814 unsigned GetSIDIForRegClass(unsigned RegClassID, unsigned Reg, bool IsSIReg);
815 void
816 AddDefaultSrcDestOperands(OperandVector &Operands,
817 std::unique_ptr<llvm::MCParsedAsmOperand> &&Src,
818 std::unique_ptr<llvm::MCParsedAsmOperand> &&Dst);
819 bool VerifyAndAdjustOperands(OperandVector &OrigOperands,
820 OperandVector &FinalOperands);
David Blaikie960ea3f2014-06-08 16:18:35 +0000821 std::unique_ptr<X86Operand> ParseOperand();
822 std::unique_ptr<X86Operand> ParseATTOperand();
823 std::unique_ptr<X86Operand> ParseIntelOperand();
824 std::unique_ptr<X86Operand> ParseIntelOffsetOfOperator();
Coby Tayreed8912892017-08-24 08:46:25 +0000825 bool ParseIntelDotOperator(IntelExprStateMachine &SM, SMLoc &End);
826 unsigned IdentifyIntelInlineAsmOperator(StringRef Name);
827 unsigned ParseIntelInlineAsmOperator(unsigned OpKind);
Elena Demikhovsky18fd4962015-03-02 15:00:34 +0000828 std::unique_ptr<X86Operand> ParseRoundingModeOp(SMLoc Start, SMLoc End);
Coby Tayree2cb497a2017-04-04 14:43:23 +0000829 bool ParseIntelNamedOperator(StringRef Name, IntelExprStateMachine &SM);
Coby Tayreed8912892017-08-24 08:46:25 +0000830 void RewriteIntelExpression(IntelExprStateMachine &SM, SMLoc Start,
831 SMLoc End);
Benjamin Kramer951b15e2013-12-01 11:47:42 +0000832 bool ParseIntelExpression(IntelExprStateMachine &SM, SMLoc &End);
Coby Tayreed8912892017-08-24 08:46:25 +0000833 bool ParseIntelInlineAsmIdentifier(const MCExpr *&Val, StringRef &Identifier,
834 InlineAsmIdentifierInfo &Info,
835 bool IsUnevaluatedOperand, SMLoc &End);
Chad Rosiercb78f0d2013-04-22 19:42:15 +0000836
David Blaikie960ea3f2014-06-08 16:18:35 +0000837 std::unique_ptr<X86Operand> ParseMemOperand(unsigned SegReg, SMLoc StartLoc);
Kevin Enderbyce4bec82009-09-10 20:51:44 +0000838
Coby Tayreed8912892017-08-24 08:46:25 +0000839 bool ParseIntelMemoryOperandSize(unsigned &Size);
David Blaikie960ea3f2014-06-08 16:18:35 +0000840 std::unique_ptr<X86Operand>
841 CreateMemForInlineAsm(unsigned SegReg, const MCExpr *Disp, unsigned BaseReg,
842 unsigned IndexReg, unsigned Scale, SMLoc Start,
843 SMLoc End, unsigned Size, StringRef Identifier,
Coby Tayreeef66b3b2017-09-10 12:21:24 +0000844 const InlineAsmIdentifierInfo &Info);
Chad Rosier7ca135b2013-03-19 21:11:56 +0000845
Michael Zuckerman02ecd432015-12-13 17:07:23 +0000846 bool parseDirectiveEven(SMLoc L);
Kevin Enderbyce4bec82009-09-10 20:51:44 +0000847 bool ParseDirectiveWord(unsigned Size, SMLoc L);
Evan Cheng481ebb02011-07-27 00:38:12 +0000848 bool ParseDirectiveCode(StringRef IDVal, SMLoc L);
Kevin Enderbyce4bec82009-09-10 20:51:44 +0000849
Reid Kleckner9cdd4df2017-10-11 21:24:33 +0000850 /// CodeView FPO data directives.
851 bool parseDirectiveFPOProc(SMLoc L);
852 bool parseDirectiveFPOSetFrame(SMLoc L);
853 bool parseDirectiveFPOPushReg(SMLoc L);
854 bool parseDirectiveFPOStackAlloc(SMLoc L);
855 bool parseDirectiveFPOEndPrologue(SMLoc L);
856 bool parseDirectiveFPOEndProc(SMLoc L);
857 bool parseDirectiveFPOData(SMLoc L);
858
David Blaikie960ea3f2014-06-08 16:18:35 +0000859 bool processInstruction(MCInst &Inst, const OperandVector &Ops);
Devang Patelde47cce2012-01-18 22:42:29 +0000860
Evgeniy Stepanov49e26252014-03-14 08:58:04 +0000861 /// Wrapper around MCStreamer::EmitInstruction(). Possibly adds
862 /// instrumentation around Inst.
David Blaikie960ea3f2014-06-08 16:18:35 +0000863 void EmitInstruction(MCInst &Inst, OperandVector &Operands, MCStreamer &Out);
Evgeniy Stepanov49e26252014-03-14 08:58:04 +0000864
Chad Rosier49963552012-10-13 00:26:04 +0000865 bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
David Blaikie960ea3f2014-06-08 16:18:35 +0000866 OperandVector &Operands, MCStreamer &Out,
Tim Northover26bb14e2014-08-18 11:49:42 +0000867 uint64_t &ErrorInfo,
Craig Topper39012cc2014-03-09 18:03:14 +0000868 bool MatchingInlineAsm) override;
Chad Rosier9cb988f2012-08-09 22:04:55 +0000869
Reid Klecknerf6fb7802014-08-26 20:32:34 +0000870 void MatchFPUWaitAlias(SMLoc IDLoc, X86Operand &Op, OperandVector &Operands,
871 MCStreamer &Out, bool MatchingInlineAsm);
872
Ranjeet Singh86ecbb72015-06-30 12:32:53 +0000873 bool ErrorMissingFeature(SMLoc IDLoc, uint64_t ErrorInfo,
Reid Klecknerf6fb7802014-08-26 20:32:34 +0000874 bool MatchingInlineAsm);
875
876 bool MatchAndEmitATTInstruction(SMLoc IDLoc, unsigned &Opcode,
877 OperandVector &Operands, MCStreamer &Out,
878 uint64_t &ErrorInfo,
879 bool MatchingInlineAsm);
880
881 bool MatchAndEmitIntelInstruction(SMLoc IDLoc, unsigned &Opcode,
882 OperandVector &Operands, MCStreamer &Out,
883 uint64_t &ErrorInfo,
884 bool MatchingInlineAsm);
885
Craig Topperfd38cbe2014-08-30 16:48:34 +0000886 bool OmitRegisterFromClobberLists(unsigned RegNo) override;
Nico Weber42f79db2014-07-17 20:24:55 +0000887
Elena Demikhovskyc9657012014-02-20 06:34:39 +0000888 /// Parses AVX512 specific operand primitives: masked registers ({%k<NUM>}, {z})
889 /// and memory broadcasting ({1to<NUM>}) primitives, updating Operands vector if required.
Michael Zuckerman1bee6342016-10-18 13:52:39 +0000890 /// return false if no parsing errors occurred, true otherwise.
David Blaikie960ea3f2014-06-08 16:18:35 +0000891 bool HandleAVX512Operand(OperandVector &Operands,
892 const MCParsedAsmOperand &Op);
Elena Demikhovskyc9657012014-02-20 06:34:39 +0000893
Michael Zuckerman1bee6342016-10-18 13:52:39 +0000894 bool ParseZ(std::unique_ptr<X86Operand> &Z, const SMLoc &StartLoc);
895
Evan Chengc5e6d2f2011-07-11 03:57:24 +0000896 bool is64BitMode() const {
Evan Cheng4d1ca962011-07-08 01:53:10 +0000897 // FIXME: Can tablegen auto-generate this?
Akira Hatanakabd9fc282015-11-14 05:20:05 +0000898 return getSTI().getFeatureBits()[X86::Mode64Bit];
Evan Cheng4d1ca962011-07-08 01:53:10 +0000899 }
Craig Topper3c80d622014-01-06 04:55:54 +0000900 bool is32BitMode() const {
901 // FIXME: Can tablegen auto-generate this?
Akira Hatanakabd9fc282015-11-14 05:20:05 +0000902 return getSTI().getFeatureBits()[X86::Mode32Bit];
Craig Topper3c80d622014-01-06 04:55:54 +0000903 }
904 bool is16BitMode() const {
905 // FIXME: Can tablegen auto-generate this?
Akira Hatanakabd9fc282015-11-14 05:20:05 +0000906 return getSTI().getFeatureBits()[X86::Mode16Bit];
Craig Topper3c80d622014-01-06 04:55:54 +0000907 }
Michael Kupersteindb0712f2015-05-26 10:47:10 +0000908 void SwitchMode(unsigned mode) {
Akira Hatanakab11ef082015-11-14 06:35:56 +0000909 MCSubtargetInfo &STI = copySTI();
Michael Kupersteindb0712f2015-05-26 10:47:10 +0000910 FeatureBitset AllModes({X86::Mode64Bit, X86::Mode32Bit, X86::Mode16Bit});
911 FeatureBitset OldMode = STI.getFeatureBits() & AllModes;
Ranjeet Singh86ecbb72015-06-30 12:32:53 +0000912 unsigned FB = ComputeAvailableFeatures(
Michael Kupersteindb0712f2015-05-26 10:47:10 +0000913 STI.ToggleFeature(OldMode.flip(mode)));
Evan Cheng481ebb02011-07-27 00:38:12 +0000914 setAvailableFeatures(FB);
NAKAMURA Takumia9cb5382015-09-22 11:14:39 +0000915
Michael Kupersteindb0712f2015-05-26 10:47:10 +0000916 assert(FeatureBitset({mode}) == (STI.getFeatureBits() & AllModes));
Evan Cheng481ebb02011-07-27 00:38:12 +0000917 }
Evan Cheng4d1ca962011-07-08 01:53:10 +0000918
Reid Kleckner5b37c182014-08-01 20:21:24 +0000919 unsigned getPointerWidth() {
920 if (is16BitMode()) return 16;
921 if (is32BitMode()) return 32;
922 if (is64BitMode()) return 64;
923 llvm_unreachable("invalid mode");
924 }
925
Chad Rosierc2f055d2013-04-18 16:13:18 +0000926 bool isParsingIntelSyntax() {
927 return getParser().getAssemblerDialect();
928 }
929
Daniel Dunbareefe8612010-07-19 05:44:09 +0000930 /// @name Auto-generated Matcher Functions
931 /// {
Michael J. Spencer530ce852010-10-09 11:00:50 +0000932
Chris Lattner3e4582a2010-09-06 19:11:01 +0000933#define GET_ASSEMBLER_HEADER
934#include "X86GenAsmMatcher.inc"
Michael J. Spencer530ce852010-10-09 11:00:50 +0000935
Daniel Dunbar00331992009-07-29 00:02:19 +0000936 /// }
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +0000937
938public:
Coby Tayree07a89742017-03-21 19:31:55 +0000939
Akira Hatanakab11ef082015-11-14 06:35:56 +0000940 X86AsmParser(const MCSubtargetInfo &sti, MCAsmParser &Parser,
Rafael Espindola961d4692014-11-11 05:18:41 +0000941 const MCInstrInfo &mii, const MCTargetOptions &Options)
Oliver Stannard4191b9e2017-10-11 09:17:43 +0000942 : MCTargetAsmParser(Options, sti, mii), InstInfo(nullptr),
Nirav Dave6477ce22016-09-26 19:33:36 +0000943 Code16GCC(false) {
Michael J. Spencer530ce852010-10-09 11:00:50 +0000944
Daniel Dunbareefe8612010-07-19 05:44:09 +0000945 // Initialize the set of available features.
Akira Hatanakabd9fc282015-11-14 05:20:05 +0000946 setAvailableFeatures(ComputeAvailableFeatures(getSTI().getFeatureBits()));
Evgeniy Stepanov0a951b72014-04-23 11:16:03 +0000947 Instrumentation.reset(
948 CreateX86AsmInstrumentation(Options, Parser.getContext(), STI));
Daniel Dunbareefe8612010-07-19 05:44:09 +0000949 }
Evgeniy Stepanov0a951b72014-04-23 11:16:03 +0000950
Craig Topper39012cc2014-03-09 18:03:14 +0000951 bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc) override;
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +0000952
Yuri Gorshenin3939dec2014-09-10 09:45:49 +0000953 void SetFrameRegister(unsigned RegNo) override;
954
David Blaikie960ea3f2014-06-08 16:18:35 +0000955 bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
956 SMLoc NameLoc, OperandVector &Operands) override;
Kevin Enderbyce4bec82009-09-10 20:51:44 +0000957
Craig Topper39012cc2014-03-09 18:03:14 +0000958 bool ParseDirective(AsmToken DirectiveID) override;
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +0000959};
Chris Lattner4eb9df02009-07-29 06:33:53 +0000960} // end anonymous namespace
961
Sean Callanan86c11812010-01-23 00:40:33 +0000962/// @name Auto-generated Match Functions
Bruno Cardoso Lopesd65cd1d2010-07-23 22:15:26 +0000963/// {
Sean Callanan86c11812010-01-23 00:40:33 +0000964
Chris Lattner60db0a62010-02-09 00:34:28 +0000965static unsigned MatchRegisterName(StringRef Name);
Sean Callanan86c11812010-01-23 00:40:33 +0000966
967/// }
Chris Lattner4eb9df02009-07-29 06:33:53 +0000968
Andrew V. Tischenko32e9b1a2017-07-25 13:05:12 +0000969static bool CheckBaseRegAndIndexRegAndScale(unsigned BaseReg, unsigned IndexReg,
970 unsigned Scale, StringRef &ErrMsg) {
Kevin Enderbybc570f22014-01-23 22:34:42 +0000971 // If we have both a base register and an index register make sure they are
972 // both 64-bit or 32-bit registers.
973 // To support VSIB, IndexReg can be 128-bit or 256-bit registers.
Douglas Katzman0411e862016-10-05 15:23:35 +0000974
975 if ((BaseReg == X86::RIP && IndexReg != 0) || (IndexReg == X86::RIP)) {
976 ErrMsg = "invalid base+index expression";
977 return true;
978 }
Kevin Enderbybc570f22014-01-23 22:34:42 +0000979 if (BaseReg != 0 && IndexReg != 0) {
980 if (X86MCRegisterClasses[X86::GR64RegClassID].contains(BaseReg) &&
981 (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) ||
982 X86MCRegisterClasses[X86::GR32RegClassID].contains(IndexReg)) &&
983 IndexReg != X86::RIZ) {
984 ErrMsg = "base register is 64-bit, but index register is not";
985 return true;
986 }
987 if (X86MCRegisterClasses[X86::GR32RegClassID].contains(BaseReg) &&
988 (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) ||
989 X86MCRegisterClasses[X86::GR64RegClassID].contains(IndexReg)) &&
990 IndexReg != X86::EIZ){
991 ErrMsg = "base register is 32-bit, but index register is not";
992 return true;
993 }
994 if (X86MCRegisterClasses[X86::GR16RegClassID].contains(BaseReg)) {
995 if (X86MCRegisterClasses[X86::GR32RegClassID].contains(IndexReg) ||
996 X86MCRegisterClasses[X86::GR64RegClassID].contains(IndexReg)) {
997 ErrMsg = "base register is 16-bit, but index register is not";
998 return true;
999 }
1000 if (((BaseReg == X86::BX || BaseReg == X86::BP) &&
1001 IndexReg != X86::SI && IndexReg != X86::DI) ||
1002 ((BaseReg == X86::SI || BaseReg == X86::DI) &&
1003 IndexReg != X86::BX && IndexReg != X86::BP)) {
1004 ErrMsg = "invalid 16-bit base/index register combination";
1005 return true;
1006 }
1007 }
1008 }
Andrew V. Tischenko32e9b1a2017-07-25 13:05:12 +00001009 return checkScale(Scale, ErrMsg);
Kevin Enderbybc570f22014-01-23 22:34:42 +00001010}
1011
Devang Patel4a6e7782012-01-12 18:03:40 +00001012bool X86AsmParser::ParseRegister(unsigned &RegNo,
1013 SMLoc &StartLoc, SMLoc &EndLoc) {
Rafael Espindola961d4692014-11-11 05:18:41 +00001014 MCAsmParser &Parser = getParser();
Chris Lattnercc2ad082010-01-15 18:27:19 +00001015 RegNo = 0;
Benjamin Kramere3d658b2012-09-07 14:51:35 +00001016 const AsmToken &PercentTok = Parser.getTok();
1017 StartLoc = PercentTok.getLoc();
1018
1019 // If we encounter a %, ignore it. This code handles registers with and
1020 // without the prefix, unprefixed registers can occur in cfi directives.
1021 if (!isParsingIntelSyntax() && PercentTok.is(AsmToken::Percent))
Devang Patel41b9dde2012-01-17 18:00:18 +00001022 Parser.Lex(); // Eat percent token.
Kevin Enderby7d912182009-09-03 17:15:07 +00001023
Sean Callanan936b0d32010-01-19 21:44:56 +00001024 const AsmToken &Tok = Parser.getTok();
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001025 EndLoc = Tok.getEndLoc();
1026
Devang Patelce6a2ca2012-01-20 22:32:05 +00001027 if (Tok.isNot(AsmToken::Identifier)) {
Reid Klecknerc990b5d2017-07-24 20:48:15 +00001028 if (isParsingIntelSyntax()) return true;
Benjamin Kramer1930b002011-10-16 12:10:27 +00001029 return Error(StartLoc, "invalid register name",
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001030 SMRange(StartLoc, EndLoc));
Devang Patelce6a2ca2012-01-20 22:32:05 +00001031 }
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +00001032
Kevin Enderby7d912182009-09-03 17:15:07 +00001033 RegNo = MatchRegisterName(Tok.getString());
Bruno Cardoso Lopesd65cd1d2010-07-23 22:15:26 +00001034
Chris Lattner1261b812010-09-22 04:11:10 +00001035 // If the match failed, try the register name as lowercase.
1036 if (RegNo == 0)
Benjamin Kramer20baffb2011-11-06 20:37:06 +00001037 RegNo = MatchRegisterName(Tok.getString().lower());
Michael J. Spencer530ce852010-10-09 11:00:50 +00001038
Michael Kupersteincdb076b2015-07-30 10:10:25 +00001039 // The "flags" register cannot be referenced directly.
1040 // Treat it as an identifier instead.
1041 if (isParsingInlineAsm() && isParsingIntelSyntax() && RegNo == X86::EFLAGS)
1042 RegNo = 0;
1043
Evan Chengeda1d4f2011-07-27 23:22:03 +00001044 if (!is64BitMode()) {
Eric Christopherc0a5aae2013-12-20 02:04:49 +00001045 // FIXME: This should be done using Requires<Not64BitMode> and
Evan Chengeda1d4f2011-07-27 23:22:03 +00001046 // Requires<In64BitMode> so "eiz" usage in 64-bit instructions can be also
1047 // checked.
1048 // FIXME: Check AH, CH, DH, BH cannot be used in an instruction requiring a
1049 // REX prefix.
1050 if (RegNo == X86::RIZ ||
1051 X86MCRegisterClasses[X86::GR64RegClassID].contains(RegNo) ||
1052 X86II::isX86_64NonExtLowByteReg(RegNo) ||
Craig Topper6acca802016-08-27 17:13:37 +00001053 X86II::isX86_64ExtendedReg(RegNo))
Benjamin Kramer1930b002011-10-16 12:10:27 +00001054 return Error(StartLoc, "register %"
1055 + Tok.getString() + " is only available in 64-bit mode",
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001056 SMRange(StartLoc, EndLoc));
Craig Topper29c22732016-02-26 05:29:32 +00001057 } else if (!getSTI().getFeatureBits()[X86::FeatureAVX512]) {
1058 if (X86II::is32ExtendedReg(RegNo))
1059 return Error(StartLoc, "register %"
Craig Topperd50b5f82016-02-26 06:50:24 +00001060 + Tok.getString() + " is only available with AVX512",
Craig Topper29c22732016-02-26 05:29:32 +00001061 SMRange(StartLoc, EndLoc));
Evan Chengeda1d4f2011-07-27 23:22:03 +00001062 }
Bruno Cardoso Lopes306a1f92010-07-24 00:06:39 +00001063
Chris Lattner1261b812010-09-22 04:11:10 +00001064 // Parse "%st" as "%st(0)" and "%st(1)", which is multiple tokens.
1065 if (RegNo == 0 && (Tok.getString() == "st" || Tok.getString() == "ST")) {
Chris Lattnerd00faaa2010-02-09 00:49:22 +00001066 RegNo = X86::ST0;
Chris Lattnerd00faaa2010-02-09 00:49:22 +00001067 Parser.Lex(); // Eat 'st'
Bruno Cardoso Lopesd65cd1d2010-07-23 22:15:26 +00001068
Chris Lattnerd00faaa2010-02-09 00:49:22 +00001069 // Check to see if we have '(4)' after %st.
1070 if (getLexer().isNot(AsmToken::LParen))
1071 return false;
1072 // Lex the paren.
1073 getParser().Lex();
1074
1075 const AsmToken &IntTok = Parser.getTok();
1076 if (IntTok.isNot(AsmToken::Integer))
1077 return Error(IntTok.getLoc(), "expected stack index");
1078 switch (IntTok.getIntVal()) {
1079 case 0: RegNo = X86::ST0; break;
1080 case 1: RegNo = X86::ST1; break;
1081 case 2: RegNo = X86::ST2; break;
1082 case 3: RegNo = X86::ST3; break;
1083 case 4: RegNo = X86::ST4; break;
1084 case 5: RegNo = X86::ST5; break;
1085 case 6: RegNo = X86::ST6; break;
1086 case 7: RegNo = X86::ST7; break;
1087 default: return Error(IntTok.getLoc(), "invalid stack index");
1088 }
Bruno Cardoso Lopesd65cd1d2010-07-23 22:15:26 +00001089
Chris Lattnerd00faaa2010-02-09 00:49:22 +00001090 if (getParser().Lex().isNot(AsmToken::RParen))
1091 return Error(Parser.getTok().getLoc(), "expected ')'");
Bruno Cardoso Lopesd65cd1d2010-07-23 22:15:26 +00001092
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001093 EndLoc = Parser.getTok().getEndLoc();
Chris Lattnerd00faaa2010-02-09 00:49:22 +00001094 Parser.Lex(); // Eat ')'
1095 return false;
1096 }
Bruno Cardoso Lopesd65cd1d2010-07-23 22:15:26 +00001097
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001098 EndLoc = Parser.getTok().getEndLoc();
1099
Chris Lattner80486622010-06-24 07:29:18 +00001100 // If this is "db[0-7]", match it as an alias
1101 // for dr[0-7].
1102 if (RegNo == 0 && Tok.getString().size() == 3 &&
1103 Tok.getString().startswith("db")) {
1104 switch (Tok.getString()[2]) {
1105 case '0': RegNo = X86::DR0; break;
1106 case '1': RegNo = X86::DR1; break;
1107 case '2': RegNo = X86::DR2; break;
1108 case '3': RegNo = X86::DR3; break;
1109 case '4': RegNo = X86::DR4; break;
1110 case '5': RegNo = X86::DR5; break;
1111 case '6': RegNo = X86::DR6; break;
1112 case '7': RegNo = X86::DR7; break;
1113 }
Bruno Cardoso Lopesd65cd1d2010-07-23 22:15:26 +00001114
Chris Lattner80486622010-06-24 07:29:18 +00001115 if (RegNo != 0) {
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001116 EndLoc = Parser.getTok().getEndLoc();
Chris Lattner80486622010-06-24 07:29:18 +00001117 Parser.Lex(); // Eat it.
1118 return false;
1119 }
1120 }
Bruno Cardoso Lopesd65cd1d2010-07-23 22:15:26 +00001121
Devang Patelce6a2ca2012-01-20 22:32:05 +00001122 if (RegNo == 0) {
Devang Patel9a9bb5c2012-01-30 20:02:42 +00001123 if (isParsingIntelSyntax()) return true;
Benjamin Kramer1930b002011-10-16 12:10:27 +00001124 return Error(StartLoc, "invalid register name",
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001125 SMRange(StartLoc, EndLoc));
Devang Patelce6a2ca2012-01-20 22:32:05 +00001126 }
Daniel Dunbar00331992009-07-29 00:02:19 +00001127
Sean Callanana83fd7d2010-01-19 20:27:46 +00001128 Parser.Lex(); // Eat identifier token.
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +00001129 return false;
Daniel Dunbar71475772009-07-17 20:42:00 +00001130}
1131
Yuri Gorshenin3939dec2014-09-10 09:45:49 +00001132void X86AsmParser::SetFrameRegister(unsigned RegNo) {
Yuri Gorshenine8c81fd2014-10-07 11:03:09 +00001133 Instrumentation->SetInitialFrameRegister(RegNo);
Yuri Gorshenin3939dec2014-09-10 09:45:49 +00001134}
1135
David Blaikie960ea3f2014-06-08 16:18:35 +00001136std::unique_ptr<X86Operand> X86AsmParser::DefaultMemSIOperand(SMLoc Loc) {
Nirav Dave6477ce22016-09-26 19:33:36 +00001137 bool Parse32 = is32BitMode() || Code16GCC;
1138 unsigned Basereg = is64BitMode() ? X86::RSI : (Parse32 ? X86::ESI : X86::SI);
Jim Grosbach13760bd2015-05-30 01:25:56 +00001139 const MCExpr *Disp = MCConstantExpr::create(0, getContext());
Craig Topper055845f2015-01-02 07:02:25 +00001140 return X86Operand::CreateMem(getPointerWidth(), /*SegReg=*/0, Disp,
Nirav Dave6477ce22016-09-26 19:33:36 +00001141 /*BaseReg=*/Basereg, /*IndexReg=*/0, /*Scale=*/1,
Craig Topper055845f2015-01-02 07:02:25 +00001142 Loc, Loc, 0);
David Woodhouse2ef8d9c2014-01-22 15:08:08 +00001143}
1144
David Blaikie960ea3f2014-06-08 16:18:35 +00001145std::unique_ptr<X86Operand> X86AsmParser::DefaultMemDIOperand(SMLoc Loc) {
Nirav Dave6477ce22016-09-26 19:33:36 +00001146 bool Parse32 = is32BitMode() || Code16GCC;
1147 unsigned Basereg = is64BitMode() ? X86::RDI : (Parse32 ? X86::EDI : X86::DI);
Jim Grosbach13760bd2015-05-30 01:25:56 +00001148 const MCExpr *Disp = MCConstantExpr::create(0, getContext());
Craig Topper055845f2015-01-02 07:02:25 +00001149 return X86Operand::CreateMem(getPointerWidth(), /*SegReg=*/0, Disp,
Nirav Dave6477ce22016-09-26 19:33:36 +00001150 /*BaseReg=*/Basereg, /*IndexReg=*/0, /*Scale=*/1,
Craig Topper055845f2015-01-02 07:02:25 +00001151 Loc, Loc, 0);
David Woodhouseb33c2ef2014-01-22 15:08:21 +00001152}
1153
Marina Yatsinab9f4f622016-01-19 15:37:56 +00001154bool X86AsmParser::IsSIReg(unsigned Reg) {
1155 switch (Reg) {
Craig Topper4d187632016-02-26 05:29:39 +00001156 default: llvm_unreachable("Only (R|E)SI and (R|E)DI are expected!");
Marina Yatsinab9f4f622016-01-19 15:37:56 +00001157 case X86::RSI:
1158 case X86::ESI:
1159 case X86::SI:
1160 return true;
1161 case X86::RDI:
1162 case X86::EDI:
1163 case X86::DI:
1164 return false;
1165 }
1166}
1167
1168unsigned X86AsmParser::GetSIDIForRegClass(unsigned RegClassID, unsigned Reg,
1169 bool IsSIReg) {
1170 switch (RegClassID) {
Craig Topper4d187632016-02-26 05:29:39 +00001171 default: llvm_unreachable("Unexpected register class");
Marina Yatsinab9f4f622016-01-19 15:37:56 +00001172 case X86::GR64RegClassID:
1173 return IsSIReg ? X86::RSI : X86::RDI;
1174 case X86::GR32RegClassID:
1175 return IsSIReg ? X86::ESI : X86::EDI;
1176 case X86::GR16RegClassID:
1177 return IsSIReg ? X86::SI : X86::DI;
1178 }
1179}
1180
Michael Kupersteinffcc7662015-07-23 10:23:48 +00001181void X86AsmParser::AddDefaultSrcDestOperands(
1182 OperandVector& Operands, std::unique_ptr<llvm::MCParsedAsmOperand> &&Src,
1183 std::unique_ptr<llvm::MCParsedAsmOperand> &&Dst) {
1184 if (isParsingIntelSyntax()) {
1185 Operands.push_back(std::move(Dst));
1186 Operands.push_back(std::move(Src));
1187 }
1188 else {
1189 Operands.push_back(std::move(Src));
1190 Operands.push_back(std::move(Dst));
1191 }
1192}
1193
Marina Yatsinab9f4f622016-01-19 15:37:56 +00001194bool X86AsmParser::VerifyAndAdjustOperands(OperandVector &OrigOperands,
1195 OperandVector &FinalOperands) {
1196
1197 if (OrigOperands.size() > 1) {
Craig Topperd55f4bc2016-02-16 07:45:07 +00001198 // Check if sizes match, OrigOperands also contains the instruction name
Marina Yatsinab9f4f622016-01-19 15:37:56 +00001199 assert(OrigOperands.size() == FinalOperands.size() + 1 &&
Craig Topperd55f4bc2016-02-16 07:45:07 +00001200 "Operand size mismatch");
Marina Yatsinab9f4f622016-01-19 15:37:56 +00001201
Marina Yatsinaff262fa2016-01-21 11:37:06 +00001202 SmallVector<std::pair<SMLoc, std::string>, 2> Warnings;
Marina Yatsinab9f4f622016-01-19 15:37:56 +00001203 // Verify types match
1204 int RegClassID = -1;
1205 for (unsigned int i = 0; i < FinalOperands.size(); ++i) {
1206 X86Operand &OrigOp = static_cast<X86Operand &>(*OrigOperands[i + 1]);
1207 X86Operand &FinalOp = static_cast<X86Operand &>(*FinalOperands[i]);
1208
1209 if (FinalOp.isReg() &&
1210 (!OrigOp.isReg() || FinalOp.getReg() != OrigOp.getReg()))
1211 // Return false and let a normal complaint about bogus operands happen
1212 return false;
1213
1214 if (FinalOp.isMem()) {
1215
1216 if (!OrigOp.isMem())
1217 // Return false and let a normal complaint about bogus operands happen
1218 return false;
1219
1220 unsigned OrigReg = OrigOp.Mem.BaseReg;
1221 unsigned FinalReg = FinalOp.Mem.BaseReg;
1222
1223 // If we've already encounterd a register class, make sure all register
1224 // bases are of the same register class
1225 if (RegClassID != -1 &&
1226 !X86MCRegisterClasses[RegClassID].contains(OrigReg)) {
1227 return Error(OrigOp.getStartLoc(),
1228 "mismatching source and destination index registers");
1229 }
1230
1231 if (X86MCRegisterClasses[X86::GR64RegClassID].contains(OrigReg))
1232 RegClassID = X86::GR64RegClassID;
1233 else if (X86MCRegisterClasses[X86::GR32RegClassID].contains(OrigReg))
1234 RegClassID = X86::GR32RegClassID;
1235 else if (X86MCRegisterClasses[X86::GR16RegClassID].contains(OrigReg))
1236 RegClassID = X86::GR16RegClassID;
Marina Yatsina701938d2016-01-20 14:03:47 +00001237 else
Craig Topper5a62f7e2016-02-16 07:28:03 +00001238 // Unexpected register class type
Marina Yatsina701938d2016-01-20 14:03:47 +00001239 // Return false and let a normal complaint about bogus operands happen
1240 return false;
Marina Yatsinab9f4f622016-01-19 15:37:56 +00001241
1242 bool IsSI = IsSIReg(FinalReg);
1243 FinalReg = GetSIDIForRegClass(RegClassID, FinalReg, IsSI);
1244
1245 if (FinalReg != OrigReg) {
1246 std::string RegName = IsSI ? "ES:(R|E)SI" : "ES:(R|E)DI";
Marina Yatsinaff262fa2016-01-21 11:37:06 +00001247 Warnings.push_back(std::make_pair(
1248 OrigOp.getStartLoc(),
1249 "memory operand is only for determining the size, " + RegName +
1250 " will be used for the location"));
Marina Yatsinab9f4f622016-01-19 15:37:56 +00001251 }
1252
1253 FinalOp.Mem.Size = OrigOp.Mem.Size;
1254 FinalOp.Mem.SegReg = OrigOp.Mem.SegReg;
1255 FinalOp.Mem.BaseReg = FinalReg;
1256 }
1257 }
1258
Marina Yatsinaff262fa2016-01-21 11:37:06 +00001259 // Produce warnings only if all the operands passed the adjustment - prevent
1260 // legal cases like "movsd (%rax), %xmm0" mistakenly produce warnings
Craig Topper16d7eb22016-02-16 07:45:04 +00001261 for (auto &WarningMsg : Warnings) {
1262 Warning(WarningMsg.first, WarningMsg.second);
Marina Yatsinaff262fa2016-01-21 11:37:06 +00001263 }
1264
1265 // Remove old operands
Marina Yatsinab9f4f622016-01-19 15:37:56 +00001266 for (unsigned int i = 0; i < FinalOperands.size(); ++i)
1267 OrigOperands.pop_back();
1268 }
1269 // OrigOperands.append(FinalOperands.begin(), FinalOperands.end());
1270 for (unsigned int i = 0; i < FinalOperands.size(); ++i)
1271 OrigOperands.push_back(std::move(FinalOperands[i]));
1272
1273 return false;
1274}
1275
David Blaikie960ea3f2014-06-08 16:18:35 +00001276std::unique_ptr<X86Operand> X86AsmParser::ParseOperand() {
Devang Patel9a9bb5c2012-01-30 20:02:42 +00001277 if (isParsingIntelSyntax())
Devang Patel46831de2012-01-12 01:36:43 +00001278 return ParseIntelOperand();
1279 return ParseATTOperand();
1280}
1281
David Blaikie960ea3f2014-06-08 16:18:35 +00001282std::unique_ptr<X86Operand> X86AsmParser::CreateMemForInlineAsm(
1283 unsigned SegReg, const MCExpr *Disp, unsigned BaseReg, unsigned IndexReg,
1284 unsigned Scale, SMLoc Start, SMLoc End, unsigned Size, StringRef Identifier,
Coby Tayreeef66b3b2017-09-10 12:21:24 +00001285 const InlineAsmIdentifierInfo &Info) {
Reid Kleckner5b37c182014-08-01 20:21:24 +00001286 // If we found a decl other than a VarDecl, then assume it is a FuncDecl or
1287 // some other label reference.
Coby Tayreec3d24112017-09-29 07:02:46 +00001288 if (Info.isKind(InlineAsmIdentifierInfo::IK_Label)) {
Reid Kleckner5b37c182014-08-01 20:21:24 +00001289 // Insert an explicit size if the user didn't have one.
1290 if (!Size) {
1291 Size = getPointerWidth();
Craig Topper7d5b2312015-10-10 05:25:02 +00001292 InstInfo->AsmRewrites->emplace_back(AOK_SizeDirective, Start,
1293 /*Len=*/0, Size);
Reid Kleckner5b37c182014-08-01 20:21:24 +00001294 }
Reid Kleckner5b37c182014-08-01 20:21:24 +00001295 // Create an absolute memory reference in order to match against
1296 // instructions taking a PC relative operand.
Craig Topper055845f2015-01-02 07:02:25 +00001297 return X86Operand::CreateMem(getPointerWidth(), Disp, Start, End, Size,
Coby Tayreec3d24112017-09-29 07:02:46 +00001298 Identifier, Info.Label.Decl);
Reid Klecknerd84e70e2014-03-04 00:33:17 +00001299 }
Reid Klecknerd84e70e2014-03-04 00:33:17 +00001300 // We either have a direct symbol reference, or an offset from a symbol. The
1301 // parser always puts the symbol on the LHS, so look there for size
1302 // calculation purposes.
Reid Kleckner6d2ea6e2017-05-04 18:19:52 +00001303 unsigned FrontendSize = 0;
Coby Tayreec3d24112017-09-29 07:02:46 +00001304 void *Decl = nullptr;
1305 bool IsGlobalLV = false;
1306 if (Info.isKind(InlineAsmIdentifierInfo::IK_Var)) {
1307 // Size is in terms of bits in this context.
1308 FrontendSize = Info.Var.Type * 8;
1309 Decl = Info.Var.Decl;
1310 IsGlobalLV = Info.Var.IsGlobalLV;
1311 }
1312 // It is widely common for MS InlineAsm to use a global variable and one/two
1313 // registers in a mmory expression, and though unaccessible via rip/eip.
1314 if (IsGlobalLV && (BaseReg || IndexReg)) {
1315 return X86Operand::CreateMem(getPointerWidth(), Disp, Start, End);
1316 // Otherwise, we set the base register to a non-zero value
Chad Rosier175d0ae2013-04-12 18:21:18 +00001317 // if we don't know the actual value at this time. This is necessary to
Chad Rosier7ca135b2013-03-19 21:11:56 +00001318 // get the matching correct in some cases.
Coby Tayreec3d24112017-09-29 07:02:46 +00001319 } else {
1320 BaseReg = BaseReg ? BaseReg : 1;
1321 return X86Operand::CreateMem(getPointerWidth(), SegReg, Disp, BaseReg,
1322 IndexReg, Scale, Start, End, Size, Identifier,
1323 Decl, FrontendSize);
1324 }
Chad Rosier7ca135b2013-03-19 21:11:56 +00001325}
1326
Coby Tayree2cb497a2017-04-04 14:43:23 +00001327// Some binary bitwise operators have a named synonymous
1328// Query a candidate string for being such a named operator
1329// and if so - invoke the appropriate handler
1330bool X86AsmParser::ParseIntelNamedOperator(StringRef Name, IntelExprStateMachine &SM) {
1331 // A named operator should be either lower or upper case, but not a mix
1332 if (Name.compare(Name.lower()) && Name.compare(Name.upper()))
1333 return false;
1334 if (Name.equals_lower("not"))
1335 SM.onNot();
1336 else if (Name.equals_lower("or"))
1337 SM.onOr();
1338 else if (Name.equals_lower("shl"))
1339 SM.onLShift();
1340 else if (Name.equals_lower("shr"))
1341 SM.onRShift();
1342 else if (Name.equals_lower("xor"))
1343 SM.onXor();
1344 else if (Name.equals_lower("and"))
1345 SM.onAnd();
Coby Tayree41a5b552017-06-27 16:58:27 +00001346 else if (Name.equals_lower("mod"))
1347 SM.onMod();
Coby Tayree2cb497a2017-04-04 14:43:23 +00001348 else
1349 return false;
1350 return true;
1351}
1352
Benjamin Kramer951b15e2013-12-01 11:47:42 +00001353bool X86AsmParser::ParseIntelExpression(IntelExprStateMachine &SM, SMLoc &End) {
Rafael Espindola961d4692014-11-11 05:18:41 +00001354 MCAsmParser &Parser = getParser();
Chad Rosier6844ea02012-10-24 22:13:37 +00001355 const AsmToken &Tok = Parser.getTok();
Andrew V. Tischenko32e9b1a2017-07-25 13:05:12 +00001356 StringRef ErrMsg;
Chad Rosier51afe632012-06-27 22:34:28 +00001357
Marina Yatsina8dfd5cb2015-12-24 12:09:51 +00001358 AsmToken::TokenKind PrevTK = AsmToken::Error;
Chad Rosier5c118fd2013-01-14 22:31:35 +00001359 bool Done = false;
Chad Rosier5c118fd2013-01-14 22:31:35 +00001360 while (!Done) {
1361 bool UpdateLocLex = true;
Andrew V. Tischenkofdb264e2017-05-26 13:23:34 +00001362 AsmToken::TokenKind TK = getLexer().getKind();
Chad Rosier5c118fd2013-01-14 22:31:35 +00001363
David Majnemer6a5b8122014-06-19 01:25:43 +00001364 switch (TK) {
Coby Tayreed8912892017-08-24 08:46:25 +00001365 default:
1366 if ((Done = SM.isValidEndState()))
Chad Rosier5c118fd2013-01-14 22:31:35 +00001367 break;
Benjamin Kramer951b15e2013-12-01 11:47:42 +00001368 return Error(Tok.getLoc(), "unknown token in expression");
Coby Tayreed8912892017-08-24 08:46:25 +00001369 case AsmToken::EndOfStatement:
Chad Rosierbfb70992013-04-17 00:11:46 +00001370 Done = true;
1371 break;
Coby Tayreed8912892017-08-24 08:46:25 +00001372 case AsmToken::Real:
1373 // DotOperator: [ebx].0
1374 UpdateLocLex = false;
1375 if (ParseIntelDotOperator(SM, End))
1376 return true;
1377 break;
David Majnemer6a5b8122014-06-19 01:25:43 +00001378 case AsmToken::String:
Chad Rosier5c118fd2013-01-14 22:31:35 +00001379 case AsmToken::Identifier: {
Chad Rosier152749c2013-04-12 18:54:20 +00001380 SMLoc IdentLoc = Tok.getLoc();
1381 StringRef Identifier = Tok.getString();
Coby Tayree07a89742017-03-21 19:31:55 +00001382 UpdateLocLex = false;
Coby Tayreec3d24112017-09-29 07:02:46 +00001383 // Register
1384 unsigned Reg;
1385 if (Tok.isNot(AsmToken::String) && !ParseRegister(Reg, IdentLoc, End)) {
1386 if (SM.onRegister(Reg, ErrMsg))
Andrew V. Tischenko32e9b1a2017-07-25 13:05:12 +00001387 return Error(Tok.getLoc(), ErrMsg);
Coby Tayreec3d24112017-09-29 07:02:46 +00001388 break;
1389 }
1390 // Operator synonymous ("not", "or" etc.)
1391 if ((UpdateLocLex = ParseIntelNamedOperator(Identifier, SM)))
1392 break;
1393 // Symbol reference, when parsing assembly content
1394 InlineAsmIdentifierInfo Info;
1395 const MCExpr *Val;
1396 if (!isParsingInlineAsm()) {
1397 if (getParser().parsePrimaryExpr(Val, End)) {
Coby Tayree07a89742017-03-21 19:31:55 +00001398 return Error(Tok.getLoc(), "Unexpected identifier!");
Coby Tayreec3d24112017-09-29 07:02:46 +00001399 } else if (SM.onIdentifierExpr(Val, Identifier, Info, false, ErrMsg)) {
Coby Tayreed8912892017-08-24 08:46:25 +00001400 return Error(IdentLoc, ErrMsg);
Coby Tayreec3d24112017-09-29 07:02:46 +00001401 } else
1402 break;
1403 }
1404 // MS InlineAsm operators (TYPE/LENGTH/SIZE)
1405 if (unsigned OpKind = IdentifyIntelInlineAsmOperator(Identifier)) {
Coby Tayreed8912892017-08-24 08:46:25 +00001406 if (OpKind == IOK_OFFSET)
Coby Tayree07a89742017-03-21 19:31:55 +00001407 return Error(IdentLoc, "Dealing OFFSET operator as part of"
1408 "a compound immediate expression is yet to be supported");
Coby Tayreec3d24112017-09-29 07:02:46 +00001409 if (int64_t Val = ParseIntelInlineAsmOperator(OpKind)) {
1410 if (SM.onInteger(Val, ErrMsg))
1411 return Error(IdentLoc, ErrMsg);
1412 } else
Coby Tayree07a89742017-03-21 19:31:55 +00001413 return true;
Coby Tayreec3d24112017-09-29 07:02:46 +00001414 break;
Chad Rosier5c118fd2013-01-14 22:31:35 +00001415 }
Coby Tayreec3d24112017-09-29 07:02:46 +00001416 // MS Dot Operator expression
1417 if (Identifier.count('.') && PrevTK == AsmToken::RBrac) {
1418 if (ParseIntelDotOperator(SM, End))
1419 return true;
1420 break;
1421 }
1422 // MS InlineAsm identifier
1423 if (ParseIntelInlineAsmIdentifier(Val, Identifier, Info, false, End))
1424 return true;
1425 else if (SM.onIdentifierExpr(Val, Identifier, Info, true, ErrMsg))
1426 return Error(IdentLoc, ErrMsg);
Coby Tayree07a89742017-03-21 19:31:55 +00001427 break;
Chad Rosier5c118fd2013-01-14 22:31:35 +00001428 }
Kevin Enderby36eba252013-12-19 23:16:14 +00001429 case AsmToken::Integer: {
Kevin Enderby36eba252013-12-19 23:16:14 +00001430 // Look for 'b' or 'f' following an Integer as a directional label
1431 SMLoc Loc = getTok().getLoc();
1432 int64_t IntVal = getTok().getIntVal();
1433 End = consumeToken();
1434 UpdateLocLex = false;
1435 if (getLexer().getKind() == AsmToken::Identifier) {
1436 StringRef IDVal = getTok().getString();
1437 if (IDVal == "f" || IDVal == "b") {
1438 MCSymbol *Sym =
Jim Grosbach6f482002015-05-18 18:43:14 +00001439 getContext().getDirectionalLocalSymbol(IntVal, IDVal == "b");
Kevin Enderby36eba252013-12-19 23:16:14 +00001440 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Michael Liao5bf95782014-12-04 05:20:33 +00001441 const MCExpr *Val =
NAKAMURA Takumi0a7d0ad2015-09-22 11:15:07 +00001442 MCSymbolRefExpr::create(Sym, Variant, getContext());
Kevin Enderby36eba252013-12-19 23:16:14 +00001443 if (IDVal == "b" && Sym->isUndefined())
1444 return Error(Loc, "invalid reference to undefined symbol");
1445 StringRef Identifier = Sym->getName();
Coby Tayreec3d24112017-09-29 07:02:46 +00001446 InlineAsmIdentifierInfo Info;
1447 if (SM.onIdentifierExpr(Val, Identifier, Info,
1448 isParsingInlineAsm(), ErrMsg))
Coby Tayreed8912892017-08-24 08:46:25 +00001449 return Error(Loc, ErrMsg);
Kevin Enderby36eba252013-12-19 23:16:14 +00001450 End = consumeToken();
1451 } else {
Kevin Enderby9d117022014-01-23 21:52:41 +00001452 if (SM.onInteger(IntVal, ErrMsg))
1453 return Error(Loc, ErrMsg);
Kevin Enderby36eba252013-12-19 23:16:14 +00001454 }
1455 } else {
Kevin Enderby9d117022014-01-23 21:52:41 +00001456 if (SM.onInteger(IntVal, ErrMsg))
1457 return Error(Loc, ErrMsg);
Kevin Enderby36eba252013-12-19 23:16:14 +00001458 }
Chad Rosier5c118fd2013-01-14 22:31:35 +00001459 break;
Kevin Enderby36eba252013-12-19 23:16:14 +00001460 }
Andrew V. Tischenko32e9b1a2017-07-25 13:05:12 +00001461 case AsmToken::Plus:
1462 if (SM.onPlus(ErrMsg))
1463 return Error(getTok().getLoc(), ErrMsg);
1464 break;
1465 case AsmToken::Minus:
1466 if (SM.onMinus(ErrMsg))
1467 return Error(getTok().getLoc(), ErrMsg);
1468 break;
Ehsan Akhgari4103da62014-07-04 19:13:05 +00001469 case AsmToken::Tilde: SM.onNot(); break;
Chad Rosier5c118fd2013-01-14 22:31:35 +00001470 case AsmToken::Star: SM.onStar(); break;
Chad Rosier4a7005e2013-04-05 16:28:55 +00001471 case AsmToken::Slash: SM.onDivide(); break;
Kevin Enderby2e13b1c2014-01-15 19:05:24 +00001472 case AsmToken::Pipe: SM.onOr(); break;
Michael Kupersteine3de07a2015-06-14 12:59:45 +00001473 case AsmToken::Caret: SM.onXor(); break;
Kevin Enderby2e13b1c2014-01-15 19:05:24 +00001474 case AsmToken::Amp: SM.onAnd(); break;
Kevin Enderbyd6b10712014-02-06 01:21:15 +00001475 case AsmToken::LessLess:
1476 SM.onLShift(); break;
1477 case AsmToken::GreaterGreater:
1478 SM.onRShift(); break;
Coby Tayreed8912892017-08-24 08:46:25 +00001479 case AsmToken::LBrac:
1480 if (SM.onLBrac())
1481 return Error(Tok.getLoc(), "unexpected bracket encountered");
1482 break;
1483 case AsmToken::RBrac:
1484 if (SM.onRBrac())
1485 return Error(Tok.getLoc(), "unexpected bracket encountered");
1486 break;
Chad Rosier4a7005e2013-04-05 16:28:55 +00001487 case AsmToken::LParen: SM.onLParen(); break;
1488 case AsmToken::RParen: SM.onRParen(); break;
Chad Rosier5c118fd2013-01-14 22:31:35 +00001489 }
Chad Rosier31246272013-04-17 21:01:45 +00001490 if (SM.hadError())
Benjamin Kramer951b15e2013-12-01 11:47:42 +00001491 return Error(Tok.getLoc(), "unknown token in expression");
Chad Rosier31246272013-04-17 21:01:45 +00001492
Alp Tokera5b88a52013-12-02 16:06:06 +00001493 if (!Done && UpdateLocLex)
1494 End = consumeToken();
Marina Yatsina8dfd5cb2015-12-24 12:09:51 +00001495
1496 PrevTK = TK;
Devang Patel41b9dde2012-01-17 18:00:18 +00001497 }
Benjamin Kramer951b15e2013-12-01 11:47:42 +00001498 return false;
Chad Rosier5362af92013-04-16 18:15:40 +00001499}
1500
Coby Tayreed8912892017-08-24 08:46:25 +00001501void X86AsmParser::RewriteIntelExpression(IntelExprStateMachine &SM,
1502 SMLoc Start, SMLoc End) {
1503 SMLoc Loc = Start;
1504 unsigned ExprLen = End.getPointer() - Start.getPointer();
1505 // Skip everything before a symbol displacement (if we have one)
1506 if (SM.getSym()) {
1507 StringRef SymName = SM.getSymName();
1508 if (unsigned Len = SymName.data() - Start.getPointer())
1509 InstInfo->AsmRewrites->emplace_back(AOK_Skip, Start, Len);
1510 Loc = SMLoc::getFromPointer(SymName.data() + SymName.size());
1511 ExprLen = End.getPointer() - (SymName.data() + SymName.size());
1512 // If we have only a symbol than there's no need for complex rewrite,
1513 // simply skip everything after it
1514 if (!(SM.getBaseReg() || SM.getIndexReg() || SM.getImm())) {
1515 if (ExprLen)
1516 InstInfo->AsmRewrites->emplace_back(AOK_Skip, Loc, ExprLen);
1517 return;
Nirav Dave8601ac12016-08-02 17:56:03 +00001518 }
1519 }
Coby Tayreed8912892017-08-24 08:46:25 +00001520 // Build an Intel Expression rewrite
1521 StringRef BaseRegStr;
1522 StringRef IndexRegStr;
1523 if (SM.getBaseReg())
1524 BaseRegStr = X86IntelInstPrinter::getRegisterName(SM.getBaseReg());
1525 if (SM.getIndexReg())
1526 IndexRegStr = X86IntelInstPrinter::getRegisterName(SM.getIndexReg());
1527 // Emit it
1528 IntelExpr Expr(BaseRegStr, IndexRegStr, SM.getScale(), SM.getImm(), SM.isMemExpr());
1529 InstInfo->AsmRewrites->emplace_back(Loc, ExprLen, Expr);
Devang Patel41b9dde2012-01-17 18:00:18 +00001530}
1531
Chad Rosier8a244662013-04-02 20:02:33 +00001532// Inline assembly may use variable names with namespace alias qualifiers.
Coby Tayreed8912892017-08-24 08:46:25 +00001533bool X86AsmParser::ParseIntelInlineAsmIdentifier(const MCExpr *&Val,
1534 StringRef &Identifier,
1535 InlineAsmIdentifierInfo &Info,
1536 bool IsUnevaluatedOperand,
1537 SMLoc &End) {
Rafael Espindola961d4692014-11-11 05:18:41 +00001538 MCAsmParser &Parser = getParser();
Reid Klecknerc2b92542015-08-26 21:57:25 +00001539 assert(isParsingInlineAsm() && "Expected to be parsing inline assembly.");
Craig Topper062a2ba2014-04-25 05:30:21 +00001540 Val = nullptr;
Chad Rosier8a244662013-04-02 20:02:33 +00001541
Chad Rosiercb78f0d2013-04-22 19:42:15 +00001542 StringRef LineBuf(Identifier.data());
Coby Tayreec3d24112017-09-29 07:02:46 +00001543 SemaCallback->LookupInlineAsmIdentifier(LineBuf, Info, IsUnevaluatedOperand);
Chad Rosiercb78f0d2013-04-22 19:42:15 +00001544
Chad Rosier8a244662013-04-02 20:02:33 +00001545 const AsmToken &Tok = Parser.getTok();
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001546 SMLoc Loc = Tok.getLoc();
John McCallf73981b2013-05-03 00:15:41 +00001547
1548 // Advance the token stream until the end of the current token is
1549 // after the end of what the frontend claimed.
1550 const char *EndPtr = Tok.getLoc().getPointer() + LineBuf.size();
Reid Klecknerc2b92542015-08-26 21:57:25 +00001551 do {
John McCallf73981b2013-05-03 00:15:41 +00001552 End = Tok.getEndLoc();
1553 getLexer().Lex();
Reid Klecknerc2b92542015-08-26 21:57:25 +00001554 } while (End.getPointer() < EndPtr);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001555 Identifier = LineBuf;
1556
Reid Klecknerc2b92542015-08-26 21:57:25 +00001557 // The frontend should end parsing on an assembler token boundary, unless it
1558 // failed parsing.
Coby Tayreec3d24112017-09-29 07:02:46 +00001559 assert((End.getPointer() == EndPtr ||
1560 Info.isKind(InlineAsmIdentifierInfo::IK_Invalid)) &&
1561 "frontend claimed part of a token?");
Reid Klecknerc2b92542015-08-26 21:57:25 +00001562
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001563 // If the identifier lookup was unsuccessful, assume that we are dealing with
1564 // a label.
Coby Tayreec3d24112017-09-29 07:02:46 +00001565 if (Info.isKind(InlineAsmIdentifierInfo::IK_Invalid)) {
Ehsan Akhgaribb6bb072014-09-22 20:40:36 +00001566 StringRef InternalName =
1567 SemaCallback->LookupInlineAsmLabel(Identifier, getSourceManager(),
1568 Loc, false);
1569 assert(InternalName.size() && "We should have an internal name here.");
1570 // Push a rewrite for replacing the identifier name with the internal name.
Craig Topper7d5b2312015-10-10 05:25:02 +00001571 InstInfo->AsmRewrites->emplace_back(AOK_Label, Loc, Identifier.size(),
1572 InternalName);
Coby Tayreec3d24112017-09-29 07:02:46 +00001573 } else if (Info.isKind(InlineAsmIdentifierInfo::IK_EnumVal))
1574 return false;
Chad Rosiercb78f0d2013-04-22 19:42:15 +00001575 // Create the symbol reference.
Jim Grosbach6f482002015-05-18 18:43:14 +00001576 MCSymbol *Sym = getContext().getOrCreateSymbol(Identifier);
Chad Rosier8a244662013-04-02 20:02:33 +00001577 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Jim Grosbach13760bd2015-05-30 01:25:56 +00001578 Val = MCSymbolRefExpr::create(Sym, Variant, getParser().getContext());
Benjamin Kramer951b15e2013-12-01 11:47:42 +00001579 return false;
Chad Rosier8a244662013-04-02 20:02:33 +00001580}
1581
Elena Demikhovsky18fd4962015-03-02 15:00:34 +00001582//ParseRoundingModeOp - Parse AVX-512 rounding mode operand
1583std::unique_ptr<X86Operand>
1584X86AsmParser::ParseRoundingModeOp(SMLoc Start, SMLoc End) {
1585 MCAsmParser &Parser = getParser();
1586 const AsmToken &Tok = Parser.getTok();
Elena Demikhovsky29792e92015-05-07 11:24:42 +00001587 // Eat "{" and mark the current place.
1588 const SMLoc consumedToken = consumeToken();
Elena Demikhovsky18fd4962015-03-02 15:00:34 +00001589 if (Tok.getIdentifier().startswith("r")){
1590 int rndMode = StringSwitch<int>(Tok.getIdentifier())
1591 .Case("rn", X86::STATIC_ROUNDING::TO_NEAREST_INT)
1592 .Case("rd", X86::STATIC_ROUNDING::TO_NEG_INF)
1593 .Case("ru", X86::STATIC_ROUNDING::TO_POS_INF)
1594 .Case("rz", X86::STATIC_ROUNDING::TO_ZERO)
1595 .Default(-1);
1596 if (-1 == rndMode)
1597 return ErrorOperand(Tok.getLoc(), "Invalid rounding mode.");
1598 Parser.Lex(); // Eat "r*" of r*-sae
1599 if (!getLexer().is(AsmToken::Minus))
1600 return ErrorOperand(Tok.getLoc(), "Expected - at this point");
1601 Parser.Lex(); // Eat "-"
1602 Parser.Lex(); // Eat the sae
1603 if (!getLexer().is(AsmToken::RCurly))
1604 return ErrorOperand(Tok.getLoc(), "Expected } at this point");
1605 Parser.Lex(); // Eat "}"
1606 const MCExpr *RndModeOp =
Jim Grosbach13760bd2015-05-30 01:25:56 +00001607 MCConstantExpr::create(rndMode, Parser.getContext());
Elena Demikhovsky18fd4962015-03-02 15:00:34 +00001608 return X86Operand::CreateImm(RndModeOp, Start, End);
1609 }
Elena Demikhovsky29792e92015-05-07 11:24:42 +00001610 if(Tok.getIdentifier().equals("sae")){
1611 Parser.Lex(); // Eat the sae
1612 if (!getLexer().is(AsmToken::RCurly))
1613 return ErrorOperand(Tok.getLoc(), "Expected } at this point");
1614 Parser.Lex(); // Eat "}"
1615 return X86Operand::CreateToken("{sae}", consumedToken);
1616 }
Elena Demikhovsky18fd4962015-03-02 15:00:34 +00001617 return ErrorOperand(Tok.getLoc(), "unknown token in expression");
1618}
Chad Rosier91c82662012-10-24 17:22:29 +00001619
Chad Rosier5dcb4662012-10-24 22:21:50 +00001620/// Parse the '.' operator.
Coby Tayreed8912892017-08-24 08:46:25 +00001621bool X86AsmParser::ParseIntelDotOperator(IntelExprStateMachine &SM, SMLoc &End) {
1622 const AsmToken &Tok = getTok();
1623 unsigned Offset;
Chad Rosier5dcb4662012-10-24 22:21:50 +00001624
Reid Kleckner94a1c4d2014-03-06 19:19:12 +00001625 // Drop the optional '.'.
1626 StringRef DotDispStr = Tok.getString();
1627 if (DotDispStr.startswith("."))
1628 DotDispStr = DotDispStr.drop_front(1);
Chad Rosier5dcb4662012-10-24 22:21:50 +00001629
Chad Rosier5dcb4662012-10-24 22:21:50 +00001630 // .Imm gets lexed as a real.
1631 if (Tok.is(AsmToken::Real)) {
1632 APInt DotDisp;
1633 DotDispStr.getAsInteger(10, DotDisp);
Coby Tayreed8912892017-08-24 08:46:25 +00001634 Offset = DotDisp.getZExtValue();
Chad Rosiercc541e82013-04-19 15:57:00 +00001635 } else if (isParsingInlineAsm() && Tok.is(AsmToken::Identifier)) {
Chad Rosier240b7b92012-10-25 21:51:10 +00001636 std::pair<StringRef, StringRef> BaseMember = DotDispStr.split('.');
1637 if (SemaCallback->LookupInlineAsmField(BaseMember.first, BaseMember.second,
Coby Tayreed8912892017-08-24 08:46:25 +00001638 Offset))
Benjamin Kramer951b15e2013-12-01 11:47:42 +00001639 return Error(Tok.getLoc(), "Unable to lookup field reference!");
Chad Rosiercc541e82013-04-19 15:57:00 +00001640 } else
Benjamin Kramer951b15e2013-12-01 11:47:42 +00001641 return Error(Tok.getLoc(), "Unexpected token type!");
Chad Rosier911c1f32012-10-25 17:37:43 +00001642
Coby Tayreed8912892017-08-24 08:46:25 +00001643 // Eat the DotExpression and update End
1644 End = SMLoc::getFromPointer(DotDispStr.data());
1645 const char *DotExprEndLoc = DotDispStr.data() + DotDispStr.size();
1646 while (Tok.getLoc().getPointer() < DotExprEndLoc)
1647 Lex();
1648 SM.addImm(Offset);
Benjamin Kramer951b15e2013-12-01 11:47:42 +00001649 return false;
Chad Rosier5dcb4662012-10-24 22:21:50 +00001650}
1651
Chad Rosier91c82662012-10-24 17:22:29 +00001652/// Parse the 'offset' operator. This operator is used to specify the
1653/// location rather then the content of a variable.
David Blaikie960ea3f2014-06-08 16:18:35 +00001654std::unique_ptr<X86Operand> X86AsmParser::ParseIntelOffsetOfOperator() {
Rafael Espindola961d4692014-11-11 05:18:41 +00001655 MCAsmParser &Parser = getParser();
Chad Rosier18785852013-04-09 20:58:48 +00001656 const AsmToken &Tok = Parser.getTok();
Chad Rosier10d1d1c2013-04-09 20:44:09 +00001657 SMLoc OffsetOfLoc = Tok.getLoc();
Chad Rosier91c82662012-10-24 17:22:29 +00001658 Parser.Lex(); // Eat offset.
Chad Rosier91c82662012-10-24 17:22:29 +00001659
Chad Rosier91c82662012-10-24 17:22:29 +00001660 const MCExpr *Val;
Chad Rosiercb78f0d2013-04-22 19:42:15 +00001661 InlineAsmIdentifierInfo Info;
Chad Rosier18785852013-04-09 20:58:48 +00001662 SMLoc Start = Tok.getLoc(), End;
Chad Rosierae7ecd62013-04-11 23:37:34 +00001663 StringRef Identifier = Tok.getString();
Coby Tayreed8912892017-08-24 08:46:25 +00001664 if (ParseIntelInlineAsmIdentifier(Val, Identifier, Info,
1665 /*Unevaluated=*/false, End))
Craig Topper062a2ba2014-04-25 05:30:21 +00001666 return nullptr;
Chad Rosierae7ecd62013-04-11 23:37:34 +00001667
Coby Tayreec3d24112017-09-29 07:02:46 +00001668 void *Decl = nullptr;
1669 // FIXME: MS evaluates "offset <Constant>" to the underlying integral
1670 if (Info.isKind(InlineAsmIdentifierInfo::IK_EnumVal))
1671 return ErrorOperand(Start, "offset operator cannot yet handle constants");
1672 else if (Info.isKind(InlineAsmIdentifierInfo::IK_Var))
1673 Decl = Info.Var.Decl;
Chad Rosiere2f03772012-10-26 16:09:20 +00001674 // Don't emit the offset operator.
Craig Topper7d5b2312015-10-10 05:25:02 +00001675 InstInfo->AsmRewrites->emplace_back(AOK_Skip, OffsetOfLoc, 7);
Chad Rosiere2f03772012-10-26 16:09:20 +00001676
Chad Rosier91c82662012-10-24 17:22:29 +00001677 // The offset operator will have an 'r' constraint, thus we need to create
1678 // register operand to ensure proper matching. Just pick a GPR based on
1679 // the size of a pointer.
Nirav Dave6477ce22016-09-26 19:33:36 +00001680 bool Parse32 = is32BitMode() || Code16GCC;
1681 unsigned RegNo = is64BitMode() ? X86::RBX : (Parse32 ? X86::EBX : X86::BX);
1682
Chad Rosiera4bc9432013-01-10 22:10:27 +00001683 return X86Operand::CreateReg(RegNo, Start, End, /*GetAddress=*/true,
Coby Tayreec3d24112017-09-29 07:02:46 +00001684 OffsetOfLoc, Identifier, Decl);
Devang Patel41b9dde2012-01-17 18:00:18 +00001685}
1686
Coby Tayree07a89742017-03-21 19:31:55 +00001687// Query a candidate string for being an Intel assembly operator
1688// Report back its kind, or IOK_INVALID if does not evaluated as a known one
Coby Tayreed8912892017-08-24 08:46:25 +00001689unsigned X86AsmParser::IdentifyIntelInlineAsmOperator(StringRef Name) {
Coby Tayree07a89742017-03-21 19:31:55 +00001690 return StringSwitch<unsigned>(Name)
1691 .Cases("TYPE","type",IOK_TYPE)
1692 .Cases("SIZE","size",IOK_SIZE)
1693 .Cases("LENGTH","length",IOK_LENGTH)
1694 .Cases("OFFSET","offset",IOK_OFFSET)
1695 .Default(IOK_INVALID);
1696}
Chad Rosierd0ed73a2013-01-17 19:21:48 +00001697
1698/// Parse the 'LENGTH', 'TYPE' and 'SIZE' operators. The LENGTH operator
1699/// returns the number of elements in an array. It returns the value 1 for
1700/// non-array variables. The SIZE operator returns the size of a C or C++
1701/// variable. A variable's size is the product of its LENGTH and TYPE. The
1702/// TYPE operator returns the size of a C or C++ type or variable. If the
1703/// variable is an array, TYPE returns the size of a single element.
Coby Tayreed8912892017-08-24 08:46:25 +00001704unsigned X86AsmParser::ParseIntelInlineAsmOperator(unsigned OpKind) {
Rafael Espindola961d4692014-11-11 05:18:41 +00001705 MCAsmParser &Parser = getParser();
Chad Rosier18785852013-04-09 20:58:48 +00001706 const AsmToken &Tok = Parser.getTok();
Chad Rosier10d1d1c2013-04-09 20:44:09 +00001707 Parser.Lex(); // Eat operator.
Chad Rosier11c42f22012-10-26 18:04:20 +00001708
Craig Topper062a2ba2014-04-25 05:30:21 +00001709 const MCExpr *Val = nullptr;
Chad Rosiercb78f0d2013-04-22 19:42:15 +00001710 InlineAsmIdentifierInfo Info;
Chad Rosier18785852013-04-09 20:58:48 +00001711 SMLoc Start = Tok.getLoc(), End;
Chad Rosierb67f8052013-04-11 23:57:04 +00001712 StringRef Identifier = Tok.getString();
Coby Tayreed8912892017-08-24 08:46:25 +00001713 if (ParseIntelInlineAsmIdentifier(Val, Identifier, Info,
1714 /*Unevaluated=*/true, End))
Coby Tayree07a89742017-03-21 19:31:55 +00001715 return 0;
Benjamin Kramer951b15e2013-12-01 11:47:42 +00001716
Coby Tayreec3d24112017-09-29 07:02:46 +00001717 if (!Info.isKind(InlineAsmIdentifierInfo::IK_Var)) {
Coby Tayree07a89742017-03-21 19:31:55 +00001718 Error(Start, "unable to lookup expression");
1719 return 0;
1720 }
Coby Tayreed8912892017-08-24 08:46:25 +00001721
Chad Rosierf6675c32013-04-22 17:01:46 +00001722 unsigned CVal = 0;
Chad Rosiercb78f0d2013-04-22 19:42:15 +00001723 switch(OpKind) {
1724 default: llvm_unreachable("Unexpected operand kind!");
Coby Tayreec3d24112017-09-29 07:02:46 +00001725 case IOK_LENGTH: CVal = Info.Var.Length; break;
1726 case IOK_SIZE: CVal = Info.Var.Size; break;
1727 case IOK_TYPE: CVal = Info.Var.Type; break;
Chad Rosiercb78f0d2013-04-22 19:42:15 +00001728 }
Eric Christopheradfe5362017-07-25 19:22:09 +00001729
Coby Tayree07a89742017-03-21 19:31:55 +00001730 return CVal;
Chad Rosier11c42f22012-10-26 18:04:20 +00001731}
1732
Coby Tayreed8912892017-08-24 08:46:25 +00001733bool X86AsmParser::ParseIntelMemoryOperandSize(unsigned &Size) {
1734 Size = StringSwitch<unsigned>(getTok().getString())
1735 .Cases("BYTE", "byte", 8)
1736 .Cases("WORD", "word", 16)
1737 .Cases("DWORD", "dword", 32)
Coby Tayree566348f2017-09-28 11:04:08 +00001738 .Cases("FLOAT", "float", 32)
1739 .Cases("LONG", "long", 32)
Coby Tayreed8912892017-08-24 08:46:25 +00001740 .Cases("FWORD", "fword", 48)
Coby Tayree566348f2017-09-28 11:04:08 +00001741 .Cases("DOUBLE", "double", 64)
Coby Tayreed8912892017-08-24 08:46:25 +00001742 .Cases("QWORD", "qword", 64)
1743 .Cases("MMWORD","mmword", 64)
1744 .Cases("XWORD", "xword", 80)
1745 .Cases("TBYTE", "tbyte", 80)
1746 .Cases("XMMWORD", "xmmword", 128)
1747 .Cases("YMMWORD", "ymmword", 256)
1748 .Cases("ZMMWORD", "zmmword", 512)
1749 .Cases("OPAQUE", "opaque", -1U) // needs to be non-zero, but doesn't matter
1750 .Default(0);
1751 if (Size) {
1752 const AsmToken &Tok = Lex(); // Eat operand size (e.g., byte, word).
1753 if (!(Tok.getString().equals("PTR") || Tok.getString().equals("ptr")))
1754 return Error(Tok.getLoc(), "Expected 'PTR' or 'ptr' token!");
1755 Lex(); // Eat ptr.
1756 }
1757 return false;
1758}
1759
David Blaikie960ea3f2014-06-08 16:18:35 +00001760std::unique_ptr<X86Operand> X86AsmParser::ParseIntelOperand() {
Rafael Espindola961d4692014-11-11 05:18:41 +00001761 MCAsmParser &Parser = getParser();
Chad Rosier70f47592013-04-10 20:07:47 +00001762 const AsmToken &Tok = Parser.getTok();
David Majnemeraa34d792013-08-27 21:56:17 +00001763 SMLoc Start, End;
Chad Rosier91c82662012-10-24 17:22:29 +00001764
Coby Tayree07a89742017-03-21 19:31:55 +00001765 // FIXME: Offset operator
1766 // Should be handled as part of immediate expression, as other operators
1767 // Currently, only supported as a stand-alone operand
1768 if (isParsingInlineAsm())
Coby Tayreed8912892017-08-24 08:46:25 +00001769 if (IdentifyIntelInlineAsmOperator(Tok.getString()) == IOK_OFFSET)
Chad Rosier10d1d1c2013-04-09 20:44:09 +00001770 return ParseIntelOffsetOfOperator();
Chad Rosier11c42f22012-10-26 18:04:20 +00001771
Coby Tayreed8912892017-08-24 08:46:25 +00001772 // Parse optional Size directive.
1773 unsigned Size;
1774 if (ParseIntelMemoryOperandSize(Size))
1775 return nullptr;
1776 bool PtrInOperand = bool(Size);
Nirav Dave8601ac12016-08-02 17:56:03 +00001777
David Majnemeraa34d792013-08-27 21:56:17 +00001778 Start = Tok.getLoc();
1779
Coby Tayreed8912892017-08-24 08:46:25 +00001780 // Rounding mode operand.
Akira Hatanakabd9fc282015-11-14 05:20:05 +00001781 if (getSTI().getFeatureBits()[X86::FeatureAVX512] &&
Elena Demikhovsky18fd4962015-03-02 15:00:34 +00001782 getLexer().is(AsmToken::LCurly))
1783 return ParseRoundingModeOp(Start, End);
1784
Coby Tayreed8912892017-08-24 08:46:25 +00001785 // Register operand.
Devang Patelce6a2ca2012-01-20 22:32:05 +00001786 unsigned RegNo = 0;
Coby Tayreed8912892017-08-24 08:46:25 +00001787 if (Tok.is(AsmToken::Identifier) && !ParseRegister(RegNo, Start, End)) {
Douglas Katzman0411e862016-10-05 15:23:35 +00001788 if (RegNo == X86::RIP)
1789 return ErrorOperand(Start, "rip can only be used as a base register");
Coby Tayreed8912892017-08-24 08:46:25 +00001790 // A Register followed by ':' is considered a segment override
1791 if (Tok.isNot(AsmToken::Colon))
1792 return !PtrInOperand ? X86Operand::CreateReg(RegNo, Start, End) :
1793 ErrorOperand(Start, "expected memory operand after 'ptr', "
1794 "found register operand instead");
1795 // An alleged segment override. check if we have a valid segment register
1796 if (!X86MCRegisterClasses[X86::SEGMENT_REGRegClassID].contains(RegNo))
1797 return ErrorOperand(Start, "invalid segment register");
1798 // Eat ':' and update Start location
1799 Start = Lex().getLoc();
Devang Patel46831de2012-01-12 01:36:43 +00001800 }
1801
Nirav Dave8601ac12016-08-02 17:56:03 +00001802 // Immediates and Memory
Coby Tayreed8912892017-08-24 08:46:25 +00001803 IntelExprStateMachine SM;
Nirav Dave8601ac12016-08-02 17:56:03 +00001804 if (ParseIntelExpression(SM, End))
1805 return nullptr;
1806
Coby Tayreed8912892017-08-24 08:46:25 +00001807 if (isParsingInlineAsm())
1808 RewriteIntelExpression(SM, Start, Tok.getLoc());
1809
Nirav Dave8601ac12016-08-02 17:56:03 +00001810 int64_t Imm = SM.getImm();
Coby Tayreed8912892017-08-24 08:46:25 +00001811 const MCExpr *Disp = SM.getSym();
1812 const MCExpr *ImmDisp = MCConstantExpr::create(Imm, getContext());
1813 if (Disp && Imm)
1814 Disp = MCBinaryExpr::createAdd(Disp, ImmDisp, getContext());
1815 if (!Disp)
1816 Disp = ImmDisp;
Nirav Dave8601ac12016-08-02 17:56:03 +00001817
Coby Tayreed8912892017-08-24 08:46:25 +00001818 // RegNo != 0 specifies a valid segment register,
1819 // and we are parsing a segment override
1820 if (!SM.isMemExpr() && !RegNo)
1821 return X86Operand::CreateImm(Disp, Start, End);
Nirav Dave8601ac12016-08-02 17:56:03 +00001822
Coby Tayreed8912892017-08-24 08:46:25 +00001823 StringRef ErrMsg;
1824 unsigned BaseReg = SM.getBaseReg();
1825 unsigned IndexReg = SM.getIndexReg();
1826 unsigned Scale = SM.getScale();
Nirav Dave8601ac12016-08-02 17:56:03 +00001827
Coby Tayreed8912892017-08-24 08:46:25 +00001828 if ((BaseReg || IndexReg) &&
1829 CheckBaseRegAndIndexRegAndScale(BaseReg, IndexReg, Scale, ErrMsg))
1830 return ErrorOperand(Start, ErrMsg);
1831 if (isParsingInlineAsm())
1832 return CreateMemForInlineAsm(RegNo, Disp, BaseReg, IndexReg,
1833 Scale, Start, End, Size, SM.getSymName(),
1834 SM.getIdentifierInfo());
1835 if (!(BaseReg || IndexReg || RegNo))
1836 return X86Operand::CreateMem(getPointerWidth(), Disp, Start, End, Size);
1837 return X86Operand::CreateMem(getPointerWidth(), RegNo, Disp,
1838 BaseReg, IndexReg, Scale, Start, End, Size);
Devang Patel46831de2012-01-12 01:36:43 +00001839}
1840
David Blaikie960ea3f2014-06-08 16:18:35 +00001841std::unique_ptr<X86Operand> X86AsmParser::ParseATTOperand() {
Rafael Espindola961d4692014-11-11 05:18:41 +00001842 MCAsmParser &Parser = getParser();
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +00001843 switch (getLexer().getKind()) {
1844 default:
Chris Lattnerb9270732010-04-17 18:56:34 +00001845 // Parse a memory operand with no segment register.
1846 return ParseMemOperand(0, Parser.getTok().getLoc());
Chris Lattnercc2ad082010-01-15 18:27:19 +00001847 case AsmToken::Percent: {
Chris Lattnerb9270732010-04-17 18:56:34 +00001848 // Read the register.
Chris Lattnercc2ad082010-01-15 18:27:19 +00001849 unsigned RegNo;
Chris Lattner0c2538f2010-01-15 18:51:29 +00001850 SMLoc Start, End;
Craig Topper062a2ba2014-04-25 05:30:21 +00001851 if (ParseRegister(RegNo, Start, End)) return nullptr;
Bruno Cardoso Lopes306a1f92010-07-24 00:06:39 +00001852 if (RegNo == X86::EIZ || RegNo == X86::RIZ) {
Benjamin Kramer1930b002011-10-16 12:10:27 +00001853 Error(Start, "%eiz and %riz can only be used as index registers",
1854 SMRange(Start, End));
Craig Topper062a2ba2014-04-25 05:30:21 +00001855 return nullptr;
Bruno Cardoso Lopes306a1f92010-07-24 00:06:39 +00001856 }
Douglas Katzman0411e862016-10-05 15:23:35 +00001857 if (RegNo == X86::RIP) {
1858 Error(Start, "%rip can only be used as a base register",
1859 SMRange(Start, End));
1860 return nullptr;
1861 }
Bruno Cardoso Lopesd65cd1d2010-07-23 22:15:26 +00001862
Chris Lattnerb9270732010-04-17 18:56:34 +00001863 // If this is a segment register followed by a ':', then this is the start
1864 // of a memory reference, otherwise this is a normal register reference.
1865 if (getLexer().isNot(AsmToken::Colon))
1866 return X86Operand::CreateReg(RegNo, Start, End);
Bruno Cardoso Lopesd65cd1d2010-07-23 22:15:26 +00001867
Reid Kleckner0c5da972014-07-31 23:03:22 +00001868 if (!X86MCRegisterClasses[X86::SEGMENT_REGRegClassID].contains(RegNo))
1869 return ErrorOperand(Start, "invalid segment register");
1870
Chris Lattnerb9270732010-04-17 18:56:34 +00001871 getParser().Lex(); // Eat the colon.
1872 return ParseMemOperand(RegNo, Start);
Chris Lattnercc2ad082010-01-15 18:27:19 +00001873 }
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +00001874 case AsmToken::Dollar: {
1875 // $42 -> immediate.
Sean Callanan936b0d32010-01-19 21:44:56 +00001876 SMLoc Start = Parser.getTok().getLoc(), End;
Sean Callanana83fd7d2010-01-19 20:27:46 +00001877 Parser.Lex();
Daniel Dunbar73da11e2009-08-31 08:08:38 +00001878 const MCExpr *Val;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001879 if (getParser().parseExpression(Val, End))
Craig Topper062a2ba2014-04-25 05:30:21 +00001880 return nullptr;
Chris Lattner528d00b2010-01-15 19:28:38 +00001881 return X86Operand::CreateImm(Val, Start, End);
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +00001882 }
Elena Demikhovsky18fd4962015-03-02 15:00:34 +00001883 case AsmToken::LCurly:{
1884 SMLoc Start = Parser.getTok().getLoc(), End;
Akira Hatanakabd9fc282015-11-14 05:20:05 +00001885 if (getSTI().getFeatureBits()[X86::FeatureAVX512])
Elena Demikhovsky18fd4962015-03-02 15:00:34 +00001886 return ParseRoundingModeOp(Start, End);
Nirav Dave8601ac12016-08-02 17:56:03 +00001887 return ErrorOperand(Start, "Unexpected '{' in expression");
Elena Demikhovsky18fd4962015-03-02 15:00:34 +00001888 }
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +00001889 }
Daniel Dunbar2b11c7d2009-07-20 20:01:54 +00001890}
1891
Michael Zuckerman1bee6342016-10-18 13:52:39 +00001892// true on failure, false otherwise
1893// If no {z} mark was found - Parser doesn't advance
1894bool X86AsmParser::ParseZ(std::unique_ptr<X86Operand> &Z,
1895 const SMLoc &StartLoc) {
1896 MCAsmParser &Parser = getParser();
1897 // Assuming we are just pass the '{' mark, quering the next token
Coby Tayree179ff0e2016-11-20 09:31:11 +00001898 // Searched for {z}, but none was found. Return false, as no parsing error was
Michael Zuckerman1bee6342016-10-18 13:52:39 +00001899 // encountered
1900 if (!(getLexer().is(AsmToken::Identifier) &&
1901 (getLexer().getTok().getIdentifier() == "z")))
1902 return false;
1903 Parser.Lex(); // Eat z
1904 // Query and eat the '}' mark
1905 if (!getLexer().is(AsmToken::RCurly))
1906 return Error(getLexer().getLoc(), "Expected } at this point");
1907 Parser.Lex(); // Eat '}'
1908 // Assign Z with the {z} mark opernad
Benjamin Kramerfc54e352016-11-24 15:17:39 +00001909 Z = X86Operand::CreateToken("{z}", StartLoc);
Michael Zuckerman1bee6342016-10-18 13:52:39 +00001910 return false;
1911}
1912
1913// true on failure, false otherwise
David Blaikie960ea3f2014-06-08 16:18:35 +00001914bool X86AsmParser::HandleAVX512Operand(OperandVector &Operands,
1915 const MCParsedAsmOperand &Op) {
Rafael Espindola961d4692014-11-11 05:18:41 +00001916 MCAsmParser &Parser = getParser();
Akira Hatanakabd9fc282015-11-14 05:20:05 +00001917 if(getSTI().getFeatureBits()[X86::FeatureAVX512]) {
Elena Demikhovskyc9657012014-02-20 06:34:39 +00001918 if (getLexer().is(AsmToken::LCurly)) {
1919 // Eat "{" and mark the current place.
1920 const SMLoc consumedToken = consumeToken();
1921 // Distinguish {1to<NUM>} from {%k<NUM>}.
1922 if(getLexer().is(AsmToken::Integer)) {
1923 // Parse memory broadcasting ({1to<NUM>}).
1924 if (getLexer().getTok().getIntVal() != 1)
Michael Zuckerman1bee6342016-10-18 13:52:39 +00001925 return TokError("Expected 1to<NUM> at this point");
Elena Demikhovskyc9657012014-02-20 06:34:39 +00001926 Parser.Lex(); // Eat "1" of 1to8
1927 if (!getLexer().is(AsmToken::Identifier) ||
1928 !getLexer().getTok().getIdentifier().startswith("to"))
Michael Zuckerman1bee6342016-10-18 13:52:39 +00001929 return TokError("Expected 1to<NUM> at this point");
Elena Demikhovskyc9657012014-02-20 06:34:39 +00001930 // Recognize only reasonable suffixes.
1931 const char *BroadcastPrimitive =
1932 StringSwitch<const char*>(getLexer().getTok().getIdentifier())
Robert Khasanovbfa01312014-07-21 14:54:21 +00001933 .Case("to2", "{1to2}")
1934 .Case("to4", "{1to4}")
Elena Demikhovskyc9657012014-02-20 06:34:39 +00001935 .Case("to8", "{1to8}")
1936 .Case("to16", "{1to16}")
Craig Topper062a2ba2014-04-25 05:30:21 +00001937 .Default(nullptr);
Elena Demikhovskyc9657012014-02-20 06:34:39 +00001938 if (!BroadcastPrimitive)
Michael Zuckerman1bee6342016-10-18 13:52:39 +00001939 return TokError("Invalid memory broadcast primitive.");
Elena Demikhovskyc9657012014-02-20 06:34:39 +00001940 Parser.Lex(); // Eat "toN" of 1toN
1941 if (!getLexer().is(AsmToken::RCurly))
Michael Zuckerman1bee6342016-10-18 13:52:39 +00001942 return TokError("Expected } at this point");
Elena Demikhovskyc9657012014-02-20 06:34:39 +00001943 Parser.Lex(); // Eat "}"
1944 Operands.push_back(X86Operand::CreateToken(BroadcastPrimitive,
1945 consumedToken));
1946 // No AVX512 specific primitives can pass
1947 // after memory broadcasting, so return.
Michael Zuckerman1bee6342016-10-18 13:52:39 +00001948 return false;
Elena Demikhovskyc9657012014-02-20 06:34:39 +00001949 } else {
Michael Zuckerman1bee6342016-10-18 13:52:39 +00001950 // Parse either {k}{z}, {z}{k}, {k} or {z}
1951 // last one have no meaning, but GCC accepts it
1952 // Currently, we're just pass a '{' mark
1953 std::unique_ptr<X86Operand> Z;
1954 if (ParseZ(Z, consumedToken))
1955 return true;
1956 // Reaching here means that parsing of the allegadly '{z}' mark yielded
1957 // no errors.
1958 // Query for the need of further parsing for a {%k<NUM>} mark
1959 if (!Z || getLexer().is(AsmToken::LCurly)) {
Coby Tayree3bfb3652017-08-09 12:32:05 +00001960 SMLoc StartLoc = Z ? consumeToken() : consumedToken;
Michael Zuckerman1bee6342016-10-18 13:52:39 +00001961 // Parse an op-mask register mark ({%k<NUM>}), which is now to be
1962 // expected
Coby Tayree3bfb3652017-08-09 12:32:05 +00001963 unsigned RegNo;
Coby Tayree799fa2c2017-08-13 12:03:00 +00001964 SMLoc RegLoc;
1965 if (!ParseRegister(RegNo, RegLoc, StartLoc) &&
Coby Tayree3bfb3652017-08-09 12:32:05 +00001966 X86MCRegisterClasses[X86::VK1RegClassID].contains(RegNo)) {
Coby Tayree799fa2c2017-08-13 12:03:00 +00001967 if (RegNo == X86::K0)
1968 return Error(RegLoc, "Register k0 can't be used as write mask");
Elena Demikhovskyc9657012014-02-20 06:34:39 +00001969 if (!getLexer().is(AsmToken::RCurly))
Michael Zuckerman1bee6342016-10-18 13:52:39 +00001970 return Error(getLexer().getLoc(), "Expected } at this point");
1971 Operands.push_back(X86Operand::CreateToken("{", StartLoc));
Haojian Wuc1cae0b2017-08-09 12:49:20 +00001972 Operands.push_back(
1973 X86Operand::CreateReg(RegNo, StartLoc, StartLoc));
Michael Zuckerman1bee6342016-10-18 13:52:39 +00001974 Operands.push_back(X86Operand::CreateToken("}", consumeToken()));
1975 } else
1976 return Error(getLexer().getLoc(),
1977 "Expected an op-mask register at this point");
1978 // {%k<NUM>} mark is found, inquire for {z}
1979 if (getLexer().is(AsmToken::LCurly) && !Z) {
1980 // Have we've found a parsing error, or found no (expected) {z} mark
1981 // - report an error
1982 if (ParseZ(Z, consumeToken()) || !Z)
Coby Tayree3bfb3652017-08-09 12:32:05 +00001983 return Error(getLexer().getLoc(),
1984 "Expected a {z} mark at this point");
Michael Zuckerman1bee6342016-10-18 13:52:39 +00001985
Elena Demikhovskyc9657012014-02-20 06:34:39 +00001986 }
Michael Zuckerman1bee6342016-10-18 13:52:39 +00001987 // '{z}' on its own is meaningless, hence should be ignored.
1988 // on the contrary - have it been accompanied by a K register,
1989 // allow it.
1990 if (Z)
1991 Operands.push_back(std::move(Z));
Elena Demikhovskyc9657012014-02-20 06:34:39 +00001992 }
1993 }
1994 }
1995 }
Michael Zuckerman1bee6342016-10-18 13:52:39 +00001996 return false;
Elena Demikhovskyc9657012014-02-20 06:34:39 +00001997}
1998
Chris Lattnerb9270732010-04-17 18:56:34 +00001999/// ParseMemOperand: segment: disp(basereg, indexreg, scale). The '%ds:' prefix
2000/// has already been parsed if present.
David Blaikie960ea3f2014-06-08 16:18:35 +00002001std::unique_ptr<X86Operand> X86AsmParser::ParseMemOperand(unsigned SegReg,
2002 SMLoc MemStart) {
Bruno Cardoso Lopesd65cd1d2010-07-23 22:15:26 +00002003
Rafael Espindola961d4692014-11-11 05:18:41 +00002004 MCAsmParser &Parser = getParser();
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +00002005 // We have to disambiguate a parenthesized expression "(4+5)" from the start
2006 // of a memory operand with a missing displacement "(%ebx)" or "(,%eax)". The
Chris Lattner807a3bc2010-01-24 01:07:33 +00002007 // only way to do this without lookahead is to eat the '(' and see what is
2008 // after it.
Jim Grosbach13760bd2015-05-30 01:25:56 +00002009 const MCExpr *Disp = MCConstantExpr::create(0, getParser().getContext());
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +00002010 if (getLexer().isNot(AsmToken::LParen)) {
Chris Lattnere17df0b2010-01-15 19:39:23 +00002011 SMLoc ExprEnd;
Craig Topper062a2ba2014-04-25 05:30:21 +00002012 if (getParser().parseExpression(Disp, ExprEnd)) return nullptr;
Bruno Cardoso Lopesd65cd1d2010-07-23 22:15:26 +00002013
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +00002014 // After parsing the base expression we could either have a parenthesized
2015 // memory address or not. If not, return now. If so, eat the (.
2016 if (getLexer().isNot(AsmToken::LParen)) {
Daniel Dunbara4fc8d92009-07-31 22:22:54 +00002017 // Unless we have a segment register, treat this as an immediate.
Chris Lattnera2bbb7c2010-01-15 18:44:13 +00002018 if (SegReg == 0)
Craig Topper055845f2015-01-02 07:02:25 +00002019 return X86Operand::CreateMem(getPointerWidth(), Disp, MemStart, ExprEnd);
2020 return X86Operand::CreateMem(getPointerWidth(), SegReg, Disp, 0, 0, 1,
2021 MemStart, ExprEnd);
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +00002022 }
Bruno Cardoso Lopesd65cd1d2010-07-23 22:15:26 +00002023
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +00002024 // Eat the '('.
Sean Callanana83fd7d2010-01-19 20:27:46 +00002025 Parser.Lex();
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +00002026 } else {
2027 // Okay, we have a '('. We don't know if this is an expression or not, but
2028 // so we have to eat the ( to see beyond it.
Sean Callanan936b0d32010-01-19 21:44:56 +00002029 SMLoc LParenLoc = Parser.getTok().getLoc();
Sean Callanana83fd7d2010-01-19 20:27:46 +00002030 Parser.Lex(); // Eat the '('.
Bruno Cardoso Lopesd65cd1d2010-07-23 22:15:26 +00002031
Kevin Enderby7d912182009-09-03 17:15:07 +00002032 if (getLexer().is(AsmToken::Percent) || getLexer().is(AsmToken::Comma)) {
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +00002033 // Nothing to do here, fall into the code below with the '(' part of the
2034 // memory operand consumed.
2035 } else {
Chris Lattner528d00b2010-01-15 19:28:38 +00002036 SMLoc ExprEnd;
Konstantin Belochapka34777112017-09-22 23:37:48 +00002037 getLexer().UnLex(AsmToken(AsmToken::LParen, "("));
Bruno Cardoso Lopesd65cd1d2010-07-23 22:15:26 +00002038
Konstantin Belochapka34777112017-09-22 23:37:48 +00002039 // It must be either an parenthesized expression, or an expression that
2040 // begins from a parenthesized expression, parse it now. Example: (1+2) or
2041 // (1+2)+3
2042 if (getParser().parseExpression(Disp, ExprEnd))
Craig Topper062a2ba2014-04-25 05:30:21 +00002043 return nullptr;
Bruno Cardoso Lopesd65cd1d2010-07-23 22:15:26 +00002044
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +00002045 // After parsing the base expression we could either have a parenthesized
2046 // memory address or not. If not, return now. If so, eat the (.
2047 if (getLexer().isNot(AsmToken::LParen)) {
Daniel Dunbara4fc8d92009-07-31 22:22:54 +00002048 // Unless we have a segment register, treat this as an immediate.
Chris Lattnera2bbb7c2010-01-15 18:44:13 +00002049 if (SegReg == 0)
Craig Topper055845f2015-01-02 07:02:25 +00002050 return X86Operand::CreateMem(getPointerWidth(), Disp, LParenLoc,
2051 ExprEnd);
2052 return X86Operand::CreateMem(getPointerWidth(), SegReg, Disp, 0, 0, 1,
2053 MemStart, ExprEnd);
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +00002054 }
Bruno Cardoso Lopesd65cd1d2010-07-23 22:15:26 +00002055
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +00002056 // Eat the '('.
Sean Callanana83fd7d2010-01-19 20:27:46 +00002057 Parser.Lex();
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +00002058 }
2059 }
Bruno Cardoso Lopesd65cd1d2010-07-23 22:15:26 +00002060
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +00002061 // If we reached here, then we just ate the ( of the memory operand. Process
2062 // the rest of the memory operand.
Daniel Dunbar3ebf8482009-07-31 20:53:16 +00002063 unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
David Woodhouse6dbda442014-01-08 12:58:28 +00002064 SMLoc IndexLoc, BaseLoc;
Bruno Cardoso Lopesd65cd1d2010-07-23 22:15:26 +00002065
Chris Lattner0c2538f2010-01-15 18:51:29 +00002066 if (getLexer().is(AsmToken::Percent)) {
Benjamin Kramer1930b002011-10-16 12:10:27 +00002067 SMLoc StartLoc, EndLoc;
David Woodhouse6dbda442014-01-08 12:58:28 +00002068 BaseLoc = Parser.getTok().getLoc();
Craig Topper062a2ba2014-04-25 05:30:21 +00002069 if (ParseRegister(BaseReg, StartLoc, EndLoc)) return nullptr;
Bruno Cardoso Lopes306a1f92010-07-24 00:06:39 +00002070 if (BaseReg == X86::EIZ || BaseReg == X86::RIZ) {
Benjamin Kramer1930b002011-10-16 12:10:27 +00002071 Error(StartLoc, "eiz and riz can only be used as index registers",
2072 SMRange(StartLoc, EndLoc));
Craig Topper062a2ba2014-04-25 05:30:21 +00002073 return nullptr;
Bruno Cardoso Lopes306a1f92010-07-24 00:06:39 +00002074 }
Chris Lattner0c2538f2010-01-15 18:51:29 +00002075 }
Bruno Cardoso Lopesd65cd1d2010-07-23 22:15:26 +00002076
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +00002077 if (getLexer().is(AsmToken::Comma)) {
Sean Callanana83fd7d2010-01-19 20:27:46 +00002078 Parser.Lex(); // Eat the comma.
Kevin Enderbyfb3110b2012-03-12 21:32:09 +00002079 IndexLoc = Parser.getTok().getLoc();
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +00002080
2081 // Following the comma we should have either an index register, or a scale
2082 // value. We don't support the later form, but we want to parse it
2083 // correctly.
2084 //
2085 // Not that even though it would be completely consistent to support syntax
Bruno Cardoso Lopes306a1f92010-07-24 00:06:39 +00002086 // like "1(%eax,,1)", the assembler doesn't. Use "eiz" or "riz" for this.
Kevin Enderby7d912182009-09-03 17:15:07 +00002087 if (getLexer().is(AsmToken::Percent)) {
Chris Lattner0c2538f2010-01-15 18:51:29 +00002088 SMLoc L;
Douglas Katzman0411e862016-10-05 15:23:35 +00002089 if (ParseRegister(IndexReg, L, L))
2090 return nullptr;
2091 if (BaseReg == X86::RIP) {
2092 Error(IndexLoc, "%rip as base register can not have an index register");
2093 return nullptr;
2094 }
2095 if (IndexReg == X86::RIP) {
2096 Error(IndexLoc, "%rip is not allowed as an index register");
2097 return nullptr;
2098 }
Bruno Cardoso Lopesd65cd1d2010-07-23 22:15:26 +00002099
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +00002100 if (getLexer().isNot(AsmToken::RParen)) {
2101 // Parse the scale amount:
2102 // ::= ',' [scale-expression]
Chris Lattnera2bbb7c2010-01-15 18:44:13 +00002103 if (getLexer().isNot(AsmToken::Comma)) {
Sean Callanan936b0d32010-01-19 21:44:56 +00002104 Error(Parser.getTok().getLoc(),
Chris Lattnera2bbb7c2010-01-15 18:44:13 +00002105 "expected comma in scale expression");
Craig Topper062a2ba2014-04-25 05:30:21 +00002106 return nullptr;
Chris Lattnera2bbb7c2010-01-15 18:44:13 +00002107 }
Sean Callanana83fd7d2010-01-19 20:27:46 +00002108 Parser.Lex(); // Eat the comma.
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +00002109
2110 if (getLexer().isNot(AsmToken::RParen)) {
Sean Callanan936b0d32010-01-19 21:44:56 +00002111 SMLoc Loc = Parser.getTok().getLoc();
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +00002112
2113 int64_t ScaleVal;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002114 if (getParser().parseAbsoluteExpression(ScaleVal)){
Kevin Enderbydeed5aa2012-03-09 22:24:10 +00002115 Error(Loc, "expected scale expression");
Craig Topper062a2ba2014-04-25 05:30:21 +00002116 return nullptr;
Craig Topper6bf3ed42012-07-18 04:59:16 +00002117 }
Bruno Cardoso Lopesd65cd1d2010-07-23 22:15:26 +00002118
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +00002119 // Validate the scale amount.
NAKAMURA Takumi0a7d0ad2015-09-22 11:15:07 +00002120 if (X86MCRegisterClasses[X86::GR16RegClassID].contains(BaseReg) &&
David Woodhouse6dbda442014-01-08 12:58:28 +00002121 ScaleVal != 1) {
2122 Error(Loc, "scale factor in 16-bit address must be 1");
Craig Topper062a2ba2014-04-25 05:30:21 +00002123 return nullptr;
NAKAMURA Takumi0a7d0ad2015-09-22 11:15:07 +00002124 }
2125 if (ScaleVal != 1 && ScaleVal != 2 && ScaleVal != 4 &&
2126 ScaleVal != 8) {
Chris Lattnera2bbb7c2010-01-15 18:44:13 +00002127 Error(Loc, "scale factor in address must be 1, 2, 4 or 8");
Craig Topper062a2ba2014-04-25 05:30:21 +00002128 return nullptr;
Chris Lattnera2bbb7c2010-01-15 18:44:13 +00002129 }
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +00002130 Scale = (unsigned)ScaleVal;
2131 }
2132 }
2133 } else if (getLexer().isNot(AsmToken::RParen)) {
Daniel Dunbar94b84a12010-08-24 19:13:38 +00002134 // A scale amount without an index is ignored.
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +00002135 // index.
Sean Callanan936b0d32010-01-19 21:44:56 +00002136 SMLoc Loc = Parser.getTok().getLoc();
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +00002137
2138 int64_t Value;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002139 if (getParser().parseAbsoluteExpression(Value))
Craig Topper062a2ba2014-04-25 05:30:21 +00002140 return nullptr;
Bruno Cardoso Lopesd65cd1d2010-07-23 22:15:26 +00002141
Daniel Dunbar94b84a12010-08-24 19:13:38 +00002142 if (Value != 1)
2143 Warning(Loc, "scale factor without index register is ignored");
2144 Scale = 1;
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +00002145 }
2146 }
Bruno Cardoso Lopesd65cd1d2010-07-23 22:15:26 +00002147
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +00002148 // Ok, we've eaten the memory operand, verify we have a ')' and eat it too.
Chris Lattnera2bbb7c2010-01-15 18:44:13 +00002149 if (getLexer().isNot(AsmToken::RParen)) {
Sean Callanan936b0d32010-01-19 21:44:56 +00002150 Error(Parser.getTok().getLoc(), "unexpected token in memory operand");
Craig Topper062a2ba2014-04-25 05:30:21 +00002151 return nullptr;
Chris Lattnera2bbb7c2010-01-15 18:44:13 +00002152 }
Jordan Rosee8f1eae2013-01-07 19:00:49 +00002153 SMLoc MemEnd = Parser.getTok().getEndLoc();
Sean Callanana83fd7d2010-01-19 20:27:46 +00002154 Parser.Lex(); // Eat the ')'.
Bruno Cardoso Lopesd65cd1d2010-07-23 22:15:26 +00002155
David Woodhouse6dbda442014-01-08 12:58:28 +00002156 // Check for use of invalid 16-bit registers. Only BX/BP/SI/DI are allowed,
2157 // and then only in non-64-bit modes. Except for DX, which is a special case
2158 // because an unofficial form of in/out instructions uses it.
2159 if (X86MCRegisterClasses[X86::GR16RegClassID].contains(BaseReg) &&
2160 (is64BitMode() || (BaseReg != X86::BX && BaseReg != X86::BP &&
2161 BaseReg != X86::SI && BaseReg != X86::DI)) &&
2162 BaseReg != X86::DX) {
2163 Error(BaseLoc, "invalid 16-bit base register");
Craig Topper062a2ba2014-04-25 05:30:21 +00002164 return nullptr;
David Woodhouse6dbda442014-01-08 12:58:28 +00002165 }
2166 if (BaseReg == 0 &&
2167 X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg)) {
2168 Error(IndexLoc, "16-bit memory operand may not include only index register");
Craig Topper062a2ba2014-04-25 05:30:21 +00002169 return nullptr;
David Woodhouse6dbda442014-01-08 12:58:28 +00002170 }
Kevin Enderbybc570f22014-01-23 22:34:42 +00002171
2172 StringRef ErrMsg;
Andrew V. Tischenko32e9b1a2017-07-25 13:05:12 +00002173 if (CheckBaseRegAndIndexRegAndScale(BaseReg, IndexReg, Scale, ErrMsg)) {
Kevin Enderbybc570f22014-01-23 22:34:42 +00002174 Error(BaseLoc, ErrMsg);
Craig Topper062a2ba2014-04-25 05:30:21 +00002175 return nullptr;
Kevin Enderbyfb3110b2012-03-12 21:32:09 +00002176 }
2177
Reid Klecknerb7e2f602014-07-31 23:26:35 +00002178 if (SegReg || BaseReg || IndexReg)
Craig Topper055845f2015-01-02 07:02:25 +00002179 return X86Operand::CreateMem(getPointerWidth(), SegReg, Disp, BaseReg,
2180 IndexReg, Scale, MemStart, MemEnd);
2181 return X86Operand::CreateMem(getPointerWidth(), Disp, MemStart, MemEnd);
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +00002182}
2183
David Blaikie960ea3f2014-06-08 16:18:35 +00002184bool X86AsmParser::ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
2185 SMLoc NameLoc, OperandVector &Operands) {
Rafael Espindola961d4692014-11-11 05:18:41 +00002186 MCAsmParser &Parser = getParser();
Chad Rosierf0e87202012-10-25 20:41:34 +00002187 InstInfo = &Info;
Chris Lattner2cb092d2010-10-30 19:23:13 +00002188 StringRef PatchedName = Name;
Daniel Dunbar0e767d72010-05-25 19:49:32 +00002189
Coby Tayree48d67cd2017-07-30 11:12:47 +00002190 if ((Name.equals("jmp") || Name.equals("jc") || Name.equals("jz")) &&
2191 isParsingIntelSyntax() && isParsingInlineAsm()) {
Michael Zuckerman174d2e72016-10-14 08:09:40 +00002192 StringRef NextTok = Parser.getTok().getString();
2193 if (NextTok == "short") {
2194 SMLoc NameEndLoc =
2195 NameLoc.getFromPointer(NameLoc.getPointer() + Name.size());
2196 // Eat the short keyword
2197 Parser.Lex();
2198 // MS ignores the short keyword, it determines the jmp type based
2199 // on the distance of the label
2200 InstInfo->AsmRewrites->emplace_back(AOK_Skip, NameEndLoc,
2201 NextTok.size() + 1);
2202 }
2203 }
2204
Chris Lattner7e8a99b2010-11-28 20:23:50 +00002205 // FIXME: Hack to recognize setneb as setne.
2206 if (PatchedName.startswith("set") && PatchedName.endswith("b") &&
2207 PatchedName != "setb" && PatchedName != "setnb")
2208 PatchedName = PatchedName.substr(0, Name.size()-1);
Chad Rosier51afe632012-06-27 22:34:28 +00002209
Daniel Dunbar0e767d72010-05-25 19:49:32 +00002210 // FIXME: Hack to recognize cmp<comparison code>{ss,sd,ps,pd}.
Bruno Cardoso Lopes3183dd52010-06-23 21:10:57 +00002211 if ((PatchedName.startswith("cmp") || PatchedName.startswith("vcmp")) &&
Daniel Dunbar0e767d72010-05-25 19:49:32 +00002212 (PatchedName.endswith("ss") || PatchedName.endswith("sd") ||
2213 PatchedName.endswith("ps") || PatchedName.endswith("pd"))) {
Craig Toppera0a603e2012-03-29 07:11:23 +00002214 bool IsVCMP = PatchedName[0] == 'v';
Craig Topper78c424d2015-02-15 07:13:48 +00002215 unsigned CCIdx = IsVCMP ? 4 : 3;
2216 unsigned ComparisonCode = StringSwitch<unsigned>(
2217 PatchedName.slice(CCIdx, PatchedName.size() - 2))
Craig Toppera0a603e2012-03-29 07:11:23 +00002218 .Case("eq", 0x00)
Michael Zuckerman72b72232016-01-25 08:43:26 +00002219 .Case("eq_oq", 0x00)
Craig Toppera0a603e2012-03-29 07:11:23 +00002220 .Case("lt", 0x01)
Michael Zuckerman72b72232016-01-25 08:43:26 +00002221 .Case("lt_os", 0x01)
Craig Toppera0a603e2012-03-29 07:11:23 +00002222 .Case("le", 0x02)
Michael Zuckerman72b72232016-01-25 08:43:26 +00002223 .Case("le_os", 0x02)
Craig Toppera0a603e2012-03-29 07:11:23 +00002224 .Case("unord", 0x03)
Michael Zuckerman72b72232016-01-25 08:43:26 +00002225 .Case("unord_q", 0x03)
Craig Toppera0a603e2012-03-29 07:11:23 +00002226 .Case("neq", 0x04)
Michael Zuckerman72b72232016-01-25 08:43:26 +00002227 .Case("neq_uq", 0x04)
Craig Toppera0a603e2012-03-29 07:11:23 +00002228 .Case("nlt", 0x05)
Michael Zuckerman72b72232016-01-25 08:43:26 +00002229 .Case("nlt_us", 0x05)
Craig Toppera0a603e2012-03-29 07:11:23 +00002230 .Case("nle", 0x06)
Michael Zuckerman72b72232016-01-25 08:43:26 +00002231 .Case("nle_us", 0x06)
Craig Toppera0a603e2012-03-29 07:11:23 +00002232 .Case("ord", 0x07)
Michael Zuckerman72b72232016-01-25 08:43:26 +00002233 .Case("ord_q", 0x07)
Craig Toppera0a603e2012-03-29 07:11:23 +00002234 /* AVX only from here */
2235 .Case("eq_uq", 0x08)
2236 .Case("nge", 0x09)
Michael Zuckerman72b72232016-01-25 08:43:26 +00002237 .Case("nge_us", 0x09)
Bruno Cardoso Lopes6c614512010-07-07 22:24:03 +00002238 .Case("ngt", 0x0A)
Michael Zuckerman72b72232016-01-25 08:43:26 +00002239 .Case("ngt_us", 0x0A)
Bruno Cardoso Lopes6c614512010-07-07 22:24:03 +00002240 .Case("false", 0x0B)
Michael Zuckerman72b72232016-01-25 08:43:26 +00002241 .Case("false_oq", 0x0B)
Bruno Cardoso Lopes6c614512010-07-07 22:24:03 +00002242 .Case("neq_oq", 0x0C)
2243 .Case("ge", 0x0D)
Michael Zuckerman72b72232016-01-25 08:43:26 +00002244 .Case("ge_os", 0x0D)
Bruno Cardoso Lopes6c614512010-07-07 22:24:03 +00002245 .Case("gt", 0x0E)
Michael Zuckerman72b72232016-01-25 08:43:26 +00002246 .Case("gt_os", 0x0E)
Bruno Cardoso Lopes6c614512010-07-07 22:24:03 +00002247 .Case("true", 0x0F)
Michael Zuckerman72b72232016-01-25 08:43:26 +00002248 .Case("true_uq", 0x0F)
Bruno Cardoso Lopes6c614512010-07-07 22:24:03 +00002249 .Case("eq_os", 0x10)
2250 .Case("lt_oq", 0x11)
2251 .Case("le_oq", 0x12)
2252 .Case("unord_s", 0x13)
2253 .Case("neq_us", 0x14)
2254 .Case("nlt_uq", 0x15)
2255 .Case("nle_uq", 0x16)
2256 .Case("ord_s", 0x17)
2257 .Case("eq_us", 0x18)
2258 .Case("nge_uq", 0x19)
2259 .Case("ngt_uq", 0x1A)
2260 .Case("false_os", 0x1B)
2261 .Case("neq_os", 0x1C)
2262 .Case("ge_oq", 0x1D)
2263 .Case("gt_oq", 0x1E)
2264 .Case("true_us", 0x1F)
Daniel Dunbar0e767d72010-05-25 19:49:32 +00002265 .Default(~0U);
Craig Topper78c424d2015-02-15 07:13:48 +00002266 if (ComparisonCode != ~0U && (IsVCMP || ComparisonCode < 8)) {
Craig Topper43860832015-02-14 21:54:03 +00002267
Craig Topper78c424d2015-02-15 07:13:48 +00002268 Operands.push_back(X86Operand::CreateToken(PatchedName.slice(0, CCIdx),
Craig Topper43860832015-02-14 21:54:03 +00002269 NameLoc));
2270
Jim Grosbach13760bd2015-05-30 01:25:56 +00002271 const MCExpr *ImmOp = MCConstantExpr::create(ComparisonCode,
Craig Topper43860832015-02-14 21:54:03 +00002272 getParser().getContext());
2273 Operands.push_back(X86Operand::CreateImm(ImmOp, NameLoc, NameLoc));
2274
2275 PatchedName = PatchedName.substr(PatchedName.size() - 2);
Daniel Dunbar0e767d72010-05-25 19:49:32 +00002276 }
2277 }
Bruno Cardoso Lopesea0e05a2010-07-23 18:41:12 +00002278
Craig Topper78c424d2015-02-15 07:13:48 +00002279 // FIXME: Hack to recognize vpcmp<comparison code>{ub,uw,ud,uq,b,w,d,q}.
2280 if (PatchedName.startswith("vpcmp") &&
2281 (PatchedName.endswith("b") || PatchedName.endswith("w") ||
2282 PatchedName.endswith("d") || PatchedName.endswith("q"))) {
2283 unsigned CCIdx = PatchedName.drop_back().back() == 'u' ? 2 : 1;
2284 unsigned ComparisonCode = StringSwitch<unsigned>(
2285 PatchedName.slice(5, PatchedName.size() - CCIdx))
2286 .Case("eq", 0x0) // Only allowed on unsigned. Checked below.
2287 .Case("lt", 0x1)
2288 .Case("le", 0x2)
2289 //.Case("false", 0x3) // Not a documented alias.
2290 .Case("neq", 0x4)
2291 .Case("nlt", 0x5)
2292 .Case("nle", 0x6)
2293 //.Case("true", 0x7) // Not a documented alias.
2294 .Default(~0U);
2295 if (ComparisonCode != ~0U && (ComparisonCode != 0 || CCIdx == 2)) {
2296 Operands.push_back(X86Operand::CreateToken("vpcmp", NameLoc));
2297
Jim Grosbach13760bd2015-05-30 01:25:56 +00002298 const MCExpr *ImmOp = MCConstantExpr::create(ComparisonCode,
Craig Topper78c424d2015-02-15 07:13:48 +00002299 getParser().getContext());
2300 Operands.push_back(X86Operand::CreateImm(ImmOp, NameLoc, NameLoc));
2301
2302 PatchedName = PatchedName.substr(PatchedName.size() - CCIdx);
2303 }
2304 }
2305
Craig Topper916708f2015-02-13 07:42:25 +00002306 // FIXME: Hack to recognize vpcom<comparison code>{ub,uw,ud,uq,b,w,d,q}.
2307 if (PatchedName.startswith("vpcom") &&
2308 (PatchedName.endswith("b") || PatchedName.endswith("w") ||
2309 PatchedName.endswith("d") || PatchedName.endswith("q"))) {
Craig Topper78c424d2015-02-15 07:13:48 +00002310 unsigned CCIdx = PatchedName.drop_back().back() == 'u' ? 2 : 1;
2311 unsigned ComparisonCode = StringSwitch<unsigned>(
2312 PatchedName.slice(5, PatchedName.size() - CCIdx))
Craig Topper916708f2015-02-13 07:42:25 +00002313 .Case("lt", 0x0)
2314 .Case("le", 0x1)
2315 .Case("gt", 0x2)
2316 .Case("ge", 0x3)
2317 .Case("eq", 0x4)
2318 .Case("neq", 0x5)
2319 .Case("false", 0x6)
2320 .Case("true", 0x7)
2321 .Default(~0U);
Craig Topper78c424d2015-02-15 07:13:48 +00002322 if (ComparisonCode != ~0U) {
Craig Topper916708f2015-02-13 07:42:25 +00002323 Operands.push_back(X86Operand::CreateToken("vpcom", NameLoc));
2324
Jim Grosbach13760bd2015-05-30 01:25:56 +00002325 const MCExpr *ImmOp = MCConstantExpr::create(ComparisonCode,
Craig Topper916708f2015-02-13 07:42:25 +00002326 getParser().getContext());
2327 Operands.push_back(X86Operand::CreateImm(ImmOp, NameLoc, NameLoc));
2328
Craig Topper78c424d2015-02-15 07:13:48 +00002329 PatchedName = PatchedName.substr(PatchedName.size() - CCIdx);
Craig Topper916708f2015-02-13 07:42:25 +00002330 }
2331 }
2332
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +00002333
Chris Lattner086a83a2010-09-08 05:17:37 +00002334 // Determine whether this is an instruction prefix.
Coby Tayreec54c5cb2017-08-21 07:50:15 +00002335 // FIXME:
Craig Topper0768bce2017-09-26 21:35:04 +00002336 // Enhance prefixes integrity robustness. for example, following forms
Coby Tayreec54c5cb2017-08-21 07:50:15 +00002337 // are currently tolerated:
2338 // repz repnz <insn> ; GAS errors for the use of two similar prefixes
2339 // lock addq %rax, %rbx ; Destination operand must be of memory type
2340 // xacquire <insn> ; xacquire must be accompanied by 'lock'
2341 bool isPrefix = StringSwitch<bool>(Name)
Andrew V. Tischenkobfc90612017-10-16 11:14:29 +00002342 .Cases("rex64", "data32", "data16", true)
2343 .Cases("xacquire", "xrelease", true)
2344 .Cases("acquire", "release", isParsingIntelSyntax())
2345 .Default(false);
2346
2347 auto isLockRepeatPrefix = [](StringRef N) {
2348 return StringSwitch<bool>(N)
2349 .Cases("lock", "rep", "repe", "repz", "repne", "repnz", true)
2350 .Default(false);
2351 };
Michael J. Spencer530ce852010-10-09 11:00:50 +00002352
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00002353 bool CurlyAsEndOfStatement = false;
Andrew V. Tischenkobfc90612017-10-16 11:14:29 +00002354
2355 unsigned Flags = X86::IP_NO_PREFIX;
2356 while (isLockRepeatPrefix(Name.lower())) {
2357 unsigned Prefix =
2358 StringSwitch<unsigned>(Name)
2359 .Cases("lock", "lock", X86::IP_HAS_LOCK)
2360 .Cases("rep", "repe", "repz", X86::IP_HAS_REPEAT)
2361 .Cases("repne", "repnz", X86::IP_HAS_REPEAT_NE)
2362 .Default(X86::IP_NO_PREFIX); // Invalid prefix (impossible)
2363 Flags |= Prefix;
2364 Name = Parser.getTok().getString();
2365 Parser.Lex(); // eat the prefix
2366 // Hack: we could have something like
2367 // "lock; cmpxchg16b $1" or "lock\0A\09incl" or "lock/incl"
2368 while (Name.startswith(";") || Name.startswith("\n") ||
2369 Name.startswith("\t") or Name.startswith("/")) {
2370 Name = Parser.getTok().getString();
2371 Parser.Lex(); // go to next prefix or instr
2372 }
2373 }
2374
2375 if (Flags)
2376 PatchedName = Name;
2377 Operands.push_back(X86Operand::CreateToken(PatchedName, NameLoc));
2378
Chris Lattner086a83a2010-09-08 05:17:37 +00002379 // This does the actual operand parsing. Don't parse any more if we have a
2380 // prefix juxtaposed with an operation like "lock incl 4(%rax)", because we
2381 // just want to parse the "lock" as the first instruction and the "incl" as
2382 // the next one.
2383 if (getLexer().isNot(AsmToken::EndOfStatement) && !isPrefix) {
Daniel Dunbar71527c12009-08-11 05:00:25 +00002384 // Parse '*' modifier.
Alp Tokera5b88a52013-12-02 16:06:06 +00002385 if (getLexer().is(AsmToken::Star))
2386 Operands.push_back(X86Operand::CreateToken("*", consumeToken()));
Daniel Dunbar71527c12009-08-11 05:00:25 +00002387
Elena Demikhovskyc9657012014-02-20 06:34:39 +00002388 // Read the operands.
Kirill Bobyrev6afbaf02017-01-18 16:34:25 +00002389 while(1) {
David Blaikie960ea3f2014-06-08 16:18:35 +00002390 if (std::unique_ptr<X86Operand> Op = ParseOperand()) {
2391 Operands.push_back(std::move(Op));
Michael Zuckerman1bee6342016-10-18 13:52:39 +00002392 if (HandleAVX512Operand(Operands, *Operands.back()))
Elena Demikhovsky89529742013-09-12 08:55:00 +00002393 return true;
Elena Demikhovskyc9657012014-02-20 06:34:39 +00002394 } else {
Elena Demikhovskyc9657012014-02-20 06:34:39 +00002395 return true;
Elena Demikhovsky89529742013-09-12 08:55:00 +00002396 }
Elena Demikhovskyc9657012014-02-20 06:34:39 +00002397 // check for comma and eat it
2398 if (getLexer().is(AsmToken::Comma))
2399 Parser.Lex();
2400 else
2401 break;
2402 }
Elena Demikhovsky89529742013-09-12 08:55:00 +00002403
Hiroshi Inouee9dea6e2017-07-13 06:48:39 +00002404 // In MS inline asm curly braces mark the beginning/end of a block,
2405 // therefore they should be interepreted as end of statement
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00002406 CurlyAsEndOfStatement =
2407 isParsingIntelSyntax() && isParsingInlineAsm() &&
2408 (getLexer().is(AsmToken::LCurly) || getLexer().is(AsmToken::RCurly));
2409 if (getLexer().isNot(AsmToken::EndOfStatement) && !CurlyAsEndOfStatement)
Nirav Dave2364748a2016-09-16 18:30:20 +00002410 return TokError("unexpected token in argument list");
Elena Demikhovskyc9657012014-02-20 06:34:39 +00002411 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00002412
Elena Demikhovskyc9657012014-02-20 06:34:39 +00002413 // Consume the EndOfStatement or the prefix separator Slash
Elena Demikhovsky9f09b3e2014-02-20 07:00:10 +00002414 if (getLexer().is(AsmToken::EndOfStatement) ||
2415 (isPrefix && getLexer().is(AsmToken::Slash)))
Elena Demikhovskyc9657012014-02-20 06:34:39 +00002416 Parser.Lex();
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00002417 else if (CurlyAsEndOfStatement)
2418 // Add an actual EndOfStatement before the curly brace
2419 Info.AsmRewrites->emplace_back(AOK_EndOfStatement,
2420 getLexer().getTok().getLoc(), 0);
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +00002421
Michael Zuckermanfd3fe9e2015-11-12 16:58:51 +00002422 // This is for gas compatibility and cannot be done in td.
2423 // Adding "p" for some floating point with no argument.
2424 // For example: fsub --> fsubp
2425 bool IsFp =
2426 Name == "fsub" || Name == "fdiv" || Name == "fsubr" || Name == "fdivr";
2427 if (IsFp && Operands.size() == 1) {
2428 const char *Repl = StringSwitch<const char *>(Name)
2429 .Case("fsub", "fsubp")
2430 .Case("fdiv", "fdivp")
2431 .Case("fsubr", "fsubrp")
2432 .Case("fdivr", "fdivrp");
2433 static_cast<X86Operand &>(*Operands[0]).setTokenValue(Repl);
2434 }
2435
Nirav Davef45fd2b2016-08-08 18:01:04 +00002436 // Moving a 32 or 16 bit value into a segment register has the same
2437 // behavior. Modify such instructions to always take shorter form.
2438 if ((Name == "mov" || Name == "movw" || Name == "movl") &&
2439 (Operands.size() == 3)) {
2440 X86Operand &Op1 = (X86Operand &)*Operands[1];
2441 X86Operand &Op2 = (X86Operand &)*Operands[2];
2442 SMLoc Loc = Op1.getEndLoc();
2443 if (Op1.isReg() && Op2.isReg() &&
2444 X86MCRegisterClasses[X86::SEGMENT_REGRegClassID].contains(
2445 Op2.getReg()) &&
2446 (X86MCRegisterClasses[X86::GR16RegClassID].contains(Op1.getReg()) ||
2447 X86MCRegisterClasses[X86::GR32RegClassID].contains(Op1.getReg()))) {
2448 // Change instruction name to match new instruction.
2449 if (Name != "mov" && Name[3] == (is16BitMode() ? 'l' : 'w')) {
2450 Name = is16BitMode() ? "movw" : "movl";
2451 Operands[0] = X86Operand::CreateToken(Name, NameLoc);
2452 }
2453 // Select the correct equivalent 16-/32-bit source register.
2454 unsigned Reg =
2455 getX86SubSuperRegisterOrZero(Op1.getReg(), is16BitMode() ? 16 : 32);
2456 Operands[1] = X86Operand::CreateReg(Reg, Loc, Loc);
2457 }
2458 }
2459
Nirav Dave8e103802016-06-29 19:54:27 +00002460 // This is a terrible hack to handle "out[s]?[bwl]? %al, (%dx)" ->
Chris Lattnerb6f8e822010-11-06 19:25:43 +00002461 // "outb %al, %dx". Out doesn't take a memory form, but this is a widely
2462 // documented form in various unofficial manuals, so a lot of code uses it.
Nirav Dave8e103802016-06-29 19:54:27 +00002463 if ((Name == "outb" || Name == "outsb" || Name == "outw" || Name == "outsw" ||
2464 Name == "outl" || Name == "outsl" || Name == "out" || Name == "outs") &&
Chris Lattnerb6f8e822010-11-06 19:25:43 +00002465 Operands.size() == 3) {
David Blaikie960ea3f2014-06-08 16:18:35 +00002466 X86Operand &Op = (X86Operand &)*Operands.back();
Chris Lattnerb6f8e822010-11-06 19:25:43 +00002467 if (Op.isMem() && Op.Mem.SegReg == 0 &&
2468 isa<MCConstantExpr>(Op.Mem.Disp) &&
2469 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
2470 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
2471 SMLoc Loc = Op.getEndLoc();
2472 Operands.back() = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
Chris Lattnerb6f8e822010-11-06 19:25:43 +00002473 }
2474 }
Nirav Dave8e103802016-06-29 19:54:27 +00002475 // Same hack for "in[s]?[bwl]? (%dx), %al" -> "inb %dx, %al".
2476 if ((Name == "inb" || Name == "insb" || Name == "inw" || Name == "insw" ||
2477 Name == "inl" || Name == "insl" || Name == "in" || Name == "ins") &&
Joerg Sonnenbergerb7e635d2011-02-22 20:40:09 +00002478 Operands.size() == 3) {
David Blaikie960ea3f2014-06-08 16:18:35 +00002479 X86Operand &Op = (X86Operand &)*Operands[1];
Joerg Sonnenbergerb7e635d2011-02-22 20:40:09 +00002480 if (Op.isMem() && Op.Mem.SegReg == 0 &&
2481 isa<MCConstantExpr>(Op.Mem.Disp) &&
2482 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
2483 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
2484 SMLoc Loc = Op.getEndLoc();
David Blaikie960ea3f2014-06-08 16:18:35 +00002485 Operands[1] = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
Joerg Sonnenbergerb7e635d2011-02-22 20:40:09 +00002486 }
2487 }
David Woodhouse4ce66062014-01-22 15:08:55 +00002488
Marina Yatsinab9f4f622016-01-19 15:37:56 +00002489 SmallVector<std::unique_ptr<MCParsedAsmOperand>, 2> TmpOperands;
2490 bool HadVerifyError = false;
2491
David Woodhouse4ce66062014-01-22 15:08:55 +00002492 // Append default arguments to "ins[bwld]"
Marina Yatsinab9f4f622016-01-19 15:37:56 +00002493 if (Name.startswith("ins") &&
2494 (Operands.size() == 1 || Operands.size() == 3) &&
2495 (Name == "insb" || Name == "insw" || Name == "insl" || Name == "insd" ||
2496 Name == "ins")) {
2497
2498 AddDefaultSrcDestOperands(TmpOperands,
Michael Kupersteinffcc7662015-07-23 10:23:48 +00002499 X86Operand::CreateReg(X86::DX, NameLoc, NameLoc),
2500 DefaultMemDIOperand(NameLoc));
Marina Yatsinab9f4f622016-01-19 15:37:56 +00002501 HadVerifyError = VerifyAndAdjustOperands(Operands, TmpOperands);
Joerg Sonnenberger3fbfcc02011-03-18 11:59:40 +00002502 }
2503
David Woodhousec472b812014-01-22 15:08:49 +00002504 // Append default arguments to "outs[bwld]"
Marina Yatsinab9f4f622016-01-19 15:37:56 +00002505 if (Name.startswith("outs") &&
2506 (Operands.size() == 1 || Operands.size() == 3) &&
David Woodhousec472b812014-01-22 15:08:49 +00002507 (Name == "outsb" || Name == "outsw" || Name == "outsl" ||
Marina Yatsinab9f4f622016-01-19 15:37:56 +00002508 Name == "outsd" || Name == "outs")) {
2509 AddDefaultSrcDestOperands(TmpOperands, DefaultMemSIOperand(NameLoc),
Michael Kupersteinffcc7662015-07-23 10:23:48 +00002510 X86Operand::CreateReg(X86::DX, NameLoc, NameLoc));
Marina Yatsinab9f4f622016-01-19 15:37:56 +00002511 HadVerifyError = VerifyAndAdjustOperands(Operands, TmpOperands);
Joerg Sonnenberger3fbfcc02011-03-18 11:59:40 +00002512 }
2513
David Woodhouse2ef8d9c2014-01-22 15:08:08 +00002514 // Transform "lods[bwlq]" into "lods[bwlq] ($SIREG)" for appropriate
2515 // values of $SIREG according to the mode. It would be nice if this
2516 // could be achieved with InstAlias in the tables.
Marina Yatsinab9f4f622016-01-19 15:37:56 +00002517 if (Name.startswith("lods") &&
2518 (Operands.size() == 1 || Operands.size() == 2) &&
Joerg Sonnenberger3fbfcc02011-03-18 11:59:40 +00002519 (Name == "lods" || Name == "lodsb" || Name == "lodsw" ||
Marina Yatsinab9f4f622016-01-19 15:37:56 +00002520 Name == "lodsl" || Name == "lodsd" || Name == "lodsq")) {
2521 TmpOperands.push_back(DefaultMemSIOperand(NameLoc));
2522 HadVerifyError = VerifyAndAdjustOperands(Operands, TmpOperands);
2523 }
David Woodhouse2ef8d9c2014-01-22 15:08:08 +00002524
David Woodhouseb33c2ef2014-01-22 15:08:21 +00002525 // Transform "stos[bwlq]" into "stos[bwlq] ($DIREG)" for appropriate
2526 // values of $DIREG according to the mode. It would be nice if this
2527 // could be achieved with InstAlias in the tables.
Marina Yatsinab9f4f622016-01-19 15:37:56 +00002528 if (Name.startswith("stos") &&
2529 (Operands.size() == 1 || Operands.size() == 2) &&
Joerg Sonnenberger3fbfcc02011-03-18 11:59:40 +00002530 (Name == "stos" || Name == "stosb" || Name == "stosw" ||
Marina Yatsinab9f4f622016-01-19 15:37:56 +00002531 Name == "stosl" || Name == "stosd" || Name == "stosq")) {
2532 TmpOperands.push_back(DefaultMemDIOperand(NameLoc));
2533 HadVerifyError = VerifyAndAdjustOperands(Operands, TmpOperands);
2534 }
Joerg Sonnenberger3fbfcc02011-03-18 11:59:40 +00002535
David Woodhouse20fe4802014-01-22 15:08:27 +00002536 // Transform "scas[bwlq]" into "scas[bwlq] ($DIREG)" for appropriate
2537 // values of $DIREG according to the mode. It would be nice if this
2538 // could be achieved with InstAlias in the tables.
Marina Yatsinab9f4f622016-01-19 15:37:56 +00002539 if (Name.startswith("scas") &&
2540 (Operands.size() == 1 || Operands.size() == 2) &&
David Woodhouse20fe4802014-01-22 15:08:27 +00002541 (Name == "scas" || Name == "scasb" || Name == "scasw" ||
Marina Yatsinab9f4f622016-01-19 15:37:56 +00002542 Name == "scasl" || Name == "scasd" || Name == "scasq")) {
2543 TmpOperands.push_back(DefaultMemDIOperand(NameLoc));
2544 HadVerifyError = VerifyAndAdjustOperands(Operands, TmpOperands);
2545 }
David Woodhouse20fe4802014-01-22 15:08:27 +00002546
David Woodhouse9bbf7ca2014-01-22 15:08:36 +00002547 // Add default SI and DI operands to "cmps[bwlq]".
2548 if (Name.startswith("cmps") &&
Marina Yatsinab9f4f622016-01-19 15:37:56 +00002549 (Operands.size() == 1 || Operands.size() == 3) &&
David Woodhouse9bbf7ca2014-01-22 15:08:36 +00002550 (Name == "cmps" || Name == "cmpsb" || Name == "cmpsw" ||
2551 Name == "cmpsl" || Name == "cmpsd" || Name == "cmpsq")) {
Marina Yatsinab9f4f622016-01-19 15:37:56 +00002552 AddDefaultSrcDestOperands(TmpOperands, DefaultMemDIOperand(NameLoc),
2553 DefaultMemSIOperand(NameLoc));
2554 HadVerifyError = VerifyAndAdjustOperands(Operands, TmpOperands);
David Woodhouse9bbf7ca2014-01-22 15:08:36 +00002555 }
2556
David Woodhouse6f417de2014-01-22 15:08:42 +00002557 // Add default SI and DI operands to "movs[bwlq]".
Marina Yatsinab9f4f622016-01-19 15:37:56 +00002558 if (((Name.startswith("movs") &&
2559 (Name == "movs" || Name == "movsb" || Name == "movsw" ||
2560 Name == "movsl" || Name == "movsd" || Name == "movsq")) ||
2561 (Name.startswith("smov") &&
2562 (Name == "smov" || Name == "smovb" || Name == "smovw" ||
2563 Name == "smovl" || Name == "smovd" || Name == "smovq"))) &&
2564 (Operands.size() == 1 || Operands.size() == 3)) {
Coby Tayree94ddbb42016-11-21 15:50:56 +00002565 if (Name == "movsd" && Operands.size() == 1 && !isParsingIntelSyntax())
Marina Yatsinab9f4f622016-01-19 15:37:56 +00002566 Operands.back() = X86Operand::CreateToken("movsl", NameLoc);
2567 AddDefaultSrcDestOperands(TmpOperands, DefaultMemSIOperand(NameLoc),
2568 DefaultMemDIOperand(NameLoc));
2569 HadVerifyError = VerifyAndAdjustOperands(Operands, TmpOperands);
2570 }
2571
2572 // Check if we encountered an error for one the string insturctions
2573 if (HadVerifyError) {
2574 return HadVerifyError;
David Woodhouse6f417de2014-01-22 15:08:42 +00002575 }
2576
Chris Lattner4bd21712010-09-15 04:33:27 +00002577 // FIXME: Hack to handle recognize s{hr,ar,hl} $1, <op>. Canonicalize to
Chris Lattner30561ab2010-09-11 16:32:12 +00002578 // "shift <op>".
Daniel Dunbar18fc3442010-03-13 00:47:29 +00002579 if ((Name.startswith("shr") || Name.startswith("sar") ||
Chris Lattner64f91b92010-11-06 21:23:40 +00002580 Name.startswith("shl") || Name.startswith("sal") ||
2581 Name.startswith("rcl") || Name.startswith("rcr") ||
2582 Name.startswith("rol") || Name.startswith("ror")) &&
Chris Lattner4cfbcdc2010-09-06 18:32:06 +00002583 Operands.size() == 3) {
Devang Patel9a9bb5c2012-01-30 20:02:42 +00002584 if (isParsingIntelSyntax()) {
Devang Patela410ed32012-01-24 21:43:36 +00002585 // Intel syntax
David Blaikie960ea3f2014-06-08 16:18:35 +00002586 X86Operand &Op1 = static_cast<X86Operand &>(*Operands[2]);
2587 if (Op1.isImm() && isa<MCConstantExpr>(Op1.getImm()) &&
2588 cast<MCConstantExpr>(Op1.getImm())->getValue() == 1)
Craig Topper6bf3ed42012-07-18 04:59:16 +00002589 Operands.pop_back();
Devang Patela410ed32012-01-24 21:43:36 +00002590 } else {
David Blaikie960ea3f2014-06-08 16:18:35 +00002591 X86Operand &Op1 = static_cast<X86Operand &>(*Operands[1]);
2592 if (Op1.isImm() && isa<MCConstantExpr>(Op1.getImm()) &&
2593 cast<MCConstantExpr>(Op1.getImm())->getValue() == 1)
Craig Topper6bf3ed42012-07-18 04:59:16 +00002594 Operands.erase(Operands.begin() + 1);
Chris Lattner4cfbcdc2010-09-06 18:32:06 +00002595 }
Daniel Dunbarfbd12cc2010-03-20 22:36:38 +00002596 }
Chad Rosier51afe632012-06-27 22:34:28 +00002597
Chris Lattnerfc4fe002011-04-09 19:41:05 +00002598 // Transforms "int $3" into "int3" as a size optimization. We can't write an
2599 // instalias with an immediate operand yet.
2600 if (Name == "int" && Operands.size() == 2) {
David Blaikie960ea3f2014-06-08 16:18:35 +00002601 X86Operand &Op1 = static_cast<X86Operand &>(*Operands[1]);
Duncan P. N. Exon Smithd5313222015-07-23 19:27:07 +00002602 if (Op1.isImm())
2603 if (auto *CE = dyn_cast<MCConstantExpr>(Op1.getImm()))
2604 if (CE->getValue() == 3) {
2605 Operands.erase(Operands.begin() + 1);
2606 static_cast<X86Operand &>(*Operands[0]).setTokenValue("int3");
2607 }
Chris Lattnerfc4fe002011-04-09 19:41:05 +00002608 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00002609
Marina Yatsinad9658d12016-01-19 16:35:38 +00002610 // Transforms "xlat mem8" into "xlatb"
2611 if ((Name == "xlat" || Name == "xlatb") && Operands.size() == 2) {
2612 X86Operand &Op1 = static_cast<X86Operand &>(*Operands[1]);
2613 if (Op1.isMem8()) {
2614 Warning(Op1.getStartLoc(), "memory operand is only for determining the "
2615 "size, (R|E)BX will be used for the location");
2616 Operands.pop_back();
2617 static_cast<X86Operand &>(*Operands[0]).setTokenValue("xlatb");
2618 }
2619 }
2620
Andrew V. Tischenkobfc90612017-10-16 11:14:29 +00002621 if (Flags)
2622 Operands.push_back(X86Operand::CreatePrefix(Flags, NameLoc, NameLoc));
Chris Lattnerf29c0b62010-01-14 22:21:20 +00002623 return false;
Daniel Dunbar3c2a8932009-07-20 18:55:04 +00002624}
2625
David Blaikie960ea3f2014-06-08 16:18:35 +00002626bool X86AsmParser::processInstruction(MCInst &Inst, const OperandVector &Ops) {
Aaron Ballmana81264b2016-05-23 15:52:59 +00002627 return false;
Devang Patelde47cce2012-01-18 22:42:29 +00002628}
2629
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002630static const char *getSubtargetFeatureName(uint64_t Val);
Evgeniy Stepanov49e26252014-03-14 08:58:04 +00002631
David Blaikie960ea3f2014-06-08 16:18:35 +00002632void X86AsmParser::EmitInstruction(MCInst &Inst, OperandVector &Operands,
2633 MCStreamer &Out) {
Evgeniy Stepanov77ad8662014-07-31 09:11:04 +00002634 Instrumentation->InstrumentAndEmitInstruction(Inst, Operands, getContext(),
2635 MII, Out);
Evgeniy Stepanov49e26252014-03-14 08:58:04 +00002636}
2637
David Blaikie960ea3f2014-06-08 16:18:35 +00002638bool X86AsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
2639 OperandVector &Operands,
Tim Northover26bb14e2014-08-18 11:49:42 +00002640 MCStreamer &Out, uint64_t &ErrorInfo,
David Blaikie960ea3f2014-06-08 16:18:35 +00002641 bool MatchingInlineAsm) {
Reid Klecknerf6fb7802014-08-26 20:32:34 +00002642 if (isParsingIntelSyntax())
2643 return MatchAndEmitIntelInstruction(IDLoc, Opcode, Operands, Out, ErrorInfo,
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002644 MatchingInlineAsm);
Reid Klecknerf6fb7802014-08-26 20:32:34 +00002645 return MatchAndEmitATTInstruction(IDLoc, Opcode, Operands, Out, ErrorInfo,
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002646 MatchingInlineAsm);
Reid Klecknerf6fb7802014-08-26 20:32:34 +00002647}
Daniel Dunbar2ecc3bb2010-08-12 00:55:38 +00002648
Reid Klecknerf6fb7802014-08-26 20:32:34 +00002649void X86AsmParser::MatchFPUWaitAlias(SMLoc IDLoc, X86Operand &Op,
2650 OperandVector &Operands, MCStreamer &Out,
2651 bool MatchingInlineAsm) {
Chris Lattnera63292a2010-09-29 01:50:45 +00002652 // FIXME: This should be replaced with a real .td file alias mechanism.
Chad Rosier3b1336c2012-08-28 23:57:47 +00002653 // Also, MatchInstructionImpl should actually *do* the EmitInstruction
Chris Lattner4869d342010-11-06 19:57:21 +00002654 // call.
Reid Klecknerb1f2d2f2014-07-31 00:07:33 +00002655 const char *Repl = StringSwitch<const char *>(Op.getToken())
2656 .Case("finit", "fninit")
2657 .Case("fsave", "fnsave")
2658 .Case("fstcw", "fnstcw")
2659 .Case("fstcww", "fnstcw")
2660 .Case("fstenv", "fnstenv")
2661 .Case("fstsw", "fnstsw")
2662 .Case("fstsww", "fnstsw")
2663 .Case("fclex", "fnclex")
2664 .Default(nullptr);
2665 if (Repl) {
Chris Lattnera63292a2010-09-29 01:50:45 +00002666 MCInst Inst;
2667 Inst.setOpcode(X86::WAIT);
Jim Grosbach8f28dbd2012-01-27 00:51:27 +00002668 Inst.setLoc(IDLoc);
Chad Rosier4453e842012-10-12 23:09:25 +00002669 if (!MatchingInlineAsm)
Evgeniy Stepanov49e26252014-03-14 08:58:04 +00002670 EmitInstruction(Inst, Operands, Out);
Chris Lattneradc0dbe2010-09-30 16:39:29 +00002671 Operands[0] = X86Operand::CreateToken(Repl, IDLoc);
Chris Lattnera63292a2010-09-29 01:50:45 +00002672 }
Reid Klecknerf6fb7802014-08-26 20:32:34 +00002673}
2674
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002675bool X86AsmParser::ErrorMissingFeature(SMLoc IDLoc, uint64_t ErrorInfo,
Reid Klecknerf6fb7802014-08-26 20:32:34 +00002676 bool MatchingInlineAsm) {
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002677 assert(ErrorInfo && "Unknown missing feature!");
Reid Klecknerf6fb7802014-08-26 20:32:34 +00002678 SmallString<126> Msg;
2679 raw_svector_ostream OS(Msg);
2680 OS << "instruction requires:";
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002681 uint64_t Mask = 1;
2682 for (unsigned i = 0; i < (sizeof(ErrorInfo)*8-1); ++i) {
2683 if (ErrorInfo & Mask)
2684 OS << ' ' << getSubtargetFeatureName(ErrorInfo & Mask);
2685 Mask <<= 1;
Reid Klecknerf6fb7802014-08-26 20:32:34 +00002686 }
Nirav Dave2364748a2016-09-16 18:30:20 +00002687 return Error(IDLoc, OS.str(), SMRange(), MatchingInlineAsm);
Reid Klecknerf6fb7802014-08-26 20:32:34 +00002688}
2689
Andrew V. Tischenkobfc90612017-10-16 11:14:29 +00002690static unsigned getPrefixes(OperandVector &Operands) {
2691 unsigned Result = 0;
2692 X86Operand &Prefix = static_cast<X86Operand &>(*Operands.back());
2693 if (Prefix.isPrefix()) {
2694 Result = Prefix.getPrefix();
2695 Operands.pop_back();
2696 }
2697 return Result;
2698}
2699
Reid Klecknerf6fb7802014-08-26 20:32:34 +00002700bool X86AsmParser::MatchAndEmitATTInstruction(SMLoc IDLoc, unsigned &Opcode,
2701 OperandVector &Operands,
2702 MCStreamer &Out,
2703 uint64_t &ErrorInfo,
2704 bool MatchingInlineAsm) {
2705 assert(!Operands.empty() && "Unexpect empty operand list!");
2706 X86Operand &Op = static_cast<X86Operand &>(*Operands[0]);
2707 assert(Op.isToken() && "Leading operand should always be a mnemonic!");
Nirav Dave2364748a2016-09-16 18:30:20 +00002708 SMRange EmptyRange = None;
Reid Klecknerf6fb7802014-08-26 20:32:34 +00002709
2710 // First, handle aliases that expand to multiple instructions.
2711 MatchFPUWaitAlias(IDLoc, Op, Operands, Out, MatchingInlineAsm);
Michael J. Spencer530ce852010-10-09 11:00:50 +00002712
Chris Lattner628fbec2010-09-06 21:54:15 +00002713 bool WasOriginallyInvalidOperand = false;
Andrew V. Tischenkobfc90612017-10-16 11:14:29 +00002714 unsigned Prefixes = getPrefixes(Operands);
2715
Chris Lattnerb44fd242010-09-29 01:42:58 +00002716 MCInst Inst;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002717
Andrew V. Tischenkobfc90612017-10-16 11:14:29 +00002718 if (Prefixes)
2719 Inst.setFlags(Prefixes);
2720
Daniel Dunbar9b816a12010-05-04 16:12:42 +00002721 // First, try a direct match.
Nirav Dave6477ce22016-09-26 19:33:36 +00002722 switch (MatchInstruction(Operands, Inst, ErrorInfo, MatchingInlineAsm,
2723 isParsingIntelSyntax())) {
Craig Topper589ceee2015-01-03 08:16:34 +00002724 default: llvm_unreachable("Unexpected match result!");
Chris Lattnerb4be28f2010-09-06 20:08:02 +00002725 case Match_Success:
Devang Patelde47cce2012-01-18 22:42:29 +00002726 // Some instructions need post-processing to, for example, tweak which
2727 // encoding is selected. Loop on it while changes happen so the
Chad Rosier51afe632012-06-27 22:34:28 +00002728 // individual transformations can chain off each other.
Chad Rosier4453e842012-10-12 23:09:25 +00002729 if (!MatchingInlineAsm)
Chad Rosierf4e35dc2012-10-01 23:45:51 +00002730 while (processInstruction(Inst, Operands))
2731 ;
Devang Patelde47cce2012-01-18 22:42:29 +00002732
Jim Grosbach8f28dbd2012-01-27 00:51:27 +00002733 Inst.setLoc(IDLoc);
Chad Rosier4453e842012-10-12 23:09:25 +00002734 if (!MatchingInlineAsm)
Evgeniy Stepanov49e26252014-03-14 08:58:04 +00002735 EmitInstruction(Inst, Operands, Out);
Chad Rosierf4e35dc2012-10-01 23:45:51 +00002736 Opcode = Inst.getOpcode();
Daniel Dunbar9b816a12010-05-04 16:12:42 +00002737 return false;
Reid Klecknerf6fb7802014-08-26 20:32:34 +00002738 case Match_MissingFeature:
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002739 return ErrorMissingFeature(IDLoc, ErrorInfo, MatchingInlineAsm);
Chris Lattner628fbec2010-09-06 21:54:15 +00002740 case Match_InvalidOperand:
2741 WasOriginallyInvalidOperand = true;
2742 break;
2743 case Match_MnemonicFail:
Chris Lattnerb4be28f2010-09-06 20:08:02 +00002744 break;
2745 }
Daniel Dunbar9b816a12010-05-04 16:12:42 +00002746
Daniel Dunbar9b816a12010-05-04 16:12:42 +00002747 // FIXME: Ideally, we would only attempt suffix matches for things which are
2748 // valid prefixes, and we could just infer the right unambiguous
2749 // type. However, that requires substantially more matcher support than the
2750 // following hack.
Michael J. Spencer530ce852010-10-09 11:00:50 +00002751
Daniel Dunbar9b816a12010-05-04 16:12:42 +00002752 // Change the operand to point to a temporary token.
David Blaikie960ea3f2014-06-08 16:18:35 +00002753 StringRef Base = Op.getToken();
Daniel Dunbar2ecc3bb2010-08-12 00:55:38 +00002754 SmallString<16> Tmp;
2755 Tmp += Base;
2756 Tmp += ' ';
Yaron Keren075759a2015-03-30 15:42:36 +00002757 Op.setTokenValue(Tmp);
Daniel Dunbar9b816a12010-05-04 16:12:42 +00002758
Chris Lattnerfab94132010-11-06 18:28:02 +00002759 // If this instruction starts with an 'f', then it is a floating point stack
2760 // instruction. These come in up to three forms for 32-bit, 64-bit, and
2761 // 80-bit floating point, which use the suffixes s,l,t respectively.
2762 //
2763 // Otherwise, we assume that this may be an integer instruction, which comes
2764 // in 8/16/32/64-bit forms using the b,w,l,q suffixes respectively.
2765 const char *Suffixes = Base[0] != 'f' ? "bwlq" : "slt\0";
Chad Rosier51afe632012-06-27 22:34:28 +00002766
Daniel Dunbar9b816a12010-05-04 16:12:42 +00002767 // Check for the various suffix matches.
Tim Northover26bb14e2014-08-18 11:49:42 +00002768 uint64_t ErrorInfoIgnore;
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002769 uint64_t ErrorInfoMissingFeature = 0; // Init suppresses compiler warnings.
Reid Kleckner7b1e1a02014-07-30 22:23:11 +00002770 unsigned Match[4];
Chad Rosier51afe632012-06-27 22:34:28 +00002771
Reid Kleckner7b1e1a02014-07-30 22:23:11 +00002772 for (unsigned I = 0, E = array_lengthof(Match); I != E; ++I) {
2773 Tmp.back() = Suffixes[I];
Nirav Dave6477ce22016-09-26 19:33:36 +00002774 Match[I] = MatchInstruction(Operands, Inst, ErrorInfoIgnore,
2775 MatchingInlineAsm, isParsingIntelSyntax());
Reid Kleckner7b1e1a02014-07-30 22:23:11 +00002776 // If this returned as a missing feature failure, remember that.
2777 if (Match[I] == Match_MissingFeature)
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002778 ErrorInfoMissingFeature = ErrorInfoIgnore;
Reid Kleckner7b1e1a02014-07-30 22:23:11 +00002779 }
Daniel Dunbar9b816a12010-05-04 16:12:42 +00002780
2781 // Restore the old token.
David Blaikie960ea3f2014-06-08 16:18:35 +00002782 Op.setTokenValue(Base);
Daniel Dunbar9b816a12010-05-04 16:12:42 +00002783
2784 // If exactly one matched, then we treat that as a successful match (and the
2785 // instruction will already have been filled in correctly, since the failing
2786 // matches won't have modified it).
Chris Lattnerb4be28f2010-09-06 20:08:02 +00002787 unsigned NumSuccessfulMatches =
Reid Kleckner7b1e1a02014-07-30 22:23:11 +00002788 std::count(std::begin(Match), std::end(Match), Match_Success);
Chris Lattnerb44fd242010-09-29 01:42:58 +00002789 if (NumSuccessfulMatches == 1) {
Jim Grosbach8f28dbd2012-01-27 00:51:27 +00002790 Inst.setLoc(IDLoc);
Chad Rosier4453e842012-10-12 23:09:25 +00002791 if (!MatchingInlineAsm)
Evgeniy Stepanov49e26252014-03-14 08:58:04 +00002792 EmitInstruction(Inst, Operands, Out);
Chad Rosierf4e35dc2012-10-01 23:45:51 +00002793 Opcode = Inst.getOpcode();
Daniel Dunbar9b816a12010-05-04 16:12:42 +00002794 return false;
Chris Lattnerb44fd242010-09-29 01:42:58 +00002795 }
Daniel Dunbar9b816a12010-05-04 16:12:42 +00002796
Chris Lattnerb4be28f2010-09-06 20:08:02 +00002797 // Otherwise, the match failed, try to produce a decent error message.
Daniel Dunbar2ecc3bb2010-08-12 00:55:38 +00002798
Daniel Dunbar7d7b4d12010-08-12 00:55:42 +00002799 // If we had multiple suffix matches, then identify this as an ambiguous
2800 // match.
Chris Lattnerb4be28f2010-09-06 20:08:02 +00002801 if (NumSuccessfulMatches > 1) {
Daniel Dunbar7d7b4d12010-08-12 00:55:42 +00002802 char MatchChars[4];
2803 unsigned NumMatches = 0;
Reid Kleckner7b1e1a02014-07-30 22:23:11 +00002804 for (unsigned I = 0, E = array_lengthof(Match); I != E; ++I)
2805 if (Match[I] == Match_Success)
2806 MatchChars[NumMatches++] = Suffixes[I];
Daniel Dunbar7d7b4d12010-08-12 00:55:42 +00002807
Alp Tokere69170a2014-06-26 22:52:05 +00002808 SmallString<126> Msg;
2809 raw_svector_ostream OS(Msg);
Daniel Dunbar7d7b4d12010-08-12 00:55:42 +00002810 OS << "ambiguous instructions require an explicit suffix (could be ";
2811 for (unsigned i = 0; i != NumMatches; ++i) {
2812 if (i != 0)
2813 OS << ", ";
2814 if (i + 1 == NumMatches)
2815 OS << "or ";
2816 OS << "'" << Base << MatchChars[i] << "'";
2817 }
2818 OS << ")";
Nirav Dave2364748a2016-09-16 18:30:20 +00002819 Error(IDLoc, OS.str(), EmptyRange, MatchingInlineAsm);
Chris Lattnerb4be28f2010-09-06 20:08:02 +00002820 return true;
Daniel Dunbar7d7b4d12010-08-12 00:55:42 +00002821 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00002822
Chris Lattner628fbec2010-09-06 21:54:15 +00002823 // Okay, we know that none of the variants matched successfully.
Michael J. Spencer530ce852010-10-09 11:00:50 +00002824
Chris Lattner628fbec2010-09-06 21:54:15 +00002825 // If all of the instructions reported an invalid mnemonic, then the original
2826 // mnemonic was invalid.
Reid Kleckner7b1e1a02014-07-30 22:23:11 +00002827 if (std::count(std::begin(Match), std::end(Match), Match_MnemonicFail) == 4) {
Chris Lattner339cc7b2010-09-06 22:11:18 +00002828 if (!WasOriginallyInvalidOperand) {
Benjamin Kramerd416bae2011-10-16 11:28:29 +00002829 return Error(IDLoc, "invalid instruction mnemonic '" + Base + "'",
Nirav Dave2364748a2016-09-16 18:30:20 +00002830 Op.getLocRange(), MatchingInlineAsm);
Chris Lattner339cc7b2010-09-06 22:11:18 +00002831 }
2832
2833 // Recover location info for the operand if we know which was the problem.
Tim Northover26bb14e2014-08-18 11:49:42 +00002834 if (ErrorInfo != ~0ULL) {
Chad Rosier49963552012-10-13 00:26:04 +00002835 if (ErrorInfo >= Operands.size())
Nirav Dave2364748a2016-09-16 18:30:20 +00002836 return Error(IDLoc, "too few operands for instruction", EmptyRange,
2837 MatchingInlineAsm);
Michael J. Spencer530ce852010-10-09 11:00:50 +00002838
David Blaikie960ea3f2014-06-08 16:18:35 +00002839 X86Operand &Operand = (X86Operand &)*Operands[ErrorInfo];
2840 if (Operand.getStartLoc().isValid()) {
2841 SMRange OperandRange = Operand.getLocRange();
2842 return Error(Operand.getStartLoc(), "invalid operand for instruction",
Chad Rosier4453e842012-10-12 23:09:25 +00002843 OperandRange, MatchingInlineAsm);
Chris Lattnera3a06812011-10-16 04:47:35 +00002844 }
Chris Lattner339cc7b2010-09-06 22:11:18 +00002845 }
2846
Nirav Dave2364748a2016-09-16 18:30:20 +00002847 return Error(IDLoc, "invalid operand for instruction", EmptyRange,
Chad Rosier4453e842012-10-12 23:09:25 +00002848 MatchingInlineAsm);
Chris Lattner628fbec2010-09-06 21:54:15 +00002849 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00002850
Chris Lattnerb4be28f2010-09-06 20:08:02 +00002851 // If one instruction matched with a missing feature, report this as a
2852 // missing feature.
Reid Kleckner7b1e1a02014-07-30 22:23:11 +00002853 if (std::count(std::begin(Match), std::end(Match),
2854 Match_MissingFeature) == 1) {
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002855 ErrorInfo = ErrorInfoMissingFeature;
2856 return ErrorMissingFeature(IDLoc, ErrorInfoMissingFeature,
Reid Klecknerf6fb7802014-08-26 20:32:34 +00002857 MatchingInlineAsm);
Chris Lattnerb4be28f2010-09-06 20:08:02 +00002858 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00002859
Chris Lattner628fbec2010-09-06 21:54:15 +00002860 // If one instruction matched with an invalid operand, report this as an
2861 // operand failure.
Reid Kleckner7b1e1a02014-07-30 22:23:11 +00002862 if (std::count(std::begin(Match), std::end(Match),
2863 Match_InvalidOperand) == 1) {
Nirav Dave2364748a2016-09-16 18:30:20 +00002864 return Error(IDLoc, "invalid operand for instruction", EmptyRange,
Reid Klecknerf6fb7802014-08-26 20:32:34 +00002865 MatchingInlineAsm);
Chris Lattner628fbec2010-09-06 21:54:15 +00002866 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00002867
Chris Lattnerb4be28f2010-09-06 20:08:02 +00002868 // If all of these were an outright failure, report it in a useless way.
Chad Rosier3d4bc622012-08-21 19:36:59 +00002869 Error(IDLoc, "unknown use of instruction mnemonic without a size suffix",
Nirav Dave2364748a2016-09-16 18:30:20 +00002870 EmptyRange, MatchingInlineAsm);
Daniel Dunbar9b816a12010-05-04 16:12:42 +00002871 return true;
2872}
2873
Reid Klecknerf6fb7802014-08-26 20:32:34 +00002874bool X86AsmParser::MatchAndEmitIntelInstruction(SMLoc IDLoc, unsigned &Opcode,
2875 OperandVector &Operands,
2876 MCStreamer &Out,
2877 uint64_t &ErrorInfo,
2878 bool MatchingInlineAsm) {
2879 assert(!Operands.empty() && "Unexpect empty operand list!");
2880 X86Operand &Op = static_cast<X86Operand &>(*Operands[0]);
2881 assert(Op.isToken() && "Leading operand should always be a mnemonic!");
2882 StringRef Mnemonic = Op.getToken();
Nirav Dave2364748a2016-09-16 18:30:20 +00002883 SMRange EmptyRange = None;
Nirav Daveee554e62016-10-06 15:28:08 +00002884 StringRef Base = Op.getToken();
Andrew V. Tischenkobfc90612017-10-16 11:14:29 +00002885 unsigned Prefixes = getPrefixes(Operands);
Reid Klecknerf6fb7802014-08-26 20:32:34 +00002886
2887 // First, handle aliases that expand to multiple instructions.
2888 MatchFPUWaitAlias(IDLoc, Op, Operands, Out, MatchingInlineAsm);
2889
2890 MCInst Inst;
2891
Andrew V. Tischenkobfc90612017-10-16 11:14:29 +00002892 if (Prefixes)
2893 Inst.setFlags(Prefixes);
2894
Reid Klecknerf6fb7802014-08-26 20:32:34 +00002895 // Find one unsized memory operand, if present.
2896 X86Operand *UnsizedMemOp = nullptr;
2897 for (const auto &Op : Operands) {
2898 X86Operand *X86Op = static_cast<X86Operand *>(Op.get());
Reid Kleckner6d2ea6e2017-05-04 18:19:52 +00002899 if (X86Op->isMemUnsized()) {
2900 UnsizedMemOp = X86Op;
Coby Tayree49b37332016-11-22 09:30:29 +00002901 // Have we found an unqualified memory operand,
2902 // break. IA allows only one memory operand.
2903 break;
2904 }
Reid Klecknerf6fb7802014-08-26 20:32:34 +00002905 }
2906
2907 // Allow some instructions to have implicitly pointer-sized operands. This is
2908 // compatible with gas.
2909 if (UnsizedMemOp) {
2910 static const char *const PtrSizedInstrs[] = {"call", "jmp", "push"};
2911 for (const char *Instr : PtrSizedInstrs) {
2912 if (Mnemonic == Instr) {
Craig Topper055845f2015-01-02 07:02:25 +00002913 UnsizedMemOp->Mem.Size = getPointerWidth();
Reid Klecknerf6fb7802014-08-26 20:32:34 +00002914 break;
2915 }
2916 }
2917 }
2918
Nirav Daveee554e62016-10-06 15:28:08 +00002919 SmallVector<unsigned, 8> Match;
2920 uint64_t ErrorInfoMissingFeature = 0;
2921
2922 // If unsized push has immediate operand we should default the default pointer
2923 // size for the size.
2924 if (Mnemonic == "push" && Operands.size() == 2) {
2925 auto *X86Op = static_cast<X86Operand *>(Operands[1].get());
2926 if (X86Op->isImm()) {
2927 // If it's not a constant fall through and let remainder take care of it.
2928 const auto *CE = dyn_cast<MCConstantExpr>(X86Op->getImm());
2929 unsigned Size = getPointerWidth();
2930 if (CE &&
2931 (isIntN(Size, CE->getValue()) || isUIntN(Size, CE->getValue()))) {
2932 SmallString<16> Tmp;
2933 Tmp += Base;
2934 Tmp += (is64BitMode())
2935 ? "q"
2936 : (is32BitMode()) ? "l" : (is16BitMode()) ? "w" : " ";
2937 Op.setTokenValue(Tmp);
2938 // Do match in ATT mode to allow explicit suffix usage.
2939 Match.push_back(MatchInstruction(Operands, Inst, ErrorInfo,
2940 MatchingInlineAsm,
2941 false /*isParsingIntelSyntax()*/));
2942 Op.setTokenValue(Base);
2943 }
2944 }
2945 }
2946
Reid Klecknerf6fb7802014-08-26 20:32:34 +00002947 // If an unsized memory operand is present, try to match with each memory
2948 // operand size. In Intel assembly, the size is not part of the instruction
2949 // mnemonic.
Reid Klecknerf6fb7802014-08-26 20:32:34 +00002950 if (UnsizedMemOp && UnsizedMemOp->isMemUnsized()) {
Ahmed Bougachad65f7872014-12-03 02:03:26 +00002951 static const unsigned MopSizes[] = {8, 16, 32, 64, 80, 128, 256, 512};
Reid Klecknerf6fb7802014-08-26 20:32:34 +00002952 for (unsigned Size : MopSizes) {
2953 UnsizedMemOp->Mem.Size = Size;
2954 uint64_t ErrorInfoIgnore;
Reid Kleckner7b7a5992014-08-27 20:10:38 +00002955 unsigned LastOpcode = Inst.getOpcode();
Nirav Dave6477ce22016-09-26 19:33:36 +00002956 unsigned M = MatchInstruction(Operands, Inst, ErrorInfoIgnore,
2957 MatchingInlineAsm, isParsingIntelSyntax());
Reid Kleckner7b7a5992014-08-27 20:10:38 +00002958 if (Match.empty() || LastOpcode != Inst.getOpcode())
2959 Match.push_back(M);
2960
Reid Klecknerf6fb7802014-08-26 20:32:34 +00002961 // If this returned as a missing feature failure, remember that.
2962 if (Match.back() == Match_MissingFeature)
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002963 ErrorInfoMissingFeature = ErrorInfoIgnore;
Reid Klecknerf6fb7802014-08-26 20:32:34 +00002964 }
Reid Kleckner7b7a5992014-08-27 20:10:38 +00002965
2966 // Restore the size of the unsized memory operand if we modified it.
Reid Kleckner6d2ea6e2017-05-04 18:19:52 +00002967 UnsizedMemOp->Mem.Size = 0;
Reid Kleckner7b7a5992014-08-27 20:10:38 +00002968 }
2969
2970 // If we haven't matched anything yet, this is not a basic integer or FPU
Saleem Abdulrasoolc3f8ad32015-01-16 20:16:06 +00002971 // operation. There shouldn't be any ambiguity in our mnemonic table, so try
Reid Kleckner7b7a5992014-08-27 20:10:38 +00002972 // matching with the unsized operand.
2973 if (Match.empty()) {
Nirav Dave6477ce22016-09-26 19:33:36 +00002974 Match.push_back(MatchInstruction(
2975 Operands, Inst, ErrorInfo, MatchingInlineAsm, isParsingIntelSyntax()));
Reid Klecknerf6fb7802014-08-26 20:32:34 +00002976 // If this returned as a missing feature failure, remember that.
2977 if (Match.back() == Match_MissingFeature)
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002978 ErrorInfoMissingFeature = ErrorInfo;
Reid Klecknerf6fb7802014-08-26 20:32:34 +00002979 }
2980
2981 // Restore the size of the unsized memory operand if we modified it.
2982 if (UnsizedMemOp)
2983 UnsizedMemOp->Mem.Size = 0;
2984
2985 // If it's a bad mnemonic, all results will be the same.
2986 if (Match.back() == Match_MnemonicFail) {
Reid Klecknerf6fb7802014-08-26 20:32:34 +00002987 return Error(IDLoc, "invalid instruction mnemonic '" + Mnemonic + "'",
Nirav Dave2364748a2016-09-16 18:30:20 +00002988 Op.getLocRange(), MatchingInlineAsm);
Reid Klecknerf6fb7802014-08-26 20:32:34 +00002989 }
2990
Reid Kleckner6d2ea6e2017-05-04 18:19:52 +00002991 unsigned NumSuccessfulMatches =
2992 std::count(std::begin(Match), std::end(Match), Match_Success);
2993
2994 // If matching was ambiguous and we had size information from the frontend,
2995 // try again with that. This handles cases like "movxz eax, m8/m16".
2996 if (UnsizedMemOp && NumSuccessfulMatches > 1 &&
2997 UnsizedMemOp->getMemFrontendSize()) {
2998 UnsizedMemOp->Mem.Size = UnsizedMemOp->getMemFrontendSize();
2999 unsigned M = MatchInstruction(
3000 Operands, Inst, ErrorInfo, MatchingInlineAsm, isParsingIntelSyntax());
3001 if (M == Match_Success)
3002 NumSuccessfulMatches = 1;
3003
3004 // Add a rewrite that encodes the size information we used from the
3005 // frontend.
3006 InstInfo->AsmRewrites->emplace_back(
3007 AOK_SizeDirective, UnsizedMemOp->getStartLoc(),
3008 /*Len=*/0, UnsizedMemOp->getMemFrontendSize());
3009 }
3010
Reid Klecknerf6fb7802014-08-26 20:32:34 +00003011 // If exactly one matched, then we treat that as a successful match (and the
3012 // instruction will already have been filled in correctly, since the failing
3013 // matches won't have modified it).
Reid Klecknerf6fb7802014-08-26 20:32:34 +00003014 if (NumSuccessfulMatches == 1) {
3015 // Some instructions need post-processing to, for example, tweak which
3016 // encoding is selected. Loop on it while changes happen so the individual
3017 // transformations can chain off each other.
3018 if (!MatchingInlineAsm)
3019 while (processInstruction(Inst, Operands))
3020 ;
3021 Inst.setLoc(IDLoc);
3022 if (!MatchingInlineAsm)
3023 EmitInstruction(Inst, Operands, Out);
3024 Opcode = Inst.getOpcode();
3025 return false;
3026 } else if (NumSuccessfulMatches > 1) {
3027 assert(UnsizedMemOp &&
3028 "multiple matches only possible with unsized memory operands");
Reid Klecknerf6fb7802014-08-26 20:32:34 +00003029 return Error(UnsizedMemOp->getStartLoc(),
3030 "ambiguous operand size for instruction '" + Mnemonic + "\'",
Reid Kleckner6d2ea6e2017-05-04 18:19:52 +00003031 UnsizedMemOp->getLocRange());
Reid Klecknerf6fb7802014-08-26 20:32:34 +00003032 }
3033
3034 // If one instruction matched with a missing feature, report this as a
3035 // missing feature.
3036 if (std::count(std::begin(Match), std::end(Match),
3037 Match_MissingFeature) == 1) {
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00003038 ErrorInfo = ErrorInfoMissingFeature;
Reid Klecknerf6fb7802014-08-26 20:32:34 +00003039 return ErrorMissingFeature(IDLoc, ErrorInfoMissingFeature,
3040 MatchingInlineAsm);
3041 }
3042
3043 // If one instruction matched with an invalid operand, report this as an
3044 // operand failure.
3045 if (std::count(std::begin(Match), std::end(Match),
3046 Match_InvalidOperand) == 1) {
Nirav Dave2364748a2016-09-16 18:30:20 +00003047 return Error(IDLoc, "invalid operand for instruction", EmptyRange,
Reid Klecknerf6fb7802014-08-26 20:32:34 +00003048 MatchingInlineAsm);
3049 }
3050
3051 // If all of these were an outright failure, report it in a useless way.
Nirav Dave2364748a2016-09-16 18:30:20 +00003052 return Error(IDLoc, "unknown instruction mnemonic", EmptyRange,
Reid Klecknerf6fb7802014-08-26 20:32:34 +00003053 MatchingInlineAsm);
3054}
3055
Nico Weber42f79db2014-07-17 20:24:55 +00003056bool X86AsmParser::OmitRegisterFromClobberLists(unsigned RegNo) {
3057 return X86MCRegisterClasses[X86::SEGMENT_REGRegClassID].contains(RegNo);
3058}
Daniel Dunbar9b816a12010-05-04 16:12:42 +00003059
Devang Patel4a6e7782012-01-12 18:03:40 +00003060bool X86AsmParser::ParseDirective(AsmToken DirectiveID) {
Rafael Espindola961d4692014-11-11 05:18:41 +00003061 MCAsmParser &Parser = getParser();
Chris Lattner72c0b592010-10-30 17:38:55 +00003062 StringRef IDVal = DirectiveID.getIdentifier();
3063 if (IDVal == ".word")
3064 return ParseDirectiveWord(2, DirectiveID.getLoc());
Evan Cheng481ebb02011-07-27 00:38:12 +00003065 else if (IDVal.startswith(".code"))
3066 return ParseDirectiveCode(IDVal, DirectiveID.getLoc());
Chad Rosier6f8d8b22012-09-10 20:54:39 +00003067 else if (IDVal.startswith(".att_syntax")) {
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +00003068 getParser().setParsingInlineAsm(false);
Reid Klecknerce63b792014-08-06 23:21:13 +00003069 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3070 if (Parser.getTok().getString() == "prefix")
3071 Parser.Lex();
3072 else if (Parser.getTok().getString() == "noprefix")
3073 return Error(DirectiveID.getLoc(), "'.att_syntax noprefix' is not "
3074 "supported: registers must have a "
3075 "'%' prefix in .att_syntax");
3076 }
Chad Rosier6f8d8b22012-09-10 20:54:39 +00003077 getParser().setAssemblerDialect(0);
3078 return false;
3079 } else if (IDVal.startswith(".intel_syntax")) {
Devang Patela173ee52012-01-31 18:14:05 +00003080 getParser().setAssemblerDialect(1);
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +00003081 getParser().setParsingInlineAsm(true);
Devang Patel9a9bb5c2012-01-30 20:02:42 +00003082 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Saleem Abdulrasoola6505ca2014-01-13 01:15:39 +00003083 if (Parser.getTok().getString() == "noprefix")
Craig Topper6bf3ed42012-07-18 04:59:16 +00003084 Parser.Lex();
Reid Klecknerce63b792014-08-06 23:21:13 +00003085 else if (Parser.getTok().getString() == "prefix")
3086 return Error(DirectiveID.getLoc(), "'.intel_syntax prefix' is not "
3087 "supported: registers must not have "
3088 "a '%' prefix in .intel_syntax");
Devang Patel9a9bb5c2012-01-30 20:02:42 +00003089 }
3090 return false;
Michael Zuckerman02ecd432015-12-13 17:07:23 +00003091 } else if (IDVal == ".even")
3092 return parseDirectiveEven(DirectiveID.getLoc());
Reid Kleckner9cdd4df2017-10-11 21:24:33 +00003093 else if (IDVal == ".cv_fpo_proc")
3094 return parseDirectiveFPOProc(DirectiveID.getLoc());
3095 else if (IDVal == ".cv_fpo_setframe")
3096 return parseDirectiveFPOSetFrame(DirectiveID.getLoc());
3097 else if (IDVal == ".cv_fpo_pushreg")
3098 return parseDirectiveFPOPushReg(DirectiveID.getLoc());
3099 else if (IDVal == ".cv_fpo_stackalloc")
3100 return parseDirectiveFPOStackAlloc(DirectiveID.getLoc());
3101 else if (IDVal == ".cv_fpo_endprologue")
3102 return parseDirectiveFPOEndPrologue(DirectiveID.getLoc());
3103 else if (IDVal == ".cv_fpo_endproc")
3104 return parseDirectiveFPOEndProc(DirectiveID.getLoc());
3105
Chris Lattner72c0b592010-10-30 17:38:55 +00003106 return true;
3107}
3108
Michael Zuckerman02ecd432015-12-13 17:07:23 +00003109/// parseDirectiveEven
3110/// ::= .even
3111bool X86AsmParser::parseDirectiveEven(SMLoc L) {
Michael Zuckerman02ecd432015-12-13 17:07:23 +00003112 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3113 TokError("unexpected token in directive");
3114 return false;
3115 }
Eric Christopher445c9522016-10-14 05:47:37 +00003116 const MCSection *Section = getStreamer().getCurrentSectionOnly();
Michael Zuckerman02ecd432015-12-13 17:07:23 +00003117 if (!Section) {
3118 getStreamer().InitSections(false);
Eric Christopher445c9522016-10-14 05:47:37 +00003119 Section = getStreamer().getCurrentSectionOnly();
Michael Zuckerman02ecd432015-12-13 17:07:23 +00003120 }
3121 if (Section->UseCodeAlign())
3122 getStreamer().EmitCodeAlignment(2, 0);
3123 else
3124 getStreamer().EmitValueToAlignment(2, 0, 1, 0);
3125 return false;
3126}
Chris Lattner72c0b592010-10-30 17:38:55 +00003127/// ParseDirectiveWord
3128/// ::= .word [ expression (, expression)* ]
Devang Patel4a6e7782012-01-12 18:03:40 +00003129bool X86AsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
Rafael Espindola961d4692014-11-11 05:18:41 +00003130 MCAsmParser &Parser = getParser();
Chris Lattner72c0b592010-10-30 17:38:55 +00003131 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3132 for (;;) {
3133 const MCExpr *Value;
David Majnemera375b262015-10-26 02:45:50 +00003134 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003135 if (getParser().parseExpression(Value))
Saleem Abdulrasoola6505ca2014-01-13 01:15:39 +00003136 return false;
Chad Rosier51afe632012-06-27 22:34:28 +00003137
David Majnemera375b262015-10-26 02:45:50 +00003138 if (const auto *MCE = dyn_cast<MCConstantExpr>(Value)) {
3139 assert(Size <= 8 && "Invalid size");
3140 uint64_t IntValue = MCE->getValue();
3141 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
3142 return Error(ExprLoc, "literal value out of range for directive");
3143 getStreamer().EmitIntValue(IntValue, Size);
3144 } else {
3145 getStreamer().EmitValue(Value, Size, ExprLoc);
3146 }
Chad Rosier51afe632012-06-27 22:34:28 +00003147
Chris Lattner72c0b592010-10-30 17:38:55 +00003148 if (getLexer().is(AsmToken::EndOfStatement))
3149 break;
Chad Rosier51afe632012-06-27 22:34:28 +00003150
Chris Lattner72c0b592010-10-30 17:38:55 +00003151 // FIXME: Improve diagnostic.
Saleem Abdulrasoola6505ca2014-01-13 01:15:39 +00003152 if (getLexer().isNot(AsmToken::Comma)) {
3153 Error(L, "unexpected token in directive");
3154 return false;
3155 }
Chris Lattner72c0b592010-10-30 17:38:55 +00003156 Parser.Lex();
3157 }
3158 }
Chad Rosier51afe632012-06-27 22:34:28 +00003159
Chris Lattner72c0b592010-10-30 17:38:55 +00003160 Parser.Lex();
3161 return false;
3162}
3163
Evan Cheng481ebb02011-07-27 00:38:12 +00003164/// ParseDirectiveCode
Craig Topper3c80d622014-01-06 04:55:54 +00003165/// ::= .code16 | .code32 | .code64
Devang Patel4a6e7782012-01-12 18:03:40 +00003166bool X86AsmParser::ParseDirectiveCode(StringRef IDVal, SMLoc L) {
Rafael Espindola961d4692014-11-11 05:18:41 +00003167 MCAsmParser &Parser = getParser();
Nirav Dave6477ce22016-09-26 19:33:36 +00003168 Code16GCC = false;
Craig Topper3c80d622014-01-06 04:55:54 +00003169 if (IDVal == ".code16") {
Evan Cheng481ebb02011-07-27 00:38:12 +00003170 Parser.Lex();
Craig Topper3c80d622014-01-06 04:55:54 +00003171 if (!is16BitMode()) {
3172 SwitchMode(X86::Mode16Bit);
3173 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
3174 }
Nirav Dave6477ce22016-09-26 19:33:36 +00003175 } else if (IDVal == ".code16gcc") {
3176 // .code16gcc parses as if in 32-bit mode, but emits code in 16-bit mode.
3177 Parser.Lex();
3178 Code16GCC = true;
3179 if (!is16BitMode()) {
3180 SwitchMode(X86::Mode16Bit);
3181 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
3182 }
Saleem Abdulrasoola6505ca2014-01-13 01:15:39 +00003183 } else if (IDVal == ".code32") {
Craig Topper3c80d622014-01-06 04:55:54 +00003184 Parser.Lex();
3185 if (!is32BitMode()) {
3186 SwitchMode(X86::Mode32Bit);
Evan Cheng481ebb02011-07-27 00:38:12 +00003187 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
3188 }
3189 } else if (IDVal == ".code64") {
3190 Parser.Lex();
3191 if (!is64BitMode()) {
Craig Topper3c80d622014-01-06 04:55:54 +00003192 SwitchMode(X86::Mode64Bit);
Evan Cheng481ebb02011-07-27 00:38:12 +00003193 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code64);
3194 }
3195 } else {
Saleem Abdulrasoola6505ca2014-01-13 01:15:39 +00003196 Error(L, "unknown directive " + IDVal);
3197 return false;
Evan Cheng481ebb02011-07-27 00:38:12 +00003198 }
Chris Lattner72c0b592010-10-30 17:38:55 +00003199
Evan Cheng481ebb02011-07-27 00:38:12 +00003200 return false;
3201}
Chris Lattner72c0b592010-10-30 17:38:55 +00003202
Reid Kleckner9cdd4df2017-10-11 21:24:33 +00003203// .cv_fpo_proc foo
3204bool X86AsmParser::parseDirectiveFPOProc(SMLoc L) {
3205 MCAsmParser &Parser = getParser();
3206 StringRef ProcName;
3207 int64_t ParamsSize;
3208 if (Parser.parseIdentifier(ProcName))
3209 return Parser.TokError("expected symbol name");
3210 if (Parser.parseIntToken(ParamsSize, "expected parameter byte count"))
3211 return true;
3212 if (!isUIntN(32, ParamsSize))
3213 return Parser.TokError("parameters size out of range");
3214 if (Parser.parseEOL("unexpected tokens"))
3215 return addErrorSuffix(" in '.cv_fpo_proc' directive");
3216 MCSymbol *ProcSym = getContext().getOrCreateSymbol(ProcName);
3217 return getTargetStreamer().emitFPOProc(ProcSym, ParamsSize, L);
3218}
3219
3220// .cv_fpo_setframe ebp
3221bool X86AsmParser::parseDirectiveFPOSetFrame(SMLoc L) {
3222 MCAsmParser &Parser = getParser();
3223 unsigned Reg;
3224 SMLoc DummyLoc;
3225 if (ParseRegister(Reg, DummyLoc, DummyLoc) ||
3226 Parser.parseEOL("unexpected tokens"))
3227 return addErrorSuffix(" in '.cv_fpo_setframe' directive");
3228 return getTargetStreamer().emitFPOSetFrame(Reg, L);
3229}
3230
3231// .cv_fpo_pushreg ebx
3232bool X86AsmParser::parseDirectiveFPOPushReg(SMLoc L) {
3233 MCAsmParser &Parser = getParser();
3234 unsigned Reg;
3235 SMLoc DummyLoc;
3236 if (ParseRegister(Reg, DummyLoc, DummyLoc) ||
3237 Parser.parseEOL("unexpected tokens"))
3238 return addErrorSuffix(" in '.cv_fpo_pushreg' directive");
3239 return getTargetStreamer().emitFPOPushReg(Reg, L);
3240}
3241
3242// .cv_fpo_stackalloc 20
3243bool X86AsmParser::parseDirectiveFPOStackAlloc(SMLoc L) {
3244 MCAsmParser &Parser = getParser();
3245 int64_t Offset;
3246 if (Parser.parseIntToken(Offset, "expected offset") ||
3247 Parser.parseEOL("unexpected tokens"))
3248 return addErrorSuffix(" in '.cv_fpo_stackalloc' directive");
3249 return getTargetStreamer().emitFPOStackAlloc(Offset, L);
3250}
3251
3252// .cv_fpo_endprologue
3253bool X86AsmParser::parseDirectiveFPOEndPrologue(SMLoc L) {
3254 MCAsmParser &Parser = getParser();
3255 if (Parser.parseEOL("unexpected tokens"))
3256 return addErrorSuffix(" in '.cv_fpo_endprologue' directive");
3257 return getTargetStreamer().emitFPOEndPrologue(L);
3258}
3259
3260// .cv_fpo_endproc
3261bool X86AsmParser::parseDirectiveFPOEndProc(SMLoc L) {
3262 MCAsmParser &Parser = getParser();
3263 if (Parser.parseEOL("unexpected tokens"))
3264 return addErrorSuffix(" in '.cv_fpo_endproc' directive");
3265 return getTargetStreamer().emitFPOEndProc(L);
3266}
3267
Daniel Dunbar71475772009-07-17 20:42:00 +00003268// Force static initialization.
3269extern "C" void LLVMInitializeX86AsmParser() {
Mehdi Aminif42454b2016-10-09 23:00:34 +00003270 RegisterMCAsmParser<X86AsmParser> X(getTheX86_32Target());
3271 RegisterMCAsmParser<X86AsmParser> Y(getTheX86_64Target());
Daniel Dunbar71475772009-07-17 20:42:00 +00003272}
Daniel Dunbar00331992009-07-29 00:02:19 +00003273
Chris Lattner3e4582a2010-09-06 19:11:01 +00003274#define GET_REGISTER_MATCHER
3275#define GET_MATCHER_IMPLEMENTATION
Jim Grosbach6f1f41b2012-11-14 18:04:47 +00003276#define GET_SUBTARGET_FEATURE_NAME
Daniel Dunbar00331992009-07-29 00:02:19 +00003277#include "X86GenAsmMatcher.inc"