blob: 32ab475f11867f16b023b62dc4a28661eae1d531 [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
Evan Cheng11424442011-07-26 00:24:13 +000010#include "MCTargetDesc/X86BaseInfo.h"
Evgeniy Stepanov49e26252014-03-14 08:58:04 +000011#include "X86AsmInstrumentation.h"
Evgeniy Stepanove3804d42014-02-28 12:28:07 +000012#include "X86AsmParserCommon.h"
13#include "X86Operand.h"
Craig Topper690d8ea2013-07-24 07:33:14 +000014#include "llvm/ADT/STLExtras.h"
Chris Lattner1261b812010-09-22 04:11:10 +000015#include "llvm/ADT/SmallString.h"
16#include "llvm/ADT/SmallVector.h"
Chris Lattner1261b812010-09-22 04:11:10 +000017#include "llvm/ADT/StringSwitch.h"
18#include "llvm/ADT/Twine.h"
Chad Rosier8a244662013-04-02 20:02:33 +000019#include "llvm/MC/MCContext.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000020#include "llvm/MC/MCExpr.h"
21#include "llvm/MC/MCInst.h"
Evgeniy Stepanovf4a36992014-04-24 13:29:34 +000022#include "llvm/MC/MCInstrInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000023#include "llvm/MC/MCParser/MCAsmLexer.h"
24#include "llvm/MC/MCParser/MCAsmParser.h"
25#include "llvm/MC/MCParser/MCParsedAsmOperand.h"
Benjamin Kramerb3e8a6d2016-01-27 10:01:28 +000026#include "llvm/MC/MCParser/MCTargetAsmParser.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000027#include "llvm/MC/MCRegisterInfo.h"
Michael Zuckerman02ecd432015-12-13 17:07:23 +000028#include "llvm/MC/MCSection.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000029#include "llvm/MC/MCStreamer.h"
30#include "llvm/MC/MCSubtargetInfo.h"
31#include "llvm/MC/MCSymbol.h"
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +000032#include "llvm/Support/SourceMgr.h"
Evan Cheng2bb40352011-08-24 18:08:43 +000033#include "llvm/Support/TargetRegistry.h"
Daniel Dunbar7d7b4d12010-08-12 00:55:42 +000034#include "llvm/Support/raw_ostream.h"
Reid Kleckner7b1e1a02014-07-30 22:23:11 +000035#include <algorithm>
Evgeniy Stepanov49e26252014-03-14 08:58:04 +000036#include <memory>
Evan Cheng4d1ca962011-07-08 01:53:10 +000037
Daniel Dunbar71475772009-07-17 20:42:00 +000038using namespace llvm;
39
40namespace {
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +000041
Chad Rosier5362af92013-04-16 18:15:40 +000042static const char OpPrecedence[] = {
Kevin Enderby2e13b1c2014-01-15 19:05:24 +000043 0, // IC_OR
Michael Kupersteine3de07a2015-06-14 12:59:45 +000044 1, // IC_XOR
45 2, // IC_AND
46 3, // IC_LSHIFT
47 3, // IC_RSHIFT
48 4, // IC_PLUS
49 4, // IC_MINUS
50 5, // IC_MULTIPLY
51 5, // IC_DIVIDE
52 6, // IC_RPAREN
53 7, // IC_LPAREN
Chad Rosier5362af92013-04-16 18:15:40 +000054 0, // IC_IMM
55 0 // IC_REGISTER
56};
57
Devang Patel4a6e7782012-01-12 18:03:40 +000058class X86AsmParser : public MCTargetAsmParser {
Evgeniy Stepanovf4a36992014-04-24 13:29:34 +000059 const MCInstrInfo &MII;
Chad Rosierf0e87202012-10-25 20:41:34 +000060 ParseInstructionInfo *InstInfo;
Evgeniy Stepanov49e26252014-03-14 08:58:04 +000061 std::unique_ptr<X86AsmInstrumentation> Instrumentation;
Nirav Dave6477ce22016-09-26 19:33:36 +000062 bool Code16GCC;
NAKAMURA Takumia9cb5382015-09-22 11:14:39 +000063
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +000064private:
Alp Tokera5b88a52013-12-02 16:06:06 +000065 SMLoc consumeToken() {
Rafael Espindola961d4692014-11-11 05:18:41 +000066 MCAsmParser &Parser = getParser();
Alp Tokera5b88a52013-12-02 16:06:06 +000067 SMLoc Result = Parser.getTok().getLoc();
68 Parser.Lex();
69 return Result;
70 }
71
Nirav Dave6477ce22016-09-26 19:33:36 +000072 unsigned MatchInstruction(const OperandVector &Operands, MCInst &Inst,
73 uint64_t &ErrorInfo, bool matchingInlineAsm,
74 unsigned VariantID = 0) {
75 // In Code16GCC mode, match as 32-bit.
76 if (Code16GCC)
77 SwitchMode(X86::Mode32Bit);
78 unsigned rv = MatchInstructionImpl(Operands, Inst, ErrorInfo,
79 matchingInlineAsm, VariantID);
80 if (Code16GCC)
81 SwitchMode(X86::Mode16Bit);
82 return rv;
83 }
84
Chad Rosier5362af92013-04-16 18:15:40 +000085 enum InfixCalculatorTok {
Kevin Enderby2e13b1c2014-01-15 19:05:24 +000086 IC_OR = 0,
Michael Kupersteine3de07a2015-06-14 12:59:45 +000087 IC_XOR,
Kevin Enderby2e13b1c2014-01-15 19:05:24 +000088 IC_AND,
Kevin Enderbyd6b10712014-02-06 01:21:15 +000089 IC_LSHIFT,
90 IC_RSHIFT,
Kevin Enderby2e13b1c2014-01-15 19:05:24 +000091 IC_PLUS,
Chad Rosier5362af92013-04-16 18:15:40 +000092 IC_MINUS,
93 IC_MULTIPLY,
94 IC_DIVIDE,
95 IC_RPAREN,
96 IC_LPAREN,
97 IC_IMM,
98 IC_REGISTER
99 };
100
Coby Tayree07a89742017-03-21 19:31:55 +0000101 enum IntelOperatorKind {
102 IOK_INVALID = 0,
103 IOK_LENGTH,
104 IOK_SIZE,
105 IOK_TYPE,
106 IOK_OFFSET
107 };
108
Chad Rosier5362af92013-04-16 18:15:40 +0000109 class InfixCalculator {
110 typedef std::pair< InfixCalculatorTok, int64_t > ICToken;
111 SmallVector<InfixCalculatorTok, 4> InfixOperatorStack;
112 SmallVector<ICToken, 4> PostfixStack;
Michael Liao5bf95782014-12-04 05:20:33 +0000113
Chad Rosier5362af92013-04-16 18:15:40 +0000114 public:
115 int64_t popOperand() {
116 assert (!PostfixStack.empty() && "Poped an empty stack!");
117 ICToken Op = PostfixStack.pop_back_val();
118 assert ((Op.first == IC_IMM || Op.first == IC_REGISTER)
119 && "Expected and immediate or register!");
120 return Op.second;
121 }
122 void pushOperand(InfixCalculatorTok Op, int64_t Val = 0) {
123 assert ((Op == IC_IMM || Op == IC_REGISTER) &&
124 "Unexpected operand!");
125 PostfixStack.push_back(std::make_pair(Op, Val));
126 }
Michael Liao5bf95782014-12-04 05:20:33 +0000127
Jakub Staszak9c349222013-08-08 15:48:46 +0000128 void popOperator() { InfixOperatorStack.pop_back(); }
Chad Rosier5362af92013-04-16 18:15:40 +0000129 void pushOperator(InfixCalculatorTok Op) {
130 // Push the new operator if the stack is empty.
131 if (InfixOperatorStack.empty()) {
132 InfixOperatorStack.push_back(Op);
133 return;
134 }
Michael Liao5bf95782014-12-04 05:20:33 +0000135
Chad Rosier5362af92013-04-16 18:15:40 +0000136 // Push the new operator if it has a higher precedence than the operator
137 // on the top of the stack or the operator on the top of the stack is a
138 // left parentheses.
139 unsigned Idx = InfixOperatorStack.size() - 1;
140 InfixCalculatorTok StackOp = InfixOperatorStack[Idx];
141 if (OpPrecedence[Op] > OpPrecedence[StackOp] || StackOp == IC_LPAREN) {
142 InfixOperatorStack.push_back(Op);
143 return;
144 }
Michael Liao5bf95782014-12-04 05:20:33 +0000145
Chad Rosier5362af92013-04-16 18:15:40 +0000146 // The operator on the top of the stack has higher precedence than the
147 // new operator.
148 unsigned ParenCount = 0;
Kirill Bobyrev6afbaf02017-01-18 16:34:25 +0000149 while (1) {
Chad Rosier5362af92013-04-16 18:15:40 +0000150 // Nothing to process.
151 if (InfixOperatorStack.empty())
152 break;
Michael Liao5bf95782014-12-04 05:20:33 +0000153
Chad Rosier5362af92013-04-16 18:15:40 +0000154 Idx = InfixOperatorStack.size() - 1;
155 StackOp = InfixOperatorStack[Idx];
156 if (!(OpPrecedence[StackOp] >= OpPrecedence[Op] || ParenCount))
157 break;
Michael Liao5bf95782014-12-04 05:20:33 +0000158
Chad Rosier5362af92013-04-16 18:15:40 +0000159 // If we have an even parentheses count and we see a left parentheses,
160 // then stop processing.
161 if (!ParenCount && StackOp == IC_LPAREN)
162 break;
Michael Liao5bf95782014-12-04 05:20:33 +0000163
Chad Rosier5362af92013-04-16 18:15:40 +0000164 if (StackOp == IC_RPAREN) {
165 ++ParenCount;
Jakub Staszak9c349222013-08-08 15:48:46 +0000166 InfixOperatorStack.pop_back();
Chad Rosier5362af92013-04-16 18:15:40 +0000167 } else if (StackOp == IC_LPAREN) {
168 --ParenCount;
Jakub Staszak9c349222013-08-08 15:48:46 +0000169 InfixOperatorStack.pop_back();
Chad Rosier5362af92013-04-16 18:15:40 +0000170 } else {
Jakub Staszak9c349222013-08-08 15:48:46 +0000171 InfixOperatorStack.pop_back();
Chad Rosier5362af92013-04-16 18:15:40 +0000172 PostfixStack.push_back(std::make_pair(StackOp, 0));
173 }
174 }
175 // Push the new operator.
176 InfixOperatorStack.push_back(Op);
177 }
Marina Yatsinaa0e02412015-08-10 11:33:10 +0000178
Chad Rosier5362af92013-04-16 18:15:40 +0000179 int64_t execute() {
180 // Push any remaining operators onto the postfix stack.
181 while (!InfixOperatorStack.empty()) {
182 InfixCalculatorTok StackOp = InfixOperatorStack.pop_back_val();
183 if (StackOp != IC_LPAREN && StackOp != IC_RPAREN)
184 PostfixStack.push_back(std::make_pair(StackOp, 0));
185 }
Michael Liao5bf95782014-12-04 05:20:33 +0000186
Chad Rosier5362af92013-04-16 18:15:40 +0000187 if (PostfixStack.empty())
188 return 0;
Michael Liao5bf95782014-12-04 05:20:33 +0000189
Chad Rosier5362af92013-04-16 18:15:40 +0000190 SmallVector<ICToken, 16> OperandStack;
191 for (unsigned i = 0, e = PostfixStack.size(); i != e; ++i) {
192 ICToken Op = PostfixStack[i];
193 if (Op.first == IC_IMM || Op.first == IC_REGISTER) {
194 OperandStack.push_back(Op);
195 } else {
196 assert (OperandStack.size() > 1 && "Too few operands.");
197 int64_t Val;
198 ICToken Op2 = OperandStack.pop_back_val();
199 ICToken Op1 = OperandStack.pop_back_val();
200 switch (Op.first) {
201 default:
202 report_fatal_error("Unexpected operator!");
203 break;
204 case IC_PLUS:
205 Val = Op1.second + Op2.second;
206 OperandStack.push_back(std::make_pair(IC_IMM, Val));
207 break;
208 case IC_MINUS:
209 Val = Op1.second - Op2.second;
210 OperandStack.push_back(std::make_pair(IC_IMM, Val));
211 break;
212 case IC_MULTIPLY:
213 assert (Op1.first == IC_IMM && Op2.first == IC_IMM &&
214 "Multiply operation with an immediate and a register!");
215 Val = Op1.second * Op2.second;
216 OperandStack.push_back(std::make_pair(IC_IMM, Val));
217 break;
218 case IC_DIVIDE:
219 assert (Op1.first == IC_IMM && Op2.first == IC_IMM &&
220 "Divide operation with an immediate and a register!");
221 assert (Op2.second != 0 && "Division by zero!");
222 Val = Op1.second / Op2.second;
223 OperandStack.push_back(std::make_pair(IC_IMM, Val));
224 break;
Kevin Enderby2e13b1c2014-01-15 19:05:24 +0000225 case IC_OR:
226 assert (Op1.first == IC_IMM && Op2.first == IC_IMM &&
227 "Or operation with an immediate and a register!");
228 Val = Op1.second | Op2.second;
229 OperandStack.push_back(std::make_pair(IC_IMM, Val));
230 break;
Michael Kupersteine3de07a2015-06-14 12:59:45 +0000231 case IC_XOR:
232 assert(Op1.first == IC_IMM && Op2.first == IC_IMM &&
233 "Xor operation with an immediate and a register!");
234 Val = Op1.second ^ Op2.second;
235 OperandStack.push_back(std::make_pair(IC_IMM, Val));
236 break;
Kevin Enderby2e13b1c2014-01-15 19:05:24 +0000237 case IC_AND:
238 assert (Op1.first == IC_IMM && Op2.first == IC_IMM &&
239 "And operation with an immediate and a register!");
240 Val = Op1.second & Op2.second;
241 OperandStack.push_back(std::make_pair(IC_IMM, Val));
242 break;
Kevin Enderbyd6b10712014-02-06 01:21:15 +0000243 case IC_LSHIFT:
244 assert (Op1.first == IC_IMM && Op2.first == IC_IMM &&
245 "Left shift operation with an immediate and a register!");
246 Val = Op1.second << Op2.second;
247 OperandStack.push_back(std::make_pair(IC_IMM, Val));
248 break;
249 case IC_RSHIFT:
250 assert (Op1.first == IC_IMM && Op2.first == IC_IMM &&
251 "Right shift operation with an immediate and a register!");
252 Val = Op1.second >> Op2.second;
253 OperandStack.push_back(std::make_pair(IC_IMM, Val));
254 break;
Chad Rosier5362af92013-04-16 18:15:40 +0000255 }
256 }
257 }
258 assert (OperandStack.size() == 1 && "Expected a single result.");
259 return OperandStack.pop_back_val().second;
260 }
261 };
262
263 enum IntelExprState {
Kevin Enderby2e13b1c2014-01-15 19:05:24 +0000264 IES_OR,
Michael Kupersteine3de07a2015-06-14 12:59:45 +0000265 IES_XOR,
Kevin Enderby2e13b1c2014-01-15 19:05:24 +0000266 IES_AND,
Kevin Enderbyd6b10712014-02-06 01:21:15 +0000267 IES_LSHIFT,
268 IES_RSHIFT,
Chad Rosier5362af92013-04-16 18:15:40 +0000269 IES_PLUS,
270 IES_MINUS,
Ehsan Akhgari4103da62014-07-04 19:13:05 +0000271 IES_NOT,
Chad Rosier5362af92013-04-16 18:15:40 +0000272 IES_MULTIPLY,
273 IES_DIVIDE,
274 IES_LBRAC,
275 IES_RBRAC,
276 IES_LPAREN,
277 IES_RPAREN,
278 IES_REGISTER,
Chad Rosier5362af92013-04-16 18:15:40 +0000279 IES_INTEGER,
Chad Rosier5362af92013-04-16 18:15:40 +0000280 IES_IDENTIFIER,
281 IES_ERROR
282 };
283
284 class IntelExprStateMachine {
Chad Rosier31246272013-04-17 21:01:45 +0000285 IntelExprState State, PrevState;
Chad Rosier5362af92013-04-16 18:15:40 +0000286 unsigned BaseReg, IndexReg, TmpReg, Scale;
Chad Rosierbfb70992013-04-17 00:11:46 +0000287 int64_t Imm;
Chad Rosier5362af92013-04-16 18:15:40 +0000288 const MCExpr *Sym;
289 StringRef SymName;
Chad Rosierbfb70992013-04-17 00:11:46 +0000290 bool StopOnLBrac, AddImmPrefix;
Chad Rosier5362af92013-04-16 18:15:40 +0000291 InfixCalculator IC;
Chad Rosiercb78f0d2013-04-22 19:42:15 +0000292 InlineAsmIdentifierInfo Info;
NAKAMURA Takumia9cb5382015-09-22 11:14:39 +0000293
Chad Rosier5362af92013-04-16 18:15:40 +0000294 public:
Chad Rosierbfb70992013-04-17 00:11:46 +0000295 IntelExprStateMachine(int64_t imm, bool stoponlbrac, bool addimmprefix) :
Chad Rosier31246272013-04-17 21:01:45 +0000296 State(IES_PLUS), PrevState(IES_ERROR), BaseReg(0), IndexReg(0), TmpReg(0),
Craig Topper062a2ba2014-04-25 05:30:21 +0000297 Scale(1), Imm(imm), Sym(nullptr), StopOnLBrac(stoponlbrac),
Chad Rosiercb78f0d2013-04-22 19:42:15 +0000298 AddImmPrefix(addimmprefix) { Info.clear(); }
Michael Liao5bf95782014-12-04 05:20:33 +0000299
Chad Rosier5362af92013-04-16 18:15:40 +0000300 unsigned getBaseReg() { return BaseReg; }
301 unsigned getIndexReg() { return IndexReg; }
302 unsigned getScale() { return Scale; }
303 const MCExpr *getSym() { return Sym; }
304 StringRef getSymName() { return SymName; }
Chad Rosierbfb70992013-04-17 00:11:46 +0000305 int64_t getImm() { return Imm + IC.execute(); }
Chad Rosieredb1dc82013-05-09 23:48:53 +0000306 bool isValidEndState() {
307 return State == IES_RBRAC || State == IES_INTEGER;
308 }
Chad Rosierbfb70992013-04-17 00:11:46 +0000309 bool getStopOnLBrac() { return StopOnLBrac; }
310 bool getAddImmPrefix() { return AddImmPrefix; }
Chad Rosier31246272013-04-17 21:01:45 +0000311 bool hadError() { return State == IES_ERROR; }
Chad Rosierbfb70992013-04-17 00:11:46 +0000312
Chad Rosiercb78f0d2013-04-22 19:42:15 +0000313 InlineAsmIdentifierInfo &getIdentifierInfo() {
314 return Info;
315 }
316
Kevin Enderby2e13b1c2014-01-15 19:05:24 +0000317 void onOr() {
318 IntelExprState CurrState = State;
319 switch (State) {
320 default:
321 State = IES_ERROR;
322 break;
323 case IES_INTEGER:
324 case IES_RPAREN:
325 case IES_REGISTER:
326 State = IES_OR;
327 IC.pushOperator(IC_OR);
328 break;
329 }
330 PrevState = CurrState;
331 }
Michael Kupersteine3de07a2015-06-14 12:59:45 +0000332 void onXor() {
333 IntelExprState CurrState = State;
334 switch (State) {
335 default:
336 State = IES_ERROR;
337 break;
338 case IES_INTEGER:
339 case IES_RPAREN:
340 case IES_REGISTER:
341 State = IES_XOR;
342 IC.pushOperator(IC_XOR);
343 break;
344 }
345 PrevState = CurrState;
346 }
Kevin Enderby2e13b1c2014-01-15 19:05:24 +0000347 void onAnd() {
348 IntelExprState CurrState = State;
349 switch (State) {
350 default:
351 State = IES_ERROR;
352 break;
353 case IES_INTEGER:
354 case IES_RPAREN:
355 case IES_REGISTER:
356 State = IES_AND;
357 IC.pushOperator(IC_AND);
358 break;
359 }
360 PrevState = CurrState;
361 }
Kevin Enderbyd6b10712014-02-06 01:21:15 +0000362 void onLShift() {
363 IntelExprState CurrState = State;
364 switch (State) {
365 default:
366 State = IES_ERROR;
367 break;
368 case IES_INTEGER:
369 case IES_RPAREN:
370 case IES_REGISTER:
371 State = IES_LSHIFT;
372 IC.pushOperator(IC_LSHIFT);
373 break;
374 }
375 PrevState = CurrState;
376 }
377 void onRShift() {
378 IntelExprState CurrState = State;
379 switch (State) {
380 default:
381 State = IES_ERROR;
382 break;
383 case IES_INTEGER:
384 case IES_RPAREN:
385 case IES_REGISTER:
386 State = IES_RSHIFT;
387 IC.pushOperator(IC_RSHIFT);
388 break;
389 }
390 PrevState = CurrState;
391 }
Chad Rosier5362af92013-04-16 18:15:40 +0000392 void onPlus() {
Chad Rosier31246272013-04-17 21:01:45 +0000393 IntelExprState CurrState = State;
Chad Rosier5362af92013-04-16 18:15:40 +0000394 switch (State) {
395 default:
396 State = IES_ERROR;
397 break;
398 case IES_INTEGER:
399 case IES_RPAREN:
Chad Rosier5362af92013-04-16 18:15:40 +0000400 case IES_REGISTER:
401 State = IES_PLUS;
Chad Rosier5362af92013-04-16 18:15:40 +0000402 IC.pushOperator(IC_PLUS);
Chad Rosier31246272013-04-17 21:01:45 +0000403 if (CurrState == IES_REGISTER && PrevState != IES_MULTIPLY) {
404 // If we already have a BaseReg, then assume this is the IndexReg with
405 // a scale of 1.
406 if (!BaseReg) {
407 BaseReg = TmpReg;
408 } else {
409 assert (!IndexReg && "BaseReg/IndexReg already set!");
410 IndexReg = TmpReg;
411 Scale = 1;
412 }
413 }
Chad Rosier5362af92013-04-16 18:15:40 +0000414 break;
415 }
Chad Rosier31246272013-04-17 21:01:45 +0000416 PrevState = CurrState;
Chad Rosier5362af92013-04-16 18:15:40 +0000417 }
418 void onMinus() {
Chad Rosier31246272013-04-17 21:01:45 +0000419 IntelExprState CurrState = State;
Chad Rosier5362af92013-04-16 18:15:40 +0000420 switch (State) {
421 default:
422 State = IES_ERROR;
423 break;
424 case IES_PLUS:
Ehsan Akhgari4103da62014-07-04 19:13:05 +0000425 case IES_NOT:
Chad Rosier31246272013-04-17 21:01:45 +0000426 case IES_MULTIPLY:
427 case IES_DIVIDE:
Chad Rosier5362af92013-04-16 18:15:40 +0000428 case IES_LPAREN:
Chad Rosier5362af92013-04-16 18:15:40 +0000429 case IES_RPAREN:
Chad Rosier31246272013-04-17 21:01:45 +0000430 case IES_LBRAC:
431 case IES_RBRAC:
432 case IES_INTEGER:
Chad Rosier5362af92013-04-16 18:15:40 +0000433 case IES_REGISTER:
434 State = IES_MINUS;
Chad Rosier31246272013-04-17 21:01:45 +0000435 // Only push the minus operator if it is not a unary operator.
436 if (!(CurrState == IES_PLUS || CurrState == IES_MINUS ||
437 CurrState == IES_MULTIPLY || CurrState == IES_DIVIDE ||
438 CurrState == IES_LPAREN || CurrState == IES_LBRAC))
439 IC.pushOperator(IC_MINUS);
440 if (CurrState == IES_REGISTER && PrevState != IES_MULTIPLY) {
441 // If we already have a BaseReg, then assume this is the IndexReg with
442 // a scale of 1.
443 if (!BaseReg) {
444 BaseReg = TmpReg;
445 } else {
446 assert (!IndexReg && "BaseReg/IndexReg already set!");
447 IndexReg = TmpReg;
448 Scale = 1;
449 }
Chad Rosier5362af92013-04-16 18:15:40 +0000450 }
Chad Rosier5362af92013-04-16 18:15:40 +0000451 break;
452 }
Chad Rosier31246272013-04-17 21:01:45 +0000453 PrevState = CurrState;
Chad Rosier5362af92013-04-16 18:15:40 +0000454 }
Ehsan Akhgari4103da62014-07-04 19:13:05 +0000455 void onNot() {
456 IntelExprState CurrState = State;
457 switch (State) {
458 default:
459 State = IES_ERROR;
460 break;
461 case IES_PLUS:
462 case IES_NOT:
463 State = IES_NOT;
464 break;
465 }
466 PrevState = CurrState;
467 }
Chad Rosier5362af92013-04-16 18:15:40 +0000468 void onRegister(unsigned Reg) {
Chad Rosier31246272013-04-17 21:01:45 +0000469 IntelExprState CurrState = State;
Chad Rosier5362af92013-04-16 18:15:40 +0000470 switch (State) {
471 default:
472 State = IES_ERROR;
473 break;
474 case IES_PLUS:
475 case IES_LPAREN:
476 State = IES_REGISTER;
477 TmpReg = Reg;
478 IC.pushOperand(IC_REGISTER);
479 break;
Chad Rosier31246272013-04-17 21:01:45 +0000480 case IES_MULTIPLY:
481 // Index Register - Scale * Register
482 if (PrevState == IES_INTEGER) {
483 assert (!IndexReg && "IndexReg already set!");
484 State = IES_REGISTER;
485 IndexReg = Reg;
486 // Get the scale and replace the 'Scale * Register' with '0'.
487 Scale = IC.popOperand();
488 IC.pushOperand(IC_IMM);
489 IC.popOperator();
490 } else {
491 State = IES_ERROR;
492 }
Chad Rosier5362af92013-04-16 18:15:40 +0000493 break;
494 }
Chad Rosier31246272013-04-17 21:01:45 +0000495 PrevState = CurrState;
Chad Rosier5362af92013-04-16 18:15:40 +0000496 }
Chad Rosier95ce8892013-04-19 18:39:50 +0000497 void onIdentifierExpr(const MCExpr *SymRef, StringRef SymRefName) {
Chad Rosierdb003992013-04-18 16:28:19 +0000498 PrevState = State;
Chad Rosier5362af92013-04-16 18:15:40 +0000499 switch (State) {
500 default:
501 State = IES_ERROR;
502 break;
503 case IES_PLUS:
504 case IES_MINUS:
Ehsan Akhgari4103da62014-07-04 19:13:05 +0000505 case IES_NOT:
Chad Rosier5362af92013-04-16 18:15:40 +0000506 State = IES_INTEGER;
507 Sym = SymRef;
508 SymName = SymRefName;
509 IC.pushOperand(IC_IMM);
510 break;
511 }
512 }
Kevin Enderby9d117022014-01-23 21:52:41 +0000513 bool onInteger(int64_t TmpInt, StringRef &ErrMsg) {
Chad Rosier31246272013-04-17 21:01:45 +0000514 IntelExprState CurrState = State;
Chad Rosier5362af92013-04-16 18:15:40 +0000515 switch (State) {
516 default:
517 State = IES_ERROR;
518 break;
519 case IES_PLUS:
520 case IES_MINUS:
Ehsan Akhgari4103da62014-07-04 19:13:05 +0000521 case IES_NOT:
Kevin Enderby2e13b1c2014-01-15 19:05:24 +0000522 case IES_OR:
Michael Kupersteine3de07a2015-06-14 12:59:45 +0000523 case IES_XOR:
Kevin Enderby2e13b1c2014-01-15 19:05:24 +0000524 case IES_AND:
Kevin Enderbyd6b10712014-02-06 01:21:15 +0000525 case IES_LSHIFT:
526 case IES_RSHIFT:
Chad Rosier5362af92013-04-16 18:15:40 +0000527 case IES_DIVIDE:
Chad Rosier31246272013-04-17 21:01:45 +0000528 case IES_MULTIPLY:
Chad Rosier5362af92013-04-16 18:15:40 +0000529 case IES_LPAREN:
Chad Rosier5362af92013-04-16 18:15:40 +0000530 State = IES_INTEGER;
Chad Rosier31246272013-04-17 21:01:45 +0000531 if (PrevState == IES_REGISTER && CurrState == IES_MULTIPLY) {
532 // Index Register - Register * Scale
533 assert (!IndexReg && "IndexReg already set!");
534 IndexReg = TmpReg;
535 Scale = TmpInt;
Kevin Enderby9d117022014-01-23 21:52:41 +0000536 if(Scale != 1 && Scale != 2 && Scale != 4 && Scale != 8) {
537 ErrMsg = "scale factor in address must be 1, 2, 4 or 8";
538 return true;
539 }
Chad Rosier31246272013-04-17 21:01:45 +0000540 // Get the scale and replace the 'Register * Scale' with '0'.
541 IC.popOperator();
542 } else if ((PrevState == IES_PLUS || PrevState == IES_MINUS ||
Kevin Enderby2e13b1c2014-01-15 19:05:24 +0000543 PrevState == IES_OR || PrevState == IES_AND ||
Kevin Enderbyd6b10712014-02-06 01:21:15 +0000544 PrevState == IES_LSHIFT || PrevState == IES_RSHIFT ||
Chad Rosier31246272013-04-17 21:01:45 +0000545 PrevState == IES_MULTIPLY || PrevState == IES_DIVIDE ||
Ehsan Akhgari4103da62014-07-04 19:13:05 +0000546 PrevState == IES_LPAREN || PrevState == IES_LBRAC ||
Michael Kupersteine3de07a2015-06-14 12:59:45 +0000547 PrevState == IES_NOT || PrevState == IES_XOR) &&
Chad Rosier31246272013-04-17 21:01:45 +0000548 CurrState == IES_MINUS) {
549 // Unary minus. No need to pop the minus operand because it was never
550 // pushed.
551 IC.pushOperand(IC_IMM, -TmpInt); // Push -Imm.
Ehsan Akhgari4103da62014-07-04 19:13:05 +0000552 } else if ((PrevState == IES_PLUS || PrevState == IES_MINUS ||
553 PrevState == IES_OR || PrevState == IES_AND ||
554 PrevState == IES_LSHIFT || PrevState == IES_RSHIFT ||
555 PrevState == IES_MULTIPLY || PrevState == IES_DIVIDE ||
556 PrevState == IES_LPAREN || PrevState == IES_LBRAC ||
Michael Kupersteine3de07a2015-06-14 12:59:45 +0000557 PrevState == IES_NOT || PrevState == IES_XOR) &&
Ehsan Akhgari4103da62014-07-04 19:13:05 +0000558 CurrState == IES_NOT) {
559 // Unary not. No need to pop the not operand because it was never
560 // pushed.
561 IC.pushOperand(IC_IMM, ~TmpInt); // Push ~Imm.
Chad Rosier31246272013-04-17 21:01:45 +0000562 } else {
563 IC.pushOperand(IC_IMM, TmpInt);
564 }
Chad Rosier5362af92013-04-16 18:15:40 +0000565 break;
566 }
Chad Rosier31246272013-04-17 21:01:45 +0000567 PrevState = CurrState;
Kevin Enderby9d117022014-01-23 21:52:41 +0000568 return false;
Chad Rosier5362af92013-04-16 18:15:40 +0000569 }
570 void onStar() {
Chad Rosierdb003992013-04-18 16:28:19 +0000571 PrevState = State;
Chad Rosier5362af92013-04-16 18:15:40 +0000572 switch (State) {
573 default:
574 State = IES_ERROR;
575 break;
576 case IES_INTEGER:
Chad Rosier5362af92013-04-16 18:15:40 +0000577 case IES_REGISTER:
Chad Rosier5362af92013-04-16 18:15:40 +0000578 case IES_RPAREN:
579 State = IES_MULTIPLY;
580 IC.pushOperator(IC_MULTIPLY);
581 break;
582 }
583 }
584 void onDivide() {
Chad Rosierdb003992013-04-18 16:28:19 +0000585 PrevState = State;
Chad Rosier5362af92013-04-16 18:15:40 +0000586 switch (State) {
587 default:
588 State = IES_ERROR;
589 break;
590 case IES_INTEGER:
Chad Rosier31246272013-04-17 21:01:45 +0000591 case IES_RPAREN:
Chad Rosier5362af92013-04-16 18:15:40 +0000592 State = IES_DIVIDE;
593 IC.pushOperator(IC_DIVIDE);
594 break;
595 }
596 }
597 void onLBrac() {
Chad Rosierdb003992013-04-18 16:28:19 +0000598 PrevState = State;
Chad Rosier5362af92013-04-16 18:15:40 +0000599 switch (State) {
600 default:
601 State = IES_ERROR;
602 break;
603 case IES_RBRAC:
604 State = IES_PLUS;
605 IC.pushOperator(IC_PLUS);
606 break;
607 }
608 }
609 void onRBrac() {
Chad Rosier31246272013-04-17 21:01:45 +0000610 IntelExprState CurrState = State;
Chad Rosier5362af92013-04-16 18:15:40 +0000611 switch (State) {
612 default:
613 State = IES_ERROR;
614 break;
Chad Rosier5362af92013-04-16 18:15:40 +0000615 case IES_INTEGER:
Chad Rosier5362af92013-04-16 18:15:40 +0000616 case IES_REGISTER:
Chad Rosier31246272013-04-17 21:01:45 +0000617 case IES_RPAREN:
Chad Rosier5362af92013-04-16 18:15:40 +0000618 State = IES_RBRAC;
Chad Rosier31246272013-04-17 21:01:45 +0000619 if (CurrState == IES_REGISTER && PrevState != IES_MULTIPLY) {
620 // If we already have a BaseReg, then assume this is the IndexReg with
621 // a scale of 1.
622 if (!BaseReg) {
623 BaseReg = TmpReg;
624 } else {
625 assert (!IndexReg && "BaseReg/IndexReg already set!");
626 IndexReg = TmpReg;
627 Scale = 1;
628 }
Chad Rosier5362af92013-04-16 18:15:40 +0000629 }
630 break;
631 }
Chad Rosier31246272013-04-17 21:01:45 +0000632 PrevState = CurrState;
Chad Rosier5362af92013-04-16 18:15:40 +0000633 }
634 void onLParen() {
Chad Rosier31246272013-04-17 21:01:45 +0000635 IntelExprState CurrState = State;
Chad Rosier5362af92013-04-16 18:15:40 +0000636 switch (State) {
637 default:
638 State = IES_ERROR;
639 break;
640 case IES_PLUS:
641 case IES_MINUS:
Ehsan Akhgari4103da62014-07-04 19:13:05 +0000642 case IES_NOT:
Kevin Enderby2e13b1c2014-01-15 19:05:24 +0000643 case IES_OR:
Michael Kupersteine3de07a2015-06-14 12:59:45 +0000644 case IES_XOR:
Kevin Enderby2e13b1c2014-01-15 19:05:24 +0000645 case IES_AND:
Kevin Enderbyd6b10712014-02-06 01:21:15 +0000646 case IES_LSHIFT:
647 case IES_RSHIFT:
Chad Rosier5362af92013-04-16 18:15:40 +0000648 case IES_MULTIPLY:
649 case IES_DIVIDE:
Chad Rosier5362af92013-04-16 18:15:40 +0000650 case IES_LPAREN:
Ehsan Akhgari4103da62014-07-04 19:13:05 +0000651 // FIXME: We don't handle this type of unary minus or not, yet.
Chad Rosierdb003992013-04-18 16:28:19 +0000652 if ((PrevState == IES_PLUS || PrevState == IES_MINUS ||
Kevin Enderby2e13b1c2014-01-15 19:05:24 +0000653 PrevState == IES_OR || PrevState == IES_AND ||
Kevin Enderbyd6b10712014-02-06 01:21:15 +0000654 PrevState == IES_LSHIFT || PrevState == IES_RSHIFT ||
Chad Rosierdb003992013-04-18 16:28:19 +0000655 PrevState == IES_MULTIPLY || PrevState == IES_DIVIDE ||
Ehsan Akhgari4103da62014-07-04 19:13:05 +0000656 PrevState == IES_LPAREN || PrevState == IES_LBRAC ||
Michael Kupersteine3de07a2015-06-14 12:59:45 +0000657 PrevState == IES_NOT || PrevState == IES_XOR) &&
Ehsan Akhgari4103da62014-07-04 19:13:05 +0000658 (CurrState == IES_MINUS || CurrState == IES_NOT)) {
Chad Rosierdb003992013-04-18 16:28:19 +0000659 State = IES_ERROR;
660 break;
661 }
Chad Rosier5362af92013-04-16 18:15:40 +0000662 State = IES_LPAREN;
663 IC.pushOperator(IC_LPAREN);
664 break;
665 }
Chad Rosier31246272013-04-17 21:01:45 +0000666 PrevState = CurrState;
Chad Rosier5362af92013-04-16 18:15:40 +0000667 }
668 void onRParen() {
Chad Rosierdb003992013-04-18 16:28:19 +0000669 PrevState = State;
Chad Rosier5362af92013-04-16 18:15:40 +0000670 switch (State) {
671 default:
672 State = IES_ERROR;
673 break;
Chad Rosier5362af92013-04-16 18:15:40 +0000674 case IES_INTEGER:
Chad Rosier31246272013-04-17 21:01:45 +0000675 case IES_REGISTER:
Chad Rosier5362af92013-04-16 18:15:40 +0000676 case IES_RPAREN:
677 State = IES_RPAREN;
678 IC.pushOperator(IC_RPAREN);
679 break;
680 }
681 }
682 };
683
Nirav Dave2364748a2016-09-16 18:30:20 +0000684 bool Error(SMLoc L, const Twine &Msg, SMRange Range = None,
Chad Rosier4453e842012-10-12 23:09:25 +0000685 bool MatchingInlineAsm = false) {
Rafael Espindola961d4692014-11-11 05:18:41 +0000686 MCAsmParser &Parser = getParser();
Nirav Dave2364748a2016-09-16 18:30:20 +0000687 if (MatchingInlineAsm) {
688 if (!getLexer().isAtStartOfStatement())
689 Parser.eatToEndOfStatement();
690 return false;
691 }
692 return Parser.Error(L, Msg, Range);
Elena Demikhovskyc9657012014-02-20 06:34:39 +0000693 }
694
David Blaikie960ea3f2014-06-08 16:18:35 +0000695 std::nullptr_t ErrorOperand(SMLoc Loc, StringRef Msg) {
Devang Patel41b9dde2012-01-17 18:00:18 +0000696 Error(Loc, Msg);
Craig Topper062a2ba2014-04-25 05:30:21 +0000697 return nullptr;
Devang Patel41b9dde2012-01-17 18:00:18 +0000698 }
699
David Blaikie960ea3f2014-06-08 16:18:35 +0000700 std::unique_ptr<X86Operand> DefaultMemSIOperand(SMLoc Loc);
701 std::unique_ptr<X86Operand> DefaultMemDIOperand(SMLoc Loc);
Marina Yatsinab9f4f622016-01-19 15:37:56 +0000702 bool IsSIReg(unsigned Reg);
703 unsigned GetSIDIForRegClass(unsigned RegClassID, unsigned Reg, bool IsSIReg);
704 void
705 AddDefaultSrcDestOperands(OperandVector &Operands,
706 std::unique_ptr<llvm::MCParsedAsmOperand> &&Src,
707 std::unique_ptr<llvm::MCParsedAsmOperand> &&Dst);
708 bool VerifyAndAdjustOperands(OperandVector &OrigOperands,
709 OperandVector &FinalOperands);
David Blaikie960ea3f2014-06-08 16:18:35 +0000710 std::unique_ptr<X86Operand> ParseOperand();
711 std::unique_ptr<X86Operand> ParseATTOperand();
712 std::unique_ptr<X86Operand> ParseIntelOperand();
713 std::unique_ptr<X86Operand> ParseIntelOffsetOfOperator();
Benjamin Kramer951b15e2013-12-01 11:47:42 +0000714 bool ParseIntelDotOperator(const MCExpr *Disp, const MCExpr *&NewDisp);
Coby Tayree07a89742017-03-21 19:31:55 +0000715 unsigned IdentifyIntelOperator(StringRef Name);
716 unsigned ParseIntelOperator(unsigned OpKind);
David Blaikie960ea3f2014-06-08 16:18:35 +0000717 std::unique_ptr<X86Operand>
718 ParseIntelSegmentOverride(unsigned SegReg, SMLoc Start, unsigned Size);
Elena Demikhovsky18fd4962015-03-02 15:00:34 +0000719 std::unique_ptr<X86Operand> ParseRoundingModeOp(SMLoc Start, SMLoc End);
Coby Tayree2cb497a2017-04-04 14:43:23 +0000720 bool ParseIntelNamedOperator(StringRef Name, IntelExprStateMachine &SM);
Benjamin Kramer951b15e2013-12-01 11:47:42 +0000721 bool ParseIntelExpression(IntelExprStateMachine &SM, SMLoc &End);
Nirav Dave8601ac12016-08-02 17:56:03 +0000722 std::unique_ptr<X86Operand>
723 ParseIntelBracExpression(unsigned SegReg, SMLoc Start, int64_t ImmDisp,
724 bool isSymbol, unsigned Size);
Benjamin Kramer951b15e2013-12-01 11:47:42 +0000725 bool ParseIntelIdentifier(const MCExpr *&Val, StringRef &Identifier,
726 InlineAsmIdentifierInfo &Info,
727 bool IsUnevaluatedOperand, SMLoc &End);
Chad Rosiercb78f0d2013-04-22 19:42:15 +0000728
David Blaikie960ea3f2014-06-08 16:18:35 +0000729 std::unique_ptr<X86Operand> ParseMemOperand(unsigned SegReg, SMLoc StartLoc);
Kevin Enderbyce4bec82009-09-10 20:51:44 +0000730
David Blaikie960ea3f2014-06-08 16:18:35 +0000731 std::unique_ptr<X86Operand>
732 CreateMemForInlineAsm(unsigned SegReg, const MCExpr *Disp, unsigned BaseReg,
733 unsigned IndexReg, unsigned Scale, SMLoc Start,
734 SMLoc End, unsigned Size, StringRef Identifier,
Coby Tayree49b37332016-11-22 09:30:29 +0000735 InlineAsmIdentifierInfo &Info,
736 bool AllowBetterSizeMatch = false);
Chad Rosier7ca135b2013-03-19 21:11:56 +0000737
Michael Zuckerman02ecd432015-12-13 17:07:23 +0000738 bool parseDirectiveEven(SMLoc L);
Kevin Enderbyce4bec82009-09-10 20:51:44 +0000739 bool ParseDirectiveWord(unsigned Size, SMLoc L);
Evan Cheng481ebb02011-07-27 00:38:12 +0000740 bool ParseDirectiveCode(StringRef IDVal, SMLoc L);
Kevin Enderbyce4bec82009-09-10 20:51:44 +0000741
David Blaikie960ea3f2014-06-08 16:18:35 +0000742 bool processInstruction(MCInst &Inst, const OperandVector &Ops);
Devang Patelde47cce2012-01-18 22:42:29 +0000743
Evgeniy Stepanov49e26252014-03-14 08:58:04 +0000744 /// Wrapper around MCStreamer::EmitInstruction(). Possibly adds
745 /// instrumentation around Inst.
David Blaikie960ea3f2014-06-08 16:18:35 +0000746 void EmitInstruction(MCInst &Inst, OperandVector &Operands, MCStreamer &Out);
Evgeniy Stepanov49e26252014-03-14 08:58:04 +0000747
Chad Rosier49963552012-10-13 00:26:04 +0000748 bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
David Blaikie960ea3f2014-06-08 16:18:35 +0000749 OperandVector &Operands, MCStreamer &Out,
Tim Northover26bb14e2014-08-18 11:49:42 +0000750 uint64_t &ErrorInfo,
Craig Topper39012cc2014-03-09 18:03:14 +0000751 bool MatchingInlineAsm) override;
Chad Rosier9cb988f2012-08-09 22:04:55 +0000752
Reid Klecknerf6fb7802014-08-26 20:32:34 +0000753 void MatchFPUWaitAlias(SMLoc IDLoc, X86Operand &Op, OperandVector &Operands,
754 MCStreamer &Out, bool MatchingInlineAsm);
755
Ranjeet Singh86ecbb72015-06-30 12:32:53 +0000756 bool ErrorMissingFeature(SMLoc IDLoc, uint64_t ErrorInfo,
Reid Klecknerf6fb7802014-08-26 20:32:34 +0000757 bool MatchingInlineAsm);
758
759 bool MatchAndEmitATTInstruction(SMLoc IDLoc, unsigned &Opcode,
760 OperandVector &Operands, MCStreamer &Out,
761 uint64_t &ErrorInfo,
762 bool MatchingInlineAsm);
763
764 bool MatchAndEmitIntelInstruction(SMLoc IDLoc, unsigned &Opcode,
765 OperandVector &Operands, MCStreamer &Out,
766 uint64_t &ErrorInfo,
767 bool MatchingInlineAsm);
768
Craig Topperfd38cbe2014-08-30 16:48:34 +0000769 bool OmitRegisterFromClobberLists(unsigned RegNo) override;
Nico Weber42f79db2014-07-17 20:24:55 +0000770
Elena Demikhovskyc9657012014-02-20 06:34:39 +0000771 /// Parses AVX512 specific operand primitives: masked registers ({%k<NUM>}, {z})
772 /// and memory broadcasting ({1to<NUM>}) primitives, updating Operands vector if required.
Michael Zuckerman1bee6342016-10-18 13:52:39 +0000773 /// return false if no parsing errors occurred, true otherwise.
David Blaikie960ea3f2014-06-08 16:18:35 +0000774 bool HandleAVX512Operand(OperandVector &Operands,
775 const MCParsedAsmOperand &Op);
Elena Demikhovskyc9657012014-02-20 06:34:39 +0000776
Michael Zuckerman1bee6342016-10-18 13:52:39 +0000777 bool ParseZ(std::unique_ptr<X86Operand> &Z, const SMLoc &StartLoc);
778
Evan Chengc5e6d2f2011-07-11 03:57:24 +0000779 bool is64BitMode() const {
Evan Cheng4d1ca962011-07-08 01:53:10 +0000780 // FIXME: Can tablegen auto-generate this?
Akira Hatanakabd9fc282015-11-14 05:20:05 +0000781 return getSTI().getFeatureBits()[X86::Mode64Bit];
Evan Cheng4d1ca962011-07-08 01:53:10 +0000782 }
Craig Topper3c80d622014-01-06 04:55:54 +0000783 bool is32BitMode() const {
784 // FIXME: Can tablegen auto-generate this?
Akira Hatanakabd9fc282015-11-14 05:20:05 +0000785 return getSTI().getFeatureBits()[X86::Mode32Bit];
Craig Topper3c80d622014-01-06 04:55:54 +0000786 }
787 bool is16BitMode() const {
788 // FIXME: Can tablegen auto-generate this?
Akira Hatanakabd9fc282015-11-14 05:20:05 +0000789 return getSTI().getFeatureBits()[X86::Mode16Bit];
Craig Topper3c80d622014-01-06 04:55:54 +0000790 }
Michael Kupersteindb0712f2015-05-26 10:47:10 +0000791 void SwitchMode(unsigned mode) {
Akira Hatanakab11ef082015-11-14 06:35:56 +0000792 MCSubtargetInfo &STI = copySTI();
Michael Kupersteindb0712f2015-05-26 10:47:10 +0000793 FeatureBitset AllModes({X86::Mode64Bit, X86::Mode32Bit, X86::Mode16Bit});
794 FeatureBitset OldMode = STI.getFeatureBits() & AllModes;
Ranjeet Singh86ecbb72015-06-30 12:32:53 +0000795 unsigned FB = ComputeAvailableFeatures(
Michael Kupersteindb0712f2015-05-26 10:47:10 +0000796 STI.ToggleFeature(OldMode.flip(mode)));
Evan Cheng481ebb02011-07-27 00:38:12 +0000797 setAvailableFeatures(FB);
NAKAMURA Takumia9cb5382015-09-22 11:14:39 +0000798
Michael Kupersteindb0712f2015-05-26 10:47:10 +0000799 assert(FeatureBitset({mode}) == (STI.getFeatureBits() & AllModes));
Evan Cheng481ebb02011-07-27 00:38:12 +0000800 }
Evan Cheng4d1ca962011-07-08 01:53:10 +0000801
Reid Kleckner5b37c182014-08-01 20:21:24 +0000802 unsigned getPointerWidth() {
803 if (is16BitMode()) return 16;
804 if (is32BitMode()) return 32;
805 if (is64BitMode()) return 64;
806 llvm_unreachable("invalid mode");
807 }
808
Chad Rosierc2f055d2013-04-18 16:13:18 +0000809 bool isParsingIntelSyntax() {
810 return getParser().getAssemblerDialect();
811 }
812
Daniel Dunbareefe8612010-07-19 05:44:09 +0000813 /// @name Auto-generated Matcher Functions
814 /// {
Michael J. Spencer530ce852010-10-09 11:00:50 +0000815
Chris Lattner3e4582a2010-09-06 19:11:01 +0000816#define GET_ASSEMBLER_HEADER
817#include "X86GenAsmMatcher.inc"
Michael J. Spencer530ce852010-10-09 11:00:50 +0000818
Daniel Dunbar00331992009-07-29 00:02:19 +0000819 /// }
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +0000820
821public:
Coby Tayree07a89742017-03-21 19:31:55 +0000822
Akira Hatanakab11ef082015-11-14 06:35:56 +0000823 X86AsmParser(const MCSubtargetInfo &sti, MCAsmParser &Parser,
Rafael Espindola961d4692014-11-11 05:18:41 +0000824 const MCInstrInfo &mii, const MCTargetOptions &Options)
Nirav Dave6477ce22016-09-26 19:33:36 +0000825 : MCTargetAsmParser(Options, sti), MII(mii), InstInfo(nullptr),
826 Code16GCC(false) {
Michael J. Spencer530ce852010-10-09 11:00:50 +0000827
Daniel Dunbareefe8612010-07-19 05:44:09 +0000828 // Initialize the set of available features.
Akira Hatanakabd9fc282015-11-14 05:20:05 +0000829 setAvailableFeatures(ComputeAvailableFeatures(getSTI().getFeatureBits()));
Evgeniy Stepanov0a951b72014-04-23 11:16:03 +0000830 Instrumentation.reset(
831 CreateX86AsmInstrumentation(Options, Parser.getContext(), STI));
Daniel Dunbareefe8612010-07-19 05:44:09 +0000832 }
Evgeniy Stepanov0a951b72014-04-23 11:16:03 +0000833
Craig Topper39012cc2014-03-09 18:03:14 +0000834 bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc) override;
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +0000835
Yuri Gorshenin3939dec2014-09-10 09:45:49 +0000836 void SetFrameRegister(unsigned RegNo) override;
837
David Blaikie960ea3f2014-06-08 16:18:35 +0000838 bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
839 SMLoc NameLoc, OperandVector &Operands) override;
Kevin Enderbyce4bec82009-09-10 20:51:44 +0000840
Craig Topper39012cc2014-03-09 18:03:14 +0000841 bool ParseDirective(AsmToken DirectiveID) override;
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +0000842};
Chris Lattner4eb9df02009-07-29 06:33:53 +0000843} // end anonymous namespace
844
Sean Callanan86c11812010-01-23 00:40:33 +0000845/// @name Auto-generated Match Functions
Bruno Cardoso Lopesd65cd1d2010-07-23 22:15:26 +0000846/// {
Sean Callanan86c11812010-01-23 00:40:33 +0000847
Chris Lattner60db0a62010-02-09 00:34:28 +0000848static unsigned MatchRegisterName(StringRef Name);
Sean Callanan86c11812010-01-23 00:40:33 +0000849
850/// }
Chris Lattner4eb9df02009-07-29 06:33:53 +0000851
Kevin Enderbybc570f22014-01-23 22:34:42 +0000852static bool CheckBaseRegAndIndexReg(unsigned BaseReg, unsigned IndexReg,
853 StringRef &ErrMsg) {
854 // If we have both a base register and an index register make sure they are
855 // both 64-bit or 32-bit registers.
856 // To support VSIB, IndexReg can be 128-bit or 256-bit registers.
Douglas Katzman0411e862016-10-05 15:23:35 +0000857
858 if ((BaseReg == X86::RIP && IndexReg != 0) || (IndexReg == X86::RIP)) {
859 ErrMsg = "invalid base+index expression";
860 return true;
861 }
Kevin Enderbybc570f22014-01-23 22:34:42 +0000862 if (BaseReg != 0 && IndexReg != 0) {
863 if (X86MCRegisterClasses[X86::GR64RegClassID].contains(BaseReg) &&
864 (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) ||
865 X86MCRegisterClasses[X86::GR32RegClassID].contains(IndexReg)) &&
866 IndexReg != X86::RIZ) {
867 ErrMsg = "base register is 64-bit, but index register is not";
868 return true;
869 }
870 if (X86MCRegisterClasses[X86::GR32RegClassID].contains(BaseReg) &&
871 (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) ||
872 X86MCRegisterClasses[X86::GR64RegClassID].contains(IndexReg)) &&
873 IndexReg != X86::EIZ){
874 ErrMsg = "base register is 32-bit, but index register is not";
875 return true;
876 }
877 if (X86MCRegisterClasses[X86::GR16RegClassID].contains(BaseReg)) {
878 if (X86MCRegisterClasses[X86::GR32RegClassID].contains(IndexReg) ||
879 X86MCRegisterClasses[X86::GR64RegClassID].contains(IndexReg)) {
880 ErrMsg = "base register is 16-bit, but index register is not";
881 return true;
882 }
883 if (((BaseReg == X86::BX || BaseReg == X86::BP) &&
884 IndexReg != X86::SI && IndexReg != X86::DI) ||
885 ((BaseReg == X86::SI || BaseReg == X86::DI) &&
886 IndexReg != X86::BX && IndexReg != X86::BP)) {
887 ErrMsg = "invalid 16-bit base/index register combination";
888 return true;
889 }
890 }
891 }
892 return false;
893}
894
Devang Patel4a6e7782012-01-12 18:03:40 +0000895bool X86AsmParser::ParseRegister(unsigned &RegNo,
896 SMLoc &StartLoc, SMLoc &EndLoc) {
Rafael Espindola961d4692014-11-11 05:18:41 +0000897 MCAsmParser &Parser = getParser();
Chris Lattnercc2ad082010-01-15 18:27:19 +0000898 RegNo = 0;
Benjamin Kramere3d658b2012-09-07 14:51:35 +0000899 const AsmToken &PercentTok = Parser.getTok();
900 StartLoc = PercentTok.getLoc();
901
902 // If we encounter a %, ignore it. This code handles registers with and
903 // without the prefix, unprefixed registers can occur in cfi directives.
904 if (!isParsingIntelSyntax() && PercentTok.is(AsmToken::Percent))
Devang Patel41b9dde2012-01-17 18:00:18 +0000905 Parser.Lex(); // Eat percent token.
Kevin Enderby7d912182009-09-03 17:15:07 +0000906
Sean Callanan936b0d32010-01-19 21:44:56 +0000907 const AsmToken &Tok = Parser.getTok();
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000908 EndLoc = Tok.getEndLoc();
909
Devang Patelce6a2ca2012-01-20 22:32:05 +0000910 if (Tok.isNot(AsmToken::Identifier)) {
Devang Patel9a9bb5c2012-01-30 20:02:42 +0000911 if (isParsingIntelSyntax()) return true;
Benjamin Kramer1930b002011-10-16 12:10:27 +0000912 return Error(StartLoc, "invalid register name",
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000913 SMRange(StartLoc, EndLoc));
Devang Patelce6a2ca2012-01-20 22:32:05 +0000914 }
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +0000915
Kevin Enderby7d912182009-09-03 17:15:07 +0000916 RegNo = MatchRegisterName(Tok.getString());
Bruno Cardoso Lopesd65cd1d2010-07-23 22:15:26 +0000917
Chris Lattner1261b812010-09-22 04:11:10 +0000918 // If the match failed, try the register name as lowercase.
919 if (RegNo == 0)
Benjamin Kramer20baffb2011-11-06 20:37:06 +0000920 RegNo = MatchRegisterName(Tok.getString().lower());
Michael J. Spencer530ce852010-10-09 11:00:50 +0000921
Michael Kupersteincdb076b2015-07-30 10:10:25 +0000922 // The "flags" register cannot be referenced directly.
923 // Treat it as an identifier instead.
924 if (isParsingInlineAsm() && isParsingIntelSyntax() && RegNo == X86::EFLAGS)
925 RegNo = 0;
926
Evan Chengeda1d4f2011-07-27 23:22:03 +0000927 if (!is64BitMode()) {
Eric Christopherc0a5aae2013-12-20 02:04:49 +0000928 // FIXME: This should be done using Requires<Not64BitMode> and
Evan Chengeda1d4f2011-07-27 23:22:03 +0000929 // Requires<In64BitMode> so "eiz" usage in 64-bit instructions can be also
930 // checked.
931 // FIXME: Check AH, CH, DH, BH cannot be used in an instruction requiring a
932 // REX prefix.
933 if (RegNo == X86::RIZ ||
934 X86MCRegisterClasses[X86::GR64RegClassID].contains(RegNo) ||
935 X86II::isX86_64NonExtLowByteReg(RegNo) ||
Craig Topper6acca802016-08-27 17:13:37 +0000936 X86II::isX86_64ExtendedReg(RegNo))
Benjamin Kramer1930b002011-10-16 12:10:27 +0000937 return Error(StartLoc, "register %"
938 + Tok.getString() + " is only available in 64-bit mode",
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000939 SMRange(StartLoc, EndLoc));
Craig Topper29c22732016-02-26 05:29:32 +0000940 } else if (!getSTI().getFeatureBits()[X86::FeatureAVX512]) {
941 if (X86II::is32ExtendedReg(RegNo))
942 return Error(StartLoc, "register %"
Craig Topperd50b5f82016-02-26 06:50:24 +0000943 + Tok.getString() + " is only available with AVX512",
Craig Topper29c22732016-02-26 05:29:32 +0000944 SMRange(StartLoc, EndLoc));
Evan Chengeda1d4f2011-07-27 23:22:03 +0000945 }
Bruno Cardoso Lopes306a1f92010-07-24 00:06:39 +0000946
Chris Lattner1261b812010-09-22 04:11:10 +0000947 // Parse "%st" as "%st(0)" and "%st(1)", which is multiple tokens.
948 if (RegNo == 0 && (Tok.getString() == "st" || Tok.getString() == "ST")) {
Chris Lattnerd00faaa2010-02-09 00:49:22 +0000949 RegNo = X86::ST0;
Chris Lattnerd00faaa2010-02-09 00:49:22 +0000950 Parser.Lex(); // Eat 'st'
Bruno Cardoso Lopesd65cd1d2010-07-23 22:15:26 +0000951
Chris Lattnerd00faaa2010-02-09 00:49:22 +0000952 // Check to see if we have '(4)' after %st.
953 if (getLexer().isNot(AsmToken::LParen))
954 return false;
955 // Lex the paren.
956 getParser().Lex();
957
958 const AsmToken &IntTok = Parser.getTok();
959 if (IntTok.isNot(AsmToken::Integer))
960 return Error(IntTok.getLoc(), "expected stack index");
961 switch (IntTok.getIntVal()) {
962 case 0: RegNo = X86::ST0; break;
963 case 1: RegNo = X86::ST1; break;
964 case 2: RegNo = X86::ST2; break;
965 case 3: RegNo = X86::ST3; break;
966 case 4: RegNo = X86::ST4; break;
967 case 5: RegNo = X86::ST5; break;
968 case 6: RegNo = X86::ST6; break;
969 case 7: RegNo = X86::ST7; break;
970 default: return Error(IntTok.getLoc(), "invalid stack index");
971 }
Bruno Cardoso Lopesd65cd1d2010-07-23 22:15:26 +0000972
Chris Lattnerd00faaa2010-02-09 00:49:22 +0000973 if (getParser().Lex().isNot(AsmToken::RParen))
974 return Error(Parser.getTok().getLoc(), "expected ')'");
Bruno Cardoso Lopesd65cd1d2010-07-23 22:15:26 +0000975
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000976 EndLoc = Parser.getTok().getEndLoc();
Chris Lattnerd00faaa2010-02-09 00:49:22 +0000977 Parser.Lex(); // Eat ')'
978 return false;
979 }
Bruno Cardoso Lopesd65cd1d2010-07-23 22:15:26 +0000980
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000981 EndLoc = Parser.getTok().getEndLoc();
982
Chris Lattner80486622010-06-24 07:29:18 +0000983 // If this is "db[0-7]", match it as an alias
984 // for dr[0-7].
985 if (RegNo == 0 && Tok.getString().size() == 3 &&
986 Tok.getString().startswith("db")) {
987 switch (Tok.getString()[2]) {
988 case '0': RegNo = X86::DR0; break;
989 case '1': RegNo = X86::DR1; break;
990 case '2': RegNo = X86::DR2; break;
991 case '3': RegNo = X86::DR3; break;
992 case '4': RegNo = X86::DR4; break;
993 case '5': RegNo = X86::DR5; break;
994 case '6': RegNo = X86::DR6; break;
995 case '7': RegNo = X86::DR7; break;
996 }
Bruno Cardoso Lopesd65cd1d2010-07-23 22:15:26 +0000997
Chris Lattner80486622010-06-24 07:29:18 +0000998 if (RegNo != 0) {
Jordan Rosee8f1eae2013-01-07 19:00:49 +0000999 EndLoc = Parser.getTok().getEndLoc();
Chris Lattner80486622010-06-24 07:29:18 +00001000 Parser.Lex(); // Eat it.
1001 return false;
1002 }
1003 }
Bruno Cardoso Lopesd65cd1d2010-07-23 22:15:26 +00001004
Devang Patelce6a2ca2012-01-20 22:32:05 +00001005 if (RegNo == 0) {
Devang Patel9a9bb5c2012-01-30 20:02:42 +00001006 if (isParsingIntelSyntax()) return true;
Benjamin Kramer1930b002011-10-16 12:10:27 +00001007 return Error(StartLoc, "invalid register name",
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001008 SMRange(StartLoc, EndLoc));
Devang Patelce6a2ca2012-01-20 22:32:05 +00001009 }
Daniel Dunbar00331992009-07-29 00:02:19 +00001010
Sean Callanana83fd7d2010-01-19 20:27:46 +00001011 Parser.Lex(); // Eat identifier token.
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +00001012 return false;
Daniel Dunbar71475772009-07-17 20:42:00 +00001013}
1014
Yuri Gorshenin3939dec2014-09-10 09:45:49 +00001015void X86AsmParser::SetFrameRegister(unsigned RegNo) {
Yuri Gorshenine8c81fd2014-10-07 11:03:09 +00001016 Instrumentation->SetInitialFrameRegister(RegNo);
Yuri Gorshenin3939dec2014-09-10 09:45:49 +00001017}
1018
David Blaikie960ea3f2014-06-08 16:18:35 +00001019std::unique_ptr<X86Operand> X86AsmParser::DefaultMemSIOperand(SMLoc Loc) {
Nirav Dave6477ce22016-09-26 19:33:36 +00001020 bool Parse32 = is32BitMode() || Code16GCC;
1021 unsigned Basereg = is64BitMode() ? X86::RSI : (Parse32 ? X86::ESI : X86::SI);
Jim Grosbach13760bd2015-05-30 01:25:56 +00001022 const MCExpr *Disp = MCConstantExpr::create(0, getContext());
Craig Topper055845f2015-01-02 07:02:25 +00001023 return X86Operand::CreateMem(getPointerWidth(), /*SegReg=*/0, Disp,
Nirav Dave6477ce22016-09-26 19:33:36 +00001024 /*BaseReg=*/Basereg, /*IndexReg=*/0, /*Scale=*/1,
Craig Topper055845f2015-01-02 07:02:25 +00001025 Loc, Loc, 0);
David Woodhouse2ef8d9c2014-01-22 15:08:08 +00001026}
1027
David Blaikie960ea3f2014-06-08 16:18:35 +00001028std::unique_ptr<X86Operand> X86AsmParser::DefaultMemDIOperand(SMLoc Loc) {
Nirav Dave6477ce22016-09-26 19:33:36 +00001029 bool Parse32 = is32BitMode() || Code16GCC;
1030 unsigned Basereg = is64BitMode() ? X86::RDI : (Parse32 ? X86::EDI : X86::DI);
Jim Grosbach13760bd2015-05-30 01:25:56 +00001031 const MCExpr *Disp = MCConstantExpr::create(0, getContext());
Craig Topper055845f2015-01-02 07:02:25 +00001032 return X86Operand::CreateMem(getPointerWidth(), /*SegReg=*/0, Disp,
Nirav Dave6477ce22016-09-26 19:33:36 +00001033 /*BaseReg=*/Basereg, /*IndexReg=*/0, /*Scale=*/1,
Craig Topper055845f2015-01-02 07:02:25 +00001034 Loc, Loc, 0);
David Woodhouseb33c2ef2014-01-22 15:08:21 +00001035}
1036
Marina Yatsinab9f4f622016-01-19 15:37:56 +00001037bool X86AsmParser::IsSIReg(unsigned Reg) {
1038 switch (Reg) {
Craig Topper4d187632016-02-26 05:29:39 +00001039 default: llvm_unreachable("Only (R|E)SI and (R|E)DI are expected!");
Marina Yatsinab9f4f622016-01-19 15:37:56 +00001040 case X86::RSI:
1041 case X86::ESI:
1042 case X86::SI:
1043 return true;
1044 case X86::RDI:
1045 case X86::EDI:
1046 case X86::DI:
1047 return false;
1048 }
1049}
1050
1051unsigned X86AsmParser::GetSIDIForRegClass(unsigned RegClassID, unsigned Reg,
1052 bool IsSIReg) {
1053 switch (RegClassID) {
Craig Topper4d187632016-02-26 05:29:39 +00001054 default: llvm_unreachable("Unexpected register class");
Marina Yatsinab9f4f622016-01-19 15:37:56 +00001055 case X86::GR64RegClassID:
1056 return IsSIReg ? X86::RSI : X86::RDI;
1057 case X86::GR32RegClassID:
1058 return IsSIReg ? X86::ESI : X86::EDI;
1059 case X86::GR16RegClassID:
1060 return IsSIReg ? X86::SI : X86::DI;
1061 }
1062}
1063
Michael Kupersteinffcc7662015-07-23 10:23:48 +00001064void X86AsmParser::AddDefaultSrcDestOperands(
1065 OperandVector& Operands, std::unique_ptr<llvm::MCParsedAsmOperand> &&Src,
1066 std::unique_ptr<llvm::MCParsedAsmOperand> &&Dst) {
1067 if (isParsingIntelSyntax()) {
1068 Operands.push_back(std::move(Dst));
1069 Operands.push_back(std::move(Src));
1070 }
1071 else {
1072 Operands.push_back(std::move(Src));
1073 Operands.push_back(std::move(Dst));
1074 }
1075}
1076
Marina Yatsinab9f4f622016-01-19 15:37:56 +00001077bool X86AsmParser::VerifyAndAdjustOperands(OperandVector &OrigOperands,
1078 OperandVector &FinalOperands) {
1079
1080 if (OrigOperands.size() > 1) {
Craig Topperd55f4bc2016-02-16 07:45:07 +00001081 // Check if sizes match, OrigOperands also contains the instruction name
Marina Yatsinab9f4f622016-01-19 15:37:56 +00001082 assert(OrigOperands.size() == FinalOperands.size() + 1 &&
Craig Topperd55f4bc2016-02-16 07:45:07 +00001083 "Operand size mismatch");
Marina Yatsinab9f4f622016-01-19 15:37:56 +00001084
Marina Yatsinaff262fa2016-01-21 11:37:06 +00001085 SmallVector<std::pair<SMLoc, std::string>, 2> Warnings;
Marina Yatsinab9f4f622016-01-19 15:37:56 +00001086 // Verify types match
1087 int RegClassID = -1;
1088 for (unsigned int i = 0; i < FinalOperands.size(); ++i) {
1089 X86Operand &OrigOp = static_cast<X86Operand &>(*OrigOperands[i + 1]);
1090 X86Operand &FinalOp = static_cast<X86Operand &>(*FinalOperands[i]);
1091
1092 if (FinalOp.isReg() &&
1093 (!OrigOp.isReg() || FinalOp.getReg() != OrigOp.getReg()))
1094 // Return false and let a normal complaint about bogus operands happen
1095 return false;
1096
1097 if (FinalOp.isMem()) {
1098
1099 if (!OrigOp.isMem())
1100 // Return false and let a normal complaint about bogus operands happen
1101 return false;
1102
1103 unsigned OrigReg = OrigOp.Mem.BaseReg;
1104 unsigned FinalReg = FinalOp.Mem.BaseReg;
1105
1106 // If we've already encounterd a register class, make sure all register
1107 // bases are of the same register class
1108 if (RegClassID != -1 &&
1109 !X86MCRegisterClasses[RegClassID].contains(OrigReg)) {
1110 return Error(OrigOp.getStartLoc(),
1111 "mismatching source and destination index registers");
1112 }
1113
1114 if (X86MCRegisterClasses[X86::GR64RegClassID].contains(OrigReg))
1115 RegClassID = X86::GR64RegClassID;
1116 else if (X86MCRegisterClasses[X86::GR32RegClassID].contains(OrigReg))
1117 RegClassID = X86::GR32RegClassID;
1118 else if (X86MCRegisterClasses[X86::GR16RegClassID].contains(OrigReg))
1119 RegClassID = X86::GR16RegClassID;
Marina Yatsina701938d2016-01-20 14:03:47 +00001120 else
Craig Topper5a62f7e2016-02-16 07:28:03 +00001121 // Unexpected register class type
Marina Yatsina701938d2016-01-20 14:03:47 +00001122 // Return false and let a normal complaint about bogus operands happen
1123 return false;
Marina Yatsinab9f4f622016-01-19 15:37:56 +00001124
1125 bool IsSI = IsSIReg(FinalReg);
1126 FinalReg = GetSIDIForRegClass(RegClassID, FinalReg, IsSI);
1127
1128 if (FinalReg != OrigReg) {
1129 std::string RegName = IsSI ? "ES:(R|E)SI" : "ES:(R|E)DI";
Marina Yatsinaff262fa2016-01-21 11:37:06 +00001130 Warnings.push_back(std::make_pair(
1131 OrigOp.getStartLoc(),
1132 "memory operand is only for determining the size, " + RegName +
1133 " will be used for the location"));
Marina Yatsinab9f4f622016-01-19 15:37:56 +00001134 }
1135
1136 FinalOp.Mem.Size = OrigOp.Mem.Size;
1137 FinalOp.Mem.SegReg = OrigOp.Mem.SegReg;
1138 FinalOp.Mem.BaseReg = FinalReg;
1139 }
1140 }
1141
Marina Yatsinaff262fa2016-01-21 11:37:06 +00001142 // Produce warnings only if all the operands passed the adjustment - prevent
1143 // legal cases like "movsd (%rax), %xmm0" mistakenly produce warnings
Craig Topper16d7eb22016-02-16 07:45:04 +00001144 for (auto &WarningMsg : Warnings) {
1145 Warning(WarningMsg.first, WarningMsg.second);
Marina Yatsinaff262fa2016-01-21 11:37:06 +00001146 }
1147
1148 // Remove old operands
Marina Yatsinab9f4f622016-01-19 15:37:56 +00001149 for (unsigned int i = 0; i < FinalOperands.size(); ++i)
1150 OrigOperands.pop_back();
1151 }
1152 // OrigOperands.append(FinalOperands.begin(), FinalOperands.end());
1153 for (unsigned int i = 0; i < FinalOperands.size(); ++i)
1154 OrigOperands.push_back(std::move(FinalOperands[i]));
1155
1156 return false;
1157}
1158
David Blaikie960ea3f2014-06-08 16:18:35 +00001159std::unique_ptr<X86Operand> X86AsmParser::ParseOperand() {
Devang Patel9a9bb5c2012-01-30 20:02:42 +00001160 if (isParsingIntelSyntax())
Devang Patel46831de2012-01-12 01:36:43 +00001161 return ParseIntelOperand();
1162 return ParseATTOperand();
1163}
1164
Devang Patel41b9dde2012-01-17 18:00:18 +00001165/// getIntelMemOperandSize - Return intel memory operand size.
1166static unsigned getIntelMemOperandSize(StringRef OpStr) {
Chad Rosierb6b8e962012-09-11 21:10:25 +00001167 unsigned Size = StringSwitch<unsigned>(OpStr)
Chad Rosierab53b4f2012-09-12 18:24:26 +00001168 .Cases("BYTE", "byte", 8)
1169 .Cases("WORD", "word", 16)
1170 .Cases("DWORD", "dword", 32)
Marina Yatsina497d44a2015-12-07 13:09:20 +00001171 .Cases("FWORD", "fword", 48)
Chad Rosierab53b4f2012-09-12 18:24:26 +00001172 .Cases("QWORD", "qword", 64)
Michael Zuckerman9beca2e2015-08-24 10:26:54 +00001173 .Cases("MMWORD","mmword", 64)
Chad Rosierab53b4f2012-09-12 18:24:26 +00001174 .Cases("XWORD", "xword", 80)
Michael Kuperstein69e40a42015-07-19 11:03:08 +00001175 .Cases("TBYTE", "tbyte", 80)
Chad Rosierab53b4f2012-09-12 18:24:26 +00001176 .Cases("XMMWORD", "xmmword", 128)
1177 .Cases("YMMWORD", "ymmword", 256)
Craig Topper9ac290a2014-01-17 07:37:39 +00001178 .Cases("ZMMWORD", "zmmword", 512)
Craig Topper2d4b3c92014-01-17 07:44:10 +00001179 .Cases("OPAQUE", "opaque", -1U) // needs to be non-zero, but doesn't matter
Chad Rosierb6b8e962012-09-11 21:10:25 +00001180 .Default(0);
1181 return Size;
Devang Patel46831de2012-01-12 01:36:43 +00001182}
1183
David Blaikie960ea3f2014-06-08 16:18:35 +00001184std::unique_ptr<X86Operand> X86AsmParser::CreateMemForInlineAsm(
1185 unsigned SegReg, const MCExpr *Disp, unsigned BaseReg, unsigned IndexReg,
1186 unsigned Scale, SMLoc Start, SMLoc End, unsigned Size, StringRef Identifier,
Coby Tayree49b37332016-11-22 09:30:29 +00001187 InlineAsmIdentifierInfo &Info, bool AllowBetterSizeMatch) {
Reid Kleckner5b37c182014-08-01 20:21:24 +00001188 // If we found a decl other than a VarDecl, then assume it is a FuncDecl or
1189 // some other label reference.
1190 if (isa<MCSymbolRefExpr>(Disp) && Info.OpDecl && !Info.IsVarDecl) {
1191 // Insert an explicit size if the user didn't have one.
1192 if (!Size) {
1193 Size = getPointerWidth();
Craig Topper7d5b2312015-10-10 05:25:02 +00001194 InstInfo->AsmRewrites->emplace_back(AOK_SizeDirective, Start,
1195 /*Len=*/0, Size);
Reid Kleckner5b37c182014-08-01 20:21:24 +00001196 }
1197
1198 // Create an absolute memory reference in order to match against
1199 // instructions taking a PC relative operand.
Craig Topper055845f2015-01-02 07:02:25 +00001200 return X86Operand::CreateMem(getPointerWidth(), Disp, Start, End, Size,
1201 Identifier, Info.OpDecl);
Reid Klecknerd84e70e2014-03-04 00:33:17 +00001202 }
1203
Reid Kleckner6d2ea6e2017-05-04 18:19:52 +00001204
Reid Klecknerd84e70e2014-03-04 00:33:17 +00001205 // We either have a direct symbol reference, or an offset from a symbol. The
1206 // parser always puts the symbol on the LHS, so look there for size
1207 // calculation purposes.
Reid Kleckner6d2ea6e2017-05-04 18:19:52 +00001208 unsigned FrontendSize = 0;
Reid Klecknerd84e70e2014-03-04 00:33:17 +00001209 const MCBinaryExpr *BinOp = dyn_cast<MCBinaryExpr>(Disp);
1210 bool IsSymRef =
1211 isa<MCSymbolRefExpr>(BinOp ? BinOp->getLHS() : Disp);
Reid Kleckner6d2ea6e2017-05-04 18:19:52 +00001212 if (IsSymRef && !Size && Info.Type)
1213 FrontendSize = Info.Type * 8; // Size is in terms of bits in this context.
Chad Rosier7ca135b2013-03-19 21:11:56 +00001214
Chad Rosier7ca135b2013-03-19 21:11:56 +00001215 // When parsing inline assembly we set the base register to a non-zero value
Chad Rosier175d0ae2013-04-12 18:21:18 +00001216 // if we don't know the actual value at this time. This is necessary to
Chad Rosier7ca135b2013-03-19 21:11:56 +00001217 // get the matching correct in some cases.
Chad Rosier175d0ae2013-04-12 18:21:18 +00001218 BaseReg = BaseReg ? BaseReg : 1;
Craig Topper055845f2015-01-02 07:02:25 +00001219 return X86Operand::CreateMem(getPointerWidth(), SegReg, Disp, BaseReg,
1220 IndexReg, Scale, Start, End, Size, Identifier,
Reid Kleckner6d2ea6e2017-05-04 18:19:52 +00001221 Info.OpDecl, FrontendSize);
Chad Rosier7ca135b2013-03-19 21:11:56 +00001222}
1223
Chad Rosierd383db52013-04-12 20:20:54 +00001224static void
Craig Topper7143d802015-10-10 05:25:06 +00001225RewriteIntelBracExpression(SmallVectorImpl<AsmRewrite> &AsmRewrites,
Chad Rosierd383db52013-04-12 20:20:54 +00001226 StringRef SymName, int64_t ImmDisp,
1227 int64_t FinalImmDisp, SMLoc &BracLoc,
1228 SMLoc &StartInBrac, SMLoc &End) {
1229 // Remove the '[' and ']' from the IR string.
Craig Topper7143d802015-10-10 05:25:06 +00001230 AsmRewrites.emplace_back(AOK_Skip, BracLoc, 1);
1231 AsmRewrites.emplace_back(AOK_Skip, End, 1);
Chad Rosierd383db52013-04-12 20:20:54 +00001232
1233 // If ImmDisp is non-zero, then we parsed a displacement before the
1234 // bracketed expression (i.e., ImmDisp [ BaseReg + Scale*IndexReg + Disp])
1235 // If ImmDisp doesn't match the displacement computed by the state machine
1236 // then we have an additional displacement in the bracketed expression.
1237 if (ImmDisp != FinalImmDisp) {
1238 if (ImmDisp) {
1239 // We have an immediate displacement before the bracketed expression.
1240 // Adjust this to match the final immediate displacement.
1241 bool Found = false;
Craig Topper7143d802015-10-10 05:25:06 +00001242 for (AsmRewrite &AR : AsmRewrites) {
1243 if (AR.Loc.getPointer() > BracLoc.getPointer())
Chad Rosierd383db52013-04-12 20:20:54 +00001244 continue;
Craig Topper7143d802015-10-10 05:25:06 +00001245 if (AR.Kind == AOK_ImmPrefix || AR.Kind == AOK_Imm) {
Chad Rosierbfb70992013-04-17 00:11:46 +00001246 assert (!Found && "ImmDisp already rewritten.");
Craig Topper7143d802015-10-10 05:25:06 +00001247 AR.Kind = AOK_Imm;
1248 AR.Len = BracLoc.getPointer() - AR.Loc.getPointer();
1249 AR.Val = FinalImmDisp;
Chad Rosierd383db52013-04-12 20:20:54 +00001250 Found = true;
1251 break;
1252 }
1253 }
1254 assert (Found && "Unable to rewrite ImmDisp.");
Duncan Sands0480b9b2013-05-13 07:50:47 +00001255 (void)Found;
Chad Rosierd383db52013-04-12 20:20:54 +00001256 } else {
1257 // We have a symbolic and an immediate displacement, but no displacement
Chad Rosierbfb70992013-04-17 00:11:46 +00001258 // before the bracketed expression. Put the immediate displacement
Chad Rosierd383db52013-04-12 20:20:54 +00001259 // before the bracketed expression.
Craig Topper7143d802015-10-10 05:25:06 +00001260 AsmRewrites.emplace_back(AOK_Imm, BracLoc, 0, FinalImmDisp);
Chad Rosierd383db52013-04-12 20:20:54 +00001261 }
1262 }
1263 // Remove all the ImmPrefix rewrites within the brackets.
Coby Tayree07a89742017-03-21 19:31:55 +00001264 // We may have some Imm rewrties as a result of an operator applying,
1265 // remove them as well
Craig Topper7143d802015-10-10 05:25:06 +00001266 for (AsmRewrite &AR : AsmRewrites) {
1267 if (AR.Loc.getPointer() < StartInBrac.getPointer())
Chad Rosierd383db52013-04-12 20:20:54 +00001268 continue;
Coby Tayree07a89742017-03-21 19:31:55 +00001269 if (AR.Kind == AOK_ImmPrefix || AR.Kind == AOK_Imm)
Craig Topper7143d802015-10-10 05:25:06 +00001270 AR.Kind = AOK_Delete;
Chad Rosierd383db52013-04-12 20:20:54 +00001271 }
1272 const char *SymLocPtr = SymName.data();
Michael Liao5bf95782014-12-04 05:20:33 +00001273 // Skip everything before the symbol.
Chad Rosierd383db52013-04-12 20:20:54 +00001274 if (unsigned Len = SymLocPtr - StartInBrac.getPointer()) {
1275 assert(Len > 0 && "Expected a non-negative length.");
Craig Topper7d5b2312015-10-10 05:25:02 +00001276 AsmRewrites.emplace_back(AOK_Skip, StartInBrac, Len);
Chad Rosierd383db52013-04-12 20:20:54 +00001277 }
1278 // Skip everything after the symbol.
1279 if (unsigned Len = End.getPointer() - (SymLocPtr + SymName.size())) {
1280 SMLoc Loc = SMLoc::getFromPointer(SymLocPtr + SymName.size());
1281 assert(Len > 0 && "Expected a non-negative length.");
Craig Topper7d5b2312015-10-10 05:25:02 +00001282 AsmRewrites.emplace_back(AOK_Skip, Loc, Len);
Chad Rosierd383db52013-04-12 20:20:54 +00001283 }
1284}
1285
Coby Tayree2cb497a2017-04-04 14:43:23 +00001286// Some binary bitwise operators have a named synonymous
1287// Query a candidate string for being such a named operator
1288// and if so - invoke the appropriate handler
1289bool X86AsmParser::ParseIntelNamedOperator(StringRef Name, IntelExprStateMachine &SM) {
1290 // A named operator should be either lower or upper case, but not a mix
1291 if (Name.compare(Name.lower()) && Name.compare(Name.upper()))
1292 return false;
1293 if (Name.equals_lower("not"))
1294 SM.onNot();
1295 else if (Name.equals_lower("or"))
1296 SM.onOr();
1297 else if (Name.equals_lower("shl"))
1298 SM.onLShift();
1299 else if (Name.equals_lower("shr"))
1300 SM.onRShift();
1301 else if (Name.equals_lower("xor"))
1302 SM.onXor();
1303 else if (Name.equals_lower("and"))
1304 SM.onAnd();
1305 else
1306 return false;
1307 return true;
1308}
1309
Benjamin Kramer951b15e2013-12-01 11:47:42 +00001310bool X86AsmParser::ParseIntelExpression(IntelExprStateMachine &SM, SMLoc &End) {
Rafael Espindola961d4692014-11-11 05:18:41 +00001311 MCAsmParser &Parser = getParser();
Chad Rosier6844ea02012-10-24 22:13:37 +00001312 const AsmToken &Tok = Parser.getTok();
Chad Rosier51afe632012-06-27 22:34:28 +00001313
Marina Yatsina8dfd5cb2015-12-24 12:09:51 +00001314 AsmToken::TokenKind PrevTK = AsmToken::Error;
Chad Rosier5c118fd2013-01-14 22:31:35 +00001315 bool Done = false;
Chad Rosier5c118fd2013-01-14 22:31:35 +00001316 while (!Done) {
1317 bool UpdateLocLex = true;
1318
1319 // The period in the dot operator (e.g., [ebx].foo.bar) is parsed as an
1320 // identifier. Don't try an parse it as a register.
Nirav Dave8601ac12016-08-02 17:56:03 +00001321 if (PrevTK != AsmToken::Error && Tok.getString().startswith("."))
Chad Rosier5c118fd2013-01-14 22:31:35 +00001322 break;
Michael Liao5bf95782014-12-04 05:20:33 +00001323
Chad Rosierbfb70992013-04-17 00:11:46 +00001324 // If we're parsing an immediate expression, we don't expect a '['.
1325 if (SM.getStopOnLBrac() && getLexer().getKind() == AsmToken::LBrac)
1326 break;
Chad Rosier5c118fd2013-01-14 22:31:35 +00001327
David Majnemer6a5b8122014-06-19 01:25:43 +00001328 AsmToken::TokenKind TK = getLexer().getKind();
1329 switch (TK) {
Chad Rosier5c118fd2013-01-14 22:31:35 +00001330 default: {
1331 if (SM.isValidEndState()) {
1332 Done = true;
1333 break;
1334 }
Benjamin Kramer951b15e2013-12-01 11:47:42 +00001335 return Error(Tok.getLoc(), "unknown token in expression");
Chad Rosier5c118fd2013-01-14 22:31:35 +00001336 }
Chad Rosierbfb70992013-04-17 00:11:46 +00001337 case AsmToken::EndOfStatement: {
1338 Done = true;
1339 break;
1340 }
David Majnemer6a5b8122014-06-19 01:25:43 +00001341 case AsmToken::String:
Chad Rosier5c118fd2013-01-14 22:31:35 +00001342 case AsmToken::Identifier: {
Chad Rosier175d0ae2013-04-12 18:21:18 +00001343 // This could be a register or a symbolic displacement.
1344 unsigned TmpReg;
Chad Rosier95ce8892013-04-19 18:39:50 +00001345 const MCExpr *Val;
Chad Rosier152749c2013-04-12 18:54:20 +00001346 SMLoc IdentLoc = Tok.getLoc();
1347 StringRef Identifier = Tok.getString();
Coby Tayree07a89742017-03-21 19:31:55 +00001348 UpdateLocLex = false;
David Majnemer6a5b8122014-06-19 01:25:43 +00001349 if (TK != AsmToken::String && !ParseRegister(TmpReg, IdentLoc, End)) {
Chad Rosier5c118fd2013-01-14 22:31:35 +00001350 SM.onRegister(TmpReg);
Coby Tayree2cb497a2017-04-04 14:43:23 +00001351 } else if (ParseIntelNamedOperator(Identifier, SM)) {
1352 UpdateLocLex = true;
Coby Tayree07a89742017-03-21 19:31:55 +00001353 } else if (!isParsingInlineAsm()) {
1354 if (getParser().parsePrimaryExpr(Val, End))
1355 return Error(Tok.getLoc(), "Unexpected identifier!");
Chad Rosier95ce8892013-04-19 18:39:50 +00001356 SM.onIdentifierExpr(Val, Identifier);
Coby Tayree07a89742017-03-21 19:31:55 +00001357 } else if (unsigned OpKind = IdentifyIntelOperator(Identifier)) {
1358 if (OpKind == IOK_OFFSET)
1359 return Error(IdentLoc, "Dealing OFFSET operator as part of"
1360 "a compound immediate expression is yet to be supported");
1361 int64_t Val = ParseIntelOperator(OpKind);
1362 if (!Val)
1363 return true;
1364 StringRef ErrMsg;
1365 if (SM.onInteger(Val, ErrMsg))
1366 return Error(IdentLoc, ErrMsg);
1367 } else if (Identifier.find('.') != StringRef::npos &&
1368 PrevTK == AsmToken::RBrac) {
1369 return false;
1370 } else {
1371 InlineAsmIdentifierInfo &Info = SM.getIdentifierInfo();
1372 if (ParseIntelIdentifier(Val, Identifier, Info,
1373 /*Unevaluated=*/false, End))
1374 return true;
1375 SM.onIdentifierExpr(Val, Identifier);
Chad Rosier5c118fd2013-01-14 22:31:35 +00001376 }
Coby Tayree07a89742017-03-21 19:31:55 +00001377 break;
Chad Rosier5c118fd2013-01-14 22:31:35 +00001378 }
Kevin Enderby36eba252013-12-19 23:16:14 +00001379 case AsmToken::Integer: {
Kevin Enderby9d117022014-01-23 21:52:41 +00001380 StringRef ErrMsg;
Chad Rosierbfb70992013-04-17 00:11:46 +00001381 if (isParsingInlineAsm() && SM.getAddImmPrefix())
Craig Topper7d5b2312015-10-10 05:25:02 +00001382 InstInfo->AsmRewrites->emplace_back(AOK_ImmPrefix, Tok.getLoc());
Kevin Enderby36eba252013-12-19 23:16:14 +00001383 // Look for 'b' or 'f' following an Integer as a directional label
1384 SMLoc Loc = getTok().getLoc();
1385 int64_t IntVal = getTok().getIntVal();
1386 End = consumeToken();
1387 UpdateLocLex = false;
1388 if (getLexer().getKind() == AsmToken::Identifier) {
1389 StringRef IDVal = getTok().getString();
1390 if (IDVal == "f" || IDVal == "b") {
1391 MCSymbol *Sym =
Jim Grosbach6f482002015-05-18 18:43:14 +00001392 getContext().getDirectionalLocalSymbol(IntVal, IDVal == "b");
Kevin Enderby36eba252013-12-19 23:16:14 +00001393 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
Michael Liao5bf95782014-12-04 05:20:33 +00001394 const MCExpr *Val =
NAKAMURA Takumi0a7d0ad2015-09-22 11:15:07 +00001395 MCSymbolRefExpr::create(Sym, Variant, getContext());
Kevin Enderby36eba252013-12-19 23:16:14 +00001396 if (IDVal == "b" && Sym->isUndefined())
1397 return Error(Loc, "invalid reference to undefined symbol");
1398 StringRef Identifier = Sym->getName();
1399 SM.onIdentifierExpr(Val, Identifier);
1400 End = consumeToken();
1401 } else {
Kevin Enderby9d117022014-01-23 21:52:41 +00001402 if (SM.onInteger(IntVal, ErrMsg))
1403 return Error(Loc, ErrMsg);
Kevin Enderby36eba252013-12-19 23:16:14 +00001404 }
1405 } else {
Kevin Enderby9d117022014-01-23 21:52:41 +00001406 if (SM.onInteger(IntVal, ErrMsg))
1407 return Error(Loc, ErrMsg);
Kevin Enderby36eba252013-12-19 23:16:14 +00001408 }
Chad Rosier5c118fd2013-01-14 22:31:35 +00001409 break;
Kevin Enderby36eba252013-12-19 23:16:14 +00001410 }
Chad Rosier5c118fd2013-01-14 22:31:35 +00001411 case AsmToken::Plus: SM.onPlus(); break;
1412 case AsmToken::Minus: SM.onMinus(); break;
Ehsan Akhgari4103da62014-07-04 19:13:05 +00001413 case AsmToken::Tilde: SM.onNot(); break;
Chad Rosier5c118fd2013-01-14 22:31:35 +00001414 case AsmToken::Star: SM.onStar(); break;
Chad Rosier4a7005e2013-04-05 16:28:55 +00001415 case AsmToken::Slash: SM.onDivide(); break;
Kevin Enderby2e13b1c2014-01-15 19:05:24 +00001416 case AsmToken::Pipe: SM.onOr(); break;
Michael Kupersteine3de07a2015-06-14 12:59:45 +00001417 case AsmToken::Caret: SM.onXor(); break;
Kevin Enderby2e13b1c2014-01-15 19:05:24 +00001418 case AsmToken::Amp: SM.onAnd(); break;
Kevin Enderbyd6b10712014-02-06 01:21:15 +00001419 case AsmToken::LessLess:
1420 SM.onLShift(); break;
1421 case AsmToken::GreaterGreater:
1422 SM.onRShift(); break;
Chad Rosier5c118fd2013-01-14 22:31:35 +00001423 case AsmToken::LBrac: SM.onLBrac(); break;
1424 case AsmToken::RBrac: SM.onRBrac(); break;
Chad Rosier4a7005e2013-04-05 16:28:55 +00001425 case AsmToken::LParen: SM.onLParen(); break;
1426 case AsmToken::RParen: SM.onRParen(); break;
Chad Rosier5c118fd2013-01-14 22:31:35 +00001427 }
Chad Rosier31246272013-04-17 21:01:45 +00001428 if (SM.hadError())
Benjamin Kramer951b15e2013-12-01 11:47:42 +00001429 return Error(Tok.getLoc(), "unknown token in expression");
Chad Rosier31246272013-04-17 21:01:45 +00001430
Alp Tokera5b88a52013-12-02 16:06:06 +00001431 if (!Done && UpdateLocLex)
1432 End = consumeToken();
Marina Yatsina8dfd5cb2015-12-24 12:09:51 +00001433
1434 PrevTK = TK;
Devang Patel41b9dde2012-01-17 18:00:18 +00001435 }
Benjamin Kramer951b15e2013-12-01 11:47:42 +00001436 return false;
Chad Rosier5362af92013-04-16 18:15:40 +00001437}
1438
David Blaikie960ea3f2014-06-08 16:18:35 +00001439std::unique_ptr<X86Operand>
1440X86AsmParser::ParseIntelBracExpression(unsigned SegReg, SMLoc Start,
Nirav Dave8601ac12016-08-02 17:56:03 +00001441 int64_t ImmDisp, bool isSymbol,
1442 unsigned Size) {
Rafael Espindola961d4692014-11-11 05:18:41 +00001443 MCAsmParser &Parser = getParser();
Chad Rosier5362af92013-04-16 18:15:40 +00001444 const AsmToken &Tok = Parser.getTok();
1445 SMLoc BracLoc = Tok.getLoc(), End = Tok.getEndLoc();
1446 if (getLexer().isNot(AsmToken::LBrac))
1447 return ErrorOperand(BracLoc, "Expected '[' token!");
1448 Parser.Lex(); // Eat '['
1449
Nirav Davea6c75952016-07-14 17:37:05 +00001450 SMLoc StartInBrac = Parser.getTok().getLoc();
Chad Rosier5362af92013-04-16 18:15:40 +00001451 // Parse [ Symbol + ImmDisp ] and [ BaseReg + Scale*IndexReg + ImmDisp ]. We
1452 // may have already parsed an immediate displacement before the bracketed
1453 // expression.
Chad Rosierbfb70992013-04-17 00:11:46 +00001454 IntelExprStateMachine SM(ImmDisp, /*StopOnLBrac=*/false, /*AddImmPrefix=*/true);
Benjamin Kramer951b15e2013-12-01 11:47:42 +00001455 if (ParseIntelExpression(SM, End))
Craig Topper062a2ba2014-04-25 05:30:21 +00001456 return nullptr;
Devang Patel41b9dde2012-01-17 18:00:18 +00001457
Craig Topper062a2ba2014-04-25 05:30:21 +00001458 const MCExpr *Disp = nullptr;
Chad Rosier175d0ae2013-04-12 18:21:18 +00001459 if (const MCExpr *Sym = SM.getSym()) {
Chad Rosierd383db52013-04-12 20:20:54 +00001460 // A symbolic displacement.
Chad Rosier175d0ae2013-04-12 18:21:18 +00001461 Disp = Sym;
Chad Rosierd383db52013-04-12 20:20:54 +00001462 if (isParsingInlineAsm())
Craig Topper7143d802015-10-10 05:25:06 +00001463 RewriteIntelBracExpression(*InstInfo->AsmRewrites, SM.getSymName(),
Chad Rosier5362af92013-04-16 18:15:40 +00001464 ImmDisp, SM.getImm(), BracLoc, StartInBrac,
Chad Rosierd383db52013-04-12 20:20:54 +00001465 End);
Reid Klecknerd84e70e2014-03-04 00:33:17 +00001466 }
1467
1468 if (SM.getImm() || !Disp) {
Jim Grosbach13760bd2015-05-30 01:25:56 +00001469 const MCExpr *Imm = MCConstantExpr::create(SM.getImm(), getContext());
Reid Klecknerd84e70e2014-03-04 00:33:17 +00001470 if (Disp)
Jim Grosbach13760bd2015-05-30 01:25:56 +00001471 Disp = MCBinaryExpr::createAdd(Disp, Imm, getContext());
Reid Klecknerd84e70e2014-03-04 00:33:17 +00001472 else
1473 Disp = Imm; // An immediate displacement only.
Chad Rosier175d0ae2013-04-12 18:21:18 +00001474 }
Devang Pateld0930ff2012-01-20 21:21:01 +00001475
Reid Kleckner94a1c4d2014-03-06 19:19:12 +00001476 // Parse struct field access. Intel requires a dot, but MSVC doesn't. MSVC
1477 // will in fact do global lookup the field name inside all global typedefs,
1478 // but we don't emulate that.
Nirav Davea6c75952016-07-14 17:37:05 +00001479 if ((Parser.getTok().getKind() == AsmToken::Identifier ||
1480 Parser.getTok().getKind() == AsmToken::Dot ||
1481 Parser.getTok().getKind() == AsmToken::Real) &&
1482 Parser.getTok().getString().find('.') != StringRef::npos) {
Chad Rosier911c1f32012-10-25 17:37:43 +00001483 const MCExpr *NewDisp;
Benjamin Kramer951b15e2013-12-01 11:47:42 +00001484 if (ParseIntelDotOperator(Disp, NewDisp))
Craig Topper062a2ba2014-04-25 05:30:21 +00001485 return nullptr;
Michael Liao5bf95782014-12-04 05:20:33 +00001486
Chad Rosier70f47592013-04-10 20:07:47 +00001487 End = Tok.getEndLoc();
Chad Rosier911c1f32012-10-25 17:37:43 +00001488 Parser.Lex(); // Eat the field.
1489 Disp = NewDisp;
1490 }
Chad Rosier5dcb4662012-10-24 22:21:50 +00001491
Nirav Dave8601ac12016-08-02 17:56:03 +00001492 if (isSymbol) {
1493 if (SM.getSym()) {
1494 Error(Start, "cannot use more than one symbol in memory operand");
1495 return nullptr;
1496 }
1497 if (SM.getBaseReg()) {
1498 Error(Start, "cannot use base register with variable reference");
1499 return nullptr;
1500 }
1501 if (SM.getIndexReg()) {
1502 Error(Start, "cannot use index register with variable reference");
1503 return nullptr;
1504 }
1505 }
1506
Chad Rosier5c118fd2013-01-14 22:31:35 +00001507 int BaseReg = SM.getBaseReg();
1508 int IndexReg = SM.getIndexReg();
Chad Rosier175d0ae2013-04-12 18:21:18 +00001509 int Scale = SM.getScale();
Chad Rosiere8f9bfd2013-04-19 19:29:50 +00001510 if (!isParsingInlineAsm()) {
1511 // handle [-42]
1512 if (!BaseReg && !IndexReg) {
1513 if (!SegReg)
Craig Topper055845f2015-01-02 07:02:25 +00001514 return X86Operand::CreateMem(getPointerWidth(), Disp, Start, End, Size);
1515 return X86Operand::CreateMem(getPointerWidth(), SegReg, Disp, 0, 0, 1,
1516 Start, End, Size);
Chad Rosiere8f9bfd2013-04-19 19:29:50 +00001517 }
Kevin Enderbybc570f22014-01-23 22:34:42 +00001518 StringRef ErrMsg;
1519 if (CheckBaseRegAndIndexReg(BaseReg, IndexReg, ErrMsg)) {
1520 Error(StartInBrac, ErrMsg);
Craig Topper062a2ba2014-04-25 05:30:21 +00001521 return nullptr;
Kevin Enderbybc570f22014-01-23 22:34:42 +00001522 }
Craig Topper055845f2015-01-02 07:02:25 +00001523 return X86Operand::CreateMem(getPointerWidth(), SegReg, Disp, BaseReg,
1524 IndexReg, Scale, Start, End, Size);
Chad Rosier5c118fd2013-01-14 22:31:35 +00001525 }
Chad Rosiere8f9bfd2013-04-19 19:29:50 +00001526
Chad Rosiercb78f0d2013-04-22 19:42:15 +00001527 InlineAsmIdentifierInfo &Info = SM.getIdentifierInfo();
Chad Rosiere8f9bfd2013-04-19 19:29:50 +00001528 return CreateMemForInlineAsm(SegReg, Disp, BaseReg, IndexReg, Scale, Start,
Coby Tayree49b37332016-11-22 09:30:29 +00001529 End, Size, SM.getSymName(), Info,
1530 isParsingInlineAsm());
Devang Patel41b9dde2012-01-17 18:00:18 +00001531}
1532
Chad Rosier8a244662013-04-02 20:02:33 +00001533// Inline assembly may use variable names with namespace alias qualifiers.
Benjamin Kramer951b15e2013-12-01 11:47:42 +00001534bool X86AsmParser::ParseIntelIdentifier(const MCExpr *&Val,
1535 StringRef &Identifier,
1536 InlineAsmIdentifierInfo &Info,
1537 bool IsUnevaluatedOperand, 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());
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001543 void *Result =
1544 SemaCallback->LookupInlineAsmIdentifier(LineBuf, Info, IsUnevaluatedOperand);
Chad Rosiercb78f0d2013-04-22 19:42:15 +00001545
Chad Rosier8a244662013-04-02 20:02:33 +00001546 const AsmToken &Tok = Parser.getTok();
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001547 SMLoc Loc = Tok.getLoc();
John McCallf73981b2013-05-03 00:15:41 +00001548
1549 // Advance the token stream until the end of the current token is
1550 // after the end of what the frontend claimed.
1551 const char *EndPtr = Tok.getLoc().getPointer() + LineBuf.size();
Reid Klecknerc2b92542015-08-26 21:57:25 +00001552 do {
John McCallf73981b2013-05-03 00:15:41 +00001553 End = Tok.getEndLoc();
1554 getLexer().Lex();
Reid Klecknerc2b92542015-08-26 21:57:25 +00001555 } while (End.getPointer() < EndPtr);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001556 Identifier = LineBuf;
1557
Reid Klecknerc2b92542015-08-26 21:57:25 +00001558 // The frontend should end parsing on an assembler token boundary, unless it
1559 // failed parsing.
1560 assert((End.getPointer() == EndPtr || !Result) &&
1561 "frontend claimed part of a token?");
1562
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001563 // If the identifier lookup was unsuccessful, assume that we are dealing with
1564 // a label.
1565 if (!Result) {
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);
Ehsan Akhgaridb0e7062014-09-22 02:21:35 +00001573 }
Chad Rosiercb78f0d2013-04-22 19:42:15 +00001574
1575 // 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
David Majnemeraa34d792013-08-27 21:56:17 +00001582/// \brief Parse intel style segment override.
David Blaikie960ea3f2014-06-08 16:18:35 +00001583std::unique_ptr<X86Operand>
1584X86AsmParser::ParseIntelSegmentOverride(unsigned SegReg, SMLoc Start,
1585 unsigned Size) {
Rafael Espindola961d4692014-11-11 05:18:41 +00001586 MCAsmParser &Parser = getParser();
David Majnemeraa34d792013-08-27 21:56:17 +00001587 assert(SegReg != 0 && "Tried to parse a segment override without a segment!");
1588 const AsmToken &Tok = Parser.getTok(); // Eat colon.
1589 if (Tok.isNot(AsmToken::Colon))
1590 return ErrorOperand(Tok.getLoc(), "Expected ':' token!");
1591 Parser.Lex(); // Eat ':'
Devang Patel41b9dde2012-01-17 18:00:18 +00001592
David Majnemeraa34d792013-08-27 21:56:17 +00001593 int64_t ImmDisp = 0;
Chad Rosier1530ba52013-03-27 21:49:56 +00001594 if (getLexer().is(AsmToken::Integer)) {
David Majnemeraa34d792013-08-27 21:56:17 +00001595 ImmDisp = Tok.getIntVal();
1596 AsmToken ImmDispToken = Parser.Lex(); // Eat the integer.
1597
Chad Rosier1530ba52013-03-27 21:49:56 +00001598 if (isParsingInlineAsm())
Craig Topper7d5b2312015-10-10 05:25:02 +00001599 InstInfo->AsmRewrites->emplace_back(AOK_ImmPrefix, ImmDispToken.getLoc());
David Majnemeraa34d792013-08-27 21:56:17 +00001600
1601 if (getLexer().isNot(AsmToken::LBrac)) {
1602 // An immediate following a 'segment register', 'colon' token sequence can
1603 // be followed by a bracketed expression. If it isn't we know we have our
1604 // final segment override.
Jim Grosbach13760bd2015-05-30 01:25:56 +00001605 const MCExpr *Disp = MCConstantExpr::create(ImmDisp, getContext());
Craig Topper055845f2015-01-02 07:02:25 +00001606 return X86Operand::CreateMem(getPointerWidth(), SegReg, Disp,
1607 /*BaseReg=*/0, /*IndexReg=*/0, /*Scale=*/1,
1608 Start, ImmDispToken.getEndLoc(), Size);
David Majnemeraa34d792013-08-27 21:56:17 +00001609 }
Chad Rosier1530ba52013-03-27 21:49:56 +00001610 }
1611
Chad Rosier91c82662012-10-24 17:22:29 +00001612 if (getLexer().is(AsmToken::LBrac))
Nirav Dave8601ac12016-08-02 17:56:03 +00001613 return ParseIntelBracExpression(SegReg, Start, ImmDisp, false, Size);
Devang Patel880bc162012-01-23 18:31:58 +00001614
David Majnemeraa34d792013-08-27 21:56:17 +00001615 const MCExpr *Val;
1616 SMLoc End;
1617 if (!isParsingInlineAsm()) {
1618 if (getParser().parsePrimaryExpr(Val, End))
Benjamin Kramer951b15e2013-12-01 11:47:42 +00001619 return ErrorOperand(Tok.getLoc(), "unknown token in expression");
David Majnemeraa34d792013-08-27 21:56:17 +00001620
Craig Topper055845f2015-01-02 07:02:25 +00001621 return X86Operand::CreateMem(getPointerWidth(), Val, Start, End, Size);
Devang Patel880bc162012-01-23 18:31:58 +00001622 }
Devang Patel41b9dde2012-01-17 18:00:18 +00001623
David Majnemeraa34d792013-08-27 21:56:17 +00001624 InlineAsmIdentifierInfo Info;
1625 StringRef Identifier = Tok.getString();
Benjamin Kramer951b15e2013-12-01 11:47:42 +00001626 if (ParseIntelIdentifier(Val, Identifier, Info,
1627 /*Unevaluated=*/false, End))
Craig Topper062a2ba2014-04-25 05:30:21 +00001628 return nullptr;
David Majnemeraa34d792013-08-27 21:56:17 +00001629 return CreateMemForInlineAsm(/*SegReg=*/0, Val, /*BaseReg=*/0,/*IndexReg=*/0,
1630 /*Scale=*/1, Start, End, Size, Identifier, Info);
1631}
1632
Elena Demikhovsky18fd4962015-03-02 15:00:34 +00001633//ParseRoundingModeOp - Parse AVX-512 rounding mode operand
1634std::unique_ptr<X86Operand>
1635X86AsmParser::ParseRoundingModeOp(SMLoc Start, SMLoc End) {
1636 MCAsmParser &Parser = getParser();
1637 const AsmToken &Tok = Parser.getTok();
Elena Demikhovsky29792e92015-05-07 11:24:42 +00001638 // Eat "{" and mark the current place.
1639 const SMLoc consumedToken = consumeToken();
Elena Demikhovsky18fd4962015-03-02 15:00:34 +00001640 if (Tok.getIdentifier().startswith("r")){
1641 int rndMode = StringSwitch<int>(Tok.getIdentifier())
1642 .Case("rn", X86::STATIC_ROUNDING::TO_NEAREST_INT)
1643 .Case("rd", X86::STATIC_ROUNDING::TO_NEG_INF)
1644 .Case("ru", X86::STATIC_ROUNDING::TO_POS_INF)
1645 .Case("rz", X86::STATIC_ROUNDING::TO_ZERO)
1646 .Default(-1);
1647 if (-1 == rndMode)
1648 return ErrorOperand(Tok.getLoc(), "Invalid rounding mode.");
1649 Parser.Lex(); // Eat "r*" of r*-sae
1650 if (!getLexer().is(AsmToken::Minus))
1651 return ErrorOperand(Tok.getLoc(), "Expected - at this point");
1652 Parser.Lex(); // Eat "-"
1653 Parser.Lex(); // Eat the sae
1654 if (!getLexer().is(AsmToken::RCurly))
1655 return ErrorOperand(Tok.getLoc(), "Expected } at this point");
1656 Parser.Lex(); // Eat "}"
1657 const MCExpr *RndModeOp =
Jim Grosbach13760bd2015-05-30 01:25:56 +00001658 MCConstantExpr::create(rndMode, Parser.getContext());
Elena Demikhovsky18fd4962015-03-02 15:00:34 +00001659 return X86Operand::CreateImm(RndModeOp, Start, End);
1660 }
Elena Demikhovsky29792e92015-05-07 11:24:42 +00001661 if(Tok.getIdentifier().equals("sae")){
1662 Parser.Lex(); // Eat the sae
1663 if (!getLexer().is(AsmToken::RCurly))
1664 return ErrorOperand(Tok.getLoc(), "Expected } at this point");
1665 Parser.Lex(); // Eat "}"
1666 return X86Operand::CreateToken("{sae}", consumedToken);
1667 }
Elena Demikhovsky18fd4962015-03-02 15:00:34 +00001668 return ErrorOperand(Tok.getLoc(), "unknown token in expression");
1669}
Chad Rosier91c82662012-10-24 17:22:29 +00001670
Chad Rosier5dcb4662012-10-24 22:21:50 +00001671/// Parse the '.' operator.
Benjamin Kramer951b15e2013-12-01 11:47:42 +00001672bool X86AsmParser::ParseIntelDotOperator(const MCExpr *Disp,
Chad Rosiercc541e82013-04-19 15:57:00 +00001673 const MCExpr *&NewDisp) {
Rafael Espindola961d4692014-11-11 05:18:41 +00001674 MCAsmParser &Parser = getParser();
Chad Rosier70f47592013-04-10 20:07:47 +00001675 const AsmToken &Tok = Parser.getTok();
Chad Rosier6241c1a2013-04-17 21:14:38 +00001676 int64_t OrigDispVal, DotDispVal;
Chad Rosier911c1f32012-10-25 17:37:43 +00001677
1678 // FIXME: Handle non-constant expressions.
Chad Rosiercc541e82013-04-19 15:57:00 +00001679 if (const MCConstantExpr *OrigDisp = dyn_cast<MCConstantExpr>(Disp))
Chad Rosier911c1f32012-10-25 17:37:43 +00001680 OrigDispVal = OrigDisp->getValue();
Chad Rosiercc541e82013-04-19 15:57:00 +00001681 else
Benjamin Kramer951b15e2013-12-01 11:47:42 +00001682 return Error(Tok.getLoc(), "Non-constant offsets are not supported!");
Chad Rosier5dcb4662012-10-24 22:21:50 +00001683
Reid Kleckner94a1c4d2014-03-06 19:19:12 +00001684 // Drop the optional '.'.
1685 StringRef DotDispStr = Tok.getString();
1686 if (DotDispStr.startswith("."))
1687 DotDispStr = DotDispStr.drop_front(1);
Chad Rosier5dcb4662012-10-24 22:21:50 +00001688
Chad Rosier5dcb4662012-10-24 22:21:50 +00001689 // .Imm gets lexed as a real.
1690 if (Tok.is(AsmToken::Real)) {
1691 APInt DotDisp;
1692 DotDispStr.getAsInteger(10, DotDisp);
Chad Rosier911c1f32012-10-25 17:37:43 +00001693 DotDispVal = DotDisp.getZExtValue();
Chad Rosiercc541e82013-04-19 15:57:00 +00001694 } else if (isParsingInlineAsm() && Tok.is(AsmToken::Identifier)) {
Chad Rosier240b7b92012-10-25 21:51:10 +00001695 unsigned DotDisp;
1696 std::pair<StringRef, StringRef> BaseMember = DotDispStr.split('.');
1697 if (SemaCallback->LookupInlineAsmField(BaseMember.first, BaseMember.second,
Chad Rosiercc541e82013-04-19 15:57:00 +00001698 DotDisp))
Benjamin Kramer951b15e2013-12-01 11:47:42 +00001699 return Error(Tok.getLoc(), "Unable to lookup field reference!");
Chad Rosier240b7b92012-10-25 21:51:10 +00001700 DotDispVal = DotDisp;
Chad Rosiercc541e82013-04-19 15:57:00 +00001701 } else
Benjamin Kramer951b15e2013-12-01 11:47:42 +00001702 return Error(Tok.getLoc(), "Unexpected token type!");
Chad Rosier911c1f32012-10-25 17:37:43 +00001703
Chad Rosier240b7b92012-10-25 21:51:10 +00001704 if (isParsingInlineAsm() && Tok.is(AsmToken::Identifier)) {
1705 SMLoc Loc = SMLoc::getFromPointer(DotDispStr.data());
1706 unsigned Len = DotDispStr.size();
1707 unsigned Val = OrigDispVal + DotDispVal;
Craig Topper7d5b2312015-10-10 05:25:02 +00001708 InstInfo->AsmRewrites->emplace_back(AOK_DotOperator, Loc, Len, Val);
Chad Rosier911c1f32012-10-25 17:37:43 +00001709 }
1710
Jim Grosbach13760bd2015-05-30 01:25:56 +00001711 NewDisp = MCConstantExpr::create(OrigDispVal + DotDispVal, getContext());
Benjamin Kramer951b15e2013-12-01 11:47:42 +00001712 return false;
Chad Rosier5dcb4662012-10-24 22:21:50 +00001713}
1714
Chad Rosier91c82662012-10-24 17:22:29 +00001715/// Parse the 'offset' operator. This operator is used to specify the
1716/// location rather then the content of a variable.
David Blaikie960ea3f2014-06-08 16:18:35 +00001717std::unique_ptr<X86Operand> X86AsmParser::ParseIntelOffsetOfOperator() {
Rafael Espindola961d4692014-11-11 05:18:41 +00001718 MCAsmParser &Parser = getParser();
Chad Rosier18785852013-04-09 20:58:48 +00001719 const AsmToken &Tok = Parser.getTok();
Chad Rosier10d1d1c2013-04-09 20:44:09 +00001720 SMLoc OffsetOfLoc = Tok.getLoc();
Chad Rosier91c82662012-10-24 17:22:29 +00001721 Parser.Lex(); // Eat offset.
Chad Rosier91c82662012-10-24 17:22:29 +00001722
Chad Rosier91c82662012-10-24 17:22:29 +00001723 const MCExpr *Val;
Chad Rosiercb78f0d2013-04-22 19:42:15 +00001724 InlineAsmIdentifierInfo Info;
Chad Rosier18785852013-04-09 20:58:48 +00001725 SMLoc Start = Tok.getLoc(), End;
Chad Rosierae7ecd62013-04-11 23:37:34 +00001726 StringRef Identifier = Tok.getString();
Benjamin Kramer951b15e2013-12-01 11:47:42 +00001727 if (ParseIntelIdentifier(Val, Identifier, Info,
1728 /*Unevaluated=*/false, End))
Craig Topper062a2ba2014-04-25 05:30:21 +00001729 return nullptr;
Chad Rosierae7ecd62013-04-11 23:37:34 +00001730
Chad Rosiere2f03772012-10-26 16:09:20 +00001731 // Don't emit the offset operator.
Craig Topper7d5b2312015-10-10 05:25:02 +00001732 InstInfo->AsmRewrites->emplace_back(AOK_Skip, OffsetOfLoc, 7);
Chad Rosiere2f03772012-10-26 16:09:20 +00001733
Chad Rosier91c82662012-10-24 17:22:29 +00001734 // The offset operator will have an 'r' constraint, thus we need to create
1735 // register operand to ensure proper matching. Just pick a GPR based on
1736 // the size of a pointer.
Nirav Dave6477ce22016-09-26 19:33:36 +00001737 bool Parse32 = is32BitMode() || Code16GCC;
1738 unsigned RegNo = is64BitMode() ? X86::RBX : (Parse32 ? X86::EBX : X86::BX);
1739
Chad Rosiera4bc9432013-01-10 22:10:27 +00001740 return X86Operand::CreateReg(RegNo, Start, End, /*GetAddress=*/true,
Peter Collingbourne0da86302016-10-10 22:49:37 +00001741 OffsetOfLoc, Identifier, Info.OpDecl);
Devang Patel41b9dde2012-01-17 18:00:18 +00001742}
1743
Coby Tayree07a89742017-03-21 19:31:55 +00001744// Query a candidate string for being an Intel assembly operator
1745// Report back its kind, or IOK_INVALID if does not evaluated as a known one
1746unsigned X86AsmParser::IdentifyIntelOperator(StringRef Name) {
1747 return StringSwitch<unsigned>(Name)
1748 .Cases("TYPE","type",IOK_TYPE)
1749 .Cases("SIZE","size",IOK_SIZE)
1750 .Cases("LENGTH","length",IOK_LENGTH)
1751 .Cases("OFFSET","offset",IOK_OFFSET)
1752 .Default(IOK_INVALID);
1753}
Chad Rosierd0ed73a2013-01-17 19:21:48 +00001754
1755/// Parse the 'LENGTH', 'TYPE' and 'SIZE' operators. The LENGTH operator
1756/// returns the number of elements in an array. It returns the value 1 for
1757/// non-array variables. The SIZE operator returns the size of a C or C++
1758/// variable. A variable's size is the product of its LENGTH and TYPE. The
1759/// TYPE operator returns the size of a C or C++ type or variable. If the
1760/// variable is an array, TYPE returns the size of a single element.
Coby Tayree07a89742017-03-21 19:31:55 +00001761unsigned X86AsmParser::ParseIntelOperator(unsigned OpKind) {
Rafael Espindola961d4692014-11-11 05:18:41 +00001762 MCAsmParser &Parser = getParser();
Chad Rosier18785852013-04-09 20:58:48 +00001763 const AsmToken &Tok = Parser.getTok();
Chad Rosier10d1d1c2013-04-09 20:44:09 +00001764 SMLoc TypeLoc = Tok.getLoc();
1765 Parser.Lex(); // Eat operator.
Chad Rosier11c42f22012-10-26 18:04:20 +00001766
Craig Topper062a2ba2014-04-25 05:30:21 +00001767 const MCExpr *Val = nullptr;
Chad Rosiercb78f0d2013-04-22 19:42:15 +00001768 InlineAsmIdentifierInfo Info;
Chad Rosier18785852013-04-09 20:58:48 +00001769 SMLoc Start = Tok.getLoc(), End;
Chad Rosierb67f8052013-04-11 23:57:04 +00001770 StringRef Identifier = Tok.getString();
Benjamin Kramer951b15e2013-12-01 11:47:42 +00001771 if (ParseIntelIdentifier(Val, Identifier, Info,
1772 /*Unevaluated=*/true, End))
Coby Tayree07a89742017-03-21 19:31:55 +00001773 return 0;
Benjamin Kramer951b15e2013-12-01 11:47:42 +00001774
Coby Tayree07a89742017-03-21 19:31:55 +00001775 if (!Info.OpDecl) {
1776 Error(Start, "unable to lookup expression");
1777 return 0;
1778 }
1779
Chad Rosierf6675c32013-04-22 17:01:46 +00001780 unsigned CVal = 0;
Chad Rosiercb78f0d2013-04-22 19:42:15 +00001781 switch(OpKind) {
1782 default: llvm_unreachable("Unexpected operand kind!");
1783 case IOK_LENGTH: CVal = Info.Length; break;
1784 case IOK_SIZE: CVal = Info.Size; break;
1785 case IOK_TYPE: CVal = Info.Type; break;
1786 }
Chad Rosier11c42f22012-10-26 18:04:20 +00001787
1788 // Rewrite the type operator and the C or C++ type or variable in terms of an
1789 // immediate. E.g. TYPE foo -> $$4
1790 unsigned Len = End.getPointer() - TypeLoc.getPointer();
Craig Topper7d5b2312015-10-10 05:25:02 +00001791 InstInfo->AsmRewrites->emplace_back(AOK_Imm, TypeLoc, Len, CVal);
Chad Rosier11c42f22012-10-26 18:04:20 +00001792
Coby Tayree07a89742017-03-21 19:31:55 +00001793 return CVal;
Chad Rosier11c42f22012-10-26 18:04:20 +00001794}
1795
David Blaikie960ea3f2014-06-08 16:18:35 +00001796std::unique_ptr<X86Operand> X86AsmParser::ParseIntelOperand() {
Rafael Espindola961d4692014-11-11 05:18:41 +00001797 MCAsmParser &Parser = getParser();
Chad Rosier70f47592013-04-10 20:07:47 +00001798 const AsmToken &Tok = Parser.getTok();
David Majnemeraa34d792013-08-27 21:56:17 +00001799 SMLoc Start, End;
Chad Rosier91c82662012-10-24 17:22:29 +00001800
Coby Tayree07a89742017-03-21 19:31:55 +00001801 // FIXME: Offset operator
1802 // Should be handled as part of immediate expression, as other operators
1803 // Currently, only supported as a stand-alone operand
1804 if (isParsingInlineAsm())
1805 if (IdentifyIntelOperator(Tok.getString()) == IOK_OFFSET)
Chad Rosier10d1d1c2013-04-09 20:44:09 +00001806 return ParseIntelOffsetOfOperator();
Chad Rosier11c42f22012-10-26 18:04:20 +00001807
Marina Yatsina4b1aea02015-12-03 12:17:03 +00001808 bool PtrInOperand = false;
David Majnemeraa34d792013-08-27 21:56:17 +00001809 unsigned Size = getIntelMemOperandSize(Tok.getString());
1810 if (Size) {
1811 Parser.Lex(); // Eat operand size (e.g., byte, word).
1812 if (Tok.getString() != "PTR" && Tok.getString() != "ptr")
Reid Kleckner71ff3f22014-08-01 00:59:22 +00001813 return ErrorOperand(Tok.getLoc(), "Expected 'PTR' or 'ptr' token!");
David Majnemeraa34d792013-08-27 21:56:17 +00001814 Parser.Lex(); // Eat ptr.
Marina Yatsina4b1aea02015-12-03 12:17:03 +00001815 PtrInOperand = true;
David Majnemeraa34d792013-08-27 21:56:17 +00001816 }
Nirav Dave8601ac12016-08-02 17:56:03 +00001817
David Majnemeraa34d792013-08-27 21:56:17 +00001818 Start = Tok.getLoc();
1819
Elena Demikhovsky18fd4962015-03-02 15:00:34 +00001820 // rounding mode token
Akira Hatanakabd9fc282015-11-14 05:20:05 +00001821 if (getSTI().getFeatureBits()[X86::FeatureAVX512] &&
Elena Demikhovsky18fd4962015-03-02 15:00:34 +00001822 getLexer().is(AsmToken::LCurly))
1823 return ParseRoundingModeOp(Start, End);
1824
Chad Rosierd0ed73a2013-01-17 19:21:48 +00001825 // Register.
Devang Patelce6a2ca2012-01-20 22:32:05 +00001826 unsigned RegNo = 0;
Nirav Dave8601ac12016-08-02 17:56:03 +00001827 if (getLexer().is(AsmToken::Identifier) &&
1828 !ParseRegister(RegNo, Start, End)) {
Chad Rosier0397edd2012-10-04 23:59:38 +00001829 // If this is a segment register followed by a ':', then this is the start
David Majnemeraa34d792013-08-27 21:56:17 +00001830 // of a segment override, otherwise this is a normal register reference.
Douglas Katzman0411e862016-10-05 15:23:35 +00001831 // In case it is a normal register and there is ptr in the operand this
Marina Yatsina4b1aea02015-12-03 12:17:03 +00001832 // is an error
Douglas Katzman0411e862016-10-05 15:23:35 +00001833 if (RegNo == X86::RIP)
1834 return ErrorOperand(Start, "rip can only be used as a base register");
1835 if (getLexer().isNot(AsmToken::Colon)) {
1836 if (PtrInOperand) {
Marina Yatsina4b1aea02015-12-03 12:17:03 +00001837 return ErrorOperand(Start, "expected memory operand after "
1838 "'ptr', found register operand instead");
1839 }
Jordan Rosee8f1eae2013-01-07 19:00:49 +00001840 return X86Operand::CreateReg(RegNo, Start, End);
Marina Yatsina4b1aea02015-12-03 12:17:03 +00001841 }
David Majnemeraa34d792013-08-27 21:56:17 +00001842 return ParseIntelSegmentOverride(/*SegReg=*/RegNo, Start, Size);
Devang Patel46831de2012-01-12 01:36:43 +00001843 }
1844
Nirav Dave8601ac12016-08-02 17:56:03 +00001845 // Immediates and Memory
1846
1847 // Parse [ BaseReg + Scale*IndexReg + Disp ].
1848 if (getLexer().is(AsmToken::LBrac))
1849 return ParseIntelBracExpression(/*SegReg=*/0, Start, /*ImmDisp=*/0, false,
1850 Size);
1851
Kirill Bobyrev6afbaf02017-01-18 16:34:25 +00001852 AsmToken StartTok = Tok;
Nirav Dave8601ac12016-08-02 17:56:03 +00001853 IntelExprStateMachine SM(/*Imm=*/0, /*StopOnLBrac=*/true,
1854 /*AddImmPrefix=*/false);
1855 if (ParseIntelExpression(SM, End))
1856 return nullptr;
1857
1858 bool isSymbol = SM.getSym() && SM.getSym()->getKind() != MCExpr::Constant;
1859 int64_t Imm = SM.getImm();
1860 if (SM.getSym() && SM.getSym()->getKind() == MCExpr::Constant)
1861 SM.getSym()->evaluateAsAbsolute(Imm);
1862
1863 if (StartTok.isNot(AsmToken::Identifier) &&
1864 StartTok.isNot(AsmToken::String) && isParsingInlineAsm()) {
1865 unsigned Len = Tok.getLoc().getPointer() - Start.getPointer();
1866 if (StartTok.getString().size() == Len)
1867 // Just add a prefix if this wasn't a complex immediate expression.
1868 InstInfo->AsmRewrites->emplace_back(AOK_ImmPrefix, Start);
1869 else
1870 // Otherwise, rewrite the complex expression as a single immediate.
1871 InstInfo->AsmRewrites->emplace_back(AOK_Imm, Start, Len, Imm);
1872 }
1873
1874 if (getLexer().isNot(AsmToken::LBrac)) {
1875 // If a directional label (ie. 1f or 2b) was parsed above from
1876 // ParseIntelExpression() then SM.getSym() was set to a pointer to
1877 // to the MCExpr with the directional local symbol and this is a
1878 // memory operand not an immediate operand.
1879 if (isSymbol) {
1880 if (isParsingInlineAsm())
1881 return CreateMemForInlineAsm(/*SegReg=*/0, SM.getSym(), /*BaseReg=*/0,
1882 /*IndexReg=*/0,
1883 /*Scale=*/1, Start, End, Size,
1884 SM.getSymName(), SM.getIdentifierInfo());
1885 return X86Operand::CreateMem(getPointerWidth(), SM.getSym(), Start, End,
1886 Size);
1887 }
1888
1889 const MCExpr *ImmExpr = MCConstantExpr::create(Imm, getContext());
1890 return X86Operand::CreateImm(ImmExpr, Start, End);
1891 }
1892
1893 // Only positive immediates are valid.
1894 if (Imm < 0)
1895 return ErrorOperand(Start, "expected a positive immediate displacement "
1896 "before bracketed expr.");
1897
1898 return ParseIntelBracExpression(/*SegReg=*/0, Start, Imm, isSymbol, Size);
Devang Patel46831de2012-01-12 01:36:43 +00001899}
1900
David Blaikie960ea3f2014-06-08 16:18:35 +00001901std::unique_ptr<X86Operand> X86AsmParser::ParseATTOperand() {
Rafael Espindola961d4692014-11-11 05:18:41 +00001902 MCAsmParser &Parser = getParser();
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +00001903 switch (getLexer().getKind()) {
1904 default:
Chris Lattnerb9270732010-04-17 18:56:34 +00001905 // Parse a memory operand with no segment register.
1906 return ParseMemOperand(0, Parser.getTok().getLoc());
Chris Lattnercc2ad082010-01-15 18:27:19 +00001907 case AsmToken::Percent: {
Chris Lattnerb9270732010-04-17 18:56:34 +00001908 // Read the register.
Chris Lattnercc2ad082010-01-15 18:27:19 +00001909 unsigned RegNo;
Chris Lattner0c2538f2010-01-15 18:51:29 +00001910 SMLoc Start, End;
Craig Topper062a2ba2014-04-25 05:30:21 +00001911 if (ParseRegister(RegNo, Start, End)) return nullptr;
Bruno Cardoso Lopes306a1f92010-07-24 00:06:39 +00001912 if (RegNo == X86::EIZ || RegNo == X86::RIZ) {
Benjamin Kramer1930b002011-10-16 12:10:27 +00001913 Error(Start, "%eiz and %riz can only be used as index registers",
1914 SMRange(Start, End));
Craig Topper062a2ba2014-04-25 05:30:21 +00001915 return nullptr;
Bruno Cardoso Lopes306a1f92010-07-24 00:06:39 +00001916 }
Douglas Katzman0411e862016-10-05 15:23:35 +00001917 if (RegNo == X86::RIP) {
1918 Error(Start, "%rip can only be used as a base register",
1919 SMRange(Start, End));
1920 return nullptr;
1921 }
Bruno Cardoso Lopesd65cd1d2010-07-23 22:15:26 +00001922
Chris Lattnerb9270732010-04-17 18:56:34 +00001923 // If this is a segment register followed by a ':', then this is the start
1924 // of a memory reference, otherwise this is a normal register reference.
1925 if (getLexer().isNot(AsmToken::Colon))
1926 return X86Operand::CreateReg(RegNo, Start, End);
Bruno Cardoso Lopesd65cd1d2010-07-23 22:15:26 +00001927
Reid Kleckner0c5da972014-07-31 23:03:22 +00001928 if (!X86MCRegisterClasses[X86::SEGMENT_REGRegClassID].contains(RegNo))
1929 return ErrorOperand(Start, "invalid segment register");
1930
Chris Lattnerb9270732010-04-17 18:56:34 +00001931 getParser().Lex(); // Eat the colon.
1932 return ParseMemOperand(RegNo, Start);
Chris Lattnercc2ad082010-01-15 18:27:19 +00001933 }
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +00001934 case AsmToken::Dollar: {
1935 // $42 -> immediate.
Sean Callanan936b0d32010-01-19 21:44:56 +00001936 SMLoc Start = Parser.getTok().getLoc(), End;
Sean Callanana83fd7d2010-01-19 20:27:46 +00001937 Parser.Lex();
Daniel Dunbar73da11e2009-08-31 08:08:38 +00001938 const MCExpr *Val;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00001939 if (getParser().parseExpression(Val, End))
Craig Topper062a2ba2014-04-25 05:30:21 +00001940 return nullptr;
Chris Lattner528d00b2010-01-15 19:28:38 +00001941 return X86Operand::CreateImm(Val, Start, End);
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +00001942 }
Elena Demikhovsky18fd4962015-03-02 15:00:34 +00001943 case AsmToken::LCurly:{
1944 SMLoc Start = Parser.getTok().getLoc(), End;
Akira Hatanakabd9fc282015-11-14 05:20:05 +00001945 if (getSTI().getFeatureBits()[X86::FeatureAVX512])
Elena Demikhovsky18fd4962015-03-02 15:00:34 +00001946 return ParseRoundingModeOp(Start, End);
Nirav Dave8601ac12016-08-02 17:56:03 +00001947 return ErrorOperand(Start, "Unexpected '{' in expression");
Elena Demikhovsky18fd4962015-03-02 15:00:34 +00001948 }
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +00001949 }
Daniel Dunbar2b11c7d2009-07-20 20:01:54 +00001950}
1951
Michael Zuckerman1bee6342016-10-18 13:52:39 +00001952// true on failure, false otherwise
1953// If no {z} mark was found - Parser doesn't advance
1954bool X86AsmParser::ParseZ(std::unique_ptr<X86Operand> &Z,
1955 const SMLoc &StartLoc) {
1956 MCAsmParser &Parser = getParser();
1957 // Assuming we are just pass the '{' mark, quering the next token
Coby Tayree179ff0e2016-11-20 09:31:11 +00001958 // Searched for {z}, but none was found. Return false, as no parsing error was
Michael Zuckerman1bee6342016-10-18 13:52:39 +00001959 // encountered
1960 if (!(getLexer().is(AsmToken::Identifier) &&
1961 (getLexer().getTok().getIdentifier() == "z")))
1962 return false;
1963 Parser.Lex(); // Eat z
1964 // Query and eat the '}' mark
1965 if (!getLexer().is(AsmToken::RCurly))
1966 return Error(getLexer().getLoc(), "Expected } at this point");
1967 Parser.Lex(); // Eat '}'
1968 // Assign Z with the {z} mark opernad
Benjamin Kramerfc54e352016-11-24 15:17:39 +00001969 Z = X86Operand::CreateToken("{z}", StartLoc);
Michael Zuckerman1bee6342016-10-18 13:52:39 +00001970 return false;
1971}
1972
1973// true on failure, false otherwise
David Blaikie960ea3f2014-06-08 16:18:35 +00001974bool X86AsmParser::HandleAVX512Operand(OperandVector &Operands,
1975 const MCParsedAsmOperand &Op) {
Rafael Espindola961d4692014-11-11 05:18:41 +00001976 MCAsmParser &Parser = getParser();
Akira Hatanakabd9fc282015-11-14 05:20:05 +00001977 if(getSTI().getFeatureBits()[X86::FeatureAVX512]) {
Elena Demikhovskyc9657012014-02-20 06:34:39 +00001978 if (getLexer().is(AsmToken::LCurly)) {
1979 // Eat "{" and mark the current place.
1980 const SMLoc consumedToken = consumeToken();
1981 // Distinguish {1to<NUM>} from {%k<NUM>}.
1982 if(getLexer().is(AsmToken::Integer)) {
1983 // Parse memory broadcasting ({1to<NUM>}).
1984 if (getLexer().getTok().getIntVal() != 1)
Michael Zuckerman1bee6342016-10-18 13:52:39 +00001985 return TokError("Expected 1to<NUM> at this point");
Elena Demikhovskyc9657012014-02-20 06:34:39 +00001986 Parser.Lex(); // Eat "1" of 1to8
1987 if (!getLexer().is(AsmToken::Identifier) ||
1988 !getLexer().getTok().getIdentifier().startswith("to"))
Michael Zuckerman1bee6342016-10-18 13:52:39 +00001989 return TokError("Expected 1to<NUM> at this point");
Elena Demikhovskyc9657012014-02-20 06:34:39 +00001990 // Recognize only reasonable suffixes.
1991 const char *BroadcastPrimitive =
1992 StringSwitch<const char*>(getLexer().getTok().getIdentifier())
Robert Khasanovbfa01312014-07-21 14:54:21 +00001993 .Case("to2", "{1to2}")
1994 .Case("to4", "{1to4}")
Elena Demikhovskyc9657012014-02-20 06:34:39 +00001995 .Case("to8", "{1to8}")
1996 .Case("to16", "{1to16}")
Craig Topper062a2ba2014-04-25 05:30:21 +00001997 .Default(nullptr);
Elena Demikhovskyc9657012014-02-20 06:34:39 +00001998 if (!BroadcastPrimitive)
Michael Zuckerman1bee6342016-10-18 13:52:39 +00001999 return TokError("Invalid memory broadcast primitive.");
Elena Demikhovskyc9657012014-02-20 06:34:39 +00002000 Parser.Lex(); // Eat "toN" of 1toN
2001 if (!getLexer().is(AsmToken::RCurly))
Michael Zuckerman1bee6342016-10-18 13:52:39 +00002002 return TokError("Expected } at this point");
Elena Demikhovskyc9657012014-02-20 06:34:39 +00002003 Parser.Lex(); // Eat "}"
2004 Operands.push_back(X86Operand::CreateToken(BroadcastPrimitive,
2005 consumedToken));
2006 // No AVX512 specific primitives can pass
2007 // after memory broadcasting, so return.
Michael Zuckerman1bee6342016-10-18 13:52:39 +00002008 return false;
Elena Demikhovskyc9657012014-02-20 06:34:39 +00002009 } else {
Michael Zuckerman1bee6342016-10-18 13:52:39 +00002010 // Parse either {k}{z}, {z}{k}, {k} or {z}
2011 // last one have no meaning, but GCC accepts it
2012 // Currently, we're just pass a '{' mark
2013 std::unique_ptr<X86Operand> Z;
2014 if (ParseZ(Z, consumedToken))
2015 return true;
2016 // Reaching here means that parsing of the allegadly '{z}' mark yielded
2017 // no errors.
2018 // Query for the need of further parsing for a {%k<NUM>} mark
2019 if (!Z || getLexer().is(AsmToken::LCurly)) {
2020 const SMLoc StartLoc = Z ? consumeToken() : consumedToken;
2021 // Parse an op-mask register mark ({%k<NUM>}), which is now to be
2022 // expected
2023 if (std::unique_ptr<X86Operand> Op = ParseOperand()) {
Elena Demikhovskyc9657012014-02-20 06:34:39 +00002024 if (!getLexer().is(AsmToken::RCurly))
Michael Zuckerman1bee6342016-10-18 13:52:39 +00002025 return Error(getLexer().getLoc(), "Expected } at this point");
2026 Operands.push_back(X86Operand::CreateToken("{", StartLoc));
2027 Operands.push_back(std::move(Op));
2028 Operands.push_back(X86Operand::CreateToken("}", consumeToken()));
2029 } else
2030 return Error(getLexer().getLoc(),
2031 "Expected an op-mask register at this point");
2032 // {%k<NUM>} mark is found, inquire for {z}
2033 if (getLexer().is(AsmToken::LCurly) && !Z) {
2034 // Have we've found a parsing error, or found no (expected) {z} mark
2035 // - report an error
2036 if (ParseZ(Z, consumeToken()) || !Z)
2037 return true;
2038
Elena Demikhovskyc9657012014-02-20 06:34:39 +00002039 }
Michael Zuckerman1bee6342016-10-18 13:52:39 +00002040 // '{z}' on its own is meaningless, hence should be ignored.
2041 // on the contrary - have it been accompanied by a K register,
2042 // allow it.
2043 if (Z)
2044 Operands.push_back(std::move(Z));
Elena Demikhovskyc9657012014-02-20 06:34:39 +00002045 }
2046 }
2047 }
2048 }
Michael Zuckerman1bee6342016-10-18 13:52:39 +00002049 return false;
Elena Demikhovskyc9657012014-02-20 06:34:39 +00002050}
2051
Chris Lattnerb9270732010-04-17 18:56:34 +00002052/// ParseMemOperand: segment: disp(basereg, indexreg, scale). The '%ds:' prefix
2053/// has already been parsed if present.
David Blaikie960ea3f2014-06-08 16:18:35 +00002054std::unique_ptr<X86Operand> X86AsmParser::ParseMemOperand(unsigned SegReg,
2055 SMLoc MemStart) {
Bruno Cardoso Lopesd65cd1d2010-07-23 22:15:26 +00002056
Rafael Espindola961d4692014-11-11 05:18:41 +00002057 MCAsmParser &Parser = getParser();
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +00002058 // We have to disambiguate a parenthesized expression "(4+5)" from the start
2059 // of a memory operand with a missing displacement "(%ebx)" or "(,%eax)". The
Chris Lattner807a3bc2010-01-24 01:07:33 +00002060 // only way to do this without lookahead is to eat the '(' and see what is
2061 // after it.
Jim Grosbach13760bd2015-05-30 01:25:56 +00002062 const MCExpr *Disp = MCConstantExpr::create(0, getParser().getContext());
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +00002063 if (getLexer().isNot(AsmToken::LParen)) {
Chris Lattnere17df0b2010-01-15 19:39:23 +00002064 SMLoc ExprEnd;
Craig Topper062a2ba2014-04-25 05:30:21 +00002065 if (getParser().parseExpression(Disp, ExprEnd)) return nullptr;
Bruno Cardoso Lopesd65cd1d2010-07-23 22:15:26 +00002066
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +00002067 // After parsing the base expression we could either have a parenthesized
2068 // memory address or not. If not, return now. If so, eat the (.
2069 if (getLexer().isNot(AsmToken::LParen)) {
Daniel Dunbara4fc8d92009-07-31 22:22:54 +00002070 // Unless we have a segment register, treat this as an immediate.
Chris Lattnera2bbb7c2010-01-15 18:44:13 +00002071 if (SegReg == 0)
Craig Topper055845f2015-01-02 07:02:25 +00002072 return X86Operand::CreateMem(getPointerWidth(), Disp, MemStart, ExprEnd);
2073 return X86Operand::CreateMem(getPointerWidth(), SegReg, Disp, 0, 0, 1,
2074 MemStart, ExprEnd);
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +00002075 }
Bruno Cardoso Lopesd65cd1d2010-07-23 22:15:26 +00002076
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +00002077 // Eat the '('.
Sean Callanana83fd7d2010-01-19 20:27:46 +00002078 Parser.Lex();
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +00002079 } else {
2080 // Okay, we have a '('. We don't know if this is an expression or not, but
2081 // so we have to eat the ( to see beyond it.
Sean Callanan936b0d32010-01-19 21:44:56 +00002082 SMLoc LParenLoc = Parser.getTok().getLoc();
Sean Callanana83fd7d2010-01-19 20:27:46 +00002083 Parser.Lex(); // Eat the '('.
Bruno Cardoso Lopesd65cd1d2010-07-23 22:15:26 +00002084
Kevin Enderby7d912182009-09-03 17:15:07 +00002085 if (getLexer().is(AsmToken::Percent) || getLexer().is(AsmToken::Comma)) {
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +00002086 // Nothing to do here, fall into the code below with the '(' part of the
2087 // memory operand consumed.
2088 } else {
Chris Lattner528d00b2010-01-15 19:28:38 +00002089 SMLoc ExprEnd;
Bruno Cardoso Lopesd65cd1d2010-07-23 22:15:26 +00002090
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +00002091 // It must be an parenthesized expression, parse it now.
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002092 if (getParser().parseParenExpression(Disp, ExprEnd))
Craig Topper062a2ba2014-04-25 05:30:21 +00002093 return nullptr;
Bruno Cardoso Lopesd65cd1d2010-07-23 22:15:26 +00002094
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +00002095 // After parsing the base expression we could either have a parenthesized
2096 // memory address or not. If not, return now. If so, eat the (.
2097 if (getLexer().isNot(AsmToken::LParen)) {
Daniel Dunbara4fc8d92009-07-31 22:22:54 +00002098 // Unless we have a segment register, treat this as an immediate.
Chris Lattnera2bbb7c2010-01-15 18:44:13 +00002099 if (SegReg == 0)
Craig Topper055845f2015-01-02 07:02:25 +00002100 return X86Operand::CreateMem(getPointerWidth(), Disp, LParenLoc,
2101 ExprEnd);
2102 return X86Operand::CreateMem(getPointerWidth(), SegReg, Disp, 0, 0, 1,
2103 MemStart, ExprEnd);
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +00002104 }
Bruno Cardoso Lopesd65cd1d2010-07-23 22:15:26 +00002105
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +00002106 // Eat the '('.
Sean Callanana83fd7d2010-01-19 20:27:46 +00002107 Parser.Lex();
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +00002108 }
2109 }
Bruno Cardoso Lopesd65cd1d2010-07-23 22:15:26 +00002110
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +00002111 // If we reached here, then we just ate the ( of the memory operand. Process
2112 // the rest of the memory operand.
Daniel Dunbar3ebf8482009-07-31 20:53:16 +00002113 unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
David Woodhouse6dbda442014-01-08 12:58:28 +00002114 SMLoc IndexLoc, BaseLoc;
Bruno Cardoso Lopesd65cd1d2010-07-23 22:15:26 +00002115
Chris Lattner0c2538f2010-01-15 18:51:29 +00002116 if (getLexer().is(AsmToken::Percent)) {
Benjamin Kramer1930b002011-10-16 12:10:27 +00002117 SMLoc StartLoc, EndLoc;
David Woodhouse6dbda442014-01-08 12:58:28 +00002118 BaseLoc = Parser.getTok().getLoc();
Craig Topper062a2ba2014-04-25 05:30:21 +00002119 if (ParseRegister(BaseReg, StartLoc, EndLoc)) return nullptr;
Bruno Cardoso Lopes306a1f92010-07-24 00:06:39 +00002120 if (BaseReg == X86::EIZ || BaseReg == X86::RIZ) {
Benjamin Kramer1930b002011-10-16 12:10:27 +00002121 Error(StartLoc, "eiz and riz can only be used as index registers",
2122 SMRange(StartLoc, EndLoc));
Craig Topper062a2ba2014-04-25 05:30:21 +00002123 return nullptr;
Bruno Cardoso Lopes306a1f92010-07-24 00:06:39 +00002124 }
Chris Lattner0c2538f2010-01-15 18:51:29 +00002125 }
Bruno Cardoso Lopesd65cd1d2010-07-23 22:15:26 +00002126
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +00002127 if (getLexer().is(AsmToken::Comma)) {
Sean Callanana83fd7d2010-01-19 20:27:46 +00002128 Parser.Lex(); // Eat the comma.
Kevin Enderbyfb3110b2012-03-12 21:32:09 +00002129 IndexLoc = Parser.getTok().getLoc();
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +00002130
2131 // Following the comma we should have either an index register, or a scale
2132 // value. We don't support the later form, but we want to parse it
2133 // correctly.
2134 //
2135 // Not that even though it would be completely consistent to support syntax
Bruno Cardoso Lopes306a1f92010-07-24 00:06:39 +00002136 // like "1(%eax,,1)", the assembler doesn't. Use "eiz" or "riz" for this.
Kevin Enderby7d912182009-09-03 17:15:07 +00002137 if (getLexer().is(AsmToken::Percent)) {
Chris Lattner0c2538f2010-01-15 18:51:29 +00002138 SMLoc L;
Douglas Katzman0411e862016-10-05 15:23:35 +00002139 if (ParseRegister(IndexReg, L, L))
2140 return nullptr;
2141 if (BaseReg == X86::RIP) {
2142 Error(IndexLoc, "%rip as base register can not have an index register");
2143 return nullptr;
2144 }
2145 if (IndexReg == X86::RIP) {
2146 Error(IndexLoc, "%rip is not allowed as an index register");
2147 return nullptr;
2148 }
Bruno Cardoso Lopesd65cd1d2010-07-23 22:15:26 +00002149
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +00002150 if (getLexer().isNot(AsmToken::RParen)) {
2151 // Parse the scale amount:
2152 // ::= ',' [scale-expression]
Chris Lattnera2bbb7c2010-01-15 18:44:13 +00002153 if (getLexer().isNot(AsmToken::Comma)) {
Sean Callanan936b0d32010-01-19 21:44:56 +00002154 Error(Parser.getTok().getLoc(),
Chris Lattnera2bbb7c2010-01-15 18:44:13 +00002155 "expected comma in scale expression");
Craig Topper062a2ba2014-04-25 05:30:21 +00002156 return nullptr;
Chris Lattnera2bbb7c2010-01-15 18:44:13 +00002157 }
Sean Callanana83fd7d2010-01-19 20:27:46 +00002158 Parser.Lex(); // Eat the comma.
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +00002159
2160 if (getLexer().isNot(AsmToken::RParen)) {
Sean Callanan936b0d32010-01-19 21:44:56 +00002161 SMLoc Loc = Parser.getTok().getLoc();
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +00002162
2163 int64_t ScaleVal;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002164 if (getParser().parseAbsoluteExpression(ScaleVal)){
Kevin Enderbydeed5aa2012-03-09 22:24:10 +00002165 Error(Loc, "expected scale expression");
Craig Topper062a2ba2014-04-25 05:30:21 +00002166 return nullptr;
Craig Topper6bf3ed42012-07-18 04:59:16 +00002167 }
Bruno Cardoso Lopesd65cd1d2010-07-23 22:15:26 +00002168
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +00002169 // Validate the scale amount.
NAKAMURA Takumi0a7d0ad2015-09-22 11:15:07 +00002170 if (X86MCRegisterClasses[X86::GR16RegClassID].contains(BaseReg) &&
David Woodhouse6dbda442014-01-08 12:58:28 +00002171 ScaleVal != 1) {
2172 Error(Loc, "scale factor in 16-bit address must be 1");
Craig Topper062a2ba2014-04-25 05:30:21 +00002173 return nullptr;
NAKAMURA Takumi0a7d0ad2015-09-22 11:15:07 +00002174 }
2175 if (ScaleVal != 1 && ScaleVal != 2 && ScaleVal != 4 &&
2176 ScaleVal != 8) {
Chris Lattnera2bbb7c2010-01-15 18:44:13 +00002177 Error(Loc, "scale factor in address must be 1, 2, 4 or 8");
Craig Topper062a2ba2014-04-25 05:30:21 +00002178 return nullptr;
Chris Lattnera2bbb7c2010-01-15 18:44:13 +00002179 }
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +00002180 Scale = (unsigned)ScaleVal;
2181 }
2182 }
2183 } else if (getLexer().isNot(AsmToken::RParen)) {
Daniel Dunbar94b84a12010-08-24 19:13:38 +00002184 // A scale amount without an index is ignored.
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +00002185 // index.
Sean Callanan936b0d32010-01-19 21:44:56 +00002186 SMLoc Loc = Parser.getTok().getLoc();
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +00002187
2188 int64_t Value;
Jim Grosbachd2037eb2013-02-20 22:21:35 +00002189 if (getParser().parseAbsoluteExpression(Value))
Craig Topper062a2ba2014-04-25 05:30:21 +00002190 return nullptr;
Bruno Cardoso Lopesd65cd1d2010-07-23 22:15:26 +00002191
Daniel Dunbar94b84a12010-08-24 19:13:38 +00002192 if (Value != 1)
2193 Warning(Loc, "scale factor without index register is ignored");
2194 Scale = 1;
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +00002195 }
2196 }
Bruno Cardoso Lopesd65cd1d2010-07-23 22:15:26 +00002197
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +00002198 // Ok, we've eaten the memory operand, verify we have a ')' and eat it too.
Chris Lattnera2bbb7c2010-01-15 18:44:13 +00002199 if (getLexer().isNot(AsmToken::RParen)) {
Sean Callanan936b0d32010-01-19 21:44:56 +00002200 Error(Parser.getTok().getLoc(), "unexpected token in memory operand");
Craig Topper062a2ba2014-04-25 05:30:21 +00002201 return nullptr;
Chris Lattnera2bbb7c2010-01-15 18:44:13 +00002202 }
Jordan Rosee8f1eae2013-01-07 19:00:49 +00002203 SMLoc MemEnd = Parser.getTok().getEndLoc();
Sean Callanana83fd7d2010-01-19 20:27:46 +00002204 Parser.Lex(); // Eat the ')'.
Bruno Cardoso Lopesd65cd1d2010-07-23 22:15:26 +00002205
David Woodhouse6dbda442014-01-08 12:58:28 +00002206 // Check for use of invalid 16-bit registers. Only BX/BP/SI/DI are allowed,
2207 // and then only in non-64-bit modes. Except for DX, which is a special case
2208 // because an unofficial form of in/out instructions uses it.
2209 if (X86MCRegisterClasses[X86::GR16RegClassID].contains(BaseReg) &&
2210 (is64BitMode() || (BaseReg != X86::BX && BaseReg != X86::BP &&
2211 BaseReg != X86::SI && BaseReg != X86::DI)) &&
2212 BaseReg != X86::DX) {
2213 Error(BaseLoc, "invalid 16-bit base register");
Craig Topper062a2ba2014-04-25 05:30:21 +00002214 return nullptr;
David Woodhouse6dbda442014-01-08 12:58:28 +00002215 }
2216 if (BaseReg == 0 &&
2217 X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg)) {
2218 Error(IndexLoc, "16-bit memory operand may not include only index register");
Craig Topper062a2ba2014-04-25 05:30:21 +00002219 return nullptr;
David Woodhouse6dbda442014-01-08 12:58:28 +00002220 }
Kevin Enderbybc570f22014-01-23 22:34:42 +00002221
2222 StringRef ErrMsg;
2223 if (CheckBaseRegAndIndexReg(BaseReg, IndexReg, ErrMsg)) {
2224 Error(BaseLoc, ErrMsg);
Craig Topper062a2ba2014-04-25 05:30:21 +00002225 return nullptr;
Kevin Enderbyfb3110b2012-03-12 21:32:09 +00002226 }
2227
Reid Klecknerb7e2f602014-07-31 23:26:35 +00002228 if (SegReg || BaseReg || IndexReg)
Craig Topper055845f2015-01-02 07:02:25 +00002229 return X86Operand::CreateMem(getPointerWidth(), SegReg, Disp, BaseReg,
2230 IndexReg, Scale, MemStart, MemEnd);
2231 return X86Operand::CreateMem(getPointerWidth(), Disp, MemStart, MemEnd);
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +00002232}
2233
David Blaikie960ea3f2014-06-08 16:18:35 +00002234bool X86AsmParser::ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
2235 SMLoc NameLoc, OperandVector &Operands) {
Rafael Espindola961d4692014-11-11 05:18:41 +00002236 MCAsmParser &Parser = getParser();
Chad Rosierf0e87202012-10-25 20:41:34 +00002237 InstInfo = &Info;
Chris Lattner2cb092d2010-10-30 19:23:13 +00002238 StringRef PatchedName = Name;
Daniel Dunbar0e767d72010-05-25 19:49:32 +00002239
Michael Zuckerman174d2e72016-10-14 08:09:40 +00002240 if (Name == "jmp" && isParsingIntelSyntax() && isParsingInlineAsm()) {
2241 StringRef NextTok = Parser.getTok().getString();
2242 if (NextTok == "short") {
2243 SMLoc NameEndLoc =
2244 NameLoc.getFromPointer(NameLoc.getPointer() + Name.size());
2245 // Eat the short keyword
2246 Parser.Lex();
2247 // MS ignores the short keyword, it determines the jmp type based
2248 // on the distance of the label
2249 InstInfo->AsmRewrites->emplace_back(AOK_Skip, NameEndLoc,
2250 NextTok.size() + 1);
2251 }
2252 }
2253
Chris Lattner7e8a99b2010-11-28 20:23:50 +00002254 // FIXME: Hack to recognize setneb as setne.
2255 if (PatchedName.startswith("set") && PatchedName.endswith("b") &&
2256 PatchedName != "setb" && PatchedName != "setnb")
2257 PatchedName = PatchedName.substr(0, Name.size()-1);
Chad Rosier51afe632012-06-27 22:34:28 +00002258
Daniel Dunbar0e767d72010-05-25 19:49:32 +00002259 // FIXME: Hack to recognize cmp<comparison code>{ss,sd,ps,pd}.
Bruno Cardoso Lopes3183dd52010-06-23 21:10:57 +00002260 if ((PatchedName.startswith("cmp") || PatchedName.startswith("vcmp")) &&
Daniel Dunbar0e767d72010-05-25 19:49:32 +00002261 (PatchedName.endswith("ss") || PatchedName.endswith("sd") ||
2262 PatchedName.endswith("ps") || PatchedName.endswith("pd"))) {
Craig Toppera0a603e2012-03-29 07:11:23 +00002263 bool IsVCMP = PatchedName[0] == 'v';
Craig Topper78c424d2015-02-15 07:13:48 +00002264 unsigned CCIdx = IsVCMP ? 4 : 3;
2265 unsigned ComparisonCode = StringSwitch<unsigned>(
2266 PatchedName.slice(CCIdx, PatchedName.size() - 2))
Craig Toppera0a603e2012-03-29 07:11:23 +00002267 .Case("eq", 0x00)
Michael Zuckerman72b72232016-01-25 08:43:26 +00002268 .Case("eq_oq", 0x00)
Craig Toppera0a603e2012-03-29 07:11:23 +00002269 .Case("lt", 0x01)
Michael Zuckerman72b72232016-01-25 08:43:26 +00002270 .Case("lt_os", 0x01)
Craig Toppera0a603e2012-03-29 07:11:23 +00002271 .Case("le", 0x02)
Michael Zuckerman72b72232016-01-25 08:43:26 +00002272 .Case("le_os", 0x02)
Craig Toppera0a603e2012-03-29 07:11:23 +00002273 .Case("unord", 0x03)
Michael Zuckerman72b72232016-01-25 08:43:26 +00002274 .Case("unord_q", 0x03)
Craig Toppera0a603e2012-03-29 07:11:23 +00002275 .Case("neq", 0x04)
Michael Zuckerman72b72232016-01-25 08:43:26 +00002276 .Case("neq_uq", 0x04)
Craig Toppera0a603e2012-03-29 07:11:23 +00002277 .Case("nlt", 0x05)
Michael Zuckerman72b72232016-01-25 08:43:26 +00002278 .Case("nlt_us", 0x05)
Craig Toppera0a603e2012-03-29 07:11:23 +00002279 .Case("nle", 0x06)
Michael Zuckerman72b72232016-01-25 08:43:26 +00002280 .Case("nle_us", 0x06)
Craig Toppera0a603e2012-03-29 07:11:23 +00002281 .Case("ord", 0x07)
Michael Zuckerman72b72232016-01-25 08:43:26 +00002282 .Case("ord_q", 0x07)
Craig Toppera0a603e2012-03-29 07:11:23 +00002283 /* AVX only from here */
2284 .Case("eq_uq", 0x08)
2285 .Case("nge", 0x09)
Michael Zuckerman72b72232016-01-25 08:43:26 +00002286 .Case("nge_us", 0x09)
Bruno Cardoso Lopes6c614512010-07-07 22:24:03 +00002287 .Case("ngt", 0x0A)
Michael Zuckerman72b72232016-01-25 08:43:26 +00002288 .Case("ngt_us", 0x0A)
Bruno Cardoso Lopes6c614512010-07-07 22:24:03 +00002289 .Case("false", 0x0B)
Michael Zuckerman72b72232016-01-25 08:43:26 +00002290 .Case("false_oq", 0x0B)
Bruno Cardoso Lopes6c614512010-07-07 22:24:03 +00002291 .Case("neq_oq", 0x0C)
2292 .Case("ge", 0x0D)
Michael Zuckerman72b72232016-01-25 08:43:26 +00002293 .Case("ge_os", 0x0D)
Bruno Cardoso Lopes6c614512010-07-07 22:24:03 +00002294 .Case("gt", 0x0E)
Michael Zuckerman72b72232016-01-25 08:43:26 +00002295 .Case("gt_os", 0x0E)
Bruno Cardoso Lopes6c614512010-07-07 22:24:03 +00002296 .Case("true", 0x0F)
Michael Zuckerman72b72232016-01-25 08:43:26 +00002297 .Case("true_uq", 0x0F)
Bruno Cardoso Lopes6c614512010-07-07 22:24:03 +00002298 .Case("eq_os", 0x10)
2299 .Case("lt_oq", 0x11)
2300 .Case("le_oq", 0x12)
2301 .Case("unord_s", 0x13)
2302 .Case("neq_us", 0x14)
2303 .Case("nlt_uq", 0x15)
2304 .Case("nle_uq", 0x16)
2305 .Case("ord_s", 0x17)
2306 .Case("eq_us", 0x18)
2307 .Case("nge_uq", 0x19)
2308 .Case("ngt_uq", 0x1A)
2309 .Case("false_os", 0x1B)
2310 .Case("neq_os", 0x1C)
2311 .Case("ge_oq", 0x1D)
2312 .Case("gt_oq", 0x1E)
2313 .Case("true_us", 0x1F)
Daniel Dunbar0e767d72010-05-25 19:49:32 +00002314 .Default(~0U);
Craig Topper78c424d2015-02-15 07:13:48 +00002315 if (ComparisonCode != ~0U && (IsVCMP || ComparisonCode < 8)) {
Craig Topper43860832015-02-14 21:54:03 +00002316
Craig Topper78c424d2015-02-15 07:13:48 +00002317 Operands.push_back(X86Operand::CreateToken(PatchedName.slice(0, CCIdx),
Craig Topper43860832015-02-14 21:54:03 +00002318 NameLoc));
2319
Jim Grosbach13760bd2015-05-30 01:25:56 +00002320 const MCExpr *ImmOp = MCConstantExpr::create(ComparisonCode,
Craig Topper43860832015-02-14 21:54:03 +00002321 getParser().getContext());
2322 Operands.push_back(X86Operand::CreateImm(ImmOp, NameLoc, NameLoc));
2323
2324 PatchedName = PatchedName.substr(PatchedName.size() - 2);
Daniel Dunbar0e767d72010-05-25 19:49:32 +00002325 }
2326 }
Bruno Cardoso Lopesea0e05a2010-07-23 18:41:12 +00002327
Craig Topper78c424d2015-02-15 07:13:48 +00002328 // FIXME: Hack to recognize vpcmp<comparison code>{ub,uw,ud,uq,b,w,d,q}.
2329 if (PatchedName.startswith("vpcmp") &&
2330 (PatchedName.endswith("b") || PatchedName.endswith("w") ||
2331 PatchedName.endswith("d") || PatchedName.endswith("q"))) {
2332 unsigned CCIdx = PatchedName.drop_back().back() == 'u' ? 2 : 1;
2333 unsigned ComparisonCode = StringSwitch<unsigned>(
2334 PatchedName.slice(5, PatchedName.size() - CCIdx))
2335 .Case("eq", 0x0) // Only allowed on unsigned. Checked below.
2336 .Case("lt", 0x1)
2337 .Case("le", 0x2)
2338 //.Case("false", 0x3) // Not a documented alias.
2339 .Case("neq", 0x4)
2340 .Case("nlt", 0x5)
2341 .Case("nle", 0x6)
2342 //.Case("true", 0x7) // Not a documented alias.
2343 .Default(~0U);
2344 if (ComparisonCode != ~0U && (ComparisonCode != 0 || CCIdx == 2)) {
2345 Operands.push_back(X86Operand::CreateToken("vpcmp", NameLoc));
2346
Jim Grosbach13760bd2015-05-30 01:25:56 +00002347 const MCExpr *ImmOp = MCConstantExpr::create(ComparisonCode,
Craig Topper78c424d2015-02-15 07:13:48 +00002348 getParser().getContext());
2349 Operands.push_back(X86Operand::CreateImm(ImmOp, NameLoc, NameLoc));
2350
2351 PatchedName = PatchedName.substr(PatchedName.size() - CCIdx);
2352 }
2353 }
2354
Craig Topper916708f2015-02-13 07:42:25 +00002355 // FIXME: Hack to recognize vpcom<comparison code>{ub,uw,ud,uq,b,w,d,q}.
2356 if (PatchedName.startswith("vpcom") &&
2357 (PatchedName.endswith("b") || PatchedName.endswith("w") ||
2358 PatchedName.endswith("d") || PatchedName.endswith("q"))) {
Craig Topper78c424d2015-02-15 07:13:48 +00002359 unsigned CCIdx = PatchedName.drop_back().back() == 'u' ? 2 : 1;
2360 unsigned ComparisonCode = StringSwitch<unsigned>(
2361 PatchedName.slice(5, PatchedName.size() - CCIdx))
Craig Topper916708f2015-02-13 07:42:25 +00002362 .Case("lt", 0x0)
2363 .Case("le", 0x1)
2364 .Case("gt", 0x2)
2365 .Case("ge", 0x3)
2366 .Case("eq", 0x4)
2367 .Case("neq", 0x5)
2368 .Case("false", 0x6)
2369 .Case("true", 0x7)
2370 .Default(~0U);
Craig Topper78c424d2015-02-15 07:13:48 +00002371 if (ComparisonCode != ~0U) {
Craig Topper916708f2015-02-13 07:42:25 +00002372 Operands.push_back(X86Operand::CreateToken("vpcom", NameLoc));
2373
Jim Grosbach13760bd2015-05-30 01:25:56 +00002374 const MCExpr *ImmOp = MCConstantExpr::create(ComparisonCode,
Craig Topper916708f2015-02-13 07:42:25 +00002375 getParser().getContext());
2376 Operands.push_back(X86Operand::CreateImm(ImmOp, NameLoc, NameLoc));
2377
Craig Topper78c424d2015-02-15 07:13:48 +00002378 PatchedName = PatchedName.substr(PatchedName.size() - CCIdx);
Craig Topper916708f2015-02-13 07:42:25 +00002379 }
2380 }
2381
Daniel Dunbar3e0c9792010-02-10 21:19:28 +00002382 Operands.push_back(X86Operand::CreateToken(PatchedName, NameLoc));
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +00002383
Chris Lattner086a83a2010-09-08 05:17:37 +00002384 // Determine whether this is an instruction prefix.
2385 bool isPrefix =
Chris Lattner2cb092d2010-10-30 19:23:13 +00002386 Name == "lock" || Name == "rep" ||
2387 Name == "repe" || Name == "repz" ||
Rafael Espindolaf6c05b12010-11-23 11:23:24 +00002388 Name == "repne" || Name == "repnz" ||
Marina Yatsina197db002017-01-18 08:07:51 +00002389 Name == "rex64" || Name == "data16" || Name == "data32";
Michael J. Spencer530ce852010-10-09 11:00:50 +00002390
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00002391 bool CurlyAsEndOfStatement = false;
Chris Lattner086a83a2010-09-08 05:17:37 +00002392 // This does the actual operand parsing. Don't parse any more if we have a
2393 // prefix juxtaposed with an operation like "lock incl 4(%rax)", because we
2394 // just want to parse the "lock" as the first instruction and the "incl" as
2395 // the next one.
2396 if (getLexer().isNot(AsmToken::EndOfStatement) && !isPrefix) {
Daniel Dunbar71527c12009-08-11 05:00:25 +00002397
2398 // Parse '*' modifier.
Alp Tokera5b88a52013-12-02 16:06:06 +00002399 if (getLexer().is(AsmToken::Star))
2400 Operands.push_back(X86Operand::CreateToken("*", consumeToken()));
Daniel Dunbar71527c12009-08-11 05:00:25 +00002401
Elena Demikhovskyc9657012014-02-20 06:34:39 +00002402 // Read the operands.
Kirill Bobyrev6afbaf02017-01-18 16:34:25 +00002403 while(1) {
David Blaikie960ea3f2014-06-08 16:18:35 +00002404 if (std::unique_ptr<X86Operand> Op = ParseOperand()) {
2405 Operands.push_back(std::move(Op));
Michael Zuckerman1bee6342016-10-18 13:52:39 +00002406 if (HandleAVX512Operand(Operands, *Operands.back()))
Elena Demikhovsky89529742013-09-12 08:55:00 +00002407 return true;
Elena Demikhovskyc9657012014-02-20 06:34:39 +00002408 } else {
Elena Demikhovskyc9657012014-02-20 06:34:39 +00002409 return true;
Elena Demikhovsky89529742013-09-12 08:55:00 +00002410 }
Elena Demikhovskyc9657012014-02-20 06:34:39 +00002411 // check for comma and eat it
2412 if (getLexer().is(AsmToken::Comma))
2413 Parser.Lex();
2414 else
2415 break;
2416 }
Elena Demikhovsky89529742013-09-12 08:55:00 +00002417
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00002418 // In MS inline asm curly braces mark the begining/end of a block, therefore
2419 // they should be interepreted as end of statement
2420 CurlyAsEndOfStatement =
2421 isParsingIntelSyntax() && isParsingInlineAsm() &&
2422 (getLexer().is(AsmToken::LCurly) || getLexer().is(AsmToken::RCurly));
2423 if (getLexer().isNot(AsmToken::EndOfStatement) && !CurlyAsEndOfStatement)
Nirav Dave2364748a2016-09-16 18:30:20 +00002424 return TokError("unexpected token in argument list");
Elena Demikhovskyc9657012014-02-20 06:34:39 +00002425 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00002426
Elena Demikhovskyc9657012014-02-20 06:34:39 +00002427 // Consume the EndOfStatement or the prefix separator Slash
Elena Demikhovsky9f09b3e2014-02-20 07:00:10 +00002428 if (getLexer().is(AsmToken::EndOfStatement) ||
2429 (isPrefix && getLexer().is(AsmToken::Slash)))
Elena Demikhovskyc9657012014-02-20 06:34:39 +00002430 Parser.Lex();
Marina Yatsina5f5de9f2016-03-07 18:11:16 +00002431 else if (CurlyAsEndOfStatement)
2432 // Add an actual EndOfStatement before the curly brace
2433 Info.AsmRewrites->emplace_back(AOK_EndOfStatement,
2434 getLexer().getTok().getLoc(), 0);
Daniel Dunbare1fdb0e2009-07-28 22:40:46 +00002435
Michael Zuckermanfd3fe9e2015-11-12 16:58:51 +00002436 // This is for gas compatibility and cannot be done in td.
2437 // Adding "p" for some floating point with no argument.
2438 // For example: fsub --> fsubp
2439 bool IsFp =
2440 Name == "fsub" || Name == "fdiv" || Name == "fsubr" || Name == "fdivr";
2441 if (IsFp && Operands.size() == 1) {
2442 const char *Repl = StringSwitch<const char *>(Name)
2443 .Case("fsub", "fsubp")
2444 .Case("fdiv", "fdivp")
2445 .Case("fsubr", "fsubrp")
2446 .Case("fdivr", "fdivrp");
2447 static_cast<X86Operand &>(*Operands[0]).setTokenValue(Repl);
2448 }
2449
Nirav Davef45fd2b2016-08-08 18:01:04 +00002450 // Moving a 32 or 16 bit value into a segment register has the same
2451 // behavior. Modify such instructions to always take shorter form.
2452 if ((Name == "mov" || Name == "movw" || Name == "movl") &&
2453 (Operands.size() == 3)) {
2454 X86Operand &Op1 = (X86Operand &)*Operands[1];
2455 X86Operand &Op2 = (X86Operand &)*Operands[2];
2456 SMLoc Loc = Op1.getEndLoc();
2457 if (Op1.isReg() && Op2.isReg() &&
2458 X86MCRegisterClasses[X86::SEGMENT_REGRegClassID].contains(
2459 Op2.getReg()) &&
2460 (X86MCRegisterClasses[X86::GR16RegClassID].contains(Op1.getReg()) ||
2461 X86MCRegisterClasses[X86::GR32RegClassID].contains(Op1.getReg()))) {
2462 // Change instruction name to match new instruction.
2463 if (Name != "mov" && Name[3] == (is16BitMode() ? 'l' : 'w')) {
2464 Name = is16BitMode() ? "movw" : "movl";
2465 Operands[0] = X86Operand::CreateToken(Name, NameLoc);
2466 }
2467 // Select the correct equivalent 16-/32-bit source register.
2468 unsigned Reg =
2469 getX86SubSuperRegisterOrZero(Op1.getReg(), is16BitMode() ? 16 : 32);
2470 Operands[1] = X86Operand::CreateReg(Reg, Loc, Loc);
2471 }
2472 }
2473
Nirav Dave8e103802016-06-29 19:54:27 +00002474 // This is a terrible hack to handle "out[s]?[bwl]? %al, (%dx)" ->
Chris Lattnerb6f8e822010-11-06 19:25:43 +00002475 // "outb %al, %dx". Out doesn't take a memory form, but this is a widely
2476 // documented form in various unofficial manuals, so a lot of code uses it.
Nirav Dave8e103802016-06-29 19:54:27 +00002477 if ((Name == "outb" || Name == "outsb" || Name == "outw" || Name == "outsw" ||
2478 Name == "outl" || Name == "outsl" || Name == "out" || Name == "outs") &&
Chris Lattnerb6f8e822010-11-06 19:25:43 +00002479 Operands.size() == 3) {
David Blaikie960ea3f2014-06-08 16:18:35 +00002480 X86Operand &Op = (X86Operand &)*Operands.back();
Chris Lattnerb6f8e822010-11-06 19:25:43 +00002481 if (Op.isMem() && Op.Mem.SegReg == 0 &&
2482 isa<MCConstantExpr>(Op.Mem.Disp) &&
2483 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
2484 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
2485 SMLoc Loc = Op.getEndLoc();
2486 Operands.back() = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
Chris Lattnerb6f8e822010-11-06 19:25:43 +00002487 }
2488 }
Nirav Dave8e103802016-06-29 19:54:27 +00002489 // Same hack for "in[s]?[bwl]? (%dx), %al" -> "inb %dx, %al".
2490 if ((Name == "inb" || Name == "insb" || Name == "inw" || Name == "insw" ||
2491 Name == "inl" || Name == "insl" || Name == "in" || Name == "ins") &&
Joerg Sonnenbergerb7e635d2011-02-22 20:40:09 +00002492 Operands.size() == 3) {
David Blaikie960ea3f2014-06-08 16:18:35 +00002493 X86Operand &Op = (X86Operand &)*Operands[1];
Joerg Sonnenbergerb7e635d2011-02-22 20:40:09 +00002494 if (Op.isMem() && Op.Mem.SegReg == 0 &&
2495 isa<MCConstantExpr>(Op.Mem.Disp) &&
2496 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
2497 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
2498 SMLoc Loc = Op.getEndLoc();
David Blaikie960ea3f2014-06-08 16:18:35 +00002499 Operands[1] = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
Joerg Sonnenbergerb7e635d2011-02-22 20:40:09 +00002500 }
2501 }
David Woodhouse4ce66062014-01-22 15:08:55 +00002502
Marina Yatsinab9f4f622016-01-19 15:37:56 +00002503 SmallVector<std::unique_ptr<MCParsedAsmOperand>, 2> TmpOperands;
2504 bool HadVerifyError = false;
2505
David Woodhouse4ce66062014-01-22 15:08:55 +00002506 // Append default arguments to "ins[bwld]"
Marina Yatsinab9f4f622016-01-19 15:37:56 +00002507 if (Name.startswith("ins") &&
2508 (Operands.size() == 1 || Operands.size() == 3) &&
2509 (Name == "insb" || Name == "insw" || Name == "insl" || Name == "insd" ||
2510 Name == "ins")) {
2511
2512 AddDefaultSrcDestOperands(TmpOperands,
Michael Kupersteinffcc7662015-07-23 10:23:48 +00002513 X86Operand::CreateReg(X86::DX, NameLoc, NameLoc),
2514 DefaultMemDIOperand(NameLoc));
Marina Yatsinab9f4f622016-01-19 15:37:56 +00002515 HadVerifyError = VerifyAndAdjustOperands(Operands, TmpOperands);
Joerg Sonnenberger3fbfcc02011-03-18 11:59:40 +00002516 }
2517
David Woodhousec472b812014-01-22 15:08:49 +00002518 // Append default arguments to "outs[bwld]"
Marina Yatsinab9f4f622016-01-19 15:37:56 +00002519 if (Name.startswith("outs") &&
2520 (Operands.size() == 1 || Operands.size() == 3) &&
David Woodhousec472b812014-01-22 15:08:49 +00002521 (Name == "outsb" || Name == "outsw" || Name == "outsl" ||
Marina Yatsinab9f4f622016-01-19 15:37:56 +00002522 Name == "outsd" || Name == "outs")) {
2523 AddDefaultSrcDestOperands(TmpOperands, DefaultMemSIOperand(NameLoc),
Michael Kupersteinffcc7662015-07-23 10:23:48 +00002524 X86Operand::CreateReg(X86::DX, NameLoc, NameLoc));
Marina Yatsinab9f4f622016-01-19 15:37:56 +00002525 HadVerifyError = VerifyAndAdjustOperands(Operands, TmpOperands);
Joerg Sonnenberger3fbfcc02011-03-18 11:59:40 +00002526 }
2527
David Woodhouse2ef8d9c2014-01-22 15:08:08 +00002528 // Transform "lods[bwlq]" into "lods[bwlq] ($SIREG)" for appropriate
2529 // values of $SIREG according to the mode. It would be nice if this
2530 // could be achieved with InstAlias in the tables.
Marina Yatsinab9f4f622016-01-19 15:37:56 +00002531 if (Name.startswith("lods") &&
2532 (Operands.size() == 1 || Operands.size() == 2) &&
Joerg Sonnenberger3fbfcc02011-03-18 11:59:40 +00002533 (Name == "lods" || Name == "lodsb" || Name == "lodsw" ||
Marina Yatsinab9f4f622016-01-19 15:37:56 +00002534 Name == "lodsl" || Name == "lodsd" || Name == "lodsq")) {
2535 TmpOperands.push_back(DefaultMemSIOperand(NameLoc));
2536 HadVerifyError = VerifyAndAdjustOperands(Operands, TmpOperands);
2537 }
David Woodhouse2ef8d9c2014-01-22 15:08:08 +00002538
David Woodhouseb33c2ef2014-01-22 15:08:21 +00002539 // Transform "stos[bwlq]" into "stos[bwlq] ($DIREG)" for appropriate
2540 // values of $DIREG according to the mode. It would be nice if this
2541 // could be achieved with InstAlias in the tables.
Marina Yatsinab9f4f622016-01-19 15:37:56 +00002542 if (Name.startswith("stos") &&
2543 (Operands.size() == 1 || Operands.size() == 2) &&
Joerg Sonnenberger3fbfcc02011-03-18 11:59:40 +00002544 (Name == "stos" || Name == "stosb" || Name == "stosw" ||
Marina Yatsinab9f4f622016-01-19 15:37:56 +00002545 Name == "stosl" || Name == "stosd" || Name == "stosq")) {
2546 TmpOperands.push_back(DefaultMemDIOperand(NameLoc));
2547 HadVerifyError = VerifyAndAdjustOperands(Operands, TmpOperands);
2548 }
Joerg Sonnenberger3fbfcc02011-03-18 11:59:40 +00002549
David Woodhouse20fe4802014-01-22 15:08:27 +00002550 // Transform "scas[bwlq]" into "scas[bwlq] ($DIREG)" for appropriate
2551 // values of $DIREG according to the mode. It would be nice if this
2552 // could be achieved with InstAlias in the tables.
Marina Yatsinab9f4f622016-01-19 15:37:56 +00002553 if (Name.startswith("scas") &&
2554 (Operands.size() == 1 || Operands.size() == 2) &&
David Woodhouse20fe4802014-01-22 15:08:27 +00002555 (Name == "scas" || Name == "scasb" || Name == "scasw" ||
Marina Yatsinab9f4f622016-01-19 15:37:56 +00002556 Name == "scasl" || Name == "scasd" || Name == "scasq")) {
2557 TmpOperands.push_back(DefaultMemDIOperand(NameLoc));
2558 HadVerifyError = VerifyAndAdjustOperands(Operands, TmpOperands);
2559 }
David Woodhouse20fe4802014-01-22 15:08:27 +00002560
David Woodhouse9bbf7ca2014-01-22 15:08:36 +00002561 // Add default SI and DI operands to "cmps[bwlq]".
2562 if (Name.startswith("cmps") &&
Marina Yatsinab9f4f622016-01-19 15:37:56 +00002563 (Operands.size() == 1 || Operands.size() == 3) &&
David Woodhouse9bbf7ca2014-01-22 15:08:36 +00002564 (Name == "cmps" || Name == "cmpsb" || Name == "cmpsw" ||
2565 Name == "cmpsl" || Name == "cmpsd" || Name == "cmpsq")) {
Marina Yatsinab9f4f622016-01-19 15:37:56 +00002566 AddDefaultSrcDestOperands(TmpOperands, DefaultMemDIOperand(NameLoc),
2567 DefaultMemSIOperand(NameLoc));
2568 HadVerifyError = VerifyAndAdjustOperands(Operands, TmpOperands);
David Woodhouse9bbf7ca2014-01-22 15:08:36 +00002569 }
2570
David Woodhouse6f417de2014-01-22 15:08:42 +00002571 // Add default SI and DI operands to "movs[bwlq]".
Marina Yatsinab9f4f622016-01-19 15:37:56 +00002572 if (((Name.startswith("movs") &&
2573 (Name == "movs" || Name == "movsb" || Name == "movsw" ||
2574 Name == "movsl" || Name == "movsd" || Name == "movsq")) ||
2575 (Name.startswith("smov") &&
2576 (Name == "smov" || Name == "smovb" || Name == "smovw" ||
2577 Name == "smovl" || Name == "smovd" || Name == "smovq"))) &&
2578 (Operands.size() == 1 || Operands.size() == 3)) {
Coby Tayree94ddbb42016-11-21 15:50:56 +00002579 if (Name == "movsd" && Operands.size() == 1 && !isParsingIntelSyntax())
Marina Yatsinab9f4f622016-01-19 15:37:56 +00002580 Operands.back() = X86Operand::CreateToken("movsl", NameLoc);
2581 AddDefaultSrcDestOperands(TmpOperands, DefaultMemSIOperand(NameLoc),
2582 DefaultMemDIOperand(NameLoc));
2583 HadVerifyError = VerifyAndAdjustOperands(Operands, TmpOperands);
2584 }
2585
2586 // Check if we encountered an error for one the string insturctions
2587 if (HadVerifyError) {
2588 return HadVerifyError;
David Woodhouse6f417de2014-01-22 15:08:42 +00002589 }
2590
Chris Lattner4bd21712010-09-15 04:33:27 +00002591 // FIXME: Hack to handle recognize s{hr,ar,hl} $1, <op>. Canonicalize to
Chris Lattner30561ab2010-09-11 16:32:12 +00002592 // "shift <op>".
Daniel Dunbar18fc3442010-03-13 00:47:29 +00002593 if ((Name.startswith("shr") || Name.startswith("sar") ||
Chris Lattner64f91b92010-11-06 21:23:40 +00002594 Name.startswith("shl") || Name.startswith("sal") ||
2595 Name.startswith("rcl") || Name.startswith("rcr") ||
2596 Name.startswith("rol") || Name.startswith("ror")) &&
Chris Lattner4cfbcdc2010-09-06 18:32:06 +00002597 Operands.size() == 3) {
Devang Patel9a9bb5c2012-01-30 20:02:42 +00002598 if (isParsingIntelSyntax()) {
Devang Patela410ed32012-01-24 21:43:36 +00002599 // Intel syntax
David Blaikie960ea3f2014-06-08 16:18:35 +00002600 X86Operand &Op1 = static_cast<X86Operand &>(*Operands[2]);
2601 if (Op1.isImm() && isa<MCConstantExpr>(Op1.getImm()) &&
2602 cast<MCConstantExpr>(Op1.getImm())->getValue() == 1)
Craig Topper6bf3ed42012-07-18 04:59:16 +00002603 Operands.pop_back();
Devang Patela410ed32012-01-24 21:43:36 +00002604 } else {
David Blaikie960ea3f2014-06-08 16:18:35 +00002605 X86Operand &Op1 = static_cast<X86Operand &>(*Operands[1]);
2606 if (Op1.isImm() && isa<MCConstantExpr>(Op1.getImm()) &&
2607 cast<MCConstantExpr>(Op1.getImm())->getValue() == 1)
Craig Topper6bf3ed42012-07-18 04:59:16 +00002608 Operands.erase(Operands.begin() + 1);
Chris Lattner4cfbcdc2010-09-06 18:32:06 +00002609 }
Daniel Dunbarfbd12cc2010-03-20 22:36:38 +00002610 }
Chad Rosier51afe632012-06-27 22:34:28 +00002611
Chris Lattnerfc4fe002011-04-09 19:41:05 +00002612 // Transforms "int $3" into "int3" as a size optimization. We can't write an
2613 // instalias with an immediate operand yet.
2614 if (Name == "int" && Operands.size() == 2) {
David Blaikie960ea3f2014-06-08 16:18:35 +00002615 X86Operand &Op1 = static_cast<X86Operand &>(*Operands[1]);
Duncan P. N. Exon Smithd5313222015-07-23 19:27:07 +00002616 if (Op1.isImm())
2617 if (auto *CE = dyn_cast<MCConstantExpr>(Op1.getImm()))
2618 if (CE->getValue() == 3) {
2619 Operands.erase(Operands.begin() + 1);
2620 static_cast<X86Operand &>(*Operands[0]).setTokenValue("int3");
2621 }
Chris Lattnerfc4fe002011-04-09 19:41:05 +00002622 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00002623
Marina Yatsinad9658d12016-01-19 16:35:38 +00002624 // Transforms "xlat mem8" into "xlatb"
2625 if ((Name == "xlat" || Name == "xlatb") && Operands.size() == 2) {
2626 X86Operand &Op1 = static_cast<X86Operand &>(*Operands[1]);
2627 if (Op1.isMem8()) {
2628 Warning(Op1.getStartLoc(), "memory operand is only for determining the "
2629 "size, (R|E)BX will be used for the location");
2630 Operands.pop_back();
2631 static_cast<X86Operand &>(*Operands[0]).setTokenValue("xlatb");
2632 }
2633 }
2634
Chris Lattnerf29c0b62010-01-14 22:21:20 +00002635 return false;
Daniel Dunbar3c2a8932009-07-20 18:55:04 +00002636}
2637
David Blaikie960ea3f2014-06-08 16:18:35 +00002638bool X86AsmParser::processInstruction(MCInst &Inst, const OperandVector &Ops) {
Aaron Ballmana81264b2016-05-23 15:52:59 +00002639 return false;
Devang Patelde47cce2012-01-18 22:42:29 +00002640}
2641
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002642static const char *getSubtargetFeatureName(uint64_t Val);
Evgeniy Stepanov49e26252014-03-14 08:58:04 +00002643
David Blaikie960ea3f2014-06-08 16:18:35 +00002644void X86AsmParser::EmitInstruction(MCInst &Inst, OperandVector &Operands,
2645 MCStreamer &Out) {
Evgeniy Stepanov77ad8662014-07-31 09:11:04 +00002646 Instrumentation->InstrumentAndEmitInstruction(Inst, Operands, getContext(),
2647 MII, Out);
Evgeniy Stepanov49e26252014-03-14 08:58:04 +00002648}
2649
David Blaikie960ea3f2014-06-08 16:18:35 +00002650bool X86AsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
2651 OperandVector &Operands,
Tim Northover26bb14e2014-08-18 11:49:42 +00002652 MCStreamer &Out, uint64_t &ErrorInfo,
David Blaikie960ea3f2014-06-08 16:18:35 +00002653 bool MatchingInlineAsm) {
Reid Klecknerf6fb7802014-08-26 20:32:34 +00002654 if (isParsingIntelSyntax())
2655 return MatchAndEmitIntelInstruction(IDLoc, Opcode, Operands, Out, ErrorInfo,
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002656 MatchingInlineAsm);
Reid Klecknerf6fb7802014-08-26 20:32:34 +00002657 return MatchAndEmitATTInstruction(IDLoc, Opcode, Operands, Out, ErrorInfo,
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002658 MatchingInlineAsm);
Reid Klecknerf6fb7802014-08-26 20:32:34 +00002659}
Daniel Dunbar2ecc3bb2010-08-12 00:55:38 +00002660
Reid Klecknerf6fb7802014-08-26 20:32:34 +00002661void X86AsmParser::MatchFPUWaitAlias(SMLoc IDLoc, X86Operand &Op,
2662 OperandVector &Operands, MCStreamer &Out,
2663 bool MatchingInlineAsm) {
Chris Lattnera63292a2010-09-29 01:50:45 +00002664 // FIXME: This should be replaced with a real .td file alias mechanism.
Chad Rosier3b1336c2012-08-28 23:57:47 +00002665 // Also, MatchInstructionImpl should actually *do* the EmitInstruction
Chris Lattner4869d342010-11-06 19:57:21 +00002666 // call.
Reid Klecknerb1f2d2f2014-07-31 00:07:33 +00002667 const char *Repl = StringSwitch<const char *>(Op.getToken())
2668 .Case("finit", "fninit")
2669 .Case("fsave", "fnsave")
2670 .Case("fstcw", "fnstcw")
2671 .Case("fstcww", "fnstcw")
2672 .Case("fstenv", "fnstenv")
2673 .Case("fstsw", "fnstsw")
2674 .Case("fstsww", "fnstsw")
2675 .Case("fclex", "fnclex")
2676 .Default(nullptr);
2677 if (Repl) {
Chris Lattnera63292a2010-09-29 01:50:45 +00002678 MCInst Inst;
2679 Inst.setOpcode(X86::WAIT);
Jim Grosbach8f28dbd2012-01-27 00:51:27 +00002680 Inst.setLoc(IDLoc);
Chad Rosier4453e842012-10-12 23:09:25 +00002681 if (!MatchingInlineAsm)
Evgeniy Stepanov49e26252014-03-14 08:58:04 +00002682 EmitInstruction(Inst, Operands, Out);
Chris Lattneradc0dbe2010-09-30 16:39:29 +00002683 Operands[0] = X86Operand::CreateToken(Repl, IDLoc);
Chris Lattnera63292a2010-09-29 01:50:45 +00002684 }
Reid Klecknerf6fb7802014-08-26 20:32:34 +00002685}
2686
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002687bool X86AsmParser::ErrorMissingFeature(SMLoc IDLoc, uint64_t ErrorInfo,
Reid Klecknerf6fb7802014-08-26 20:32:34 +00002688 bool MatchingInlineAsm) {
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002689 assert(ErrorInfo && "Unknown missing feature!");
Reid Klecknerf6fb7802014-08-26 20:32:34 +00002690 SmallString<126> Msg;
2691 raw_svector_ostream OS(Msg);
2692 OS << "instruction requires:";
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002693 uint64_t Mask = 1;
2694 for (unsigned i = 0; i < (sizeof(ErrorInfo)*8-1); ++i) {
2695 if (ErrorInfo & Mask)
2696 OS << ' ' << getSubtargetFeatureName(ErrorInfo & Mask);
2697 Mask <<= 1;
Reid Klecknerf6fb7802014-08-26 20:32:34 +00002698 }
Nirav Dave2364748a2016-09-16 18:30:20 +00002699 return Error(IDLoc, OS.str(), SMRange(), MatchingInlineAsm);
Reid Klecknerf6fb7802014-08-26 20:32:34 +00002700}
2701
2702bool X86AsmParser::MatchAndEmitATTInstruction(SMLoc IDLoc, unsigned &Opcode,
2703 OperandVector &Operands,
2704 MCStreamer &Out,
2705 uint64_t &ErrorInfo,
2706 bool MatchingInlineAsm) {
2707 assert(!Operands.empty() && "Unexpect empty operand list!");
2708 X86Operand &Op = static_cast<X86Operand &>(*Operands[0]);
2709 assert(Op.isToken() && "Leading operand should always be a mnemonic!");
Nirav Dave2364748a2016-09-16 18:30:20 +00002710 SMRange EmptyRange = None;
Reid Klecknerf6fb7802014-08-26 20:32:34 +00002711
2712 // First, handle aliases that expand to multiple instructions.
2713 MatchFPUWaitAlias(IDLoc, Op, Operands, Out, MatchingInlineAsm);
Michael J. Spencer530ce852010-10-09 11:00:50 +00002714
Chris Lattner628fbec2010-09-06 21:54:15 +00002715 bool WasOriginallyInvalidOperand = false;
Chris Lattnerb44fd242010-09-29 01:42:58 +00002716 MCInst Inst;
Michael J. Spencer530ce852010-10-09 11:00:50 +00002717
Daniel Dunbar9b816a12010-05-04 16:12:42 +00002718 // First, try a direct match.
Nirav Dave6477ce22016-09-26 19:33:36 +00002719 switch (MatchInstruction(Operands, Inst, ErrorInfo, MatchingInlineAsm,
2720 isParsingIntelSyntax())) {
Craig Topper589ceee2015-01-03 08:16:34 +00002721 default: llvm_unreachable("Unexpected match result!");
Chris Lattnerb4be28f2010-09-06 20:08:02 +00002722 case Match_Success:
Devang Patelde47cce2012-01-18 22:42:29 +00002723 // Some instructions need post-processing to, for example, tweak which
2724 // encoding is selected. Loop on it while changes happen so the
Chad Rosier51afe632012-06-27 22:34:28 +00002725 // individual transformations can chain off each other.
Chad Rosier4453e842012-10-12 23:09:25 +00002726 if (!MatchingInlineAsm)
Chad Rosierf4e35dc2012-10-01 23:45:51 +00002727 while (processInstruction(Inst, Operands))
2728 ;
Devang Patelde47cce2012-01-18 22:42:29 +00002729
Jim Grosbach8f28dbd2012-01-27 00:51:27 +00002730 Inst.setLoc(IDLoc);
Chad Rosier4453e842012-10-12 23:09:25 +00002731 if (!MatchingInlineAsm)
Evgeniy Stepanov49e26252014-03-14 08:58:04 +00002732 EmitInstruction(Inst, Operands, Out);
Chad Rosierf4e35dc2012-10-01 23:45:51 +00002733 Opcode = Inst.getOpcode();
Daniel Dunbar9b816a12010-05-04 16:12:42 +00002734 return false;
Reid Klecknerf6fb7802014-08-26 20:32:34 +00002735 case Match_MissingFeature:
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002736 return ErrorMissingFeature(IDLoc, ErrorInfo, MatchingInlineAsm);
Chris Lattner628fbec2010-09-06 21:54:15 +00002737 case Match_InvalidOperand:
2738 WasOriginallyInvalidOperand = true;
2739 break;
2740 case Match_MnemonicFail:
Chris Lattnerb4be28f2010-09-06 20:08:02 +00002741 break;
2742 }
Daniel Dunbar9b816a12010-05-04 16:12:42 +00002743
Daniel Dunbar9b816a12010-05-04 16:12:42 +00002744 // FIXME: Ideally, we would only attempt suffix matches for things which are
2745 // valid prefixes, and we could just infer the right unambiguous
2746 // type. However, that requires substantially more matcher support than the
2747 // following hack.
Michael J. Spencer530ce852010-10-09 11:00:50 +00002748
Daniel Dunbar9b816a12010-05-04 16:12:42 +00002749 // Change the operand to point to a temporary token.
David Blaikie960ea3f2014-06-08 16:18:35 +00002750 StringRef Base = Op.getToken();
Daniel Dunbar2ecc3bb2010-08-12 00:55:38 +00002751 SmallString<16> Tmp;
2752 Tmp += Base;
2753 Tmp += ' ';
Yaron Keren075759a2015-03-30 15:42:36 +00002754 Op.setTokenValue(Tmp);
Daniel Dunbar9b816a12010-05-04 16:12:42 +00002755
Chris Lattnerfab94132010-11-06 18:28:02 +00002756 // If this instruction starts with an 'f', then it is a floating point stack
2757 // instruction. These come in up to three forms for 32-bit, 64-bit, and
2758 // 80-bit floating point, which use the suffixes s,l,t respectively.
2759 //
2760 // Otherwise, we assume that this may be an integer instruction, which comes
2761 // in 8/16/32/64-bit forms using the b,w,l,q suffixes respectively.
2762 const char *Suffixes = Base[0] != 'f' ? "bwlq" : "slt\0";
Chad Rosier51afe632012-06-27 22:34:28 +00002763
Daniel Dunbar9b816a12010-05-04 16:12:42 +00002764 // Check for the various suffix matches.
Tim Northover26bb14e2014-08-18 11:49:42 +00002765 uint64_t ErrorInfoIgnore;
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002766 uint64_t ErrorInfoMissingFeature = 0; // Init suppresses compiler warnings.
Reid Kleckner7b1e1a02014-07-30 22:23:11 +00002767 unsigned Match[4];
Chad Rosier51afe632012-06-27 22:34:28 +00002768
Reid Kleckner7b1e1a02014-07-30 22:23:11 +00002769 for (unsigned I = 0, E = array_lengthof(Match); I != E; ++I) {
2770 Tmp.back() = Suffixes[I];
Nirav Dave6477ce22016-09-26 19:33:36 +00002771 Match[I] = MatchInstruction(Operands, Inst, ErrorInfoIgnore,
2772 MatchingInlineAsm, isParsingIntelSyntax());
Reid Kleckner7b1e1a02014-07-30 22:23:11 +00002773 // If this returned as a missing feature failure, remember that.
2774 if (Match[I] == Match_MissingFeature)
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002775 ErrorInfoMissingFeature = ErrorInfoIgnore;
Reid Kleckner7b1e1a02014-07-30 22:23:11 +00002776 }
Daniel Dunbar9b816a12010-05-04 16:12:42 +00002777
2778 // Restore the old token.
David Blaikie960ea3f2014-06-08 16:18:35 +00002779 Op.setTokenValue(Base);
Daniel Dunbar9b816a12010-05-04 16:12:42 +00002780
2781 // If exactly one matched, then we treat that as a successful match (and the
2782 // instruction will already have been filled in correctly, since the failing
2783 // matches won't have modified it).
Chris Lattnerb4be28f2010-09-06 20:08:02 +00002784 unsigned NumSuccessfulMatches =
Reid Kleckner7b1e1a02014-07-30 22:23:11 +00002785 std::count(std::begin(Match), std::end(Match), Match_Success);
Chris Lattnerb44fd242010-09-29 01:42:58 +00002786 if (NumSuccessfulMatches == 1) {
Jim Grosbach8f28dbd2012-01-27 00:51:27 +00002787 Inst.setLoc(IDLoc);
Chad Rosier4453e842012-10-12 23:09:25 +00002788 if (!MatchingInlineAsm)
Evgeniy Stepanov49e26252014-03-14 08:58:04 +00002789 EmitInstruction(Inst, Operands, Out);
Chad Rosierf4e35dc2012-10-01 23:45:51 +00002790 Opcode = Inst.getOpcode();
Daniel Dunbar9b816a12010-05-04 16:12:42 +00002791 return false;
Chris Lattnerb44fd242010-09-29 01:42:58 +00002792 }
Daniel Dunbar9b816a12010-05-04 16:12:42 +00002793
Chris Lattnerb4be28f2010-09-06 20:08:02 +00002794 // Otherwise, the match failed, try to produce a decent error message.
Daniel Dunbar2ecc3bb2010-08-12 00:55:38 +00002795
Daniel Dunbar7d7b4d12010-08-12 00:55:42 +00002796 // If we had multiple suffix matches, then identify this as an ambiguous
2797 // match.
Chris Lattnerb4be28f2010-09-06 20:08:02 +00002798 if (NumSuccessfulMatches > 1) {
Daniel Dunbar7d7b4d12010-08-12 00:55:42 +00002799 char MatchChars[4];
2800 unsigned NumMatches = 0;
Reid Kleckner7b1e1a02014-07-30 22:23:11 +00002801 for (unsigned I = 0, E = array_lengthof(Match); I != E; ++I)
2802 if (Match[I] == Match_Success)
2803 MatchChars[NumMatches++] = Suffixes[I];
Daniel Dunbar7d7b4d12010-08-12 00:55:42 +00002804
Alp Tokere69170a2014-06-26 22:52:05 +00002805 SmallString<126> Msg;
2806 raw_svector_ostream OS(Msg);
Daniel Dunbar7d7b4d12010-08-12 00:55:42 +00002807 OS << "ambiguous instructions require an explicit suffix (could be ";
2808 for (unsigned i = 0; i != NumMatches; ++i) {
2809 if (i != 0)
2810 OS << ", ";
2811 if (i + 1 == NumMatches)
2812 OS << "or ";
2813 OS << "'" << Base << MatchChars[i] << "'";
2814 }
2815 OS << ")";
Nirav Dave2364748a2016-09-16 18:30:20 +00002816 Error(IDLoc, OS.str(), EmptyRange, MatchingInlineAsm);
Chris Lattnerb4be28f2010-09-06 20:08:02 +00002817 return true;
Daniel Dunbar7d7b4d12010-08-12 00:55:42 +00002818 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00002819
Chris Lattner628fbec2010-09-06 21:54:15 +00002820 // Okay, we know that none of the variants matched successfully.
Michael J. Spencer530ce852010-10-09 11:00:50 +00002821
Chris Lattner628fbec2010-09-06 21:54:15 +00002822 // If all of the instructions reported an invalid mnemonic, then the original
2823 // mnemonic was invalid.
Reid Kleckner7b1e1a02014-07-30 22:23:11 +00002824 if (std::count(std::begin(Match), std::end(Match), Match_MnemonicFail) == 4) {
Chris Lattner339cc7b2010-09-06 22:11:18 +00002825 if (!WasOriginallyInvalidOperand) {
Benjamin Kramerd416bae2011-10-16 11:28:29 +00002826 return Error(IDLoc, "invalid instruction mnemonic '" + Base + "'",
Nirav Dave2364748a2016-09-16 18:30:20 +00002827 Op.getLocRange(), MatchingInlineAsm);
Chris Lattner339cc7b2010-09-06 22:11:18 +00002828 }
2829
2830 // Recover location info for the operand if we know which was the problem.
Tim Northover26bb14e2014-08-18 11:49:42 +00002831 if (ErrorInfo != ~0ULL) {
Chad Rosier49963552012-10-13 00:26:04 +00002832 if (ErrorInfo >= Operands.size())
Nirav Dave2364748a2016-09-16 18:30:20 +00002833 return Error(IDLoc, "too few operands for instruction", EmptyRange,
2834 MatchingInlineAsm);
Michael J. Spencer530ce852010-10-09 11:00:50 +00002835
David Blaikie960ea3f2014-06-08 16:18:35 +00002836 X86Operand &Operand = (X86Operand &)*Operands[ErrorInfo];
2837 if (Operand.getStartLoc().isValid()) {
2838 SMRange OperandRange = Operand.getLocRange();
2839 return Error(Operand.getStartLoc(), "invalid operand for instruction",
Chad Rosier4453e842012-10-12 23:09:25 +00002840 OperandRange, MatchingInlineAsm);
Chris Lattnera3a06812011-10-16 04:47:35 +00002841 }
Chris Lattner339cc7b2010-09-06 22:11:18 +00002842 }
2843
Nirav Dave2364748a2016-09-16 18:30:20 +00002844 return Error(IDLoc, "invalid operand for instruction", EmptyRange,
Chad Rosier4453e842012-10-12 23:09:25 +00002845 MatchingInlineAsm);
Chris Lattner628fbec2010-09-06 21:54:15 +00002846 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00002847
Chris Lattnerb4be28f2010-09-06 20:08:02 +00002848 // If one instruction matched with a missing feature, report this as a
2849 // missing feature.
Reid Kleckner7b1e1a02014-07-30 22:23:11 +00002850 if (std::count(std::begin(Match), std::end(Match),
2851 Match_MissingFeature) == 1) {
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002852 ErrorInfo = ErrorInfoMissingFeature;
2853 return ErrorMissingFeature(IDLoc, ErrorInfoMissingFeature,
Reid Klecknerf6fb7802014-08-26 20:32:34 +00002854 MatchingInlineAsm);
Chris Lattnerb4be28f2010-09-06 20:08:02 +00002855 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00002856
Chris Lattner628fbec2010-09-06 21:54:15 +00002857 // If one instruction matched with an invalid operand, report this as an
2858 // operand failure.
Reid Kleckner7b1e1a02014-07-30 22:23:11 +00002859 if (std::count(std::begin(Match), std::end(Match),
2860 Match_InvalidOperand) == 1) {
Nirav Dave2364748a2016-09-16 18:30:20 +00002861 return Error(IDLoc, "invalid operand for instruction", EmptyRange,
Reid Klecknerf6fb7802014-08-26 20:32:34 +00002862 MatchingInlineAsm);
Chris Lattner628fbec2010-09-06 21:54:15 +00002863 }
Michael J. Spencer530ce852010-10-09 11:00:50 +00002864
Chris Lattnerb4be28f2010-09-06 20:08:02 +00002865 // If all of these were an outright failure, report it in a useless way.
Chad Rosier3d4bc622012-08-21 19:36:59 +00002866 Error(IDLoc, "unknown use of instruction mnemonic without a size suffix",
Nirav Dave2364748a2016-09-16 18:30:20 +00002867 EmptyRange, MatchingInlineAsm);
Daniel Dunbar9b816a12010-05-04 16:12:42 +00002868 return true;
2869}
2870
Reid Klecknerf6fb7802014-08-26 20:32:34 +00002871bool X86AsmParser::MatchAndEmitIntelInstruction(SMLoc IDLoc, unsigned &Opcode,
2872 OperandVector &Operands,
2873 MCStreamer &Out,
2874 uint64_t &ErrorInfo,
2875 bool MatchingInlineAsm) {
2876 assert(!Operands.empty() && "Unexpect empty operand list!");
2877 X86Operand &Op = static_cast<X86Operand &>(*Operands[0]);
2878 assert(Op.isToken() && "Leading operand should always be a mnemonic!");
2879 StringRef Mnemonic = Op.getToken();
Nirav Dave2364748a2016-09-16 18:30:20 +00002880 SMRange EmptyRange = None;
Nirav Daveee554e62016-10-06 15:28:08 +00002881 StringRef Base = Op.getToken();
Reid Klecknerf6fb7802014-08-26 20:32:34 +00002882
2883 // First, handle aliases that expand to multiple instructions.
2884 MatchFPUWaitAlias(IDLoc, Op, Operands, Out, MatchingInlineAsm);
2885
2886 MCInst Inst;
2887
2888 // Find one unsized memory operand, if present.
2889 X86Operand *UnsizedMemOp = nullptr;
2890 for (const auto &Op : Operands) {
2891 X86Operand *X86Op = static_cast<X86Operand *>(Op.get());
Reid Kleckner6d2ea6e2017-05-04 18:19:52 +00002892 if (X86Op->isMemUnsized()) {
2893 UnsizedMemOp = X86Op;
Coby Tayree49b37332016-11-22 09:30:29 +00002894 // Have we found an unqualified memory operand,
2895 // break. IA allows only one memory operand.
2896 break;
2897 }
Reid Klecknerf6fb7802014-08-26 20:32:34 +00002898 }
2899
2900 // Allow some instructions to have implicitly pointer-sized operands. This is
2901 // compatible with gas.
2902 if (UnsizedMemOp) {
2903 static const char *const PtrSizedInstrs[] = {"call", "jmp", "push"};
2904 for (const char *Instr : PtrSizedInstrs) {
2905 if (Mnemonic == Instr) {
Craig Topper055845f2015-01-02 07:02:25 +00002906 UnsizedMemOp->Mem.Size = getPointerWidth();
Reid Klecknerf6fb7802014-08-26 20:32:34 +00002907 break;
2908 }
2909 }
2910 }
2911
Nirav Daveee554e62016-10-06 15:28:08 +00002912 SmallVector<unsigned, 8> Match;
2913 uint64_t ErrorInfoMissingFeature = 0;
2914
2915 // If unsized push has immediate operand we should default the default pointer
2916 // size for the size.
2917 if (Mnemonic == "push" && Operands.size() == 2) {
2918 auto *X86Op = static_cast<X86Operand *>(Operands[1].get());
2919 if (X86Op->isImm()) {
2920 // If it's not a constant fall through and let remainder take care of it.
2921 const auto *CE = dyn_cast<MCConstantExpr>(X86Op->getImm());
2922 unsigned Size = getPointerWidth();
2923 if (CE &&
2924 (isIntN(Size, CE->getValue()) || isUIntN(Size, CE->getValue()))) {
2925 SmallString<16> Tmp;
2926 Tmp += Base;
2927 Tmp += (is64BitMode())
2928 ? "q"
2929 : (is32BitMode()) ? "l" : (is16BitMode()) ? "w" : " ";
2930 Op.setTokenValue(Tmp);
2931 // Do match in ATT mode to allow explicit suffix usage.
2932 Match.push_back(MatchInstruction(Operands, Inst, ErrorInfo,
2933 MatchingInlineAsm,
2934 false /*isParsingIntelSyntax()*/));
2935 Op.setTokenValue(Base);
2936 }
2937 }
2938 }
2939
Reid Klecknerf6fb7802014-08-26 20:32:34 +00002940 // If an unsized memory operand is present, try to match with each memory
2941 // operand size. In Intel assembly, the size is not part of the instruction
2942 // mnemonic.
Reid Klecknerf6fb7802014-08-26 20:32:34 +00002943 if (UnsizedMemOp && UnsizedMemOp->isMemUnsized()) {
Ahmed Bougachad65f7872014-12-03 02:03:26 +00002944 static const unsigned MopSizes[] = {8, 16, 32, 64, 80, 128, 256, 512};
Reid Klecknerf6fb7802014-08-26 20:32:34 +00002945 for (unsigned Size : MopSizes) {
2946 UnsizedMemOp->Mem.Size = Size;
2947 uint64_t ErrorInfoIgnore;
Reid Kleckner7b7a5992014-08-27 20:10:38 +00002948 unsigned LastOpcode = Inst.getOpcode();
Nirav Dave6477ce22016-09-26 19:33:36 +00002949 unsigned M = MatchInstruction(Operands, Inst, ErrorInfoIgnore,
2950 MatchingInlineAsm, isParsingIntelSyntax());
Reid Kleckner7b7a5992014-08-27 20:10:38 +00002951 if (Match.empty() || LastOpcode != Inst.getOpcode())
2952 Match.push_back(M);
2953
Reid Klecknerf6fb7802014-08-26 20:32:34 +00002954 // If this returned as a missing feature failure, remember that.
2955 if (Match.back() == Match_MissingFeature)
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002956 ErrorInfoMissingFeature = ErrorInfoIgnore;
Reid Klecknerf6fb7802014-08-26 20:32:34 +00002957 }
Reid Kleckner7b7a5992014-08-27 20:10:38 +00002958
2959 // Restore the size of the unsized memory operand if we modified it.
Reid Kleckner6d2ea6e2017-05-04 18:19:52 +00002960 UnsizedMemOp->Mem.Size = 0;
Reid Kleckner7b7a5992014-08-27 20:10:38 +00002961 }
2962
2963 // If we haven't matched anything yet, this is not a basic integer or FPU
Saleem Abdulrasoolc3f8ad32015-01-16 20:16:06 +00002964 // operation. There shouldn't be any ambiguity in our mnemonic table, so try
Reid Kleckner7b7a5992014-08-27 20:10:38 +00002965 // matching with the unsized operand.
2966 if (Match.empty()) {
Nirav Dave6477ce22016-09-26 19:33:36 +00002967 Match.push_back(MatchInstruction(
2968 Operands, Inst, ErrorInfo, MatchingInlineAsm, isParsingIntelSyntax()));
Reid Klecknerf6fb7802014-08-26 20:32:34 +00002969 // If this returned as a missing feature failure, remember that.
2970 if (Match.back() == Match_MissingFeature)
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00002971 ErrorInfoMissingFeature = ErrorInfo;
Reid Klecknerf6fb7802014-08-26 20:32:34 +00002972 }
2973
2974 // Restore the size of the unsized memory operand if we modified it.
2975 if (UnsizedMemOp)
2976 UnsizedMemOp->Mem.Size = 0;
2977
2978 // If it's a bad mnemonic, all results will be the same.
2979 if (Match.back() == Match_MnemonicFail) {
Reid Klecknerf6fb7802014-08-26 20:32:34 +00002980 return Error(IDLoc, "invalid instruction mnemonic '" + Mnemonic + "'",
Nirav Dave2364748a2016-09-16 18:30:20 +00002981 Op.getLocRange(), MatchingInlineAsm);
Reid Klecknerf6fb7802014-08-26 20:32:34 +00002982 }
2983
Reid Kleckner6d2ea6e2017-05-04 18:19:52 +00002984 unsigned NumSuccessfulMatches =
2985 std::count(std::begin(Match), std::end(Match), Match_Success);
2986
2987 // If matching was ambiguous and we had size information from the frontend,
2988 // try again with that. This handles cases like "movxz eax, m8/m16".
2989 if (UnsizedMemOp && NumSuccessfulMatches > 1 &&
2990 UnsizedMemOp->getMemFrontendSize()) {
2991 UnsizedMemOp->Mem.Size = UnsizedMemOp->getMemFrontendSize();
2992 unsigned M = MatchInstruction(
2993 Operands, Inst, ErrorInfo, MatchingInlineAsm, isParsingIntelSyntax());
2994 if (M == Match_Success)
2995 NumSuccessfulMatches = 1;
2996
2997 // Add a rewrite that encodes the size information we used from the
2998 // frontend.
2999 InstInfo->AsmRewrites->emplace_back(
3000 AOK_SizeDirective, UnsizedMemOp->getStartLoc(),
3001 /*Len=*/0, UnsizedMemOp->getMemFrontendSize());
3002 }
3003
Reid Klecknerf6fb7802014-08-26 20:32:34 +00003004 // If exactly one matched, then we treat that as a successful match (and the
3005 // instruction will already have been filled in correctly, since the failing
3006 // matches won't have modified it).
Reid Klecknerf6fb7802014-08-26 20:32:34 +00003007 if (NumSuccessfulMatches == 1) {
3008 // Some instructions need post-processing to, for example, tweak which
3009 // encoding is selected. Loop on it while changes happen so the individual
3010 // transformations can chain off each other.
3011 if (!MatchingInlineAsm)
3012 while (processInstruction(Inst, Operands))
3013 ;
3014 Inst.setLoc(IDLoc);
3015 if (!MatchingInlineAsm)
3016 EmitInstruction(Inst, Operands, Out);
3017 Opcode = Inst.getOpcode();
3018 return false;
3019 } else if (NumSuccessfulMatches > 1) {
3020 assert(UnsizedMemOp &&
3021 "multiple matches only possible with unsized memory operands");
Reid Klecknerf6fb7802014-08-26 20:32:34 +00003022 return Error(UnsizedMemOp->getStartLoc(),
3023 "ambiguous operand size for instruction '" + Mnemonic + "\'",
Reid Kleckner6d2ea6e2017-05-04 18:19:52 +00003024 UnsizedMemOp->getLocRange());
Reid Klecknerf6fb7802014-08-26 20:32:34 +00003025 }
3026
3027 // If one instruction matched with a missing feature, report this as a
3028 // missing feature.
3029 if (std::count(std::begin(Match), std::end(Match),
3030 Match_MissingFeature) == 1) {
Ranjeet Singh86ecbb72015-06-30 12:32:53 +00003031 ErrorInfo = ErrorInfoMissingFeature;
Reid Klecknerf6fb7802014-08-26 20:32:34 +00003032 return ErrorMissingFeature(IDLoc, ErrorInfoMissingFeature,
3033 MatchingInlineAsm);
3034 }
3035
3036 // If one instruction matched with an invalid operand, report this as an
3037 // operand failure.
3038 if (std::count(std::begin(Match), std::end(Match),
3039 Match_InvalidOperand) == 1) {
Nirav Dave2364748a2016-09-16 18:30:20 +00003040 return Error(IDLoc, "invalid operand for instruction", EmptyRange,
Reid Klecknerf6fb7802014-08-26 20:32:34 +00003041 MatchingInlineAsm);
3042 }
3043
3044 // If all of these were an outright failure, report it in a useless way.
Nirav Dave2364748a2016-09-16 18:30:20 +00003045 return Error(IDLoc, "unknown instruction mnemonic", EmptyRange,
Reid Klecknerf6fb7802014-08-26 20:32:34 +00003046 MatchingInlineAsm);
3047}
3048
Nico Weber42f79db2014-07-17 20:24:55 +00003049bool X86AsmParser::OmitRegisterFromClobberLists(unsigned RegNo) {
3050 return X86MCRegisterClasses[X86::SEGMENT_REGRegClassID].contains(RegNo);
3051}
Daniel Dunbar9b816a12010-05-04 16:12:42 +00003052
Devang Patel4a6e7782012-01-12 18:03:40 +00003053bool X86AsmParser::ParseDirective(AsmToken DirectiveID) {
Rafael Espindola961d4692014-11-11 05:18:41 +00003054 MCAsmParser &Parser = getParser();
Chris Lattner72c0b592010-10-30 17:38:55 +00003055 StringRef IDVal = DirectiveID.getIdentifier();
3056 if (IDVal == ".word")
3057 return ParseDirectiveWord(2, DirectiveID.getLoc());
Evan Cheng481ebb02011-07-27 00:38:12 +00003058 else if (IDVal.startswith(".code"))
3059 return ParseDirectiveCode(IDVal, DirectiveID.getLoc());
Chad Rosier6f8d8b22012-09-10 20:54:39 +00003060 else if (IDVal.startswith(".att_syntax")) {
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +00003061 getParser().setParsingInlineAsm(false);
Reid Klecknerce63b792014-08-06 23:21:13 +00003062 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3063 if (Parser.getTok().getString() == "prefix")
3064 Parser.Lex();
3065 else if (Parser.getTok().getString() == "noprefix")
3066 return Error(DirectiveID.getLoc(), "'.att_syntax noprefix' is not "
3067 "supported: registers must have a "
3068 "'%' prefix in .att_syntax");
3069 }
Chad Rosier6f8d8b22012-09-10 20:54:39 +00003070 getParser().setAssemblerDialect(0);
3071 return false;
3072 } else if (IDVal.startswith(".intel_syntax")) {
Devang Patela173ee52012-01-31 18:14:05 +00003073 getParser().setAssemblerDialect(1);
Andrew V. Tischenkoc3c67232017-04-26 09:56:59 +00003074 getParser().setParsingInlineAsm(true);
Devang Patel9a9bb5c2012-01-30 20:02:42 +00003075 if (getLexer().isNot(AsmToken::EndOfStatement)) {
Saleem Abdulrasoola6505ca2014-01-13 01:15:39 +00003076 if (Parser.getTok().getString() == "noprefix")
Craig Topper6bf3ed42012-07-18 04:59:16 +00003077 Parser.Lex();
Reid Klecknerce63b792014-08-06 23:21:13 +00003078 else if (Parser.getTok().getString() == "prefix")
3079 return Error(DirectiveID.getLoc(), "'.intel_syntax prefix' is not "
3080 "supported: registers must not have "
3081 "a '%' prefix in .intel_syntax");
Devang Patel9a9bb5c2012-01-30 20:02:42 +00003082 }
3083 return false;
Michael Zuckerman02ecd432015-12-13 17:07:23 +00003084 } else if (IDVal == ".even")
3085 return parseDirectiveEven(DirectiveID.getLoc());
Chris Lattner72c0b592010-10-30 17:38:55 +00003086 return true;
3087}
3088
Michael Zuckerman02ecd432015-12-13 17:07:23 +00003089/// parseDirectiveEven
3090/// ::= .even
3091bool X86AsmParser::parseDirectiveEven(SMLoc L) {
Michael Zuckerman02ecd432015-12-13 17:07:23 +00003092 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3093 TokError("unexpected token in directive");
3094 return false;
3095 }
Eric Christopher445c9522016-10-14 05:47:37 +00003096 const MCSection *Section = getStreamer().getCurrentSectionOnly();
Michael Zuckerman02ecd432015-12-13 17:07:23 +00003097 if (!Section) {
3098 getStreamer().InitSections(false);
Eric Christopher445c9522016-10-14 05:47:37 +00003099 Section = getStreamer().getCurrentSectionOnly();
Michael Zuckerman02ecd432015-12-13 17:07:23 +00003100 }
3101 if (Section->UseCodeAlign())
3102 getStreamer().EmitCodeAlignment(2, 0);
3103 else
3104 getStreamer().EmitValueToAlignment(2, 0, 1, 0);
3105 return false;
3106}
Chris Lattner72c0b592010-10-30 17:38:55 +00003107/// ParseDirectiveWord
3108/// ::= .word [ expression (, expression)* ]
Devang Patel4a6e7782012-01-12 18:03:40 +00003109bool X86AsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
Rafael Espindola961d4692014-11-11 05:18:41 +00003110 MCAsmParser &Parser = getParser();
Chris Lattner72c0b592010-10-30 17:38:55 +00003111 if (getLexer().isNot(AsmToken::EndOfStatement)) {
3112 for (;;) {
3113 const MCExpr *Value;
David Majnemera375b262015-10-26 02:45:50 +00003114 SMLoc ExprLoc = getLexer().getLoc();
Jim Grosbachd2037eb2013-02-20 22:21:35 +00003115 if (getParser().parseExpression(Value))
Saleem Abdulrasoola6505ca2014-01-13 01:15:39 +00003116 return false;
Chad Rosier51afe632012-06-27 22:34:28 +00003117
David Majnemera375b262015-10-26 02:45:50 +00003118 if (const auto *MCE = dyn_cast<MCConstantExpr>(Value)) {
3119 assert(Size <= 8 && "Invalid size");
3120 uint64_t IntValue = MCE->getValue();
3121 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
3122 return Error(ExprLoc, "literal value out of range for directive");
3123 getStreamer().EmitIntValue(IntValue, Size);
3124 } else {
3125 getStreamer().EmitValue(Value, Size, ExprLoc);
3126 }
Chad Rosier51afe632012-06-27 22:34:28 +00003127
Chris Lattner72c0b592010-10-30 17:38:55 +00003128 if (getLexer().is(AsmToken::EndOfStatement))
3129 break;
Chad Rosier51afe632012-06-27 22:34:28 +00003130
Chris Lattner72c0b592010-10-30 17:38:55 +00003131 // FIXME: Improve diagnostic.
Saleem Abdulrasoola6505ca2014-01-13 01:15:39 +00003132 if (getLexer().isNot(AsmToken::Comma)) {
3133 Error(L, "unexpected token in directive");
3134 return false;
3135 }
Chris Lattner72c0b592010-10-30 17:38:55 +00003136 Parser.Lex();
3137 }
3138 }
Chad Rosier51afe632012-06-27 22:34:28 +00003139
Chris Lattner72c0b592010-10-30 17:38:55 +00003140 Parser.Lex();
3141 return false;
3142}
3143
Evan Cheng481ebb02011-07-27 00:38:12 +00003144/// ParseDirectiveCode
Craig Topper3c80d622014-01-06 04:55:54 +00003145/// ::= .code16 | .code32 | .code64
Devang Patel4a6e7782012-01-12 18:03:40 +00003146bool X86AsmParser::ParseDirectiveCode(StringRef IDVal, SMLoc L) {
Rafael Espindola961d4692014-11-11 05:18:41 +00003147 MCAsmParser &Parser = getParser();
Nirav Dave6477ce22016-09-26 19:33:36 +00003148 Code16GCC = false;
Craig Topper3c80d622014-01-06 04:55:54 +00003149 if (IDVal == ".code16") {
Evan Cheng481ebb02011-07-27 00:38:12 +00003150 Parser.Lex();
Craig Topper3c80d622014-01-06 04:55:54 +00003151 if (!is16BitMode()) {
3152 SwitchMode(X86::Mode16Bit);
3153 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
3154 }
Nirav Dave6477ce22016-09-26 19:33:36 +00003155 } else if (IDVal == ".code16gcc") {
3156 // .code16gcc parses as if in 32-bit mode, but emits code in 16-bit mode.
3157 Parser.Lex();
3158 Code16GCC = true;
3159 if (!is16BitMode()) {
3160 SwitchMode(X86::Mode16Bit);
3161 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
3162 }
Saleem Abdulrasoola6505ca2014-01-13 01:15:39 +00003163 } else if (IDVal == ".code32") {
Craig Topper3c80d622014-01-06 04:55:54 +00003164 Parser.Lex();
3165 if (!is32BitMode()) {
3166 SwitchMode(X86::Mode32Bit);
Evan Cheng481ebb02011-07-27 00:38:12 +00003167 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
3168 }
3169 } else if (IDVal == ".code64") {
3170 Parser.Lex();
3171 if (!is64BitMode()) {
Craig Topper3c80d622014-01-06 04:55:54 +00003172 SwitchMode(X86::Mode64Bit);
Evan Cheng481ebb02011-07-27 00:38:12 +00003173 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code64);
3174 }
3175 } else {
Saleem Abdulrasoola6505ca2014-01-13 01:15:39 +00003176 Error(L, "unknown directive " + IDVal);
3177 return false;
Evan Cheng481ebb02011-07-27 00:38:12 +00003178 }
Chris Lattner72c0b592010-10-30 17:38:55 +00003179
Evan Cheng481ebb02011-07-27 00:38:12 +00003180 return false;
3181}
Chris Lattner72c0b592010-10-30 17:38:55 +00003182
Daniel Dunbar71475772009-07-17 20:42:00 +00003183// Force static initialization.
3184extern "C" void LLVMInitializeX86AsmParser() {
Mehdi Aminif42454b2016-10-09 23:00:34 +00003185 RegisterMCAsmParser<X86AsmParser> X(getTheX86_32Target());
3186 RegisterMCAsmParser<X86AsmParser> Y(getTheX86_64Target());
Daniel Dunbar71475772009-07-17 20:42:00 +00003187}
Daniel Dunbar00331992009-07-29 00:02:19 +00003188
Chris Lattner3e4582a2010-09-06 19:11:01 +00003189#define GET_REGISTER_MATCHER
3190#define GET_MATCHER_IMPLEMENTATION
Jim Grosbach6f1f41b2012-11-14 18:04:47 +00003191#define GET_SUBTARGET_FEATURE_NAME
Daniel Dunbar00331992009-07-29 00:02:19 +00003192#include "X86GenAsmMatcher.inc"