ARMAsmParser.cpp revision b412915ff6229b3e2dffedcfb0f3fb7e85259841
1//===-- ARMAsmParser.cpp - Parse ARM 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 "ARM.h"
11#include "ARMAddressingModes.h"
12#include "ARMMCExpr.h"
13#include "ARMBaseRegisterInfo.h"
14#include "ARMSubtarget.h"
15#include "llvm/MC/MCParser/MCAsmLexer.h"
16#include "llvm/MC/MCParser/MCAsmParser.h"
17#include "llvm/MC/MCParser/MCParsedAsmOperand.h"
18#include "llvm/MC/MCContext.h"
19#include "llvm/MC/MCStreamer.h"
20#include "llvm/MC/MCExpr.h"
21#include "llvm/MC/MCInst.h"
22#include "llvm/Target/TargetRegistry.h"
23#include "llvm/Target/TargetAsmParser.h"
24#include "llvm/Support/SourceMgr.h"
25#include "llvm/Support/raw_ostream.h"
26#include "llvm/ADT/SmallVector.h"
27#include "llvm/ADT/StringExtras.h"
28#include "llvm/ADT/StringSwitch.h"
29#include "llvm/ADT/Twine.h"
30using namespace llvm;
31
32/// Shift types used for register controlled shifts in ARM memory addressing.
33enum ShiftType {
34  Lsl,
35  Lsr,
36  Asr,
37  Ror,
38  Rrx
39};
40
41namespace {
42
43class ARMOperand;
44
45class ARMAsmParser : public TargetAsmParser {
46  MCAsmParser &Parser;
47  TargetMachine &TM;
48
49  MCAsmParser &getParser() const { return Parser; }
50  MCAsmLexer &getLexer() const { return Parser.getLexer(); }
51
52  void Warning(SMLoc L, const Twine &Msg) { Parser.Warning(L, Msg); }
53  bool Error(SMLoc L, const Twine &Msg) { return Parser.Error(L, Msg); }
54
55  int TryParseRegister();
56  virtual bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc);
57  bool TryParseCoprocessorOperandName(SmallVectorImpl<MCParsedAsmOperand*>&);
58  bool TryParseRegisterWithWriteBack(SmallVectorImpl<MCParsedAsmOperand*> &);
59  bool ParseRegisterList(SmallVectorImpl<MCParsedAsmOperand*> &);
60  bool ParseMemory(SmallVectorImpl<MCParsedAsmOperand*> &);
61  bool ParseOperand(SmallVectorImpl<MCParsedAsmOperand*> &, bool hasCoprocOp);
62  bool ParsePrefix(ARMMCExpr::VariantKind &RefKind);
63  const MCExpr *ApplyPrefixToExpr(const MCExpr *E,
64                                  MCSymbolRefExpr::VariantKind Variant);
65
66
67  bool ParseMemoryOffsetReg(bool &Negative,
68                            bool &OffsetRegShifted,
69                            enum ShiftType &ShiftType,
70                            const MCExpr *&ShiftAmount,
71                            const MCExpr *&Offset,
72                            bool &OffsetIsReg,
73                            int &OffsetRegNum,
74                            SMLoc &E);
75  bool ParseShift(enum ShiftType &St, const MCExpr *&ShiftAmount, SMLoc &E);
76  bool ParseDirectiveWord(unsigned Size, SMLoc L);
77  bool ParseDirectiveThumb(SMLoc L);
78  bool ParseDirectiveThumbFunc(SMLoc L);
79  bool ParseDirectiveCode(SMLoc L);
80  bool ParseDirectiveSyntax(SMLoc L);
81
82  bool MatchAndEmitInstruction(SMLoc IDLoc,
83                               SmallVectorImpl<MCParsedAsmOperand*> &Operands,
84                               MCStreamer &Out);
85  void GetMnemonicAcceptInfo(StringRef Mnemonic, bool &CanAcceptCarrySet,
86                             bool &CanAcceptPredicationCode);
87
88  /// @name Auto-generated Match Functions
89  /// {
90
91#define GET_ASSEMBLER_HEADER
92#include "ARMGenAsmMatcher.inc"
93
94  /// }
95
96public:
97  ARMAsmParser(const Target &T, MCAsmParser &_Parser, TargetMachine &_TM)
98    : TargetAsmParser(T), Parser(_Parser), TM(_TM) {
99      // Initialize the set of available features.
100      setAvailableFeatures(ComputeAvailableFeatures(
101          &TM.getSubtarget<ARMSubtarget>()));
102    }
103
104  virtual bool ParseInstruction(StringRef Name, SMLoc NameLoc,
105                                SmallVectorImpl<MCParsedAsmOperand*> &Operands);
106  virtual bool ParseDirective(AsmToken DirectiveID);
107};
108} // end anonymous namespace
109
110namespace {
111
112/// ARMOperand - Instances of this class represent a parsed ARM machine
113/// instruction.
114class ARMOperand : public MCParsedAsmOperand {
115  enum KindTy {
116    CondCode,
117    CCOut,
118    Immediate,
119    Memory,
120    Register,
121    RegisterList,
122    DPRRegisterList,
123    SPRRegisterList,
124    Token
125  } Kind;
126
127  SMLoc StartLoc, EndLoc;
128  SmallVector<unsigned, 8> Registers;
129
130  union {
131    struct {
132      ARMCC::CondCodes Val;
133    } CC;
134
135    struct {
136      const char *Data;
137      unsigned Length;
138    } Tok;
139
140    struct {
141      unsigned RegNum;
142    } Reg;
143
144    struct {
145      const MCExpr *Val;
146    } Imm;
147
148    /// Combined record for all forms of ARM address expressions.
149    struct {
150      unsigned BaseRegNum;
151      union {
152        unsigned RegNum;     ///< Offset register num, when OffsetIsReg.
153        const MCExpr *Value; ///< Offset value, when !OffsetIsReg.
154      } Offset;
155      const MCExpr *ShiftAmount;     // used when OffsetRegShifted is true
156      enum ShiftType ShiftType;      // used when OffsetRegShifted is true
157      unsigned OffsetRegShifted : 1; // only used when OffsetIsReg is true
158      unsigned Preindexed       : 1;
159      unsigned Postindexed      : 1;
160      unsigned OffsetIsReg      : 1;
161      unsigned Negative         : 1; // only used when OffsetIsReg is true
162      unsigned Writeback        : 1;
163    } Mem;
164  };
165
166  ARMOperand(KindTy K) : MCParsedAsmOperand(), Kind(K) {}
167public:
168  ARMOperand(const ARMOperand &o) : MCParsedAsmOperand() {
169    Kind = o.Kind;
170    StartLoc = o.StartLoc;
171    EndLoc = o.EndLoc;
172    switch (Kind) {
173    case CondCode:
174      CC = o.CC;
175      break;
176    case Token:
177      Tok = o.Tok;
178      break;
179    case CCOut:
180    case Register:
181      Reg = o.Reg;
182      break;
183    case RegisterList:
184    case DPRRegisterList:
185    case SPRRegisterList:
186      Registers = o.Registers;
187      break;
188    case Immediate:
189      Imm = o.Imm;
190      break;
191    case Memory:
192      Mem = o.Mem;
193      break;
194    }
195  }
196
197  /// getStartLoc - Get the location of the first token of this operand.
198  SMLoc getStartLoc() const { return StartLoc; }
199  /// getEndLoc - Get the location of the last token of this operand.
200  SMLoc getEndLoc() const { return EndLoc; }
201
202  ARMCC::CondCodes getCondCode() const {
203    assert(Kind == CondCode && "Invalid access!");
204    return CC.Val;
205  }
206
207  StringRef getToken() const {
208    assert(Kind == Token && "Invalid access!");
209    return StringRef(Tok.Data, Tok.Length);
210  }
211
212  unsigned getReg() const {
213    assert((Kind == Register || Kind == CCOut) && "Invalid access!");
214    return Reg.RegNum;
215  }
216
217  const SmallVectorImpl<unsigned> &getRegList() const {
218    assert((Kind == RegisterList || Kind == DPRRegisterList ||
219            Kind == SPRRegisterList) && "Invalid access!");
220    return Registers;
221  }
222
223  const MCExpr *getImm() const {
224    assert(Kind == Immediate && "Invalid access!");
225    return Imm.Val;
226  }
227
228  /// @name Memory Operand Accessors
229  /// @{
230
231  unsigned getMemBaseRegNum() const {
232    return Mem.BaseRegNum;
233  }
234  unsigned getMemOffsetRegNum() const {
235    assert(Mem.OffsetIsReg && "Invalid access!");
236    return Mem.Offset.RegNum;
237  }
238  const MCExpr *getMemOffset() const {
239    assert(!Mem.OffsetIsReg && "Invalid access!");
240    return Mem.Offset.Value;
241  }
242  unsigned getMemOffsetRegShifted() const {
243    assert(Mem.OffsetIsReg && "Invalid access!");
244    return Mem.OffsetRegShifted;
245  }
246  const MCExpr *getMemShiftAmount() const {
247    assert(Mem.OffsetIsReg && Mem.OffsetRegShifted && "Invalid access!");
248    return Mem.ShiftAmount;
249  }
250  enum ShiftType getMemShiftType() const {
251    assert(Mem.OffsetIsReg && Mem.OffsetRegShifted && "Invalid access!");
252    return Mem.ShiftType;
253  }
254  bool getMemPreindexed() const { return Mem.Preindexed; }
255  bool getMemPostindexed() const { return Mem.Postindexed; }
256  bool getMemOffsetIsReg() const { return Mem.OffsetIsReg; }
257  bool getMemNegative() const { return Mem.Negative; }
258  bool getMemWriteback() const { return Mem.Writeback; }
259
260  /// @}
261
262  bool isCondCode() const { return Kind == CondCode; }
263  bool isCCOut() const { return Kind == CCOut; }
264  bool isImm() const { return Kind == Immediate; }
265  bool isReg() const { return Kind == Register; }
266  bool isRegList() const { return Kind == RegisterList; }
267  bool isDPRRegList() const { return Kind == DPRRegisterList; }
268  bool isSPRRegList() const { return Kind == SPRRegisterList; }
269  bool isToken() const { return Kind == Token; }
270  bool isMemory() const { return Kind == Memory; }
271  bool isMemMode5() const {
272    if (!isMemory() || getMemOffsetIsReg() || getMemWriteback() ||
273        getMemNegative())
274      return false;
275
276    const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemOffset());
277    if (!CE) return false;
278
279    // The offset must be a multiple of 4 in the range 0-1020.
280    int64_t Value = CE->getValue();
281    return ((Value & 0x3) == 0 && Value <= 1020 && Value >= -1020);
282  }
283  bool isMemModeRegThumb() const {
284    if (!isMemory() || !getMemOffsetIsReg() || getMemWriteback())
285      return false;
286    return true;
287  }
288  bool isMemModeImmThumb() const {
289    if (!isMemory() || getMemOffsetIsReg() || getMemWriteback())
290      return false;
291
292    const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemOffset());
293    if (!CE) return false;
294
295    // The offset must be a multiple of 4 in the range 0-124.
296    uint64_t Value = CE->getValue();
297    return ((Value & 0x3) == 0 && Value <= 124);
298  }
299
300  void addExpr(MCInst &Inst, const MCExpr *Expr) const {
301    // Add as immediates when possible.  Null MCExpr = 0.
302    if (Expr == 0)
303      Inst.addOperand(MCOperand::CreateImm(0));
304    else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
305      Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
306    else
307      Inst.addOperand(MCOperand::CreateExpr(Expr));
308  }
309
310  void addCondCodeOperands(MCInst &Inst, unsigned N) const {
311    assert(N == 2 && "Invalid number of operands!");
312    Inst.addOperand(MCOperand::CreateImm(unsigned(getCondCode())));
313    unsigned RegNum = getCondCode() == ARMCC::AL ? 0: ARM::CPSR;
314    Inst.addOperand(MCOperand::CreateReg(RegNum));
315  }
316
317  void addCCOutOperands(MCInst &Inst, unsigned N) const {
318    assert(N == 1 && "Invalid number of operands!");
319    Inst.addOperand(MCOperand::CreateReg(getReg()));
320  }
321
322  void addRegOperands(MCInst &Inst, unsigned N) const {
323    assert(N == 1 && "Invalid number of operands!");
324    Inst.addOperand(MCOperand::CreateReg(getReg()));
325  }
326
327  void addRegListOperands(MCInst &Inst, unsigned N) const {
328    assert(N == 1 && "Invalid number of operands!");
329    const SmallVectorImpl<unsigned> &RegList = getRegList();
330    for (SmallVectorImpl<unsigned>::const_iterator
331           I = RegList.begin(), E = RegList.end(); I != E; ++I)
332      Inst.addOperand(MCOperand::CreateReg(*I));
333  }
334
335  void addDPRRegListOperands(MCInst &Inst, unsigned N) const {
336    addRegListOperands(Inst, N);
337  }
338
339  void addSPRRegListOperands(MCInst &Inst, unsigned N) const {
340    addRegListOperands(Inst, N);
341  }
342
343  void addImmOperands(MCInst &Inst, unsigned N) const {
344    assert(N == 1 && "Invalid number of operands!");
345    addExpr(Inst, getImm());
346  }
347
348  void addMemMode5Operands(MCInst &Inst, unsigned N) const {
349    assert(N == 2 && isMemMode5() && "Invalid number of operands!");
350
351    Inst.addOperand(MCOperand::CreateReg(getMemBaseRegNum()));
352    assert(!getMemOffsetIsReg() && "Invalid mode 5 operand");
353
354    // FIXME: #-0 is encoded differently than #0. Does the parser preserve
355    // the difference?
356    const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemOffset());
357    assert(CE && "Non-constant mode 5 offset operand!");
358
359    // The MCInst offset operand doesn't include the low two bits (like
360    // the instruction encoding).
361    int64_t Offset = CE->getValue() / 4;
362    if (Offset >= 0)
363      Inst.addOperand(MCOperand::CreateImm(ARM_AM::getAM5Opc(ARM_AM::add,
364                                                             Offset)));
365    else
366      Inst.addOperand(MCOperand::CreateImm(ARM_AM::getAM5Opc(ARM_AM::sub,
367                                                             -Offset)));
368  }
369
370  void addMemModeRegThumbOperands(MCInst &Inst, unsigned N) const {
371    assert(N == 2 && isMemModeRegThumb() && "Invalid number of operands!");
372    Inst.addOperand(MCOperand::CreateReg(getMemBaseRegNum()));
373    Inst.addOperand(MCOperand::CreateReg(getMemOffsetRegNum()));
374  }
375
376  void addMemModeImmThumbOperands(MCInst &Inst, unsigned N) const {
377    assert(N == 2 && isMemModeImmThumb() && "Invalid number of operands!");
378    Inst.addOperand(MCOperand::CreateReg(getMemBaseRegNum()));
379    const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemOffset());
380    assert(CE && "Non-constant mode offset operand!");
381    Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
382  }
383
384  virtual void dump(raw_ostream &OS) const;
385
386  static ARMOperand *CreateCondCode(ARMCC::CondCodes CC, SMLoc S) {
387    ARMOperand *Op = new ARMOperand(CondCode);
388    Op->CC.Val = CC;
389    Op->StartLoc = S;
390    Op->EndLoc = S;
391    return Op;
392  }
393
394  static ARMOperand *CreateCCOut(unsigned RegNum, SMLoc S) {
395    ARMOperand *Op = new ARMOperand(CCOut);
396    Op->Reg.RegNum = RegNum;
397    Op->StartLoc = S;
398    Op->EndLoc = S;
399    return Op;
400  }
401
402  static ARMOperand *CreateToken(StringRef Str, SMLoc S) {
403    ARMOperand *Op = new ARMOperand(Token);
404    Op->Tok.Data = Str.data();
405    Op->Tok.Length = Str.size();
406    Op->StartLoc = S;
407    Op->EndLoc = S;
408    return Op;
409  }
410
411  static ARMOperand *CreateReg(unsigned RegNum, SMLoc S, SMLoc E) {
412    ARMOperand *Op = new ARMOperand(Register);
413    Op->Reg.RegNum = RegNum;
414    Op->StartLoc = S;
415    Op->EndLoc = E;
416    return Op;
417  }
418
419  static ARMOperand *
420  CreateRegList(const SmallVectorImpl<std::pair<unsigned, SMLoc> > &Regs,
421                SMLoc StartLoc, SMLoc EndLoc) {
422    KindTy Kind = RegisterList;
423
424    if (ARM::DPRRegClass.contains(Regs.front().first))
425      Kind = DPRRegisterList;
426    else if (ARM::SPRRegClass.contains(Regs.front().first))
427      Kind = SPRRegisterList;
428
429    ARMOperand *Op = new ARMOperand(Kind);
430    for (SmallVectorImpl<std::pair<unsigned, SMLoc> >::const_iterator
431           I = Regs.begin(), E = Regs.end(); I != E; ++I)
432      Op->Registers.push_back(I->first);
433    array_pod_sort(Op->Registers.begin(), Op->Registers.end());
434    Op->StartLoc = StartLoc;
435    Op->EndLoc = EndLoc;
436    return Op;
437  }
438
439  static ARMOperand *CreateImm(const MCExpr *Val, SMLoc S, SMLoc E) {
440    ARMOperand *Op = new ARMOperand(Immediate);
441    Op->Imm.Val = Val;
442    Op->StartLoc = S;
443    Op->EndLoc = E;
444    return Op;
445  }
446
447  static ARMOperand *CreateMem(unsigned BaseRegNum, bool OffsetIsReg,
448                               const MCExpr *Offset, int OffsetRegNum,
449                               bool OffsetRegShifted, enum ShiftType ShiftType,
450                               const MCExpr *ShiftAmount, bool Preindexed,
451                               bool Postindexed, bool Negative, bool Writeback,
452                               SMLoc S, SMLoc E) {
453    assert((OffsetRegNum == -1 || OffsetIsReg) &&
454           "OffsetRegNum must imply OffsetIsReg!");
455    assert((!OffsetRegShifted || OffsetIsReg) &&
456           "OffsetRegShifted must imply OffsetIsReg!");
457    assert((Offset || OffsetIsReg) &&
458           "Offset must exists unless register offset is used!");
459    assert((!ShiftAmount || (OffsetIsReg && OffsetRegShifted)) &&
460           "Cannot have shift amount without shifted register offset!");
461    assert((!Offset || !OffsetIsReg) &&
462           "Cannot have expression offset and register offset!");
463
464    ARMOperand *Op = new ARMOperand(Memory);
465    Op->Mem.BaseRegNum = BaseRegNum;
466    Op->Mem.OffsetIsReg = OffsetIsReg;
467    if (OffsetIsReg)
468      Op->Mem.Offset.RegNum = OffsetRegNum;
469    else
470      Op->Mem.Offset.Value = Offset;
471    Op->Mem.OffsetRegShifted = OffsetRegShifted;
472    Op->Mem.ShiftType = ShiftType;
473    Op->Mem.ShiftAmount = ShiftAmount;
474    Op->Mem.Preindexed = Preindexed;
475    Op->Mem.Postindexed = Postindexed;
476    Op->Mem.Negative = Negative;
477    Op->Mem.Writeback = Writeback;
478
479    Op->StartLoc = S;
480    Op->EndLoc = E;
481    return Op;
482  }
483};
484
485} // end anonymous namespace.
486
487void ARMOperand::dump(raw_ostream &OS) const {
488  switch (Kind) {
489  case CondCode:
490    OS << "<ARMCC::" << ARMCondCodeToString(getCondCode()) << ">";
491    break;
492  case CCOut:
493    OS << "<ccout " << getReg() << ">";
494    break;
495  case Immediate:
496    getImm()->print(OS);
497    break;
498  case Memory:
499    OS << "<memory "
500       << "base:" << getMemBaseRegNum();
501    if (getMemOffsetIsReg()) {
502      OS << " offset:<register " << getMemOffsetRegNum();
503      if (getMemOffsetRegShifted()) {
504        OS << " offset-shift-type:" << getMemShiftType();
505        OS << " offset-shift-amount:" << *getMemShiftAmount();
506      }
507    } else {
508      OS << " offset:" << *getMemOffset();
509    }
510    if (getMemOffsetIsReg())
511      OS << " (offset-is-reg)";
512    if (getMemPreindexed())
513      OS << " (pre-indexed)";
514    if (getMemPostindexed())
515      OS << " (post-indexed)";
516    if (getMemNegative())
517      OS << " (negative)";
518    if (getMemWriteback())
519      OS << " (writeback)";
520    OS << ">";
521    break;
522  case Register:
523    OS << "<register " << getReg() << ">";
524    break;
525  case RegisterList:
526  case DPRRegisterList:
527  case SPRRegisterList: {
528    OS << "<register_list ";
529
530    const SmallVectorImpl<unsigned> &RegList = getRegList();
531    for (SmallVectorImpl<unsigned>::const_iterator
532           I = RegList.begin(), E = RegList.end(); I != E; ) {
533      OS << *I;
534      if (++I < E) OS << ", ";
535    }
536
537    OS << ">";
538    break;
539  }
540  case Token:
541    OS << "'" << getToken() << "'";
542    break;
543  }
544}
545
546/// @name Auto-generated Match Functions
547/// {
548
549static unsigned MatchRegisterName(StringRef Name);
550
551/// }
552
553bool ARMAsmParser::ParseRegister(unsigned &RegNo,
554                                 SMLoc &StartLoc, SMLoc &EndLoc) {
555  RegNo = TryParseRegister();
556
557  return (RegNo == (unsigned)-1);
558}
559
560/// Try to parse a register name.  The token must be an Identifier when called,
561/// and if it is a register name the token is eaten and the register number is
562/// returned.  Otherwise return -1.
563///
564int ARMAsmParser::TryParseRegister() {
565  const AsmToken &Tok = Parser.getTok();
566  assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
567
568  // FIXME: Validate register for the current architecture; we have to do
569  // validation later, so maybe there is no need for this here.
570  std::string upperCase = Tok.getString().str();
571  std::string lowerCase = LowercaseString(upperCase);
572  unsigned RegNum = MatchRegisterName(lowerCase);
573  if (!RegNum) {
574    RegNum = StringSwitch<unsigned>(lowerCase)
575      .Case("r13", ARM::SP)
576      .Case("r14", ARM::LR)
577      .Case("r15", ARM::PC)
578      .Case("ip", ARM::R12)
579      .Default(0);
580  }
581  if (!RegNum) return -1;
582
583  Parser.Lex(); // Eat identifier token.
584  return RegNum;
585}
586
587/// Try to parse a register name.  The token must be an Identifier when called.
588/// If it's a register, an AsmOperand is created. Another AsmOperand is created
589/// if there is a "writeback". 'true' if it's not a register.
590///
591/// TODO this is likely to change to allow different register types and or to
592/// parse for a specific register type.
593bool ARMAsmParser::
594TryParseRegisterWithWriteBack(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
595  SMLoc S = Parser.getTok().getLoc();
596  int RegNo = TryParseRegister();
597  if (RegNo == -1)
598    return true;
599
600  Operands.push_back(ARMOperand::CreateReg(RegNo, S, Parser.getTok().getLoc()));
601
602  const AsmToken &ExclaimTok = Parser.getTok();
603  if (ExclaimTok.is(AsmToken::Exclaim)) {
604    Operands.push_back(ARMOperand::CreateToken(ExclaimTok.getString(),
605                                               ExclaimTok.getLoc()));
606    Parser.Lex(); // Eat exclaim token
607  }
608
609  return false;
610}
611
612static int MatchCoprocessorOperandName(StringRef Name) {
613  // Use the same layout as the tablegen'erated register name matcher. Ugly,
614  // but efficient.
615  switch (Name.size()) {
616  default: break;
617  case 2:
618    if (Name[0] != 'p' && Name[0] != 'c')
619      return -1;
620    switch (Name[1]) {
621    default:  return -1;
622    case '0': return 0;
623    case '1': return 1;
624    case '2': return 2;
625    case '3': return 3;
626    case '4': return 4;
627    case '5': return 5;
628    case '6': return 6;
629    case '7': return 7;
630    case '8': return 8;
631    case '9': return 9;
632    }
633    break;
634  case 3:
635    if ((Name[0] != 'p' && Name[0] != 'c') || Name[1] != '1')
636      return -1;
637    switch (Name[2]) {
638    default:  return -1;
639    case '0': return 10;
640    case '1': return 11;
641    case '2': return 12;
642    case '3': return 13;
643    case '4': return 14;
644    case '5': return 15;
645    }
646    break;
647  }
648
649  llvm_unreachable("Unhandled coprocessor operand string!");
650  return -1;
651}
652
653/// TryParseCoprocessorOperandName - Try to parse an coprocessor related
654/// instruction with a symbolic operand name.  The token must be an Identifier
655/// when called, and if it is a coprocessor related operand name, the token is
656/// eaten and the operand is added to the operand list. Example: operands like
657/// "p1", "p7", "c3", "c5", ...
658bool ARMAsmParser::
659TryParseCoprocessorOperandName(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
660  SMLoc S = Parser.getTok().getLoc();
661  const AsmToken &Tok = Parser.getTok();
662  assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
663
664  int Num = MatchCoprocessorOperandName(Tok.getString());
665  if (Num == -1)
666    return true;
667
668  Parser.Lex(); // Eat identifier token.
669  Operands.push_back(ARMOperand::CreateImm(
670       MCConstantExpr::Create(Num, getContext()), S, Parser.getTok().getLoc()));
671  return false;
672}
673
674/// Parse a register list, return it if successful else return null.  The first
675/// token must be a '{' when called.
676bool ARMAsmParser::
677ParseRegisterList(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
678  assert(Parser.getTok().is(AsmToken::LCurly) &&
679         "Token is not a Left Curly Brace");
680  SMLoc S = Parser.getTok().getLoc();
681
682  // Read the rest of the registers in the list.
683  unsigned PrevRegNum = 0;
684  SmallVector<std::pair<unsigned, SMLoc>, 32> Registers;
685
686  do {
687    bool IsRange = Parser.getTok().is(AsmToken::Minus);
688    Parser.Lex(); // Eat non-identifier token.
689
690    const AsmToken &RegTok = Parser.getTok();
691    SMLoc RegLoc = RegTok.getLoc();
692    if (RegTok.isNot(AsmToken::Identifier)) {
693      Error(RegLoc, "register expected");
694      return true;
695    }
696
697    int RegNum = TryParseRegister();
698    if (RegNum == -1) {
699      Error(RegLoc, "register expected");
700      return true;
701    }
702
703    if (IsRange) {
704      int Reg = PrevRegNum;
705      do {
706        ++Reg;
707        Registers.push_back(std::make_pair(Reg, RegLoc));
708      } while (Reg != RegNum);
709    } else {
710      Registers.push_back(std::make_pair(RegNum, RegLoc));
711    }
712
713    PrevRegNum = RegNum;
714  } while (Parser.getTok().is(AsmToken::Comma) ||
715           Parser.getTok().is(AsmToken::Minus));
716
717  // Process the right curly brace of the list.
718  const AsmToken &RCurlyTok = Parser.getTok();
719  if (RCurlyTok.isNot(AsmToken::RCurly)) {
720    Error(RCurlyTok.getLoc(), "'}' expected");
721    return true;
722  }
723
724  SMLoc E = RCurlyTok.getLoc();
725  Parser.Lex(); // Eat right curly brace token.
726
727  // Verify the register list.
728  SmallVectorImpl<std::pair<unsigned, SMLoc> >::const_iterator
729    RI = Registers.begin(), RE = Registers.end();
730
731  unsigned HighRegNum = getARMRegisterNumbering(RI->first);
732  bool EmittedWarning = false;
733
734  DenseMap<unsigned, bool> RegMap;
735  RegMap[HighRegNum] = true;
736
737  for (++RI; RI != RE; ++RI) {
738    const std::pair<unsigned, SMLoc> &RegInfo = *RI;
739    unsigned Reg = getARMRegisterNumbering(RegInfo.first);
740
741    if (RegMap[Reg]) {
742      Error(RegInfo.second, "register duplicated in register list");
743      return true;
744    }
745
746    if (!EmittedWarning && Reg < HighRegNum)
747      Warning(RegInfo.second,
748              "register not in ascending order in register list");
749
750    RegMap[Reg] = true;
751    HighRegNum = std::max(Reg, HighRegNum);
752  }
753
754  Operands.push_back(ARMOperand::CreateRegList(Registers, S, E));
755  return false;
756}
757
758/// Parse an ARM memory expression, return false if successful else return true
759/// or an error.  The first token must be a '[' when called.
760///
761/// TODO Only preindexing and postindexing addressing are started, unindexed
762/// with option, etc are still to do.
763bool ARMAsmParser::
764ParseMemory(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
765  SMLoc S, E;
766  assert(Parser.getTok().is(AsmToken::LBrac) &&
767         "Token is not a Left Bracket");
768  S = Parser.getTok().getLoc();
769  Parser.Lex(); // Eat left bracket token.
770
771  const AsmToken &BaseRegTok = Parser.getTok();
772  if (BaseRegTok.isNot(AsmToken::Identifier)) {
773    Error(BaseRegTok.getLoc(), "register expected");
774    return true;
775  }
776  int BaseRegNum = TryParseRegister();
777  if (BaseRegNum == -1) {
778    Error(BaseRegTok.getLoc(), "register expected");
779    return true;
780  }
781
782  // The next token must either be a comma or a closing bracket.
783  const AsmToken &Tok = Parser.getTok();
784  if (!Tok.is(AsmToken::Comma) && !Tok.is(AsmToken::RBrac))
785    return true;
786
787  bool Preindexed = false;
788  bool Postindexed = false;
789  bool OffsetIsReg = false;
790  bool Negative = false;
791  bool Writeback = false;
792  ARMOperand *WBOp = 0;
793  int OffsetRegNum = -1;
794  bool OffsetRegShifted = false;
795  enum ShiftType ShiftType = Lsl;
796  const MCExpr *ShiftAmount = 0;
797  const MCExpr *Offset = 0;
798
799  // First look for preindexed address forms, that is after the "[Rn" we now
800  // have to see if the next token is a comma.
801  if (Tok.is(AsmToken::Comma)) {
802    Preindexed = true;
803    Parser.Lex(); // Eat comma token.
804
805    if (ParseMemoryOffsetReg(Negative, OffsetRegShifted, ShiftType, ShiftAmount,
806                             Offset, OffsetIsReg, OffsetRegNum, E))
807      return true;
808    const AsmToken &RBracTok = Parser.getTok();
809    if (RBracTok.isNot(AsmToken::RBrac)) {
810      Error(RBracTok.getLoc(), "']' expected");
811      return true;
812    }
813    E = RBracTok.getLoc();
814    Parser.Lex(); // Eat right bracket token.
815
816    const AsmToken &ExclaimTok = Parser.getTok();
817    if (ExclaimTok.is(AsmToken::Exclaim)) {
818      WBOp = ARMOperand::CreateToken(ExclaimTok.getString(),
819                                     ExclaimTok.getLoc());
820      Writeback = true;
821      Parser.Lex(); // Eat exclaim token
822    }
823  } else {
824    // The "[Rn" we have so far was not followed by a comma.
825
826    // If there's anything other than the right brace, this is a post indexing
827    // addressing form.
828    E = Tok.getLoc();
829    Parser.Lex(); // Eat right bracket token.
830
831    const AsmToken &NextTok = Parser.getTok();
832
833    if (NextTok.isNot(AsmToken::EndOfStatement)) {
834      Postindexed = true;
835      Writeback = true;
836
837      if (NextTok.isNot(AsmToken::Comma)) {
838        Error(NextTok.getLoc(), "',' expected");
839        return true;
840      }
841
842      Parser.Lex(); // Eat comma token.
843
844      if (ParseMemoryOffsetReg(Negative, OffsetRegShifted, ShiftType,
845                               ShiftAmount, Offset, OffsetIsReg, OffsetRegNum,
846                               E))
847        return true;
848    }
849  }
850
851  // Force Offset to exist if used.
852  if (!OffsetIsReg) {
853    if (!Offset)
854      Offset = MCConstantExpr::Create(0, getContext());
855  }
856
857  Operands.push_back(ARMOperand::CreateMem(BaseRegNum, OffsetIsReg, Offset,
858                                           OffsetRegNum, OffsetRegShifted,
859                                           ShiftType, ShiftAmount, Preindexed,
860                                           Postindexed, Negative, Writeback,
861                                           S, E));
862  if (WBOp)
863    Operands.push_back(WBOp);
864
865  return false;
866}
867
868/// Parse the offset of a memory operand after we have seen "[Rn," or "[Rn],"
869/// we will parse the following (were +/- means that a plus or minus is
870/// optional):
871///   +/-Rm
872///   +/-Rm, shift
873///   #offset
874/// we return false on success or an error otherwise.
875bool ARMAsmParser::ParseMemoryOffsetReg(bool &Negative,
876                                        bool &OffsetRegShifted,
877                                        enum ShiftType &ShiftType,
878                                        const MCExpr *&ShiftAmount,
879                                        const MCExpr *&Offset,
880                                        bool &OffsetIsReg,
881                                        int &OffsetRegNum,
882                                        SMLoc &E) {
883  Negative = false;
884  OffsetRegShifted = false;
885  OffsetIsReg = false;
886  OffsetRegNum = -1;
887  const AsmToken &NextTok = Parser.getTok();
888  E = NextTok.getLoc();
889  if (NextTok.is(AsmToken::Plus))
890    Parser.Lex(); // Eat plus token.
891  else if (NextTok.is(AsmToken::Minus)) {
892    Negative = true;
893    Parser.Lex(); // Eat minus token
894  }
895  // See if there is a register following the "[Rn," or "[Rn]," we have so far.
896  const AsmToken &OffsetRegTok = Parser.getTok();
897  if (OffsetRegTok.is(AsmToken::Identifier)) {
898    SMLoc CurLoc = OffsetRegTok.getLoc();
899    OffsetRegNum = TryParseRegister();
900    if (OffsetRegNum != -1) {
901      OffsetIsReg = true;
902      E = CurLoc;
903    }
904  }
905
906  // If we parsed a register as the offset then there can be a shift after that.
907  if (OffsetRegNum != -1) {
908    // Look for a comma then a shift
909    const AsmToken &Tok = Parser.getTok();
910    if (Tok.is(AsmToken::Comma)) {
911      Parser.Lex(); // Eat comma token.
912
913      const AsmToken &Tok = Parser.getTok();
914      if (ParseShift(ShiftType, ShiftAmount, E))
915        return Error(Tok.getLoc(), "shift expected");
916      OffsetRegShifted = true;
917    }
918  }
919  else { // the "[Rn," or "[Rn,]" we have so far was not followed by "Rm"
920    // Look for #offset following the "[Rn," or "[Rn],"
921    const AsmToken &HashTok = Parser.getTok();
922    if (HashTok.isNot(AsmToken::Hash))
923      return Error(HashTok.getLoc(), "'#' expected");
924
925    Parser.Lex(); // Eat hash token.
926
927    if (getParser().ParseExpression(Offset))
928     return true;
929    E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
930  }
931  return false;
932}
933
934/// ParseShift as one of these two:
935///   ( lsl | lsr | asr | ror ) , # shift_amount
936///   rrx
937/// and returns true if it parses a shift otherwise it returns false.
938bool ARMAsmParser::ParseShift(ShiftType &St, const MCExpr *&ShiftAmount,
939                              SMLoc &E) {
940  const AsmToken &Tok = Parser.getTok();
941  if (Tok.isNot(AsmToken::Identifier))
942    return true;
943  StringRef ShiftName = Tok.getString();
944  if (ShiftName == "lsl" || ShiftName == "LSL")
945    St = Lsl;
946  else if (ShiftName == "lsr" || ShiftName == "LSR")
947    St = Lsr;
948  else if (ShiftName == "asr" || ShiftName == "ASR")
949    St = Asr;
950  else if (ShiftName == "ror" || ShiftName == "ROR")
951    St = Ror;
952  else if (ShiftName == "rrx" || ShiftName == "RRX")
953    St = Rrx;
954  else
955    return true;
956  Parser.Lex(); // Eat shift type token.
957
958  // Rrx stands alone.
959  if (St == Rrx)
960    return false;
961
962  // Otherwise, there must be a '#' and a shift amount.
963  const AsmToken &HashTok = Parser.getTok();
964  if (HashTok.isNot(AsmToken::Hash))
965    return Error(HashTok.getLoc(), "'#' expected");
966  Parser.Lex(); // Eat hash token.
967
968  if (getParser().ParseExpression(ShiftAmount))
969    return true;
970
971  return false;
972}
973
974/// Parse a arm instruction operand.  For now this parses the operand regardless
975/// of the mnemonic.
976bool ARMAsmParser::ParseOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands,
977                                bool hasCoprocOp){
978  SMLoc S, E;
979  switch (getLexer().getKind()) {
980  default:
981    Error(Parser.getTok().getLoc(), "unexpected token in operand");
982    return true;
983  case AsmToken::Identifier:
984    if (!TryParseRegisterWithWriteBack(Operands))
985      return false;
986    if (hasCoprocOp && !TryParseCoprocessorOperandName(Operands))
987      return false;
988
989    // Fall though for the Identifier case that is not a register or a
990    // special name.
991  case AsmToken::Integer: // things like 1f and 2b as a branch targets
992  case AsmToken::Dot: {   // . as a branch target
993    // This was not a register so parse other operands that start with an
994    // identifier (like labels) as expressions and create them as immediates.
995    const MCExpr *IdVal;
996    S = Parser.getTok().getLoc();
997    if (getParser().ParseExpression(IdVal))
998      return true;
999    E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1000    Operands.push_back(ARMOperand::CreateImm(IdVal, S, E));
1001    return false;
1002  }
1003  case AsmToken::LBrac:
1004    return ParseMemory(Operands);
1005  case AsmToken::LCurly:
1006    return ParseRegisterList(Operands);
1007  case AsmToken::Hash:
1008    // #42 -> immediate.
1009    // TODO: ":lower16:" and ":upper16:" modifiers after # before immediate
1010    S = Parser.getTok().getLoc();
1011    Parser.Lex();
1012    const MCExpr *ImmVal;
1013    if (getParser().ParseExpression(ImmVal))
1014      return true;
1015    E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1016    Operands.push_back(ARMOperand::CreateImm(ImmVal, S, E));
1017    return false;
1018  case AsmToken::Colon: {
1019    // ":lower16:" and ":upper16:" expression prefixes
1020    // FIXME: Check it's an expression prefix,
1021    // e.g. (FOO - :lower16:BAR) isn't legal.
1022    ARMMCExpr::VariantKind RefKind;
1023    if (ParsePrefix(RefKind))
1024      return true;
1025
1026    const MCExpr *SubExprVal;
1027    if (getParser().ParseExpression(SubExprVal))
1028      return true;
1029
1030    const MCExpr *ExprVal = ARMMCExpr::Create(RefKind, SubExprVal,
1031                                                   getContext());
1032    E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
1033    Operands.push_back(ARMOperand::CreateImm(ExprVal, S, E));
1034    return false;
1035  }
1036  }
1037}
1038
1039// ParsePrefix - Parse ARM 16-bit relocations expression prefix, i.e.
1040//  :lower16: and :upper16:.
1041bool ARMAsmParser::ParsePrefix(ARMMCExpr::VariantKind &RefKind) {
1042  RefKind = ARMMCExpr::VK_ARM_None;
1043
1044  // :lower16: and :upper16: modifiers
1045  assert(getLexer().is(AsmToken::Colon) && "expected a :");
1046  Parser.Lex(); // Eat ':'
1047
1048  if (getLexer().isNot(AsmToken::Identifier)) {
1049    Error(Parser.getTok().getLoc(), "expected prefix identifier in operand");
1050    return true;
1051  }
1052
1053  StringRef IDVal = Parser.getTok().getIdentifier();
1054  if (IDVal == "lower16") {
1055    RefKind = ARMMCExpr::VK_ARM_LO16;
1056  } else if (IDVal == "upper16") {
1057    RefKind = ARMMCExpr::VK_ARM_HI16;
1058  } else {
1059    Error(Parser.getTok().getLoc(), "unexpected prefix in operand");
1060    return true;
1061  }
1062  Parser.Lex();
1063
1064  if (getLexer().isNot(AsmToken::Colon)) {
1065    Error(Parser.getTok().getLoc(), "unexpected token after prefix");
1066    return true;
1067  }
1068  Parser.Lex(); // Eat the last ':'
1069  return false;
1070}
1071
1072const MCExpr *
1073ARMAsmParser::ApplyPrefixToExpr(const MCExpr *E,
1074                                MCSymbolRefExpr::VariantKind Variant) {
1075  // Recurse over the given expression, rebuilding it to apply the given variant
1076  // to the leftmost symbol.
1077  if (Variant == MCSymbolRefExpr::VK_None)
1078    return E;
1079
1080  switch (E->getKind()) {
1081  case MCExpr::Target:
1082    llvm_unreachable("Can't handle target expr yet");
1083  case MCExpr::Constant:
1084    llvm_unreachable("Can't handle lower16/upper16 of constant yet");
1085
1086  case MCExpr::SymbolRef: {
1087    const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
1088
1089    if (SRE->getKind() != MCSymbolRefExpr::VK_None)
1090      return 0;
1091
1092    return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
1093  }
1094
1095  case MCExpr::Unary:
1096    llvm_unreachable("Can't handle unary expressions yet");
1097
1098  case MCExpr::Binary: {
1099    const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
1100    const MCExpr *LHS = ApplyPrefixToExpr(BE->getLHS(), Variant);
1101    const MCExpr *RHS = BE->getRHS();
1102    if (!LHS)
1103      return 0;
1104
1105    return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
1106  }
1107  }
1108
1109  assert(0 && "Invalid expression kind!");
1110  return 0;
1111}
1112
1113/// \brief Given a mnemonic, split out possible predication code and carry
1114/// setting letters to form a canonical mnemonic and flags.
1115//
1116// FIXME: Would be nice to autogen this.
1117static StringRef SplitMnemonicAndCC(StringRef Mnemonic,
1118                                    unsigned &PredicationCode,
1119                                    bool &CarrySetting) {
1120  PredicationCode = ARMCC::AL;
1121  CarrySetting = false;
1122
1123  // Ignore some mnemonics we know aren't predicated forms.
1124  //
1125  // FIXME: Would be nice to autogen this.
1126  if (Mnemonic == "teq" || Mnemonic == "vceq" ||
1127      Mnemonic == "movs" ||
1128      Mnemonic == "svc" ||
1129      (Mnemonic == "mls" || Mnemonic == "smmls" || Mnemonic == "vcls" ||
1130       Mnemonic == "vmls" || Mnemonic == "vnmls") ||
1131      Mnemonic == "vacge" || Mnemonic == "vcge" ||
1132      Mnemonic == "vclt" ||
1133      Mnemonic == "vacgt" || Mnemonic == "vcgt" ||
1134      Mnemonic == "vcle" ||
1135      (Mnemonic == "smlal" || Mnemonic == "umaal" || Mnemonic == "umlal" ||
1136       Mnemonic == "vabal" || Mnemonic == "vmlal" || Mnemonic == "vpadal" ||
1137       Mnemonic == "vqdmlal"))
1138    return Mnemonic;
1139
1140  // First, split out any predication code.
1141  unsigned CC = StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2))
1142    .Case("eq", ARMCC::EQ)
1143    .Case("ne", ARMCC::NE)
1144    .Case("hs", ARMCC::HS)
1145    .Case("lo", ARMCC::LO)
1146    .Case("mi", ARMCC::MI)
1147    .Case("pl", ARMCC::PL)
1148    .Case("vs", ARMCC::VS)
1149    .Case("vc", ARMCC::VC)
1150    .Case("hi", ARMCC::HI)
1151    .Case("ls", ARMCC::LS)
1152    .Case("ge", ARMCC::GE)
1153    .Case("lt", ARMCC::LT)
1154    .Case("gt", ARMCC::GT)
1155    .Case("le", ARMCC::LE)
1156    .Case("al", ARMCC::AL)
1157    .Default(~0U);
1158  if (CC != ~0U) {
1159    Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 2);
1160    PredicationCode = CC;
1161  }
1162
1163  // Next, determine if we have a carry setting bit. We explicitly ignore all
1164  // the instructions we know end in 's'.
1165  if (Mnemonic.endswith("s") &&
1166      !(Mnemonic == "asrs" || Mnemonic == "cps" || Mnemonic == "mls" ||
1167        Mnemonic == "movs" || Mnemonic == "mrs" || Mnemonic == "smmls" ||
1168        Mnemonic == "vabs" || Mnemonic == "vcls" || Mnemonic == "vmls" ||
1169        Mnemonic == "vmrs" || Mnemonic == "vnmls" || Mnemonic == "vqabs" ||
1170        Mnemonic == "vrecps" || Mnemonic == "vrsqrts")) {
1171    Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 1);
1172    CarrySetting = true;
1173  }
1174
1175  return Mnemonic;
1176}
1177
1178/// \brief Given a canonical mnemonic, determine if the instruction ever allows
1179/// inclusion of carry set or predication code operands.
1180//
1181// FIXME: It would be nice to autogen this.
1182void ARMAsmParser::
1183GetMnemonicAcceptInfo(StringRef Mnemonic, bool &CanAcceptCarrySet,
1184                      bool &CanAcceptPredicationCode) {
1185  bool isThumb = TM.getSubtarget<ARMSubtarget>().isThumb();
1186
1187  if (Mnemonic == "and" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
1188      Mnemonic == "rrx" || Mnemonic == "ror" || Mnemonic == "sub" ||
1189      Mnemonic == "smull" || Mnemonic == "add" || Mnemonic == "adc" ||
1190      Mnemonic == "mul" || Mnemonic == "bic" || Mnemonic == "asr" ||
1191      Mnemonic == "umlal" || Mnemonic == "orr" || Mnemonic == "mov" ||
1192      Mnemonic == "rsb" || Mnemonic == "rsc" || Mnemonic == "orn" ||
1193      Mnemonic == "sbc" || Mnemonic == "mla" || Mnemonic == "umull" ||
1194      Mnemonic == "eor" || Mnemonic == "smlal" || Mnemonic == "mvn") {
1195    CanAcceptCarrySet = true;
1196  } else {
1197    CanAcceptCarrySet = false;
1198  }
1199
1200  if (Mnemonic == "cbnz" || Mnemonic == "setend" || Mnemonic == "dmb" ||
1201      Mnemonic == "cps" || Mnemonic == "mcr2" || Mnemonic == "it" ||
1202      Mnemonic == "mcrr2" || Mnemonic == "cbz" || Mnemonic == "cdp2" ||
1203      Mnemonic == "trap" || Mnemonic == "mrc2" || Mnemonic == "mrrc2" ||
1204      Mnemonic == "dsb" || Mnemonic == "movs" || Mnemonic == "isb" ||
1205      Mnemonic == "clrex") {
1206    CanAcceptPredicationCode = false;
1207  } else {
1208    CanAcceptPredicationCode = true;
1209  }
1210
1211  if (isThumb)
1212    if (Mnemonic == "bkpt" || Mnemonic == "mcr" || Mnemonic == "mcrr" ||
1213        Mnemonic == "mrc" || Mnemonic == "mrrc" || Mnemonic == "cdp")
1214      CanAcceptPredicationCode = false;
1215}
1216
1217/// Parse an arm instruction mnemonic followed by its operands.
1218bool ARMAsmParser::ParseInstruction(StringRef Name, SMLoc NameLoc,
1219                               SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1220  // Create the leading tokens for the mnemonic, split by '.' characters.
1221  size_t Start = 0, Next = Name.find('.');
1222  StringRef Head = Name.slice(Start, Next);
1223
1224  // Split out the predication code and carry setting flag from the mnemonic.
1225  unsigned PredicationCode;
1226  bool CarrySetting;
1227  Head = SplitMnemonicAndCC(Head, PredicationCode, CarrySetting);
1228
1229  Operands.push_back(ARMOperand::CreateToken(Head, NameLoc));
1230
1231  // Next, add the CCOut and ConditionCode operands, if needed.
1232  //
1233  // For mnemonics which can ever incorporate a carry setting bit or predication
1234  // code, our matching model involves us always generating CCOut and
1235  // ConditionCode operands to match the mnemonic "as written" and then we let
1236  // the matcher deal with finding the right instruction or generating an
1237  // appropriate error.
1238  bool CanAcceptCarrySet, CanAcceptPredicationCode;
1239  GetMnemonicAcceptInfo(Head, CanAcceptCarrySet, CanAcceptPredicationCode);
1240
1241  // Add the carry setting operand, if necessary.
1242  //
1243  // FIXME: It would be awesome if we could somehow invent a location such that
1244  // match errors on this operand would print a nice diagnostic about how the
1245  // 's' character in the mnemonic resulted in a CCOut operand.
1246  if (CanAcceptCarrySet) {
1247    Operands.push_back(ARMOperand::CreateCCOut(CarrySetting ? ARM::CPSR : 0,
1248                                               NameLoc));
1249  } else {
1250    // This mnemonic can't ever accept a carry set, but the user wrote one (or
1251    // misspelled another mnemonic).
1252
1253    // FIXME: Issue a nice error.
1254  }
1255
1256  // Add the predication code operand, if necessary.
1257  if (CanAcceptPredicationCode) {
1258    Operands.push_back(ARMOperand::CreateCondCode(
1259                         ARMCC::CondCodes(PredicationCode), NameLoc));
1260  } else {
1261    // This mnemonic can't ever accept a predication code, but the user wrote
1262    // one (or misspelled another mnemonic).
1263
1264    // FIXME: Issue a nice error.
1265  }
1266
1267  // Add the remaining tokens in the mnemonic.
1268  while (Next != StringRef::npos) {
1269    Start = Next;
1270    Next = Name.find('.', Start + 1);
1271    Head = Name.slice(Start, Next);
1272
1273    Operands.push_back(ARMOperand::CreateToken(Head, NameLoc));
1274  }
1275
1276  // Enable the parsing of instructions containing coprocessor related
1277  // asm syntax, such as coprocessor names "p7, p15, ..." and coprocessor
1278  // registers "c1, c3, ..."
1279  // FIXME: we probably want AsmOperandClass and ParserMatchClass declarations
1280  // in the .td file rather than hacking the ASMParser for every symbolic
1281  // operand type.
1282  bool hasCoprocOp = (Head == "mcr"  || Head == "mcr2" ||
1283                      Head == "mcrr" || Head == "mcrr2" ||
1284                      Head == "mrc"  || Head == "mrc2" ||
1285                      Head == "mrrc" || Head == "mrrc2" ||
1286                      Head == "cdp"  || Head == "cdp2");
1287
1288  // Read the remaining operands.
1289  if (getLexer().isNot(AsmToken::EndOfStatement)) {
1290    // Read the first operand.
1291    if (ParseOperand(Operands, hasCoprocOp)) {
1292      Parser.EatToEndOfStatement();
1293      return true;
1294    }
1295
1296    while (getLexer().is(AsmToken::Comma)) {
1297      Parser.Lex();  // Eat the comma.
1298
1299      // Parse and remember the operand.
1300      if (ParseOperand(Operands, hasCoprocOp)) {
1301        Parser.EatToEndOfStatement();
1302        return true;
1303      }
1304    }
1305  }
1306
1307  if (getLexer().isNot(AsmToken::EndOfStatement)) {
1308    Parser.EatToEndOfStatement();
1309    return TokError("unexpected token in argument list");
1310  }
1311
1312  Parser.Lex(); // Consume the EndOfStatement
1313  return false;
1314}
1315
1316bool ARMAsmParser::
1317MatchAndEmitInstruction(SMLoc IDLoc,
1318                        SmallVectorImpl<MCParsedAsmOperand*> &Operands,
1319                        MCStreamer &Out) {
1320  MCInst Inst;
1321  unsigned ErrorInfo;
1322  MatchResultTy MatchResult, MatchResult2;
1323  MatchResult = MatchInstructionImpl(Operands, Inst, ErrorInfo);
1324  if (MatchResult != Match_Success) {
1325    // If we get a Match_InvalidOperand it might be some arithmetic instruction
1326    // that does not update the condition codes.  So try adding a CCOut operand
1327    // with a value of reg0.
1328    if (MatchResult == Match_InvalidOperand) {
1329      Operands.insert(Operands.begin() + 1,
1330                      ARMOperand::CreateCCOut(0,
1331                                  ((ARMOperand*)Operands[0])->getStartLoc()));
1332      MatchResult2 = MatchInstructionImpl(Operands, Inst, ErrorInfo);
1333      if (MatchResult2 == Match_Success)
1334        MatchResult = Match_Success;
1335      else {
1336        ARMOperand *CCOut = ((ARMOperand*)Operands[1]);
1337        Operands.erase(Operands.begin() + 1);
1338        delete CCOut;
1339      }
1340    }
1341    // If we get a Match_MnemonicFail it might be some arithmetic instruction
1342    // that updates the condition codes if it ends in 's'.  So see if the
1343    // mnemonic ends in 's' and if so try removing the 's' and adding a CCOut
1344    // operand with a value of CPSR.
1345    else if(MatchResult == Match_MnemonicFail) {
1346      // Get the instruction mnemonic, which is the first token.
1347      StringRef Mnemonic = ((ARMOperand*)Operands[0])->getToken();
1348      if (Mnemonic.substr(Mnemonic.size()-1) == "s") {
1349        // removed the 's' from the mnemonic for matching.
1350        StringRef MnemonicNoS = Mnemonic.slice(0, Mnemonic.size() - 1);
1351        SMLoc NameLoc = ((ARMOperand*)Operands[0])->getStartLoc();
1352        ARMOperand *OldMnemonic = ((ARMOperand*)Operands[0]);
1353        Operands.erase(Operands.begin());
1354        delete OldMnemonic;
1355        Operands.insert(Operands.begin(),
1356                        ARMOperand::CreateToken(MnemonicNoS, NameLoc));
1357        Operands.insert(Operands.begin() + 1,
1358                        ARMOperand::CreateCCOut(ARM::CPSR, NameLoc));
1359        MatchResult2 = MatchInstructionImpl(Operands, Inst, ErrorInfo);
1360        if (MatchResult2 == Match_Success)
1361          MatchResult = Match_Success;
1362        else {
1363          ARMOperand *OldMnemonic = ((ARMOperand*)Operands[0]);
1364          Operands.erase(Operands.begin());
1365          delete OldMnemonic;
1366          Operands.insert(Operands.begin(),
1367                          ARMOperand::CreateToken(Mnemonic, NameLoc));
1368          ARMOperand *CCOut = ((ARMOperand*)Operands[1]);
1369          Operands.erase(Operands.begin() + 1);
1370          delete CCOut;
1371        }
1372      }
1373    }
1374  }
1375  switch (MatchResult) {
1376  case Match_Success:
1377    Out.EmitInstruction(Inst);
1378    return false;
1379  case Match_MissingFeature:
1380    Error(IDLoc, "instruction requires a CPU feature not currently enabled");
1381    return true;
1382  case Match_InvalidOperand: {
1383    SMLoc ErrorLoc = IDLoc;
1384    if (ErrorInfo != ~0U) {
1385      if (ErrorInfo >= Operands.size())
1386        return Error(IDLoc, "too few operands for instruction");
1387
1388      ErrorLoc = ((ARMOperand*)Operands[ErrorInfo])->getStartLoc();
1389      if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
1390    }
1391
1392    return Error(ErrorLoc, "invalid operand for instruction");
1393  }
1394  case Match_MnemonicFail:
1395    return Error(IDLoc, "unrecognized instruction mnemonic");
1396  case Match_ConversionFail:
1397    return Error(IDLoc, "unable to convert operands to instruction");
1398  }
1399
1400  llvm_unreachable("Implement any new match types added!");
1401  return true;
1402}
1403
1404/// ParseDirective parses the arm specific directives
1405bool ARMAsmParser::ParseDirective(AsmToken DirectiveID) {
1406  StringRef IDVal = DirectiveID.getIdentifier();
1407  if (IDVal == ".word")
1408    return ParseDirectiveWord(4, DirectiveID.getLoc());
1409  else if (IDVal == ".thumb")
1410    return ParseDirectiveThumb(DirectiveID.getLoc());
1411  else if (IDVal == ".thumb_func")
1412    return ParseDirectiveThumbFunc(DirectiveID.getLoc());
1413  else if (IDVal == ".code")
1414    return ParseDirectiveCode(DirectiveID.getLoc());
1415  else if (IDVal == ".syntax")
1416    return ParseDirectiveSyntax(DirectiveID.getLoc());
1417  return true;
1418}
1419
1420/// ParseDirectiveWord
1421///  ::= .word [ expression (, expression)* ]
1422bool ARMAsmParser::ParseDirectiveWord(unsigned Size, SMLoc L) {
1423  if (getLexer().isNot(AsmToken::EndOfStatement)) {
1424    for (;;) {
1425      const MCExpr *Value;
1426      if (getParser().ParseExpression(Value))
1427        return true;
1428
1429      getParser().getStreamer().EmitValue(Value, Size, 0/*addrspace*/);
1430
1431      if (getLexer().is(AsmToken::EndOfStatement))
1432        break;
1433
1434      // FIXME: Improve diagnostic.
1435      if (getLexer().isNot(AsmToken::Comma))
1436        return Error(L, "unexpected token in directive");
1437      Parser.Lex();
1438    }
1439  }
1440
1441  Parser.Lex();
1442  return false;
1443}
1444
1445/// ParseDirectiveThumb
1446///  ::= .thumb
1447bool ARMAsmParser::ParseDirectiveThumb(SMLoc L) {
1448  if (getLexer().isNot(AsmToken::EndOfStatement))
1449    return Error(L, "unexpected token in directive");
1450  Parser.Lex();
1451
1452  // TODO: set thumb mode
1453  // TODO: tell the MC streamer the mode
1454  // getParser().getStreamer().Emit???();
1455  return false;
1456}
1457
1458/// ParseDirectiveThumbFunc
1459///  ::= .thumbfunc symbol_name
1460bool ARMAsmParser::ParseDirectiveThumbFunc(SMLoc L) {
1461  const AsmToken &Tok = Parser.getTok();
1462  if (Tok.isNot(AsmToken::Identifier) && Tok.isNot(AsmToken::String))
1463    return Error(L, "unexpected token in .thumb_func directive");
1464  StringRef Name = Tok.getString();
1465  Parser.Lex(); // Consume the identifier token.
1466  if (getLexer().isNot(AsmToken::EndOfStatement))
1467    return Error(L, "unexpected token in directive");
1468  Parser.Lex();
1469
1470  // Mark symbol as a thumb symbol.
1471  MCSymbol *Func = getParser().getContext().GetOrCreateSymbol(Name);
1472  getParser().getStreamer().EmitThumbFunc(Func);
1473  return false;
1474}
1475
1476/// ParseDirectiveSyntax
1477///  ::= .syntax unified | divided
1478bool ARMAsmParser::ParseDirectiveSyntax(SMLoc L) {
1479  const AsmToken &Tok = Parser.getTok();
1480  if (Tok.isNot(AsmToken::Identifier))
1481    return Error(L, "unexpected token in .syntax directive");
1482  StringRef Mode = Tok.getString();
1483  if (Mode == "unified" || Mode == "UNIFIED")
1484    Parser.Lex();
1485  else if (Mode == "divided" || Mode == "DIVIDED")
1486    return Error(L, "'.syntax divided' arm asssembly not supported");
1487  else
1488    return Error(L, "unrecognized syntax mode in .syntax directive");
1489
1490  if (getLexer().isNot(AsmToken::EndOfStatement))
1491    return Error(Parser.getTok().getLoc(), "unexpected token in directive");
1492  Parser.Lex();
1493
1494  // TODO tell the MC streamer the mode
1495  // getParser().getStreamer().Emit???();
1496  return false;
1497}
1498
1499/// ParseDirectiveCode
1500///  ::= .code 16 | 32
1501bool ARMAsmParser::ParseDirectiveCode(SMLoc L) {
1502  const AsmToken &Tok = Parser.getTok();
1503  if (Tok.isNot(AsmToken::Integer))
1504    return Error(L, "unexpected token in .code directive");
1505  int64_t Val = Parser.getTok().getIntVal();
1506  if (Val == 16)
1507    Parser.Lex();
1508  else if (Val == 32)
1509    Parser.Lex();
1510  else
1511    return Error(L, "invalid operand to .code directive");
1512
1513  if (getLexer().isNot(AsmToken::EndOfStatement))
1514    return Error(Parser.getTok().getLoc(), "unexpected token in directive");
1515  Parser.Lex();
1516
1517  // FIXME: We need to be able switch subtargets at this point so that
1518  // MatchInstructionImpl() will work when it gets the AvailableFeatures which
1519  // includes Feature_IsThumb or not to match the right instructions.  This is
1520  // blocked on the FIXME in llvm-mc.cpp when creating the TargetMachine.
1521  if (Val == 16){
1522    assert(TM.getSubtarget<ARMSubtarget>().isThumb() &&
1523	   "switching between arm/thumb not yet suppported via .code 16)");
1524    getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
1525  }
1526  else{
1527    assert(!TM.getSubtarget<ARMSubtarget>().isThumb() &&
1528           "switching between thumb/arm not yet suppported via .code 32)");
1529    getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
1530   }
1531
1532  return false;
1533}
1534
1535extern "C" void LLVMInitializeARMAsmLexer();
1536
1537/// Force static initialization.
1538extern "C" void LLVMInitializeARMAsmParser() {
1539  RegisterAsmParser<ARMAsmParser> X(TheARMTarget);
1540  RegisterAsmParser<ARMAsmParser> Y(TheThumbTarget);
1541  LLVMInitializeARMAsmLexer();
1542}
1543
1544#define GET_REGISTER_MATCHER
1545#define GET_MATCHER_IMPLEMENTATION
1546#include "ARMGenAsmMatcher.inc"
1547