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