Deleted Added
full compact
X86AsmParser.cpp (263508) X86AsmParser.cpp (266715)
1//===-- 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
10#include "MCTargetDesc/X86BaseInfo.h"
11#include "llvm/ADT/APFloat.h"
12#include "llvm/ADT/STLExtras.h"
13#include "llvm/ADT/SmallString.h"
14#include "llvm/ADT/SmallVector.h"
15#include "llvm/ADT/StringSwitch.h"
16#include "llvm/ADT/Twine.h"
17#include "llvm/MC/MCContext.h"
18#include "llvm/MC/MCExpr.h"
19#include "llvm/MC/MCInst.h"
20#include "llvm/MC/MCParser/MCAsmLexer.h"
21#include "llvm/MC/MCParser/MCAsmParser.h"
22#include "llvm/MC/MCParser/MCParsedAsmOperand.h"
23#include "llvm/MC/MCRegisterInfo.h"
24#include "llvm/MC/MCStreamer.h"
25#include "llvm/MC/MCSubtargetInfo.h"
26#include "llvm/MC/MCSymbol.h"
27#include "llvm/MC/MCTargetAsmParser.h"
28#include "llvm/Support/SourceMgr.h"
29#include "llvm/Support/TargetRegistry.h"
30#include "llvm/Support/raw_ostream.h"
31
32using namespace llvm;
33
34namespace {
35struct X86Operand;
36
37static const char OpPrecedence[] = {
38 0, // IC_PLUS
39 0, // IC_MINUS
40 1, // IC_MULTIPLY
41 1, // IC_DIVIDE
42 2, // IC_RPAREN
43 3, // IC_LPAREN
44 0, // IC_IMM
45 0 // IC_REGISTER
46};
47
48class X86AsmParser : public MCTargetAsmParser {
49 MCSubtargetInfo &STI;
50 MCAsmParser &Parser;
51 ParseInstructionInfo *InstInfo;
52private:
53 enum InfixCalculatorTok {
54 IC_PLUS = 0,
55 IC_MINUS,
56 IC_MULTIPLY,
57 IC_DIVIDE,
58 IC_RPAREN,
59 IC_LPAREN,
60 IC_IMM,
61 IC_REGISTER
62 };
63
64 class InfixCalculator {
65 typedef std::pair< InfixCalculatorTok, int64_t > ICToken;
66 SmallVector<InfixCalculatorTok, 4> InfixOperatorStack;
67 SmallVector<ICToken, 4> PostfixStack;
68
69 public:
70 int64_t popOperand() {
71 assert (!PostfixStack.empty() && "Poped an empty stack!");
72 ICToken Op = PostfixStack.pop_back_val();
73 assert ((Op.first == IC_IMM || Op.first == IC_REGISTER)
74 && "Expected and immediate or register!");
75 return Op.second;
76 }
77 void pushOperand(InfixCalculatorTok Op, int64_t Val = 0) {
78 assert ((Op == IC_IMM || Op == IC_REGISTER) &&
79 "Unexpected operand!");
80 PostfixStack.push_back(std::make_pair(Op, Val));
81 }
82
83 void popOperator() { InfixOperatorStack.pop_back(); }
84 void pushOperator(InfixCalculatorTok Op) {
85 // Push the new operator if the stack is empty.
86 if (InfixOperatorStack.empty()) {
87 InfixOperatorStack.push_back(Op);
88 return;
89 }
90
91 // Push the new operator if it has a higher precedence than the operator
92 // on the top of the stack or the operator on the top of the stack is a
93 // left parentheses.
94 unsigned Idx = InfixOperatorStack.size() - 1;
95 InfixCalculatorTok StackOp = InfixOperatorStack[Idx];
96 if (OpPrecedence[Op] > OpPrecedence[StackOp] || StackOp == IC_LPAREN) {
97 InfixOperatorStack.push_back(Op);
98 return;
99 }
100
101 // The operator on the top of the stack has higher precedence than the
102 // new operator.
103 unsigned ParenCount = 0;
104 while (1) {
105 // Nothing to process.
106 if (InfixOperatorStack.empty())
107 break;
108
109 Idx = InfixOperatorStack.size() - 1;
110 StackOp = InfixOperatorStack[Idx];
111 if (!(OpPrecedence[StackOp] >= OpPrecedence[Op] || ParenCount))
112 break;
113
114 // If we have an even parentheses count and we see a left parentheses,
115 // then stop processing.
116 if (!ParenCount && StackOp == IC_LPAREN)
117 break;
118
119 if (StackOp == IC_RPAREN) {
120 ++ParenCount;
121 InfixOperatorStack.pop_back();
122 } else if (StackOp == IC_LPAREN) {
123 --ParenCount;
124 InfixOperatorStack.pop_back();
125 } else {
126 InfixOperatorStack.pop_back();
127 PostfixStack.push_back(std::make_pair(StackOp, 0));
128 }
129 }
130 // Push the new operator.
131 InfixOperatorStack.push_back(Op);
132 }
133 int64_t execute() {
134 // Push any remaining operators onto the postfix stack.
135 while (!InfixOperatorStack.empty()) {
136 InfixCalculatorTok StackOp = InfixOperatorStack.pop_back_val();
137 if (StackOp != IC_LPAREN && StackOp != IC_RPAREN)
138 PostfixStack.push_back(std::make_pair(StackOp, 0));
139 }
140
141 if (PostfixStack.empty())
142 return 0;
143
144 SmallVector<ICToken, 16> OperandStack;
145 for (unsigned i = 0, e = PostfixStack.size(); i != e; ++i) {
146 ICToken Op = PostfixStack[i];
147 if (Op.first == IC_IMM || Op.first == IC_REGISTER) {
148 OperandStack.push_back(Op);
149 } else {
150 assert (OperandStack.size() > 1 && "Too few operands.");
151 int64_t Val;
152 ICToken Op2 = OperandStack.pop_back_val();
153 ICToken Op1 = OperandStack.pop_back_val();
154 switch (Op.first) {
155 default:
156 report_fatal_error("Unexpected operator!");
157 break;
158 case IC_PLUS:
159 Val = Op1.second + Op2.second;
160 OperandStack.push_back(std::make_pair(IC_IMM, Val));
161 break;
162 case IC_MINUS:
163 Val = Op1.second - Op2.second;
164 OperandStack.push_back(std::make_pair(IC_IMM, Val));
165 break;
166 case IC_MULTIPLY:
167 assert (Op1.first == IC_IMM && Op2.first == IC_IMM &&
168 "Multiply operation with an immediate and a register!");
169 Val = Op1.second * Op2.second;
170 OperandStack.push_back(std::make_pair(IC_IMM, Val));
171 break;
172 case IC_DIVIDE:
173 assert (Op1.first == IC_IMM && Op2.first == IC_IMM &&
174 "Divide operation with an immediate and a register!");
175 assert (Op2.second != 0 && "Division by zero!");
176 Val = Op1.second / Op2.second;
177 OperandStack.push_back(std::make_pair(IC_IMM, Val));
178 break;
179 }
180 }
181 }
182 assert (OperandStack.size() == 1 && "Expected a single result.");
183 return OperandStack.pop_back_val().second;
184 }
185 };
186
187 enum IntelExprState {
188 IES_PLUS,
189 IES_MINUS,
190 IES_MULTIPLY,
191 IES_DIVIDE,
192 IES_LBRAC,
193 IES_RBRAC,
194 IES_LPAREN,
195 IES_RPAREN,
196 IES_REGISTER,
197 IES_INTEGER,
198 IES_IDENTIFIER,
199 IES_ERROR
200 };
201
202 class IntelExprStateMachine {
203 IntelExprState State, PrevState;
204 unsigned BaseReg, IndexReg, TmpReg, Scale;
205 int64_t Imm;
206 const MCExpr *Sym;
207 StringRef SymName;
208 bool StopOnLBrac, AddImmPrefix;
209 InfixCalculator IC;
210 InlineAsmIdentifierInfo Info;
211 public:
212 IntelExprStateMachine(int64_t imm, bool stoponlbrac, bool addimmprefix) :
213 State(IES_PLUS), PrevState(IES_ERROR), BaseReg(0), IndexReg(0), TmpReg(0),
214 Scale(1), Imm(imm), Sym(0), StopOnLBrac(stoponlbrac),
215 AddImmPrefix(addimmprefix) { Info.clear(); }
216
217 unsigned getBaseReg() { return BaseReg; }
218 unsigned getIndexReg() { return IndexReg; }
219 unsigned getScale() { return Scale; }
220 const MCExpr *getSym() { return Sym; }
221 StringRef getSymName() { return SymName; }
222 int64_t getImm() { return Imm + IC.execute(); }
223 bool isValidEndState() {
224 return State == IES_RBRAC || State == IES_INTEGER;
225 }
226 bool getStopOnLBrac() { return StopOnLBrac; }
227 bool getAddImmPrefix() { return AddImmPrefix; }
228 bool hadError() { return State == IES_ERROR; }
229
230 InlineAsmIdentifierInfo &getIdentifierInfo() {
231 return Info;
232 }
233
234 void onPlus() {
235 IntelExprState CurrState = State;
236 switch (State) {
237 default:
238 State = IES_ERROR;
239 break;
240 case IES_INTEGER:
241 case IES_RPAREN:
242 case IES_REGISTER:
243 State = IES_PLUS;
244 IC.pushOperator(IC_PLUS);
245 if (CurrState == IES_REGISTER && PrevState != IES_MULTIPLY) {
246 // If we already have a BaseReg, then assume this is the IndexReg with
247 // a scale of 1.
248 if (!BaseReg) {
249 BaseReg = TmpReg;
250 } else {
251 assert (!IndexReg && "BaseReg/IndexReg already set!");
252 IndexReg = TmpReg;
253 Scale = 1;
254 }
255 }
256 break;
257 }
258 PrevState = CurrState;
259 }
260 void onMinus() {
261 IntelExprState CurrState = State;
262 switch (State) {
263 default:
264 State = IES_ERROR;
265 break;
266 case IES_PLUS:
267 case IES_MULTIPLY:
268 case IES_DIVIDE:
269 case IES_LPAREN:
270 case IES_RPAREN:
271 case IES_LBRAC:
272 case IES_RBRAC:
273 case IES_INTEGER:
274 case IES_REGISTER:
275 State = IES_MINUS;
276 // Only push the minus operator if it is not a unary operator.
277 if (!(CurrState == IES_PLUS || CurrState == IES_MINUS ||
278 CurrState == IES_MULTIPLY || CurrState == IES_DIVIDE ||
279 CurrState == IES_LPAREN || CurrState == IES_LBRAC))
280 IC.pushOperator(IC_MINUS);
281 if (CurrState == IES_REGISTER && PrevState != IES_MULTIPLY) {
282 // If we already have a BaseReg, then assume this is the IndexReg with
283 // a scale of 1.
284 if (!BaseReg) {
285 BaseReg = TmpReg;
286 } else {
287 assert (!IndexReg && "BaseReg/IndexReg already set!");
288 IndexReg = TmpReg;
289 Scale = 1;
290 }
291 }
292 break;
293 }
294 PrevState = CurrState;
295 }
296 void onRegister(unsigned Reg) {
297 IntelExprState CurrState = State;
298 switch (State) {
299 default:
300 State = IES_ERROR;
301 break;
302 case IES_PLUS:
303 case IES_LPAREN:
304 State = IES_REGISTER;
305 TmpReg = Reg;
306 IC.pushOperand(IC_REGISTER);
307 break;
308 case IES_MULTIPLY:
309 // Index Register - Scale * Register
310 if (PrevState == IES_INTEGER) {
311 assert (!IndexReg && "IndexReg already set!");
312 State = IES_REGISTER;
313 IndexReg = Reg;
314 // Get the scale and replace the 'Scale * Register' with '0'.
315 Scale = IC.popOperand();
316 IC.pushOperand(IC_IMM);
317 IC.popOperator();
318 } else {
319 State = IES_ERROR;
320 }
321 break;
322 }
323 PrevState = CurrState;
324 }
325 void onIdentifierExpr(const MCExpr *SymRef, StringRef SymRefName) {
326 PrevState = State;
327 switch (State) {
328 default:
329 State = IES_ERROR;
330 break;
331 case IES_PLUS:
332 case IES_MINUS:
333 State = IES_INTEGER;
334 Sym = SymRef;
335 SymName = SymRefName;
336 IC.pushOperand(IC_IMM);
337 break;
338 }
339 }
340 void onInteger(int64_t TmpInt) {
341 IntelExprState CurrState = State;
342 switch (State) {
343 default:
344 State = IES_ERROR;
345 break;
346 case IES_PLUS:
347 case IES_MINUS:
348 case IES_DIVIDE:
349 case IES_MULTIPLY:
350 case IES_LPAREN:
351 State = IES_INTEGER;
352 if (PrevState == IES_REGISTER && CurrState == IES_MULTIPLY) {
353 // Index Register - Register * Scale
354 assert (!IndexReg && "IndexReg already set!");
355 IndexReg = TmpReg;
356 Scale = TmpInt;
357 // Get the scale and replace the 'Register * Scale' with '0'.
358 IC.popOperator();
359 } else if ((PrevState == IES_PLUS || PrevState == IES_MINUS ||
360 PrevState == IES_MULTIPLY || PrevState == IES_DIVIDE ||
361 PrevState == IES_LPAREN || PrevState == IES_LBRAC) &&
362 CurrState == IES_MINUS) {
363 // Unary minus. No need to pop the minus operand because it was never
364 // pushed.
365 IC.pushOperand(IC_IMM, -TmpInt); // Push -Imm.
366 } else {
367 IC.pushOperand(IC_IMM, TmpInt);
368 }
369 break;
370 }
371 PrevState = CurrState;
372 }
373 void onStar() {
374 PrevState = State;
375 switch (State) {
376 default:
377 State = IES_ERROR;
378 break;
379 case IES_INTEGER:
380 case IES_REGISTER:
381 case IES_RPAREN:
382 State = IES_MULTIPLY;
383 IC.pushOperator(IC_MULTIPLY);
384 break;
385 }
386 }
387 void onDivide() {
388 PrevState = State;
389 switch (State) {
390 default:
391 State = IES_ERROR;
392 break;
393 case IES_INTEGER:
394 case IES_RPAREN:
395 State = IES_DIVIDE;
396 IC.pushOperator(IC_DIVIDE);
397 break;
398 }
399 }
400 void onLBrac() {
401 PrevState = State;
402 switch (State) {
403 default:
404 State = IES_ERROR;
405 break;
406 case IES_RBRAC:
407 State = IES_PLUS;
408 IC.pushOperator(IC_PLUS);
409 break;
410 }
411 }
412 void onRBrac() {
413 IntelExprState CurrState = State;
414 switch (State) {
415 default:
416 State = IES_ERROR;
417 break;
418 case IES_INTEGER:
419 case IES_REGISTER:
420 case IES_RPAREN:
421 State = IES_RBRAC;
422 if (CurrState == IES_REGISTER && PrevState != IES_MULTIPLY) {
423 // If we already have a BaseReg, then assume this is the IndexReg with
424 // a scale of 1.
425 if (!BaseReg) {
426 BaseReg = TmpReg;
427 } else {
428 assert (!IndexReg && "BaseReg/IndexReg already set!");
429 IndexReg = TmpReg;
430 Scale = 1;
431 }
432 }
433 break;
434 }
435 PrevState = CurrState;
436 }
437 void onLParen() {
438 IntelExprState CurrState = State;
439 switch (State) {
440 default:
441 State = IES_ERROR;
442 break;
443 case IES_PLUS:
444 case IES_MINUS:
445 case IES_MULTIPLY:
446 case IES_DIVIDE:
447 case IES_LPAREN:
448 // FIXME: We don't handle this type of unary minus, yet.
449 if ((PrevState == IES_PLUS || PrevState == IES_MINUS ||
450 PrevState == IES_MULTIPLY || PrevState == IES_DIVIDE ||
451 PrevState == IES_LPAREN || PrevState == IES_LBRAC) &&
452 CurrState == IES_MINUS) {
453 State = IES_ERROR;
454 break;
455 }
456 State = IES_LPAREN;
457 IC.pushOperator(IC_LPAREN);
458 break;
459 }
460 PrevState = CurrState;
461 }
462 void onRParen() {
463 PrevState = State;
464 switch (State) {
465 default:
466 State = IES_ERROR;
467 break;
468 case IES_INTEGER:
469 case IES_REGISTER:
470 case IES_RPAREN:
471 State = IES_RPAREN;
472 IC.pushOperator(IC_RPAREN);
473 break;
474 }
475 }
476 };
477
478 MCAsmParser &getParser() const { return Parser; }
479
480 MCAsmLexer &getLexer() const { return Parser.getLexer(); }
481
482 bool Error(SMLoc L, const Twine &Msg,
483 ArrayRef<SMRange> Ranges = None,
484 bool MatchingInlineAsm = false) {
485 if (MatchingInlineAsm) return true;
486 return Parser.Error(L, Msg, Ranges);
487 }
488
489 X86Operand *ErrorOperand(SMLoc Loc, StringRef Msg) {
490 Error(Loc, Msg);
491 return 0;
492 }
493
494 X86Operand *ParseOperand();
495 X86Operand *ParseATTOperand();
496 X86Operand *ParseIntelOperand();
497 X86Operand *ParseIntelOffsetOfOperator();
498 bool ParseIntelDotOperator(const MCExpr *Disp, const MCExpr *&NewDisp);
499 X86Operand *ParseIntelOperator(unsigned OpKind);
500 X86Operand *ParseIntelSegmentOverride(unsigned SegReg, SMLoc Start, unsigned Size);
501 X86Operand *ParseIntelMemOperand(int64_t ImmDisp, SMLoc StartLoc,
502 unsigned Size);
503 bool ParseIntelExpression(IntelExprStateMachine &SM, SMLoc &End);
504 X86Operand *ParseIntelBracExpression(unsigned SegReg, SMLoc Start,
505 int64_t ImmDisp, unsigned Size);
506 bool ParseIntelIdentifier(const MCExpr *&Val, StringRef &Identifier,
507 InlineAsmIdentifierInfo &Info,
508 bool IsUnevaluatedOperand, SMLoc &End);
509
510 X86Operand *ParseMemOperand(unsigned SegReg, SMLoc StartLoc);
511
512 X86Operand *CreateMemForInlineAsm(unsigned SegReg, const MCExpr *Disp,
513 unsigned BaseReg, unsigned IndexReg,
514 unsigned Scale, SMLoc Start, SMLoc End,
515 unsigned Size, StringRef Identifier,
516 InlineAsmIdentifierInfo &Info);
517
518 bool ParseDirectiveWord(unsigned Size, SMLoc L);
519 bool ParseDirectiveCode(StringRef IDVal, SMLoc L);
520
521 bool processInstruction(MCInst &Inst,
522 const SmallVectorImpl<MCParsedAsmOperand*> &Ops);
523
524 bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
525 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
526 MCStreamer &Out, unsigned &ErrorInfo,
527 bool MatchingInlineAsm);
528
529 /// isSrcOp - Returns true if operand is either (%rsi) or %ds:%(rsi)
530 /// in 64bit mode or (%esi) or %es:(%esi) in 32bit mode.
531 bool isSrcOp(X86Operand &Op);
532
533 /// isDstOp - Returns true if operand is either (%rdi) or %es:(%rdi)
534 /// in 64bit mode or (%edi) or %es:(%edi) in 32bit mode.
535 bool isDstOp(X86Operand &Op);
536
537 bool is64BitMode() const {
538 // FIXME: Can tablegen auto-generate this?
539 return (STI.getFeatureBits() & X86::Mode64Bit) != 0;
540 }
541 void SwitchMode() {
542 unsigned FB = ComputeAvailableFeatures(STI.ToggleFeature(X86::Mode64Bit));
543 setAvailableFeatures(FB);
544 }
545
546 bool isParsingIntelSyntax() {
547 return getParser().getAssemblerDialect();
548 }
549
550 /// @name Auto-generated Matcher Functions
551 /// {
552
553#define GET_ASSEMBLER_HEADER
554#include "X86GenAsmMatcher.inc"
555
556 /// }
557
558public:
559 X86AsmParser(MCSubtargetInfo &sti, MCAsmParser &parser,
560 const MCInstrInfo &MII)
561 : MCTargetAsmParser(), STI(sti), Parser(parser), InstInfo(0) {
562
563 // Initialize the set of available features.
564 setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
565 }
566 virtual bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc);
567
568 virtual bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
569 SMLoc NameLoc,
570 SmallVectorImpl<MCParsedAsmOperand*> &Operands);
571
572 virtual bool ParseDirective(AsmToken DirectiveID);
573};
574} // end anonymous namespace
575
576/// @name Auto-generated Match Functions
577/// {
578
579static unsigned MatchRegisterName(StringRef Name);
580
581/// }
582
583static bool isImmSExti16i8Value(uint64_t Value) {
584 return (( Value <= 0x000000000000007FULL)||
585 (0x000000000000FF80ULL <= Value && Value <= 0x000000000000FFFFULL)||
586 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
587}
588
589static bool isImmSExti32i8Value(uint64_t Value) {
590 return (( Value <= 0x000000000000007FULL)||
591 (0x00000000FFFFFF80ULL <= Value && Value <= 0x00000000FFFFFFFFULL)||
592 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
593}
594
595static bool isImmZExtu32u8Value(uint64_t Value) {
596 return (Value <= 0x00000000000000FFULL);
597}
598
599static bool isImmSExti64i8Value(uint64_t Value) {
600 return (( Value <= 0x000000000000007FULL)||
601 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
602}
603
604static bool isImmSExti64i32Value(uint64_t Value) {
605 return (( Value <= 0x000000007FFFFFFFULL)||
606 (0xFFFFFFFF80000000ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
607}
608namespace {
609
610/// X86Operand - Instances of this class represent a parsed X86 machine
611/// instruction.
612struct X86Operand : public MCParsedAsmOperand {
613 enum KindTy {
614 Token,
615 Register,
616 Immediate,
617 Memory
618 } Kind;
619
620 SMLoc StartLoc, EndLoc;
621 SMLoc OffsetOfLoc;
622 StringRef SymName;
623 void *OpDecl;
624 bool AddressOf;
625
626 struct TokOp {
627 const char *Data;
628 unsigned Length;
629 };
630
631 struct RegOp {
632 unsigned RegNo;
633 };
634
635 struct ImmOp {
636 const MCExpr *Val;
637 };
638
639 struct MemOp {
640 unsigned SegReg;
641 const MCExpr *Disp;
642 unsigned BaseReg;
643 unsigned IndexReg;
644 unsigned Scale;
645 unsigned Size;
646 };
647
648 union {
649 struct TokOp Tok;
650 struct RegOp Reg;
651 struct ImmOp Imm;
652 struct MemOp Mem;
653 };
654
655 X86Operand(KindTy K, SMLoc Start, SMLoc End)
656 : Kind(K), StartLoc(Start), EndLoc(End) {}
657
658 StringRef getSymName() { return SymName; }
659 void *getOpDecl() { return OpDecl; }
660
661 /// getStartLoc - Get the location of the first token of this operand.
662 SMLoc getStartLoc() const { return StartLoc; }
663 /// getEndLoc - Get the location of the last token of this operand.
664 SMLoc getEndLoc() const { return EndLoc; }
665 /// getLocRange - Get the range between the first and last token of this
666 /// operand.
667 SMRange getLocRange() const { return SMRange(StartLoc, EndLoc); }
668 /// getOffsetOfLoc - Get the location of the offset operator.
669 SMLoc getOffsetOfLoc() const { return OffsetOfLoc; }
670
671 virtual void print(raw_ostream &OS) const {}
672
673 StringRef getToken() const {
674 assert(Kind == Token && "Invalid access!");
675 return StringRef(Tok.Data, Tok.Length);
676 }
677 void setTokenValue(StringRef Value) {
678 assert(Kind == Token && "Invalid access!");
679 Tok.Data = Value.data();
680 Tok.Length = Value.size();
681 }
682
683 unsigned getReg() const {
684 assert(Kind == Register && "Invalid access!");
685 return Reg.RegNo;
686 }
687
688 const MCExpr *getImm() const {
689 assert(Kind == Immediate && "Invalid access!");
690 return Imm.Val;
691 }
692
693 const MCExpr *getMemDisp() const {
694 assert(Kind == Memory && "Invalid access!");
695 return Mem.Disp;
696 }
697 unsigned getMemSegReg() const {
698 assert(Kind == Memory && "Invalid access!");
699 return Mem.SegReg;
700 }
701 unsigned getMemBaseReg() const {
702 assert(Kind == Memory && "Invalid access!");
703 return Mem.BaseReg;
704 }
705 unsigned getMemIndexReg() const {
706 assert(Kind == Memory && "Invalid access!");
707 return Mem.IndexReg;
708 }
709 unsigned getMemScale() const {
710 assert(Kind == Memory && "Invalid access!");
711 return Mem.Scale;
712 }
713
714 bool isToken() const {return Kind == Token; }
715
716 bool isImm() const { return Kind == Immediate; }
717
718 bool isImmSExti16i8() const {
719 if (!isImm())
720 return false;
721
722 // If this isn't a constant expr, just assume it fits and let relaxation
723 // handle it.
724 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
725 if (!CE)
726 return true;
727
728 // Otherwise, check the value is in a range that makes sense for this
729 // extension.
730 return isImmSExti16i8Value(CE->getValue());
731 }
732 bool isImmSExti32i8() const {
733 if (!isImm())
734 return false;
735
736 // If this isn't a constant expr, just assume it fits and let relaxation
737 // handle it.
738 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
739 if (!CE)
740 return true;
741
742 // Otherwise, check the value is in a range that makes sense for this
743 // extension.
744 return isImmSExti32i8Value(CE->getValue());
745 }
746 bool isImmZExtu32u8() const {
747 if (!isImm())
748 return false;
749
750 // If this isn't a constant expr, just assume it fits and let relaxation
751 // handle it.
752 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
753 if (!CE)
754 return true;
755
756 // Otherwise, check the value is in a range that makes sense for this
757 // extension.
758 return isImmZExtu32u8Value(CE->getValue());
759 }
760 bool isImmSExti64i8() const {
761 if (!isImm())
762 return false;
763
764 // If this isn't a constant expr, just assume it fits and let relaxation
765 // handle it.
766 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
767 if (!CE)
768 return true;
769
770 // Otherwise, check the value is in a range that makes sense for this
771 // extension.
772 return isImmSExti64i8Value(CE->getValue());
773 }
774 bool isImmSExti64i32() const {
775 if (!isImm())
776 return false;
777
778 // If this isn't a constant expr, just assume it fits and let relaxation
779 // handle it.
780 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
781 if (!CE)
782 return true;
783
784 // Otherwise, check the value is in a range that makes sense for this
785 // extension.
786 return isImmSExti64i32Value(CE->getValue());
787 }
788
789 bool isOffsetOf() const {
790 return OffsetOfLoc.getPointer();
791 }
792
793 bool needAddressOf() const {
794 return AddressOf;
795 }
796
797 bool isMem() const { return Kind == Memory; }
798 bool isMem8() const {
799 return Kind == Memory && (!Mem.Size || Mem.Size == 8);
800 }
801 bool isMem16() const {
802 return Kind == Memory && (!Mem.Size || Mem.Size == 16);
803 }
804 bool isMem32() const {
805 return Kind == Memory && (!Mem.Size || Mem.Size == 32);
806 }
807 bool isMem64() const {
808 return Kind == Memory && (!Mem.Size || Mem.Size == 64);
809 }
810 bool isMem80() const {
811 return Kind == Memory && (!Mem.Size || Mem.Size == 80);
812 }
813 bool isMem128() const {
814 return Kind == Memory && (!Mem.Size || Mem.Size == 128);
815 }
816 bool isMem256() const {
817 return Kind == Memory && (!Mem.Size || Mem.Size == 256);
818 }
819 bool isMem512() const {
820 return Kind == Memory && (!Mem.Size || Mem.Size == 512);
821 }
822
823 bool isMemVX32() const {
824 return Kind == Memory && (!Mem.Size || Mem.Size == 32) &&
825 getMemIndexReg() >= X86::XMM0 && getMemIndexReg() <= X86::XMM15;
826 }
827 bool isMemVY32() const {
828 return Kind == Memory && (!Mem.Size || Mem.Size == 32) &&
829 getMemIndexReg() >= X86::YMM0 && getMemIndexReg() <= X86::YMM15;
830 }
831 bool isMemVX64() const {
832 return Kind == Memory && (!Mem.Size || Mem.Size == 64) &&
833 getMemIndexReg() >= X86::XMM0 && getMemIndexReg() <= X86::XMM15;
834 }
835 bool isMemVY64() const {
836 return Kind == Memory && (!Mem.Size || Mem.Size == 64) &&
837 getMemIndexReg() >= X86::YMM0 && getMemIndexReg() <= X86::YMM15;
838 }
839 bool isMemVZ32() const {
840 return Kind == Memory && (!Mem.Size || Mem.Size == 32) &&
841 getMemIndexReg() >= X86::ZMM0 && getMemIndexReg() <= X86::ZMM31;
842 }
843 bool isMemVZ64() const {
844 return Kind == Memory && (!Mem.Size || Mem.Size == 64) &&
845 getMemIndexReg() >= X86::ZMM0 && getMemIndexReg() <= X86::ZMM31;
846 }
847
848 bool isAbsMem() const {
849 return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
850 !getMemIndexReg() && getMemScale() == 1;
851 }
852
853 bool isMemOffs8() const {
854 return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
855 !getMemIndexReg() && getMemScale() == 1 && (!Mem.Size || Mem.Size == 8);
856 }
857 bool isMemOffs16() const {
858 return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
859 !getMemIndexReg() && getMemScale() == 1 && (!Mem.Size || Mem.Size == 16);
860 }
861 bool isMemOffs32() const {
862 return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
863 !getMemIndexReg() && getMemScale() == 1 && (!Mem.Size || Mem.Size == 32);
864 }
865 bool isMemOffs64() const {
866 return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
867 !getMemIndexReg() && getMemScale() == 1 && (!Mem.Size || Mem.Size == 64);
868 }
869
870 bool isReg() const { return Kind == Register; }
871
872 bool isGR32orGR64() const {
873 return Kind == Register &&
874 (X86MCRegisterClasses[X86::GR32RegClassID].contains(getReg()) ||
875 X86MCRegisterClasses[X86::GR64RegClassID].contains(getReg()));
876 }
877
878 void addExpr(MCInst &Inst, const MCExpr *Expr) const {
879 // Add as immediates when possible.
880 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
881 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
882 else
883 Inst.addOperand(MCOperand::CreateExpr(Expr));
884 }
885
886 void addRegOperands(MCInst &Inst, unsigned N) const {
887 assert(N == 1 && "Invalid number of operands!");
888 Inst.addOperand(MCOperand::CreateReg(getReg()));
889 }
890
891 static unsigned getGR32FromGR64(unsigned RegNo) {
892 switch (RegNo) {
893 default: llvm_unreachable("Unexpected register");
894 case X86::RAX: return X86::EAX;
895 case X86::RCX: return X86::ECX;
896 case X86::RDX: return X86::EDX;
897 case X86::RBX: return X86::EBX;
898 case X86::RBP: return X86::EBP;
899 case X86::RSP: return X86::ESP;
900 case X86::RSI: return X86::ESI;
901 case X86::RDI: return X86::EDI;
902 case X86::R8: return X86::R8D;
903 case X86::R9: return X86::R9D;
904 case X86::R10: return X86::R10D;
905 case X86::R11: return X86::R11D;
906 case X86::R12: return X86::R12D;
907 case X86::R13: return X86::R13D;
908 case X86::R14: return X86::R14D;
909 case X86::R15: return X86::R15D;
910 case X86::RIP: return X86::EIP;
911 }
912 }
913
914 void addGR32orGR64Operands(MCInst &Inst, unsigned N) const {
915 assert(N == 1 && "Invalid number of operands!");
916 unsigned RegNo = getReg();
917 if (X86MCRegisterClasses[X86::GR64RegClassID].contains(RegNo))
918 RegNo = getGR32FromGR64(RegNo);
919 Inst.addOperand(MCOperand::CreateReg(RegNo));
920 }
921
922 void addImmOperands(MCInst &Inst, unsigned N) const {
923 assert(N == 1 && "Invalid number of operands!");
924 addExpr(Inst, getImm());
925 }
926
927 void addMemOperands(MCInst &Inst, unsigned N) const {
928 assert((N == 5) && "Invalid number of operands!");
929 Inst.addOperand(MCOperand::CreateReg(getMemBaseReg()));
930 Inst.addOperand(MCOperand::CreateImm(getMemScale()));
931 Inst.addOperand(MCOperand::CreateReg(getMemIndexReg()));
932 addExpr(Inst, getMemDisp());
933 Inst.addOperand(MCOperand::CreateReg(getMemSegReg()));
934 }
935
936 void addAbsMemOperands(MCInst &Inst, unsigned N) const {
937 assert((N == 1) && "Invalid number of operands!");
938 // Add as immediates when possible.
939 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemDisp()))
940 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
941 else
942 Inst.addOperand(MCOperand::CreateExpr(getMemDisp()));
943 }
944
945 void addMemOffsOperands(MCInst &Inst, unsigned N) const {
946 assert((N == 1) && "Invalid number of operands!");
947 // Add as immediates when possible.
948 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemDisp()))
949 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
950 else
951 Inst.addOperand(MCOperand::CreateExpr(getMemDisp()));
952 }
953
954 static X86Operand *CreateToken(StringRef Str, SMLoc Loc) {
955 SMLoc EndLoc = SMLoc::getFromPointer(Loc.getPointer() + Str.size());
956 X86Operand *Res = new X86Operand(Token, Loc, EndLoc);
957 Res->Tok.Data = Str.data();
958 Res->Tok.Length = Str.size();
959 return Res;
960 }
961
962 static X86Operand *CreateReg(unsigned RegNo, SMLoc StartLoc, SMLoc EndLoc,
963 bool AddressOf = false,
964 SMLoc OffsetOfLoc = SMLoc(),
965 StringRef SymName = StringRef(),
966 void *OpDecl = 0) {
967 X86Operand *Res = new X86Operand(Register, StartLoc, EndLoc);
968 Res->Reg.RegNo = RegNo;
969 Res->AddressOf = AddressOf;
970 Res->OffsetOfLoc = OffsetOfLoc;
971 Res->SymName = SymName;
972 Res->OpDecl = OpDecl;
973 return Res;
974 }
975
976 static X86Operand *CreateImm(const MCExpr *Val, SMLoc StartLoc, SMLoc EndLoc){
977 X86Operand *Res = new X86Operand(Immediate, StartLoc, EndLoc);
978 Res->Imm.Val = Val;
979 return Res;
980 }
981
982 /// Create an absolute memory operand.
983 static X86Operand *CreateMem(const MCExpr *Disp, SMLoc StartLoc, SMLoc EndLoc,
984 unsigned Size = 0, StringRef SymName = StringRef(),
985 void *OpDecl = 0) {
986 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
987 Res->Mem.SegReg = 0;
988 Res->Mem.Disp = Disp;
989 Res->Mem.BaseReg = 0;
990 Res->Mem.IndexReg = 0;
991 Res->Mem.Scale = 1;
992 Res->Mem.Size = Size;
993 Res->SymName = SymName;
994 Res->OpDecl = OpDecl;
995 Res->AddressOf = false;
996 return Res;
997 }
998
999 /// Create a generalized memory operand.
1000 static X86Operand *CreateMem(unsigned SegReg, const MCExpr *Disp,
1001 unsigned BaseReg, unsigned IndexReg,
1002 unsigned Scale, SMLoc StartLoc, SMLoc EndLoc,
1003 unsigned Size = 0,
1004 StringRef SymName = StringRef(),
1005 void *OpDecl = 0) {
1006 // We should never just have a displacement, that should be parsed as an
1007 // absolute memory operand.
1008 assert((SegReg || BaseReg || IndexReg) && "Invalid memory operand!");
1009
1010 // The scale should always be one of {1,2,4,8}.
1011 assert(((Scale == 1 || Scale == 2 || Scale == 4 || Scale == 8)) &&
1012 "Invalid scale!");
1013 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
1014 Res->Mem.SegReg = SegReg;
1015 Res->Mem.Disp = Disp;
1016 Res->Mem.BaseReg = BaseReg;
1017 Res->Mem.IndexReg = IndexReg;
1018 Res->Mem.Scale = Scale;
1019 Res->Mem.Size = Size;
1020 Res->SymName = SymName;
1021 Res->OpDecl = OpDecl;
1022 Res->AddressOf = false;
1023 return Res;
1024 }
1025};
1026
1027} // end anonymous namespace.
1028
1029bool X86AsmParser::isSrcOp(X86Operand &Op) {
1030 unsigned basereg = is64BitMode() ? X86::RSI : X86::ESI;
1031
1032 return (Op.isMem() &&
1033 (Op.Mem.SegReg == 0 || Op.Mem.SegReg == X86::DS) &&
1034 isa<MCConstantExpr>(Op.Mem.Disp) &&
1035 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1036 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0);
1037}
1038
1039bool X86AsmParser::isDstOp(X86Operand &Op) {
1040 unsigned basereg = is64BitMode() ? X86::RDI : X86::EDI;
1041
1042 return Op.isMem() &&
1043 (Op.Mem.SegReg == 0 || Op.Mem.SegReg == X86::ES) &&
1044 isa<MCConstantExpr>(Op.Mem.Disp) &&
1045 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1046 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0;
1047}
1048
1049bool X86AsmParser::ParseRegister(unsigned &RegNo,
1050 SMLoc &StartLoc, SMLoc &EndLoc) {
1051 RegNo = 0;
1052 const AsmToken &PercentTok = Parser.getTok();
1053 StartLoc = PercentTok.getLoc();
1054
1055 // If we encounter a %, ignore it. This code handles registers with and
1056 // without the prefix, unprefixed registers can occur in cfi directives.
1057 if (!isParsingIntelSyntax() && PercentTok.is(AsmToken::Percent))
1058 Parser.Lex(); // Eat percent token.
1059
1060 const AsmToken &Tok = Parser.getTok();
1061 EndLoc = Tok.getEndLoc();
1062
1063 if (Tok.isNot(AsmToken::Identifier)) {
1064 if (isParsingIntelSyntax()) return true;
1065 return Error(StartLoc, "invalid register name",
1066 SMRange(StartLoc, EndLoc));
1067 }
1068
1069 RegNo = MatchRegisterName(Tok.getString());
1070
1071 // If the match failed, try the register name as lowercase.
1072 if (RegNo == 0)
1073 RegNo = MatchRegisterName(Tok.getString().lower());
1074
1075 if (!is64BitMode()) {
1076 // FIXME: This should be done using Requires<In32BitMode> and
1077 // Requires<In64BitMode> so "eiz" usage in 64-bit instructions can be also
1078 // checked.
1079 // FIXME: Check AH, CH, DH, BH cannot be used in an instruction requiring a
1080 // REX prefix.
1081 if (RegNo == X86::RIZ ||
1082 X86MCRegisterClasses[X86::GR64RegClassID].contains(RegNo) ||
1083 X86II::isX86_64NonExtLowByteReg(RegNo) ||
1084 X86II::isX86_64ExtendedReg(RegNo))
1085 return Error(StartLoc, "register %"
1086 + Tok.getString() + " is only available in 64-bit mode",
1087 SMRange(StartLoc, EndLoc));
1088 }
1089
1090 // Parse "%st" as "%st(0)" and "%st(1)", which is multiple tokens.
1091 if (RegNo == 0 && (Tok.getString() == "st" || Tok.getString() == "ST")) {
1092 RegNo = X86::ST0;
1093 Parser.Lex(); // Eat 'st'
1094
1095 // Check to see if we have '(4)' after %st.
1096 if (getLexer().isNot(AsmToken::LParen))
1097 return false;
1098 // Lex the paren.
1099 getParser().Lex();
1100
1101 const AsmToken &IntTok = Parser.getTok();
1102 if (IntTok.isNot(AsmToken::Integer))
1103 return Error(IntTok.getLoc(), "expected stack index");
1104 switch (IntTok.getIntVal()) {
1105 case 0: RegNo = X86::ST0; break;
1106 case 1: RegNo = X86::ST1; break;
1107 case 2: RegNo = X86::ST2; break;
1108 case 3: RegNo = X86::ST3; break;
1109 case 4: RegNo = X86::ST4; break;
1110 case 5: RegNo = X86::ST5; break;
1111 case 6: RegNo = X86::ST6; break;
1112 case 7: RegNo = X86::ST7; break;
1113 default: return Error(IntTok.getLoc(), "invalid stack index");
1114 }
1115
1116 if (getParser().Lex().isNot(AsmToken::RParen))
1117 return Error(Parser.getTok().getLoc(), "expected ')'");
1118
1119 EndLoc = Parser.getTok().getEndLoc();
1120 Parser.Lex(); // Eat ')'
1121 return false;
1122 }
1123
1124 EndLoc = Parser.getTok().getEndLoc();
1125
1126 // If this is "db[0-7]", match it as an alias
1127 // for dr[0-7].
1128 if (RegNo == 0 && Tok.getString().size() == 3 &&
1129 Tok.getString().startswith("db")) {
1130 switch (Tok.getString()[2]) {
1131 case '0': RegNo = X86::DR0; break;
1132 case '1': RegNo = X86::DR1; break;
1133 case '2': RegNo = X86::DR2; break;
1134 case '3': RegNo = X86::DR3; break;
1135 case '4': RegNo = X86::DR4; break;
1136 case '5': RegNo = X86::DR5; break;
1137 case '6': RegNo = X86::DR6; break;
1138 case '7': RegNo = X86::DR7; break;
1139 }
1140
1141 if (RegNo != 0) {
1142 EndLoc = Parser.getTok().getEndLoc();
1143 Parser.Lex(); // Eat it.
1144 return false;
1145 }
1146 }
1147
1148 if (RegNo == 0) {
1149 if (isParsingIntelSyntax()) return true;
1150 return Error(StartLoc, "invalid register name",
1151 SMRange(StartLoc, EndLoc));
1152 }
1153
1154 Parser.Lex(); // Eat identifier token.
1155 return false;
1156}
1157
1158X86Operand *X86AsmParser::ParseOperand() {
1159 if (isParsingIntelSyntax())
1160 return ParseIntelOperand();
1161 return ParseATTOperand();
1162}
1163
1164/// getIntelMemOperandSize - Return intel memory operand size.
1165static unsigned getIntelMemOperandSize(StringRef OpStr) {
1166 unsigned Size = StringSwitch<unsigned>(OpStr)
1167 .Cases("BYTE", "byte", 8)
1168 .Cases("WORD", "word", 16)
1169 .Cases("DWORD", "dword", 32)
1170 .Cases("QWORD", "qword", 64)
1171 .Cases("XWORD", "xword", 80)
1172 .Cases("XMMWORD", "xmmword", 128)
1173 .Cases("YMMWORD", "ymmword", 256)
1174 .Default(0);
1175 return Size;
1176}
1177
1178X86Operand *
1179X86AsmParser::CreateMemForInlineAsm(unsigned SegReg, const MCExpr *Disp,
1180 unsigned BaseReg, unsigned IndexReg,
1181 unsigned Scale, SMLoc Start, SMLoc End,
1182 unsigned Size, StringRef Identifier,
1183 InlineAsmIdentifierInfo &Info){
1//===-- 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
10#include "MCTargetDesc/X86BaseInfo.h"
11#include "llvm/ADT/APFloat.h"
12#include "llvm/ADT/STLExtras.h"
13#include "llvm/ADT/SmallString.h"
14#include "llvm/ADT/SmallVector.h"
15#include "llvm/ADT/StringSwitch.h"
16#include "llvm/ADT/Twine.h"
17#include "llvm/MC/MCContext.h"
18#include "llvm/MC/MCExpr.h"
19#include "llvm/MC/MCInst.h"
20#include "llvm/MC/MCParser/MCAsmLexer.h"
21#include "llvm/MC/MCParser/MCAsmParser.h"
22#include "llvm/MC/MCParser/MCParsedAsmOperand.h"
23#include "llvm/MC/MCRegisterInfo.h"
24#include "llvm/MC/MCStreamer.h"
25#include "llvm/MC/MCSubtargetInfo.h"
26#include "llvm/MC/MCSymbol.h"
27#include "llvm/MC/MCTargetAsmParser.h"
28#include "llvm/Support/SourceMgr.h"
29#include "llvm/Support/TargetRegistry.h"
30#include "llvm/Support/raw_ostream.h"
31
32using namespace llvm;
33
34namespace {
35struct X86Operand;
36
37static const char OpPrecedence[] = {
38 0, // IC_PLUS
39 0, // IC_MINUS
40 1, // IC_MULTIPLY
41 1, // IC_DIVIDE
42 2, // IC_RPAREN
43 3, // IC_LPAREN
44 0, // IC_IMM
45 0 // IC_REGISTER
46};
47
48class X86AsmParser : public MCTargetAsmParser {
49 MCSubtargetInfo &STI;
50 MCAsmParser &Parser;
51 ParseInstructionInfo *InstInfo;
52private:
53 enum InfixCalculatorTok {
54 IC_PLUS = 0,
55 IC_MINUS,
56 IC_MULTIPLY,
57 IC_DIVIDE,
58 IC_RPAREN,
59 IC_LPAREN,
60 IC_IMM,
61 IC_REGISTER
62 };
63
64 class InfixCalculator {
65 typedef std::pair< InfixCalculatorTok, int64_t > ICToken;
66 SmallVector<InfixCalculatorTok, 4> InfixOperatorStack;
67 SmallVector<ICToken, 4> PostfixStack;
68
69 public:
70 int64_t popOperand() {
71 assert (!PostfixStack.empty() && "Poped an empty stack!");
72 ICToken Op = PostfixStack.pop_back_val();
73 assert ((Op.first == IC_IMM || Op.first == IC_REGISTER)
74 && "Expected and immediate or register!");
75 return Op.second;
76 }
77 void pushOperand(InfixCalculatorTok Op, int64_t Val = 0) {
78 assert ((Op == IC_IMM || Op == IC_REGISTER) &&
79 "Unexpected operand!");
80 PostfixStack.push_back(std::make_pair(Op, Val));
81 }
82
83 void popOperator() { InfixOperatorStack.pop_back(); }
84 void pushOperator(InfixCalculatorTok Op) {
85 // Push the new operator if the stack is empty.
86 if (InfixOperatorStack.empty()) {
87 InfixOperatorStack.push_back(Op);
88 return;
89 }
90
91 // Push the new operator if it has a higher precedence than the operator
92 // on the top of the stack or the operator on the top of the stack is a
93 // left parentheses.
94 unsigned Idx = InfixOperatorStack.size() - 1;
95 InfixCalculatorTok StackOp = InfixOperatorStack[Idx];
96 if (OpPrecedence[Op] > OpPrecedence[StackOp] || StackOp == IC_LPAREN) {
97 InfixOperatorStack.push_back(Op);
98 return;
99 }
100
101 // The operator on the top of the stack has higher precedence than the
102 // new operator.
103 unsigned ParenCount = 0;
104 while (1) {
105 // Nothing to process.
106 if (InfixOperatorStack.empty())
107 break;
108
109 Idx = InfixOperatorStack.size() - 1;
110 StackOp = InfixOperatorStack[Idx];
111 if (!(OpPrecedence[StackOp] >= OpPrecedence[Op] || ParenCount))
112 break;
113
114 // If we have an even parentheses count and we see a left parentheses,
115 // then stop processing.
116 if (!ParenCount && StackOp == IC_LPAREN)
117 break;
118
119 if (StackOp == IC_RPAREN) {
120 ++ParenCount;
121 InfixOperatorStack.pop_back();
122 } else if (StackOp == IC_LPAREN) {
123 --ParenCount;
124 InfixOperatorStack.pop_back();
125 } else {
126 InfixOperatorStack.pop_back();
127 PostfixStack.push_back(std::make_pair(StackOp, 0));
128 }
129 }
130 // Push the new operator.
131 InfixOperatorStack.push_back(Op);
132 }
133 int64_t execute() {
134 // Push any remaining operators onto the postfix stack.
135 while (!InfixOperatorStack.empty()) {
136 InfixCalculatorTok StackOp = InfixOperatorStack.pop_back_val();
137 if (StackOp != IC_LPAREN && StackOp != IC_RPAREN)
138 PostfixStack.push_back(std::make_pair(StackOp, 0));
139 }
140
141 if (PostfixStack.empty())
142 return 0;
143
144 SmallVector<ICToken, 16> OperandStack;
145 for (unsigned i = 0, e = PostfixStack.size(); i != e; ++i) {
146 ICToken Op = PostfixStack[i];
147 if (Op.first == IC_IMM || Op.first == IC_REGISTER) {
148 OperandStack.push_back(Op);
149 } else {
150 assert (OperandStack.size() > 1 && "Too few operands.");
151 int64_t Val;
152 ICToken Op2 = OperandStack.pop_back_val();
153 ICToken Op1 = OperandStack.pop_back_val();
154 switch (Op.first) {
155 default:
156 report_fatal_error("Unexpected operator!");
157 break;
158 case IC_PLUS:
159 Val = Op1.second + Op2.second;
160 OperandStack.push_back(std::make_pair(IC_IMM, Val));
161 break;
162 case IC_MINUS:
163 Val = Op1.second - Op2.second;
164 OperandStack.push_back(std::make_pair(IC_IMM, Val));
165 break;
166 case IC_MULTIPLY:
167 assert (Op1.first == IC_IMM && Op2.first == IC_IMM &&
168 "Multiply operation with an immediate and a register!");
169 Val = Op1.second * Op2.second;
170 OperandStack.push_back(std::make_pair(IC_IMM, Val));
171 break;
172 case IC_DIVIDE:
173 assert (Op1.first == IC_IMM && Op2.first == IC_IMM &&
174 "Divide operation with an immediate and a register!");
175 assert (Op2.second != 0 && "Division by zero!");
176 Val = Op1.second / Op2.second;
177 OperandStack.push_back(std::make_pair(IC_IMM, Val));
178 break;
179 }
180 }
181 }
182 assert (OperandStack.size() == 1 && "Expected a single result.");
183 return OperandStack.pop_back_val().second;
184 }
185 };
186
187 enum IntelExprState {
188 IES_PLUS,
189 IES_MINUS,
190 IES_MULTIPLY,
191 IES_DIVIDE,
192 IES_LBRAC,
193 IES_RBRAC,
194 IES_LPAREN,
195 IES_RPAREN,
196 IES_REGISTER,
197 IES_INTEGER,
198 IES_IDENTIFIER,
199 IES_ERROR
200 };
201
202 class IntelExprStateMachine {
203 IntelExprState State, PrevState;
204 unsigned BaseReg, IndexReg, TmpReg, Scale;
205 int64_t Imm;
206 const MCExpr *Sym;
207 StringRef SymName;
208 bool StopOnLBrac, AddImmPrefix;
209 InfixCalculator IC;
210 InlineAsmIdentifierInfo Info;
211 public:
212 IntelExprStateMachine(int64_t imm, bool stoponlbrac, bool addimmprefix) :
213 State(IES_PLUS), PrevState(IES_ERROR), BaseReg(0), IndexReg(0), TmpReg(0),
214 Scale(1), Imm(imm), Sym(0), StopOnLBrac(stoponlbrac),
215 AddImmPrefix(addimmprefix) { Info.clear(); }
216
217 unsigned getBaseReg() { return BaseReg; }
218 unsigned getIndexReg() { return IndexReg; }
219 unsigned getScale() { return Scale; }
220 const MCExpr *getSym() { return Sym; }
221 StringRef getSymName() { return SymName; }
222 int64_t getImm() { return Imm + IC.execute(); }
223 bool isValidEndState() {
224 return State == IES_RBRAC || State == IES_INTEGER;
225 }
226 bool getStopOnLBrac() { return StopOnLBrac; }
227 bool getAddImmPrefix() { return AddImmPrefix; }
228 bool hadError() { return State == IES_ERROR; }
229
230 InlineAsmIdentifierInfo &getIdentifierInfo() {
231 return Info;
232 }
233
234 void onPlus() {
235 IntelExprState CurrState = State;
236 switch (State) {
237 default:
238 State = IES_ERROR;
239 break;
240 case IES_INTEGER:
241 case IES_RPAREN:
242 case IES_REGISTER:
243 State = IES_PLUS;
244 IC.pushOperator(IC_PLUS);
245 if (CurrState == IES_REGISTER && PrevState != IES_MULTIPLY) {
246 // If we already have a BaseReg, then assume this is the IndexReg with
247 // a scale of 1.
248 if (!BaseReg) {
249 BaseReg = TmpReg;
250 } else {
251 assert (!IndexReg && "BaseReg/IndexReg already set!");
252 IndexReg = TmpReg;
253 Scale = 1;
254 }
255 }
256 break;
257 }
258 PrevState = CurrState;
259 }
260 void onMinus() {
261 IntelExprState CurrState = State;
262 switch (State) {
263 default:
264 State = IES_ERROR;
265 break;
266 case IES_PLUS:
267 case IES_MULTIPLY:
268 case IES_DIVIDE:
269 case IES_LPAREN:
270 case IES_RPAREN:
271 case IES_LBRAC:
272 case IES_RBRAC:
273 case IES_INTEGER:
274 case IES_REGISTER:
275 State = IES_MINUS;
276 // Only push the minus operator if it is not a unary operator.
277 if (!(CurrState == IES_PLUS || CurrState == IES_MINUS ||
278 CurrState == IES_MULTIPLY || CurrState == IES_DIVIDE ||
279 CurrState == IES_LPAREN || CurrState == IES_LBRAC))
280 IC.pushOperator(IC_MINUS);
281 if (CurrState == IES_REGISTER && PrevState != IES_MULTIPLY) {
282 // If we already have a BaseReg, then assume this is the IndexReg with
283 // a scale of 1.
284 if (!BaseReg) {
285 BaseReg = TmpReg;
286 } else {
287 assert (!IndexReg && "BaseReg/IndexReg already set!");
288 IndexReg = TmpReg;
289 Scale = 1;
290 }
291 }
292 break;
293 }
294 PrevState = CurrState;
295 }
296 void onRegister(unsigned Reg) {
297 IntelExprState CurrState = State;
298 switch (State) {
299 default:
300 State = IES_ERROR;
301 break;
302 case IES_PLUS:
303 case IES_LPAREN:
304 State = IES_REGISTER;
305 TmpReg = Reg;
306 IC.pushOperand(IC_REGISTER);
307 break;
308 case IES_MULTIPLY:
309 // Index Register - Scale * Register
310 if (PrevState == IES_INTEGER) {
311 assert (!IndexReg && "IndexReg already set!");
312 State = IES_REGISTER;
313 IndexReg = Reg;
314 // Get the scale and replace the 'Scale * Register' with '0'.
315 Scale = IC.popOperand();
316 IC.pushOperand(IC_IMM);
317 IC.popOperator();
318 } else {
319 State = IES_ERROR;
320 }
321 break;
322 }
323 PrevState = CurrState;
324 }
325 void onIdentifierExpr(const MCExpr *SymRef, StringRef SymRefName) {
326 PrevState = State;
327 switch (State) {
328 default:
329 State = IES_ERROR;
330 break;
331 case IES_PLUS:
332 case IES_MINUS:
333 State = IES_INTEGER;
334 Sym = SymRef;
335 SymName = SymRefName;
336 IC.pushOperand(IC_IMM);
337 break;
338 }
339 }
340 void onInteger(int64_t TmpInt) {
341 IntelExprState CurrState = State;
342 switch (State) {
343 default:
344 State = IES_ERROR;
345 break;
346 case IES_PLUS:
347 case IES_MINUS:
348 case IES_DIVIDE:
349 case IES_MULTIPLY:
350 case IES_LPAREN:
351 State = IES_INTEGER;
352 if (PrevState == IES_REGISTER && CurrState == IES_MULTIPLY) {
353 // Index Register - Register * Scale
354 assert (!IndexReg && "IndexReg already set!");
355 IndexReg = TmpReg;
356 Scale = TmpInt;
357 // Get the scale and replace the 'Register * Scale' with '0'.
358 IC.popOperator();
359 } else if ((PrevState == IES_PLUS || PrevState == IES_MINUS ||
360 PrevState == IES_MULTIPLY || PrevState == IES_DIVIDE ||
361 PrevState == IES_LPAREN || PrevState == IES_LBRAC) &&
362 CurrState == IES_MINUS) {
363 // Unary minus. No need to pop the minus operand because it was never
364 // pushed.
365 IC.pushOperand(IC_IMM, -TmpInt); // Push -Imm.
366 } else {
367 IC.pushOperand(IC_IMM, TmpInt);
368 }
369 break;
370 }
371 PrevState = CurrState;
372 }
373 void onStar() {
374 PrevState = State;
375 switch (State) {
376 default:
377 State = IES_ERROR;
378 break;
379 case IES_INTEGER:
380 case IES_REGISTER:
381 case IES_RPAREN:
382 State = IES_MULTIPLY;
383 IC.pushOperator(IC_MULTIPLY);
384 break;
385 }
386 }
387 void onDivide() {
388 PrevState = State;
389 switch (State) {
390 default:
391 State = IES_ERROR;
392 break;
393 case IES_INTEGER:
394 case IES_RPAREN:
395 State = IES_DIVIDE;
396 IC.pushOperator(IC_DIVIDE);
397 break;
398 }
399 }
400 void onLBrac() {
401 PrevState = State;
402 switch (State) {
403 default:
404 State = IES_ERROR;
405 break;
406 case IES_RBRAC:
407 State = IES_PLUS;
408 IC.pushOperator(IC_PLUS);
409 break;
410 }
411 }
412 void onRBrac() {
413 IntelExprState CurrState = State;
414 switch (State) {
415 default:
416 State = IES_ERROR;
417 break;
418 case IES_INTEGER:
419 case IES_REGISTER:
420 case IES_RPAREN:
421 State = IES_RBRAC;
422 if (CurrState == IES_REGISTER && PrevState != IES_MULTIPLY) {
423 // If we already have a BaseReg, then assume this is the IndexReg with
424 // a scale of 1.
425 if (!BaseReg) {
426 BaseReg = TmpReg;
427 } else {
428 assert (!IndexReg && "BaseReg/IndexReg already set!");
429 IndexReg = TmpReg;
430 Scale = 1;
431 }
432 }
433 break;
434 }
435 PrevState = CurrState;
436 }
437 void onLParen() {
438 IntelExprState CurrState = State;
439 switch (State) {
440 default:
441 State = IES_ERROR;
442 break;
443 case IES_PLUS:
444 case IES_MINUS:
445 case IES_MULTIPLY:
446 case IES_DIVIDE:
447 case IES_LPAREN:
448 // FIXME: We don't handle this type of unary minus, yet.
449 if ((PrevState == IES_PLUS || PrevState == IES_MINUS ||
450 PrevState == IES_MULTIPLY || PrevState == IES_DIVIDE ||
451 PrevState == IES_LPAREN || PrevState == IES_LBRAC) &&
452 CurrState == IES_MINUS) {
453 State = IES_ERROR;
454 break;
455 }
456 State = IES_LPAREN;
457 IC.pushOperator(IC_LPAREN);
458 break;
459 }
460 PrevState = CurrState;
461 }
462 void onRParen() {
463 PrevState = State;
464 switch (State) {
465 default:
466 State = IES_ERROR;
467 break;
468 case IES_INTEGER:
469 case IES_REGISTER:
470 case IES_RPAREN:
471 State = IES_RPAREN;
472 IC.pushOperator(IC_RPAREN);
473 break;
474 }
475 }
476 };
477
478 MCAsmParser &getParser() const { return Parser; }
479
480 MCAsmLexer &getLexer() const { return Parser.getLexer(); }
481
482 bool Error(SMLoc L, const Twine &Msg,
483 ArrayRef<SMRange> Ranges = None,
484 bool MatchingInlineAsm = false) {
485 if (MatchingInlineAsm) return true;
486 return Parser.Error(L, Msg, Ranges);
487 }
488
489 X86Operand *ErrorOperand(SMLoc Loc, StringRef Msg) {
490 Error(Loc, Msg);
491 return 0;
492 }
493
494 X86Operand *ParseOperand();
495 X86Operand *ParseATTOperand();
496 X86Operand *ParseIntelOperand();
497 X86Operand *ParseIntelOffsetOfOperator();
498 bool ParseIntelDotOperator(const MCExpr *Disp, const MCExpr *&NewDisp);
499 X86Operand *ParseIntelOperator(unsigned OpKind);
500 X86Operand *ParseIntelSegmentOverride(unsigned SegReg, SMLoc Start, unsigned Size);
501 X86Operand *ParseIntelMemOperand(int64_t ImmDisp, SMLoc StartLoc,
502 unsigned Size);
503 bool ParseIntelExpression(IntelExprStateMachine &SM, SMLoc &End);
504 X86Operand *ParseIntelBracExpression(unsigned SegReg, SMLoc Start,
505 int64_t ImmDisp, unsigned Size);
506 bool ParseIntelIdentifier(const MCExpr *&Val, StringRef &Identifier,
507 InlineAsmIdentifierInfo &Info,
508 bool IsUnevaluatedOperand, SMLoc &End);
509
510 X86Operand *ParseMemOperand(unsigned SegReg, SMLoc StartLoc);
511
512 X86Operand *CreateMemForInlineAsm(unsigned SegReg, const MCExpr *Disp,
513 unsigned BaseReg, unsigned IndexReg,
514 unsigned Scale, SMLoc Start, SMLoc End,
515 unsigned Size, StringRef Identifier,
516 InlineAsmIdentifierInfo &Info);
517
518 bool ParseDirectiveWord(unsigned Size, SMLoc L);
519 bool ParseDirectiveCode(StringRef IDVal, SMLoc L);
520
521 bool processInstruction(MCInst &Inst,
522 const SmallVectorImpl<MCParsedAsmOperand*> &Ops);
523
524 bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
525 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
526 MCStreamer &Out, unsigned &ErrorInfo,
527 bool MatchingInlineAsm);
528
529 /// isSrcOp - Returns true if operand is either (%rsi) or %ds:%(rsi)
530 /// in 64bit mode or (%esi) or %es:(%esi) in 32bit mode.
531 bool isSrcOp(X86Operand &Op);
532
533 /// isDstOp - Returns true if operand is either (%rdi) or %es:(%rdi)
534 /// in 64bit mode or (%edi) or %es:(%edi) in 32bit mode.
535 bool isDstOp(X86Operand &Op);
536
537 bool is64BitMode() const {
538 // FIXME: Can tablegen auto-generate this?
539 return (STI.getFeatureBits() & X86::Mode64Bit) != 0;
540 }
541 void SwitchMode() {
542 unsigned FB = ComputeAvailableFeatures(STI.ToggleFeature(X86::Mode64Bit));
543 setAvailableFeatures(FB);
544 }
545
546 bool isParsingIntelSyntax() {
547 return getParser().getAssemblerDialect();
548 }
549
550 /// @name Auto-generated Matcher Functions
551 /// {
552
553#define GET_ASSEMBLER_HEADER
554#include "X86GenAsmMatcher.inc"
555
556 /// }
557
558public:
559 X86AsmParser(MCSubtargetInfo &sti, MCAsmParser &parser,
560 const MCInstrInfo &MII)
561 : MCTargetAsmParser(), STI(sti), Parser(parser), InstInfo(0) {
562
563 // Initialize the set of available features.
564 setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
565 }
566 virtual bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc);
567
568 virtual bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
569 SMLoc NameLoc,
570 SmallVectorImpl<MCParsedAsmOperand*> &Operands);
571
572 virtual bool ParseDirective(AsmToken DirectiveID);
573};
574} // end anonymous namespace
575
576/// @name Auto-generated Match Functions
577/// {
578
579static unsigned MatchRegisterName(StringRef Name);
580
581/// }
582
583static bool isImmSExti16i8Value(uint64_t Value) {
584 return (( Value <= 0x000000000000007FULL)||
585 (0x000000000000FF80ULL <= Value && Value <= 0x000000000000FFFFULL)||
586 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
587}
588
589static bool isImmSExti32i8Value(uint64_t Value) {
590 return (( Value <= 0x000000000000007FULL)||
591 (0x00000000FFFFFF80ULL <= Value && Value <= 0x00000000FFFFFFFFULL)||
592 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
593}
594
595static bool isImmZExtu32u8Value(uint64_t Value) {
596 return (Value <= 0x00000000000000FFULL);
597}
598
599static bool isImmSExti64i8Value(uint64_t Value) {
600 return (( Value <= 0x000000000000007FULL)||
601 (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
602}
603
604static bool isImmSExti64i32Value(uint64_t Value) {
605 return (( Value <= 0x000000007FFFFFFFULL)||
606 (0xFFFFFFFF80000000ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
607}
608namespace {
609
610/// X86Operand - Instances of this class represent a parsed X86 machine
611/// instruction.
612struct X86Operand : public MCParsedAsmOperand {
613 enum KindTy {
614 Token,
615 Register,
616 Immediate,
617 Memory
618 } Kind;
619
620 SMLoc StartLoc, EndLoc;
621 SMLoc OffsetOfLoc;
622 StringRef SymName;
623 void *OpDecl;
624 bool AddressOf;
625
626 struct TokOp {
627 const char *Data;
628 unsigned Length;
629 };
630
631 struct RegOp {
632 unsigned RegNo;
633 };
634
635 struct ImmOp {
636 const MCExpr *Val;
637 };
638
639 struct MemOp {
640 unsigned SegReg;
641 const MCExpr *Disp;
642 unsigned BaseReg;
643 unsigned IndexReg;
644 unsigned Scale;
645 unsigned Size;
646 };
647
648 union {
649 struct TokOp Tok;
650 struct RegOp Reg;
651 struct ImmOp Imm;
652 struct MemOp Mem;
653 };
654
655 X86Operand(KindTy K, SMLoc Start, SMLoc End)
656 : Kind(K), StartLoc(Start), EndLoc(End) {}
657
658 StringRef getSymName() { return SymName; }
659 void *getOpDecl() { return OpDecl; }
660
661 /// getStartLoc - Get the location of the first token of this operand.
662 SMLoc getStartLoc() const { return StartLoc; }
663 /// getEndLoc - Get the location of the last token of this operand.
664 SMLoc getEndLoc() const { return EndLoc; }
665 /// getLocRange - Get the range between the first and last token of this
666 /// operand.
667 SMRange getLocRange() const { return SMRange(StartLoc, EndLoc); }
668 /// getOffsetOfLoc - Get the location of the offset operator.
669 SMLoc getOffsetOfLoc() const { return OffsetOfLoc; }
670
671 virtual void print(raw_ostream &OS) const {}
672
673 StringRef getToken() const {
674 assert(Kind == Token && "Invalid access!");
675 return StringRef(Tok.Data, Tok.Length);
676 }
677 void setTokenValue(StringRef Value) {
678 assert(Kind == Token && "Invalid access!");
679 Tok.Data = Value.data();
680 Tok.Length = Value.size();
681 }
682
683 unsigned getReg() const {
684 assert(Kind == Register && "Invalid access!");
685 return Reg.RegNo;
686 }
687
688 const MCExpr *getImm() const {
689 assert(Kind == Immediate && "Invalid access!");
690 return Imm.Val;
691 }
692
693 const MCExpr *getMemDisp() const {
694 assert(Kind == Memory && "Invalid access!");
695 return Mem.Disp;
696 }
697 unsigned getMemSegReg() const {
698 assert(Kind == Memory && "Invalid access!");
699 return Mem.SegReg;
700 }
701 unsigned getMemBaseReg() const {
702 assert(Kind == Memory && "Invalid access!");
703 return Mem.BaseReg;
704 }
705 unsigned getMemIndexReg() const {
706 assert(Kind == Memory && "Invalid access!");
707 return Mem.IndexReg;
708 }
709 unsigned getMemScale() const {
710 assert(Kind == Memory && "Invalid access!");
711 return Mem.Scale;
712 }
713
714 bool isToken() const {return Kind == Token; }
715
716 bool isImm() const { return Kind == Immediate; }
717
718 bool isImmSExti16i8() const {
719 if (!isImm())
720 return false;
721
722 // If this isn't a constant expr, just assume it fits and let relaxation
723 // handle it.
724 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
725 if (!CE)
726 return true;
727
728 // Otherwise, check the value is in a range that makes sense for this
729 // extension.
730 return isImmSExti16i8Value(CE->getValue());
731 }
732 bool isImmSExti32i8() const {
733 if (!isImm())
734 return false;
735
736 // If this isn't a constant expr, just assume it fits and let relaxation
737 // handle it.
738 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
739 if (!CE)
740 return true;
741
742 // Otherwise, check the value is in a range that makes sense for this
743 // extension.
744 return isImmSExti32i8Value(CE->getValue());
745 }
746 bool isImmZExtu32u8() const {
747 if (!isImm())
748 return false;
749
750 // If this isn't a constant expr, just assume it fits and let relaxation
751 // handle it.
752 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
753 if (!CE)
754 return true;
755
756 // Otherwise, check the value is in a range that makes sense for this
757 // extension.
758 return isImmZExtu32u8Value(CE->getValue());
759 }
760 bool isImmSExti64i8() const {
761 if (!isImm())
762 return false;
763
764 // If this isn't a constant expr, just assume it fits and let relaxation
765 // handle it.
766 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
767 if (!CE)
768 return true;
769
770 // Otherwise, check the value is in a range that makes sense for this
771 // extension.
772 return isImmSExti64i8Value(CE->getValue());
773 }
774 bool isImmSExti64i32() const {
775 if (!isImm())
776 return false;
777
778 // If this isn't a constant expr, just assume it fits and let relaxation
779 // handle it.
780 const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
781 if (!CE)
782 return true;
783
784 // Otherwise, check the value is in a range that makes sense for this
785 // extension.
786 return isImmSExti64i32Value(CE->getValue());
787 }
788
789 bool isOffsetOf() const {
790 return OffsetOfLoc.getPointer();
791 }
792
793 bool needAddressOf() const {
794 return AddressOf;
795 }
796
797 bool isMem() const { return Kind == Memory; }
798 bool isMem8() const {
799 return Kind == Memory && (!Mem.Size || Mem.Size == 8);
800 }
801 bool isMem16() const {
802 return Kind == Memory && (!Mem.Size || Mem.Size == 16);
803 }
804 bool isMem32() const {
805 return Kind == Memory && (!Mem.Size || Mem.Size == 32);
806 }
807 bool isMem64() const {
808 return Kind == Memory && (!Mem.Size || Mem.Size == 64);
809 }
810 bool isMem80() const {
811 return Kind == Memory && (!Mem.Size || Mem.Size == 80);
812 }
813 bool isMem128() const {
814 return Kind == Memory && (!Mem.Size || Mem.Size == 128);
815 }
816 bool isMem256() const {
817 return Kind == Memory && (!Mem.Size || Mem.Size == 256);
818 }
819 bool isMem512() const {
820 return Kind == Memory && (!Mem.Size || Mem.Size == 512);
821 }
822
823 bool isMemVX32() const {
824 return Kind == Memory && (!Mem.Size || Mem.Size == 32) &&
825 getMemIndexReg() >= X86::XMM0 && getMemIndexReg() <= X86::XMM15;
826 }
827 bool isMemVY32() const {
828 return Kind == Memory && (!Mem.Size || Mem.Size == 32) &&
829 getMemIndexReg() >= X86::YMM0 && getMemIndexReg() <= X86::YMM15;
830 }
831 bool isMemVX64() const {
832 return Kind == Memory && (!Mem.Size || Mem.Size == 64) &&
833 getMemIndexReg() >= X86::XMM0 && getMemIndexReg() <= X86::XMM15;
834 }
835 bool isMemVY64() const {
836 return Kind == Memory && (!Mem.Size || Mem.Size == 64) &&
837 getMemIndexReg() >= X86::YMM0 && getMemIndexReg() <= X86::YMM15;
838 }
839 bool isMemVZ32() const {
840 return Kind == Memory && (!Mem.Size || Mem.Size == 32) &&
841 getMemIndexReg() >= X86::ZMM0 && getMemIndexReg() <= X86::ZMM31;
842 }
843 bool isMemVZ64() const {
844 return Kind == Memory && (!Mem.Size || Mem.Size == 64) &&
845 getMemIndexReg() >= X86::ZMM0 && getMemIndexReg() <= X86::ZMM31;
846 }
847
848 bool isAbsMem() const {
849 return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
850 !getMemIndexReg() && getMemScale() == 1;
851 }
852
853 bool isMemOffs8() const {
854 return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
855 !getMemIndexReg() && getMemScale() == 1 && (!Mem.Size || Mem.Size == 8);
856 }
857 bool isMemOffs16() const {
858 return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
859 !getMemIndexReg() && getMemScale() == 1 && (!Mem.Size || Mem.Size == 16);
860 }
861 bool isMemOffs32() const {
862 return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
863 !getMemIndexReg() && getMemScale() == 1 && (!Mem.Size || Mem.Size == 32);
864 }
865 bool isMemOffs64() const {
866 return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
867 !getMemIndexReg() && getMemScale() == 1 && (!Mem.Size || Mem.Size == 64);
868 }
869
870 bool isReg() const { return Kind == Register; }
871
872 bool isGR32orGR64() const {
873 return Kind == Register &&
874 (X86MCRegisterClasses[X86::GR32RegClassID].contains(getReg()) ||
875 X86MCRegisterClasses[X86::GR64RegClassID].contains(getReg()));
876 }
877
878 void addExpr(MCInst &Inst, const MCExpr *Expr) const {
879 // Add as immediates when possible.
880 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
881 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
882 else
883 Inst.addOperand(MCOperand::CreateExpr(Expr));
884 }
885
886 void addRegOperands(MCInst &Inst, unsigned N) const {
887 assert(N == 1 && "Invalid number of operands!");
888 Inst.addOperand(MCOperand::CreateReg(getReg()));
889 }
890
891 static unsigned getGR32FromGR64(unsigned RegNo) {
892 switch (RegNo) {
893 default: llvm_unreachable("Unexpected register");
894 case X86::RAX: return X86::EAX;
895 case X86::RCX: return X86::ECX;
896 case X86::RDX: return X86::EDX;
897 case X86::RBX: return X86::EBX;
898 case X86::RBP: return X86::EBP;
899 case X86::RSP: return X86::ESP;
900 case X86::RSI: return X86::ESI;
901 case X86::RDI: return X86::EDI;
902 case X86::R8: return X86::R8D;
903 case X86::R9: return X86::R9D;
904 case X86::R10: return X86::R10D;
905 case X86::R11: return X86::R11D;
906 case X86::R12: return X86::R12D;
907 case X86::R13: return X86::R13D;
908 case X86::R14: return X86::R14D;
909 case X86::R15: return X86::R15D;
910 case X86::RIP: return X86::EIP;
911 }
912 }
913
914 void addGR32orGR64Operands(MCInst &Inst, unsigned N) const {
915 assert(N == 1 && "Invalid number of operands!");
916 unsigned RegNo = getReg();
917 if (X86MCRegisterClasses[X86::GR64RegClassID].contains(RegNo))
918 RegNo = getGR32FromGR64(RegNo);
919 Inst.addOperand(MCOperand::CreateReg(RegNo));
920 }
921
922 void addImmOperands(MCInst &Inst, unsigned N) const {
923 assert(N == 1 && "Invalid number of operands!");
924 addExpr(Inst, getImm());
925 }
926
927 void addMemOperands(MCInst &Inst, unsigned N) const {
928 assert((N == 5) && "Invalid number of operands!");
929 Inst.addOperand(MCOperand::CreateReg(getMemBaseReg()));
930 Inst.addOperand(MCOperand::CreateImm(getMemScale()));
931 Inst.addOperand(MCOperand::CreateReg(getMemIndexReg()));
932 addExpr(Inst, getMemDisp());
933 Inst.addOperand(MCOperand::CreateReg(getMemSegReg()));
934 }
935
936 void addAbsMemOperands(MCInst &Inst, unsigned N) const {
937 assert((N == 1) && "Invalid number of operands!");
938 // Add as immediates when possible.
939 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemDisp()))
940 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
941 else
942 Inst.addOperand(MCOperand::CreateExpr(getMemDisp()));
943 }
944
945 void addMemOffsOperands(MCInst &Inst, unsigned N) const {
946 assert((N == 1) && "Invalid number of operands!");
947 // Add as immediates when possible.
948 if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemDisp()))
949 Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
950 else
951 Inst.addOperand(MCOperand::CreateExpr(getMemDisp()));
952 }
953
954 static X86Operand *CreateToken(StringRef Str, SMLoc Loc) {
955 SMLoc EndLoc = SMLoc::getFromPointer(Loc.getPointer() + Str.size());
956 X86Operand *Res = new X86Operand(Token, Loc, EndLoc);
957 Res->Tok.Data = Str.data();
958 Res->Tok.Length = Str.size();
959 return Res;
960 }
961
962 static X86Operand *CreateReg(unsigned RegNo, SMLoc StartLoc, SMLoc EndLoc,
963 bool AddressOf = false,
964 SMLoc OffsetOfLoc = SMLoc(),
965 StringRef SymName = StringRef(),
966 void *OpDecl = 0) {
967 X86Operand *Res = new X86Operand(Register, StartLoc, EndLoc);
968 Res->Reg.RegNo = RegNo;
969 Res->AddressOf = AddressOf;
970 Res->OffsetOfLoc = OffsetOfLoc;
971 Res->SymName = SymName;
972 Res->OpDecl = OpDecl;
973 return Res;
974 }
975
976 static X86Operand *CreateImm(const MCExpr *Val, SMLoc StartLoc, SMLoc EndLoc){
977 X86Operand *Res = new X86Operand(Immediate, StartLoc, EndLoc);
978 Res->Imm.Val = Val;
979 return Res;
980 }
981
982 /// Create an absolute memory operand.
983 static X86Operand *CreateMem(const MCExpr *Disp, SMLoc StartLoc, SMLoc EndLoc,
984 unsigned Size = 0, StringRef SymName = StringRef(),
985 void *OpDecl = 0) {
986 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
987 Res->Mem.SegReg = 0;
988 Res->Mem.Disp = Disp;
989 Res->Mem.BaseReg = 0;
990 Res->Mem.IndexReg = 0;
991 Res->Mem.Scale = 1;
992 Res->Mem.Size = Size;
993 Res->SymName = SymName;
994 Res->OpDecl = OpDecl;
995 Res->AddressOf = false;
996 return Res;
997 }
998
999 /// Create a generalized memory operand.
1000 static X86Operand *CreateMem(unsigned SegReg, const MCExpr *Disp,
1001 unsigned BaseReg, unsigned IndexReg,
1002 unsigned Scale, SMLoc StartLoc, SMLoc EndLoc,
1003 unsigned Size = 0,
1004 StringRef SymName = StringRef(),
1005 void *OpDecl = 0) {
1006 // We should never just have a displacement, that should be parsed as an
1007 // absolute memory operand.
1008 assert((SegReg || BaseReg || IndexReg) && "Invalid memory operand!");
1009
1010 // The scale should always be one of {1,2,4,8}.
1011 assert(((Scale == 1 || Scale == 2 || Scale == 4 || Scale == 8)) &&
1012 "Invalid scale!");
1013 X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
1014 Res->Mem.SegReg = SegReg;
1015 Res->Mem.Disp = Disp;
1016 Res->Mem.BaseReg = BaseReg;
1017 Res->Mem.IndexReg = IndexReg;
1018 Res->Mem.Scale = Scale;
1019 Res->Mem.Size = Size;
1020 Res->SymName = SymName;
1021 Res->OpDecl = OpDecl;
1022 Res->AddressOf = false;
1023 return Res;
1024 }
1025};
1026
1027} // end anonymous namespace.
1028
1029bool X86AsmParser::isSrcOp(X86Operand &Op) {
1030 unsigned basereg = is64BitMode() ? X86::RSI : X86::ESI;
1031
1032 return (Op.isMem() &&
1033 (Op.Mem.SegReg == 0 || Op.Mem.SegReg == X86::DS) &&
1034 isa<MCConstantExpr>(Op.Mem.Disp) &&
1035 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1036 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0);
1037}
1038
1039bool X86AsmParser::isDstOp(X86Operand &Op) {
1040 unsigned basereg = is64BitMode() ? X86::RDI : X86::EDI;
1041
1042 return Op.isMem() &&
1043 (Op.Mem.SegReg == 0 || Op.Mem.SegReg == X86::ES) &&
1044 isa<MCConstantExpr>(Op.Mem.Disp) &&
1045 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
1046 Op.Mem.BaseReg == basereg && Op.Mem.IndexReg == 0;
1047}
1048
1049bool X86AsmParser::ParseRegister(unsigned &RegNo,
1050 SMLoc &StartLoc, SMLoc &EndLoc) {
1051 RegNo = 0;
1052 const AsmToken &PercentTok = Parser.getTok();
1053 StartLoc = PercentTok.getLoc();
1054
1055 // If we encounter a %, ignore it. This code handles registers with and
1056 // without the prefix, unprefixed registers can occur in cfi directives.
1057 if (!isParsingIntelSyntax() && PercentTok.is(AsmToken::Percent))
1058 Parser.Lex(); // Eat percent token.
1059
1060 const AsmToken &Tok = Parser.getTok();
1061 EndLoc = Tok.getEndLoc();
1062
1063 if (Tok.isNot(AsmToken::Identifier)) {
1064 if (isParsingIntelSyntax()) return true;
1065 return Error(StartLoc, "invalid register name",
1066 SMRange(StartLoc, EndLoc));
1067 }
1068
1069 RegNo = MatchRegisterName(Tok.getString());
1070
1071 // If the match failed, try the register name as lowercase.
1072 if (RegNo == 0)
1073 RegNo = MatchRegisterName(Tok.getString().lower());
1074
1075 if (!is64BitMode()) {
1076 // FIXME: This should be done using Requires<In32BitMode> and
1077 // Requires<In64BitMode> so "eiz" usage in 64-bit instructions can be also
1078 // checked.
1079 // FIXME: Check AH, CH, DH, BH cannot be used in an instruction requiring a
1080 // REX prefix.
1081 if (RegNo == X86::RIZ ||
1082 X86MCRegisterClasses[X86::GR64RegClassID].contains(RegNo) ||
1083 X86II::isX86_64NonExtLowByteReg(RegNo) ||
1084 X86II::isX86_64ExtendedReg(RegNo))
1085 return Error(StartLoc, "register %"
1086 + Tok.getString() + " is only available in 64-bit mode",
1087 SMRange(StartLoc, EndLoc));
1088 }
1089
1090 // Parse "%st" as "%st(0)" and "%st(1)", which is multiple tokens.
1091 if (RegNo == 0 && (Tok.getString() == "st" || Tok.getString() == "ST")) {
1092 RegNo = X86::ST0;
1093 Parser.Lex(); // Eat 'st'
1094
1095 // Check to see if we have '(4)' after %st.
1096 if (getLexer().isNot(AsmToken::LParen))
1097 return false;
1098 // Lex the paren.
1099 getParser().Lex();
1100
1101 const AsmToken &IntTok = Parser.getTok();
1102 if (IntTok.isNot(AsmToken::Integer))
1103 return Error(IntTok.getLoc(), "expected stack index");
1104 switch (IntTok.getIntVal()) {
1105 case 0: RegNo = X86::ST0; break;
1106 case 1: RegNo = X86::ST1; break;
1107 case 2: RegNo = X86::ST2; break;
1108 case 3: RegNo = X86::ST3; break;
1109 case 4: RegNo = X86::ST4; break;
1110 case 5: RegNo = X86::ST5; break;
1111 case 6: RegNo = X86::ST6; break;
1112 case 7: RegNo = X86::ST7; break;
1113 default: return Error(IntTok.getLoc(), "invalid stack index");
1114 }
1115
1116 if (getParser().Lex().isNot(AsmToken::RParen))
1117 return Error(Parser.getTok().getLoc(), "expected ')'");
1118
1119 EndLoc = Parser.getTok().getEndLoc();
1120 Parser.Lex(); // Eat ')'
1121 return false;
1122 }
1123
1124 EndLoc = Parser.getTok().getEndLoc();
1125
1126 // If this is "db[0-7]", match it as an alias
1127 // for dr[0-7].
1128 if (RegNo == 0 && Tok.getString().size() == 3 &&
1129 Tok.getString().startswith("db")) {
1130 switch (Tok.getString()[2]) {
1131 case '0': RegNo = X86::DR0; break;
1132 case '1': RegNo = X86::DR1; break;
1133 case '2': RegNo = X86::DR2; break;
1134 case '3': RegNo = X86::DR3; break;
1135 case '4': RegNo = X86::DR4; break;
1136 case '5': RegNo = X86::DR5; break;
1137 case '6': RegNo = X86::DR6; break;
1138 case '7': RegNo = X86::DR7; break;
1139 }
1140
1141 if (RegNo != 0) {
1142 EndLoc = Parser.getTok().getEndLoc();
1143 Parser.Lex(); // Eat it.
1144 return false;
1145 }
1146 }
1147
1148 if (RegNo == 0) {
1149 if (isParsingIntelSyntax()) return true;
1150 return Error(StartLoc, "invalid register name",
1151 SMRange(StartLoc, EndLoc));
1152 }
1153
1154 Parser.Lex(); // Eat identifier token.
1155 return false;
1156}
1157
1158X86Operand *X86AsmParser::ParseOperand() {
1159 if (isParsingIntelSyntax())
1160 return ParseIntelOperand();
1161 return ParseATTOperand();
1162}
1163
1164/// getIntelMemOperandSize - Return intel memory operand size.
1165static unsigned getIntelMemOperandSize(StringRef OpStr) {
1166 unsigned Size = StringSwitch<unsigned>(OpStr)
1167 .Cases("BYTE", "byte", 8)
1168 .Cases("WORD", "word", 16)
1169 .Cases("DWORD", "dword", 32)
1170 .Cases("QWORD", "qword", 64)
1171 .Cases("XWORD", "xword", 80)
1172 .Cases("XMMWORD", "xmmword", 128)
1173 .Cases("YMMWORD", "ymmword", 256)
1174 .Default(0);
1175 return Size;
1176}
1177
1178X86Operand *
1179X86AsmParser::CreateMemForInlineAsm(unsigned SegReg, const MCExpr *Disp,
1180 unsigned BaseReg, unsigned IndexReg,
1181 unsigned Scale, SMLoc Start, SMLoc End,
1182 unsigned Size, StringRef Identifier,
1183 InlineAsmIdentifierInfo &Info){
1184 if (isa<MCSymbolRefExpr>(Disp)) {
1185 // If this is not a VarDecl then assume it is a FuncDecl or some other label
1186 // reference. We need an 'r' constraint here, so we need to create register
1187 // operand to ensure proper matching. Just pick a GPR based on the size of
1188 // a pointer.
1189 if (!Info.IsVarDecl) {
1190 unsigned RegNo = is64BitMode() ? X86::RBX : X86::EBX;
1191 return X86Operand::CreateReg(RegNo, Start, End, /*AddressOf=*/true,
1192 SMLoc(), Identifier, Info.OpDecl);
1193 }
1184 // If this is not a VarDecl then assume it is a FuncDecl or some other label
1185 // reference. We need an 'r' constraint here, so we need to create register
1186 // operand to ensure proper matching. Just pick a GPR based on the size of
1187 // a pointer.
1188 if (isa<MCSymbolRefExpr>(Disp) && !Info.IsVarDecl) {
1189 unsigned RegNo = is64BitMode() ? X86::RBX : X86::EBX;
1190 return X86Operand::CreateReg(RegNo, Start, End, /*AddressOf=*/true,
1191 SMLoc(), Identifier, Info.OpDecl);
1192 }
1193
1194 // We either have a direct symbol reference, or an offset from a symbol. The
1195 // parser always puts the symbol on the LHS, so look there for size
1196 // calculation purposes.
1197 const MCBinaryExpr *BinOp = dyn_cast<MCBinaryExpr>(Disp);
1198 bool IsSymRef =
1199 isa<MCSymbolRefExpr>(BinOp ? BinOp->getLHS() : Disp);
1200 if (IsSymRef) {
1194 if (!Size) {
1195 Size = Info.Type * 8; // Size is in terms of bits in this context.
1196 if (Size)
1197 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_SizeDirective, Start,
1198 /*Len=*/0, Size));
1199 }
1200 }
1201
1202 // When parsing inline assembly we set the base register to a non-zero value
1203 // if we don't know the actual value at this time. This is necessary to
1204 // get the matching correct in some cases.
1205 BaseReg = BaseReg ? BaseReg : 1;
1206 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale, Start,
1207 End, Size, Identifier, Info.OpDecl);
1208}
1209
1210static void
1211RewriteIntelBracExpression(SmallVectorImpl<AsmRewrite> *AsmRewrites,
1212 StringRef SymName, int64_t ImmDisp,
1213 int64_t FinalImmDisp, SMLoc &BracLoc,
1214 SMLoc &StartInBrac, SMLoc &End) {
1215 // Remove the '[' and ']' from the IR string.
1216 AsmRewrites->push_back(AsmRewrite(AOK_Skip, BracLoc, 1));
1217 AsmRewrites->push_back(AsmRewrite(AOK_Skip, End, 1));
1218
1219 // If ImmDisp is non-zero, then we parsed a displacement before the
1220 // bracketed expression (i.e., ImmDisp [ BaseReg + Scale*IndexReg + Disp])
1221 // If ImmDisp doesn't match the displacement computed by the state machine
1222 // then we have an additional displacement in the bracketed expression.
1223 if (ImmDisp != FinalImmDisp) {
1224 if (ImmDisp) {
1225 // We have an immediate displacement before the bracketed expression.
1226 // Adjust this to match the final immediate displacement.
1227 bool Found = false;
1228 for (SmallVectorImpl<AsmRewrite>::iterator I = AsmRewrites->begin(),
1229 E = AsmRewrites->end(); I != E; ++I) {
1230 if ((*I).Loc.getPointer() > BracLoc.getPointer())
1231 continue;
1232 if ((*I).Kind == AOK_ImmPrefix || (*I).Kind == AOK_Imm) {
1233 assert (!Found && "ImmDisp already rewritten.");
1234 (*I).Kind = AOK_Imm;
1235 (*I).Len = BracLoc.getPointer() - (*I).Loc.getPointer();
1236 (*I).Val = FinalImmDisp;
1237 Found = true;
1238 break;
1239 }
1240 }
1241 assert (Found && "Unable to rewrite ImmDisp.");
1242 (void)Found;
1243 } else {
1244 // We have a symbolic and an immediate displacement, but no displacement
1245 // before the bracketed expression. Put the immediate displacement
1246 // before the bracketed expression.
1247 AsmRewrites->push_back(AsmRewrite(AOK_Imm, BracLoc, 0, FinalImmDisp));
1248 }
1249 }
1250 // Remove all the ImmPrefix rewrites within the brackets.
1251 for (SmallVectorImpl<AsmRewrite>::iterator I = AsmRewrites->begin(),
1252 E = AsmRewrites->end(); I != E; ++I) {
1253 if ((*I).Loc.getPointer() < StartInBrac.getPointer())
1254 continue;
1255 if ((*I).Kind == AOK_ImmPrefix)
1256 (*I).Kind = AOK_Delete;
1257 }
1258 const char *SymLocPtr = SymName.data();
1259 // Skip everything before the symbol.
1260 if (unsigned Len = SymLocPtr - StartInBrac.getPointer()) {
1261 assert(Len > 0 && "Expected a non-negative length.");
1262 AsmRewrites->push_back(AsmRewrite(AOK_Skip, StartInBrac, Len));
1263 }
1264 // Skip everything after the symbol.
1265 if (unsigned Len = End.getPointer() - (SymLocPtr + SymName.size())) {
1266 SMLoc Loc = SMLoc::getFromPointer(SymLocPtr + SymName.size());
1267 assert(Len > 0 && "Expected a non-negative length.");
1268 AsmRewrites->push_back(AsmRewrite(AOK_Skip, Loc, Len));
1269 }
1270}
1271
1272bool X86AsmParser::ParseIntelExpression(IntelExprStateMachine &SM, SMLoc &End) {
1273 const AsmToken &Tok = Parser.getTok();
1274
1275 bool Done = false;
1276 while (!Done) {
1277 bool UpdateLocLex = true;
1278
1279 // The period in the dot operator (e.g., [ebx].foo.bar) is parsed as an
1280 // identifier. Don't try an parse it as a register.
1281 if (Tok.getString().startswith("."))
1282 break;
1283
1284 // If we're parsing an immediate expression, we don't expect a '['.
1285 if (SM.getStopOnLBrac() && getLexer().getKind() == AsmToken::LBrac)
1286 break;
1287
1288 switch (getLexer().getKind()) {
1289 default: {
1290 if (SM.isValidEndState()) {
1291 Done = true;
1292 break;
1293 }
1294 return Error(Tok.getLoc(), "unknown token in expression");
1295 }
1296 case AsmToken::EndOfStatement: {
1297 Done = true;
1298 break;
1299 }
1300 case AsmToken::Identifier: {
1301 // This could be a register or a symbolic displacement.
1302 unsigned TmpReg;
1303 const MCExpr *Val;
1304 SMLoc IdentLoc = Tok.getLoc();
1305 StringRef Identifier = Tok.getString();
1306 if(!ParseRegister(TmpReg, IdentLoc, End)) {
1307 SM.onRegister(TmpReg);
1308 UpdateLocLex = false;
1309 break;
1310 } else {
1311 if (!isParsingInlineAsm()) {
1312 if (getParser().parsePrimaryExpr(Val, End))
1313 return Error(Tok.getLoc(), "Unexpected identifier!");
1314 } else {
1201 if (!Size) {
1202 Size = Info.Type * 8; // Size is in terms of bits in this context.
1203 if (Size)
1204 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_SizeDirective, Start,
1205 /*Len=*/0, Size));
1206 }
1207 }
1208
1209 // When parsing inline assembly we set the base register to a non-zero value
1210 // if we don't know the actual value at this time. This is necessary to
1211 // get the matching correct in some cases.
1212 BaseReg = BaseReg ? BaseReg : 1;
1213 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale, Start,
1214 End, Size, Identifier, Info.OpDecl);
1215}
1216
1217static void
1218RewriteIntelBracExpression(SmallVectorImpl<AsmRewrite> *AsmRewrites,
1219 StringRef SymName, int64_t ImmDisp,
1220 int64_t FinalImmDisp, SMLoc &BracLoc,
1221 SMLoc &StartInBrac, SMLoc &End) {
1222 // Remove the '[' and ']' from the IR string.
1223 AsmRewrites->push_back(AsmRewrite(AOK_Skip, BracLoc, 1));
1224 AsmRewrites->push_back(AsmRewrite(AOK_Skip, End, 1));
1225
1226 // If ImmDisp is non-zero, then we parsed a displacement before the
1227 // bracketed expression (i.e., ImmDisp [ BaseReg + Scale*IndexReg + Disp])
1228 // If ImmDisp doesn't match the displacement computed by the state machine
1229 // then we have an additional displacement in the bracketed expression.
1230 if (ImmDisp != FinalImmDisp) {
1231 if (ImmDisp) {
1232 // We have an immediate displacement before the bracketed expression.
1233 // Adjust this to match the final immediate displacement.
1234 bool Found = false;
1235 for (SmallVectorImpl<AsmRewrite>::iterator I = AsmRewrites->begin(),
1236 E = AsmRewrites->end(); I != E; ++I) {
1237 if ((*I).Loc.getPointer() > BracLoc.getPointer())
1238 continue;
1239 if ((*I).Kind == AOK_ImmPrefix || (*I).Kind == AOK_Imm) {
1240 assert (!Found && "ImmDisp already rewritten.");
1241 (*I).Kind = AOK_Imm;
1242 (*I).Len = BracLoc.getPointer() - (*I).Loc.getPointer();
1243 (*I).Val = FinalImmDisp;
1244 Found = true;
1245 break;
1246 }
1247 }
1248 assert (Found && "Unable to rewrite ImmDisp.");
1249 (void)Found;
1250 } else {
1251 // We have a symbolic and an immediate displacement, but no displacement
1252 // before the bracketed expression. Put the immediate displacement
1253 // before the bracketed expression.
1254 AsmRewrites->push_back(AsmRewrite(AOK_Imm, BracLoc, 0, FinalImmDisp));
1255 }
1256 }
1257 // Remove all the ImmPrefix rewrites within the brackets.
1258 for (SmallVectorImpl<AsmRewrite>::iterator I = AsmRewrites->begin(),
1259 E = AsmRewrites->end(); I != E; ++I) {
1260 if ((*I).Loc.getPointer() < StartInBrac.getPointer())
1261 continue;
1262 if ((*I).Kind == AOK_ImmPrefix)
1263 (*I).Kind = AOK_Delete;
1264 }
1265 const char *SymLocPtr = SymName.data();
1266 // Skip everything before the symbol.
1267 if (unsigned Len = SymLocPtr - StartInBrac.getPointer()) {
1268 assert(Len > 0 && "Expected a non-negative length.");
1269 AsmRewrites->push_back(AsmRewrite(AOK_Skip, StartInBrac, Len));
1270 }
1271 // Skip everything after the symbol.
1272 if (unsigned Len = End.getPointer() - (SymLocPtr + SymName.size())) {
1273 SMLoc Loc = SMLoc::getFromPointer(SymLocPtr + SymName.size());
1274 assert(Len > 0 && "Expected a non-negative length.");
1275 AsmRewrites->push_back(AsmRewrite(AOK_Skip, Loc, Len));
1276 }
1277}
1278
1279bool X86AsmParser::ParseIntelExpression(IntelExprStateMachine &SM, SMLoc &End) {
1280 const AsmToken &Tok = Parser.getTok();
1281
1282 bool Done = false;
1283 while (!Done) {
1284 bool UpdateLocLex = true;
1285
1286 // The period in the dot operator (e.g., [ebx].foo.bar) is parsed as an
1287 // identifier. Don't try an parse it as a register.
1288 if (Tok.getString().startswith("."))
1289 break;
1290
1291 // If we're parsing an immediate expression, we don't expect a '['.
1292 if (SM.getStopOnLBrac() && getLexer().getKind() == AsmToken::LBrac)
1293 break;
1294
1295 switch (getLexer().getKind()) {
1296 default: {
1297 if (SM.isValidEndState()) {
1298 Done = true;
1299 break;
1300 }
1301 return Error(Tok.getLoc(), "unknown token in expression");
1302 }
1303 case AsmToken::EndOfStatement: {
1304 Done = true;
1305 break;
1306 }
1307 case AsmToken::Identifier: {
1308 // This could be a register or a symbolic displacement.
1309 unsigned TmpReg;
1310 const MCExpr *Val;
1311 SMLoc IdentLoc = Tok.getLoc();
1312 StringRef Identifier = Tok.getString();
1313 if(!ParseRegister(TmpReg, IdentLoc, End)) {
1314 SM.onRegister(TmpReg);
1315 UpdateLocLex = false;
1316 break;
1317 } else {
1318 if (!isParsingInlineAsm()) {
1319 if (getParser().parsePrimaryExpr(Val, End))
1320 return Error(Tok.getLoc(), "Unexpected identifier!");
1321 } else {
1315 InlineAsmIdentifierInfo &Info = SM.getIdentifierInfo();
1316 if (ParseIntelIdentifier(Val, Identifier, Info,
1317 /*Unevaluated=*/false, End))
1318 return true;
1322 // This is a dot operator, not an adjacent identifier.
1323 if (Identifier.find('.') != StringRef::npos) {
1324 return false;
1325 } else {
1326 InlineAsmIdentifierInfo &Info = SM.getIdentifierInfo();
1327 if (ParseIntelIdentifier(Val, Identifier, Info,
1328 /*Unevaluated=*/false, End))
1329 return true;
1330 }
1319 }
1320 SM.onIdentifierExpr(Val, Identifier);
1321 UpdateLocLex = false;
1322 break;
1323 }
1324 return Error(Tok.getLoc(), "Unexpected identifier!");
1325 }
1326 case AsmToken::Integer:
1327 if (isParsingInlineAsm() && SM.getAddImmPrefix())
1328 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_ImmPrefix,
1329 Tok.getLoc()));
1330 SM.onInteger(Tok.getIntVal());
1331 break;
1332 case AsmToken::Plus: SM.onPlus(); break;
1333 case AsmToken::Minus: SM.onMinus(); break;
1334 case AsmToken::Star: SM.onStar(); break;
1335 case AsmToken::Slash: SM.onDivide(); break;
1336 case AsmToken::LBrac: SM.onLBrac(); break;
1337 case AsmToken::RBrac: SM.onRBrac(); break;
1338 case AsmToken::LParen: SM.onLParen(); break;
1339 case AsmToken::RParen: SM.onRParen(); break;
1340 }
1341 if (SM.hadError())
1342 return Error(Tok.getLoc(), "unknown token in expression");
1343
1344 if (!Done && UpdateLocLex) {
1345 End = Tok.getLoc();
1346 Parser.Lex(); // Consume the token.
1347 }
1348 }
1349 return false;
1350}
1351
1352X86Operand *X86AsmParser::ParseIntelBracExpression(unsigned SegReg, SMLoc Start,
1353 int64_t ImmDisp,
1354 unsigned Size) {
1355 const AsmToken &Tok = Parser.getTok();
1356 SMLoc BracLoc = Tok.getLoc(), End = Tok.getEndLoc();
1357 if (getLexer().isNot(AsmToken::LBrac))
1358 return ErrorOperand(BracLoc, "Expected '[' token!");
1359 Parser.Lex(); // Eat '['
1360
1361 SMLoc StartInBrac = Tok.getLoc();
1362 // Parse [ Symbol + ImmDisp ] and [ BaseReg + Scale*IndexReg + ImmDisp ]. We
1363 // may have already parsed an immediate displacement before the bracketed
1364 // expression.
1365 IntelExprStateMachine SM(ImmDisp, /*StopOnLBrac=*/false, /*AddImmPrefix=*/true);
1366 if (ParseIntelExpression(SM, End))
1367 return 0;
1368
1331 }
1332 SM.onIdentifierExpr(Val, Identifier);
1333 UpdateLocLex = false;
1334 break;
1335 }
1336 return Error(Tok.getLoc(), "Unexpected identifier!");
1337 }
1338 case AsmToken::Integer:
1339 if (isParsingInlineAsm() && SM.getAddImmPrefix())
1340 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_ImmPrefix,
1341 Tok.getLoc()));
1342 SM.onInteger(Tok.getIntVal());
1343 break;
1344 case AsmToken::Plus: SM.onPlus(); break;
1345 case AsmToken::Minus: SM.onMinus(); break;
1346 case AsmToken::Star: SM.onStar(); break;
1347 case AsmToken::Slash: SM.onDivide(); break;
1348 case AsmToken::LBrac: SM.onLBrac(); break;
1349 case AsmToken::RBrac: SM.onRBrac(); break;
1350 case AsmToken::LParen: SM.onLParen(); break;
1351 case AsmToken::RParen: SM.onRParen(); break;
1352 }
1353 if (SM.hadError())
1354 return Error(Tok.getLoc(), "unknown token in expression");
1355
1356 if (!Done && UpdateLocLex) {
1357 End = Tok.getLoc();
1358 Parser.Lex(); // Consume the token.
1359 }
1360 }
1361 return false;
1362}
1363
1364X86Operand *X86AsmParser::ParseIntelBracExpression(unsigned SegReg, SMLoc Start,
1365 int64_t ImmDisp,
1366 unsigned Size) {
1367 const AsmToken &Tok = Parser.getTok();
1368 SMLoc BracLoc = Tok.getLoc(), End = Tok.getEndLoc();
1369 if (getLexer().isNot(AsmToken::LBrac))
1370 return ErrorOperand(BracLoc, "Expected '[' token!");
1371 Parser.Lex(); // Eat '['
1372
1373 SMLoc StartInBrac = Tok.getLoc();
1374 // Parse [ Symbol + ImmDisp ] and [ BaseReg + Scale*IndexReg + ImmDisp ]. We
1375 // may have already parsed an immediate displacement before the bracketed
1376 // expression.
1377 IntelExprStateMachine SM(ImmDisp, /*StopOnLBrac=*/false, /*AddImmPrefix=*/true);
1378 if (ParseIntelExpression(SM, End))
1379 return 0;
1380
1369 const MCExpr *Disp;
1381 const MCExpr *Disp = 0;
1370 if (const MCExpr *Sym = SM.getSym()) {
1371 // A symbolic displacement.
1372 Disp = Sym;
1373 if (isParsingInlineAsm())
1374 RewriteIntelBracExpression(InstInfo->AsmRewrites, SM.getSymName(),
1375 ImmDisp, SM.getImm(), BracLoc, StartInBrac,
1376 End);
1382 if (const MCExpr *Sym = SM.getSym()) {
1383 // A symbolic displacement.
1384 Disp = Sym;
1385 if (isParsingInlineAsm())
1386 RewriteIntelBracExpression(InstInfo->AsmRewrites, SM.getSymName(),
1387 ImmDisp, SM.getImm(), BracLoc, StartInBrac,
1388 End);
1377 } else {
1378 // An immediate displacement only.
1379 Disp = MCConstantExpr::Create(SM.getImm(), getContext());
1380 }
1381
1389 }
1390
1382 // Parse the dot operator (e.g., [ebx].foo.bar).
1383 if (Tok.getString().startswith(".")) {
1391 if (SM.getImm() || !Disp) {
1392 const MCExpr *Imm = MCConstantExpr::Create(SM.getImm(), getContext());
1393 if (Disp)
1394 Disp = MCBinaryExpr::CreateAdd(Disp, Imm, getContext());
1395 else
1396 Disp = Imm; // An immediate displacement only.
1397 }
1398
1399 // Parse struct field access. Intel requires a dot, but MSVC doesn't. MSVC
1400 // will in fact do global lookup the field name inside all global typedefs,
1401 // but we don't emulate that.
1402 if (Tok.getString().find('.') != StringRef::npos) {
1384 const MCExpr *NewDisp;
1385 if (ParseIntelDotOperator(Disp, NewDisp))
1386 return 0;
1387
1388 End = Tok.getEndLoc();
1389 Parser.Lex(); // Eat the field.
1390 Disp = NewDisp;
1391 }
1392
1393 int BaseReg = SM.getBaseReg();
1394 int IndexReg = SM.getIndexReg();
1395 int Scale = SM.getScale();
1396 if (!isParsingInlineAsm()) {
1397 // handle [-42]
1398 if (!BaseReg && !IndexReg) {
1399 if (!SegReg)
1400 return X86Operand::CreateMem(Disp, Start, End, Size);
1401 else
1402 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, Start, End, Size);
1403 }
1404 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale, Start,
1405 End, Size);
1406 }
1407
1408 InlineAsmIdentifierInfo &Info = SM.getIdentifierInfo();
1409 return CreateMemForInlineAsm(SegReg, Disp, BaseReg, IndexReg, Scale, Start,
1410 End, Size, SM.getSymName(), Info);
1411}
1412
1413// Inline assembly may use variable names with namespace alias qualifiers.
1414bool X86AsmParser::ParseIntelIdentifier(const MCExpr *&Val,
1415 StringRef &Identifier,
1416 InlineAsmIdentifierInfo &Info,
1417 bool IsUnevaluatedOperand, SMLoc &End) {
1418 assert (isParsingInlineAsm() && "Expected to be parsing inline assembly.");
1419 Val = 0;
1420
1421 StringRef LineBuf(Identifier.data());
1422 SemaCallback->LookupInlineAsmIdentifier(LineBuf, Info, IsUnevaluatedOperand);
1423
1424 const AsmToken &Tok = Parser.getTok();
1425
1426 // Advance the token stream until the end of the current token is
1427 // after the end of what the frontend claimed.
1428 const char *EndPtr = Tok.getLoc().getPointer() + LineBuf.size();
1429 while (true) {
1430 End = Tok.getEndLoc();
1431 getLexer().Lex();
1432
1433 assert(End.getPointer() <= EndPtr && "frontend claimed part of a token?");
1434 if (End.getPointer() == EndPtr) break;
1435 }
1436
1437 // Create the symbol reference.
1438 Identifier = LineBuf;
1439 MCSymbol *Sym = getContext().GetOrCreateSymbol(Identifier);
1440 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
1441 Val = MCSymbolRefExpr::Create(Sym, Variant, getParser().getContext());
1442 return false;
1443}
1444
1445/// \brief Parse intel style segment override.
1446X86Operand *X86AsmParser::ParseIntelSegmentOverride(unsigned SegReg,
1447 SMLoc Start,
1448 unsigned Size) {
1449 assert(SegReg != 0 && "Tried to parse a segment override without a segment!");
1450 const AsmToken &Tok = Parser.getTok(); // Eat colon.
1451 if (Tok.isNot(AsmToken::Colon))
1452 return ErrorOperand(Tok.getLoc(), "Expected ':' token!");
1453 Parser.Lex(); // Eat ':'
1454
1455 int64_t ImmDisp = 0;
1456 if (getLexer().is(AsmToken::Integer)) {
1457 ImmDisp = Tok.getIntVal();
1458 AsmToken ImmDispToken = Parser.Lex(); // Eat the integer.
1459
1460 if (isParsingInlineAsm())
1461 InstInfo->AsmRewrites->push_back(
1462 AsmRewrite(AOK_ImmPrefix, ImmDispToken.getLoc()));
1463
1464 if (getLexer().isNot(AsmToken::LBrac)) {
1465 // An immediate following a 'segment register', 'colon' token sequence can
1466 // be followed by a bracketed expression. If it isn't we know we have our
1467 // final segment override.
1468 const MCExpr *Disp = MCConstantExpr::Create(ImmDisp, getContext());
1469 return X86Operand::CreateMem(SegReg, Disp, /*BaseReg=*/0, /*IndexReg=*/0,
1470 /*Scale=*/1, Start, ImmDispToken.getEndLoc(),
1471 Size);
1472 }
1473 }
1474
1475 if (getLexer().is(AsmToken::LBrac))
1476 return ParseIntelBracExpression(SegReg, Start, ImmDisp, Size);
1477
1478 const MCExpr *Val;
1479 SMLoc End;
1480 if (!isParsingInlineAsm()) {
1481 if (getParser().parsePrimaryExpr(Val, End))
1482 return ErrorOperand(Tok.getLoc(), "unknown token in expression");
1483
1484 return X86Operand::CreateMem(Val, Start, End, Size);
1485 }
1486
1487 InlineAsmIdentifierInfo Info;
1488 StringRef Identifier = Tok.getString();
1489 if (ParseIntelIdentifier(Val, Identifier, Info,
1490 /*Unevaluated=*/false, End))
1491 return 0;
1492 return CreateMemForInlineAsm(/*SegReg=*/0, Val, /*BaseReg=*/0,/*IndexReg=*/0,
1493 /*Scale=*/1, Start, End, Size, Identifier, Info);
1494}
1495
1496/// ParseIntelMemOperand - Parse intel style memory operand.
1497X86Operand *X86AsmParser::ParseIntelMemOperand(int64_t ImmDisp, SMLoc Start,
1498 unsigned Size) {
1499 const AsmToken &Tok = Parser.getTok();
1500 SMLoc End;
1501
1502 // Parse ImmDisp [ BaseReg + Scale*IndexReg + Disp ].
1503 if (getLexer().is(AsmToken::LBrac))
1504 return ParseIntelBracExpression(/*SegReg=*/0, Start, ImmDisp, Size);
1505
1506 const MCExpr *Val;
1507 if (!isParsingInlineAsm()) {
1508 if (getParser().parsePrimaryExpr(Val, End))
1509 return ErrorOperand(Tok.getLoc(), "unknown token in expression");
1510
1511 return X86Operand::CreateMem(Val, Start, End, Size);
1512 }
1513
1514 InlineAsmIdentifierInfo Info;
1515 StringRef Identifier = Tok.getString();
1516 if (ParseIntelIdentifier(Val, Identifier, Info,
1517 /*Unevaluated=*/false, End))
1518 return 0;
1519 return CreateMemForInlineAsm(/*SegReg=*/0, Val, /*BaseReg=*/0, /*IndexReg=*/0,
1520 /*Scale=*/1, Start, End, Size, Identifier, Info);
1521}
1522
1523/// Parse the '.' operator.
1524bool X86AsmParser::ParseIntelDotOperator(const MCExpr *Disp,
1525 const MCExpr *&NewDisp) {
1526 const AsmToken &Tok = Parser.getTok();
1527 int64_t OrigDispVal, DotDispVal;
1528
1529 // FIXME: Handle non-constant expressions.
1530 if (const MCConstantExpr *OrigDisp = dyn_cast<MCConstantExpr>(Disp))
1531 OrigDispVal = OrigDisp->getValue();
1532 else
1533 return Error(Tok.getLoc(), "Non-constant offsets are not supported!");
1534
1403 const MCExpr *NewDisp;
1404 if (ParseIntelDotOperator(Disp, NewDisp))
1405 return 0;
1406
1407 End = Tok.getEndLoc();
1408 Parser.Lex(); // Eat the field.
1409 Disp = NewDisp;
1410 }
1411
1412 int BaseReg = SM.getBaseReg();
1413 int IndexReg = SM.getIndexReg();
1414 int Scale = SM.getScale();
1415 if (!isParsingInlineAsm()) {
1416 // handle [-42]
1417 if (!BaseReg && !IndexReg) {
1418 if (!SegReg)
1419 return X86Operand::CreateMem(Disp, Start, End, Size);
1420 else
1421 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, Start, End, Size);
1422 }
1423 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale, Start,
1424 End, Size);
1425 }
1426
1427 InlineAsmIdentifierInfo &Info = SM.getIdentifierInfo();
1428 return CreateMemForInlineAsm(SegReg, Disp, BaseReg, IndexReg, Scale, Start,
1429 End, Size, SM.getSymName(), Info);
1430}
1431
1432// Inline assembly may use variable names with namespace alias qualifiers.
1433bool X86AsmParser::ParseIntelIdentifier(const MCExpr *&Val,
1434 StringRef &Identifier,
1435 InlineAsmIdentifierInfo &Info,
1436 bool IsUnevaluatedOperand, SMLoc &End) {
1437 assert (isParsingInlineAsm() && "Expected to be parsing inline assembly.");
1438 Val = 0;
1439
1440 StringRef LineBuf(Identifier.data());
1441 SemaCallback->LookupInlineAsmIdentifier(LineBuf, Info, IsUnevaluatedOperand);
1442
1443 const AsmToken &Tok = Parser.getTok();
1444
1445 // Advance the token stream until the end of the current token is
1446 // after the end of what the frontend claimed.
1447 const char *EndPtr = Tok.getLoc().getPointer() + LineBuf.size();
1448 while (true) {
1449 End = Tok.getEndLoc();
1450 getLexer().Lex();
1451
1452 assert(End.getPointer() <= EndPtr && "frontend claimed part of a token?");
1453 if (End.getPointer() == EndPtr) break;
1454 }
1455
1456 // Create the symbol reference.
1457 Identifier = LineBuf;
1458 MCSymbol *Sym = getContext().GetOrCreateSymbol(Identifier);
1459 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
1460 Val = MCSymbolRefExpr::Create(Sym, Variant, getParser().getContext());
1461 return false;
1462}
1463
1464/// \brief Parse intel style segment override.
1465X86Operand *X86AsmParser::ParseIntelSegmentOverride(unsigned SegReg,
1466 SMLoc Start,
1467 unsigned Size) {
1468 assert(SegReg != 0 && "Tried to parse a segment override without a segment!");
1469 const AsmToken &Tok = Parser.getTok(); // Eat colon.
1470 if (Tok.isNot(AsmToken::Colon))
1471 return ErrorOperand(Tok.getLoc(), "Expected ':' token!");
1472 Parser.Lex(); // Eat ':'
1473
1474 int64_t ImmDisp = 0;
1475 if (getLexer().is(AsmToken::Integer)) {
1476 ImmDisp = Tok.getIntVal();
1477 AsmToken ImmDispToken = Parser.Lex(); // Eat the integer.
1478
1479 if (isParsingInlineAsm())
1480 InstInfo->AsmRewrites->push_back(
1481 AsmRewrite(AOK_ImmPrefix, ImmDispToken.getLoc()));
1482
1483 if (getLexer().isNot(AsmToken::LBrac)) {
1484 // An immediate following a 'segment register', 'colon' token sequence can
1485 // be followed by a bracketed expression. If it isn't we know we have our
1486 // final segment override.
1487 const MCExpr *Disp = MCConstantExpr::Create(ImmDisp, getContext());
1488 return X86Operand::CreateMem(SegReg, Disp, /*BaseReg=*/0, /*IndexReg=*/0,
1489 /*Scale=*/1, Start, ImmDispToken.getEndLoc(),
1490 Size);
1491 }
1492 }
1493
1494 if (getLexer().is(AsmToken::LBrac))
1495 return ParseIntelBracExpression(SegReg, Start, ImmDisp, Size);
1496
1497 const MCExpr *Val;
1498 SMLoc End;
1499 if (!isParsingInlineAsm()) {
1500 if (getParser().parsePrimaryExpr(Val, End))
1501 return ErrorOperand(Tok.getLoc(), "unknown token in expression");
1502
1503 return X86Operand::CreateMem(Val, Start, End, Size);
1504 }
1505
1506 InlineAsmIdentifierInfo Info;
1507 StringRef Identifier = Tok.getString();
1508 if (ParseIntelIdentifier(Val, Identifier, Info,
1509 /*Unevaluated=*/false, End))
1510 return 0;
1511 return CreateMemForInlineAsm(/*SegReg=*/0, Val, /*BaseReg=*/0,/*IndexReg=*/0,
1512 /*Scale=*/1, Start, End, Size, Identifier, Info);
1513}
1514
1515/// ParseIntelMemOperand - Parse intel style memory operand.
1516X86Operand *X86AsmParser::ParseIntelMemOperand(int64_t ImmDisp, SMLoc Start,
1517 unsigned Size) {
1518 const AsmToken &Tok = Parser.getTok();
1519 SMLoc End;
1520
1521 // Parse ImmDisp [ BaseReg + Scale*IndexReg + Disp ].
1522 if (getLexer().is(AsmToken::LBrac))
1523 return ParseIntelBracExpression(/*SegReg=*/0, Start, ImmDisp, Size);
1524
1525 const MCExpr *Val;
1526 if (!isParsingInlineAsm()) {
1527 if (getParser().parsePrimaryExpr(Val, End))
1528 return ErrorOperand(Tok.getLoc(), "unknown token in expression");
1529
1530 return X86Operand::CreateMem(Val, Start, End, Size);
1531 }
1532
1533 InlineAsmIdentifierInfo Info;
1534 StringRef Identifier = Tok.getString();
1535 if (ParseIntelIdentifier(Val, Identifier, Info,
1536 /*Unevaluated=*/false, End))
1537 return 0;
1538 return CreateMemForInlineAsm(/*SegReg=*/0, Val, /*BaseReg=*/0, /*IndexReg=*/0,
1539 /*Scale=*/1, Start, End, Size, Identifier, Info);
1540}
1541
1542/// Parse the '.' operator.
1543bool X86AsmParser::ParseIntelDotOperator(const MCExpr *Disp,
1544 const MCExpr *&NewDisp) {
1545 const AsmToken &Tok = Parser.getTok();
1546 int64_t OrigDispVal, DotDispVal;
1547
1548 // FIXME: Handle non-constant expressions.
1549 if (const MCConstantExpr *OrigDisp = dyn_cast<MCConstantExpr>(Disp))
1550 OrigDispVal = OrigDisp->getValue();
1551 else
1552 return Error(Tok.getLoc(), "Non-constant offsets are not supported!");
1553
1535 // Drop the '.'.
1536 StringRef DotDispStr = Tok.getString().drop_front(1);
1554 // Drop the optional '.'.
1555 StringRef DotDispStr = Tok.getString();
1556 if (DotDispStr.startswith("."))
1557 DotDispStr = DotDispStr.drop_front(1);
1537
1538 // .Imm gets lexed as a real.
1539 if (Tok.is(AsmToken::Real)) {
1540 APInt DotDisp;
1541 DotDispStr.getAsInteger(10, DotDisp);
1542 DotDispVal = DotDisp.getZExtValue();
1543 } else if (isParsingInlineAsm() && Tok.is(AsmToken::Identifier)) {
1544 unsigned DotDisp;
1545 std::pair<StringRef, StringRef> BaseMember = DotDispStr.split('.');
1546 if (SemaCallback->LookupInlineAsmField(BaseMember.first, BaseMember.second,
1547 DotDisp))
1548 return Error(Tok.getLoc(), "Unable to lookup field reference!");
1549 DotDispVal = DotDisp;
1550 } else
1551 return Error(Tok.getLoc(), "Unexpected token type!");
1552
1553 if (isParsingInlineAsm() && Tok.is(AsmToken::Identifier)) {
1554 SMLoc Loc = SMLoc::getFromPointer(DotDispStr.data());
1555 unsigned Len = DotDispStr.size();
1556 unsigned Val = OrigDispVal + DotDispVal;
1557 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_DotOperator, Loc, Len,
1558 Val));
1559 }
1560
1561 NewDisp = MCConstantExpr::Create(OrigDispVal + DotDispVal, getContext());
1562 return false;
1563}
1564
1565/// Parse the 'offset' operator. This operator is used to specify the
1566/// location rather then the content of a variable.
1567X86Operand *X86AsmParser::ParseIntelOffsetOfOperator() {
1568 const AsmToken &Tok = Parser.getTok();
1569 SMLoc OffsetOfLoc = Tok.getLoc();
1570 Parser.Lex(); // Eat offset.
1571
1572 const MCExpr *Val;
1573 InlineAsmIdentifierInfo Info;
1574 SMLoc Start = Tok.getLoc(), End;
1575 StringRef Identifier = Tok.getString();
1576 if (ParseIntelIdentifier(Val, Identifier, Info,
1577 /*Unevaluated=*/false, End))
1578 return 0;
1579
1580 // Don't emit the offset operator.
1581 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_Skip, OffsetOfLoc, 7));
1582
1583 // The offset operator will have an 'r' constraint, thus we need to create
1584 // register operand to ensure proper matching. Just pick a GPR based on
1585 // the size of a pointer.
1586 unsigned RegNo = is64BitMode() ? X86::RBX : X86::EBX;
1587 return X86Operand::CreateReg(RegNo, Start, End, /*GetAddress=*/true,
1588 OffsetOfLoc, Identifier, Info.OpDecl);
1589}
1590
1591enum IntelOperatorKind {
1592 IOK_LENGTH,
1593 IOK_SIZE,
1594 IOK_TYPE
1595};
1596
1597/// Parse the 'LENGTH', 'TYPE' and 'SIZE' operators. The LENGTH operator
1598/// returns the number of elements in an array. It returns the value 1 for
1599/// non-array variables. The SIZE operator returns the size of a C or C++
1600/// variable. A variable's size is the product of its LENGTH and TYPE. The
1601/// TYPE operator returns the size of a C or C++ type or variable. If the
1602/// variable is an array, TYPE returns the size of a single element.
1603X86Operand *X86AsmParser::ParseIntelOperator(unsigned OpKind) {
1604 const AsmToken &Tok = Parser.getTok();
1605 SMLoc TypeLoc = Tok.getLoc();
1606 Parser.Lex(); // Eat operator.
1607
1608 const MCExpr *Val = 0;
1609 InlineAsmIdentifierInfo Info;
1610 SMLoc Start = Tok.getLoc(), End;
1611 StringRef Identifier = Tok.getString();
1612 if (ParseIntelIdentifier(Val, Identifier, Info,
1613 /*Unevaluated=*/true, End))
1614 return 0;
1615
1616 if (!Info.OpDecl)
1617 return ErrorOperand(Start, "unable to lookup expression");
1618
1619 unsigned CVal = 0;
1620 switch(OpKind) {
1621 default: llvm_unreachable("Unexpected operand kind!");
1622 case IOK_LENGTH: CVal = Info.Length; break;
1623 case IOK_SIZE: CVal = Info.Size; break;
1624 case IOK_TYPE: CVal = Info.Type; break;
1625 }
1626
1627 // Rewrite the type operator and the C or C++ type or variable in terms of an
1628 // immediate. E.g. TYPE foo -> $$4
1629 unsigned Len = End.getPointer() - TypeLoc.getPointer();
1630 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_Imm, TypeLoc, Len, CVal));
1631
1632 const MCExpr *Imm = MCConstantExpr::Create(CVal, getContext());
1633 return X86Operand::CreateImm(Imm, Start, End);
1634}
1635
1636X86Operand *X86AsmParser::ParseIntelOperand() {
1637 const AsmToken &Tok = Parser.getTok();
1638 SMLoc Start, End;
1639
1640 // Offset, length, type and size operators.
1641 if (isParsingInlineAsm()) {
1642 StringRef AsmTokStr = Tok.getString();
1643 if (AsmTokStr == "offset" || AsmTokStr == "OFFSET")
1644 return ParseIntelOffsetOfOperator();
1645 if (AsmTokStr == "length" || AsmTokStr == "LENGTH")
1646 return ParseIntelOperator(IOK_LENGTH);
1647 if (AsmTokStr == "size" || AsmTokStr == "SIZE")
1648 return ParseIntelOperator(IOK_SIZE);
1649 if (AsmTokStr == "type" || AsmTokStr == "TYPE")
1650 return ParseIntelOperator(IOK_TYPE);
1651 }
1652
1653 unsigned Size = getIntelMemOperandSize(Tok.getString());
1654 if (Size) {
1655 Parser.Lex(); // Eat operand size (e.g., byte, word).
1656 if (Tok.getString() != "PTR" && Tok.getString() != "ptr")
1657 return ErrorOperand(Start, "Expected 'PTR' or 'ptr' token!");
1658 Parser.Lex(); // Eat ptr.
1659 }
1660 Start = Tok.getLoc();
1661
1662 // Immediate.
1663 if (getLexer().is(AsmToken::Integer) || getLexer().is(AsmToken::Minus) ||
1664 getLexer().is(AsmToken::LParen)) {
1665 AsmToken StartTok = Tok;
1666 IntelExprStateMachine SM(/*Imm=*/0, /*StopOnLBrac=*/true,
1667 /*AddImmPrefix=*/false);
1668 if (ParseIntelExpression(SM, End))
1669 return 0;
1670
1671 int64_t Imm = SM.getImm();
1672 if (isParsingInlineAsm()) {
1673 unsigned Len = Tok.getLoc().getPointer() - Start.getPointer();
1674 if (StartTok.getString().size() == Len)
1675 // Just add a prefix if this wasn't a complex immediate expression.
1676 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_ImmPrefix, Start));
1677 else
1678 // Otherwise, rewrite the complex expression as a single immediate.
1679 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_Imm, Start, Len, Imm));
1680 }
1681
1682 if (getLexer().isNot(AsmToken::LBrac)) {
1683 const MCExpr *ImmExpr = MCConstantExpr::Create(Imm, getContext());
1684 return X86Operand::CreateImm(ImmExpr, Start, End);
1685 }
1686
1687 // Only positive immediates are valid.
1688 if (Imm < 0)
1689 return ErrorOperand(Start, "expected a positive immediate displacement "
1690 "before bracketed expr.");
1691
1692 // Parse ImmDisp [ BaseReg + Scale*IndexReg + Disp ].
1693 return ParseIntelMemOperand(Imm, Start, Size);
1694 }
1695
1696 // Register.
1697 unsigned RegNo = 0;
1698 if (!ParseRegister(RegNo, Start, End)) {
1699 // If this is a segment register followed by a ':', then this is the start
1700 // of a segment override, otherwise this is a normal register reference.
1701 if (getLexer().isNot(AsmToken::Colon))
1702 return X86Operand::CreateReg(RegNo, Start, End);
1703
1704 return ParseIntelSegmentOverride(/*SegReg=*/RegNo, Start, Size);
1705 }
1706
1707 // Memory operand.
1708 return ParseIntelMemOperand(/*Disp=*/0, Start, Size);
1709}
1710
1711X86Operand *X86AsmParser::ParseATTOperand() {
1712 switch (getLexer().getKind()) {
1713 default:
1714 // Parse a memory operand with no segment register.
1715 return ParseMemOperand(0, Parser.getTok().getLoc());
1716 case AsmToken::Percent: {
1717 // Read the register.
1718 unsigned RegNo;
1719 SMLoc Start, End;
1720 if (ParseRegister(RegNo, Start, End)) return 0;
1721 if (RegNo == X86::EIZ || RegNo == X86::RIZ) {
1722 Error(Start, "%eiz and %riz can only be used as index registers",
1723 SMRange(Start, End));
1724 return 0;
1725 }
1726
1727 // If this is a segment register followed by a ':', then this is the start
1728 // of a memory reference, otherwise this is a normal register reference.
1729 if (getLexer().isNot(AsmToken::Colon))
1730 return X86Operand::CreateReg(RegNo, Start, End);
1731
1732 getParser().Lex(); // Eat the colon.
1733 return ParseMemOperand(RegNo, Start);
1734 }
1735 case AsmToken::Dollar: {
1736 // $42 -> immediate.
1737 SMLoc Start = Parser.getTok().getLoc(), End;
1738 Parser.Lex();
1739 const MCExpr *Val;
1740 if (getParser().parseExpression(Val, End))
1741 return 0;
1742 return X86Operand::CreateImm(Val, Start, End);
1743 }
1744 }
1745}
1746
1747/// ParseMemOperand: segment: disp(basereg, indexreg, scale). The '%ds:' prefix
1748/// has already been parsed if present.
1749X86Operand *X86AsmParser::ParseMemOperand(unsigned SegReg, SMLoc MemStart) {
1750
1751 // We have to disambiguate a parenthesized expression "(4+5)" from the start
1752 // of a memory operand with a missing displacement "(%ebx)" or "(,%eax)". The
1753 // only way to do this without lookahead is to eat the '(' and see what is
1754 // after it.
1755 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
1756 if (getLexer().isNot(AsmToken::LParen)) {
1757 SMLoc ExprEnd;
1758 if (getParser().parseExpression(Disp, ExprEnd)) return 0;
1759
1760 // After parsing the base expression we could either have a parenthesized
1761 // memory address or not. If not, return now. If so, eat the (.
1762 if (getLexer().isNot(AsmToken::LParen)) {
1763 // Unless we have a segment register, treat this as an immediate.
1764 if (SegReg == 0)
1765 return X86Operand::CreateMem(Disp, MemStart, ExprEnd);
1766 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
1767 }
1768
1769 // Eat the '('.
1770 Parser.Lex();
1771 } else {
1772 // Okay, we have a '('. We don't know if this is an expression or not, but
1773 // so we have to eat the ( to see beyond it.
1774 SMLoc LParenLoc = Parser.getTok().getLoc();
1775 Parser.Lex(); // Eat the '('.
1776
1777 if (getLexer().is(AsmToken::Percent) || getLexer().is(AsmToken::Comma)) {
1778 // Nothing to do here, fall into the code below with the '(' part of the
1779 // memory operand consumed.
1780 } else {
1781 SMLoc ExprEnd;
1782
1783 // It must be an parenthesized expression, parse it now.
1784 if (getParser().parseParenExpression(Disp, ExprEnd))
1785 return 0;
1786
1787 // After parsing the base expression we could either have a parenthesized
1788 // memory address or not. If not, return now. If so, eat the (.
1789 if (getLexer().isNot(AsmToken::LParen)) {
1790 // Unless we have a segment register, treat this as an immediate.
1791 if (SegReg == 0)
1792 return X86Operand::CreateMem(Disp, LParenLoc, ExprEnd);
1793 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
1794 }
1795
1796 // Eat the '('.
1797 Parser.Lex();
1798 }
1799 }
1800
1801 // If we reached here, then we just ate the ( of the memory operand. Process
1802 // the rest of the memory operand.
1803 unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
1804 SMLoc IndexLoc;
1805
1806 if (getLexer().is(AsmToken::Percent)) {
1807 SMLoc StartLoc, EndLoc;
1808 if (ParseRegister(BaseReg, StartLoc, EndLoc)) return 0;
1809 if (BaseReg == X86::EIZ || BaseReg == X86::RIZ) {
1810 Error(StartLoc, "eiz and riz can only be used as index registers",
1811 SMRange(StartLoc, EndLoc));
1812 return 0;
1813 }
1814 }
1815
1816 if (getLexer().is(AsmToken::Comma)) {
1817 Parser.Lex(); // Eat the comma.
1818 IndexLoc = Parser.getTok().getLoc();
1819
1820 // Following the comma we should have either an index register, or a scale
1821 // value. We don't support the later form, but we want to parse it
1822 // correctly.
1823 //
1824 // Not that even though it would be completely consistent to support syntax
1825 // like "1(%eax,,1)", the assembler doesn't. Use "eiz" or "riz" for this.
1826 if (getLexer().is(AsmToken::Percent)) {
1827 SMLoc L;
1828 if (ParseRegister(IndexReg, L, L)) return 0;
1829
1830 if (getLexer().isNot(AsmToken::RParen)) {
1831 // Parse the scale amount:
1832 // ::= ',' [scale-expression]
1833 if (getLexer().isNot(AsmToken::Comma)) {
1834 Error(Parser.getTok().getLoc(),
1835 "expected comma in scale expression");
1836 return 0;
1837 }
1838 Parser.Lex(); // Eat the comma.
1839
1840 if (getLexer().isNot(AsmToken::RParen)) {
1841 SMLoc Loc = Parser.getTok().getLoc();
1842
1843 int64_t ScaleVal;
1844 if (getParser().parseAbsoluteExpression(ScaleVal)){
1845 Error(Loc, "expected scale expression");
1846 return 0;
1847 }
1848
1849 // Validate the scale amount.
1850 if (ScaleVal != 1 && ScaleVal != 2 && ScaleVal != 4 && ScaleVal != 8){
1851 Error(Loc, "scale factor in address must be 1, 2, 4 or 8");
1852 return 0;
1853 }
1854 Scale = (unsigned)ScaleVal;
1855 }
1856 }
1857 } else if (getLexer().isNot(AsmToken::RParen)) {
1858 // A scale amount without an index is ignored.
1859 // index.
1860 SMLoc Loc = Parser.getTok().getLoc();
1861
1862 int64_t Value;
1863 if (getParser().parseAbsoluteExpression(Value))
1864 return 0;
1865
1866 if (Value != 1)
1867 Warning(Loc, "scale factor without index register is ignored");
1868 Scale = 1;
1869 }
1870 }
1871
1872 // Ok, we've eaten the memory operand, verify we have a ')' and eat it too.
1873 if (getLexer().isNot(AsmToken::RParen)) {
1874 Error(Parser.getTok().getLoc(), "unexpected token in memory operand");
1875 return 0;
1876 }
1877 SMLoc MemEnd = Parser.getTok().getEndLoc();
1878 Parser.Lex(); // Eat the ')'.
1879
1880 // If we have both a base register and an index register make sure they are
1881 // both 64-bit or 32-bit registers.
1882 // To support VSIB, IndexReg can be 128-bit or 256-bit registers.
1883 if (BaseReg != 0 && IndexReg != 0) {
1884 if (X86MCRegisterClasses[X86::GR64RegClassID].contains(BaseReg) &&
1885 (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) ||
1886 X86MCRegisterClasses[X86::GR32RegClassID].contains(IndexReg)) &&
1887 IndexReg != X86::RIZ) {
1888 Error(IndexLoc, "index register is 32-bit, but base register is 64-bit");
1889 return 0;
1890 }
1891 if (X86MCRegisterClasses[X86::GR32RegClassID].contains(BaseReg) &&
1892 (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) ||
1893 X86MCRegisterClasses[X86::GR64RegClassID].contains(IndexReg)) &&
1894 IndexReg != X86::EIZ){
1895 Error(IndexLoc, "index register is 64-bit, but base register is 32-bit");
1896 return 0;
1897 }
1898 }
1899
1900 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
1901 MemStart, MemEnd);
1902}
1903
1904bool X86AsmParser::
1905ParseInstruction(ParseInstructionInfo &Info, StringRef Name, SMLoc NameLoc,
1906 SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1907 InstInfo = &Info;
1908 StringRef PatchedName = Name;
1909
1910 // FIXME: Hack to recognize setneb as setne.
1911 if (PatchedName.startswith("set") && PatchedName.endswith("b") &&
1912 PatchedName != "setb" && PatchedName != "setnb")
1913 PatchedName = PatchedName.substr(0, Name.size()-1);
1914
1915 // FIXME: Hack to recognize cmp<comparison code>{ss,sd,ps,pd}.
1916 const MCExpr *ExtraImmOp = 0;
1917 if ((PatchedName.startswith("cmp") || PatchedName.startswith("vcmp")) &&
1918 (PatchedName.endswith("ss") || PatchedName.endswith("sd") ||
1919 PatchedName.endswith("ps") || PatchedName.endswith("pd"))) {
1920 bool IsVCMP = PatchedName[0] == 'v';
1921 unsigned SSECCIdx = IsVCMP ? 4 : 3;
1922 unsigned SSEComparisonCode = StringSwitch<unsigned>(
1923 PatchedName.slice(SSECCIdx, PatchedName.size() - 2))
1924 .Case("eq", 0x00)
1925 .Case("lt", 0x01)
1926 .Case("le", 0x02)
1927 .Case("unord", 0x03)
1928 .Case("neq", 0x04)
1929 .Case("nlt", 0x05)
1930 .Case("nle", 0x06)
1931 .Case("ord", 0x07)
1932 /* AVX only from here */
1933 .Case("eq_uq", 0x08)
1934 .Case("nge", 0x09)
1935 .Case("ngt", 0x0A)
1936 .Case("false", 0x0B)
1937 .Case("neq_oq", 0x0C)
1938 .Case("ge", 0x0D)
1939 .Case("gt", 0x0E)
1940 .Case("true", 0x0F)
1941 .Case("eq_os", 0x10)
1942 .Case("lt_oq", 0x11)
1943 .Case("le_oq", 0x12)
1944 .Case("unord_s", 0x13)
1945 .Case("neq_us", 0x14)
1946 .Case("nlt_uq", 0x15)
1947 .Case("nle_uq", 0x16)
1948 .Case("ord_s", 0x17)
1949 .Case("eq_us", 0x18)
1950 .Case("nge_uq", 0x19)
1951 .Case("ngt_uq", 0x1A)
1952 .Case("false_os", 0x1B)
1953 .Case("neq_os", 0x1C)
1954 .Case("ge_oq", 0x1D)
1955 .Case("gt_oq", 0x1E)
1956 .Case("true_us", 0x1F)
1957 .Default(~0U);
1958 if (SSEComparisonCode != ~0U && (IsVCMP || SSEComparisonCode < 8)) {
1959 ExtraImmOp = MCConstantExpr::Create(SSEComparisonCode,
1960 getParser().getContext());
1961 if (PatchedName.endswith("ss")) {
1962 PatchedName = IsVCMP ? "vcmpss" : "cmpss";
1963 } else if (PatchedName.endswith("sd")) {
1964 PatchedName = IsVCMP ? "vcmpsd" : "cmpsd";
1965 } else if (PatchedName.endswith("ps")) {
1966 PatchedName = IsVCMP ? "vcmpps" : "cmpps";
1967 } else {
1968 assert(PatchedName.endswith("pd") && "Unexpected mnemonic!");
1969 PatchedName = IsVCMP ? "vcmppd" : "cmppd";
1970 }
1971 }
1972 }
1973
1974 Operands.push_back(X86Operand::CreateToken(PatchedName, NameLoc));
1975
1976 if (ExtraImmOp && !isParsingIntelSyntax())
1977 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
1978
1979 // Determine whether this is an instruction prefix.
1980 bool isPrefix =
1981 Name == "lock" || Name == "rep" ||
1982 Name == "repe" || Name == "repz" ||
1983 Name == "repne" || Name == "repnz" ||
1984 Name == "rex64" || Name == "data16";
1985
1986
1987 // This does the actual operand parsing. Don't parse any more if we have a
1988 // prefix juxtaposed with an operation like "lock incl 4(%rax)", because we
1989 // just want to parse the "lock" as the first instruction and the "incl" as
1990 // the next one.
1991 if (getLexer().isNot(AsmToken::EndOfStatement) && !isPrefix) {
1992
1993 // Parse '*' modifier.
1994 if (getLexer().is(AsmToken::Star)) {
1995 SMLoc Loc = Parser.getTok().getLoc();
1996 Operands.push_back(X86Operand::CreateToken("*", Loc));
1997 Parser.Lex(); // Eat the star.
1998 }
1999
2000 // Read the first operand.
2001 if (X86Operand *Op = ParseOperand())
2002 Operands.push_back(Op);
2003 else {
2004 Parser.eatToEndOfStatement();
2005 return true;
2006 }
2007
2008 while (getLexer().is(AsmToken::Comma)) {
2009 Parser.Lex(); // Eat the comma.
2010
2011 // Parse and remember the operand.
2012 if (X86Operand *Op = ParseOperand())
2013 Operands.push_back(Op);
2014 else {
2015 Parser.eatToEndOfStatement();
2016 return true;
2017 }
2018 }
2019
2020 if (STI.getFeatureBits() & X86::FeatureAVX512) {
2021 // Parse mask register {%k1}
2022 if (getLexer().is(AsmToken::LCurly)) {
2023 SMLoc Loc = Parser.getTok().getLoc();
2024 Operands.push_back(X86Operand::CreateToken("{", Loc));
2025 Parser.Lex(); // Eat the {
2026 if (X86Operand *Op = ParseOperand()) {
2027 Operands.push_back(Op);
2028 if (!getLexer().is(AsmToken::RCurly)) {
2029 SMLoc Loc = getLexer().getLoc();
2030 Parser.eatToEndOfStatement();
2031 return Error(Loc, "Expected } at this point");
2032 }
2033 Loc = Parser.getTok().getLoc();
2034 Operands.push_back(X86Operand::CreateToken("}", Loc));
2035 Parser.Lex(); // Eat the }
2036 } else {
2037 Parser.eatToEndOfStatement();
2038 return true;
2039 }
2040 }
2041 // Parse "zeroing non-masked" semantic {z}
2042 if (getLexer().is(AsmToken::LCurly)) {
2043 SMLoc Loc = Parser.getTok().getLoc();
2044 Operands.push_back(X86Operand::CreateToken("{z}", Loc));
2045 Parser.Lex(); // Eat the {
2046 if (!getLexer().is(AsmToken::Identifier) || getLexer().getTok().getIdentifier() != "z") {
2047 SMLoc Loc = getLexer().getLoc();
2048 Parser.eatToEndOfStatement();
2049 return Error(Loc, "Expected z at this point");
2050 }
2051 Parser.Lex(); // Eat the z
2052 if (!getLexer().is(AsmToken::RCurly)) {
2053 SMLoc Loc = getLexer().getLoc();
2054 Parser.eatToEndOfStatement();
2055 return Error(Loc, "Expected } at this point");
2056 }
2057 Parser.Lex(); // Eat the }
2058 }
2059 }
2060
2061 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2062 SMLoc Loc = getLexer().getLoc();
2063 Parser.eatToEndOfStatement();
2064 return Error(Loc, "unexpected token in argument list");
2065 }
2066 }
2067
2068 if (getLexer().is(AsmToken::EndOfStatement))
2069 Parser.Lex(); // Consume the EndOfStatement
2070 else if (isPrefix && getLexer().is(AsmToken::Slash))
2071 Parser.Lex(); // Consume the prefix separator Slash
2072
2073 if (ExtraImmOp && isParsingIntelSyntax())
2074 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
2075
2076 // This is a terrible hack to handle "out[bwl]? %al, (%dx)" ->
2077 // "outb %al, %dx". Out doesn't take a memory form, but this is a widely
2078 // documented form in various unofficial manuals, so a lot of code uses it.
2079 if ((Name == "outb" || Name == "outw" || Name == "outl" || Name == "out") &&
2080 Operands.size() == 3) {
2081 X86Operand &Op = *(X86Operand*)Operands.back();
2082 if (Op.isMem() && Op.Mem.SegReg == 0 &&
2083 isa<MCConstantExpr>(Op.Mem.Disp) &&
2084 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
2085 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
2086 SMLoc Loc = Op.getEndLoc();
2087 Operands.back() = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
2088 delete &Op;
2089 }
2090 }
2091 // Same hack for "in[bwl]? (%dx), %al" -> "inb %dx, %al".
2092 if ((Name == "inb" || Name == "inw" || Name == "inl" || Name == "in") &&
2093 Operands.size() == 3) {
2094 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
2095 if (Op.isMem() && Op.Mem.SegReg == 0 &&
2096 isa<MCConstantExpr>(Op.Mem.Disp) &&
2097 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
2098 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
2099 SMLoc Loc = Op.getEndLoc();
2100 Operands.begin()[1] = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
2101 delete &Op;
2102 }
2103 }
2104 // Transform "ins[bwl] %dx, %es:(%edi)" into "ins[bwl]"
2105 if (Name.startswith("ins") && Operands.size() == 3 &&
2106 (Name == "insb" || Name == "insw" || Name == "insl")) {
2107 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
2108 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
2109 if (Op.isReg() && Op.getReg() == X86::DX && isDstOp(Op2)) {
2110 Operands.pop_back();
2111 Operands.pop_back();
2112 delete &Op;
2113 delete &Op2;
2114 }
2115 }
2116
2117 // Transform "outs[bwl] %ds:(%esi), %dx" into "out[bwl]"
2118 if (Name.startswith("outs") && Operands.size() == 3 &&
2119 (Name == "outsb" || Name == "outsw" || Name == "outsl")) {
2120 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
2121 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
2122 if (isSrcOp(Op) && Op2.isReg() && Op2.getReg() == X86::DX) {
2123 Operands.pop_back();
2124 Operands.pop_back();
2125 delete &Op;
2126 delete &Op2;
2127 }
2128 }
2129
2130 // Transform "movs[bwl] %ds:(%esi), %es:(%edi)" into "movs[bwl]"
2131 if (Name.startswith("movs") && Operands.size() == 3 &&
2132 (Name == "movsb" || Name == "movsw" || Name == "movsl" ||
2133 (is64BitMode() && Name == "movsq"))) {
2134 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
2135 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
2136 if (isSrcOp(Op) && isDstOp(Op2)) {
2137 Operands.pop_back();
2138 Operands.pop_back();
2139 delete &Op;
2140 delete &Op2;
2141 }
2142 }
2143 // Transform "lods[bwl] %ds:(%esi),{%al,%ax,%eax,%rax}" into "lods[bwl]"
2144 if (Name.startswith("lods") && Operands.size() == 3 &&
2145 (Name == "lods" || Name == "lodsb" || Name == "lodsw" ||
2146 Name == "lodsl" || (is64BitMode() && Name == "lodsq"))) {
2147 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
2148 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
2149 if (isSrcOp(*Op1) && Op2->isReg()) {
2150 const char *ins;
2151 unsigned reg = Op2->getReg();
2152 bool isLods = Name == "lods";
2153 if (reg == X86::AL && (isLods || Name == "lodsb"))
2154 ins = "lodsb";
2155 else if (reg == X86::AX && (isLods || Name == "lodsw"))
2156 ins = "lodsw";
2157 else if (reg == X86::EAX && (isLods || Name == "lodsl"))
2158 ins = "lodsl";
2159 else if (reg == X86::RAX && (isLods || Name == "lodsq"))
2160 ins = "lodsq";
2161 else
2162 ins = NULL;
2163 if (ins != NULL) {
2164 Operands.pop_back();
2165 Operands.pop_back();
2166 delete Op1;
2167 delete Op2;
2168 if (Name != ins)
2169 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
2170 }
2171 }
2172 }
2173 // Transform "stos[bwl] {%al,%ax,%eax,%rax},%es:(%edi)" into "stos[bwl]"
2174 if (Name.startswith("stos") && Operands.size() == 3 &&
2175 (Name == "stos" || Name == "stosb" || Name == "stosw" ||
2176 Name == "stosl" || (is64BitMode() && Name == "stosq"))) {
2177 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
2178 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
2179 if (isDstOp(*Op2) && Op1->isReg()) {
2180 const char *ins;
2181 unsigned reg = Op1->getReg();
2182 bool isStos = Name == "stos";
2183 if (reg == X86::AL && (isStos || Name == "stosb"))
2184 ins = "stosb";
2185 else if (reg == X86::AX && (isStos || Name == "stosw"))
2186 ins = "stosw";
2187 else if (reg == X86::EAX && (isStos || Name == "stosl"))
2188 ins = "stosl";
2189 else if (reg == X86::RAX && (isStos || Name == "stosq"))
2190 ins = "stosq";
2191 else
2192 ins = NULL;
2193 if (ins != NULL) {
2194 Operands.pop_back();
2195 Operands.pop_back();
2196 delete Op1;
2197 delete Op2;
2198 if (Name != ins)
2199 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
2200 }
2201 }
2202 }
2203
2204 // FIXME: Hack to handle recognize s{hr,ar,hl} $1, <op>. Canonicalize to
2205 // "shift <op>".
2206 if ((Name.startswith("shr") || Name.startswith("sar") ||
2207 Name.startswith("shl") || Name.startswith("sal") ||
2208 Name.startswith("rcl") || Name.startswith("rcr") ||
2209 Name.startswith("rol") || Name.startswith("ror")) &&
2210 Operands.size() == 3) {
2211 if (isParsingIntelSyntax()) {
2212 // Intel syntax
2213 X86Operand *Op1 = static_cast<X86Operand*>(Operands[2]);
2214 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
2215 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
2216 delete Operands[2];
2217 Operands.pop_back();
2218 }
2219 } else {
2220 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
2221 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
2222 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
2223 delete Operands[1];
2224 Operands.erase(Operands.begin() + 1);
2225 }
2226 }
2227 }
2228
2229 // Transforms "int $3" into "int3" as a size optimization. We can't write an
2230 // instalias with an immediate operand yet.
2231 if (Name == "int" && Operands.size() == 2) {
2232 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
2233 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
2234 cast<MCConstantExpr>(Op1->getImm())->getValue() == 3) {
2235 delete Operands[1];
2236 Operands.erase(Operands.begin() + 1);
2237 static_cast<X86Operand*>(Operands[0])->setTokenValue("int3");
2238 }
2239 }
2240
2241 return false;
2242}
2243
2244static bool convertToSExti8(MCInst &Inst, unsigned Opcode, unsigned Reg,
2245 bool isCmp) {
2246 MCInst TmpInst;
2247 TmpInst.setOpcode(Opcode);
2248 if (!isCmp)
2249 TmpInst.addOperand(MCOperand::CreateReg(Reg));
2250 TmpInst.addOperand(MCOperand::CreateReg(Reg));
2251 TmpInst.addOperand(Inst.getOperand(0));
2252 Inst = TmpInst;
2253 return true;
2254}
2255
2256static bool convert16i16to16ri8(MCInst &Inst, unsigned Opcode,
2257 bool isCmp = false) {
2258 if (!Inst.getOperand(0).isImm() ||
2259 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
2260 return false;
2261
2262 return convertToSExti8(Inst, Opcode, X86::AX, isCmp);
2263}
2264
2265static bool convert32i32to32ri8(MCInst &Inst, unsigned Opcode,
2266 bool isCmp = false) {
2267 if (!Inst.getOperand(0).isImm() ||
2268 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
2269 return false;
2270
2271 return convertToSExti8(Inst, Opcode, X86::EAX, isCmp);
2272}
2273
2274static bool convert64i32to64ri8(MCInst &Inst, unsigned Opcode,
2275 bool isCmp = false) {
2276 if (!Inst.getOperand(0).isImm() ||
2277 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
2278 return false;
2279
2280 return convertToSExti8(Inst, Opcode, X86::RAX, isCmp);
2281}
2282
2283bool X86AsmParser::
2284processInstruction(MCInst &Inst,
2285 const SmallVectorImpl<MCParsedAsmOperand*> &Ops) {
2286 switch (Inst.getOpcode()) {
2287 default: return false;
2288 case X86::AND16i16: return convert16i16to16ri8(Inst, X86::AND16ri8);
2289 case X86::AND32i32: return convert32i32to32ri8(Inst, X86::AND32ri8);
2290 case X86::AND64i32: return convert64i32to64ri8(Inst, X86::AND64ri8);
2291 case X86::XOR16i16: return convert16i16to16ri8(Inst, X86::XOR16ri8);
2292 case X86::XOR32i32: return convert32i32to32ri8(Inst, X86::XOR32ri8);
2293 case X86::XOR64i32: return convert64i32to64ri8(Inst, X86::XOR64ri8);
2294 case X86::OR16i16: return convert16i16to16ri8(Inst, X86::OR16ri8);
2295 case X86::OR32i32: return convert32i32to32ri8(Inst, X86::OR32ri8);
2296 case X86::OR64i32: return convert64i32to64ri8(Inst, X86::OR64ri8);
2297 case X86::CMP16i16: return convert16i16to16ri8(Inst, X86::CMP16ri8, true);
2298 case X86::CMP32i32: return convert32i32to32ri8(Inst, X86::CMP32ri8, true);
2299 case X86::CMP64i32: return convert64i32to64ri8(Inst, X86::CMP64ri8, true);
2300 case X86::ADD16i16: return convert16i16to16ri8(Inst, X86::ADD16ri8);
2301 case X86::ADD32i32: return convert32i32to32ri8(Inst, X86::ADD32ri8);
2302 case X86::ADD64i32: return convert64i32to64ri8(Inst, X86::ADD64ri8);
2303 case X86::SUB16i16: return convert16i16to16ri8(Inst, X86::SUB16ri8);
2304 case X86::SUB32i32: return convert32i32to32ri8(Inst, X86::SUB32ri8);
2305 case X86::SUB64i32: return convert64i32to64ri8(Inst, X86::SUB64ri8);
2306 case X86::ADC16i16: return convert16i16to16ri8(Inst, X86::ADC16ri8);
2307 case X86::ADC32i32: return convert32i32to32ri8(Inst, X86::ADC32ri8);
2308 case X86::ADC64i32: return convert64i32to64ri8(Inst, X86::ADC64ri8);
2309 case X86::SBB16i16: return convert16i16to16ri8(Inst, X86::SBB16ri8);
2310 case X86::SBB32i32: return convert32i32to32ri8(Inst, X86::SBB32ri8);
2311 case X86::SBB64i32: return convert64i32to64ri8(Inst, X86::SBB64ri8);
2312 case X86::VMOVAPDrr:
2313 case X86::VMOVAPDYrr:
2314 case X86::VMOVAPSrr:
2315 case X86::VMOVAPSYrr:
2316 case X86::VMOVDQArr:
2317 case X86::VMOVDQAYrr:
2318 case X86::VMOVDQUrr:
2319 case X86::VMOVDQUYrr:
2320 case X86::VMOVUPDrr:
2321 case X86::VMOVUPDYrr:
2322 case X86::VMOVUPSrr:
2323 case X86::VMOVUPSYrr: {
2324 if (X86II::isX86_64ExtendedReg(Inst.getOperand(0).getReg()) ||
2325 !X86II::isX86_64ExtendedReg(Inst.getOperand(1).getReg()))
2326 return false;
2327
2328 unsigned NewOpc;
2329 switch (Inst.getOpcode()) {
2330 default: llvm_unreachable("Invalid opcode");
2331 case X86::VMOVAPDrr: NewOpc = X86::VMOVAPDrr_REV; break;
2332 case X86::VMOVAPDYrr: NewOpc = X86::VMOVAPDYrr_REV; break;
2333 case X86::VMOVAPSrr: NewOpc = X86::VMOVAPSrr_REV; break;
2334 case X86::VMOVAPSYrr: NewOpc = X86::VMOVAPSYrr_REV; break;
2335 case X86::VMOVDQArr: NewOpc = X86::VMOVDQArr_REV; break;
2336 case X86::VMOVDQAYrr: NewOpc = X86::VMOVDQAYrr_REV; break;
2337 case X86::VMOVDQUrr: NewOpc = X86::VMOVDQUrr_REV; break;
2338 case X86::VMOVDQUYrr: NewOpc = X86::VMOVDQUYrr_REV; break;
2339 case X86::VMOVUPDrr: NewOpc = X86::VMOVUPDrr_REV; break;
2340 case X86::VMOVUPDYrr: NewOpc = X86::VMOVUPDYrr_REV; break;
2341 case X86::VMOVUPSrr: NewOpc = X86::VMOVUPSrr_REV; break;
2342 case X86::VMOVUPSYrr: NewOpc = X86::VMOVUPSYrr_REV; break;
2343 }
2344 Inst.setOpcode(NewOpc);
2345 return true;
2346 }
2347 case X86::VMOVSDrr:
2348 case X86::VMOVSSrr: {
2349 if (X86II::isX86_64ExtendedReg(Inst.getOperand(0).getReg()) ||
2350 !X86II::isX86_64ExtendedReg(Inst.getOperand(2).getReg()))
2351 return false;
2352 unsigned NewOpc;
2353 switch (Inst.getOpcode()) {
2354 default: llvm_unreachable("Invalid opcode");
2355 case X86::VMOVSDrr: NewOpc = X86::VMOVSDrr_REV; break;
2356 case X86::VMOVSSrr: NewOpc = X86::VMOVSSrr_REV; break;
2357 }
2358 Inst.setOpcode(NewOpc);
2359 return true;
2360 }
2361 }
2362}
2363
2364static const char *getSubtargetFeatureName(unsigned Val);
2365bool X86AsmParser::
2366MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
2367 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
2368 MCStreamer &Out, unsigned &ErrorInfo,
2369 bool MatchingInlineAsm) {
2370 assert(!Operands.empty() && "Unexpect empty operand list!");
2371 X86Operand *Op = static_cast<X86Operand*>(Operands[0]);
2372 assert(Op->isToken() && "Leading operand should always be a mnemonic!");
2373 ArrayRef<SMRange> EmptyRanges = None;
2374
2375 // First, handle aliases that expand to multiple instructions.
2376 // FIXME: This should be replaced with a real .td file alias mechanism.
2377 // Also, MatchInstructionImpl should actually *do* the EmitInstruction
2378 // call.
2379 if (Op->getToken() == "fstsw" || Op->getToken() == "fstcw" ||
2380 Op->getToken() == "fstsww" || Op->getToken() == "fstcww" ||
2381 Op->getToken() == "finit" || Op->getToken() == "fsave" ||
2382 Op->getToken() == "fstenv" || Op->getToken() == "fclex") {
2383 MCInst Inst;
2384 Inst.setOpcode(X86::WAIT);
2385 Inst.setLoc(IDLoc);
2386 if (!MatchingInlineAsm)
2387 Out.EmitInstruction(Inst);
2388
2389 const char *Repl =
2390 StringSwitch<const char*>(Op->getToken())
2391 .Case("finit", "fninit")
2392 .Case("fsave", "fnsave")
2393 .Case("fstcw", "fnstcw")
2394 .Case("fstcww", "fnstcw")
2395 .Case("fstenv", "fnstenv")
2396 .Case("fstsw", "fnstsw")
2397 .Case("fstsww", "fnstsw")
2398 .Case("fclex", "fnclex")
2399 .Default(0);
2400 assert(Repl && "Unknown wait-prefixed instruction");
2401 delete Operands[0];
2402 Operands[0] = X86Operand::CreateToken(Repl, IDLoc);
2403 }
2404
2405 bool WasOriginallyInvalidOperand = false;
2406 MCInst Inst;
2407
2408 // First, try a direct match.
2409 switch (MatchInstructionImpl(Operands, Inst,
2410 ErrorInfo, MatchingInlineAsm,
2411 isParsingIntelSyntax())) {
2412 default: break;
2413 case Match_Success:
2414 // Some instructions need post-processing to, for example, tweak which
2415 // encoding is selected. Loop on it while changes happen so the
2416 // individual transformations can chain off each other.
2417 if (!MatchingInlineAsm)
2418 while (processInstruction(Inst, Operands))
2419 ;
2420
2421 Inst.setLoc(IDLoc);
2422 if (!MatchingInlineAsm)
2423 Out.EmitInstruction(Inst);
2424 Opcode = Inst.getOpcode();
2425 return false;
2426 case Match_MissingFeature: {
2427 assert(ErrorInfo && "Unknown missing feature!");
2428 // Special case the error message for the very common case where only
2429 // a single subtarget feature is missing.
2430 std::string Msg = "instruction requires:";
2431 unsigned Mask = 1;
2432 for (unsigned i = 0; i < (sizeof(ErrorInfo)*8-1); ++i) {
2433 if (ErrorInfo & Mask) {
2434 Msg += " ";
2435 Msg += getSubtargetFeatureName(ErrorInfo & Mask);
2436 }
2437 Mask <<= 1;
2438 }
2439 return Error(IDLoc, Msg, EmptyRanges, MatchingInlineAsm);
2440 }
2441 case Match_InvalidOperand:
2442 WasOriginallyInvalidOperand = true;
2443 break;
2444 case Match_MnemonicFail:
2445 break;
2446 }
2447
2448 // FIXME: Ideally, we would only attempt suffix matches for things which are
2449 // valid prefixes, and we could just infer the right unambiguous
2450 // type. However, that requires substantially more matcher support than the
2451 // following hack.
2452
2453 // Change the operand to point to a temporary token.
2454 StringRef Base = Op->getToken();
2455 SmallString<16> Tmp;
2456 Tmp += Base;
2457 Tmp += ' ';
2458 Op->setTokenValue(Tmp.str());
2459
2460 // If this instruction starts with an 'f', then it is a floating point stack
2461 // instruction. These come in up to three forms for 32-bit, 64-bit, and
2462 // 80-bit floating point, which use the suffixes s,l,t respectively.
2463 //
2464 // Otherwise, we assume that this may be an integer instruction, which comes
2465 // in 8/16/32/64-bit forms using the b,w,l,q suffixes respectively.
2466 const char *Suffixes = Base[0] != 'f' ? "bwlq" : "slt\0";
2467
2468 // Check for the various suffix matches.
2469 Tmp[Base.size()] = Suffixes[0];
2470 unsigned ErrorInfoIgnore;
2471 unsigned ErrorInfoMissingFeature = 0; // Init suppresses compiler warnings.
2472 unsigned Match1, Match2, Match3, Match4;
2473
2474 Match1 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
2475 MatchingInlineAsm, isParsingIntelSyntax());
2476 // If this returned as a missing feature failure, remember that.
2477 if (Match1 == Match_MissingFeature)
2478 ErrorInfoMissingFeature = ErrorInfoIgnore;
2479 Tmp[Base.size()] = Suffixes[1];
2480 Match2 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
2481 MatchingInlineAsm, isParsingIntelSyntax());
2482 // If this returned as a missing feature failure, remember that.
2483 if (Match2 == Match_MissingFeature)
2484 ErrorInfoMissingFeature = ErrorInfoIgnore;
2485 Tmp[Base.size()] = Suffixes[2];
2486 Match3 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
2487 MatchingInlineAsm, isParsingIntelSyntax());
2488 // If this returned as a missing feature failure, remember that.
2489 if (Match3 == Match_MissingFeature)
2490 ErrorInfoMissingFeature = ErrorInfoIgnore;
2491 Tmp[Base.size()] = Suffixes[3];
2492 Match4 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
2493 MatchingInlineAsm, isParsingIntelSyntax());
2494 // If this returned as a missing feature failure, remember that.
2495 if (Match4 == Match_MissingFeature)
2496 ErrorInfoMissingFeature = ErrorInfoIgnore;
2497
2498 // Restore the old token.
2499 Op->setTokenValue(Base);
2500
2501 // If exactly one matched, then we treat that as a successful match (and the
2502 // instruction will already have been filled in correctly, since the failing
2503 // matches won't have modified it).
2504 unsigned NumSuccessfulMatches =
2505 (Match1 == Match_Success) + (Match2 == Match_Success) +
2506 (Match3 == Match_Success) + (Match4 == Match_Success);
2507 if (NumSuccessfulMatches == 1) {
2508 Inst.setLoc(IDLoc);
2509 if (!MatchingInlineAsm)
2510 Out.EmitInstruction(Inst);
2511 Opcode = Inst.getOpcode();
2512 return false;
2513 }
2514
2515 // Otherwise, the match failed, try to produce a decent error message.
2516
2517 // If we had multiple suffix matches, then identify this as an ambiguous
2518 // match.
2519 if (NumSuccessfulMatches > 1) {
2520 char MatchChars[4];
2521 unsigned NumMatches = 0;
2522 if (Match1 == Match_Success) MatchChars[NumMatches++] = Suffixes[0];
2523 if (Match2 == Match_Success) MatchChars[NumMatches++] = Suffixes[1];
2524 if (Match3 == Match_Success) MatchChars[NumMatches++] = Suffixes[2];
2525 if (Match4 == Match_Success) MatchChars[NumMatches++] = Suffixes[3];
2526
2527 SmallString<126> Msg;
2528 raw_svector_ostream OS(Msg);
2529 OS << "ambiguous instructions require an explicit suffix (could be ";
2530 for (unsigned i = 0; i != NumMatches; ++i) {
2531 if (i != 0)
2532 OS << ", ";
2533 if (i + 1 == NumMatches)
2534 OS << "or ";
2535 OS << "'" << Base << MatchChars[i] << "'";
2536 }
2537 OS << ")";
2538 Error(IDLoc, OS.str(), EmptyRanges, MatchingInlineAsm);
2539 return true;
2540 }
2541
2542 // Okay, we know that none of the variants matched successfully.
2543
2544 // If all of the instructions reported an invalid mnemonic, then the original
2545 // mnemonic was invalid.
2546 if ((Match1 == Match_MnemonicFail) && (Match2 == Match_MnemonicFail) &&
2547 (Match3 == Match_MnemonicFail) && (Match4 == Match_MnemonicFail)) {
2548 if (!WasOriginallyInvalidOperand) {
2549 ArrayRef<SMRange> Ranges = MatchingInlineAsm ? EmptyRanges :
2550 Op->getLocRange();
2551 return Error(IDLoc, "invalid instruction mnemonic '" + Base + "'",
2552 Ranges, MatchingInlineAsm);
2553 }
2554
2555 // Recover location info for the operand if we know which was the problem.
2556 if (ErrorInfo != ~0U) {
2557 if (ErrorInfo >= Operands.size())
2558 return Error(IDLoc, "too few operands for instruction",
2559 EmptyRanges, MatchingInlineAsm);
2560
2561 X86Operand *Operand = (X86Operand*)Operands[ErrorInfo];
2562 if (Operand->getStartLoc().isValid()) {
2563 SMRange OperandRange = Operand->getLocRange();
2564 return Error(Operand->getStartLoc(), "invalid operand for instruction",
2565 OperandRange, MatchingInlineAsm);
2566 }
2567 }
2568
2569 return Error(IDLoc, "invalid operand for instruction", EmptyRanges,
2570 MatchingInlineAsm);
2571 }
2572
2573 // If one instruction matched with a missing feature, report this as a
2574 // missing feature.
2575 if ((Match1 == Match_MissingFeature) + (Match2 == Match_MissingFeature) +
2576 (Match3 == Match_MissingFeature) + (Match4 == Match_MissingFeature) == 1){
2577 std::string Msg = "instruction requires:";
2578 unsigned Mask = 1;
2579 for (unsigned i = 0; i < (sizeof(ErrorInfoMissingFeature)*8-1); ++i) {
2580 if (ErrorInfoMissingFeature & Mask) {
2581 Msg += " ";
2582 Msg += getSubtargetFeatureName(ErrorInfoMissingFeature & Mask);
2583 }
2584 Mask <<= 1;
2585 }
2586 return Error(IDLoc, Msg, EmptyRanges, MatchingInlineAsm);
2587 }
2588
2589 // If one instruction matched with an invalid operand, report this as an
2590 // operand failure.
2591 if ((Match1 == Match_InvalidOperand) + (Match2 == Match_InvalidOperand) +
2592 (Match3 == Match_InvalidOperand) + (Match4 == Match_InvalidOperand) == 1){
2593 Error(IDLoc, "invalid operand for instruction", EmptyRanges,
2594 MatchingInlineAsm);
2595 return true;
2596 }
2597
2598 // If all of these were an outright failure, report it in a useless way.
2599 Error(IDLoc, "unknown use of instruction mnemonic without a size suffix",
2600 EmptyRanges, MatchingInlineAsm);
2601 return true;
2602}
2603
2604
2605bool X86AsmParser::ParseDirective(AsmToken DirectiveID) {
2606 StringRef IDVal = DirectiveID.getIdentifier();
2607 if (IDVal == ".word")
2608 return ParseDirectiveWord(2, DirectiveID.getLoc());
2609 else if (IDVal.startswith(".code"))
2610 return ParseDirectiveCode(IDVal, DirectiveID.getLoc());
2611 else if (IDVal.startswith(".att_syntax")) {
2612 getParser().setAssemblerDialect(0);
2613 return false;
2614 } else if (IDVal.startswith(".intel_syntax")) {
2615 getParser().setAssemblerDialect(1);
2616 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2617 if(Parser.getTok().getString() == "noprefix") {
2618 // FIXME : Handle noprefix
2619 Parser.Lex();
2620 } else
2621 return true;
2622 }
2623 return false;
2624 }
2625 return true;
2626}
2627
2628/// ParseDirectiveWord
2629/// ::= .word [ expression (, expression)* ]
2630bool X86AsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
2631 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2632 for (;;) {
2633 const MCExpr *Value;
2634 if (getParser().parseExpression(Value))
2635 return true;
2636
2637 getParser().getStreamer().EmitValue(Value, Size);
2638
2639 if (getLexer().is(AsmToken::EndOfStatement))
2640 break;
2641
2642 // FIXME: Improve diagnostic.
2643 if (getLexer().isNot(AsmToken::Comma))
2644 return Error(L, "unexpected token in directive");
2645 Parser.Lex();
2646 }
2647 }
2648
2649 Parser.Lex();
2650 return false;
2651}
2652
2653/// ParseDirectiveCode
2654/// ::= .code32 | .code64
2655bool X86AsmParser::ParseDirectiveCode(StringRef IDVal, SMLoc L) {
2656 if (IDVal == ".code32") {
2657 Parser.Lex();
2658 if (is64BitMode()) {
2659 SwitchMode();
2660 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
2661 }
2662 } else if (IDVal == ".code64") {
2663 Parser.Lex();
2664 if (!is64BitMode()) {
2665 SwitchMode();
2666 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code64);
2667 }
2668 } else {
2669 return Error(L, "unexpected directive " + IDVal);
2670 }
2671
2672 return false;
2673}
2674
2675// Force static initialization.
2676extern "C" void LLVMInitializeX86AsmParser() {
2677 RegisterMCAsmParser<X86AsmParser> X(TheX86_32Target);
2678 RegisterMCAsmParser<X86AsmParser> Y(TheX86_64Target);
2679}
2680
2681#define GET_REGISTER_MATCHER
2682#define GET_MATCHER_IMPLEMENTATION
2683#define GET_SUBTARGET_FEATURE_NAME
2684#include "X86GenAsmMatcher.inc"
1558
1559 // .Imm gets lexed as a real.
1560 if (Tok.is(AsmToken::Real)) {
1561 APInt DotDisp;
1562 DotDispStr.getAsInteger(10, DotDisp);
1563 DotDispVal = DotDisp.getZExtValue();
1564 } else if (isParsingInlineAsm() && Tok.is(AsmToken::Identifier)) {
1565 unsigned DotDisp;
1566 std::pair<StringRef, StringRef> BaseMember = DotDispStr.split('.');
1567 if (SemaCallback->LookupInlineAsmField(BaseMember.first, BaseMember.second,
1568 DotDisp))
1569 return Error(Tok.getLoc(), "Unable to lookup field reference!");
1570 DotDispVal = DotDisp;
1571 } else
1572 return Error(Tok.getLoc(), "Unexpected token type!");
1573
1574 if (isParsingInlineAsm() && Tok.is(AsmToken::Identifier)) {
1575 SMLoc Loc = SMLoc::getFromPointer(DotDispStr.data());
1576 unsigned Len = DotDispStr.size();
1577 unsigned Val = OrigDispVal + DotDispVal;
1578 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_DotOperator, Loc, Len,
1579 Val));
1580 }
1581
1582 NewDisp = MCConstantExpr::Create(OrigDispVal + DotDispVal, getContext());
1583 return false;
1584}
1585
1586/// Parse the 'offset' operator. This operator is used to specify the
1587/// location rather then the content of a variable.
1588X86Operand *X86AsmParser::ParseIntelOffsetOfOperator() {
1589 const AsmToken &Tok = Parser.getTok();
1590 SMLoc OffsetOfLoc = Tok.getLoc();
1591 Parser.Lex(); // Eat offset.
1592
1593 const MCExpr *Val;
1594 InlineAsmIdentifierInfo Info;
1595 SMLoc Start = Tok.getLoc(), End;
1596 StringRef Identifier = Tok.getString();
1597 if (ParseIntelIdentifier(Val, Identifier, Info,
1598 /*Unevaluated=*/false, End))
1599 return 0;
1600
1601 // Don't emit the offset operator.
1602 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_Skip, OffsetOfLoc, 7));
1603
1604 // The offset operator will have an 'r' constraint, thus we need to create
1605 // register operand to ensure proper matching. Just pick a GPR based on
1606 // the size of a pointer.
1607 unsigned RegNo = is64BitMode() ? X86::RBX : X86::EBX;
1608 return X86Operand::CreateReg(RegNo, Start, End, /*GetAddress=*/true,
1609 OffsetOfLoc, Identifier, Info.OpDecl);
1610}
1611
1612enum IntelOperatorKind {
1613 IOK_LENGTH,
1614 IOK_SIZE,
1615 IOK_TYPE
1616};
1617
1618/// Parse the 'LENGTH', 'TYPE' and 'SIZE' operators. The LENGTH operator
1619/// returns the number of elements in an array. It returns the value 1 for
1620/// non-array variables. The SIZE operator returns the size of a C or C++
1621/// variable. A variable's size is the product of its LENGTH and TYPE. The
1622/// TYPE operator returns the size of a C or C++ type or variable. If the
1623/// variable is an array, TYPE returns the size of a single element.
1624X86Operand *X86AsmParser::ParseIntelOperator(unsigned OpKind) {
1625 const AsmToken &Tok = Parser.getTok();
1626 SMLoc TypeLoc = Tok.getLoc();
1627 Parser.Lex(); // Eat operator.
1628
1629 const MCExpr *Val = 0;
1630 InlineAsmIdentifierInfo Info;
1631 SMLoc Start = Tok.getLoc(), End;
1632 StringRef Identifier = Tok.getString();
1633 if (ParseIntelIdentifier(Val, Identifier, Info,
1634 /*Unevaluated=*/true, End))
1635 return 0;
1636
1637 if (!Info.OpDecl)
1638 return ErrorOperand(Start, "unable to lookup expression");
1639
1640 unsigned CVal = 0;
1641 switch(OpKind) {
1642 default: llvm_unreachable("Unexpected operand kind!");
1643 case IOK_LENGTH: CVal = Info.Length; break;
1644 case IOK_SIZE: CVal = Info.Size; break;
1645 case IOK_TYPE: CVal = Info.Type; break;
1646 }
1647
1648 // Rewrite the type operator and the C or C++ type or variable in terms of an
1649 // immediate. E.g. TYPE foo -> $$4
1650 unsigned Len = End.getPointer() - TypeLoc.getPointer();
1651 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_Imm, TypeLoc, Len, CVal));
1652
1653 const MCExpr *Imm = MCConstantExpr::Create(CVal, getContext());
1654 return X86Operand::CreateImm(Imm, Start, End);
1655}
1656
1657X86Operand *X86AsmParser::ParseIntelOperand() {
1658 const AsmToken &Tok = Parser.getTok();
1659 SMLoc Start, End;
1660
1661 // Offset, length, type and size operators.
1662 if (isParsingInlineAsm()) {
1663 StringRef AsmTokStr = Tok.getString();
1664 if (AsmTokStr == "offset" || AsmTokStr == "OFFSET")
1665 return ParseIntelOffsetOfOperator();
1666 if (AsmTokStr == "length" || AsmTokStr == "LENGTH")
1667 return ParseIntelOperator(IOK_LENGTH);
1668 if (AsmTokStr == "size" || AsmTokStr == "SIZE")
1669 return ParseIntelOperator(IOK_SIZE);
1670 if (AsmTokStr == "type" || AsmTokStr == "TYPE")
1671 return ParseIntelOperator(IOK_TYPE);
1672 }
1673
1674 unsigned Size = getIntelMemOperandSize(Tok.getString());
1675 if (Size) {
1676 Parser.Lex(); // Eat operand size (e.g., byte, word).
1677 if (Tok.getString() != "PTR" && Tok.getString() != "ptr")
1678 return ErrorOperand(Start, "Expected 'PTR' or 'ptr' token!");
1679 Parser.Lex(); // Eat ptr.
1680 }
1681 Start = Tok.getLoc();
1682
1683 // Immediate.
1684 if (getLexer().is(AsmToken::Integer) || getLexer().is(AsmToken::Minus) ||
1685 getLexer().is(AsmToken::LParen)) {
1686 AsmToken StartTok = Tok;
1687 IntelExprStateMachine SM(/*Imm=*/0, /*StopOnLBrac=*/true,
1688 /*AddImmPrefix=*/false);
1689 if (ParseIntelExpression(SM, End))
1690 return 0;
1691
1692 int64_t Imm = SM.getImm();
1693 if (isParsingInlineAsm()) {
1694 unsigned Len = Tok.getLoc().getPointer() - Start.getPointer();
1695 if (StartTok.getString().size() == Len)
1696 // Just add a prefix if this wasn't a complex immediate expression.
1697 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_ImmPrefix, Start));
1698 else
1699 // Otherwise, rewrite the complex expression as a single immediate.
1700 InstInfo->AsmRewrites->push_back(AsmRewrite(AOK_Imm, Start, Len, Imm));
1701 }
1702
1703 if (getLexer().isNot(AsmToken::LBrac)) {
1704 const MCExpr *ImmExpr = MCConstantExpr::Create(Imm, getContext());
1705 return X86Operand::CreateImm(ImmExpr, Start, End);
1706 }
1707
1708 // Only positive immediates are valid.
1709 if (Imm < 0)
1710 return ErrorOperand(Start, "expected a positive immediate displacement "
1711 "before bracketed expr.");
1712
1713 // Parse ImmDisp [ BaseReg + Scale*IndexReg + Disp ].
1714 return ParseIntelMemOperand(Imm, Start, Size);
1715 }
1716
1717 // Register.
1718 unsigned RegNo = 0;
1719 if (!ParseRegister(RegNo, Start, End)) {
1720 // If this is a segment register followed by a ':', then this is the start
1721 // of a segment override, otherwise this is a normal register reference.
1722 if (getLexer().isNot(AsmToken::Colon))
1723 return X86Operand::CreateReg(RegNo, Start, End);
1724
1725 return ParseIntelSegmentOverride(/*SegReg=*/RegNo, Start, Size);
1726 }
1727
1728 // Memory operand.
1729 return ParseIntelMemOperand(/*Disp=*/0, Start, Size);
1730}
1731
1732X86Operand *X86AsmParser::ParseATTOperand() {
1733 switch (getLexer().getKind()) {
1734 default:
1735 // Parse a memory operand with no segment register.
1736 return ParseMemOperand(0, Parser.getTok().getLoc());
1737 case AsmToken::Percent: {
1738 // Read the register.
1739 unsigned RegNo;
1740 SMLoc Start, End;
1741 if (ParseRegister(RegNo, Start, End)) return 0;
1742 if (RegNo == X86::EIZ || RegNo == X86::RIZ) {
1743 Error(Start, "%eiz and %riz can only be used as index registers",
1744 SMRange(Start, End));
1745 return 0;
1746 }
1747
1748 // If this is a segment register followed by a ':', then this is the start
1749 // of a memory reference, otherwise this is a normal register reference.
1750 if (getLexer().isNot(AsmToken::Colon))
1751 return X86Operand::CreateReg(RegNo, Start, End);
1752
1753 getParser().Lex(); // Eat the colon.
1754 return ParseMemOperand(RegNo, Start);
1755 }
1756 case AsmToken::Dollar: {
1757 // $42 -> immediate.
1758 SMLoc Start = Parser.getTok().getLoc(), End;
1759 Parser.Lex();
1760 const MCExpr *Val;
1761 if (getParser().parseExpression(Val, End))
1762 return 0;
1763 return X86Operand::CreateImm(Val, Start, End);
1764 }
1765 }
1766}
1767
1768/// ParseMemOperand: segment: disp(basereg, indexreg, scale). The '%ds:' prefix
1769/// has already been parsed if present.
1770X86Operand *X86AsmParser::ParseMemOperand(unsigned SegReg, SMLoc MemStart) {
1771
1772 // We have to disambiguate a parenthesized expression "(4+5)" from the start
1773 // of a memory operand with a missing displacement "(%ebx)" or "(,%eax)". The
1774 // only way to do this without lookahead is to eat the '(' and see what is
1775 // after it.
1776 const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
1777 if (getLexer().isNot(AsmToken::LParen)) {
1778 SMLoc ExprEnd;
1779 if (getParser().parseExpression(Disp, ExprEnd)) return 0;
1780
1781 // After parsing the base expression we could either have a parenthesized
1782 // memory address or not. If not, return now. If so, eat the (.
1783 if (getLexer().isNot(AsmToken::LParen)) {
1784 // Unless we have a segment register, treat this as an immediate.
1785 if (SegReg == 0)
1786 return X86Operand::CreateMem(Disp, MemStart, ExprEnd);
1787 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
1788 }
1789
1790 // Eat the '('.
1791 Parser.Lex();
1792 } else {
1793 // Okay, we have a '('. We don't know if this is an expression or not, but
1794 // so we have to eat the ( to see beyond it.
1795 SMLoc LParenLoc = Parser.getTok().getLoc();
1796 Parser.Lex(); // Eat the '('.
1797
1798 if (getLexer().is(AsmToken::Percent) || getLexer().is(AsmToken::Comma)) {
1799 // Nothing to do here, fall into the code below with the '(' part of the
1800 // memory operand consumed.
1801 } else {
1802 SMLoc ExprEnd;
1803
1804 // It must be an parenthesized expression, parse it now.
1805 if (getParser().parseParenExpression(Disp, ExprEnd))
1806 return 0;
1807
1808 // After parsing the base expression we could either have a parenthesized
1809 // memory address or not. If not, return now. If so, eat the (.
1810 if (getLexer().isNot(AsmToken::LParen)) {
1811 // Unless we have a segment register, treat this as an immediate.
1812 if (SegReg == 0)
1813 return X86Operand::CreateMem(Disp, LParenLoc, ExprEnd);
1814 return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
1815 }
1816
1817 // Eat the '('.
1818 Parser.Lex();
1819 }
1820 }
1821
1822 // If we reached here, then we just ate the ( of the memory operand. Process
1823 // the rest of the memory operand.
1824 unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
1825 SMLoc IndexLoc;
1826
1827 if (getLexer().is(AsmToken::Percent)) {
1828 SMLoc StartLoc, EndLoc;
1829 if (ParseRegister(BaseReg, StartLoc, EndLoc)) return 0;
1830 if (BaseReg == X86::EIZ || BaseReg == X86::RIZ) {
1831 Error(StartLoc, "eiz and riz can only be used as index registers",
1832 SMRange(StartLoc, EndLoc));
1833 return 0;
1834 }
1835 }
1836
1837 if (getLexer().is(AsmToken::Comma)) {
1838 Parser.Lex(); // Eat the comma.
1839 IndexLoc = Parser.getTok().getLoc();
1840
1841 // Following the comma we should have either an index register, or a scale
1842 // value. We don't support the later form, but we want to parse it
1843 // correctly.
1844 //
1845 // Not that even though it would be completely consistent to support syntax
1846 // like "1(%eax,,1)", the assembler doesn't. Use "eiz" or "riz" for this.
1847 if (getLexer().is(AsmToken::Percent)) {
1848 SMLoc L;
1849 if (ParseRegister(IndexReg, L, L)) return 0;
1850
1851 if (getLexer().isNot(AsmToken::RParen)) {
1852 // Parse the scale amount:
1853 // ::= ',' [scale-expression]
1854 if (getLexer().isNot(AsmToken::Comma)) {
1855 Error(Parser.getTok().getLoc(),
1856 "expected comma in scale expression");
1857 return 0;
1858 }
1859 Parser.Lex(); // Eat the comma.
1860
1861 if (getLexer().isNot(AsmToken::RParen)) {
1862 SMLoc Loc = Parser.getTok().getLoc();
1863
1864 int64_t ScaleVal;
1865 if (getParser().parseAbsoluteExpression(ScaleVal)){
1866 Error(Loc, "expected scale expression");
1867 return 0;
1868 }
1869
1870 // Validate the scale amount.
1871 if (ScaleVal != 1 && ScaleVal != 2 && ScaleVal != 4 && ScaleVal != 8){
1872 Error(Loc, "scale factor in address must be 1, 2, 4 or 8");
1873 return 0;
1874 }
1875 Scale = (unsigned)ScaleVal;
1876 }
1877 }
1878 } else if (getLexer().isNot(AsmToken::RParen)) {
1879 // A scale amount without an index is ignored.
1880 // index.
1881 SMLoc Loc = Parser.getTok().getLoc();
1882
1883 int64_t Value;
1884 if (getParser().parseAbsoluteExpression(Value))
1885 return 0;
1886
1887 if (Value != 1)
1888 Warning(Loc, "scale factor without index register is ignored");
1889 Scale = 1;
1890 }
1891 }
1892
1893 // Ok, we've eaten the memory operand, verify we have a ')' and eat it too.
1894 if (getLexer().isNot(AsmToken::RParen)) {
1895 Error(Parser.getTok().getLoc(), "unexpected token in memory operand");
1896 return 0;
1897 }
1898 SMLoc MemEnd = Parser.getTok().getEndLoc();
1899 Parser.Lex(); // Eat the ')'.
1900
1901 // If we have both a base register and an index register make sure they are
1902 // both 64-bit or 32-bit registers.
1903 // To support VSIB, IndexReg can be 128-bit or 256-bit registers.
1904 if (BaseReg != 0 && IndexReg != 0) {
1905 if (X86MCRegisterClasses[X86::GR64RegClassID].contains(BaseReg) &&
1906 (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) ||
1907 X86MCRegisterClasses[X86::GR32RegClassID].contains(IndexReg)) &&
1908 IndexReg != X86::RIZ) {
1909 Error(IndexLoc, "index register is 32-bit, but base register is 64-bit");
1910 return 0;
1911 }
1912 if (X86MCRegisterClasses[X86::GR32RegClassID].contains(BaseReg) &&
1913 (X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg) ||
1914 X86MCRegisterClasses[X86::GR64RegClassID].contains(IndexReg)) &&
1915 IndexReg != X86::EIZ){
1916 Error(IndexLoc, "index register is 64-bit, but base register is 32-bit");
1917 return 0;
1918 }
1919 }
1920
1921 return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
1922 MemStart, MemEnd);
1923}
1924
1925bool X86AsmParser::
1926ParseInstruction(ParseInstructionInfo &Info, StringRef Name, SMLoc NameLoc,
1927 SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1928 InstInfo = &Info;
1929 StringRef PatchedName = Name;
1930
1931 // FIXME: Hack to recognize setneb as setne.
1932 if (PatchedName.startswith("set") && PatchedName.endswith("b") &&
1933 PatchedName != "setb" && PatchedName != "setnb")
1934 PatchedName = PatchedName.substr(0, Name.size()-1);
1935
1936 // FIXME: Hack to recognize cmp<comparison code>{ss,sd,ps,pd}.
1937 const MCExpr *ExtraImmOp = 0;
1938 if ((PatchedName.startswith("cmp") || PatchedName.startswith("vcmp")) &&
1939 (PatchedName.endswith("ss") || PatchedName.endswith("sd") ||
1940 PatchedName.endswith("ps") || PatchedName.endswith("pd"))) {
1941 bool IsVCMP = PatchedName[0] == 'v';
1942 unsigned SSECCIdx = IsVCMP ? 4 : 3;
1943 unsigned SSEComparisonCode = StringSwitch<unsigned>(
1944 PatchedName.slice(SSECCIdx, PatchedName.size() - 2))
1945 .Case("eq", 0x00)
1946 .Case("lt", 0x01)
1947 .Case("le", 0x02)
1948 .Case("unord", 0x03)
1949 .Case("neq", 0x04)
1950 .Case("nlt", 0x05)
1951 .Case("nle", 0x06)
1952 .Case("ord", 0x07)
1953 /* AVX only from here */
1954 .Case("eq_uq", 0x08)
1955 .Case("nge", 0x09)
1956 .Case("ngt", 0x0A)
1957 .Case("false", 0x0B)
1958 .Case("neq_oq", 0x0C)
1959 .Case("ge", 0x0D)
1960 .Case("gt", 0x0E)
1961 .Case("true", 0x0F)
1962 .Case("eq_os", 0x10)
1963 .Case("lt_oq", 0x11)
1964 .Case("le_oq", 0x12)
1965 .Case("unord_s", 0x13)
1966 .Case("neq_us", 0x14)
1967 .Case("nlt_uq", 0x15)
1968 .Case("nle_uq", 0x16)
1969 .Case("ord_s", 0x17)
1970 .Case("eq_us", 0x18)
1971 .Case("nge_uq", 0x19)
1972 .Case("ngt_uq", 0x1A)
1973 .Case("false_os", 0x1B)
1974 .Case("neq_os", 0x1C)
1975 .Case("ge_oq", 0x1D)
1976 .Case("gt_oq", 0x1E)
1977 .Case("true_us", 0x1F)
1978 .Default(~0U);
1979 if (SSEComparisonCode != ~0U && (IsVCMP || SSEComparisonCode < 8)) {
1980 ExtraImmOp = MCConstantExpr::Create(SSEComparisonCode,
1981 getParser().getContext());
1982 if (PatchedName.endswith("ss")) {
1983 PatchedName = IsVCMP ? "vcmpss" : "cmpss";
1984 } else if (PatchedName.endswith("sd")) {
1985 PatchedName = IsVCMP ? "vcmpsd" : "cmpsd";
1986 } else if (PatchedName.endswith("ps")) {
1987 PatchedName = IsVCMP ? "vcmpps" : "cmpps";
1988 } else {
1989 assert(PatchedName.endswith("pd") && "Unexpected mnemonic!");
1990 PatchedName = IsVCMP ? "vcmppd" : "cmppd";
1991 }
1992 }
1993 }
1994
1995 Operands.push_back(X86Operand::CreateToken(PatchedName, NameLoc));
1996
1997 if (ExtraImmOp && !isParsingIntelSyntax())
1998 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
1999
2000 // Determine whether this is an instruction prefix.
2001 bool isPrefix =
2002 Name == "lock" || Name == "rep" ||
2003 Name == "repe" || Name == "repz" ||
2004 Name == "repne" || Name == "repnz" ||
2005 Name == "rex64" || Name == "data16";
2006
2007
2008 // This does the actual operand parsing. Don't parse any more if we have a
2009 // prefix juxtaposed with an operation like "lock incl 4(%rax)", because we
2010 // just want to parse the "lock" as the first instruction and the "incl" as
2011 // the next one.
2012 if (getLexer().isNot(AsmToken::EndOfStatement) && !isPrefix) {
2013
2014 // Parse '*' modifier.
2015 if (getLexer().is(AsmToken::Star)) {
2016 SMLoc Loc = Parser.getTok().getLoc();
2017 Operands.push_back(X86Operand::CreateToken("*", Loc));
2018 Parser.Lex(); // Eat the star.
2019 }
2020
2021 // Read the first operand.
2022 if (X86Operand *Op = ParseOperand())
2023 Operands.push_back(Op);
2024 else {
2025 Parser.eatToEndOfStatement();
2026 return true;
2027 }
2028
2029 while (getLexer().is(AsmToken::Comma)) {
2030 Parser.Lex(); // Eat the comma.
2031
2032 // Parse and remember the operand.
2033 if (X86Operand *Op = ParseOperand())
2034 Operands.push_back(Op);
2035 else {
2036 Parser.eatToEndOfStatement();
2037 return true;
2038 }
2039 }
2040
2041 if (STI.getFeatureBits() & X86::FeatureAVX512) {
2042 // Parse mask register {%k1}
2043 if (getLexer().is(AsmToken::LCurly)) {
2044 SMLoc Loc = Parser.getTok().getLoc();
2045 Operands.push_back(X86Operand::CreateToken("{", Loc));
2046 Parser.Lex(); // Eat the {
2047 if (X86Operand *Op = ParseOperand()) {
2048 Operands.push_back(Op);
2049 if (!getLexer().is(AsmToken::RCurly)) {
2050 SMLoc Loc = getLexer().getLoc();
2051 Parser.eatToEndOfStatement();
2052 return Error(Loc, "Expected } at this point");
2053 }
2054 Loc = Parser.getTok().getLoc();
2055 Operands.push_back(X86Operand::CreateToken("}", Loc));
2056 Parser.Lex(); // Eat the }
2057 } else {
2058 Parser.eatToEndOfStatement();
2059 return true;
2060 }
2061 }
2062 // Parse "zeroing non-masked" semantic {z}
2063 if (getLexer().is(AsmToken::LCurly)) {
2064 SMLoc Loc = Parser.getTok().getLoc();
2065 Operands.push_back(X86Operand::CreateToken("{z}", Loc));
2066 Parser.Lex(); // Eat the {
2067 if (!getLexer().is(AsmToken::Identifier) || getLexer().getTok().getIdentifier() != "z") {
2068 SMLoc Loc = getLexer().getLoc();
2069 Parser.eatToEndOfStatement();
2070 return Error(Loc, "Expected z at this point");
2071 }
2072 Parser.Lex(); // Eat the z
2073 if (!getLexer().is(AsmToken::RCurly)) {
2074 SMLoc Loc = getLexer().getLoc();
2075 Parser.eatToEndOfStatement();
2076 return Error(Loc, "Expected } at this point");
2077 }
2078 Parser.Lex(); // Eat the }
2079 }
2080 }
2081
2082 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2083 SMLoc Loc = getLexer().getLoc();
2084 Parser.eatToEndOfStatement();
2085 return Error(Loc, "unexpected token in argument list");
2086 }
2087 }
2088
2089 if (getLexer().is(AsmToken::EndOfStatement))
2090 Parser.Lex(); // Consume the EndOfStatement
2091 else if (isPrefix && getLexer().is(AsmToken::Slash))
2092 Parser.Lex(); // Consume the prefix separator Slash
2093
2094 if (ExtraImmOp && isParsingIntelSyntax())
2095 Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
2096
2097 // This is a terrible hack to handle "out[bwl]? %al, (%dx)" ->
2098 // "outb %al, %dx". Out doesn't take a memory form, but this is a widely
2099 // documented form in various unofficial manuals, so a lot of code uses it.
2100 if ((Name == "outb" || Name == "outw" || Name == "outl" || Name == "out") &&
2101 Operands.size() == 3) {
2102 X86Operand &Op = *(X86Operand*)Operands.back();
2103 if (Op.isMem() && Op.Mem.SegReg == 0 &&
2104 isa<MCConstantExpr>(Op.Mem.Disp) &&
2105 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
2106 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
2107 SMLoc Loc = Op.getEndLoc();
2108 Operands.back() = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
2109 delete &Op;
2110 }
2111 }
2112 // Same hack for "in[bwl]? (%dx), %al" -> "inb %dx, %al".
2113 if ((Name == "inb" || Name == "inw" || Name == "inl" || Name == "in") &&
2114 Operands.size() == 3) {
2115 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
2116 if (Op.isMem() && Op.Mem.SegReg == 0 &&
2117 isa<MCConstantExpr>(Op.Mem.Disp) &&
2118 cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
2119 Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
2120 SMLoc Loc = Op.getEndLoc();
2121 Operands.begin()[1] = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
2122 delete &Op;
2123 }
2124 }
2125 // Transform "ins[bwl] %dx, %es:(%edi)" into "ins[bwl]"
2126 if (Name.startswith("ins") && Operands.size() == 3 &&
2127 (Name == "insb" || Name == "insw" || Name == "insl")) {
2128 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
2129 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
2130 if (Op.isReg() && Op.getReg() == X86::DX && isDstOp(Op2)) {
2131 Operands.pop_back();
2132 Operands.pop_back();
2133 delete &Op;
2134 delete &Op2;
2135 }
2136 }
2137
2138 // Transform "outs[bwl] %ds:(%esi), %dx" into "out[bwl]"
2139 if (Name.startswith("outs") && Operands.size() == 3 &&
2140 (Name == "outsb" || Name == "outsw" || Name == "outsl")) {
2141 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
2142 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
2143 if (isSrcOp(Op) && Op2.isReg() && Op2.getReg() == X86::DX) {
2144 Operands.pop_back();
2145 Operands.pop_back();
2146 delete &Op;
2147 delete &Op2;
2148 }
2149 }
2150
2151 // Transform "movs[bwl] %ds:(%esi), %es:(%edi)" into "movs[bwl]"
2152 if (Name.startswith("movs") && Operands.size() == 3 &&
2153 (Name == "movsb" || Name == "movsw" || Name == "movsl" ||
2154 (is64BitMode() && Name == "movsq"))) {
2155 X86Operand &Op = *(X86Operand*)Operands.begin()[1];
2156 X86Operand &Op2 = *(X86Operand*)Operands.begin()[2];
2157 if (isSrcOp(Op) && isDstOp(Op2)) {
2158 Operands.pop_back();
2159 Operands.pop_back();
2160 delete &Op;
2161 delete &Op2;
2162 }
2163 }
2164 // Transform "lods[bwl] %ds:(%esi),{%al,%ax,%eax,%rax}" into "lods[bwl]"
2165 if (Name.startswith("lods") && Operands.size() == 3 &&
2166 (Name == "lods" || Name == "lodsb" || Name == "lodsw" ||
2167 Name == "lodsl" || (is64BitMode() && Name == "lodsq"))) {
2168 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
2169 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
2170 if (isSrcOp(*Op1) && Op2->isReg()) {
2171 const char *ins;
2172 unsigned reg = Op2->getReg();
2173 bool isLods = Name == "lods";
2174 if (reg == X86::AL && (isLods || Name == "lodsb"))
2175 ins = "lodsb";
2176 else if (reg == X86::AX && (isLods || Name == "lodsw"))
2177 ins = "lodsw";
2178 else if (reg == X86::EAX && (isLods || Name == "lodsl"))
2179 ins = "lodsl";
2180 else if (reg == X86::RAX && (isLods || Name == "lodsq"))
2181 ins = "lodsq";
2182 else
2183 ins = NULL;
2184 if (ins != NULL) {
2185 Operands.pop_back();
2186 Operands.pop_back();
2187 delete Op1;
2188 delete Op2;
2189 if (Name != ins)
2190 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
2191 }
2192 }
2193 }
2194 // Transform "stos[bwl] {%al,%ax,%eax,%rax},%es:(%edi)" into "stos[bwl]"
2195 if (Name.startswith("stos") && Operands.size() == 3 &&
2196 (Name == "stos" || Name == "stosb" || Name == "stosw" ||
2197 Name == "stosl" || (is64BitMode() && Name == "stosq"))) {
2198 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
2199 X86Operand *Op2 = static_cast<X86Operand*>(Operands[2]);
2200 if (isDstOp(*Op2) && Op1->isReg()) {
2201 const char *ins;
2202 unsigned reg = Op1->getReg();
2203 bool isStos = Name == "stos";
2204 if (reg == X86::AL && (isStos || Name == "stosb"))
2205 ins = "stosb";
2206 else if (reg == X86::AX && (isStos || Name == "stosw"))
2207 ins = "stosw";
2208 else if (reg == X86::EAX && (isStos || Name == "stosl"))
2209 ins = "stosl";
2210 else if (reg == X86::RAX && (isStos || Name == "stosq"))
2211 ins = "stosq";
2212 else
2213 ins = NULL;
2214 if (ins != NULL) {
2215 Operands.pop_back();
2216 Operands.pop_back();
2217 delete Op1;
2218 delete Op2;
2219 if (Name != ins)
2220 static_cast<X86Operand*>(Operands[0])->setTokenValue(ins);
2221 }
2222 }
2223 }
2224
2225 // FIXME: Hack to handle recognize s{hr,ar,hl} $1, <op>. Canonicalize to
2226 // "shift <op>".
2227 if ((Name.startswith("shr") || Name.startswith("sar") ||
2228 Name.startswith("shl") || Name.startswith("sal") ||
2229 Name.startswith("rcl") || Name.startswith("rcr") ||
2230 Name.startswith("rol") || Name.startswith("ror")) &&
2231 Operands.size() == 3) {
2232 if (isParsingIntelSyntax()) {
2233 // Intel syntax
2234 X86Operand *Op1 = static_cast<X86Operand*>(Operands[2]);
2235 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
2236 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
2237 delete Operands[2];
2238 Operands.pop_back();
2239 }
2240 } else {
2241 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
2242 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
2243 cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
2244 delete Operands[1];
2245 Operands.erase(Operands.begin() + 1);
2246 }
2247 }
2248 }
2249
2250 // Transforms "int $3" into "int3" as a size optimization. We can't write an
2251 // instalias with an immediate operand yet.
2252 if (Name == "int" && Operands.size() == 2) {
2253 X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
2254 if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
2255 cast<MCConstantExpr>(Op1->getImm())->getValue() == 3) {
2256 delete Operands[1];
2257 Operands.erase(Operands.begin() + 1);
2258 static_cast<X86Operand*>(Operands[0])->setTokenValue("int3");
2259 }
2260 }
2261
2262 return false;
2263}
2264
2265static bool convertToSExti8(MCInst &Inst, unsigned Opcode, unsigned Reg,
2266 bool isCmp) {
2267 MCInst TmpInst;
2268 TmpInst.setOpcode(Opcode);
2269 if (!isCmp)
2270 TmpInst.addOperand(MCOperand::CreateReg(Reg));
2271 TmpInst.addOperand(MCOperand::CreateReg(Reg));
2272 TmpInst.addOperand(Inst.getOperand(0));
2273 Inst = TmpInst;
2274 return true;
2275}
2276
2277static bool convert16i16to16ri8(MCInst &Inst, unsigned Opcode,
2278 bool isCmp = false) {
2279 if (!Inst.getOperand(0).isImm() ||
2280 !isImmSExti16i8Value(Inst.getOperand(0).getImm()))
2281 return false;
2282
2283 return convertToSExti8(Inst, Opcode, X86::AX, isCmp);
2284}
2285
2286static bool convert32i32to32ri8(MCInst &Inst, unsigned Opcode,
2287 bool isCmp = false) {
2288 if (!Inst.getOperand(0).isImm() ||
2289 !isImmSExti32i8Value(Inst.getOperand(0).getImm()))
2290 return false;
2291
2292 return convertToSExti8(Inst, Opcode, X86::EAX, isCmp);
2293}
2294
2295static bool convert64i32to64ri8(MCInst &Inst, unsigned Opcode,
2296 bool isCmp = false) {
2297 if (!Inst.getOperand(0).isImm() ||
2298 !isImmSExti64i8Value(Inst.getOperand(0).getImm()))
2299 return false;
2300
2301 return convertToSExti8(Inst, Opcode, X86::RAX, isCmp);
2302}
2303
2304bool X86AsmParser::
2305processInstruction(MCInst &Inst,
2306 const SmallVectorImpl<MCParsedAsmOperand*> &Ops) {
2307 switch (Inst.getOpcode()) {
2308 default: return false;
2309 case X86::AND16i16: return convert16i16to16ri8(Inst, X86::AND16ri8);
2310 case X86::AND32i32: return convert32i32to32ri8(Inst, X86::AND32ri8);
2311 case X86::AND64i32: return convert64i32to64ri8(Inst, X86::AND64ri8);
2312 case X86::XOR16i16: return convert16i16to16ri8(Inst, X86::XOR16ri8);
2313 case X86::XOR32i32: return convert32i32to32ri8(Inst, X86::XOR32ri8);
2314 case X86::XOR64i32: return convert64i32to64ri8(Inst, X86::XOR64ri8);
2315 case X86::OR16i16: return convert16i16to16ri8(Inst, X86::OR16ri8);
2316 case X86::OR32i32: return convert32i32to32ri8(Inst, X86::OR32ri8);
2317 case X86::OR64i32: return convert64i32to64ri8(Inst, X86::OR64ri8);
2318 case X86::CMP16i16: return convert16i16to16ri8(Inst, X86::CMP16ri8, true);
2319 case X86::CMP32i32: return convert32i32to32ri8(Inst, X86::CMP32ri8, true);
2320 case X86::CMP64i32: return convert64i32to64ri8(Inst, X86::CMP64ri8, true);
2321 case X86::ADD16i16: return convert16i16to16ri8(Inst, X86::ADD16ri8);
2322 case X86::ADD32i32: return convert32i32to32ri8(Inst, X86::ADD32ri8);
2323 case X86::ADD64i32: return convert64i32to64ri8(Inst, X86::ADD64ri8);
2324 case X86::SUB16i16: return convert16i16to16ri8(Inst, X86::SUB16ri8);
2325 case X86::SUB32i32: return convert32i32to32ri8(Inst, X86::SUB32ri8);
2326 case X86::SUB64i32: return convert64i32to64ri8(Inst, X86::SUB64ri8);
2327 case X86::ADC16i16: return convert16i16to16ri8(Inst, X86::ADC16ri8);
2328 case X86::ADC32i32: return convert32i32to32ri8(Inst, X86::ADC32ri8);
2329 case X86::ADC64i32: return convert64i32to64ri8(Inst, X86::ADC64ri8);
2330 case X86::SBB16i16: return convert16i16to16ri8(Inst, X86::SBB16ri8);
2331 case X86::SBB32i32: return convert32i32to32ri8(Inst, X86::SBB32ri8);
2332 case X86::SBB64i32: return convert64i32to64ri8(Inst, X86::SBB64ri8);
2333 case X86::VMOVAPDrr:
2334 case X86::VMOVAPDYrr:
2335 case X86::VMOVAPSrr:
2336 case X86::VMOVAPSYrr:
2337 case X86::VMOVDQArr:
2338 case X86::VMOVDQAYrr:
2339 case X86::VMOVDQUrr:
2340 case X86::VMOVDQUYrr:
2341 case X86::VMOVUPDrr:
2342 case X86::VMOVUPDYrr:
2343 case X86::VMOVUPSrr:
2344 case X86::VMOVUPSYrr: {
2345 if (X86II::isX86_64ExtendedReg(Inst.getOperand(0).getReg()) ||
2346 !X86II::isX86_64ExtendedReg(Inst.getOperand(1).getReg()))
2347 return false;
2348
2349 unsigned NewOpc;
2350 switch (Inst.getOpcode()) {
2351 default: llvm_unreachable("Invalid opcode");
2352 case X86::VMOVAPDrr: NewOpc = X86::VMOVAPDrr_REV; break;
2353 case X86::VMOVAPDYrr: NewOpc = X86::VMOVAPDYrr_REV; break;
2354 case X86::VMOVAPSrr: NewOpc = X86::VMOVAPSrr_REV; break;
2355 case X86::VMOVAPSYrr: NewOpc = X86::VMOVAPSYrr_REV; break;
2356 case X86::VMOVDQArr: NewOpc = X86::VMOVDQArr_REV; break;
2357 case X86::VMOVDQAYrr: NewOpc = X86::VMOVDQAYrr_REV; break;
2358 case X86::VMOVDQUrr: NewOpc = X86::VMOVDQUrr_REV; break;
2359 case X86::VMOVDQUYrr: NewOpc = X86::VMOVDQUYrr_REV; break;
2360 case X86::VMOVUPDrr: NewOpc = X86::VMOVUPDrr_REV; break;
2361 case X86::VMOVUPDYrr: NewOpc = X86::VMOVUPDYrr_REV; break;
2362 case X86::VMOVUPSrr: NewOpc = X86::VMOVUPSrr_REV; break;
2363 case X86::VMOVUPSYrr: NewOpc = X86::VMOVUPSYrr_REV; break;
2364 }
2365 Inst.setOpcode(NewOpc);
2366 return true;
2367 }
2368 case X86::VMOVSDrr:
2369 case X86::VMOVSSrr: {
2370 if (X86II::isX86_64ExtendedReg(Inst.getOperand(0).getReg()) ||
2371 !X86II::isX86_64ExtendedReg(Inst.getOperand(2).getReg()))
2372 return false;
2373 unsigned NewOpc;
2374 switch (Inst.getOpcode()) {
2375 default: llvm_unreachable("Invalid opcode");
2376 case X86::VMOVSDrr: NewOpc = X86::VMOVSDrr_REV; break;
2377 case X86::VMOVSSrr: NewOpc = X86::VMOVSSrr_REV; break;
2378 }
2379 Inst.setOpcode(NewOpc);
2380 return true;
2381 }
2382 }
2383}
2384
2385static const char *getSubtargetFeatureName(unsigned Val);
2386bool X86AsmParser::
2387MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
2388 SmallVectorImpl<MCParsedAsmOperand*> &Operands,
2389 MCStreamer &Out, unsigned &ErrorInfo,
2390 bool MatchingInlineAsm) {
2391 assert(!Operands.empty() && "Unexpect empty operand list!");
2392 X86Operand *Op = static_cast<X86Operand*>(Operands[0]);
2393 assert(Op->isToken() && "Leading operand should always be a mnemonic!");
2394 ArrayRef<SMRange> EmptyRanges = None;
2395
2396 // First, handle aliases that expand to multiple instructions.
2397 // FIXME: This should be replaced with a real .td file alias mechanism.
2398 // Also, MatchInstructionImpl should actually *do* the EmitInstruction
2399 // call.
2400 if (Op->getToken() == "fstsw" || Op->getToken() == "fstcw" ||
2401 Op->getToken() == "fstsww" || Op->getToken() == "fstcww" ||
2402 Op->getToken() == "finit" || Op->getToken() == "fsave" ||
2403 Op->getToken() == "fstenv" || Op->getToken() == "fclex") {
2404 MCInst Inst;
2405 Inst.setOpcode(X86::WAIT);
2406 Inst.setLoc(IDLoc);
2407 if (!MatchingInlineAsm)
2408 Out.EmitInstruction(Inst);
2409
2410 const char *Repl =
2411 StringSwitch<const char*>(Op->getToken())
2412 .Case("finit", "fninit")
2413 .Case("fsave", "fnsave")
2414 .Case("fstcw", "fnstcw")
2415 .Case("fstcww", "fnstcw")
2416 .Case("fstenv", "fnstenv")
2417 .Case("fstsw", "fnstsw")
2418 .Case("fstsww", "fnstsw")
2419 .Case("fclex", "fnclex")
2420 .Default(0);
2421 assert(Repl && "Unknown wait-prefixed instruction");
2422 delete Operands[0];
2423 Operands[0] = X86Operand::CreateToken(Repl, IDLoc);
2424 }
2425
2426 bool WasOriginallyInvalidOperand = false;
2427 MCInst Inst;
2428
2429 // First, try a direct match.
2430 switch (MatchInstructionImpl(Operands, Inst,
2431 ErrorInfo, MatchingInlineAsm,
2432 isParsingIntelSyntax())) {
2433 default: break;
2434 case Match_Success:
2435 // Some instructions need post-processing to, for example, tweak which
2436 // encoding is selected. Loop on it while changes happen so the
2437 // individual transformations can chain off each other.
2438 if (!MatchingInlineAsm)
2439 while (processInstruction(Inst, Operands))
2440 ;
2441
2442 Inst.setLoc(IDLoc);
2443 if (!MatchingInlineAsm)
2444 Out.EmitInstruction(Inst);
2445 Opcode = Inst.getOpcode();
2446 return false;
2447 case Match_MissingFeature: {
2448 assert(ErrorInfo && "Unknown missing feature!");
2449 // Special case the error message for the very common case where only
2450 // a single subtarget feature is missing.
2451 std::string Msg = "instruction requires:";
2452 unsigned Mask = 1;
2453 for (unsigned i = 0; i < (sizeof(ErrorInfo)*8-1); ++i) {
2454 if (ErrorInfo & Mask) {
2455 Msg += " ";
2456 Msg += getSubtargetFeatureName(ErrorInfo & Mask);
2457 }
2458 Mask <<= 1;
2459 }
2460 return Error(IDLoc, Msg, EmptyRanges, MatchingInlineAsm);
2461 }
2462 case Match_InvalidOperand:
2463 WasOriginallyInvalidOperand = true;
2464 break;
2465 case Match_MnemonicFail:
2466 break;
2467 }
2468
2469 // FIXME: Ideally, we would only attempt suffix matches for things which are
2470 // valid prefixes, and we could just infer the right unambiguous
2471 // type. However, that requires substantially more matcher support than the
2472 // following hack.
2473
2474 // Change the operand to point to a temporary token.
2475 StringRef Base = Op->getToken();
2476 SmallString<16> Tmp;
2477 Tmp += Base;
2478 Tmp += ' ';
2479 Op->setTokenValue(Tmp.str());
2480
2481 // If this instruction starts with an 'f', then it is a floating point stack
2482 // instruction. These come in up to three forms for 32-bit, 64-bit, and
2483 // 80-bit floating point, which use the suffixes s,l,t respectively.
2484 //
2485 // Otherwise, we assume that this may be an integer instruction, which comes
2486 // in 8/16/32/64-bit forms using the b,w,l,q suffixes respectively.
2487 const char *Suffixes = Base[0] != 'f' ? "bwlq" : "slt\0";
2488
2489 // Check for the various suffix matches.
2490 Tmp[Base.size()] = Suffixes[0];
2491 unsigned ErrorInfoIgnore;
2492 unsigned ErrorInfoMissingFeature = 0; // Init suppresses compiler warnings.
2493 unsigned Match1, Match2, Match3, Match4;
2494
2495 Match1 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
2496 MatchingInlineAsm, isParsingIntelSyntax());
2497 // If this returned as a missing feature failure, remember that.
2498 if (Match1 == Match_MissingFeature)
2499 ErrorInfoMissingFeature = ErrorInfoIgnore;
2500 Tmp[Base.size()] = Suffixes[1];
2501 Match2 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
2502 MatchingInlineAsm, isParsingIntelSyntax());
2503 // If this returned as a missing feature failure, remember that.
2504 if (Match2 == Match_MissingFeature)
2505 ErrorInfoMissingFeature = ErrorInfoIgnore;
2506 Tmp[Base.size()] = Suffixes[2];
2507 Match3 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
2508 MatchingInlineAsm, isParsingIntelSyntax());
2509 // If this returned as a missing feature failure, remember that.
2510 if (Match3 == Match_MissingFeature)
2511 ErrorInfoMissingFeature = ErrorInfoIgnore;
2512 Tmp[Base.size()] = Suffixes[3];
2513 Match4 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore,
2514 MatchingInlineAsm, isParsingIntelSyntax());
2515 // If this returned as a missing feature failure, remember that.
2516 if (Match4 == Match_MissingFeature)
2517 ErrorInfoMissingFeature = ErrorInfoIgnore;
2518
2519 // Restore the old token.
2520 Op->setTokenValue(Base);
2521
2522 // If exactly one matched, then we treat that as a successful match (and the
2523 // instruction will already have been filled in correctly, since the failing
2524 // matches won't have modified it).
2525 unsigned NumSuccessfulMatches =
2526 (Match1 == Match_Success) + (Match2 == Match_Success) +
2527 (Match3 == Match_Success) + (Match4 == Match_Success);
2528 if (NumSuccessfulMatches == 1) {
2529 Inst.setLoc(IDLoc);
2530 if (!MatchingInlineAsm)
2531 Out.EmitInstruction(Inst);
2532 Opcode = Inst.getOpcode();
2533 return false;
2534 }
2535
2536 // Otherwise, the match failed, try to produce a decent error message.
2537
2538 // If we had multiple suffix matches, then identify this as an ambiguous
2539 // match.
2540 if (NumSuccessfulMatches > 1) {
2541 char MatchChars[4];
2542 unsigned NumMatches = 0;
2543 if (Match1 == Match_Success) MatchChars[NumMatches++] = Suffixes[0];
2544 if (Match2 == Match_Success) MatchChars[NumMatches++] = Suffixes[1];
2545 if (Match3 == Match_Success) MatchChars[NumMatches++] = Suffixes[2];
2546 if (Match4 == Match_Success) MatchChars[NumMatches++] = Suffixes[3];
2547
2548 SmallString<126> Msg;
2549 raw_svector_ostream OS(Msg);
2550 OS << "ambiguous instructions require an explicit suffix (could be ";
2551 for (unsigned i = 0; i != NumMatches; ++i) {
2552 if (i != 0)
2553 OS << ", ";
2554 if (i + 1 == NumMatches)
2555 OS << "or ";
2556 OS << "'" << Base << MatchChars[i] << "'";
2557 }
2558 OS << ")";
2559 Error(IDLoc, OS.str(), EmptyRanges, MatchingInlineAsm);
2560 return true;
2561 }
2562
2563 // Okay, we know that none of the variants matched successfully.
2564
2565 // If all of the instructions reported an invalid mnemonic, then the original
2566 // mnemonic was invalid.
2567 if ((Match1 == Match_MnemonicFail) && (Match2 == Match_MnemonicFail) &&
2568 (Match3 == Match_MnemonicFail) && (Match4 == Match_MnemonicFail)) {
2569 if (!WasOriginallyInvalidOperand) {
2570 ArrayRef<SMRange> Ranges = MatchingInlineAsm ? EmptyRanges :
2571 Op->getLocRange();
2572 return Error(IDLoc, "invalid instruction mnemonic '" + Base + "'",
2573 Ranges, MatchingInlineAsm);
2574 }
2575
2576 // Recover location info for the operand if we know which was the problem.
2577 if (ErrorInfo != ~0U) {
2578 if (ErrorInfo >= Operands.size())
2579 return Error(IDLoc, "too few operands for instruction",
2580 EmptyRanges, MatchingInlineAsm);
2581
2582 X86Operand *Operand = (X86Operand*)Operands[ErrorInfo];
2583 if (Operand->getStartLoc().isValid()) {
2584 SMRange OperandRange = Operand->getLocRange();
2585 return Error(Operand->getStartLoc(), "invalid operand for instruction",
2586 OperandRange, MatchingInlineAsm);
2587 }
2588 }
2589
2590 return Error(IDLoc, "invalid operand for instruction", EmptyRanges,
2591 MatchingInlineAsm);
2592 }
2593
2594 // If one instruction matched with a missing feature, report this as a
2595 // missing feature.
2596 if ((Match1 == Match_MissingFeature) + (Match2 == Match_MissingFeature) +
2597 (Match3 == Match_MissingFeature) + (Match4 == Match_MissingFeature) == 1){
2598 std::string Msg = "instruction requires:";
2599 unsigned Mask = 1;
2600 for (unsigned i = 0; i < (sizeof(ErrorInfoMissingFeature)*8-1); ++i) {
2601 if (ErrorInfoMissingFeature & Mask) {
2602 Msg += " ";
2603 Msg += getSubtargetFeatureName(ErrorInfoMissingFeature & Mask);
2604 }
2605 Mask <<= 1;
2606 }
2607 return Error(IDLoc, Msg, EmptyRanges, MatchingInlineAsm);
2608 }
2609
2610 // If one instruction matched with an invalid operand, report this as an
2611 // operand failure.
2612 if ((Match1 == Match_InvalidOperand) + (Match2 == Match_InvalidOperand) +
2613 (Match3 == Match_InvalidOperand) + (Match4 == Match_InvalidOperand) == 1){
2614 Error(IDLoc, "invalid operand for instruction", EmptyRanges,
2615 MatchingInlineAsm);
2616 return true;
2617 }
2618
2619 // If all of these were an outright failure, report it in a useless way.
2620 Error(IDLoc, "unknown use of instruction mnemonic without a size suffix",
2621 EmptyRanges, MatchingInlineAsm);
2622 return true;
2623}
2624
2625
2626bool X86AsmParser::ParseDirective(AsmToken DirectiveID) {
2627 StringRef IDVal = DirectiveID.getIdentifier();
2628 if (IDVal == ".word")
2629 return ParseDirectiveWord(2, DirectiveID.getLoc());
2630 else if (IDVal.startswith(".code"))
2631 return ParseDirectiveCode(IDVal, DirectiveID.getLoc());
2632 else if (IDVal.startswith(".att_syntax")) {
2633 getParser().setAssemblerDialect(0);
2634 return false;
2635 } else if (IDVal.startswith(".intel_syntax")) {
2636 getParser().setAssemblerDialect(1);
2637 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2638 if(Parser.getTok().getString() == "noprefix") {
2639 // FIXME : Handle noprefix
2640 Parser.Lex();
2641 } else
2642 return true;
2643 }
2644 return false;
2645 }
2646 return true;
2647}
2648
2649/// ParseDirectiveWord
2650/// ::= .word [ expression (, expression)* ]
2651bool X86AsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
2652 if (getLexer().isNot(AsmToken::EndOfStatement)) {
2653 for (;;) {
2654 const MCExpr *Value;
2655 if (getParser().parseExpression(Value))
2656 return true;
2657
2658 getParser().getStreamer().EmitValue(Value, Size);
2659
2660 if (getLexer().is(AsmToken::EndOfStatement))
2661 break;
2662
2663 // FIXME: Improve diagnostic.
2664 if (getLexer().isNot(AsmToken::Comma))
2665 return Error(L, "unexpected token in directive");
2666 Parser.Lex();
2667 }
2668 }
2669
2670 Parser.Lex();
2671 return false;
2672}
2673
2674/// ParseDirectiveCode
2675/// ::= .code32 | .code64
2676bool X86AsmParser::ParseDirectiveCode(StringRef IDVal, SMLoc L) {
2677 if (IDVal == ".code32") {
2678 Parser.Lex();
2679 if (is64BitMode()) {
2680 SwitchMode();
2681 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
2682 }
2683 } else if (IDVal == ".code64") {
2684 Parser.Lex();
2685 if (!is64BitMode()) {
2686 SwitchMode();
2687 getParser().getStreamer().EmitAssemblerFlag(MCAF_Code64);
2688 }
2689 } else {
2690 return Error(L, "unexpected directive " + IDVal);
2691 }
2692
2693 return false;
2694}
2695
2696// Force static initialization.
2697extern "C" void LLVMInitializeX86AsmParser() {
2698 RegisterMCAsmParser<X86AsmParser> X(TheX86_32Target);
2699 RegisterMCAsmParser<X86AsmParser> Y(TheX86_64Target);
2700}
2701
2702#define GET_REGISTER_MATCHER
2703#define GET_MATCHER_IMPLEMENTATION
2704#define GET_SUBTARGET_FEATURE_NAME
2705#include "X86GenAsmMatcher.inc"