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