MC/AsmParser: Add support for allowing the conversion process to fail (via
[oota-llvm.git] / lib / Target / X86 / AsmParser / X86AsmParser.cpp
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 "llvm/Target/TargetAsmParser.h"
11 #include "X86.h"
12 #include "X86Subtarget.h"
13 #include "llvm/Target/TargetRegistry.h"
14 #include "llvm/Target/TargetAsmParser.h"
15 #include "llvm/MC/MCStreamer.h"
16 #include "llvm/MC/MCExpr.h"
17 #include "llvm/MC/MCInst.h"
18 #include "llvm/MC/MCParser/MCAsmLexer.h"
19 #include "llvm/MC/MCParser/MCAsmParser.h"
20 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/StringSwitch.h"
25 #include "llvm/ADT/Twine.h"
26 #include "llvm/Support/SourceMgr.h"
27 #include "llvm/Support/raw_ostream.h"
28 using namespace llvm;
29
30 namespace {
31 struct X86Operand;
32
33 class X86ATTAsmParser : public TargetAsmParser {
34   MCAsmParser &Parser;
35   TargetMachine &TM;
36
37 protected:
38   unsigned Is64Bit : 1;
39
40 private:
41   MCAsmParser &getParser() const { return Parser; }
42
43   MCAsmLexer &getLexer() const { return Parser.getLexer(); }
44
45   bool Error(SMLoc L, const Twine &Msg) { return Parser.Error(L, Msg); }
46
47   X86Operand *ParseOperand();
48   X86Operand *ParseMemOperand(unsigned SegReg, SMLoc StartLoc);
49
50   bool ParseDirectiveWord(unsigned Size, SMLoc L);
51
52   bool MatchAndEmitInstruction(SMLoc IDLoc,
53                                SmallVectorImpl<MCParsedAsmOperand*> &Operands,
54                                MCStreamer &Out);
55
56   /// @name Auto-generated Matcher Functions
57   /// {
58
59 #define GET_ASSEMBLER_HEADER
60 #include "X86GenAsmMatcher.inc"
61
62   /// }
63
64 public:
65   X86ATTAsmParser(const Target &T, MCAsmParser &parser, TargetMachine &TM)
66     : TargetAsmParser(T), Parser(parser), TM(TM) {
67
68     // Initialize the set of available features.
69     setAvailableFeatures(ComputeAvailableFeatures(
70                            &TM.getSubtarget<X86Subtarget>()));
71   }
72   virtual bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc);
73
74   virtual bool ParseInstruction(StringRef Name, SMLoc NameLoc,
75                                 SmallVectorImpl<MCParsedAsmOperand*> &Operands);
76
77   virtual bool ParseDirective(AsmToken DirectiveID);
78 };
79
80 class X86_32ATTAsmParser : public X86ATTAsmParser {
81 public:
82   X86_32ATTAsmParser(const Target &T, MCAsmParser &Parser, TargetMachine &TM)
83     : X86ATTAsmParser(T, Parser, TM) {
84     Is64Bit = false;
85   }
86 };
87
88 class X86_64ATTAsmParser : public X86ATTAsmParser {
89 public:
90   X86_64ATTAsmParser(const Target &T, MCAsmParser &Parser, TargetMachine &TM)
91     : X86ATTAsmParser(T, Parser, TM) {
92     Is64Bit = true;
93   }
94 };
95
96 } // end anonymous namespace
97
98 /// @name Auto-generated Match Functions
99 /// {
100
101 static unsigned MatchRegisterName(StringRef Name);
102
103 /// }
104
105 namespace {
106
107 /// X86Operand - Instances of this class represent a parsed X86 machine
108 /// instruction.
109 struct X86Operand : public MCParsedAsmOperand {
110   enum KindTy {
111     Token,
112     Register,
113     Immediate,
114     Memory
115   } Kind;
116
117   SMLoc StartLoc, EndLoc;
118
119   union {
120     struct {
121       const char *Data;
122       unsigned Length;
123     } Tok;
124
125     struct {
126       unsigned RegNo;
127     } Reg;
128
129     struct {
130       const MCExpr *Val;
131     } Imm;
132
133     struct {
134       unsigned SegReg;
135       const MCExpr *Disp;
136       unsigned BaseReg;
137       unsigned IndexReg;
138       unsigned Scale;
139     } Mem;
140   };
141
142   X86Operand(KindTy K, SMLoc Start, SMLoc End)
143     : Kind(K), StartLoc(Start), EndLoc(End) {}
144
145   /// getStartLoc - Get the location of the first token of this operand.
146   SMLoc getStartLoc() const { return StartLoc; }
147   /// getEndLoc - Get the location of the last token of this operand.
148   SMLoc getEndLoc() const { return EndLoc; }
149
150   virtual void dump(raw_ostream &OS) const {}
151
152   StringRef getToken() const {
153     assert(Kind == Token && "Invalid access!");
154     return StringRef(Tok.Data, Tok.Length);
155   }
156   void setTokenValue(StringRef Value) {
157     assert(Kind == Token && "Invalid access!");
158     Tok.Data = Value.data();
159     Tok.Length = Value.size();
160   }
161
162   unsigned getReg() const {
163     assert(Kind == Register && "Invalid access!");
164     return Reg.RegNo;
165   }
166
167   const MCExpr *getImm() const {
168     assert(Kind == Immediate && "Invalid access!");
169     return Imm.Val;
170   }
171
172   const MCExpr *getMemDisp() const {
173     assert(Kind == Memory && "Invalid access!");
174     return Mem.Disp;
175   }
176   unsigned getMemSegReg() const {
177     assert(Kind == Memory && "Invalid access!");
178     return Mem.SegReg;
179   }
180   unsigned getMemBaseReg() const {
181     assert(Kind == Memory && "Invalid access!");
182     return Mem.BaseReg;
183   }
184   unsigned getMemIndexReg() const {
185     assert(Kind == Memory && "Invalid access!");
186     return Mem.IndexReg;
187   }
188   unsigned getMemScale() const {
189     assert(Kind == Memory && "Invalid access!");
190     return Mem.Scale;
191   }
192
193   bool isToken() const {return Kind == Token; }
194
195   bool isImm() const { return Kind == Immediate; }
196
197   bool isImmSExti16i8() const {
198     if (!isImm())
199       return false;
200
201     // If this isn't a constant expr, just assume it fits and let relaxation
202     // handle it.
203     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
204     if (!CE)
205       return true;
206
207     // Otherwise, check the value is in a range that makes sense for this
208     // extension.
209     uint64_t Value = CE->getValue();
210     return ((                                  Value <= 0x000000000000007FULL)||
211             (0x000000000000FF80ULL <= Value && Value <= 0x000000000000FFFFULL)||
212             (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
213   }
214   bool isImmSExti32i8() const {
215     if (!isImm())
216       return false;
217
218     // If this isn't a constant expr, just assume it fits and let relaxation
219     // handle it.
220     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
221     if (!CE)
222       return true;
223
224     // Otherwise, check the value is in a range that makes sense for this
225     // extension.
226     uint64_t Value = CE->getValue();
227     return ((                                  Value <= 0x000000000000007FULL)||
228             (0x00000000FFFFFF80ULL <= Value && Value <= 0x00000000FFFFFFFFULL)||
229             (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
230   }
231   bool isImmSExti64i8() const {
232     if (!isImm())
233       return false;
234
235     // If this isn't a constant expr, just assume it fits and let relaxation
236     // handle it.
237     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
238     if (!CE)
239       return true;
240
241     // Otherwise, check the value is in a range that makes sense for this
242     // extension.
243     uint64_t Value = CE->getValue();
244     return ((                                  Value <= 0x000000000000007FULL)||
245             (0xFFFFFFFFFFFFFF80ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
246   }
247   bool isImmSExti64i32() const {
248     if (!isImm())
249       return false;
250
251     // If this isn't a constant expr, just assume it fits and let relaxation
252     // handle it.
253     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
254     if (!CE)
255       return true;
256
257     // Otherwise, check the value is in a range that makes sense for this
258     // extension.
259     uint64_t Value = CE->getValue();
260     return ((                                  Value <= 0x000000007FFFFFFFULL)||
261             (0xFFFFFFFF80000000ULL <= Value && Value <= 0xFFFFFFFFFFFFFFFFULL));
262   }
263
264   bool isMem() const { return Kind == Memory; }
265
266   bool isAbsMem() const {
267     return Kind == Memory && !getMemSegReg() && !getMemBaseReg() &&
268       !getMemIndexReg() && getMemScale() == 1;
269   }
270
271   bool isReg() const { return Kind == Register; }
272
273   void addExpr(MCInst &Inst, const MCExpr *Expr) const {
274     // Add as immediates when possible.
275     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
276       Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
277     else
278       Inst.addOperand(MCOperand::CreateExpr(Expr));
279   }
280
281   void addRegOperands(MCInst &Inst, unsigned N) const {
282     assert(N == 1 && "Invalid number of operands!");
283     Inst.addOperand(MCOperand::CreateReg(getReg()));
284   }
285
286   void addImmOperands(MCInst &Inst, unsigned N) const {
287     assert(N == 1 && "Invalid number of operands!");
288     addExpr(Inst, getImm());
289   }
290
291   void addMemOperands(MCInst &Inst, unsigned N) const {
292     assert((N == 5) && "Invalid number of operands!");
293     Inst.addOperand(MCOperand::CreateReg(getMemBaseReg()));
294     Inst.addOperand(MCOperand::CreateImm(getMemScale()));
295     Inst.addOperand(MCOperand::CreateReg(getMemIndexReg()));
296     addExpr(Inst, getMemDisp());
297     Inst.addOperand(MCOperand::CreateReg(getMemSegReg()));
298   }
299
300   void addAbsMemOperands(MCInst &Inst, unsigned N) const {
301     assert((N == 1) && "Invalid number of operands!");
302     Inst.addOperand(MCOperand::CreateExpr(getMemDisp()));
303   }
304
305   static X86Operand *CreateToken(StringRef Str, SMLoc Loc) {
306     X86Operand *Res = new X86Operand(Token, Loc, Loc);
307     Res->Tok.Data = Str.data();
308     Res->Tok.Length = Str.size();
309     return Res;
310   }
311
312   static X86Operand *CreateReg(unsigned RegNo, SMLoc StartLoc, SMLoc EndLoc) {
313     X86Operand *Res = new X86Operand(Register, StartLoc, EndLoc);
314     Res->Reg.RegNo = RegNo;
315     return Res;
316   }
317
318   static X86Operand *CreateImm(const MCExpr *Val, SMLoc StartLoc, SMLoc EndLoc){
319     X86Operand *Res = new X86Operand(Immediate, StartLoc, EndLoc);
320     Res->Imm.Val = Val;
321     return Res;
322   }
323
324   /// Create an absolute memory operand.
325   static X86Operand *CreateMem(const MCExpr *Disp, SMLoc StartLoc,
326                                SMLoc EndLoc) {
327     X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
328     Res->Mem.SegReg   = 0;
329     Res->Mem.Disp     = Disp;
330     Res->Mem.BaseReg  = 0;
331     Res->Mem.IndexReg = 0;
332     Res->Mem.Scale    = 1;
333     return Res;
334   }
335
336   /// Create a generalized memory operand.
337   static X86Operand *CreateMem(unsigned SegReg, const MCExpr *Disp,
338                                unsigned BaseReg, unsigned IndexReg,
339                                unsigned Scale, SMLoc StartLoc, SMLoc EndLoc) {
340     // We should never just have a displacement, that should be parsed as an
341     // absolute memory operand.
342     assert((SegReg || BaseReg || IndexReg) && "Invalid memory operand!");
343
344     // The scale should always be one of {1,2,4,8}.
345     assert(((Scale == 1 || Scale == 2 || Scale == 4 || Scale == 8)) &&
346            "Invalid scale!");
347     X86Operand *Res = new X86Operand(Memory, StartLoc, EndLoc);
348     Res->Mem.SegReg   = SegReg;
349     Res->Mem.Disp     = Disp;
350     Res->Mem.BaseReg  = BaseReg;
351     Res->Mem.IndexReg = IndexReg;
352     Res->Mem.Scale    = Scale;
353     return Res;
354   }
355 };
356
357 } // end anonymous namespace.
358
359
360 bool X86ATTAsmParser::ParseRegister(unsigned &RegNo,
361                                     SMLoc &StartLoc, SMLoc &EndLoc) {
362   RegNo = 0;
363   const AsmToken &TokPercent = Parser.getTok();
364   assert(TokPercent.is(AsmToken::Percent) && "Invalid token kind!");
365   StartLoc = TokPercent.getLoc();
366   Parser.Lex(); // Eat percent token.
367
368   const AsmToken &Tok = Parser.getTok();
369   if (Tok.isNot(AsmToken::Identifier))
370     return Error(Tok.getLoc(), "invalid register name");
371
372   // FIXME: Validate register for the current architecture; we have to do
373   // validation later, so maybe there is no need for this here.
374   RegNo = MatchRegisterName(Tok.getString());
375
376   // If the match failed, try the register name as lowercase.
377   if (RegNo == 0)
378     RegNo = MatchRegisterName(LowercaseString(Tok.getString()));
379
380   // FIXME: This should be done using Requires<In32BitMode> and
381   // Requires<In64BitMode> so "eiz" usage in 64-bit instructions
382   // can be also checked.
383   if (RegNo == X86::RIZ && !Is64Bit)
384     return Error(Tok.getLoc(), "riz register in 64-bit mode only");
385
386   // Parse "%st" as "%st(0)" and "%st(1)", which is multiple tokens.
387   if (RegNo == 0 && (Tok.getString() == "st" || Tok.getString() == "ST")) {
388     RegNo = X86::ST0;
389     EndLoc = Tok.getLoc();
390     Parser.Lex(); // Eat 'st'
391
392     // Check to see if we have '(4)' after %st.
393     if (getLexer().isNot(AsmToken::LParen))
394       return false;
395     // Lex the paren.
396     getParser().Lex();
397
398     const AsmToken &IntTok = Parser.getTok();
399     if (IntTok.isNot(AsmToken::Integer))
400       return Error(IntTok.getLoc(), "expected stack index");
401     switch (IntTok.getIntVal()) {
402     case 0: RegNo = X86::ST0; break;
403     case 1: RegNo = X86::ST1; break;
404     case 2: RegNo = X86::ST2; break;
405     case 3: RegNo = X86::ST3; break;
406     case 4: RegNo = X86::ST4; break;
407     case 5: RegNo = X86::ST5; break;
408     case 6: RegNo = X86::ST6; break;
409     case 7: RegNo = X86::ST7; break;
410     default: return Error(IntTok.getLoc(), "invalid stack index");
411     }
412
413     if (getParser().Lex().isNot(AsmToken::RParen))
414       return Error(Parser.getTok().getLoc(), "expected ')'");
415
416     EndLoc = Tok.getLoc();
417     Parser.Lex(); // Eat ')'
418     return false;
419   }
420
421   // If this is "db[0-7]", match it as an alias
422   // for dr[0-7].
423   if (RegNo == 0 && Tok.getString().size() == 3 &&
424       Tok.getString().startswith("db")) {
425     switch (Tok.getString()[2]) {
426     case '0': RegNo = X86::DR0; break;
427     case '1': RegNo = X86::DR1; break;
428     case '2': RegNo = X86::DR2; break;
429     case '3': RegNo = X86::DR3; break;
430     case '4': RegNo = X86::DR4; break;
431     case '5': RegNo = X86::DR5; break;
432     case '6': RegNo = X86::DR6; break;
433     case '7': RegNo = X86::DR7; break;
434     }
435
436     if (RegNo != 0) {
437       EndLoc = Tok.getLoc();
438       Parser.Lex(); // Eat it.
439       return false;
440     }
441   }
442
443   if (RegNo == 0)
444     return Error(Tok.getLoc(), "invalid register name");
445
446   EndLoc = Tok.getLoc();
447   Parser.Lex(); // Eat identifier token.
448   return false;
449 }
450
451 X86Operand *X86ATTAsmParser::ParseOperand() {
452   switch (getLexer().getKind()) {
453   default:
454     // Parse a memory operand with no segment register.
455     return ParseMemOperand(0, Parser.getTok().getLoc());
456   case AsmToken::Percent: {
457     // Read the register.
458     unsigned RegNo;
459     SMLoc Start, End;
460     if (ParseRegister(RegNo, Start, End)) return 0;
461     if (RegNo == X86::EIZ || RegNo == X86::RIZ) {
462       Error(Start, "eiz and riz can only be used as index registers");
463       return 0;
464     }
465
466     // If this is a segment register followed by a ':', then this is the start
467     // of a memory reference, otherwise this is a normal register reference.
468     if (getLexer().isNot(AsmToken::Colon))
469       return X86Operand::CreateReg(RegNo, Start, End);
470
471
472     getParser().Lex(); // Eat the colon.
473     return ParseMemOperand(RegNo, Start);
474   }
475   case AsmToken::Dollar: {
476     // $42 -> immediate.
477     SMLoc Start = Parser.getTok().getLoc(), End;
478     Parser.Lex();
479     const MCExpr *Val;
480     if (getParser().ParseExpression(Val, End))
481       return 0;
482     return X86Operand::CreateImm(Val, Start, End);
483   }
484   }
485 }
486
487 /// ParseMemOperand: segment: disp(basereg, indexreg, scale).  The '%ds:' prefix
488 /// has already been parsed if present.
489 X86Operand *X86ATTAsmParser::ParseMemOperand(unsigned SegReg, SMLoc MemStart) {
490
491   // We have to disambiguate a parenthesized expression "(4+5)" from the start
492   // of a memory operand with a missing displacement "(%ebx)" or "(,%eax)".  The
493   // only way to do this without lookahead is to eat the '(' and see what is
494   // after it.
495   const MCExpr *Disp = MCConstantExpr::Create(0, getParser().getContext());
496   if (getLexer().isNot(AsmToken::LParen)) {
497     SMLoc ExprEnd;
498     if (getParser().ParseExpression(Disp, ExprEnd)) return 0;
499
500     // After parsing the base expression we could either have a parenthesized
501     // memory address or not.  If not, return now.  If so, eat the (.
502     if (getLexer().isNot(AsmToken::LParen)) {
503       // Unless we have a segment register, treat this as an immediate.
504       if (SegReg == 0)
505         return X86Operand::CreateMem(Disp, MemStart, ExprEnd);
506       return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
507     }
508
509     // Eat the '('.
510     Parser.Lex();
511   } else {
512     // Okay, we have a '('.  We don't know if this is an expression or not, but
513     // so we have to eat the ( to see beyond it.
514     SMLoc LParenLoc = Parser.getTok().getLoc();
515     Parser.Lex(); // Eat the '('.
516
517     if (getLexer().is(AsmToken::Percent) || getLexer().is(AsmToken::Comma)) {
518       // Nothing to do here, fall into the code below with the '(' part of the
519       // memory operand consumed.
520     } else {
521       SMLoc ExprEnd;
522
523       // It must be an parenthesized expression, parse it now.
524       if (getParser().ParseParenExpression(Disp, ExprEnd))
525         return 0;
526
527       // After parsing the base expression we could either have a parenthesized
528       // memory address or not.  If not, return now.  If so, eat the (.
529       if (getLexer().isNot(AsmToken::LParen)) {
530         // Unless we have a segment register, treat this as an immediate.
531         if (SegReg == 0)
532           return X86Operand::CreateMem(Disp, LParenLoc, ExprEnd);
533         return X86Operand::CreateMem(SegReg, Disp, 0, 0, 1, MemStart, ExprEnd);
534       }
535
536       // Eat the '('.
537       Parser.Lex();
538     }
539   }
540
541   // If we reached here, then we just ate the ( of the memory operand.  Process
542   // the rest of the memory operand.
543   unsigned BaseReg = 0, IndexReg = 0, Scale = 1;
544
545   if (getLexer().is(AsmToken::Percent)) {
546     SMLoc L;
547     if (ParseRegister(BaseReg, L, L)) return 0;
548     if (BaseReg == X86::EIZ || BaseReg == X86::RIZ) {
549       Error(L, "eiz and riz can only be used as index registers");
550       return 0;
551     }
552   }
553
554   if (getLexer().is(AsmToken::Comma)) {
555     Parser.Lex(); // Eat the comma.
556
557     // Following the comma we should have either an index register, or a scale
558     // value. We don't support the later form, but we want to parse it
559     // correctly.
560     //
561     // Not that even though it would be completely consistent to support syntax
562     // like "1(%eax,,1)", the assembler doesn't. Use "eiz" or "riz" for this.
563     if (getLexer().is(AsmToken::Percent)) {
564       SMLoc L;
565       if (ParseRegister(IndexReg, L, L)) return 0;
566
567       if (getLexer().isNot(AsmToken::RParen)) {
568         // Parse the scale amount:
569         //  ::= ',' [scale-expression]
570         if (getLexer().isNot(AsmToken::Comma)) {
571           Error(Parser.getTok().getLoc(),
572                 "expected comma in scale expression");
573           return 0;
574         }
575         Parser.Lex(); // Eat the comma.
576
577         if (getLexer().isNot(AsmToken::RParen)) {
578           SMLoc Loc = Parser.getTok().getLoc();
579
580           int64_t ScaleVal;
581           if (getParser().ParseAbsoluteExpression(ScaleVal))
582             return 0;
583
584           // Validate the scale amount.
585           if (ScaleVal != 1 && ScaleVal != 2 && ScaleVal != 4 && ScaleVal != 8){
586             Error(Loc, "scale factor in address must be 1, 2, 4 or 8");
587             return 0;
588           }
589           Scale = (unsigned)ScaleVal;
590         }
591       }
592     } else if (getLexer().isNot(AsmToken::RParen)) {
593       // A scale amount without an index is ignored.
594       // index.
595       SMLoc Loc = Parser.getTok().getLoc();
596
597       int64_t Value;
598       if (getParser().ParseAbsoluteExpression(Value))
599         return 0;
600
601       if (Value != 1)
602         Warning(Loc, "scale factor without index register is ignored");
603       Scale = 1;
604     }
605   }
606
607   // Ok, we've eaten the memory operand, verify we have a ')' and eat it too.
608   if (getLexer().isNot(AsmToken::RParen)) {
609     Error(Parser.getTok().getLoc(), "unexpected token in memory operand");
610     return 0;
611   }
612   SMLoc MemEnd = Parser.getTok().getLoc();
613   Parser.Lex(); // Eat the ')'.
614
615   return X86Operand::CreateMem(SegReg, Disp, BaseReg, IndexReg, Scale,
616                                MemStart, MemEnd);
617 }
618
619 bool X86ATTAsmParser::
620 ParseInstruction(StringRef Name, SMLoc NameLoc,
621                  SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
622   StringRef PatchedName = Name;
623
624   // FIXME: Hack to recognize setneb as setne.
625   if (PatchedName.startswith("set") && PatchedName.endswith("b") &&
626       PatchedName != "setb" && PatchedName != "setnb")
627     PatchedName = PatchedName.substr(0, Name.size()-1);
628   
629   // FIXME: Hack to recognize cmp<comparison code>{ss,sd,ps,pd}.
630   const MCExpr *ExtraImmOp = 0;
631   if ((PatchedName.startswith("cmp") || PatchedName.startswith("vcmp")) &&
632       (PatchedName.endswith("ss") || PatchedName.endswith("sd") ||
633        PatchedName.endswith("ps") || PatchedName.endswith("pd"))) {
634     bool IsVCMP = PatchedName.startswith("vcmp");
635     unsigned SSECCIdx = IsVCMP ? 4 : 3;
636     unsigned SSEComparisonCode = StringSwitch<unsigned>(
637       PatchedName.slice(SSECCIdx, PatchedName.size() - 2))
638       .Case("eq",          0)
639       .Case("lt",          1)
640       .Case("le",          2)
641       .Case("unord",       3)
642       .Case("neq",         4)
643       .Case("nlt",         5)
644       .Case("nle",         6)
645       .Case("ord",         7)
646       .Case("eq_uq",       8)
647       .Case("nge",         9)
648       .Case("ngt",      0x0A)
649       .Case("false",    0x0B)
650       .Case("neq_oq",   0x0C)
651       .Case("ge",       0x0D)
652       .Case("gt",       0x0E)
653       .Case("true",     0x0F)
654       .Case("eq_os",    0x10)
655       .Case("lt_oq",    0x11)
656       .Case("le_oq",    0x12)
657       .Case("unord_s",  0x13)
658       .Case("neq_us",   0x14)
659       .Case("nlt_uq",   0x15)
660       .Case("nle_uq",   0x16)
661       .Case("ord_s",    0x17)
662       .Case("eq_us",    0x18)
663       .Case("nge_uq",   0x19)
664       .Case("ngt_uq",   0x1A)
665       .Case("false_os", 0x1B)
666       .Case("neq_os",   0x1C)
667       .Case("ge_oq",    0x1D)
668       .Case("gt_oq",    0x1E)
669       .Case("true_us",  0x1F)
670       .Default(~0U);
671     if (SSEComparisonCode != ~0U) {
672       ExtraImmOp = MCConstantExpr::Create(SSEComparisonCode,
673                                           getParser().getContext());
674       if (PatchedName.endswith("ss")) {
675         PatchedName = IsVCMP ? "vcmpss" : "cmpss";
676       } else if (PatchedName.endswith("sd")) {
677         PatchedName = IsVCMP ? "vcmpsd" : "cmpsd";
678       } else if (PatchedName.endswith("ps")) {
679         PatchedName = IsVCMP ? "vcmpps" : "cmpps";
680       } else {
681         assert(PatchedName.endswith("pd") && "Unexpected mnemonic!");
682         PatchedName = IsVCMP ? "vcmppd" : "cmppd";
683       }
684     }
685   }
686
687   // FIXME: Hack to recognize vpclmul<src1_quadword, src2_quadword>dq
688   if (PatchedName.startswith("vpclmul")) {
689     unsigned CLMULQuadWordSelect = StringSwitch<unsigned>(
690       PatchedName.slice(7, PatchedName.size() - 2))
691       .Case("lqlq", 0x00) // src1[63:0],   src2[63:0]
692       .Case("hqlq", 0x01) // src1[127:64], src2[63:0]
693       .Case("lqhq", 0x10) // src1[63:0],   src2[127:64]
694       .Case("hqhq", 0x11) // src1[127:64], src2[127:64]
695       .Default(~0U);
696     if (CLMULQuadWordSelect != ~0U) {
697       ExtraImmOp = MCConstantExpr::Create(CLMULQuadWordSelect,
698                                           getParser().getContext());
699       assert(PatchedName.endswith("dq") && "Unexpected mnemonic!");
700       PatchedName = "vpclmulqdq";
701     }
702   }
703
704   Operands.push_back(X86Operand::CreateToken(PatchedName, NameLoc));
705
706   if (ExtraImmOp)
707     Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
708
709
710   // Determine whether this is an instruction prefix.
711   bool isPrefix =
712     Name == "lock" || Name == "rep" ||
713     Name == "repe" || Name == "repz" ||
714     Name == "repne" || Name == "repnz" ||
715     Name == "rex64" || Name == "data16";
716
717
718   // This does the actual operand parsing.  Don't parse any more if we have a
719   // prefix juxtaposed with an operation like "lock incl 4(%rax)", because we
720   // just want to parse the "lock" as the first instruction and the "incl" as
721   // the next one.
722   if (getLexer().isNot(AsmToken::EndOfStatement) && !isPrefix) {
723
724     // Parse '*' modifier.
725     if (getLexer().is(AsmToken::Star)) {
726       SMLoc Loc = Parser.getTok().getLoc();
727       Operands.push_back(X86Operand::CreateToken("*", Loc));
728       Parser.Lex(); // Eat the star.
729     }
730
731     // Read the first operand.
732     if (X86Operand *Op = ParseOperand())
733       Operands.push_back(Op);
734     else {
735       Parser.EatToEndOfStatement();
736       return true;
737     }
738
739     while (getLexer().is(AsmToken::Comma)) {
740       Parser.Lex();  // Eat the comma.
741
742       // Parse and remember the operand.
743       if (X86Operand *Op = ParseOperand())
744         Operands.push_back(Op);
745       else {
746         Parser.EatToEndOfStatement();
747         return true;
748       }
749     }
750
751     if (getLexer().isNot(AsmToken::EndOfStatement)) {
752       SMLoc Loc = getLexer().getLoc();
753       Parser.EatToEndOfStatement();
754       return Error(Loc, "unexpected token in argument list");
755     }
756   }
757
758   if (getLexer().is(AsmToken::EndOfStatement))
759     Parser.Lex(); // Consume the EndOfStatement
760   else if (isPrefix && getLexer().is(AsmToken::Slash))
761     Parser.Lex(); // Consume the prefix separator Slash
762
763   // This is a terrible hack to handle "out[bwl]? %al, (%dx)" ->
764   // "outb %al, %dx".  Out doesn't take a memory form, but this is a widely
765   // documented form in various unofficial manuals, so a lot of code uses it.
766   if ((Name == "outb" || Name == "outw" || Name == "outl" || Name == "out") &&
767       Operands.size() == 3) {
768     X86Operand &Op = *(X86Operand*)Operands.back();
769     if (Op.isMem() && Op.Mem.SegReg == 0 &&
770         isa<MCConstantExpr>(Op.Mem.Disp) &&
771         cast<MCConstantExpr>(Op.Mem.Disp)->getValue() == 0 &&
772         Op.Mem.BaseReg == MatchRegisterName("dx") && Op.Mem.IndexReg == 0) {
773       SMLoc Loc = Op.getEndLoc();
774       Operands.back() = X86Operand::CreateReg(Op.Mem.BaseReg, Loc, Loc);
775       delete &Op;
776     }
777   }
778   
779   // FIXME: Hack to handle recognize s{hr,ar,hl} $1, <op>.  Canonicalize to
780   // "shift <op>".
781   if ((Name.startswith("shr") || Name.startswith("sar") ||
782        Name.startswith("shl") || Name.startswith("sal") ||
783        Name.startswith("rcl") || Name.startswith("rcr") ||
784        Name.startswith("rol") || Name.startswith("ror")) &&
785       Operands.size() == 3) {
786     X86Operand *Op1 = static_cast<X86Operand*>(Operands[1]);
787     if (Op1->isImm() && isa<MCConstantExpr>(Op1->getImm()) &&
788         cast<MCConstantExpr>(Op1->getImm())->getValue() == 1) {
789       delete Operands[1];
790       Operands.erase(Operands.begin() + 1);
791     }
792   }
793
794   return false;
795 }
796
797 bool X86ATTAsmParser::
798 MatchAndEmitInstruction(SMLoc IDLoc,
799                         SmallVectorImpl<MCParsedAsmOperand*> &Operands,
800                         MCStreamer &Out) {
801   assert(!Operands.empty() && "Unexpect empty operand list!");
802   X86Operand *Op = static_cast<X86Operand*>(Operands[0]);
803   assert(Op->isToken() && "Leading operand should always be a mnemonic!");
804
805   // First, handle aliases that expand to multiple instructions.
806   // FIXME: This should be replaced with a real .td file alias mechanism.
807   // Also, MatchInstructionImpl should do actually *do* the EmitInstruction
808   // call.
809   if (Op->getToken() == "fstsw" || Op->getToken() == "fstcw" ||
810       Op->getToken() == "fstsww" || Op->getToken() == "fstcww" ||
811       Op->getToken() == "finit" || Op->getToken() == "fsave" ||
812       Op->getToken() == "fstenv" || Op->getToken() == "fclex") {
813     MCInst Inst;
814     Inst.setOpcode(X86::WAIT);
815     Out.EmitInstruction(Inst);
816
817     const char *Repl =
818       StringSwitch<const char*>(Op->getToken())
819         .Case("finit",  "fninit")
820         .Case("fsave",  "fnsave")
821         .Case("fstcw",  "fnstcw")
822         .Case("fstcww",  "fnstcw")
823         .Case("fstenv", "fnstenv")
824         .Case("fstsw",  "fnstsw")
825         .Case("fstsww", "fnstsw")
826         .Case("fclex",  "fnclex")
827         .Default(0);
828     assert(Repl && "Unknown wait-prefixed instruction");
829     delete Operands[0];
830     Operands[0] = X86Operand::CreateToken(Repl, IDLoc);
831   }
832
833   bool WasOriginallyInvalidOperand = false;
834   unsigned OrigErrorInfo;
835   MCInst Inst;
836
837   // First, try a direct match.
838   switch (MatchInstructionImpl(Operands, Inst, OrigErrorInfo)) {
839   case Match_Success:
840     Out.EmitInstruction(Inst);
841     return false;
842   case Match_MissingFeature:
843     Error(IDLoc, "instruction requires a CPU feature not currently enabled");
844     return true;
845   case Match_ConversionFail:
846     return Error(IDLoc, "unable to convert operands to instruction");
847   case Match_InvalidOperand:
848     WasOriginallyInvalidOperand = true;
849     break;
850   case Match_MnemonicFail:
851     break;
852   }
853
854   // FIXME: Ideally, we would only attempt suffix matches for things which are
855   // valid prefixes, and we could just infer the right unambiguous
856   // type. However, that requires substantially more matcher support than the
857   // following hack.
858
859   // Change the operand to point to a temporary token.
860   StringRef Base = Op->getToken();
861   SmallString<16> Tmp;
862   Tmp += Base;
863   Tmp += ' ';
864   Op->setTokenValue(Tmp.str());
865
866   // If this instruction starts with an 'f', then it is a floating point stack
867   // instruction.  These come in up to three forms for 32-bit, 64-bit, and
868   // 80-bit floating point, which use the suffixes s,l,t respectively.
869   //
870   // Otherwise, we assume that this may be an integer instruction, which comes
871   // in 8/16/32/64-bit forms using the b,w,l,q suffixes respectively.
872   const char *Suffixes = Base[0] != 'f' ? "bwlq" : "slt\0";
873   
874   // Check for the various suffix matches.
875   Tmp[Base.size()] = Suffixes[0];
876   unsigned ErrorInfoIgnore;
877   MatchResultTy Match1, Match2, Match3, Match4;
878   
879   Match1 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
880   Tmp[Base.size()] = Suffixes[1];
881   Match2 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
882   Tmp[Base.size()] = Suffixes[2];
883   Match3 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
884   Tmp[Base.size()] = Suffixes[3];
885   Match4 = MatchInstructionImpl(Operands, Inst, ErrorInfoIgnore);
886
887   // Restore the old token.
888   Op->setTokenValue(Base);
889
890   // If exactly one matched, then we treat that as a successful match (and the
891   // instruction will already have been filled in correctly, since the failing
892   // matches won't have modified it).
893   unsigned NumSuccessfulMatches =
894     (Match1 == Match_Success) + (Match2 == Match_Success) +
895     (Match3 == Match_Success) + (Match4 == Match_Success);
896   if (NumSuccessfulMatches == 1) {
897     Out.EmitInstruction(Inst);
898     return false;
899   }
900
901   // Otherwise, the match failed, try to produce a decent error message.
902
903   // If we had multiple suffix matches, then identify this as an ambiguous
904   // match.
905   if (NumSuccessfulMatches > 1) {
906     char MatchChars[4];
907     unsigned NumMatches = 0;
908     if (Match1 == Match_Success) MatchChars[NumMatches++] = Suffixes[0];
909     if (Match2 == Match_Success) MatchChars[NumMatches++] = Suffixes[1];
910     if (Match3 == Match_Success) MatchChars[NumMatches++] = Suffixes[2];
911     if (Match4 == Match_Success) MatchChars[NumMatches++] = Suffixes[3];
912
913     SmallString<126> Msg;
914     raw_svector_ostream OS(Msg);
915     OS << "ambiguous instructions require an explicit suffix (could be ";
916     for (unsigned i = 0; i != NumMatches; ++i) {
917       if (i != 0)
918         OS << ", ";
919       if (i + 1 == NumMatches)
920         OS << "or ";
921       OS << "'" << Base << MatchChars[i] << "'";
922     }
923     OS << ")";
924     Error(IDLoc, OS.str());
925     return true;
926   }
927
928   // Okay, we know that none of the variants matched successfully.
929
930   // If all of the instructions reported an invalid mnemonic, then the original
931   // mnemonic was invalid.
932   if ((Match1 == Match_MnemonicFail) && (Match2 == Match_MnemonicFail) &&
933       (Match3 == Match_MnemonicFail) && (Match4 == Match_MnemonicFail)) {
934     if (!WasOriginallyInvalidOperand) {
935       Error(IDLoc, "invalid instruction mnemonic '" + Base + "'");
936       return true;
937     }
938
939     // Recover location info for the operand if we know which was the problem.
940     SMLoc ErrorLoc = IDLoc;
941     if (OrigErrorInfo != ~0U) {
942       if (OrigErrorInfo >= Operands.size())
943         return Error(IDLoc, "too few operands for instruction");
944
945       ErrorLoc = ((X86Operand*)Operands[OrigErrorInfo])->getStartLoc();
946       if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
947     }
948
949     return Error(ErrorLoc, "invalid operand for instruction");
950   }
951
952   // If one instruction matched with a missing feature, report this as a
953   // missing feature.
954   if ((Match1 == Match_MissingFeature) + (Match2 == Match_MissingFeature) +
955       (Match3 == Match_MissingFeature) + (Match4 == Match_MissingFeature) == 1){
956     Error(IDLoc, "instruction requires a CPU feature not currently enabled");
957     return true;
958   }
959
960   // If one instruction matched with an invalid operand, report this as an
961   // operand failure.
962   if ((Match1 == Match_InvalidOperand) + (Match2 == Match_InvalidOperand) +
963       (Match3 == Match_InvalidOperand) + (Match4 == Match_InvalidOperand) == 1){
964     Error(IDLoc, "invalid operand for instruction");
965     return true;
966   }
967
968   // If all of these were an outright failure, report it in a useless way.
969   // FIXME: We should give nicer diagnostics about the exact failure.
970   Error(IDLoc, "unknown use of instruction mnemonic without a size suffix");
971   return true;
972 }
973
974
975 bool X86ATTAsmParser::ParseDirective(AsmToken DirectiveID) {
976   StringRef IDVal = DirectiveID.getIdentifier();
977   if (IDVal == ".word")
978     return ParseDirectiveWord(2, DirectiveID.getLoc());
979   return true;
980 }
981
982 /// ParseDirectiveWord
983 ///  ::= .word [ expression (, expression)* ]
984 bool X86ATTAsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
985   if (getLexer().isNot(AsmToken::EndOfStatement)) {
986     for (;;) {
987       const MCExpr *Value;
988       if (getParser().ParseExpression(Value))
989         return true;
990       
991       getParser().getStreamer().EmitValue(Value, Size, 0 /*addrspace*/);
992       
993       if (getLexer().is(AsmToken::EndOfStatement))
994         break;
995       
996       // FIXME: Improve diagnostic.
997       if (getLexer().isNot(AsmToken::Comma))
998         return Error(L, "unexpected token in directive");
999       Parser.Lex();
1000     }
1001   }
1002   
1003   Parser.Lex();
1004   return false;
1005 }
1006
1007
1008
1009
1010 extern "C" void LLVMInitializeX86AsmLexer();
1011
1012 // Force static initialization.
1013 extern "C" void LLVMInitializeX86AsmParser() {
1014   RegisterAsmParser<X86_32ATTAsmParser> X(TheX86_32Target);
1015   RegisterAsmParser<X86_64ATTAsmParser> Y(TheX86_64Target);
1016   LLVMInitializeX86AsmLexer();
1017 }
1018
1019 #define GET_REGISTER_MATCHER
1020 #define GET_MATCHER_IMPLEMENTATION
1021 #include "X86GenAsmMatcher.inc"