Emit an error is asm parser parsed X86_64 only registers, e.g. %rax, %sil.
[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 "MCTargetDesc/ARMBaseInfo.h"
11 #include "MCTargetDesc/ARMAddressingModes.h"
12 #include "MCTargetDesc/ARMMCExpr.h"
13 #include "llvm/MC/MCParser/MCAsmLexer.h"
14 #include "llvm/MC/MCParser/MCAsmParser.h"
15 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
16 #include "llvm/MC/MCAsmInfo.h"
17 #include "llvm/MC/MCContext.h"
18 #include "llvm/MC/MCStreamer.h"
19 #include "llvm/MC/MCExpr.h"
20 #include "llvm/MC/MCInst.h"
21 #include "llvm/MC/MCRegisterInfo.h"
22 #include "llvm/MC/MCSubtargetInfo.h"
23 #include "llvm/MC/MCTargetAsmParser.h"
24 #include "llvm/Target/TargetRegistry.h"
25 #include "llvm/Support/SourceMgr.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/ADT/OwningPtr.h"
28 #include "llvm/ADT/STLExtras.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/ADT/StringExtras.h"
31 #include "llvm/ADT/StringSwitch.h"
32 #include "llvm/ADT/Twine.h"
33
34 using namespace llvm;
35
36 namespace {
37
38 class ARMOperand;
39
40 class ARMAsmParser : public MCTargetAsmParser {
41   MCSubtargetInfo &STI;
42   MCAsmParser &Parser;
43
44   MCAsmParser &getParser() const { return Parser; }
45   MCAsmLexer &getLexer() const { return Parser.getLexer(); }
46
47   void Warning(SMLoc L, const Twine &Msg) { Parser.Warning(L, Msg); }
48   bool Error(SMLoc L, const Twine &Msg) { return Parser.Error(L, Msg); }
49
50   int tryParseRegister();
51   bool tryParseRegisterWithWriteBack(SmallVectorImpl<MCParsedAsmOperand*> &);
52   int tryParseShiftRegister(SmallVectorImpl<MCParsedAsmOperand*> &);
53   bool parseRegisterList(SmallVectorImpl<MCParsedAsmOperand*> &);
54   bool parseMemory(SmallVectorImpl<MCParsedAsmOperand*> &,
55                    ARMII::AddrMode AddrMode);
56   bool parseOperand(SmallVectorImpl<MCParsedAsmOperand*> &, StringRef Mnemonic);
57   bool parsePrefix(ARMMCExpr::VariantKind &RefKind);
58   const MCExpr *applyPrefixToExpr(const MCExpr *E,
59                                   MCSymbolRefExpr::VariantKind Variant);
60
61
62   bool parseMemoryOffsetReg(bool &Negative,
63                             bool &OffsetRegShifted,
64                             enum ARM_AM::ShiftOpc &ShiftType,
65                             const MCExpr *&ShiftAmount,
66                             const MCExpr *&Offset,
67                             bool &OffsetIsReg,
68                             int &OffsetRegNum,
69                             SMLoc &E);
70   bool parseShift(enum ARM_AM::ShiftOpc &St,
71                   const MCExpr *&ShiftAmount, SMLoc &E);
72   bool parseDirectiveWord(unsigned Size, SMLoc L);
73   bool parseDirectiveThumb(SMLoc L);
74   bool parseDirectiveThumbFunc(SMLoc L);
75   bool parseDirectiveCode(SMLoc L);
76   bool parseDirectiveSyntax(SMLoc L);
77
78   StringRef splitMnemonic(StringRef Mnemonic, unsigned &PredicationCode,
79                           bool &CarrySetting, unsigned &ProcessorIMod);
80   void getMnemonicAcceptInfo(StringRef Mnemonic, bool &CanAcceptCarrySet,
81                              bool &CanAcceptPredicationCode);
82
83   bool isThumb() const {
84     // FIXME: Can tablegen auto-generate this?
85     return (STI.getFeatureBits() & ARM::ModeThumb) != 0;
86   }
87   bool isThumbOne() const {
88     return isThumb() && (STI.getFeatureBits() & ARM::FeatureThumb2) == 0;
89   }
90   void SwitchMode() {
91     unsigned FB = ComputeAvailableFeatures(STI.ToggleFeature(ARM::ModeThumb));
92     setAvailableFeatures(FB);
93   }
94
95   /// @name Auto-generated Match Functions
96   /// {
97
98 #define GET_ASSEMBLER_HEADER
99 #include "ARMGenAsmMatcher.inc"
100
101   /// }
102
103   OperandMatchResultTy parseCoprocNumOperand(
104     SmallVectorImpl<MCParsedAsmOperand*>&);
105   OperandMatchResultTy parseCoprocRegOperand(
106     SmallVectorImpl<MCParsedAsmOperand*>&);
107   OperandMatchResultTy parseMemBarrierOptOperand(
108     SmallVectorImpl<MCParsedAsmOperand*>&);
109   OperandMatchResultTy parseProcIFlagsOperand(
110     SmallVectorImpl<MCParsedAsmOperand*>&);
111   OperandMatchResultTy parseMSRMaskOperand(
112     SmallVectorImpl<MCParsedAsmOperand*>&);
113   OperandMatchResultTy parseMemMode2Operand(
114     SmallVectorImpl<MCParsedAsmOperand*>&);
115   OperandMatchResultTy parseMemMode3Operand(
116     SmallVectorImpl<MCParsedAsmOperand*>&);
117   OperandMatchResultTy parsePKHImm(SmallVectorImpl<MCParsedAsmOperand*> &O,
118                                    StringRef Op, int Low, int High);
119   OperandMatchResultTy parsePKHLSLImm(SmallVectorImpl<MCParsedAsmOperand*> &O) {
120     return parsePKHImm(O, "lsl", 0, 31);
121   }
122   OperandMatchResultTy parsePKHASRImm(SmallVectorImpl<MCParsedAsmOperand*> &O) {
123     return parsePKHImm(O, "asr", 1, 32);
124   }
125   OperandMatchResultTy parseSetEndImm(SmallVectorImpl<MCParsedAsmOperand*>&);
126   OperandMatchResultTy parseShifterImm(SmallVectorImpl<MCParsedAsmOperand*>&);
127   OperandMatchResultTy parseRotImm(SmallVectorImpl<MCParsedAsmOperand*>&);
128
129   // Asm Match Converter Methods
130   bool cvtLdWriteBackRegAddrMode2(MCInst &Inst, unsigned Opcode,
131                                   const SmallVectorImpl<MCParsedAsmOperand*> &);
132   bool cvtStWriteBackRegAddrMode2(MCInst &Inst, unsigned Opcode,
133                                   const SmallVectorImpl<MCParsedAsmOperand*> &);
134   bool cvtLdWriteBackRegAddrMode3(MCInst &Inst, unsigned Opcode,
135                                   const SmallVectorImpl<MCParsedAsmOperand*> &);
136   bool cvtStWriteBackRegAddrMode3(MCInst &Inst, unsigned Opcode,
137                                   const SmallVectorImpl<MCParsedAsmOperand*> &);
138
139
140   bool validateInstruction(MCInst &Inst,
141                            const SmallVectorImpl<MCParsedAsmOperand*> &Ops);
142
143 public:
144   ARMAsmParser(MCSubtargetInfo &_STI, MCAsmParser &_Parser)
145     : MCTargetAsmParser(), STI(_STI), Parser(_Parser) {
146     MCAsmParserExtension::Initialize(_Parser);
147
148     // Initialize the set of available features.
149     setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
150   }
151
152   // Implementation of the MCTargetAsmParser interface:
153   bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc);
154   bool ParseInstruction(StringRef Name, SMLoc NameLoc,
155                         SmallVectorImpl<MCParsedAsmOperand*> &Operands);
156   bool ParseDirective(AsmToken DirectiveID);
157
158   bool MatchAndEmitInstruction(SMLoc IDLoc,
159                                SmallVectorImpl<MCParsedAsmOperand*> &Operands,
160                                MCStreamer &Out);
161 };
162 } // end anonymous namespace
163
164 namespace {
165
166 /// ARMOperand - Instances of this class represent a parsed ARM machine
167 /// instruction.
168 class ARMOperand : public MCParsedAsmOperand {
169   enum KindTy {
170     CondCode,
171     CCOut,
172     CoprocNum,
173     CoprocReg,
174     Immediate,
175     MemBarrierOpt,
176     Memory,
177     MSRMask,
178     ProcIFlags,
179     Register,
180     RegisterList,
181     DPRRegisterList,
182     SPRRegisterList,
183     ShiftedRegister,
184     ShiftedImmediate,
185     ShifterImmediate,
186     RotateImmediate,
187     Token
188   } Kind;
189
190   SMLoc StartLoc, EndLoc;
191   SmallVector<unsigned, 8> Registers;
192
193   union {
194     struct {
195       ARMCC::CondCodes Val;
196     } CC;
197
198     struct {
199       ARM_MB::MemBOpt Val;
200     } MBOpt;
201
202     struct {
203       unsigned Val;
204     } Cop;
205
206     struct {
207       ARM_PROC::IFlags Val;
208     } IFlags;
209
210     struct {
211       unsigned Val;
212     } MMask;
213
214     struct {
215       const char *Data;
216       unsigned Length;
217     } Tok;
218
219     struct {
220       unsigned RegNum;
221     } Reg;
222
223     struct {
224       const MCExpr *Val;
225     } Imm;
226
227     /// Combined record for all forms of ARM address expressions.
228     struct {
229       ARMII::AddrMode AddrMode;
230       unsigned BaseRegNum;
231       union {
232         unsigned RegNum;     ///< Offset register num, when OffsetIsReg.
233         const MCExpr *Value; ///< Offset value, when !OffsetIsReg.
234       } Offset;
235       const MCExpr *ShiftAmount;     // used when OffsetRegShifted is true
236       enum ARM_AM::ShiftOpc ShiftType; // used when OffsetRegShifted is true
237       unsigned OffsetRegShifted : 1; // only used when OffsetIsReg is true
238       unsigned Preindexed       : 1;
239       unsigned Postindexed      : 1;
240       unsigned OffsetIsReg      : 1;
241       unsigned Negative         : 1; // only used when OffsetIsReg is true
242       unsigned Writeback        : 1;
243     } Mem;
244
245     struct {
246       bool isASR;
247       unsigned Imm;
248     } ShifterImm;
249     struct {
250       ARM_AM::ShiftOpc ShiftTy;
251       unsigned SrcReg;
252       unsigned ShiftReg;
253       unsigned ShiftImm;
254     } RegShiftedReg;
255     struct {
256       ARM_AM::ShiftOpc ShiftTy;
257       unsigned SrcReg;
258       unsigned ShiftImm;
259     } RegShiftedImm;
260     struct {
261       unsigned Imm;
262     } RotImm;
263   };
264
265   ARMOperand(KindTy K) : MCParsedAsmOperand(), Kind(K) {}
266 public:
267   ARMOperand(const ARMOperand &o) : MCParsedAsmOperand() {
268     Kind = o.Kind;
269     StartLoc = o.StartLoc;
270     EndLoc = o.EndLoc;
271     switch (Kind) {
272     case CondCode:
273       CC = o.CC;
274       break;
275     case Token:
276       Tok = o.Tok;
277       break;
278     case CCOut:
279     case Register:
280       Reg = o.Reg;
281       break;
282     case RegisterList:
283     case DPRRegisterList:
284     case SPRRegisterList:
285       Registers = o.Registers;
286       break;
287     case CoprocNum:
288     case CoprocReg:
289       Cop = o.Cop;
290       break;
291     case Immediate:
292       Imm = o.Imm;
293       break;
294     case MemBarrierOpt:
295       MBOpt = o.MBOpt;
296       break;
297     case Memory:
298       Mem = o.Mem;
299       break;
300     case MSRMask:
301       MMask = o.MMask;
302       break;
303     case ProcIFlags:
304       IFlags = o.IFlags;
305       break;
306     case ShifterImmediate:
307       ShifterImm = o.ShifterImm;
308       break;
309     case ShiftedRegister:
310       RegShiftedReg = o.RegShiftedReg;
311       break;
312     case ShiftedImmediate:
313       RegShiftedImm = o.RegShiftedImm;
314       break;
315     case RotateImmediate:
316       RotImm = o.RotImm;
317       break;
318     }
319   }
320
321   /// getStartLoc - Get the location of the first token of this operand.
322   SMLoc getStartLoc() const { return StartLoc; }
323   /// getEndLoc - Get the location of the last token of this operand.
324   SMLoc getEndLoc() const { return EndLoc; }
325
326   ARMCC::CondCodes getCondCode() const {
327     assert(Kind == CondCode && "Invalid access!");
328     return CC.Val;
329   }
330
331   unsigned getCoproc() const {
332     assert((Kind == CoprocNum || Kind == CoprocReg) && "Invalid access!");
333     return Cop.Val;
334   }
335
336   StringRef getToken() const {
337     assert(Kind == Token && "Invalid access!");
338     return StringRef(Tok.Data, Tok.Length);
339   }
340
341   unsigned getReg() const {
342     assert((Kind == Register || Kind == CCOut) && "Invalid access!");
343     return Reg.RegNum;
344   }
345
346   const SmallVectorImpl<unsigned> &getRegList() const {
347     assert((Kind == RegisterList || Kind == DPRRegisterList ||
348             Kind == SPRRegisterList) && "Invalid access!");
349     return Registers;
350   }
351
352   const MCExpr *getImm() const {
353     assert(Kind == Immediate && "Invalid access!");
354     return Imm.Val;
355   }
356
357   ARM_MB::MemBOpt getMemBarrierOpt() const {
358     assert(Kind == MemBarrierOpt && "Invalid access!");
359     return MBOpt.Val;
360   }
361
362   ARM_PROC::IFlags getProcIFlags() const {
363     assert(Kind == ProcIFlags && "Invalid access!");
364     return IFlags.Val;
365   }
366
367   unsigned getMSRMask() const {
368     assert(Kind == MSRMask && "Invalid access!");
369     return MMask.Val;
370   }
371
372   /// @name Memory Operand Accessors
373   /// @{
374   ARMII::AddrMode getMemAddrMode() const {
375     return Mem.AddrMode;
376   }
377   unsigned getMemBaseRegNum() const {
378     return Mem.BaseRegNum;
379   }
380   unsigned getMemOffsetRegNum() const {
381     assert(Mem.OffsetIsReg && "Invalid access!");
382     return Mem.Offset.RegNum;
383   }
384   const MCExpr *getMemOffset() const {
385     assert(!Mem.OffsetIsReg && "Invalid access!");
386     return Mem.Offset.Value;
387   }
388   unsigned getMemOffsetRegShifted() const {
389     assert(Mem.OffsetIsReg && "Invalid access!");
390     return Mem.OffsetRegShifted;
391   }
392   const MCExpr *getMemShiftAmount() const {
393     assert(Mem.OffsetIsReg && Mem.OffsetRegShifted && "Invalid access!");
394     return Mem.ShiftAmount;
395   }
396   enum ARM_AM::ShiftOpc getMemShiftType() const {
397     assert(Mem.OffsetIsReg && Mem.OffsetRegShifted && "Invalid access!");
398     return Mem.ShiftType;
399   }
400   bool getMemPreindexed() const { return Mem.Preindexed; }
401   bool getMemPostindexed() const { return Mem.Postindexed; }
402   bool getMemOffsetIsReg() const { return Mem.OffsetIsReg; }
403   bool getMemNegative() const { return Mem.Negative; }
404   bool getMemWriteback() const { return Mem.Writeback; }
405
406   /// @}
407
408   bool isCoprocNum() const { return Kind == CoprocNum; }
409   bool isCoprocReg() const { return Kind == CoprocReg; }
410   bool isCondCode() const { return Kind == CondCode; }
411   bool isCCOut() const { return Kind == CCOut; }
412   bool isImm() const { return Kind == Immediate; }
413   bool isImm0_255() const {
414     if (Kind != Immediate)
415       return false;
416     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
417     if (!CE) return false;
418     int64_t Value = CE->getValue();
419     return Value >= 0 && Value < 256;
420   }
421   bool isImm0_7() const {
422     if (Kind != Immediate)
423       return false;
424     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
425     if (!CE) return false;
426     int64_t Value = CE->getValue();
427     return Value >= 0 && Value < 8;
428   }
429   bool isImm0_15() const {
430     if (Kind != Immediate)
431       return false;
432     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
433     if (!CE) return false;
434     int64_t Value = CE->getValue();
435     return Value >= 0 && Value < 16;
436   }
437   bool isImm0_31() const {
438     if (Kind != Immediate)
439       return false;
440     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
441     if (!CE) return false;
442     int64_t Value = CE->getValue();
443     return Value >= 0 && Value < 32;
444   }
445   bool isImm1_16() const {
446     if (Kind != Immediate)
447       return false;
448     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
449     if (!CE) return false;
450     int64_t Value = CE->getValue();
451     return Value > 0 && Value < 17;
452   }
453   bool isImm1_32() const {
454     if (Kind != Immediate)
455       return false;
456     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
457     if (!CE) return false;
458     int64_t Value = CE->getValue();
459     return Value > 0 && Value < 33;
460   }
461   bool isImm0_65535() const {
462     if (Kind != Immediate)
463       return false;
464     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
465     if (!CE) return false;
466     int64_t Value = CE->getValue();
467     return Value >= 0 && Value < 65536;
468   }
469   bool isImm0_65535Expr() const {
470     if (Kind != Immediate)
471       return false;
472     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
473     // If it's not a constant expression, it'll generate a fixup and be
474     // handled later.
475     if (!CE) return true;
476     int64_t Value = CE->getValue();
477     return Value >= 0 && Value < 65536;
478   }
479   bool isImm24bit() const {
480     if (Kind != Immediate)
481       return false;
482     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
483     if (!CE) return false;
484     int64_t Value = CE->getValue();
485     return Value >= 0 && Value <= 0xffffff;
486   }
487   bool isPKHLSLImm() const {
488     if (Kind != Immediate)
489       return false;
490     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
491     if (!CE) return false;
492     int64_t Value = CE->getValue();
493     return Value >= 0 && Value < 32;
494   }
495   bool isPKHASRImm() const {
496     if (Kind != Immediate)
497       return false;
498     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
499     if (!CE) return false;
500     int64_t Value = CE->getValue();
501     return Value > 0 && Value <= 32;
502   }
503   bool isARMSOImm() const {
504     if (Kind != Immediate)
505       return false;
506     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
507     if (!CE) return false;
508     int64_t Value = CE->getValue();
509     return ARM_AM::getSOImmVal(Value) != -1;
510   }
511   bool isT2SOImm() const {
512     if (Kind != Immediate)
513       return false;
514     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
515     if (!CE) return false;
516     int64_t Value = CE->getValue();
517     return ARM_AM::getT2SOImmVal(Value) != -1;
518   }
519   bool isSetEndImm() const {
520     if (Kind != Immediate)
521       return false;
522     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
523     if (!CE) return false;
524     int64_t Value = CE->getValue();
525     return Value == 1 || Value == 0;
526   }
527   bool isReg() const { return Kind == Register; }
528   bool isRegList() const { return Kind == RegisterList; }
529   bool isDPRRegList() const { return Kind == DPRRegisterList; }
530   bool isSPRRegList() const { return Kind == SPRRegisterList; }
531   bool isToken() const { return Kind == Token; }
532   bool isMemBarrierOpt() const { return Kind == MemBarrierOpt; }
533   bool isMemory() const { return Kind == Memory; }
534   bool isShifterImm() const { return Kind == ShifterImmediate; }
535   bool isRegShiftedReg() const { return Kind == ShiftedRegister; }
536   bool isRegShiftedImm() const { return Kind == ShiftedImmediate; }
537   bool isRotImm() const { return Kind == RotateImmediate; }
538   bool isMemMode2() const {
539     if (getMemAddrMode() != ARMII::AddrMode2)
540       return false;
541
542     if (getMemOffsetIsReg())
543       return true;
544
545     if (getMemNegative() &&
546         !(getMemPostindexed() || getMemPreindexed()))
547       return false;
548
549     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemOffset());
550     if (!CE) return false;
551     int64_t Value = CE->getValue();
552
553     // The offset must be in the range 0-4095 (imm12).
554     if (Value > 4095 || Value < -4095)
555       return false;
556
557     return true;
558   }
559   bool isMemMode3() const {
560     if (getMemAddrMode() != ARMII::AddrMode3)
561       return false;
562
563     if (getMemOffsetIsReg()) {
564       if (getMemOffsetRegShifted())
565         return false; // No shift with offset reg allowed
566       return true;
567     }
568
569     if (getMemNegative() &&
570         !(getMemPostindexed() || getMemPreindexed()))
571       return false;
572
573     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemOffset());
574     if (!CE) return false;
575     int64_t Value = CE->getValue();
576
577     // The offset must be in the range 0-255 (imm8).
578     if (Value > 255 || Value < -255)
579       return false;
580
581     return true;
582   }
583   bool isMemMode5() const {
584     if (!isMemory() || getMemOffsetIsReg() || getMemWriteback() ||
585         getMemNegative())
586       return false;
587
588     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemOffset());
589     if (!CE) return false;
590
591     // The offset must be a multiple of 4 in the range 0-1020.
592     int64_t Value = CE->getValue();
593     return ((Value & 0x3) == 0 && Value <= 1020 && Value >= -1020);
594   }
595   bool isMemMode7() const {
596     if (!isMemory() ||
597         getMemPreindexed() ||
598         getMemPostindexed() ||
599         getMemOffsetIsReg() ||
600         getMemNegative() ||
601         getMemWriteback())
602       return false;
603
604     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemOffset());
605     if (!CE) return false;
606
607     if (CE->getValue())
608       return false;
609
610     return true;
611   }
612   bool isMemModeRegThumb() const {
613     if (!isMemory() || !getMemOffsetIsReg() || getMemWriteback())
614       return false;
615     return true;
616   }
617   bool isMemModeImmThumb() const {
618     if (!isMemory() || getMemOffsetIsReg() || getMemWriteback())
619       return false;
620
621     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemOffset());
622     if (!CE) return false;
623
624     // The offset must be a multiple of 4 in the range 0-124.
625     uint64_t Value = CE->getValue();
626     return ((Value & 0x3) == 0 && Value <= 124);
627   }
628   bool isMSRMask() const { return Kind == MSRMask; }
629   bool isProcIFlags() const { return Kind == ProcIFlags; }
630
631   void addExpr(MCInst &Inst, const MCExpr *Expr) const {
632     // Add as immediates when possible.  Null MCExpr = 0.
633     if (Expr == 0)
634       Inst.addOperand(MCOperand::CreateImm(0));
635     else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
636       Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
637     else
638       Inst.addOperand(MCOperand::CreateExpr(Expr));
639   }
640
641   void addCondCodeOperands(MCInst &Inst, unsigned N) const {
642     assert(N == 2 && "Invalid number of operands!");
643     Inst.addOperand(MCOperand::CreateImm(unsigned(getCondCode())));
644     unsigned RegNum = getCondCode() == ARMCC::AL ? 0: ARM::CPSR;
645     Inst.addOperand(MCOperand::CreateReg(RegNum));
646   }
647
648   void addCoprocNumOperands(MCInst &Inst, unsigned N) const {
649     assert(N == 1 && "Invalid number of operands!");
650     Inst.addOperand(MCOperand::CreateImm(getCoproc()));
651   }
652
653   void addCoprocRegOperands(MCInst &Inst, unsigned N) const {
654     assert(N == 1 && "Invalid number of operands!");
655     Inst.addOperand(MCOperand::CreateImm(getCoproc()));
656   }
657
658   void addCCOutOperands(MCInst &Inst, unsigned N) const {
659     assert(N == 1 && "Invalid number of operands!");
660     Inst.addOperand(MCOperand::CreateReg(getReg()));
661   }
662
663   void addRegOperands(MCInst &Inst, unsigned N) const {
664     assert(N == 1 && "Invalid number of operands!");
665     Inst.addOperand(MCOperand::CreateReg(getReg()));
666   }
667
668   void addRegShiftedRegOperands(MCInst &Inst, unsigned N) const {
669     assert(N == 3 && "Invalid number of operands!");
670     assert(isRegShiftedReg() && "addRegShiftedRegOperands() on non RegShiftedReg!");
671     Inst.addOperand(MCOperand::CreateReg(RegShiftedReg.SrcReg));
672     Inst.addOperand(MCOperand::CreateReg(RegShiftedReg.ShiftReg));
673     Inst.addOperand(MCOperand::CreateImm(
674       ARM_AM::getSORegOpc(RegShiftedReg.ShiftTy, RegShiftedReg.ShiftImm)));
675   }
676
677   void addRegShiftedImmOperands(MCInst &Inst, unsigned N) const {
678     assert(N == 2 && "Invalid number of operands!");
679     assert(isRegShiftedImm() && "addRegShiftedImmOperands() on non RegShiftedImm!");
680     Inst.addOperand(MCOperand::CreateReg(RegShiftedImm.SrcReg));
681     Inst.addOperand(MCOperand::CreateImm(
682       ARM_AM::getSORegOpc(RegShiftedImm.ShiftTy, RegShiftedImm.ShiftImm)));
683   }
684
685
686   void addShifterImmOperands(MCInst &Inst, unsigned N) const {
687     assert(N == 1 && "Invalid number of operands!");
688     Inst.addOperand(MCOperand::CreateImm((ShifterImm.isASR << 5) |
689                                          ShifterImm.Imm));
690   }
691
692   void addRegListOperands(MCInst &Inst, unsigned N) const {
693     assert(N == 1 && "Invalid number of operands!");
694     const SmallVectorImpl<unsigned> &RegList = getRegList();
695     for (SmallVectorImpl<unsigned>::const_iterator
696            I = RegList.begin(), E = RegList.end(); I != E; ++I)
697       Inst.addOperand(MCOperand::CreateReg(*I));
698   }
699
700   void addDPRRegListOperands(MCInst &Inst, unsigned N) const {
701     addRegListOperands(Inst, N);
702   }
703
704   void addSPRRegListOperands(MCInst &Inst, unsigned N) const {
705     addRegListOperands(Inst, N);
706   }
707
708   void addRotImmOperands(MCInst &Inst, unsigned N) const {
709     assert(N == 1 && "Invalid number of operands!");
710     // Encoded as val>>3. The printer handles display as 8, 16, 24.
711     Inst.addOperand(MCOperand::CreateImm(RotImm.Imm >> 3));
712   }
713
714   void addImmOperands(MCInst &Inst, unsigned N) const {
715     assert(N == 1 && "Invalid number of operands!");
716     addExpr(Inst, getImm());
717   }
718
719   void addImm0_255Operands(MCInst &Inst, unsigned N) const {
720     assert(N == 1 && "Invalid number of operands!");
721     addExpr(Inst, getImm());
722   }
723
724   void addImm0_7Operands(MCInst &Inst, unsigned N) const {
725     assert(N == 1 && "Invalid number of operands!");
726     addExpr(Inst, getImm());
727   }
728
729   void addImm0_15Operands(MCInst &Inst, unsigned N) const {
730     assert(N == 1 && "Invalid number of operands!");
731     addExpr(Inst, getImm());
732   }
733
734   void addImm0_31Operands(MCInst &Inst, unsigned N) const {
735     assert(N == 1 && "Invalid number of operands!");
736     addExpr(Inst, getImm());
737   }
738
739   void addImm1_16Operands(MCInst &Inst, unsigned N) const {
740     assert(N == 1 && "Invalid number of operands!");
741     // The constant encodes as the immediate-1, and we store in the instruction
742     // the bits as encoded, so subtract off one here.
743     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
744     Inst.addOperand(MCOperand::CreateImm(CE->getValue() - 1));
745   }
746
747   void addImm1_32Operands(MCInst &Inst, unsigned N) const {
748     assert(N == 1 && "Invalid number of operands!");
749     // The constant encodes as the immediate-1, and we store in the instruction
750     // the bits as encoded, so subtract off one here.
751     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
752     Inst.addOperand(MCOperand::CreateImm(CE->getValue() - 1));
753   }
754
755   void addImm0_65535Operands(MCInst &Inst, unsigned N) const {
756     assert(N == 1 && "Invalid number of operands!");
757     addExpr(Inst, getImm());
758   }
759
760   void addImm0_65535ExprOperands(MCInst &Inst, unsigned N) const {
761     assert(N == 1 && "Invalid number of operands!");
762     addExpr(Inst, getImm());
763   }
764
765   void addImm24bitOperands(MCInst &Inst, unsigned N) const {
766     assert(N == 1 && "Invalid number of operands!");
767     addExpr(Inst, getImm());
768   }
769
770   void addPKHLSLImmOperands(MCInst &Inst, unsigned N) const {
771     assert(N == 1 && "Invalid number of operands!");
772     addExpr(Inst, getImm());
773   }
774
775   void addPKHASRImmOperands(MCInst &Inst, unsigned N) const {
776     assert(N == 1 && "Invalid number of operands!");
777     // An ASR value of 32 encodes as 0, so that's how we want to add it to
778     // the instruction as well.
779     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
780     int Val = CE->getValue();
781     Inst.addOperand(MCOperand::CreateImm(Val == 32 ? 0 : Val));
782   }
783
784   void addARMSOImmOperands(MCInst &Inst, unsigned N) const {
785     assert(N == 1 && "Invalid number of operands!");
786     addExpr(Inst, getImm());
787   }
788
789   void addT2SOImmOperands(MCInst &Inst, unsigned N) const {
790     assert(N == 1 && "Invalid number of operands!");
791     addExpr(Inst, getImm());
792   }
793
794   void addSetEndImmOperands(MCInst &Inst, unsigned N) const {
795     assert(N == 1 && "Invalid number of operands!");
796     addExpr(Inst, getImm());
797   }
798
799   void addMemBarrierOptOperands(MCInst &Inst, unsigned N) const {
800     assert(N == 1 && "Invalid number of operands!");
801     Inst.addOperand(MCOperand::CreateImm(unsigned(getMemBarrierOpt())));
802   }
803
804   void addMemMode7Operands(MCInst &Inst, unsigned N) const {
805     assert(N == 1 && isMemMode7() && "Invalid number of operands!");
806     Inst.addOperand(MCOperand::CreateReg(getMemBaseRegNum()));
807
808     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemOffset());
809     (void)CE;
810     assert((CE || CE->getValue() == 0) &&
811            "No offset operand support in mode 7");
812   }
813
814   void addMemMode2Operands(MCInst &Inst, unsigned N) const {
815     assert(isMemMode2() && "Invalid mode or number of operands!");
816     Inst.addOperand(MCOperand::CreateReg(getMemBaseRegNum()));
817     unsigned IdxMode = (getMemPreindexed() | getMemPostindexed() << 1);
818
819     if (getMemOffsetIsReg()) {
820       Inst.addOperand(MCOperand::CreateReg(getMemOffsetRegNum()));
821
822       ARM_AM::AddrOpc AMOpc = getMemNegative() ? ARM_AM::sub : ARM_AM::add;
823       ARM_AM::ShiftOpc ShOpc = ARM_AM::no_shift;
824       int64_t ShiftAmount = 0;
825
826       if (getMemOffsetRegShifted()) {
827         ShOpc = getMemShiftType();
828         const MCConstantExpr *CE =
829                    dyn_cast<MCConstantExpr>(getMemShiftAmount());
830         ShiftAmount = CE->getValue();
831       }
832
833       Inst.addOperand(MCOperand::CreateImm(ARM_AM::getAM2Opc(AMOpc, ShiftAmount,
834                                            ShOpc, IdxMode)));
835       return;
836     }
837
838     // Create a operand placeholder to always yield the same number of operands.
839     Inst.addOperand(MCOperand::CreateReg(0));
840
841     // FIXME: #-0 is encoded differently than #0. Does the parser preserve
842     // the difference?
843     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemOffset());
844     assert(CE && "Non-constant mode 2 offset operand!");
845     int64_t Offset = CE->getValue();
846
847     if (Offset >= 0)
848       Inst.addOperand(MCOperand::CreateImm(ARM_AM::getAM2Opc(ARM_AM::add,
849                                            Offset, ARM_AM::no_shift, IdxMode)));
850     else
851       Inst.addOperand(MCOperand::CreateImm(ARM_AM::getAM2Opc(ARM_AM::sub,
852                                           -Offset, ARM_AM::no_shift, IdxMode)));
853   }
854
855   void addMemMode3Operands(MCInst &Inst, unsigned N) const {
856     assert(isMemMode3() && "Invalid mode or number of operands!");
857     Inst.addOperand(MCOperand::CreateReg(getMemBaseRegNum()));
858     unsigned IdxMode = (getMemPreindexed() | getMemPostindexed() << 1);
859
860     if (getMemOffsetIsReg()) {
861       Inst.addOperand(MCOperand::CreateReg(getMemOffsetRegNum()));
862
863       ARM_AM::AddrOpc AMOpc = getMemNegative() ? ARM_AM::sub : ARM_AM::add;
864       Inst.addOperand(MCOperand::CreateImm(ARM_AM::getAM3Opc(AMOpc, 0,
865                                                              IdxMode)));
866       return;
867     }
868
869     // Create a operand placeholder to always yield the same number of operands.
870     Inst.addOperand(MCOperand::CreateReg(0));
871
872     // FIXME: #-0 is encoded differently than #0. Does the parser preserve
873     // the difference?
874     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemOffset());
875     assert(CE && "Non-constant mode 3 offset operand!");
876     int64_t Offset = CE->getValue();
877
878     if (Offset >= 0)
879       Inst.addOperand(MCOperand::CreateImm(ARM_AM::getAM3Opc(ARM_AM::add,
880                                            Offset, IdxMode)));
881     else
882       Inst.addOperand(MCOperand::CreateImm(ARM_AM::getAM3Opc(ARM_AM::sub,
883                                            -Offset, IdxMode)));
884   }
885
886   void addMemMode5Operands(MCInst &Inst, unsigned N) const {
887     assert(N == 2 && isMemMode5() && "Invalid number of operands!");
888
889     Inst.addOperand(MCOperand::CreateReg(getMemBaseRegNum()));
890     assert(!getMemOffsetIsReg() && "Invalid mode 5 operand");
891
892     // FIXME: #-0 is encoded differently than #0. Does the parser preserve
893     // the difference?
894     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemOffset());
895     assert(CE && "Non-constant mode 5 offset operand!");
896
897     // The MCInst offset operand doesn't include the low two bits (like
898     // the instruction encoding).
899     int64_t Offset = CE->getValue() / 4;
900     if (Offset >= 0)
901       Inst.addOperand(MCOperand::CreateImm(ARM_AM::getAM5Opc(ARM_AM::add,
902                                                              Offset)));
903     else
904       Inst.addOperand(MCOperand::CreateImm(ARM_AM::getAM5Opc(ARM_AM::sub,
905                                                              -Offset)));
906   }
907
908   void addMemModeRegThumbOperands(MCInst &Inst, unsigned N) const {
909     assert(N == 2 && isMemModeRegThumb() && "Invalid number of operands!");
910     Inst.addOperand(MCOperand::CreateReg(getMemBaseRegNum()));
911     Inst.addOperand(MCOperand::CreateReg(getMemOffsetRegNum()));
912   }
913
914   void addMemModeImmThumbOperands(MCInst &Inst, unsigned N) const {
915     assert(N == 2 && isMemModeImmThumb() && "Invalid number of operands!");
916     Inst.addOperand(MCOperand::CreateReg(getMemBaseRegNum()));
917     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getMemOffset());
918     assert(CE && "Non-constant mode offset operand!");
919     Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
920   }
921
922   void addMSRMaskOperands(MCInst &Inst, unsigned N) const {
923     assert(N == 1 && "Invalid number of operands!");
924     Inst.addOperand(MCOperand::CreateImm(unsigned(getMSRMask())));
925   }
926
927   void addProcIFlagsOperands(MCInst &Inst, unsigned N) const {
928     assert(N == 1 && "Invalid number of operands!");
929     Inst.addOperand(MCOperand::CreateImm(unsigned(getProcIFlags())));
930   }
931
932   virtual void print(raw_ostream &OS) const;
933
934   static ARMOperand *CreateCondCode(ARMCC::CondCodes CC, SMLoc S) {
935     ARMOperand *Op = new ARMOperand(CondCode);
936     Op->CC.Val = CC;
937     Op->StartLoc = S;
938     Op->EndLoc = S;
939     return Op;
940   }
941
942   static ARMOperand *CreateCoprocNum(unsigned CopVal, SMLoc S) {
943     ARMOperand *Op = new ARMOperand(CoprocNum);
944     Op->Cop.Val = CopVal;
945     Op->StartLoc = S;
946     Op->EndLoc = S;
947     return Op;
948   }
949
950   static ARMOperand *CreateCoprocReg(unsigned CopVal, SMLoc S) {
951     ARMOperand *Op = new ARMOperand(CoprocReg);
952     Op->Cop.Val = CopVal;
953     Op->StartLoc = S;
954     Op->EndLoc = S;
955     return Op;
956   }
957
958   static ARMOperand *CreateCCOut(unsigned RegNum, SMLoc S) {
959     ARMOperand *Op = new ARMOperand(CCOut);
960     Op->Reg.RegNum = RegNum;
961     Op->StartLoc = S;
962     Op->EndLoc = S;
963     return Op;
964   }
965
966   static ARMOperand *CreateToken(StringRef Str, SMLoc S) {
967     ARMOperand *Op = new ARMOperand(Token);
968     Op->Tok.Data = Str.data();
969     Op->Tok.Length = Str.size();
970     Op->StartLoc = S;
971     Op->EndLoc = S;
972     return Op;
973   }
974
975   static ARMOperand *CreateReg(unsigned RegNum, SMLoc S, SMLoc E) {
976     ARMOperand *Op = new ARMOperand(Register);
977     Op->Reg.RegNum = RegNum;
978     Op->StartLoc = S;
979     Op->EndLoc = E;
980     return Op;
981   }
982
983   static ARMOperand *CreateShiftedRegister(ARM_AM::ShiftOpc ShTy,
984                                            unsigned SrcReg,
985                                            unsigned ShiftReg,
986                                            unsigned ShiftImm,
987                                            SMLoc S, SMLoc E) {
988     ARMOperand *Op = new ARMOperand(ShiftedRegister);
989     Op->RegShiftedReg.ShiftTy = ShTy;
990     Op->RegShiftedReg.SrcReg = SrcReg;
991     Op->RegShiftedReg.ShiftReg = ShiftReg;
992     Op->RegShiftedReg.ShiftImm = ShiftImm;
993     Op->StartLoc = S;
994     Op->EndLoc = E;
995     return Op;
996   }
997
998   static ARMOperand *CreateShiftedImmediate(ARM_AM::ShiftOpc ShTy,
999                                             unsigned SrcReg,
1000                                             unsigned ShiftImm,
1001                                             SMLoc S, SMLoc E) {
1002     ARMOperand *Op = new ARMOperand(ShiftedImmediate);
1003     Op->RegShiftedImm.ShiftTy = ShTy;
1004     Op->RegShiftedImm.SrcReg = SrcReg;
1005     Op->RegShiftedImm.ShiftImm = ShiftImm;
1006     Op->StartLoc = S;
1007     Op->EndLoc = E;
1008     return Op;
1009   }
1010
1011   static ARMOperand *CreateShifterImm(bool isASR, unsigned Imm,
1012                                    SMLoc S, SMLoc E) {
1013     ARMOperand *Op = new ARMOperand(ShifterImmediate);
1014     Op->ShifterImm.isASR = isASR;
1015     Op->ShifterImm.Imm = Imm;
1016     Op->StartLoc = S;
1017     Op->EndLoc = E;
1018     return Op;
1019   }
1020
1021   static ARMOperand *CreateRotImm(unsigned Imm, SMLoc S, SMLoc E) {
1022     ARMOperand *Op = new ARMOperand(RotateImmediate);
1023     Op->RotImm.Imm = Imm;
1024     Op->StartLoc = S;
1025     Op->EndLoc = E;
1026     return Op;
1027   }
1028
1029   static ARMOperand *
1030   CreateRegList(const SmallVectorImpl<std::pair<unsigned, SMLoc> > &Regs,
1031                 SMLoc StartLoc, SMLoc EndLoc) {
1032     KindTy Kind = RegisterList;
1033
1034     if (llvm::ARMMCRegisterClasses[ARM::DPRRegClassID].
1035         contains(Regs.front().first))
1036       Kind = DPRRegisterList;
1037     else if (llvm::ARMMCRegisterClasses[ARM::SPRRegClassID].
1038              contains(Regs.front().first))
1039       Kind = SPRRegisterList;
1040
1041     ARMOperand *Op = new ARMOperand(Kind);
1042     for (SmallVectorImpl<std::pair<unsigned, SMLoc> >::const_iterator
1043            I = Regs.begin(), E = Regs.end(); I != E; ++I)
1044       Op->Registers.push_back(I->first);
1045     array_pod_sort(Op->Registers.begin(), Op->Registers.end());
1046     Op->StartLoc = StartLoc;
1047     Op->EndLoc = EndLoc;
1048     return Op;
1049   }
1050
1051   static ARMOperand *CreateImm(const MCExpr *Val, SMLoc S, SMLoc E) {
1052     ARMOperand *Op = new ARMOperand(Immediate);
1053     Op->Imm.Val = Val;
1054     Op->StartLoc = S;
1055     Op->EndLoc = E;
1056     return Op;
1057   }
1058
1059   static ARMOperand *CreateMem(ARMII::AddrMode AddrMode, unsigned BaseRegNum,
1060                                bool OffsetIsReg, const MCExpr *Offset,
1061                                int OffsetRegNum, bool OffsetRegShifted,
1062                                enum ARM_AM::ShiftOpc ShiftType,
1063                                const MCExpr *ShiftAmount, bool Preindexed,
1064                                bool Postindexed, bool Negative, bool Writeback,
1065                                SMLoc S, SMLoc E) {
1066     assert((OffsetRegNum == -1 || OffsetIsReg) &&
1067            "OffsetRegNum must imply OffsetIsReg!");
1068     assert((!OffsetRegShifted || OffsetIsReg) &&
1069            "OffsetRegShifted must imply OffsetIsReg!");
1070     assert((Offset || OffsetIsReg) &&
1071            "Offset must exists unless register offset is used!");
1072     assert((!ShiftAmount || (OffsetIsReg && OffsetRegShifted)) &&
1073            "Cannot have shift amount without shifted register offset!");
1074     assert((!Offset || !OffsetIsReg) &&
1075            "Cannot have expression offset and register offset!");
1076
1077     ARMOperand *Op = new ARMOperand(Memory);
1078     Op->Mem.AddrMode = AddrMode;
1079     Op->Mem.BaseRegNum = BaseRegNum;
1080     Op->Mem.OffsetIsReg = OffsetIsReg;
1081     if (OffsetIsReg)
1082       Op->Mem.Offset.RegNum = OffsetRegNum;
1083     else
1084       Op->Mem.Offset.Value = Offset;
1085     Op->Mem.OffsetRegShifted = OffsetRegShifted;
1086     Op->Mem.ShiftType = ShiftType;
1087     Op->Mem.ShiftAmount = ShiftAmount;
1088     Op->Mem.Preindexed = Preindexed;
1089     Op->Mem.Postindexed = Postindexed;
1090     Op->Mem.Negative = Negative;
1091     Op->Mem.Writeback = Writeback;
1092
1093     Op->StartLoc = S;
1094     Op->EndLoc = E;
1095     return Op;
1096   }
1097
1098   static ARMOperand *CreateMemBarrierOpt(ARM_MB::MemBOpt Opt, SMLoc S) {
1099     ARMOperand *Op = new ARMOperand(MemBarrierOpt);
1100     Op->MBOpt.Val = Opt;
1101     Op->StartLoc = S;
1102     Op->EndLoc = S;
1103     return Op;
1104   }
1105
1106   static ARMOperand *CreateProcIFlags(ARM_PROC::IFlags IFlags, SMLoc S) {
1107     ARMOperand *Op = new ARMOperand(ProcIFlags);
1108     Op->IFlags.Val = IFlags;
1109     Op->StartLoc = S;
1110     Op->EndLoc = S;
1111     return Op;
1112   }
1113
1114   static ARMOperand *CreateMSRMask(unsigned MMask, SMLoc S) {
1115     ARMOperand *Op = new ARMOperand(MSRMask);
1116     Op->MMask.Val = MMask;
1117     Op->StartLoc = S;
1118     Op->EndLoc = S;
1119     return Op;
1120   }
1121 };
1122
1123 } // end anonymous namespace.
1124
1125 void ARMOperand::print(raw_ostream &OS) const {
1126   switch (Kind) {
1127   case CondCode:
1128     OS << "<ARMCC::" << ARMCondCodeToString(getCondCode()) << ">";
1129     break;
1130   case CCOut:
1131     OS << "<ccout " << getReg() << ">";
1132     break;
1133   case CoprocNum:
1134     OS << "<coprocessor number: " << getCoproc() << ">";
1135     break;
1136   case CoprocReg:
1137     OS << "<coprocessor register: " << getCoproc() << ">";
1138     break;
1139   case MSRMask:
1140     OS << "<mask: " << getMSRMask() << ">";
1141     break;
1142   case Immediate:
1143     getImm()->print(OS);
1144     break;
1145   case MemBarrierOpt:
1146     OS << "<ARM_MB::" << MemBOptToString(getMemBarrierOpt()) << ">";
1147     break;
1148   case Memory:
1149     OS << "<memory "
1150        << "am:" << ARMII::AddrModeToString(getMemAddrMode())
1151        << " base:" << getMemBaseRegNum();
1152     if (getMemOffsetIsReg()) {
1153       OS << " offset:<register " << getMemOffsetRegNum();
1154       if (getMemOffsetRegShifted()) {
1155         OS << " offset-shift-type:" << getMemShiftType();
1156         OS << " offset-shift-amount:" << *getMemShiftAmount();
1157       }
1158     } else {
1159       OS << " offset:" << *getMemOffset();
1160     }
1161     if (getMemOffsetIsReg())
1162       OS << " (offset-is-reg)";
1163     if (getMemPreindexed())
1164       OS << " (pre-indexed)";
1165     if (getMemPostindexed())
1166       OS << " (post-indexed)";
1167     if (getMemNegative())
1168       OS << " (negative)";
1169     if (getMemWriteback())
1170       OS << " (writeback)";
1171     OS << ">";
1172     break;
1173   case ProcIFlags: {
1174     OS << "<ARM_PROC::";
1175     unsigned IFlags = getProcIFlags();
1176     for (int i=2; i >= 0; --i)
1177       if (IFlags & (1 << i))
1178         OS << ARM_PROC::IFlagsToString(1 << i);
1179     OS << ">";
1180     break;
1181   }
1182   case Register:
1183     OS << "<register " << getReg() << ">";
1184     break;
1185   case ShifterImmediate:
1186     OS << "<shift " << (ShifterImm.isASR ? "asr" : "lsl")
1187        << " #" << ShifterImm.Imm << ">";
1188     break;
1189   case ShiftedRegister:
1190     OS << "<so_reg_reg "
1191        << RegShiftedReg.SrcReg
1192        << ARM_AM::getShiftOpcStr(ARM_AM::getSORegShOp(RegShiftedReg.ShiftImm))
1193        << ", " << RegShiftedReg.ShiftReg << ", "
1194        << ARM_AM::getSORegOffset(RegShiftedReg.ShiftImm)
1195        << ">";
1196     break;
1197   case ShiftedImmediate:
1198     OS << "<so_reg_imm "
1199        << RegShiftedImm.SrcReg
1200        << ARM_AM::getShiftOpcStr(ARM_AM::getSORegShOp(RegShiftedImm.ShiftImm))
1201        << ", " << ARM_AM::getSORegOffset(RegShiftedImm.ShiftImm)
1202        << ">";
1203     break;
1204   case RotateImmediate:
1205     OS << "<ror " << " #" << (RotImm.Imm * 8) << ">";
1206     break;
1207   case RegisterList:
1208   case DPRRegisterList:
1209   case SPRRegisterList: {
1210     OS << "<register_list ";
1211
1212     const SmallVectorImpl<unsigned> &RegList = getRegList();
1213     for (SmallVectorImpl<unsigned>::const_iterator
1214            I = RegList.begin(), E = RegList.end(); I != E; ) {
1215       OS << *I;
1216       if (++I < E) OS << ", ";
1217     }
1218
1219     OS << ">";
1220     break;
1221   }
1222   case Token:
1223     OS << "'" << getToken() << "'";
1224     break;
1225   }
1226 }
1227
1228 /// @name Auto-generated Match Functions
1229 /// {
1230
1231 static unsigned MatchRegisterName(StringRef Name);
1232
1233 /// }
1234
1235 bool ARMAsmParser::ParseRegister(unsigned &RegNo,
1236                                  SMLoc &StartLoc, SMLoc &EndLoc) {
1237   RegNo = tryParseRegister();
1238
1239   return (RegNo == (unsigned)-1);
1240 }
1241
1242 /// Try to parse a register name.  The token must be an Identifier when called,
1243 /// and if it is a register name the token is eaten and the register number is
1244 /// returned.  Otherwise return -1.
1245 ///
1246 int ARMAsmParser::tryParseRegister() {
1247   const AsmToken &Tok = Parser.getTok();
1248   assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
1249
1250   // FIXME: Validate register for the current architecture; we have to do
1251   // validation later, so maybe there is no need for this here.
1252   std::string upperCase = Tok.getString().str();
1253   std::string lowerCase = LowercaseString(upperCase);
1254   unsigned RegNum = MatchRegisterName(lowerCase);
1255   if (!RegNum) {
1256     RegNum = StringSwitch<unsigned>(lowerCase)
1257       .Case("r13", ARM::SP)
1258       .Case("r14", ARM::LR)
1259       .Case("r15", ARM::PC)
1260       .Case("ip", ARM::R12)
1261       .Default(0);
1262   }
1263   if (!RegNum) return -1;
1264
1265   Parser.Lex(); // Eat identifier token.
1266   return RegNum;
1267 }
1268
1269 // Try to parse a shifter  (e.g., "lsl <amt>"). On success, return 0.
1270 // If a recoverable error occurs, return 1. If an irrecoverable error
1271 // occurs, return -1. An irrecoverable error is one where tokens have been
1272 // consumed in the process of trying to parse the shifter (i.e., when it is
1273 // indeed a shifter operand, but malformed).
1274 int ARMAsmParser::tryParseShiftRegister(
1275                                SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1276   SMLoc S = Parser.getTok().getLoc();
1277   const AsmToken &Tok = Parser.getTok();
1278   assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
1279
1280   std::string upperCase = Tok.getString().str();
1281   std::string lowerCase = LowercaseString(upperCase);
1282   ARM_AM::ShiftOpc ShiftTy = StringSwitch<ARM_AM::ShiftOpc>(lowerCase)
1283       .Case("lsl", ARM_AM::lsl)
1284       .Case("lsr", ARM_AM::lsr)
1285       .Case("asr", ARM_AM::asr)
1286       .Case("ror", ARM_AM::ror)
1287       .Case("rrx", ARM_AM::rrx)
1288       .Default(ARM_AM::no_shift);
1289
1290   if (ShiftTy == ARM_AM::no_shift)
1291     return 1;
1292
1293   Parser.Lex(); // Eat the operator.
1294
1295   // The source register for the shift has already been added to the
1296   // operand list, so we need to pop it off and combine it into the shifted
1297   // register operand instead.
1298   OwningPtr<ARMOperand> PrevOp((ARMOperand*)Operands.pop_back_val());
1299   if (!PrevOp->isReg())
1300     return Error(PrevOp->getStartLoc(), "shift must be of a register");
1301   int SrcReg = PrevOp->getReg();
1302   int64_t Imm = 0;
1303   int ShiftReg = 0;
1304   if (ShiftTy == ARM_AM::rrx) {
1305     // RRX Doesn't have an explicit shift amount. The encoder expects
1306     // the shift register to be the same as the source register. Seems odd,
1307     // but OK.
1308     ShiftReg = SrcReg;
1309   } else {
1310     // Figure out if this is shifted by a constant or a register (for non-RRX).
1311     if (Parser.getTok().is(AsmToken::Hash)) {
1312       Parser.Lex(); // Eat hash.
1313       SMLoc ImmLoc = Parser.getTok().getLoc();
1314       const MCExpr *ShiftExpr = 0;
1315       if (getParser().ParseExpression(ShiftExpr)) {
1316         Error(ImmLoc, "invalid immediate shift value");
1317         return -1;
1318       }
1319       // The expression must be evaluatable as an immediate.
1320       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftExpr);
1321       if (!CE) {
1322         Error(ImmLoc, "invalid immediate shift value");
1323         return -1;
1324       }
1325       // Range check the immediate.
1326       // lsl, ror: 0 <= imm <= 31
1327       // lsr, asr: 0 <= imm <= 32
1328       Imm = CE->getValue();
1329       if (Imm < 0 ||
1330           ((ShiftTy == ARM_AM::lsl || ShiftTy == ARM_AM::ror) && Imm > 31) ||
1331           ((ShiftTy == ARM_AM::lsr || ShiftTy == ARM_AM::asr) && Imm > 32)) {
1332         Error(ImmLoc, "immediate shift value out of range");
1333         return -1;
1334       }
1335     } else if (Parser.getTok().is(AsmToken::Identifier)) {
1336       ShiftReg = tryParseRegister();
1337       SMLoc L = Parser.getTok().getLoc();
1338       if (ShiftReg == -1) {
1339         Error (L, "expected immediate or register in shift operand");
1340         return -1;
1341       }
1342     } else {
1343       Error (Parser.getTok().getLoc(),
1344                     "expected immediate or register in shift operand");
1345       return -1;
1346     }
1347   }
1348
1349   if (ShiftReg && ShiftTy != ARM_AM::rrx)
1350     Operands.push_back(ARMOperand::CreateShiftedRegister(ShiftTy, SrcReg,
1351                                                          ShiftReg, Imm,
1352                                                S, Parser.getTok().getLoc()));
1353   else
1354     Operands.push_back(ARMOperand::CreateShiftedImmediate(ShiftTy, SrcReg, Imm,
1355                                                S, Parser.getTok().getLoc()));
1356
1357   return 0;
1358 }
1359
1360
1361 /// Try to parse a register name.  The token must be an Identifier when called.
1362 /// If it's a register, an AsmOperand is created. Another AsmOperand is created
1363 /// if there is a "writeback". 'true' if it's not a register.
1364 ///
1365 /// TODO this is likely to change to allow different register types and or to
1366 /// parse for a specific register type.
1367 bool ARMAsmParser::
1368 tryParseRegisterWithWriteBack(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1369   SMLoc S = Parser.getTok().getLoc();
1370   int RegNo = tryParseRegister();
1371   if (RegNo == -1)
1372     return true;
1373
1374   Operands.push_back(ARMOperand::CreateReg(RegNo, S, Parser.getTok().getLoc()));
1375
1376   const AsmToken &ExclaimTok = Parser.getTok();
1377   if (ExclaimTok.is(AsmToken::Exclaim)) {
1378     Operands.push_back(ARMOperand::CreateToken(ExclaimTok.getString(),
1379                                                ExclaimTok.getLoc()));
1380     Parser.Lex(); // Eat exclaim token
1381   }
1382
1383   return false;
1384 }
1385
1386 /// MatchCoprocessorOperandName - Try to parse an coprocessor related
1387 /// instruction with a symbolic operand name. Example: "p1", "p7", "c3",
1388 /// "c5", ...
1389 static int MatchCoprocessorOperandName(StringRef Name, char CoprocOp) {
1390   // Use the same layout as the tablegen'erated register name matcher. Ugly,
1391   // but efficient.
1392   switch (Name.size()) {
1393   default: break;
1394   case 2:
1395     if (Name[0] != CoprocOp)
1396       return -1;
1397     switch (Name[1]) {
1398     default:  return -1;
1399     case '0': return 0;
1400     case '1': return 1;
1401     case '2': return 2;
1402     case '3': return 3;
1403     case '4': return 4;
1404     case '5': return 5;
1405     case '6': return 6;
1406     case '7': return 7;
1407     case '8': return 8;
1408     case '9': return 9;
1409     }
1410     break;
1411   case 3:
1412     if (Name[0] != CoprocOp || Name[1] != '1')
1413       return -1;
1414     switch (Name[2]) {
1415     default:  return -1;
1416     case '0': return 10;
1417     case '1': return 11;
1418     case '2': return 12;
1419     case '3': return 13;
1420     case '4': return 14;
1421     case '5': return 15;
1422     }
1423     break;
1424   }
1425
1426   return -1;
1427 }
1428
1429 /// parseCoprocNumOperand - Try to parse an coprocessor number operand. The
1430 /// token must be an Identifier when called, and if it is a coprocessor
1431 /// number, the token is eaten and the operand is added to the operand list.
1432 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
1433 parseCoprocNumOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1434   SMLoc S = Parser.getTok().getLoc();
1435   const AsmToken &Tok = Parser.getTok();
1436   assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
1437
1438   int Num = MatchCoprocessorOperandName(Tok.getString(), 'p');
1439   if (Num == -1)
1440     return MatchOperand_NoMatch;
1441
1442   Parser.Lex(); // Eat identifier token.
1443   Operands.push_back(ARMOperand::CreateCoprocNum(Num, S));
1444   return MatchOperand_Success;
1445 }
1446
1447 /// parseCoprocRegOperand - Try to parse an coprocessor register operand. The
1448 /// token must be an Identifier when called, and if it is a coprocessor
1449 /// number, the token is eaten and the operand is added to the operand list.
1450 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
1451 parseCoprocRegOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1452   SMLoc S = Parser.getTok().getLoc();
1453   const AsmToken &Tok = Parser.getTok();
1454   assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
1455
1456   int Reg = MatchCoprocessorOperandName(Tok.getString(), 'c');
1457   if (Reg == -1)
1458     return MatchOperand_NoMatch;
1459
1460   Parser.Lex(); // Eat identifier token.
1461   Operands.push_back(ARMOperand::CreateCoprocReg(Reg, S));
1462   return MatchOperand_Success;
1463 }
1464
1465 /// Parse a register list, return it if successful else return null.  The first
1466 /// token must be a '{' when called.
1467 bool ARMAsmParser::
1468 parseRegisterList(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1469   assert(Parser.getTok().is(AsmToken::LCurly) &&
1470          "Token is not a Left Curly Brace");
1471   SMLoc S = Parser.getTok().getLoc();
1472
1473   // Read the rest of the registers in the list.
1474   unsigned PrevRegNum = 0;
1475   SmallVector<std::pair<unsigned, SMLoc>, 32> Registers;
1476
1477   do {
1478     bool IsRange = Parser.getTok().is(AsmToken::Minus);
1479     Parser.Lex(); // Eat non-identifier token.
1480
1481     const AsmToken &RegTok = Parser.getTok();
1482     SMLoc RegLoc = RegTok.getLoc();
1483     if (RegTok.isNot(AsmToken::Identifier)) {
1484       Error(RegLoc, "register expected");
1485       return true;
1486     }
1487
1488     int RegNum = tryParseRegister();
1489     if (RegNum == -1) {
1490       Error(RegLoc, "register expected");
1491       return true;
1492     }
1493
1494     if (IsRange) {
1495       int Reg = PrevRegNum;
1496       do {
1497         ++Reg;
1498         Registers.push_back(std::make_pair(Reg, RegLoc));
1499       } while (Reg != RegNum);
1500     } else {
1501       Registers.push_back(std::make_pair(RegNum, RegLoc));
1502     }
1503
1504     PrevRegNum = RegNum;
1505   } while (Parser.getTok().is(AsmToken::Comma) ||
1506            Parser.getTok().is(AsmToken::Minus));
1507
1508   // Process the right curly brace of the list.
1509   const AsmToken &RCurlyTok = Parser.getTok();
1510   if (RCurlyTok.isNot(AsmToken::RCurly)) {
1511     Error(RCurlyTok.getLoc(), "'}' expected");
1512     return true;
1513   }
1514
1515   SMLoc E = RCurlyTok.getLoc();
1516   Parser.Lex(); // Eat right curly brace token.
1517
1518   // Verify the register list.
1519   SmallVectorImpl<std::pair<unsigned, SMLoc> >::const_iterator
1520     RI = Registers.begin(), RE = Registers.end();
1521
1522   unsigned HighRegNum = getARMRegisterNumbering(RI->first);
1523   bool EmittedWarning = false;
1524
1525   DenseMap<unsigned, bool> RegMap;
1526   RegMap[HighRegNum] = true;
1527
1528   for (++RI; RI != RE; ++RI) {
1529     const std::pair<unsigned, SMLoc> &RegInfo = *RI;
1530     unsigned Reg = getARMRegisterNumbering(RegInfo.first);
1531
1532     if (RegMap[Reg]) {
1533       Error(RegInfo.second, "register duplicated in register list");
1534       return true;
1535     }
1536
1537     if (!EmittedWarning && Reg < HighRegNum)
1538       Warning(RegInfo.second,
1539               "register not in ascending order in register list");
1540
1541     RegMap[Reg] = true;
1542     HighRegNum = std::max(Reg, HighRegNum);
1543   }
1544
1545   Operands.push_back(ARMOperand::CreateRegList(Registers, S, E));
1546   return false;
1547 }
1548
1549 /// parseMemBarrierOptOperand - Try to parse DSB/DMB data barrier options.
1550 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
1551 parseMemBarrierOptOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1552   SMLoc S = Parser.getTok().getLoc();
1553   const AsmToken &Tok = Parser.getTok();
1554   assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
1555   StringRef OptStr = Tok.getString();
1556
1557   unsigned Opt = StringSwitch<unsigned>(OptStr.slice(0, OptStr.size()))
1558     .Case("sy",    ARM_MB::SY)
1559     .Case("st",    ARM_MB::ST)
1560     .Case("sh",    ARM_MB::ISH)
1561     .Case("ish",   ARM_MB::ISH)
1562     .Case("shst",  ARM_MB::ISHST)
1563     .Case("ishst", ARM_MB::ISHST)
1564     .Case("nsh",   ARM_MB::NSH)
1565     .Case("un",    ARM_MB::NSH)
1566     .Case("nshst", ARM_MB::NSHST)
1567     .Case("unst",  ARM_MB::NSHST)
1568     .Case("osh",   ARM_MB::OSH)
1569     .Case("oshst", ARM_MB::OSHST)
1570     .Default(~0U);
1571
1572   if (Opt == ~0U)
1573     return MatchOperand_NoMatch;
1574
1575   Parser.Lex(); // Eat identifier token.
1576   Operands.push_back(ARMOperand::CreateMemBarrierOpt((ARM_MB::MemBOpt)Opt, S));
1577   return MatchOperand_Success;
1578 }
1579
1580 /// parseProcIFlagsOperand - Try to parse iflags from CPS instruction.
1581 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
1582 parseProcIFlagsOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1583   SMLoc S = Parser.getTok().getLoc();
1584   const AsmToken &Tok = Parser.getTok();
1585   assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
1586   StringRef IFlagsStr = Tok.getString();
1587
1588   unsigned IFlags = 0;
1589   for (int i = 0, e = IFlagsStr.size(); i != e; ++i) {
1590     unsigned Flag = StringSwitch<unsigned>(IFlagsStr.substr(i, 1))
1591     .Case("a", ARM_PROC::A)
1592     .Case("i", ARM_PROC::I)
1593     .Case("f", ARM_PROC::F)
1594     .Default(~0U);
1595
1596     // If some specific iflag is already set, it means that some letter is
1597     // present more than once, this is not acceptable.
1598     if (Flag == ~0U || (IFlags & Flag))
1599       return MatchOperand_NoMatch;
1600
1601     IFlags |= Flag;
1602   }
1603
1604   Parser.Lex(); // Eat identifier token.
1605   Operands.push_back(ARMOperand::CreateProcIFlags((ARM_PROC::IFlags)IFlags, S));
1606   return MatchOperand_Success;
1607 }
1608
1609 /// parseMSRMaskOperand - Try to parse mask flags from MSR instruction.
1610 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
1611 parseMSRMaskOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1612   SMLoc S = Parser.getTok().getLoc();
1613   const AsmToken &Tok = Parser.getTok();
1614   assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
1615   StringRef Mask = Tok.getString();
1616
1617   // Split spec_reg from flag, example: CPSR_sxf => "CPSR" and "sxf"
1618   size_t Start = 0, Next = Mask.find('_');
1619   StringRef Flags = "";
1620   std::string SpecReg = LowercaseString(Mask.slice(Start, Next));
1621   if (Next != StringRef::npos)
1622     Flags = Mask.slice(Next+1, Mask.size());
1623
1624   // FlagsVal contains the complete mask:
1625   // 3-0: Mask
1626   // 4: Special Reg (cpsr, apsr => 0; spsr => 1)
1627   unsigned FlagsVal = 0;
1628
1629   if (SpecReg == "apsr") {
1630     FlagsVal = StringSwitch<unsigned>(Flags)
1631     .Case("nzcvq",  0x8) // same as CPSR_f
1632     .Case("g",      0x4) // same as CPSR_s
1633     .Case("nzcvqg", 0xc) // same as CPSR_fs
1634     .Default(~0U);
1635
1636     if (FlagsVal == ~0U) {
1637       if (!Flags.empty())
1638         return MatchOperand_NoMatch;
1639       else
1640         FlagsVal = 0; // No flag
1641     }
1642   } else if (SpecReg == "cpsr" || SpecReg == "spsr") {
1643     if (Flags == "all") // cpsr_all is an alias for cpsr_fc
1644       Flags = "fc";
1645     for (int i = 0, e = Flags.size(); i != e; ++i) {
1646       unsigned Flag = StringSwitch<unsigned>(Flags.substr(i, 1))
1647       .Case("c", 1)
1648       .Case("x", 2)
1649       .Case("s", 4)
1650       .Case("f", 8)
1651       .Default(~0U);
1652
1653       // If some specific flag is already set, it means that some letter is
1654       // present more than once, this is not acceptable.
1655       if (FlagsVal == ~0U || (FlagsVal & Flag))
1656         return MatchOperand_NoMatch;
1657       FlagsVal |= Flag;
1658     }
1659   } else // No match for special register.
1660     return MatchOperand_NoMatch;
1661
1662   // Special register without flags are equivalent to "fc" flags.
1663   if (!FlagsVal)
1664     FlagsVal = 0x9;
1665
1666   // Bit 4: Special Reg (cpsr, apsr => 0; spsr => 1)
1667   if (SpecReg == "spsr")
1668     FlagsVal |= 16;
1669
1670   Parser.Lex(); // Eat identifier token.
1671   Operands.push_back(ARMOperand::CreateMSRMask(FlagsVal, S));
1672   return MatchOperand_Success;
1673 }
1674
1675 /// parseMemMode2Operand - Try to parse memory addressing mode 2 operand.
1676 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
1677 parseMemMode2Operand(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1678   assert(Parser.getTok().is(AsmToken::LBrac) && "Token is not a \"[\"");
1679
1680   if (parseMemory(Operands, ARMII::AddrMode2))
1681     return MatchOperand_NoMatch;
1682
1683   return MatchOperand_Success;
1684 }
1685
1686 /// parseMemMode3Operand - Try to parse memory addressing mode 3 operand.
1687 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
1688 parseMemMode3Operand(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1689   assert(Parser.getTok().is(AsmToken::LBrac) && "Token is not a \"[\"");
1690
1691   if (parseMemory(Operands, ARMII::AddrMode3))
1692     return MatchOperand_NoMatch;
1693
1694   return MatchOperand_Success;
1695 }
1696
1697 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
1698 parsePKHImm(SmallVectorImpl<MCParsedAsmOperand*> &Operands, StringRef Op,
1699             int Low, int High) {
1700   const AsmToken &Tok = Parser.getTok();
1701   if (Tok.isNot(AsmToken::Identifier)) {
1702     Error(Parser.getTok().getLoc(), Op + " operand expected.");
1703     return MatchOperand_ParseFail;
1704   }
1705   StringRef ShiftName = Tok.getString();
1706   std::string LowerOp = LowercaseString(Op);
1707   std::string UpperOp = UppercaseString(Op);
1708   if (ShiftName != LowerOp && ShiftName != UpperOp) {
1709     Error(Parser.getTok().getLoc(), Op + " operand expected.");
1710     return MatchOperand_ParseFail;
1711   }
1712   Parser.Lex(); // Eat shift type token.
1713
1714   // There must be a '#' and a shift amount.
1715   if (Parser.getTok().isNot(AsmToken::Hash)) {
1716     Error(Parser.getTok().getLoc(), "'#' expected");
1717     return MatchOperand_ParseFail;
1718   }
1719   Parser.Lex(); // Eat hash token.
1720
1721   const MCExpr *ShiftAmount;
1722   SMLoc Loc = Parser.getTok().getLoc();
1723   if (getParser().ParseExpression(ShiftAmount)) {
1724     Error(Loc, "illegal expression");
1725     return MatchOperand_ParseFail;
1726   }
1727   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
1728   if (!CE) {
1729     Error(Loc, "constant expression expected");
1730     return MatchOperand_ParseFail;
1731   }
1732   int Val = CE->getValue();
1733   if (Val < Low || Val > High) {
1734     Error(Loc, "immediate value out of range");
1735     return MatchOperand_ParseFail;
1736   }
1737
1738   Operands.push_back(ARMOperand::CreateImm(CE, Loc, Parser.getTok().getLoc()));
1739
1740   return MatchOperand_Success;
1741 }
1742
1743 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
1744 parseSetEndImm(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1745   const AsmToken &Tok = Parser.getTok();
1746   SMLoc S = Tok.getLoc();
1747   if (Tok.isNot(AsmToken::Identifier)) {
1748     Error(Tok.getLoc(), "'be' or 'le' operand expected");
1749     return MatchOperand_ParseFail;
1750   }
1751   int Val = StringSwitch<int>(Tok.getString())
1752     .Case("be", 1)
1753     .Case("le", 0)
1754     .Default(-1);
1755   Parser.Lex(); // Eat the token.
1756
1757   if (Val == -1) {
1758     Error(Tok.getLoc(), "'be' or 'le' operand expected");
1759     return MatchOperand_ParseFail;
1760   }
1761   Operands.push_back(ARMOperand::CreateImm(MCConstantExpr::Create(Val,
1762                                                                   getContext()),
1763                                            S, Parser.getTok().getLoc()));
1764   return MatchOperand_Success;
1765 }
1766
1767 /// parseShifterImm - Parse the shifter immediate operand for SSAT/USAT
1768 /// instructions. Legal values are:
1769 ///     lsl #n  'n' in [0,31]
1770 ///     asr #n  'n' in [1,32]
1771 ///             n == 32 encoded as n == 0.
1772 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
1773 parseShifterImm(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1774   const AsmToken &Tok = Parser.getTok();
1775   SMLoc S = Tok.getLoc();
1776   if (Tok.isNot(AsmToken::Identifier)) {
1777     Error(S, "shift operator 'asr' or 'lsl' expected");
1778     return MatchOperand_ParseFail;
1779   }
1780   StringRef ShiftName = Tok.getString();
1781   bool isASR;
1782   if (ShiftName == "lsl" || ShiftName == "LSL")
1783     isASR = false;
1784   else if (ShiftName == "asr" || ShiftName == "ASR")
1785     isASR = true;
1786   else {
1787     Error(S, "shift operator 'asr' or 'lsl' expected");
1788     return MatchOperand_ParseFail;
1789   }
1790   Parser.Lex(); // Eat the operator.
1791
1792   // A '#' and a shift amount.
1793   if (Parser.getTok().isNot(AsmToken::Hash)) {
1794     Error(Parser.getTok().getLoc(), "'#' expected");
1795     return MatchOperand_ParseFail;
1796   }
1797   Parser.Lex(); // Eat hash token.
1798
1799   const MCExpr *ShiftAmount;
1800   SMLoc E = Parser.getTok().getLoc();
1801   if (getParser().ParseExpression(ShiftAmount)) {
1802     Error(E, "malformed shift expression");
1803     return MatchOperand_ParseFail;
1804   }
1805   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
1806   if (!CE) {
1807     Error(E, "shift amount must be an immediate");
1808     return MatchOperand_ParseFail;
1809   }
1810
1811   int64_t Val = CE->getValue();
1812   if (isASR) {
1813     // Shift amount must be in [1,32]
1814     if (Val < 1 || Val > 32) {
1815       Error(E, "'asr' shift amount must be in range [1,32]");
1816       return MatchOperand_ParseFail;
1817     }
1818     // asr #32 encoded as asr #0.
1819     if (Val == 32) Val = 0;
1820   } else {
1821     // Shift amount must be in [1,32]
1822     if (Val < 0 || Val > 31) {
1823       Error(E, "'lsr' shift amount must be in range [0,31]");
1824       return MatchOperand_ParseFail;
1825     }
1826   }
1827
1828   E = Parser.getTok().getLoc();
1829   Operands.push_back(ARMOperand::CreateShifterImm(isASR, Val, S, E));
1830
1831   return MatchOperand_Success;
1832 }
1833
1834 /// parseRotImm - Parse the shifter immediate operand for SXTB/UXTB family
1835 /// of instructions. Legal values are:
1836 ///     ror #n  'n' in {0, 8, 16, 24}
1837 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
1838 parseRotImm(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1839   const AsmToken &Tok = Parser.getTok();
1840   SMLoc S = Tok.getLoc();
1841   if (Tok.isNot(AsmToken::Identifier)) {
1842     Error(S, "rotate operator 'ror' expected");
1843     return MatchOperand_ParseFail;
1844   }
1845   StringRef ShiftName = Tok.getString();
1846   if (ShiftName != "ror" && ShiftName != "ROR") {
1847     Error(S, "rotate operator 'ror' expected");
1848     return MatchOperand_ParseFail;
1849   }
1850   Parser.Lex(); // Eat the operator.
1851
1852   // A '#' and a rotate amount.
1853   if (Parser.getTok().isNot(AsmToken::Hash)) {
1854     Error(Parser.getTok().getLoc(), "'#' expected");
1855     return MatchOperand_ParseFail;
1856   }
1857   Parser.Lex(); // Eat hash token.
1858
1859   const MCExpr *ShiftAmount;
1860   SMLoc E = Parser.getTok().getLoc();
1861   if (getParser().ParseExpression(ShiftAmount)) {
1862     Error(E, "malformed rotate expression");
1863     return MatchOperand_ParseFail;
1864   }
1865   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
1866   if (!CE) {
1867     Error(E, "rotate amount must be an immediate");
1868     return MatchOperand_ParseFail;
1869   }
1870
1871   int64_t Val = CE->getValue();
1872   // Shift amount must be in {0, 8, 16, 24} (0 is undocumented extension)
1873   // normally, zero is represented in asm by omitting the rotate operand
1874   // entirely.
1875   if (Val != 8 && Val != 16 && Val != 24 && Val != 0) {
1876     Error(E, "'ror' rotate amount must be 8, 16, or 24");
1877     return MatchOperand_ParseFail;
1878   }
1879
1880   E = Parser.getTok().getLoc();
1881   Operands.push_back(ARMOperand::CreateRotImm(Val, S, E));
1882
1883   return MatchOperand_Success;
1884 }
1885
1886 /// cvtLdWriteBackRegAddrMode2 - Convert parsed operands to MCInst.
1887 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
1888 /// when they refer multiple MIOperands inside a single one.
1889 bool ARMAsmParser::
1890 cvtLdWriteBackRegAddrMode2(MCInst &Inst, unsigned Opcode,
1891                          const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1892   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
1893
1894   // Create a writeback register dummy placeholder.
1895   Inst.addOperand(MCOperand::CreateImm(0));
1896
1897   ((ARMOperand*)Operands[3])->addMemMode2Operands(Inst, 3);
1898   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
1899   return true;
1900 }
1901
1902 /// cvtStWriteBackRegAddrMode2 - Convert parsed operands to MCInst.
1903 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
1904 /// when they refer multiple MIOperands inside a single one.
1905 bool ARMAsmParser::
1906 cvtStWriteBackRegAddrMode2(MCInst &Inst, unsigned Opcode,
1907                          const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1908   // Create a writeback register dummy placeholder.
1909   Inst.addOperand(MCOperand::CreateImm(0));
1910   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
1911   ((ARMOperand*)Operands[3])->addMemMode2Operands(Inst, 3);
1912   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
1913   return true;
1914 }
1915
1916 /// cvtLdWriteBackRegAddrMode3 - Convert parsed operands to MCInst.
1917 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
1918 /// when they refer multiple MIOperands inside a single one.
1919 bool ARMAsmParser::
1920 cvtLdWriteBackRegAddrMode3(MCInst &Inst, unsigned Opcode,
1921                          const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1922   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
1923
1924   // Create a writeback register dummy placeholder.
1925   Inst.addOperand(MCOperand::CreateImm(0));
1926
1927   ((ARMOperand*)Operands[3])->addMemMode3Operands(Inst, 3);
1928   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
1929   return true;
1930 }
1931
1932 /// cvtStWriteBackRegAddrMode3 - Convert parsed operands to MCInst.
1933 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
1934 /// when they refer multiple MIOperands inside a single one.
1935 bool ARMAsmParser::
1936 cvtStWriteBackRegAddrMode3(MCInst &Inst, unsigned Opcode,
1937                          const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1938   // Create a writeback register dummy placeholder.
1939   Inst.addOperand(MCOperand::CreateImm(0));
1940   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
1941   ((ARMOperand*)Operands[3])->addMemMode3Operands(Inst, 3);
1942   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
1943   return true;
1944 }
1945
1946 /// Parse an ARM memory expression, return false if successful else return true
1947 /// or an error.  The first token must be a '[' when called.
1948 ///
1949 /// TODO Only preindexing and postindexing addressing are started, unindexed
1950 /// with option, etc are still to do.
1951 bool ARMAsmParser::
1952 parseMemory(SmallVectorImpl<MCParsedAsmOperand*> &Operands,
1953             ARMII::AddrMode AddrMode = ARMII::AddrModeNone) {
1954   SMLoc S, E;
1955   assert(Parser.getTok().is(AsmToken::LBrac) &&
1956          "Token is not a Left Bracket");
1957   S = Parser.getTok().getLoc();
1958   Parser.Lex(); // Eat left bracket token.
1959
1960   const AsmToken &BaseRegTok = Parser.getTok();
1961   if (BaseRegTok.isNot(AsmToken::Identifier)) {
1962     Error(BaseRegTok.getLoc(), "register expected");
1963     return true;
1964   }
1965   int BaseRegNum = tryParseRegister();
1966   if (BaseRegNum == -1) {
1967     Error(BaseRegTok.getLoc(), "register expected");
1968     return true;
1969   }
1970
1971   // The next token must either be a comma or a closing bracket.
1972   const AsmToken &Tok = Parser.getTok();
1973   if (!Tok.is(AsmToken::Comma) && !Tok.is(AsmToken::RBrac))
1974     return true;
1975
1976   bool Preindexed = false;
1977   bool Postindexed = false;
1978   bool OffsetIsReg = false;
1979   bool Negative = false;
1980   bool Writeback = false;
1981   ARMOperand *WBOp = 0;
1982   int OffsetRegNum = -1;
1983   bool OffsetRegShifted = false;
1984   enum ARM_AM::ShiftOpc ShiftType = ARM_AM::lsl;
1985   const MCExpr *ShiftAmount = 0;
1986   const MCExpr *Offset = 0;
1987
1988   // First look for preindexed address forms, that is after the "[Rn" we now
1989   // have to see if the next token is a comma.
1990   if (Tok.is(AsmToken::Comma)) {
1991     Preindexed = true;
1992     Parser.Lex(); // Eat comma token.
1993
1994     if (parseMemoryOffsetReg(Negative, OffsetRegShifted, ShiftType, ShiftAmount,
1995                              Offset, OffsetIsReg, OffsetRegNum, E))
1996       return true;
1997     const AsmToken &RBracTok = Parser.getTok();
1998     if (RBracTok.isNot(AsmToken::RBrac)) {
1999       Error(RBracTok.getLoc(), "']' expected");
2000       return true;
2001     }
2002     E = RBracTok.getLoc();
2003     Parser.Lex(); // Eat right bracket token.
2004
2005     const AsmToken &ExclaimTok = Parser.getTok();
2006     if (ExclaimTok.is(AsmToken::Exclaim)) {
2007       // None of addrmode3 instruction uses "!"
2008       if (AddrMode == ARMII::AddrMode3)
2009         return true;
2010
2011       WBOp = ARMOperand::CreateToken(ExclaimTok.getString(),
2012                                      ExclaimTok.getLoc());
2013       Writeback = true;
2014       Parser.Lex(); // Eat exclaim token
2015     } else { // In addressing mode 2, pre-indexed mode always end with "!"
2016       if (AddrMode == ARMII::AddrMode2)
2017         Preindexed = false;
2018     }
2019   } else {
2020     // The "[Rn" we have so far was not followed by a comma.
2021
2022     // If there's anything other than the right brace, this is a post indexing
2023     // addressing form.
2024     E = Tok.getLoc();
2025     Parser.Lex(); // Eat right bracket token.
2026
2027     const AsmToken &NextTok = Parser.getTok();
2028
2029     if (NextTok.isNot(AsmToken::EndOfStatement)) {
2030       Postindexed = true;
2031       Writeback = true;
2032
2033       if (NextTok.isNot(AsmToken::Comma)) {
2034         Error(NextTok.getLoc(), "',' expected");
2035         return true;
2036       }
2037
2038       Parser.Lex(); // Eat comma token.
2039
2040       if (parseMemoryOffsetReg(Negative, OffsetRegShifted, ShiftType,
2041                                ShiftAmount, Offset, OffsetIsReg, OffsetRegNum,
2042                                E))
2043         return true;
2044     }
2045   }
2046
2047   // Force Offset to exist if used.
2048   if (!OffsetIsReg) {
2049     if (!Offset)
2050       Offset = MCConstantExpr::Create(0, getContext());
2051   } else {
2052     if (AddrMode == ARMII::AddrMode3 && OffsetRegShifted) {
2053       Error(E, "shift amount not supported");
2054       return true;
2055     }
2056   }
2057
2058   Operands.push_back(ARMOperand::CreateMem(AddrMode, BaseRegNum, OffsetIsReg,
2059                                      Offset, OffsetRegNum, OffsetRegShifted,
2060                                      ShiftType, ShiftAmount, Preindexed,
2061                                      Postindexed, Negative, Writeback, S, E));
2062   if (WBOp)
2063     Operands.push_back(WBOp);
2064
2065   return false;
2066 }
2067
2068 /// Parse the offset of a memory operand after we have seen "[Rn," or "[Rn],"
2069 /// we will parse the following (were +/- means that a plus or minus is
2070 /// optional):
2071 ///   +/-Rm
2072 ///   +/-Rm, shift
2073 ///   #offset
2074 /// we return false on success or an error otherwise.
2075 bool ARMAsmParser::parseMemoryOffsetReg(bool &Negative,
2076                                         bool &OffsetRegShifted,
2077                                         enum ARM_AM::ShiftOpc &ShiftType,
2078                                         const MCExpr *&ShiftAmount,
2079                                         const MCExpr *&Offset,
2080                                         bool &OffsetIsReg,
2081                                         int &OffsetRegNum,
2082                                         SMLoc &E) {
2083   Negative = false;
2084   OffsetRegShifted = false;
2085   OffsetIsReg = false;
2086   OffsetRegNum = -1;
2087   const AsmToken &NextTok = Parser.getTok();
2088   E = NextTok.getLoc();
2089   if (NextTok.is(AsmToken::Plus))
2090     Parser.Lex(); // Eat plus token.
2091   else if (NextTok.is(AsmToken::Minus)) {
2092     Negative = true;
2093     Parser.Lex(); // Eat minus token
2094   }
2095   // See if there is a register following the "[Rn," or "[Rn]," we have so far.
2096   const AsmToken &OffsetRegTok = Parser.getTok();
2097   if (OffsetRegTok.is(AsmToken::Identifier)) {
2098     SMLoc CurLoc = OffsetRegTok.getLoc();
2099     OffsetRegNum = tryParseRegister();
2100     if (OffsetRegNum != -1) {
2101       OffsetIsReg = true;
2102       E = CurLoc;
2103     }
2104   }
2105
2106   // If we parsed a register as the offset then there can be a shift after that.
2107   if (OffsetRegNum != -1) {
2108     // Look for a comma then a shift
2109     const AsmToken &Tok = Parser.getTok();
2110     if (Tok.is(AsmToken::Comma)) {
2111       Parser.Lex(); // Eat comma token.
2112
2113       const AsmToken &Tok = Parser.getTok();
2114       if (parseShift(ShiftType, ShiftAmount, E))
2115         return Error(Tok.getLoc(), "shift expected");
2116       OffsetRegShifted = true;
2117     }
2118   }
2119   else { // the "[Rn," or "[Rn,]" we have so far was not followed by "Rm"
2120     // Look for #offset following the "[Rn," or "[Rn],"
2121     const AsmToken &HashTok = Parser.getTok();
2122     if (HashTok.isNot(AsmToken::Hash))
2123       return Error(HashTok.getLoc(), "'#' expected");
2124
2125     Parser.Lex(); // Eat hash token.
2126
2127     if (getParser().ParseExpression(Offset))
2128      return true;
2129     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
2130   }
2131   return false;
2132 }
2133
2134 /// parseShift as one of these two:
2135 ///   ( lsl | lsr | asr | ror ) , # shift_amount
2136 ///   rrx
2137 /// and returns true if it parses a shift otherwise it returns false.
2138 bool ARMAsmParser::parseShift(ARM_AM::ShiftOpc &St,
2139                               const MCExpr *&ShiftAmount, SMLoc &E) {
2140   const AsmToken &Tok = Parser.getTok();
2141   if (Tok.isNot(AsmToken::Identifier))
2142     return true;
2143   StringRef ShiftName = Tok.getString();
2144   if (ShiftName == "lsl" || ShiftName == "LSL")
2145     St = ARM_AM::lsl;
2146   else if (ShiftName == "lsr" || ShiftName == "LSR")
2147     St = ARM_AM::lsr;
2148   else if (ShiftName == "asr" || ShiftName == "ASR")
2149     St = ARM_AM::asr;
2150   else if (ShiftName == "ror" || ShiftName == "ROR")
2151     St = ARM_AM::ror;
2152   else if (ShiftName == "rrx" || ShiftName == "RRX")
2153     St = ARM_AM::rrx;
2154   else
2155     return true;
2156   Parser.Lex(); // Eat shift type token.
2157
2158   // Rrx stands alone.
2159   if (St == ARM_AM::rrx)
2160     return false;
2161
2162   // Otherwise, there must be a '#' and a shift amount.
2163   const AsmToken &HashTok = Parser.getTok();
2164   if (HashTok.isNot(AsmToken::Hash))
2165     return Error(HashTok.getLoc(), "'#' expected");
2166   Parser.Lex(); // Eat hash token.
2167
2168   if (getParser().ParseExpression(ShiftAmount))
2169     return true;
2170
2171   return false;
2172 }
2173
2174 /// Parse a arm instruction operand.  For now this parses the operand regardless
2175 /// of the mnemonic.
2176 bool ARMAsmParser::parseOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands,
2177                                 StringRef Mnemonic) {
2178   SMLoc S, E;
2179
2180   // Check if the current operand has a custom associated parser, if so, try to
2181   // custom parse the operand, or fallback to the general approach.
2182   OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
2183   if (ResTy == MatchOperand_Success)
2184     return false;
2185   // If there wasn't a custom match, try the generic matcher below. Otherwise,
2186   // there was a match, but an error occurred, in which case, just return that
2187   // the operand parsing failed.
2188   if (ResTy == MatchOperand_ParseFail)
2189     return true;
2190
2191   switch (getLexer().getKind()) {
2192   default:
2193     Error(Parser.getTok().getLoc(), "unexpected token in operand");
2194     return true;
2195   case AsmToken::Identifier: {
2196     if (!tryParseRegisterWithWriteBack(Operands))
2197       return false;
2198     int Res = tryParseShiftRegister(Operands);
2199     if (Res == 0) // success
2200       return false;
2201     else if (Res == -1) // irrecoverable error
2202       return true;
2203
2204     // Fall though for the Identifier case that is not a register or a
2205     // special name.
2206   }
2207   case AsmToken::Integer: // things like 1f and 2b as a branch targets
2208   case AsmToken::Dot: {   // . as a branch target
2209     // This was not a register so parse other operands that start with an
2210     // identifier (like labels) as expressions and create them as immediates.
2211     const MCExpr *IdVal;
2212     S = Parser.getTok().getLoc();
2213     if (getParser().ParseExpression(IdVal))
2214       return true;
2215     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
2216     Operands.push_back(ARMOperand::CreateImm(IdVal, S, E));
2217     return false;
2218   }
2219   case AsmToken::LBrac:
2220     return parseMemory(Operands);
2221   case AsmToken::LCurly:
2222     return parseRegisterList(Operands);
2223   case AsmToken::Hash:
2224     // #42 -> immediate.
2225     // TODO: ":lower16:" and ":upper16:" modifiers after # before immediate
2226     S = Parser.getTok().getLoc();
2227     Parser.Lex();
2228     const MCExpr *ImmVal;
2229     if (getParser().ParseExpression(ImmVal))
2230       return true;
2231     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
2232     Operands.push_back(ARMOperand::CreateImm(ImmVal, S, E));
2233     return false;
2234   case AsmToken::Colon: {
2235     // ":lower16:" and ":upper16:" expression prefixes
2236     // FIXME: Check it's an expression prefix,
2237     // e.g. (FOO - :lower16:BAR) isn't legal.
2238     ARMMCExpr::VariantKind RefKind;
2239     if (parsePrefix(RefKind))
2240       return true;
2241
2242     const MCExpr *SubExprVal;
2243     if (getParser().ParseExpression(SubExprVal))
2244       return true;
2245
2246     const MCExpr *ExprVal = ARMMCExpr::Create(RefKind, SubExprVal,
2247                                                    getContext());
2248     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
2249     Operands.push_back(ARMOperand::CreateImm(ExprVal, S, E));
2250     return false;
2251   }
2252   }
2253 }
2254
2255 // parsePrefix - Parse ARM 16-bit relocations expression prefix, i.e.
2256 //  :lower16: and :upper16:.
2257 bool ARMAsmParser::parsePrefix(ARMMCExpr::VariantKind &RefKind) {
2258   RefKind = ARMMCExpr::VK_ARM_None;
2259
2260   // :lower16: and :upper16: modifiers
2261   assert(getLexer().is(AsmToken::Colon) && "expected a :");
2262   Parser.Lex(); // Eat ':'
2263
2264   if (getLexer().isNot(AsmToken::Identifier)) {
2265     Error(Parser.getTok().getLoc(), "expected prefix identifier in operand");
2266     return true;
2267   }
2268
2269   StringRef IDVal = Parser.getTok().getIdentifier();
2270   if (IDVal == "lower16") {
2271     RefKind = ARMMCExpr::VK_ARM_LO16;
2272   } else if (IDVal == "upper16") {
2273     RefKind = ARMMCExpr::VK_ARM_HI16;
2274   } else {
2275     Error(Parser.getTok().getLoc(), "unexpected prefix in operand");
2276     return true;
2277   }
2278   Parser.Lex();
2279
2280   if (getLexer().isNot(AsmToken::Colon)) {
2281     Error(Parser.getTok().getLoc(), "unexpected token after prefix");
2282     return true;
2283   }
2284   Parser.Lex(); // Eat the last ':'
2285   return false;
2286 }
2287
2288 const MCExpr *
2289 ARMAsmParser::applyPrefixToExpr(const MCExpr *E,
2290                                 MCSymbolRefExpr::VariantKind Variant) {
2291   // Recurse over the given expression, rebuilding it to apply the given variant
2292   // to the leftmost symbol.
2293   if (Variant == MCSymbolRefExpr::VK_None)
2294     return E;
2295
2296   switch (E->getKind()) {
2297   case MCExpr::Target:
2298     llvm_unreachable("Can't handle target expr yet");
2299   case MCExpr::Constant:
2300     llvm_unreachable("Can't handle lower16/upper16 of constant yet");
2301
2302   case MCExpr::SymbolRef: {
2303     const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
2304
2305     if (SRE->getKind() != MCSymbolRefExpr::VK_None)
2306       return 0;
2307
2308     return MCSymbolRefExpr::Create(&SRE->getSymbol(), Variant, getContext());
2309   }
2310
2311   case MCExpr::Unary:
2312     llvm_unreachable("Can't handle unary expressions yet");
2313
2314   case MCExpr::Binary: {
2315     const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
2316     const MCExpr *LHS = applyPrefixToExpr(BE->getLHS(), Variant);
2317     const MCExpr *RHS = BE->getRHS();
2318     if (!LHS)
2319       return 0;
2320
2321     return MCBinaryExpr::Create(BE->getOpcode(), LHS, RHS, getContext());
2322   }
2323   }
2324
2325   assert(0 && "Invalid expression kind!");
2326   return 0;
2327 }
2328
2329 /// \brief Given a mnemonic, split out possible predication code and carry
2330 /// setting letters to form a canonical mnemonic and flags.
2331 //
2332 // FIXME: Would be nice to autogen this.
2333 StringRef ARMAsmParser::splitMnemonic(StringRef Mnemonic,
2334                                       unsigned &PredicationCode,
2335                                       bool &CarrySetting,
2336                                       unsigned &ProcessorIMod) {
2337   PredicationCode = ARMCC::AL;
2338   CarrySetting = false;
2339   ProcessorIMod = 0;
2340
2341   // Ignore some mnemonics we know aren't predicated forms.
2342   //
2343   // FIXME: Would be nice to autogen this.
2344   if ((Mnemonic == "movs" && isThumb()) ||
2345       Mnemonic == "teq"   || Mnemonic == "vceq"   || Mnemonic == "svc"   ||
2346       Mnemonic == "mls"   || Mnemonic == "smmls"  || Mnemonic == "vcls"  ||
2347       Mnemonic == "vmls"  || Mnemonic == "vnmls"  || Mnemonic == "vacge" ||
2348       Mnemonic == "vcge"  || Mnemonic == "vclt"   || Mnemonic == "vacgt" ||
2349       Mnemonic == "vcgt"  || Mnemonic == "vcle"   || Mnemonic == "smlal" ||
2350       Mnemonic == "umaal" || Mnemonic == "umlal"  || Mnemonic == "vabal" ||
2351       Mnemonic == "vmlal" || Mnemonic == "vpadal" || Mnemonic == "vqdmlal")
2352     return Mnemonic;
2353
2354   // First, split out any predication code. Ignore mnemonics we know aren't
2355   // predicated but do have a carry-set and so weren't caught above.
2356   if (Mnemonic != "adcs" && Mnemonic != "bics" && Mnemonic != "movs" &&
2357       Mnemonic != "muls" && Mnemonic != "smlals" && Mnemonic != "smulls" &&
2358       Mnemonic != "umlals" && Mnemonic != "umulls") {
2359     unsigned CC = StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2))
2360       .Case("eq", ARMCC::EQ)
2361       .Case("ne", ARMCC::NE)
2362       .Case("hs", ARMCC::HS)
2363       .Case("cs", ARMCC::HS)
2364       .Case("lo", ARMCC::LO)
2365       .Case("cc", ARMCC::LO)
2366       .Case("mi", ARMCC::MI)
2367       .Case("pl", ARMCC::PL)
2368       .Case("vs", ARMCC::VS)
2369       .Case("vc", ARMCC::VC)
2370       .Case("hi", ARMCC::HI)
2371       .Case("ls", ARMCC::LS)
2372       .Case("ge", ARMCC::GE)
2373       .Case("lt", ARMCC::LT)
2374       .Case("gt", ARMCC::GT)
2375       .Case("le", ARMCC::LE)
2376       .Case("al", ARMCC::AL)
2377       .Default(~0U);
2378     if (CC != ~0U) {
2379       Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 2);
2380       PredicationCode = CC;
2381     }
2382   }
2383
2384   // Next, determine if we have a carry setting bit. We explicitly ignore all
2385   // the instructions we know end in 's'.
2386   if (Mnemonic.endswith("s") &&
2387       !(Mnemonic == "asrs" || Mnemonic == "cps" || Mnemonic == "mls" ||
2388         Mnemonic == "mrs" || Mnemonic == "smmls" || Mnemonic == "vabs" ||
2389         Mnemonic == "vcls" || Mnemonic == "vmls" || Mnemonic == "vmrs" ||
2390         Mnemonic == "vnmls" || Mnemonic == "vqabs" || Mnemonic == "vrecps" ||
2391         Mnemonic == "vrsqrts" || (Mnemonic == "movs" && isThumb()))) {
2392     Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 1);
2393     CarrySetting = true;
2394   }
2395
2396   // The "cps" instruction can have a interrupt mode operand which is glued into
2397   // the mnemonic. Check if this is the case, split it and parse the imod op
2398   if (Mnemonic.startswith("cps")) {
2399     // Split out any imod code.
2400     unsigned IMod =
2401       StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2, 2))
2402       .Case("ie", ARM_PROC::IE)
2403       .Case("id", ARM_PROC::ID)
2404       .Default(~0U);
2405     if (IMod != ~0U) {
2406       Mnemonic = Mnemonic.slice(0, Mnemonic.size()-2);
2407       ProcessorIMod = IMod;
2408     }
2409   }
2410
2411   return Mnemonic;
2412 }
2413
2414 /// \brief Given a canonical mnemonic, determine if the instruction ever allows
2415 /// inclusion of carry set or predication code operands.
2416 //
2417 // FIXME: It would be nice to autogen this.
2418 void ARMAsmParser::
2419 getMnemonicAcceptInfo(StringRef Mnemonic, bool &CanAcceptCarrySet,
2420                       bool &CanAcceptPredicationCode) {
2421   if (Mnemonic == "and" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
2422       Mnemonic == "rrx" || Mnemonic == "ror" || Mnemonic == "sub" ||
2423       Mnemonic == "smull" || Mnemonic == "add" || Mnemonic == "adc" ||
2424       Mnemonic == "mul" || Mnemonic == "bic" || Mnemonic == "asr" ||
2425       Mnemonic == "umlal" || Mnemonic == "orr" || Mnemonic == "mvn" ||
2426       Mnemonic == "rsb" || Mnemonic == "rsc" || Mnemonic == "orn" ||
2427       Mnemonic == "sbc" || Mnemonic == "mla" || Mnemonic == "umull" ||
2428       Mnemonic == "eor" || Mnemonic == "smlal" ||
2429       (Mnemonic == "mov" && !isThumbOne())) {
2430     CanAcceptCarrySet = true;
2431   } else {
2432     CanAcceptCarrySet = false;
2433   }
2434
2435   if (Mnemonic == "cbnz" || Mnemonic == "setend" || Mnemonic == "dmb" ||
2436       Mnemonic == "cps" || Mnemonic == "mcr2" || Mnemonic == "it" ||
2437       Mnemonic == "mcrr2" || Mnemonic == "cbz" || Mnemonic == "cdp2" ||
2438       Mnemonic == "trap" || Mnemonic == "mrc2" || Mnemonic == "mrrc2" ||
2439       Mnemonic == "dsb" || Mnemonic == "isb" || Mnemonic == "clrex" ||
2440       Mnemonic == "setend" ||
2441       Mnemonic.startswith("cps") || (Mnemonic == "movs" && isThumb())) {
2442     CanAcceptPredicationCode = false;
2443   } else {
2444     CanAcceptPredicationCode = true;
2445   }
2446
2447   if (isThumb())
2448     if (Mnemonic == "bkpt" || Mnemonic == "mcr" || Mnemonic == "mcrr" ||
2449         Mnemonic == "mrc" || Mnemonic == "mrrc" || Mnemonic == "cdp")
2450       CanAcceptPredicationCode = false;
2451 }
2452
2453 /// Parse an arm instruction mnemonic followed by its operands.
2454 bool ARMAsmParser::ParseInstruction(StringRef Name, SMLoc NameLoc,
2455                                SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2456   // Create the leading tokens for the mnemonic, split by '.' characters.
2457   size_t Start = 0, Next = Name.find('.');
2458   StringRef Mnemonic = Name.slice(Start, Next);
2459
2460   // Split out the predication code and carry setting flag from the mnemonic.
2461   unsigned PredicationCode;
2462   unsigned ProcessorIMod;
2463   bool CarrySetting;
2464   Mnemonic = splitMnemonic(Mnemonic, PredicationCode, CarrySetting,
2465                            ProcessorIMod);
2466
2467   Operands.push_back(ARMOperand::CreateToken(Mnemonic, NameLoc));
2468
2469   // FIXME: This is all a pretty gross hack. We should automatically handle
2470   // optional operands like this via tblgen.
2471
2472   // Next, add the CCOut and ConditionCode operands, if needed.
2473   //
2474   // For mnemonics which can ever incorporate a carry setting bit or predication
2475   // code, our matching model involves us always generating CCOut and
2476   // ConditionCode operands to match the mnemonic "as written" and then we let
2477   // the matcher deal with finding the right instruction or generating an
2478   // appropriate error.
2479   bool CanAcceptCarrySet, CanAcceptPredicationCode;
2480   getMnemonicAcceptInfo(Mnemonic, CanAcceptCarrySet, CanAcceptPredicationCode);
2481
2482   // If we had a carry-set on an instruction that can't do that, issue an
2483   // error.
2484   if (!CanAcceptCarrySet && CarrySetting) {
2485     Parser.EatToEndOfStatement();
2486     return Error(NameLoc, "instruction '" + Mnemonic +
2487                  "' can not set flags, but 's' suffix specified");
2488   }
2489   // If we had a predication code on an instruction that can't do that, issue an
2490   // error.
2491   if (!CanAcceptPredicationCode && PredicationCode != ARMCC::AL) {
2492     Parser.EatToEndOfStatement();
2493     return Error(NameLoc, "instruction '" + Mnemonic +
2494                  "' is not predicable, but condition code specified");
2495   }
2496
2497   // Add the carry setting operand, if necessary.
2498   //
2499   // FIXME: It would be awesome if we could somehow invent a location such that
2500   // match errors on this operand would print a nice diagnostic about how the
2501   // 's' character in the mnemonic resulted in a CCOut operand.
2502   if (CanAcceptCarrySet)
2503     Operands.push_back(ARMOperand::CreateCCOut(CarrySetting ? ARM::CPSR : 0,
2504                                                NameLoc));
2505
2506   // Add the predication code operand, if necessary.
2507   if (CanAcceptPredicationCode) {
2508     Operands.push_back(ARMOperand::CreateCondCode(
2509                          ARMCC::CondCodes(PredicationCode), NameLoc));
2510   }
2511
2512   // Add the processor imod operand, if necessary.
2513   if (ProcessorIMod) {
2514     Operands.push_back(ARMOperand::CreateImm(
2515           MCConstantExpr::Create(ProcessorIMod, getContext()),
2516                                  NameLoc, NameLoc));
2517   } else {
2518     // This mnemonic can't ever accept a imod, but the user wrote
2519     // one (or misspelled another mnemonic).
2520
2521     // FIXME: Issue a nice error.
2522   }
2523
2524   // Add the remaining tokens in the mnemonic.
2525   while (Next != StringRef::npos) {
2526     Start = Next;
2527     Next = Name.find('.', Start + 1);
2528     StringRef ExtraToken = Name.slice(Start, Next);
2529
2530     Operands.push_back(ARMOperand::CreateToken(ExtraToken, NameLoc));
2531   }
2532
2533   // Read the remaining operands.
2534   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2535     // Read the first operand.
2536     if (parseOperand(Operands, Mnemonic)) {
2537       Parser.EatToEndOfStatement();
2538       return true;
2539     }
2540
2541     while (getLexer().is(AsmToken::Comma)) {
2542       Parser.Lex();  // Eat the comma.
2543
2544       // Parse and remember the operand.
2545       if (parseOperand(Operands, Mnemonic)) {
2546         Parser.EatToEndOfStatement();
2547         return true;
2548       }
2549     }
2550   }
2551
2552   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2553     Parser.EatToEndOfStatement();
2554     return TokError("unexpected token in argument list");
2555   }
2556
2557   Parser.Lex(); // Consume the EndOfStatement
2558
2559
2560   // The 'mov' mnemonic is special. One variant has a cc_out operand, while
2561   // another does not. Specifically, the MOVW instruction does not. So we
2562   // special case it here and remove the defaulted (non-setting) cc_out
2563   // operand if that's the instruction we're trying to match.
2564   //
2565   // We do this post-processing of the explicit operands rather than just
2566   // conditionally adding the cc_out in the first place because we need
2567   // to check the type of the parsed immediate operand.
2568   if (Mnemonic == "mov" && Operands.size() > 4 &&
2569       !static_cast<ARMOperand*>(Operands[4])->isARMSOImm() &&
2570       static_cast<ARMOperand*>(Operands[4])->isImm0_65535Expr() &&
2571       static_cast<ARMOperand*>(Operands[1])->getReg() == 0) {
2572     ARMOperand *Op = static_cast<ARMOperand*>(Operands[1]);
2573     Operands.erase(Operands.begin() + 1);
2574     delete Op;
2575   }
2576
2577   return false;
2578 }
2579
2580 // Validate context-sensitive operand constraints.
2581 // FIXME: We would really like to be able to tablegen'erate this.
2582 bool ARMAsmParser::
2583 validateInstruction(MCInst &Inst,
2584                     const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2585   switch (Inst.getOpcode()) {
2586   case ARM::LDREXD: {
2587     // Rt2 must be Rt + 1.
2588     unsigned Rt = getARMRegisterNumbering(Inst.getOperand(0).getReg());
2589     unsigned Rt2 = getARMRegisterNumbering(Inst.getOperand(1).getReg());
2590     if (Rt2 != Rt + 1)
2591       return Error(Operands[3]->getStartLoc(),
2592                    "destination operands must be sequential");
2593     return false;
2594   }
2595   case ARM::STREXD: {
2596     // Rt2 must be Rt + 1.
2597     unsigned Rt = getARMRegisterNumbering(Inst.getOperand(1).getReg());
2598     unsigned Rt2 = getARMRegisterNumbering(Inst.getOperand(2).getReg());
2599     if (Rt2 != Rt + 1)
2600       return Error(Operands[4]->getStartLoc(),
2601                    "source operands must be sequential");
2602     return false;
2603   }
2604   case ARM::SBFX:
2605   case ARM::UBFX: {
2606     // width must be in range [1, 32-lsb]
2607     unsigned lsb = Inst.getOperand(2).getImm();
2608     unsigned widthm1 = Inst.getOperand(3).getImm();
2609     if (widthm1 >= 32 - lsb)
2610       return Error(Operands[5]->getStartLoc(),
2611                    "bitfield width must be in range [1,32-lsb]");
2612   }
2613   }
2614
2615   return false;
2616 }
2617
2618 bool ARMAsmParser::
2619 MatchAndEmitInstruction(SMLoc IDLoc,
2620                         SmallVectorImpl<MCParsedAsmOperand*> &Operands,
2621                         MCStreamer &Out) {
2622   MCInst Inst;
2623   unsigned ErrorInfo;
2624   MatchResultTy MatchResult;
2625   MatchResult = MatchInstructionImpl(Operands, Inst, ErrorInfo);
2626   switch (MatchResult) {
2627   case Match_Success:
2628     // Context sensitive operand constraints aren't handled by the matcher,
2629     // so check them here.
2630     if (validateInstruction(Inst, Operands))
2631       return true;
2632
2633     Out.EmitInstruction(Inst);
2634     return false;
2635   case Match_MissingFeature:
2636     Error(IDLoc, "instruction requires a CPU feature not currently enabled");
2637     return true;
2638   case Match_InvalidOperand: {
2639     SMLoc ErrorLoc = IDLoc;
2640     if (ErrorInfo != ~0U) {
2641       if (ErrorInfo >= Operands.size())
2642         return Error(IDLoc, "too few operands for instruction");
2643
2644       ErrorLoc = ((ARMOperand*)Operands[ErrorInfo])->getStartLoc();
2645       if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
2646     }
2647
2648     return Error(ErrorLoc, "invalid operand for instruction");
2649   }
2650   case Match_MnemonicFail:
2651     return Error(IDLoc, "unrecognized instruction mnemonic");
2652   case Match_ConversionFail:
2653     return Error(IDLoc, "unable to convert operands to instruction");
2654   }
2655
2656   llvm_unreachable("Implement any new match types added!");
2657   return true;
2658 }
2659
2660 /// parseDirective parses the arm specific directives
2661 bool ARMAsmParser::ParseDirective(AsmToken DirectiveID) {
2662   StringRef IDVal = DirectiveID.getIdentifier();
2663   if (IDVal == ".word")
2664     return parseDirectiveWord(4, DirectiveID.getLoc());
2665   else if (IDVal == ".thumb")
2666     return parseDirectiveThumb(DirectiveID.getLoc());
2667   else if (IDVal == ".thumb_func")
2668     return parseDirectiveThumbFunc(DirectiveID.getLoc());
2669   else if (IDVal == ".code")
2670     return parseDirectiveCode(DirectiveID.getLoc());
2671   else if (IDVal == ".syntax")
2672     return parseDirectiveSyntax(DirectiveID.getLoc());
2673   return true;
2674 }
2675
2676 /// parseDirectiveWord
2677 ///  ::= .word [ expression (, expression)* ]
2678 bool ARMAsmParser::parseDirectiveWord(unsigned Size, SMLoc L) {
2679   if (getLexer().isNot(AsmToken::EndOfStatement)) {
2680     for (;;) {
2681       const MCExpr *Value;
2682       if (getParser().ParseExpression(Value))
2683         return true;
2684
2685       getParser().getStreamer().EmitValue(Value, Size, 0/*addrspace*/);
2686
2687       if (getLexer().is(AsmToken::EndOfStatement))
2688         break;
2689
2690       // FIXME: Improve diagnostic.
2691       if (getLexer().isNot(AsmToken::Comma))
2692         return Error(L, "unexpected token in directive");
2693       Parser.Lex();
2694     }
2695   }
2696
2697   Parser.Lex();
2698   return false;
2699 }
2700
2701 /// parseDirectiveThumb
2702 ///  ::= .thumb
2703 bool ARMAsmParser::parseDirectiveThumb(SMLoc L) {
2704   if (getLexer().isNot(AsmToken::EndOfStatement))
2705     return Error(L, "unexpected token in directive");
2706   Parser.Lex();
2707
2708   // TODO: set thumb mode
2709   // TODO: tell the MC streamer the mode
2710   // getParser().getStreamer().Emit???();
2711   return false;
2712 }
2713
2714 /// parseDirectiveThumbFunc
2715 ///  ::= .thumbfunc symbol_name
2716 bool ARMAsmParser::parseDirectiveThumbFunc(SMLoc L) {
2717   const MCAsmInfo &MAI = getParser().getStreamer().getContext().getAsmInfo();
2718   bool isMachO = MAI.hasSubsectionsViaSymbols();
2719   StringRef Name;
2720
2721   // Darwin asm has function name after .thumb_func direction
2722   // ELF doesn't
2723   if (isMachO) {
2724     const AsmToken &Tok = Parser.getTok();
2725     if (Tok.isNot(AsmToken::Identifier) && Tok.isNot(AsmToken::String))
2726       return Error(L, "unexpected token in .thumb_func directive");
2727     Name = Tok.getString();
2728     Parser.Lex(); // Consume the identifier token.
2729   }
2730
2731   if (getLexer().isNot(AsmToken::EndOfStatement))
2732     return Error(L, "unexpected token in directive");
2733   Parser.Lex();
2734
2735   // FIXME: assuming function name will be the line following .thumb_func
2736   if (!isMachO) {
2737     Name = Parser.getTok().getString();
2738   }
2739
2740   // Mark symbol as a thumb symbol.
2741   MCSymbol *Func = getParser().getContext().GetOrCreateSymbol(Name);
2742   getParser().getStreamer().EmitThumbFunc(Func);
2743   return false;
2744 }
2745
2746 /// parseDirectiveSyntax
2747 ///  ::= .syntax unified | divided
2748 bool ARMAsmParser::parseDirectiveSyntax(SMLoc L) {
2749   const AsmToken &Tok = Parser.getTok();
2750   if (Tok.isNot(AsmToken::Identifier))
2751     return Error(L, "unexpected token in .syntax directive");
2752   StringRef Mode = Tok.getString();
2753   if (Mode == "unified" || Mode == "UNIFIED")
2754     Parser.Lex();
2755   else if (Mode == "divided" || Mode == "DIVIDED")
2756     return Error(L, "'.syntax divided' arm asssembly not supported");
2757   else
2758     return Error(L, "unrecognized syntax mode in .syntax directive");
2759
2760   if (getLexer().isNot(AsmToken::EndOfStatement))
2761     return Error(Parser.getTok().getLoc(), "unexpected token in directive");
2762   Parser.Lex();
2763
2764   // TODO tell the MC streamer the mode
2765   // getParser().getStreamer().Emit???();
2766   return false;
2767 }
2768
2769 /// parseDirectiveCode
2770 ///  ::= .code 16 | 32
2771 bool ARMAsmParser::parseDirectiveCode(SMLoc L) {
2772   const AsmToken &Tok = Parser.getTok();
2773   if (Tok.isNot(AsmToken::Integer))
2774     return Error(L, "unexpected token in .code directive");
2775   int64_t Val = Parser.getTok().getIntVal();
2776   if (Val == 16)
2777     Parser.Lex();
2778   else if (Val == 32)
2779     Parser.Lex();
2780   else
2781     return Error(L, "invalid operand to .code directive");
2782
2783   if (getLexer().isNot(AsmToken::EndOfStatement))
2784     return Error(Parser.getTok().getLoc(), "unexpected token in directive");
2785   Parser.Lex();
2786
2787   if (Val == 16) {
2788     if (!isThumb()) {
2789       SwitchMode();
2790       getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
2791     }
2792   } else {
2793     if (isThumb()) {
2794       SwitchMode();
2795       getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
2796     }
2797   }
2798
2799   return false;
2800 }
2801
2802 extern "C" void LLVMInitializeARMAsmLexer();
2803
2804 /// Force static initialization.
2805 extern "C" void LLVMInitializeARMAsmParser() {
2806   RegisterMCAsmParser<ARMAsmParser> X(TheARMTarget);
2807   RegisterMCAsmParser<ARMAsmParser> Y(TheThumbTarget);
2808   LLVMInitializeARMAsmLexer();
2809 }
2810
2811 #define GET_REGISTER_MATCHER
2812 #define GET_MATCHER_IMPLEMENTATION
2813 #include "ARMGenAsmMatcher.inc"