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