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