30bed29949cba9e3598cf163b06be2879d5cad16
[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/MCInstrDesc.h"
22 #include "llvm/MC/MCRegisterInfo.h"
23 #include "llvm/MC/MCSubtargetInfo.h"
24 #include "llvm/MC/MCTargetAsmParser.h"
25 #include "llvm/Support/MathExtras.h"
26 #include "llvm/Support/SourceMgr.h"
27 #include "llvm/Support/TargetRegistry.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/ADT/BitVector.h"
30 #include "llvm/ADT/OwningPtr.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/ADT/SmallVector.h"
33 #include "llvm/ADT/StringExtras.h"
34 #include "llvm/ADT/StringSwitch.h"
35 #include "llvm/ADT/Twine.h"
36
37 using namespace llvm;
38
39 namespace {
40
41 class ARMOperand;
42
43 class ARMAsmParser : public MCTargetAsmParser {
44   MCSubtargetInfo &STI;
45   MCAsmParser &Parser;
46
47   struct {
48     ARMCC::CondCodes Cond;    // Condition for IT block.
49     unsigned Mask:4;          // Condition mask for instructions.
50                               // Starting at first 1 (from lsb).
51                               //   '1'  condition as indicated in IT.
52                               //   '0'  inverse of condition (else).
53                               // Count of instructions in IT block is
54                               // 4 - trailingzeroes(mask)
55
56     bool FirstCond;           // Explicit flag for when we're parsing the
57                               // First instruction in the IT block. It's
58                               // implied in the mask, so needs special
59                               // handling.
60
61     unsigned CurPosition;     // Current position in parsing of IT
62                               // block. In range [0,3]. Initialized
63                               // according to count of instructions in block.
64                               // ~0U if no active IT block.
65   } ITState;
66   bool inITBlock() { return ITState.CurPosition != ~0U;}
67   void forwardITPosition() {
68     if (!inITBlock()) return;
69     // Move to the next instruction in the IT block, if there is one. If not,
70     // mark the block as done.
71     unsigned TZ = CountTrailingZeros_32(ITState.Mask);
72     if (++ITState.CurPosition == 5 - TZ)
73       ITState.CurPosition = ~0U; // Done with the IT block after this.
74   }
75
76
77   MCAsmParser &getParser() const { return Parser; }
78   MCAsmLexer &getLexer() const { return Parser.getLexer(); }
79
80   void Warning(SMLoc L, const Twine &Msg) { Parser.Warning(L, Msg); }
81   bool Error(SMLoc L, const Twine &Msg) { return Parser.Error(L, Msg); }
82
83   int tryParseRegister();
84   bool tryParseRegisterWithWriteBack(SmallVectorImpl<MCParsedAsmOperand*> &);
85   int tryParseShiftRegister(SmallVectorImpl<MCParsedAsmOperand*> &);
86   bool parseRegisterList(SmallVectorImpl<MCParsedAsmOperand*> &);
87   bool parseMemory(SmallVectorImpl<MCParsedAsmOperand*> &);
88   bool parseOperand(SmallVectorImpl<MCParsedAsmOperand*> &, StringRef Mnemonic);
89   bool parsePrefix(ARMMCExpr::VariantKind &RefKind);
90   bool parseMemRegOffsetShift(ARM_AM::ShiftOpc &ShiftType,
91                               unsigned &ShiftAmount);
92   bool parseDirectiveWord(unsigned Size, SMLoc L);
93   bool parseDirectiveThumb(SMLoc L);
94   bool parseDirectiveThumbFunc(SMLoc L);
95   bool parseDirectiveCode(SMLoc L);
96   bool parseDirectiveSyntax(SMLoc L);
97
98   StringRef splitMnemonic(StringRef Mnemonic, unsigned &PredicationCode,
99                           bool &CarrySetting, unsigned &ProcessorIMod,
100                           StringRef &ITMask);
101   void getMnemonicAcceptInfo(StringRef Mnemonic, bool &CanAcceptCarrySet,
102                              bool &CanAcceptPredicationCode);
103
104   bool isThumb() const {
105     // FIXME: Can tablegen auto-generate this?
106     return (STI.getFeatureBits() & ARM::ModeThumb) != 0;
107   }
108   bool isThumbOne() const {
109     return isThumb() && (STI.getFeatureBits() & ARM::FeatureThumb2) == 0;
110   }
111   bool isThumbTwo() const {
112     return isThumb() && (STI.getFeatureBits() & ARM::FeatureThumb2);
113   }
114   bool hasV6Ops() const {
115     return STI.getFeatureBits() & ARM::HasV6Ops;
116   }
117   void SwitchMode() {
118     unsigned FB = ComputeAvailableFeatures(STI.ToggleFeature(ARM::ModeThumb));
119     setAvailableFeatures(FB);
120   }
121
122   /// @name Auto-generated Match Functions
123   /// {
124
125 #define GET_ASSEMBLER_HEADER
126 #include "ARMGenAsmMatcher.inc"
127
128   /// }
129
130   OperandMatchResultTy parseITCondCode(SmallVectorImpl<MCParsedAsmOperand*>&);
131   OperandMatchResultTy parseCoprocNumOperand(
132     SmallVectorImpl<MCParsedAsmOperand*>&);
133   OperandMatchResultTy parseCoprocRegOperand(
134     SmallVectorImpl<MCParsedAsmOperand*>&);
135   OperandMatchResultTy parseMemBarrierOptOperand(
136     SmallVectorImpl<MCParsedAsmOperand*>&);
137   OperandMatchResultTy parseProcIFlagsOperand(
138     SmallVectorImpl<MCParsedAsmOperand*>&);
139   OperandMatchResultTy parseMSRMaskOperand(
140     SmallVectorImpl<MCParsedAsmOperand*>&);
141   OperandMatchResultTy parsePKHImm(SmallVectorImpl<MCParsedAsmOperand*> &O,
142                                    StringRef Op, int Low, int High);
143   OperandMatchResultTy parsePKHLSLImm(SmallVectorImpl<MCParsedAsmOperand*> &O) {
144     return parsePKHImm(O, "lsl", 0, 31);
145   }
146   OperandMatchResultTy parsePKHASRImm(SmallVectorImpl<MCParsedAsmOperand*> &O) {
147     return parsePKHImm(O, "asr", 1, 32);
148   }
149   OperandMatchResultTy parseSetEndImm(SmallVectorImpl<MCParsedAsmOperand*>&);
150   OperandMatchResultTy parseShifterImm(SmallVectorImpl<MCParsedAsmOperand*>&);
151   OperandMatchResultTy parseRotImm(SmallVectorImpl<MCParsedAsmOperand*>&);
152   OperandMatchResultTy parseBitfield(SmallVectorImpl<MCParsedAsmOperand*>&);
153   OperandMatchResultTy parsePostIdxReg(SmallVectorImpl<MCParsedAsmOperand*>&);
154   OperandMatchResultTy parseAM3Offset(SmallVectorImpl<MCParsedAsmOperand*>&);
155
156   // Asm Match Converter Methods
157   bool cvtT2LdrdPre(MCInst &Inst, unsigned Opcode,
158                     const SmallVectorImpl<MCParsedAsmOperand*> &);
159   bool cvtT2StrdPre(MCInst &Inst, unsigned Opcode,
160                     const SmallVectorImpl<MCParsedAsmOperand*> &);
161   bool cvtLdWriteBackRegT2AddrModeImm8(MCInst &Inst, unsigned Opcode,
162                                   const SmallVectorImpl<MCParsedAsmOperand*> &);
163   bool cvtStWriteBackRegT2AddrModeImm8(MCInst &Inst, unsigned Opcode,
164                                   const SmallVectorImpl<MCParsedAsmOperand*> &);
165   bool cvtLdWriteBackRegAddrMode2(MCInst &Inst, unsigned Opcode,
166                                   const SmallVectorImpl<MCParsedAsmOperand*> &);
167   bool cvtLdWriteBackRegAddrModeImm12(MCInst &Inst, unsigned Opcode,
168                                   const SmallVectorImpl<MCParsedAsmOperand*> &);
169   bool cvtStWriteBackRegAddrModeImm12(MCInst &Inst, unsigned Opcode,
170                                   const SmallVectorImpl<MCParsedAsmOperand*> &);
171   bool cvtStWriteBackRegAddrMode2(MCInst &Inst, unsigned Opcode,
172                                   const SmallVectorImpl<MCParsedAsmOperand*> &);
173   bool cvtStWriteBackRegAddrMode3(MCInst &Inst, unsigned Opcode,
174                                   const SmallVectorImpl<MCParsedAsmOperand*> &);
175   bool cvtLdExtTWriteBackImm(MCInst &Inst, unsigned Opcode,
176                              const SmallVectorImpl<MCParsedAsmOperand*> &);
177   bool cvtLdExtTWriteBackReg(MCInst &Inst, unsigned Opcode,
178                              const SmallVectorImpl<MCParsedAsmOperand*> &);
179   bool cvtStExtTWriteBackImm(MCInst &Inst, unsigned Opcode,
180                              const SmallVectorImpl<MCParsedAsmOperand*> &);
181   bool cvtStExtTWriteBackReg(MCInst &Inst, unsigned Opcode,
182                              const SmallVectorImpl<MCParsedAsmOperand*> &);
183   bool cvtLdrdPre(MCInst &Inst, unsigned Opcode,
184                   const SmallVectorImpl<MCParsedAsmOperand*> &);
185   bool cvtStrdPre(MCInst &Inst, unsigned Opcode,
186                   const SmallVectorImpl<MCParsedAsmOperand*> &);
187   bool cvtLdWriteBackRegAddrMode3(MCInst &Inst, unsigned Opcode,
188                                   const SmallVectorImpl<MCParsedAsmOperand*> &);
189   bool cvtThumbMultiply(MCInst &Inst, unsigned Opcode,
190                         const SmallVectorImpl<MCParsedAsmOperand*> &);
191
192   bool validateInstruction(MCInst &Inst,
193                            const SmallVectorImpl<MCParsedAsmOperand*> &Ops);
194   void processInstruction(MCInst &Inst,
195                           const SmallVectorImpl<MCParsedAsmOperand*> &Ops);
196   bool shouldOmitCCOutOperand(StringRef Mnemonic,
197                               SmallVectorImpl<MCParsedAsmOperand*> &Operands);
198
199 public:
200   enum ARMMatchResultTy {
201     Match_RequiresITBlock = FIRST_TARGET_MATCH_RESULT_TY,
202     Match_RequiresNotITBlock,
203     Match_RequiresV6,
204     Match_RequiresThumb2
205   };
206
207   ARMAsmParser(MCSubtargetInfo &_STI, MCAsmParser &_Parser)
208     : MCTargetAsmParser(), STI(_STI), Parser(_Parser) {
209     MCAsmParserExtension::Initialize(_Parser);
210
211     // Initialize the set of available features.
212     setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
213
214     // Not in an ITBlock to start with.
215     ITState.CurPosition = ~0U;
216   }
217
218   // Implementation of the MCTargetAsmParser interface:
219   bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc);
220   bool ParseInstruction(StringRef Name, SMLoc NameLoc,
221                         SmallVectorImpl<MCParsedAsmOperand*> &Operands);
222   bool ParseDirective(AsmToken DirectiveID);
223
224   unsigned checkTargetMatchPredicate(MCInst &Inst);
225
226   bool MatchAndEmitInstruction(SMLoc IDLoc,
227                                SmallVectorImpl<MCParsedAsmOperand*> &Operands,
228                                MCStreamer &Out);
229 };
230 } // end anonymous namespace
231
232 namespace {
233
234 /// ARMOperand - Instances of this class represent a parsed ARM machine
235 /// instruction.
236 class ARMOperand : public MCParsedAsmOperand {
237   enum KindTy {
238     CondCode,
239     CCOut,
240     ITCondMask,
241     CoprocNum,
242     CoprocReg,
243     Immediate,
244     MemBarrierOpt,
245     Memory,
246     PostIndexRegister,
247     MSRMask,
248     ProcIFlags,
249     Register,
250     RegisterList,
251     DPRRegisterList,
252     SPRRegisterList,
253     ShiftedRegister,
254     ShiftedImmediate,
255     ShifterImmediate,
256     RotateImmediate,
257     BitfieldDescriptor,
258     Token
259   } Kind;
260
261   SMLoc StartLoc, EndLoc;
262   SmallVector<unsigned, 8> Registers;
263
264   union {
265     struct {
266       ARMCC::CondCodes Val;
267     } CC;
268
269     struct {
270       unsigned Val;
271     } Cop;
272
273     struct {
274       unsigned Mask:4;
275     } ITMask;
276
277     struct {
278       ARM_MB::MemBOpt Val;
279     } MBOpt;
280
281     struct {
282       ARM_PROC::IFlags Val;
283     } IFlags;
284
285     struct {
286       unsigned Val;
287     } MMask;
288
289     struct {
290       const char *Data;
291       unsigned Length;
292     } Tok;
293
294     struct {
295       unsigned RegNum;
296     } Reg;
297
298     struct {
299       const MCExpr *Val;
300     } Imm;
301
302     /// Combined record for all forms of ARM address expressions.
303     struct {
304       unsigned BaseRegNum;
305       // Offset is in OffsetReg or OffsetImm. If both are zero, no offset
306       // was specified.
307       const MCConstantExpr *OffsetImm;  // Offset immediate value
308       unsigned OffsetRegNum;    // Offset register num, when OffsetImm == NULL
309       ARM_AM::ShiftOpc ShiftType; // Shift type for OffsetReg
310       unsigned ShiftImm;      // shift for OffsetReg.
311       unsigned isNegative : 1;  // Negated OffsetReg? (~'U' bit)
312     } Mem;
313
314     struct {
315       unsigned RegNum;
316       bool isAdd;
317       ARM_AM::ShiftOpc ShiftTy;
318       unsigned ShiftImm;
319     } PostIdxReg;
320
321     struct {
322       bool isASR;
323       unsigned Imm;
324     } ShifterImm;
325     struct {
326       ARM_AM::ShiftOpc ShiftTy;
327       unsigned SrcReg;
328       unsigned ShiftReg;
329       unsigned ShiftImm;
330     } RegShiftedReg;
331     struct {
332       ARM_AM::ShiftOpc ShiftTy;
333       unsigned SrcReg;
334       unsigned ShiftImm;
335     } RegShiftedImm;
336     struct {
337       unsigned Imm;
338     } RotImm;
339     struct {
340       unsigned LSB;
341       unsigned Width;
342     } Bitfield;
343   };
344
345   ARMOperand(KindTy K) : MCParsedAsmOperand(), Kind(K) {}
346 public:
347   ARMOperand(const ARMOperand &o) : MCParsedAsmOperand() {
348     Kind = o.Kind;
349     StartLoc = o.StartLoc;
350     EndLoc = o.EndLoc;
351     switch (Kind) {
352     case CondCode:
353       CC = o.CC;
354       break;
355     case ITCondMask:
356       ITMask = o.ITMask;
357       break;
358     case Token:
359       Tok = o.Tok;
360       break;
361     case CCOut:
362     case Register:
363       Reg = o.Reg;
364       break;
365     case RegisterList:
366     case DPRRegisterList:
367     case SPRRegisterList:
368       Registers = o.Registers;
369       break;
370     case CoprocNum:
371     case CoprocReg:
372       Cop = o.Cop;
373       break;
374     case Immediate:
375       Imm = o.Imm;
376       break;
377     case MemBarrierOpt:
378       MBOpt = o.MBOpt;
379       break;
380     case Memory:
381       Mem = o.Mem;
382       break;
383     case PostIndexRegister:
384       PostIdxReg = o.PostIdxReg;
385       break;
386     case MSRMask:
387       MMask = o.MMask;
388       break;
389     case ProcIFlags:
390       IFlags = o.IFlags;
391       break;
392     case ShifterImmediate:
393       ShifterImm = o.ShifterImm;
394       break;
395     case ShiftedRegister:
396       RegShiftedReg = o.RegShiftedReg;
397       break;
398     case ShiftedImmediate:
399       RegShiftedImm = o.RegShiftedImm;
400       break;
401     case RotateImmediate:
402       RotImm = o.RotImm;
403       break;
404     case BitfieldDescriptor:
405       Bitfield = o.Bitfield;
406       break;
407     }
408   }
409
410   /// getStartLoc - Get the location of the first token of this operand.
411   SMLoc getStartLoc() const { return StartLoc; }
412   /// getEndLoc - Get the location of the last token of this operand.
413   SMLoc getEndLoc() const { return EndLoc; }
414
415   ARMCC::CondCodes getCondCode() const {
416     assert(Kind == CondCode && "Invalid access!");
417     return CC.Val;
418   }
419
420   unsigned getCoproc() const {
421     assert((Kind == CoprocNum || Kind == CoprocReg) && "Invalid access!");
422     return Cop.Val;
423   }
424
425   StringRef getToken() const {
426     assert(Kind == Token && "Invalid access!");
427     return StringRef(Tok.Data, Tok.Length);
428   }
429
430   unsigned getReg() const {
431     assert((Kind == Register || Kind == CCOut) && "Invalid access!");
432     return Reg.RegNum;
433   }
434
435   const SmallVectorImpl<unsigned> &getRegList() const {
436     assert((Kind == RegisterList || Kind == DPRRegisterList ||
437             Kind == SPRRegisterList) && "Invalid access!");
438     return Registers;
439   }
440
441   const MCExpr *getImm() const {
442     assert(Kind == Immediate && "Invalid access!");
443     return Imm.Val;
444   }
445
446   ARM_MB::MemBOpt getMemBarrierOpt() const {
447     assert(Kind == MemBarrierOpt && "Invalid access!");
448     return MBOpt.Val;
449   }
450
451   ARM_PROC::IFlags getProcIFlags() const {
452     assert(Kind == ProcIFlags && "Invalid access!");
453     return IFlags.Val;
454   }
455
456   unsigned getMSRMask() const {
457     assert(Kind == MSRMask && "Invalid access!");
458     return MMask.Val;
459   }
460
461   bool isCoprocNum() const { return Kind == CoprocNum; }
462   bool isCoprocReg() const { return Kind == CoprocReg; }
463   bool isCondCode() const { return Kind == CondCode; }
464   bool isCCOut() const { return Kind == CCOut; }
465   bool isITMask() const { return Kind == ITCondMask; }
466   bool isITCondCode() const { return Kind == CondCode; }
467   bool isImm() const { return Kind == Immediate; }
468   bool isImm8s4() const {
469     if (Kind != Immediate)
470       return false;
471     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
472     if (!CE) return false;
473     int64_t Value = CE->getValue();
474     return ((Value & 3) == 0) && Value >= -1020 && Value <= 1020;
475   }
476   bool isImm0_1020s4() const {
477     if (Kind != Immediate)
478       return false;
479     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
480     if (!CE) return false;
481     int64_t Value = CE->getValue();
482     return ((Value & 3) == 0) && Value >= 0 && Value <= 1020;
483   }
484   bool isImm0_508s4() const {
485     if (Kind != Immediate)
486       return false;
487     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
488     if (!CE) return false;
489     int64_t Value = CE->getValue();
490     return ((Value & 3) == 0) && Value >= 0 && Value <= 508;
491   }
492   bool isImm0_255() const {
493     if (Kind != Immediate)
494       return false;
495     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
496     if (!CE) return false;
497     int64_t Value = CE->getValue();
498     return Value >= 0 && Value < 256;
499   }
500   bool isImm0_7() const {
501     if (Kind != Immediate)
502       return false;
503     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
504     if (!CE) return false;
505     int64_t Value = CE->getValue();
506     return Value >= 0 && Value < 8;
507   }
508   bool isImm0_15() const {
509     if (Kind != Immediate)
510       return false;
511     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
512     if (!CE) return false;
513     int64_t Value = CE->getValue();
514     return Value >= 0 && Value < 16;
515   }
516   bool isImm0_31() const {
517     if (Kind != Immediate)
518       return false;
519     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
520     if (!CE) return false;
521     int64_t Value = CE->getValue();
522     return Value >= 0 && Value < 32;
523   }
524   bool isImm1_16() const {
525     if (Kind != Immediate)
526       return false;
527     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
528     if (!CE) return false;
529     int64_t Value = CE->getValue();
530     return Value > 0 && Value < 17;
531   }
532   bool isImm1_32() const {
533     if (Kind != Immediate)
534       return false;
535     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
536     if (!CE) return false;
537     int64_t Value = CE->getValue();
538     return Value > 0 && Value < 33;
539   }
540   bool isImm0_65535() const {
541     if (Kind != Immediate)
542       return false;
543     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
544     if (!CE) return false;
545     int64_t Value = CE->getValue();
546     return Value >= 0 && Value < 65536;
547   }
548   bool isImm0_65535Expr() const {
549     if (Kind != Immediate)
550       return false;
551     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
552     // If it's not a constant expression, it'll generate a fixup and be
553     // handled later.
554     if (!CE) return true;
555     int64_t Value = CE->getValue();
556     return Value >= 0 && Value < 65536;
557   }
558   bool isImm24bit() const {
559     if (Kind != Immediate)
560       return false;
561     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
562     if (!CE) return false;
563     int64_t Value = CE->getValue();
564     return Value >= 0 && Value <= 0xffffff;
565   }
566   bool isImmThumbSR() const {
567     if (Kind != Immediate)
568       return false;
569     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
570     if (!CE) return false;
571     int64_t Value = CE->getValue();
572     return Value > 0 && Value < 33;
573   }
574   bool isPKHLSLImm() const {
575     if (Kind != Immediate)
576       return false;
577     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
578     if (!CE) return false;
579     int64_t Value = CE->getValue();
580     return Value >= 0 && Value < 32;
581   }
582   bool isPKHASRImm() const {
583     if (Kind != Immediate)
584       return false;
585     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
586     if (!CE) return false;
587     int64_t Value = CE->getValue();
588     return Value > 0 && Value <= 32;
589   }
590   bool isARMSOImm() const {
591     if (Kind != Immediate)
592       return false;
593     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
594     if (!CE) return false;
595     int64_t Value = CE->getValue();
596     return ARM_AM::getSOImmVal(Value) != -1;
597   }
598   bool isT2SOImm() const {
599     if (Kind != Immediate)
600       return false;
601     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
602     if (!CE) return false;
603     int64_t Value = CE->getValue();
604     return ARM_AM::getT2SOImmVal(Value) != -1;
605   }
606   bool isSetEndImm() const {
607     if (Kind != Immediate)
608       return false;
609     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
610     if (!CE) return false;
611     int64_t Value = CE->getValue();
612     return Value == 1 || Value == 0;
613   }
614   bool isReg() const { return Kind == Register; }
615   bool isRegList() const { return Kind == RegisterList; }
616   bool isDPRRegList() const { return Kind == DPRRegisterList; }
617   bool isSPRRegList() const { return Kind == SPRRegisterList; }
618   bool isToken() const { return Kind == Token; }
619   bool isMemBarrierOpt() const { return Kind == MemBarrierOpt; }
620   bool isMemory() const { return Kind == Memory; }
621   bool isShifterImm() const { return Kind == ShifterImmediate; }
622   bool isRegShiftedReg() const { return Kind == ShiftedRegister; }
623   bool isRegShiftedImm() const { return Kind == ShiftedImmediate; }
624   bool isRotImm() const { return Kind == RotateImmediate; }
625   bool isBitfield() const { return Kind == BitfieldDescriptor; }
626   bool isPostIdxRegShifted() const { return Kind == PostIndexRegister; }
627   bool isPostIdxReg() const {
628     return Kind == PostIndexRegister && PostIdxReg.ShiftTy == ARM_AM::no_shift;
629   }
630   bool isMemNoOffset() const {
631     if (Kind != Memory)
632       return false;
633     // No offset of any kind.
634     return Mem.OffsetRegNum == 0 && Mem.OffsetImm == 0;
635   }
636   bool isAddrMode2() const {
637     if (Kind != Memory)
638       return false;
639     // Check for register offset.
640     if (Mem.OffsetRegNum) return true;
641     // Immediate offset in range [-4095, 4095].
642     if (!Mem.OffsetImm) return true;
643     int64_t Val = Mem.OffsetImm->getValue();
644     return Val > -4096 && Val < 4096;
645   }
646   bool isAM2OffsetImm() const {
647     if (Kind != Immediate)
648       return false;
649     // Immediate offset in range [-4095, 4095].
650     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
651     if (!CE) return false;
652     int64_t Val = CE->getValue();
653     return Val > -4096 && Val < 4096;
654   }
655   bool isAddrMode3() const {
656     if (Kind != Memory)
657       return false;
658     // No shifts are legal for AM3.
659     if (Mem.ShiftType != ARM_AM::no_shift) return false;
660     // Check for register offset.
661     if (Mem.OffsetRegNum) return true;
662     // Immediate offset in range [-255, 255].
663     if (!Mem.OffsetImm) return true;
664     int64_t Val = Mem.OffsetImm->getValue();
665     return Val > -256 && Val < 256;
666   }
667   bool isAM3Offset() const {
668     if (Kind != Immediate && Kind != PostIndexRegister)
669       return false;
670     if (Kind == PostIndexRegister)
671       return PostIdxReg.ShiftTy == ARM_AM::no_shift;
672     // Immediate offset in range [-255, 255].
673     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
674     if (!CE) return false;
675     int64_t Val = CE->getValue();
676     // Special case, #-0 is INT32_MIN.
677     return (Val > -256 && Val < 256) || Val == INT32_MIN;
678   }
679   bool isAddrMode5() const {
680     if (Kind != Memory)
681       return false;
682     // Check for register offset.
683     if (Mem.OffsetRegNum) return false;
684     // Immediate offset in range [-1020, 1020] and a multiple of 4.
685     if (!Mem.OffsetImm) return true;
686     int64_t Val = Mem.OffsetImm->getValue();
687     return (Val >= -1020 && Val <= 1020 && ((Val & 3) == 0)) ||
688            Val == INT32_MIN;
689   }
690   bool isMemRegOffset() const {
691     if (Kind != Memory || !Mem.OffsetRegNum)
692       return false;
693     return true;
694   }
695   bool isT2MemRegOffset() const {
696     if (Kind != Memory || !Mem.OffsetRegNum || Mem.isNegative)
697       return false;
698     // Only lsl #{0, 1, 2, 3} allowed.
699     if (Mem.ShiftType == ARM_AM::no_shift)
700       return true;
701     if (Mem.ShiftType != ARM_AM::lsl || Mem.ShiftImm > 3)
702       return false;
703     return true;
704   }
705   bool isMemThumbRR() const {
706     // Thumb reg+reg addressing is simple. Just two registers, a base and
707     // an offset. No shifts, negations or any other complicating factors.
708     if (Kind != Memory || !Mem.OffsetRegNum || Mem.isNegative ||
709         Mem.ShiftType != ARM_AM::no_shift)
710       return false;
711     return isARMLowRegister(Mem.BaseRegNum) &&
712       (!Mem.OffsetRegNum || isARMLowRegister(Mem.OffsetRegNum));
713   }
714   bool isMemThumbRIs4() const {
715     if (Kind != Memory || Mem.OffsetRegNum != 0 ||
716         !isARMLowRegister(Mem.BaseRegNum))
717       return false;
718     // Immediate offset, multiple of 4 in range [0, 124].
719     if (!Mem.OffsetImm) return true;
720     int64_t Val = Mem.OffsetImm->getValue();
721     return Val >= 0 && Val <= 124 && (Val % 4) == 0;
722   }
723   bool isMemThumbRIs2() const {
724     if (Kind != Memory || Mem.OffsetRegNum != 0 ||
725         !isARMLowRegister(Mem.BaseRegNum))
726       return false;
727     // Immediate offset, multiple of 4 in range [0, 62].
728     if (!Mem.OffsetImm) return true;
729     int64_t Val = Mem.OffsetImm->getValue();
730     return Val >= 0 && Val <= 62 && (Val % 2) == 0;
731   }
732   bool isMemThumbRIs1() const {
733     if (Kind != Memory || Mem.OffsetRegNum != 0 ||
734         !isARMLowRegister(Mem.BaseRegNum))
735       return false;
736     // Immediate offset in range [0, 31].
737     if (!Mem.OffsetImm) return true;
738     int64_t Val = Mem.OffsetImm->getValue();
739     return Val >= 0 && Val <= 31;
740   }
741   bool isMemThumbSPI() const {
742     if (Kind != Memory || Mem.OffsetRegNum != 0 || Mem.BaseRegNum != ARM::SP)
743       return false;
744     // Immediate offset, multiple of 4 in range [0, 1020].
745     if (!Mem.OffsetImm) return true;
746     int64_t Val = Mem.OffsetImm->getValue();
747     return Val >= 0 && Val <= 1020 && (Val % 4) == 0;
748   }
749   bool isMemImm8s4Offset() const {
750     if (Kind != Memory || Mem.OffsetRegNum != 0)
751       return false;
752     // Immediate offset a multiple of 4 in range [-1020, 1020].
753     if (!Mem.OffsetImm) return true;
754     int64_t Val = Mem.OffsetImm->getValue();
755     return Val >= -1020 && Val <= 1020 && (Val & 3) == 0;
756   }
757   bool isMemImm0_1020s4Offset() const {
758     if (Kind != Memory || Mem.OffsetRegNum != 0)
759       return false;
760     // Immediate offset a multiple of 4 in range [0, 1020].
761     if (!Mem.OffsetImm) return true;
762     int64_t Val = Mem.OffsetImm->getValue();
763     return Val >= 0 && Val <= 1020 && (Val & 3) == 0;
764   }
765   bool isMemImm8Offset() const {
766     if (Kind != Memory || Mem.OffsetRegNum != 0)
767       return false;
768     // Immediate offset in range [-255, 255].
769     if (!Mem.OffsetImm) return true;
770     int64_t Val = Mem.OffsetImm->getValue();
771     return Val > -256 && Val < 256;
772   }
773   bool isMemPosImm8Offset() const {
774     if (Kind != Memory || Mem.OffsetRegNum != 0)
775       return false;
776     // Immediate offset in range [0, 255].
777     if (!Mem.OffsetImm) return true;
778     int64_t Val = Mem.OffsetImm->getValue();
779     return Val >= 0 && Val < 256;
780   }
781   bool isMemNegImm8Offset() const {
782     if (Kind != Memory || Mem.OffsetRegNum != 0)
783       return false;
784     // Immediate offset in range [-255, -1].
785     if (!Mem.OffsetImm) return true;
786     int64_t Val = Mem.OffsetImm->getValue();
787     return Val > -256 && Val < 0;
788   }
789   bool isMemUImm12Offset() const {
790     // If we have an immediate that's not a constant, treat it as a label
791     // reference needing a fixup. If it is a constant, it's something else
792     // and we reject it.
793     if (Kind == Immediate && !isa<MCConstantExpr>(getImm()))
794       return true;
795
796     if (Kind != Memory || Mem.OffsetRegNum != 0)
797       return false;
798     // Immediate offset in range [0, 4095].
799     if (!Mem.OffsetImm) return true;
800     int64_t Val = Mem.OffsetImm->getValue();
801     return (Val >= 0 && Val < 4096);
802   }
803   bool isMemImm12Offset() const {
804     // If we have an immediate that's not a constant, treat it as a label
805     // reference needing a fixup. If it is a constant, it's something else
806     // and we reject it.
807     if (Kind == Immediate && !isa<MCConstantExpr>(getImm()))
808       return true;
809
810     if (Kind != Memory || Mem.OffsetRegNum != 0)
811       return false;
812     // Immediate offset in range [-4095, 4095].
813     if (!Mem.OffsetImm) return true;
814     int64_t Val = Mem.OffsetImm->getValue();
815     return (Val > -4096 && Val < 4096) || (Val == INT32_MIN);
816   }
817   bool isPostIdxImm8() const {
818     if (Kind != Immediate)
819       return false;
820     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
821     if (!CE) return false;
822     int64_t Val = CE->getValue();
823     return (Val > -256 && Val < 256) || (Val == INT32_MIN);
824   }
825
826   bool isMSRMask() const { return Kind == MSRMask; }
827   bool isProcIFlags() const { return Kind == ProcIFlags; }
828
829   void addExpr(MCInst &Inst, const MCExpr *Expr) const {
830     // Add as immediates when possible.  Null MCExpr = 0.
831     if (Expr == 0)
832       Inst.addOperand(MCOperand::CreateImm(0));
833     else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
834       Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
835     else
836       Inst.addOperand(MCOperand::CreateExpr(Expr));
837   }
838
839   void addCondCodeOperands(MCInst &Inst, unsigned N) const {
840     assert(N == 2 && "Invalid number of operands!");
841     Inst.addOperand(MCOperand::CreateImm(unsigned(getCondCode())));
842     unsigned RegNum = getCondCode() == ARMCC::AL ? 0: ARM::CPSR;
843     Inst.addOperand(MCOperand::CreateReg(RegNum));
844   }
845
846   void addCoprocNumOperands(MCInst &Inst, unsigned N) const {
847     assert(N == 1 && "Invalid number of operands!");
848     Inst.addOperand(MCOperand::CreateImm(getCoproc()));
849   }
850
851   void addITMaskOperands(MCInst &Inst, unsigned N) const {
852     assert(N == 1 && "Invalid number of operands!");
853     Inst.addOperand(MCOperand::CreateImm(ITMask.Mask));
854   }
855
856   void addITCondCodeOperands(MCInst &Inst, unsigned N) const {
857     assert(N == 1 && "Invalid number of operands!");
858     Inst.addOperand(MCOperand::CreateImm(unsigned(getCondCode())));
859   }
860
861   void addCoprocRegOperands(MCInst &Inst, unsigned N) const {
862     assert(N == 1 && "Invalid number of operands!");
863     Inst.addOperand(MCOperand::CreateImm(getCoproc()));
864   }
865
866   void addCCOutOperands(MCInst &Inst, unsigned N) const {
867     assert(N == 1 && "Invalid number of operands!");
868     Inst.addOperand(MCOperand::CreateReg(getReg()));
869   }
870
871   void addRegOperands(MCInst &Inst, unsigned N) const {
872     assert(N == 1 && "Invalid number of operands!");
873     Inst.addOperand(MCOperand::CreateReg(getReg()));
874   }
875
876   void addRegShiftedRegOperands(MCInst &Inst, unsigned N) const {
877     assert(N == 3 && "Invalid number of operands!");
878     assert(isRegShiftedReg() && "addRegShiftedRegOperands() on non RegShiftedReg!");
879     Inst.addOperand(MCOperand::CreateReg(RegShiftedReg.SrcReg));
880     Inst.addOperand(MCOperand::CreateReg(RegShiftedReg.ShiftReg));
881     Inst.addOperand(MCOperand::CreateImm(
882       ARM_AM::getSORegOpc(RegShiftedReg.ShiftTy, RegShiftedReg.ShiftImm)));
883   }
884
885   void addRegShiftedImmOperands(MCInst &Inst, unsigned N) const {
886     assert(N == 2 && "Invalid number of operands!");
887     assert(isRegShiftedImm() && "addRegShiftedImmOperands() on non RegShiftedImm!");
888     Inst.addOperand(MCOperand::CreateReg(RegShiftedImm.SrcReg));
889     Inst.addOperand(MCOperand::CreateImm(
890       ARM_AM::getSORegOpc(RegShiftedImm.ShiftTy, RegShiftedImm.ShiftImm)));
891   }
892
893   void addShifterImmOperands(MCInst &Inst, unsigned N) const {
894     assert(N == 1 && "Invalid number of operands!");
895     Inst.addOperand(MCOperand::CreateImm((ShifterImm.isASR << 5) |
896                                          ShifterImm.Imm));
897   }
898
899   void addRegListOperands(MCInst &Inst, unsigned N) const {
900     assert(N == 1 && "Invalid number of operands!");
901     const SmallVectorImpl<unsigned> &RegList = getRegList();
902     for (SmallVectorImpl<unsigned>::const_iterator
903            I = RegList.begin(), E = RegList.end(); I != E; ++I)
904       Inst.addOperand(MCOperand::CreateReg(*I));
905   }
906
907   void addDPRRegListOperands(MCInst &Inst, unsigned N) const {
908     addRegListOperands(Inst, N);
909   }
910
911   void addSPRRegListOperands(MCInst &Inst, unsigned N) const {
912     addRegListOperands(Inst, N);
913   }
914
915   void addRotImmOperands(MCInst &Inst, unsigned N) const {
916     assert(N == 1 && "Invalid number of operands!");
917     // Encoded as val>>3. The printer handles display as 8, 16, 24.
918     Inst.addOperand(MCOperand::CreateImm(RotImm.Imm >> 3));
919   }
920
921   void addBitfieldOperands(MCInst &Inst, unsigned N) const {
922     assert(N == 1 && "Invalid number of operands!");
923     // Munge the lsb/width into a bitfield mask.
924     unsigned lsb = Bitfield.LSB;
925     unsigned width = Bitfield.Width;
926     // Make a 32-bit mask w/ the referenced bits clear and all other bits set.
927     uint32_t Mask = ~(((uint32_t)0xffffffff >> lsb) << (32 - width) >>
928                       (32 - (lsb + width)));
929     Inst.addOperand(MCOperand::CreateImm(Mask));
930   }
931
932   void addImmOperands(MCInst &Inst, unsigned N) const {
933     assert(N == 1 && "Invalid number of operands!");
934     addExpr(Inst, getImm());
935   }
936
937   void addImm8s4Operands(MCInst &Inst, unsigned N) const {
938     assert(N == 1 && "Invalid number of operands!");
939     // FIXME: We really want to scale the value here, but the LDRD/STRD
940     // instruction don't encode operands that way yet.
941     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
942     Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
943   }
944
945   void addImm0_1020s4Operands(MCInst &Inst, unsigned N) const {
946     assert(N == 1 && "Invalid number of operands!");
947     // The immediate is scaled by four in the encoding and is stored
948     // in the MCInst as such. Lop off the low two bits here.
949     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
950     Inst.addOperand(MCOperand::CreateImm(CE->getValue() / 4));
951   }
952
953   void addImm0_508s4Operands(MCInst &Inst, unsigned N) const {
954     assert(N == 1 && "Invalid number of operands!");
955     // The immediate is scaled by four in the encoding and is stored
956     // in the MCInst as such. Lop off the low two bits here.
957     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
958     Inst.addOperand(MCOperand::CreateImm(CE->getValue() / 4));
959   }
960
961   void addImm0_255Operands(MCInst &Inst, unsigned N) const {
962     assert(N == 1 && "Invalid number of operands!");
963     addExpr(Inst, getImm());
964   }
965
966   void addImm0_7Operands(MCInst &Inst, unsigned N) const {
967     assert(N == 1 && "Invalid number of operands!");
968     addExpr(Inst, getImm());
969   }
970
971   void addImm0_15Operands(MCInst &Inst, unsigned N) const {
972     assert(N == 1 && "Invalid number of operands!");
973     addExpr(Inst, getImm());
974   }
975
976   void addImm0_31Operands(MCInst &Inst, unsigned N) const {
977     assert(N == 1 && "Invalid number of operands!");
978     addExpr(Inst, getImm());
979   }
980
981   void addImm1_16Operands(MCInst &Inst, unsigned N) const {
982     assert(N == 1 && "Invalid number of operands!");
983     // The constant encodes as the immediate-1, and we store in the instruction
984     // the bits as encoded, so subtract off one here.
985     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
986     Inst.addOperand(MCOperand::CreateImm(CE->getValue() - 1));
987   }
988
989   void addImm1_32Operands(MCInst &Inst, unsigned N) const {
990     assert(N == 1 && "Invalid number of operands!");
991     // The constant encodes as the immediate-1, and we store in the instruction
992     // the bits as encoded, so subtract off one here.
993     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
994     Inst.addOperand(MCOperand::CreateImm(CE->getValue() - 1));
995   }
996
997   void addImm0_65535Operands(MCInst &Inst, unsigned N) const {
998     assert(N == 1 && "Invalid number of operands!");
999     addExpr(Inst, getImm());
1000   }
1001
1002   void addImm0_65535ExprOperands(MCInst &Inst, unsigned N) const {
1003     assert(N == 1 && "Invalid number of operands!");
1004     addExpr(Inst, getImm());
1005   }
1006
1007   void addImm24bitOperands(MCInst &Inst, unsigned N) const {
1008     assert(N == 1 && "Invalid number of operands!");
1009     addExpr(Inst, getImm());
1010   }
1011
1012   void addImmThumbSROperands(MCInst &Inst, unsigned N) const {
1013     assert(N == 1 && "Invalid number of operands!");
1014     // The constant encodes as the immediate, except for 32, which encodes as
1015     // zero.
1016     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1017     unsigned Imm = CE->getValue();
1018     Inst.addOperand(MCOperand::CreateImm((Imm == 32 ? 0 : Imm)));
1019   }
1020
1021   void addPKHLSLImmOperands(MCInst &Inst, unsigned N) const {
1022     assert(N == 1 && "Invalid number of operands!");
1023     addExpr(Inst, getImm());
1024   }
1025
1026   void addPKHASRImmOperands(MCInst &Inst, unsigned N) const {
1027     assert(N == 1 && "Invalid number of operands!");
1028     // An ASR value of 32 encodes as 0, so that's how we want to add it to
1029     // the instruction as well.
1030     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1031     int Val = CE->getValue();
1032     Inst.addOperand(MCOperand::CreateImm(Val == 32 ? 0 : Val));
1033   }
1034
1035   void addARMSOImmOperands(MCInst &Inst, unsigned N) const {
1036     assert(N == 1 && "Invalid number of operands!");
1037     addExpr(Inst, getImm());
1038   }
1039
1040   void addT2SOImmOperands(MCInst &Inst, unsigned N) const {
1041     assert(N == 1 && "Invalid number of operands!");
1042     addExpr(Inst, getImm());
1043   }
1044
1045   void addSetEndImmOperands(MCInst &Inst, unsigned N) const {
1046     assert(N == 1 && "Invalid number of operands!");
1047     addExpr(Inst, getImm());
1048   }
1049
1050   void addMemBarrierOptOperands(MCInst &Inst, unsigned N) const {
1051     assert(N == 1 && "Invalid number of operands!");
1052     Inst.addOperand(MCOperand::CreateImm(unsigned(getMemBarrierOpt())));
1053   }
1054
1055   void addMemNoOffsetOperands(MCInst &Inst, unsigned N) const {
1056     assert(N == 1 && "Invalid number of operands!");
1057     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
1058   }
1059
1060   void addAddrMode2Operands(MCInst &Inst, unsigned N) const {
1061     assert(N == 3 && "Invalid number of operands!");
1062     int32_t Val = Mem.OffsetImm ? Mem.OffsetImm->getValue() : 0;
1063     if (!Mem.OffsetRegNum) {
1064       ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
1065       // Special case for #-0
1066       if (Val == INT32_MIN) Val = 0;
1067       if (Val < 0) Val = -Val;
1068       Val = ARM_AM::getAM2Opc(AddSub, Val, ARM_AM::no_shift);
1069     } else {
1070       // For register offset, we encode the shift type and negation flag
1071       // here.
1072       Val = ARM_AM::getAM2Opc(Mem.isNegative ? ARM_AM::sub : ARM_AM::add,
1073                               Mem.ShiftImm, Mem.ShiftType);
1074     }
1075     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
1076     Inst.addOperand(MCOperand::CreateReg(Mem.OffsetRegNum));
1077     Inst.addOperand(MCOperand::CreateImm(Val));
1078   }
1079
1080   void addAM2OffsetImmOperands(MCInst &Inst, unsigned N) const {
1081     assert(N == 2 && "Invalid number of operands!");
1082     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1083     assert(CE && "non-constant AM2OffsetImm operand!");
1084     int32_t Val = CE->getValue();
1085     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
1086     // Special case for #-0
1087     if (Val == INT32_MIN) Val = 0;
1088     if (Val < 0) Val = -Val;
1089     Val = ARM_AM::getAM2Opc(AddSub, Val, ARM_AM::no_shift);
1090     Inst.addOperand(MCOperand::CreateReg(0));
1091     Inst.addOperand(MCOperand::CreateImm(Val));
1092   }
1093
1094   void addAddrMode3Operands(MCInst &Inst, unsigned N) const {
1095     assert(N == 3 && "Invalid number of operands!");
1096     int32_t Val = Mem.OffsetImm ? Mem.OffsetImm->getValue() : 0;
1097     if (!Mem.OffsetRegNum) {
1098       ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
1099       // Special case for #-0
1100       if (Val == INT32_MIN) Val = 0;
1101       if (Val < 0) Val = -Val;
1102       Val = ARM_AM::getAM3Opc(AddSub, Val);
1103     } else {
1104       // For register offset, we encode the shift type and negation flag
1105       // here.
1106       Val = ARM_AM::getAM3Opc(Mem.isNegative ? ARM_AM::sub : ARM_AM::add, 0);
1107     }
1108     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
1109     Inst.addOperand(MCOperand::CreateReg(Mem.OffsetRegNum));
1110     Inst.addOperand(MCOperand::CreateImm(Val));
1111   }
1112
1113   void addAM3OffsetOperands(MCInst &Inst, unsigned N) const {
1114     assert(N == 2 && "Invalid number of operands!");
1115     if (Kind == PostIndexRegister) {
1116       int32_t Val =
1117         ARM_AM::getAM3Opc(PostIdxReg.isAdd ? ARM_AM::add : ARM_AM::sub, 0);
1118       Inst.addOperand(MCOperand::CreateReg(PostIdxReg.RegNum));
1119       Inst.addOperand(MCOperand::CreateImm(Val));
1120       return;
1121     }
1122
1123     // Constant offset.
1124     const MCConstantExpr *CE = static_cast<const MCConstantExpr*>(getImm());
1125     int32_t Val = CE->getValue();
1126     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
1127     // Special case for #-0
1128     if (Val == INT32_MIN) Val = 0;
1129     if (Val < 0) Val = -Val;
1130     Val = ARM_AM::getAM3Opc(AddSub, Val);
1131     Inst.addOperand(MCOperand::CreateReg(0));
1132     Inst.addOperand(MCOperand::CreateImm(Val));
1133   }
1134
1135   void addAddrMode5Operands(MCInst &Inst, unsigned N) const {
1136     assert(N == 2 && "Invalid number of operands!");
1137     // The lower two bits are always zero and as such are not encoded.
1138     int32_t Val = Mem.OffsetImm ? Mem.OffsetImm->getValue() / 4 : 0;
1139     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
1140     // Special case for #-0
1141     if (Val == INT32_MIN) Val = 0;
1142     if (Val < 0) Val = -Val;
1143     Val = ARM_AM::getAM5Opc(AddSub, Val);
1144     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
1145     Inst.addOperand(MCOperand::CreateImm(Val));
1146   }
1147
1148   void addMemImm8s4OffsetOperands(MCInst &Inst, unsigned N) const {
1149     assert(N == 2 && "Invalid number of operands!");
1150     int64_t Val = Mem.OffsetImm ? Mem.OffsetImm->getValue() : 0;
1151     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
1152     Inst.addOperand(MCOperand::CreateImm(Val));
1153   }
1154
1155   void addMemImm0_1020s4OffsetOperands(MCInst &Inst, unsigned N) const {
1156     assert(N == 2 && "Invalid number of operands!");
1157     // The lower two bits are always zero and as such are not encoded.
1158     int32_t Val = Mem.OffsetImm ? Mem.OffsetImm->getValue() / 4 : 0;
1159     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
1160     Inst.addOperand(MCOperand::CreateImm(Val));
1161   }
1162
1163   void addMemImm8OffsetOperands(MCInst &Inst, unsigned N) const {
1164     assert(N == 2 && "Invalid number of operands!");
1165     int64_t Val = Mem.OffsetImm ? Mem.OffsetImm->getValue() : 0;
1166     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
1167     Inst.addOperand(MCOperand::CreateImm(Val));
1168   }
1169
1170   void addMemPosImm8OffsetOperands(MCInst &Inst, unsigned N) const {
1171     addMemImm8OffsetOperands(Inst, N);
1172   }
1173
1174   void addMemNegImm8OffsetOperands(MCInst &Inst, unsigned N) const {
1175     addMemImm8OffsetOperands(Inst, N);
1176   }
1177
1178   void addMemUImm12OffsetOperands(MCInst &Inst, unsigned N) const {
1179     assert(N == 2 && "Invalid number of operands!");
1180     // If this is an immediate, it's a label reference.
1181     if (Kind == Immediate) {
1182       addExpr(Inst, getImm());
1183       Inst.addOperand(MCOperand::CreateImm(0));
1184       return;
1185     }
1186
1187     // Otherwise, it's a normal memory reg+offset.
1188     int64_t Val = Mem.OffsetImm ? Mem.OffsetImm->getValue() : 0;
1189     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
1190     Inst.addOperand(MCOperand::CreateImm(Val));
1191   }
1192
1193   void addMemImm12OffsetOperands(MCInst &Inst, unsigned N) const {
1194     assert(N == 2 && "Invalid number of operands!");
1195     // If this is an immediate, it's a label reference.
1196     if (Kind == Immediate) {
1197       addExpr(Inst, getImm());
1198       Inst.addOperand(MCOperand::CreateImm(0));
1199       return;
1200     }
1201
1202     // Otherwise, it's a normal memory reg+offset.
1203     int64_t Val = Mem.OffsetImm ? Mem.OffsetImm->getValue() : 0;
1204     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
1205     Inst.addOperand(MCOperand::CreateImm(Val));
1206   }
1207
1208   void addMemRegOffsetOperands(MCInst &Inst, unsigned N) const {
1209     assert(N == 3 && "Invalid number of operands!");
1210     unsigned Val = ARM_AM::getAM2Opc(Mem.isNegative ? ARM_AM::sub : ARM_AM::add,
1211                                      Mem.ShiftImm, Mem.ShiftType);
1212     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
1213     Inst.addOperand(MCOperand::CreateReg(Mem.OffsetRegNum));
1214     Inst.addOperand(MCOperand::CreateImm(Val));
1215   }
1216
1217   void addT2MemRegOffsetOperands(MCInst &Inst, unsigned N) const {
1218     assert(N == 3 && "Invalid number of operands!");
1219     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
1220     Inst.addOperand(MCOperand::CreateReg(Mem.OffsetRegNum));
1221     Inst.addOperand(MCOperand::CreateImm(Mem.ShiftImm));
1222   }
1223
1224   void addMemThumbRROperands(MCInst &Inst, unsigned N) const {
1225     assert(N == 2 && "Invalid number of operands!");
1226     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
1227     Inst.addOperand(MCOperand::CreateReg(Mem.OffsetRegNum));
1228   }
1229
1230   void addMemThumbRIs4Operands(MCInst &Inst, unsigned N) const {
1231     assert(N == 2 && "Invalid number of operands!");
1232     int64_t Val = Mem.OffsetImm ? (Mem.OffsetImm->getValue() / 4) : 0;
1233     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
1234     Inst.addOperand(MCOperand::CreateImm(Val));
1235   }
1236
1237   void addMemThumbRIs2Operands(MCInst &Inst, unsigned N) const {
1238     assert(N == 2 && "Invalid number of operands!");
1239     int64_t Val = Mem.OffsetImm ? (Mem.OffsetImm->getValue() / 2) : 0;
1240     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
1241     Inst.addOperand(MCOperand::CreateImm(Val));
1242   }
1243
1244   void addMemThumbRIs1Operands(MCInst &Inst, unsigned N) const {
1245     assert(N == 2 && "Invalid number of operands!");
1246     int64_t Val = Mem.OffsetImm ? (Mem.OffsetImm->getValue()) : 0;
1247     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
1248     Inst.addOperand(MCOperand::CreateImm(Val));
1249   }
1250
1251   void addMemThumbSPIOperands(MCInst &Inst, unsigned N) const {
1252     assert(N == 2 && "Invalid number of operands!");
1253     int64_t Val = Mem.OffsetImm ? (Mem.OffsetImm->getValue() / 4) : 0;
1254     Inst.addOperand(MCOperand::CreateReg(Mem.BaseRegNum));
1255     Inst.addOperand(MCOperand::CreateImm(Val));
1256   }
1257
1258   void addPostIdxImm8Operands(MCInst &Inst, unsigned N) const {
1259     assert(N == 1 && "Invalid number of operands!");
1260     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1261     assert(CE && "non-constant post-idx-imm8 operand!");
1262     int Imm = CE->getValue();
1263     bool isAdd = Imm >= 0;
1264     if (Imm == INT32_MIN) Imm = 0;
1265     Imm = (Imm < 0 ? -Imm : Imm) | (int)isAdd << 8;
1266     Inst.addOperand(MCOperand::CreateImm(Imm));
1267   }
1268
1269   void addPostIdxRegOperands(MCInst &Inst, unsigned N) const {
1270     assert(N == 2 && "Invalid number of operands!");
1271     Inst.addOperand(MCOperand::CreateReg(PostIdxReg.RegNum));
1272     Inst.addOperand(MCOperand::CreateImm(PostIdxReg.isAdd));
1273   }
1274
1275   void addPostIdxRegShiftedOperands(MCInst &Inst, unsigned N) const {
1276     assert(N == 2 && "Invalid number of operands!");
1277     Inst.addOperand(MCOperand::CreateReg(PostIdxReg.RegNum));
1278     // The sign, shift type, and shift amount are encoded in a single operand
1279     // using the AM2 encoding helpers.
1280     ARM_AM::AddrOpc opc = PostIdxReg.isAdd ? ARM_AM::add : ARM_AM::sub;
1281     unsigned Imm = ARM_AM::getAM2Opc(opc, PostIdxReg.ShiftImm,
1282                                      PostIdxReg.ShiftTy);
1283     Inst.addOperand(MCOperand::CreateImm(Imm));
1284   }
1285
1286   void addMSRMaskOperands(MCInst &Inst, unsigned N) const {
1287     assert(N == 1 && "Invalid number of operands!");
1288     Inst.addOperand(MCOperand::CreateImm(unsigned(getMSRMask())));
1289   }
1290
1291   void addProcIFlagsOperands(MCInst &Inst, unsigned N) const {
1292     assert(N == 1 && "Invalid number of operands!");
1293     Inst.addOperand(MCOperand::CreateImm(unsigned(getProcIFlags())));
1294   }
1295
1296   virtual void print(raw_ostream &OS) const;
1297
1298   static ARMOperand *CreateITMask(unsigned Mask, SMLoc S) {
1299     ARMOperand *Op = new ARMOperand(ITCondMask);
1300     Op->ITMask.Mask = Mask;
1301     Op->StartLoc = S;
1302     Op->EndLoc = S;
1303     return Op;
1304   }
1305
1306   static ARMOperand *CreateCondCode(ARMCC::CondCodes CC, SMLoc S) {
1307     ARMOperand *Op = new ARMOperand(CondCode);
1308     Op->CC.Val = CC;
1309     Op->StartLoc = S;
1310     Op->EndLoc = S;
1311     return Op;
1312   }
1313
1314   static ARMOperand *CreateCoprocNum(unsigned CopVal, SMLoc S) {
1315     ARMOperand *Op = new ARMOperand(CoprocNum);
1316     Op->Cop.Val = CopVal;
1317     Op->StartLoc = S;
1318     Op->EndLoc = S;
1319     return Op;
1320   }
1321
1322   static ARMOperand *CreateCoprocReg(unsigned CopVal, SMLoc S) {
1323     ARMOperand *Op = new ARMOperand(CoprocReg);
1324     Op->Cop.Val = CopVal;
1325     Op->StartLoc = S;
1326     Op->EndLoc = S;
1327     return Op;
1328   }
1329
1330   static ARMOperand *CreateCCOut(unsigned RegNum, SMLoc S) {
1331     ARMOperand *Op = new ARMOperand(CCOut);
1332     Op->Reg.RegNum = RegNum;
1333     Op->StartLoc = S;
1334     Op->EndLoc = S;
1335     return Op;
1336   }
1337
1338   static ARMOperand *CreateToken(StringRef Str, SMLoc S) {
1339     ARMOperand *Op = new ARMOperand(Token);
1340     Op->Tok.Data = Str.data();
1341     Op->Tok.Length = Str.size();
1342     Op->StartLoc = S;
1343     Op->EndLoc = S;
1344     return Op;
1345   }
1346
1347   static ARMOperand *CreateReg(unsigned RegNum, SMLoc S, SMLoc E) {
1348     ARMOperand *Op = new ARMOperand(Register);
1349     Op->Reg.RegNum = RegNum;
1350     Op->StartLoc = S;
1351     Op->EndLoc = E;
1352     return Op;
1353   }
1354
1355   static ARMOperand *CreateShiftedRegister(ARM_AM::ShiftOpc ShTy,
1356                                            unsigned SrcReg,
1357                                            unsigned ShiftReg,
1358                                            unsigned ShiftImm,
1359                                            SMLoc S, SMLoc E) {
1360     ARMOperand *Op = new ARMOperand(ShiftedRegister);
1361     Op->RegShiftedReg.ShiftTy = ShTy;
1362     Op->RegShiftedReg.SrcReg = SrcReg;
1363     Op->RegShiftedReg.ShiftReg = ShiftReg;
1364     Op->RegShiftedReg.ShiftImm = ShiftImm;
1365     Op->StartLoc = S;
1366     Op->EndLoc = E;
1367     return Op;
1368   }
1369
1370   static ARMOperand *CreateShiftedImmediate(ARM_AM::ShiftOpc ShTy,
1371                                             unsigned SrcReg,
1372                                             unsigned ShiftImm,
1373                                             SMLoc S, SMLoc E) {
1374     ARMOperand *Op = new ARMOperand(ShiftedImmediate);
1375     Op->RegShiftedImm.ShiftTy = ShTy;
1376     Op->RegShiftedImm.SrcReg = SrcReg;
1377     Op->RegShiftedImm.ShiftImm = ShiftImm;
1378     Op->StartLoc = S;
1379     Op->EndLoc = E;
1380     return Op;
1381   }
1382
1383   static ARMOperand *CreateShifterImm(bool isASR, unsigned Imm,
1384                                    SMLoc S, SMLoc E) {
1385     ARMOperand *Op = new ARMOperand(ShifterImmediate);
1386     Op->ShifterImm.isASR = isASR;
1387     Op->ShifterImm.Imm = Imm;
1388     Op->StartLoc = S;
1389     Op->EndLoc = E;
1390     return Op;
1391   }
1392
1393   static ARMOperand *CreateRotImm(unsigned Imm, SMLoc S, SMLoc E) {
1394     ARMOperand *Op = new ARMOperand(RotateImmediate);
1395     Op->RotImm.Imm = Imm;
1396     Op->StartLoc = S;
1397     Op->EndLoc = E;
1398     return Op;
1399   }
1400
1401   static ARMOperand *CreateBitfield(unsigned LSB, unsigned Width,
1402                                     SMLoc S, SMLoc E) {
1403     ARMOperand *Op = new ARMOperand(BitfieldDescriptor);
1404     Op->Bitfield.LSB = LSB;
1405     Op->Bitfield.Width = Width;
1406     Op->StartLoc = S;
1407     Op->EndLoc = E;
1408     return Op;
1409   }
1410
1411   static ARMOperand *
1412   CreateRegList(const SmallVectorImpl<std::pair<unsigned, SMLoc> > &Regs,
1413                 SMLoc StartLoc, SMLoc EndLoc) {
1414     KindTy Kind = RegisterList;
1415
1416     if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Regs.front().first))
1417       Kind = DPRRegisterList;
1418     else if (ARMMCRegisterClasses[ARM::SPRRegClassID].
1419              contains(Regs.front().first))
1420       Kind = SPRRegisterList;
1421
1422     ARMOperand *Op = new ARMOperand(Kind);
1423     for (SmallVectorImpl<std::pair<unsigned, SMLoc> >::const_iterator
1424            I = Regs.begin(), E = Regs.end(); I != E; ++I)
1425       Op->Registers.push_back(I->first);
1426     array_pod_sort(Op->Registers.begin(), Op->Registers.end());
1427     Op->StartLoc = StartLoc;
1428     Op->EndLoc = EndLoc;
1429     return Op;
1430   }
1431
1432   static ARMOperand *CreateImm(const MCExpr *Val, SMLoc S, SMLoc E) {
1433     ARMOperand *Op = new ARMOperand(Immediate);
1434     Op->Imm.Val = Val;
1435     Op->StartLoc = S;
1436     Op->EndLoc = E;
1437     return Op;
1438   }
1439
1440   static ARMOperand *CreateMem(unsigned BaseRegNum,
1441                                const MCConstantExpr *OffsetImm,
1442                                unsigned OffsetRegNum,
1443                                ARM_AM::ShiftOpc ShiftType,
1444                                unsigned ShiftImm,
1445                                bool isNegative,
1446                                SMLoc S, SMLoc E) {
1447     ARMOperand *Op = new ARMOperand(Memory);
1448     Op->Mem.BaseRegNum = BaseRegNum;
1449     Op->Mem.OffsetImm = OffsetImm;
1450     Op->Mem.OffsetRegNum = OffsetRegNum;
1451     Op->Mem.ShiftType = ShiftType;
1452     Op->Mem.ShiftImm = ShiftImm;
1453     Op->Mem.isNegative = isNegative;
1454     Op->StartLoc = S;
1455     Op->EndLoc = E;
1456     return Op;
1457   }
1458
1459   static ARMOperand *CreatePostIdxReg(unsigned RegNum, bool isAdd,
1460                                       ARM_AM::ShiftOpc ShiftTy,
1461                                       unsigned ShiftImm,
1462                                       SMLoc S, SMLoc E) {
1463     ARMOperand *Op = new ARMOperand(PostIndexRegister);
1464     Op->PostIdxReg.RegNum = RegNum;
1465     Op->PostIdxReg.isAdd = isAdd;
1466     Op->PostIdxReg.ShiftTy = ShiftTy;
1467     Op->PostIdxReg.ShiftImm = ShiftImm;
1468     Op->StartLoc = S;
1469     Op->EndLoc = E;
1470     return Op;
1471   }
1472
1473   static ARMOperand *CreateMemBarrierOpt(ARM_MB::MemBOpt Opt, SMLoc S) {
1474     ARMOperand *Op = new ARMOperand(MemBarrierOpt);
1475     Op->MBOpt.Val = Opt;
1476     Op->StartLoc = S;
1477     Op->EndLoc = S;
1478     return Op;
1479   }
1480
1481   static ARMOperand *CreateProcIFlags(ARM_PROC::IFlags IFlags, SMLoc S) {
1482     ARMOperand *Op = new ARMOperand(ProcIFlags);
1483     Op->IFlags.Val = IFlags;
1484     Op->StartLoc = S;
1485     Op->EndLoc = S;
1486     return Op;
1487   }
1488
1489   static ARMOperand *CreateMSRMask(unsigned MMask, SMLoc S) {
1490     ARMOperand *Op = new ARMOperand(MSRMask);
1491     Op->MMask.Val = MMask;
1492     Op->StartLoc = S;
1493     Op->EndLoc = S;
1494     return Op;
1495   }
1496 };
1497
1498 } // end anonymous namespace.
1499
1500 void ARMOperand::print(raw_ostream &OS) const {
1501   switch (Kind) {
1502   case CondCode:
1503     OS << "<ARMCC::" << ARMCondCodeToString(getCondCode()) << ">";
1504     break;
1505   case CCOut:
1506     OS << "<ccout " << getReg() << ">";
1507     break;
1508   case ITCondMask: {
1509     static char MaskStr[][6] = { "()", "(t)", "(e)", "(tt)", "(et)", "(te)",
1510       "(ee)", "(ttt)", "(ett)", "(tet)", "(eet)", "(tte)", "(ete)",
1511       "(tee)", "(eee)" };
1512     assert((ITMask.Mask & 0xf) == ITMask.Mask);
1513     OS << "<it-mask " << MaskStr[ITMask.Mask] << ">";
1514     break;
1515   }
1516   case CoprocNum:
1517     OS << "<coprocessor number: " << getCoproc() << ">";
1518     break;
1519   case CoprocReg:
1520     OS << "<coprocessor register: " << getCoproc() << ">";
1521     break;
1522   case MSRMask:
1523     OS << "<mask: " << getMSRMask() << ">";
1524     break;
1525   case Immediate:
1526     getImm()->print(OS);
1527     break;
1528   case MemBarrierOpt:
1529     OS << "<ARM_MB::" << MemBOptToString(getMemBarrierOpt()) << ">";
1530     break;
1531   case Memory:
1532     OS << "<memory "
1533        << " base:" << Mem.BaseRegNum;
1534     OS << ">";
1535     break;
1536   case PostIndexRegister:
1537     OS << "post-idx register " << (PostIdxReg.isAdd ? "" : "-")
1538        << PostIdxReg.RegNum;
1539     if (PostIdxReg.ShiftTy != ARM_AM::no_shift)
1540       OS << ARM_AM::getShiftOpcStr(PostIdxReg.ShiftTy) << " "
1541          << PostIdxReg.ShiftImm;
1542     OS << ">";
1543     break;
1544   case ProcIFlags: {
1545     OS << "<ARM_PROC::";
1546     unsigned IFlags = getProcIFlags();
1547     for (int i=2; i >= 0; --i)
1548       if (IFlags & (1 << i))
1549         OS << ARM_PROC::IFlagsToString(1 << i);
1550     OS << ">";
1551     break;
1552   }
1553   case Register:
1554     OS << "<register " << getReg() << ">";
1555     break;
1556   case ShifterImmediate:
1557     OS << "<shift " << (ShifterImm.isASR ? "asr" : "lsl")
1558        << " #" << ShifterImm.Imm << ">";
1559     break;
1560   case ShiftedRegister:
1561     OS << "<so_reg_reg "
1562        << RegShiftedReg.SrcReg
1563        << ARM_AM::getShiftOpcStr(ARM_AM::getSORegShOp(RegShiftedReg.ShiftImm))
1564        << ", " << RegShiftedReg.ShiftReg << ", "
1565        << ARM_AM::getSORegOffset(RegShiftedReg.ShiftImm)
1566        << ">";
1567     break;
1568   case ShiftedImmediate:
1569     OS << "<so_reg_imm "
1570        << RegShiftedImm.SrcReg
1571        << ARM_AM::getShiftOpcStr(ARM_AM::getSORegShOp(RegShiftedImm.ShiftImm))
1572        << ", " << ARM_AM::getSORegOffset(RegShiftedImm.ShiftImm)
1573        << ">";
1574     break;
1575   case RotateImmediate:
1576     OS << "<ror " << " #" << (RotImm.Imm * 8) << ">";
1577     break;
1578   case BitfieldDescriptor:
1579     OS << "<bitfield " << "lsb: " << Bitfield.LSB
1580        << ", width: " << Bitfield.Width << ">";
1581     break;
1582   case RegisterList:
1583   case DPRRegisterList:
1584   case SPRRegisterList: {
1585     OS << "<register_list ";
1586
1587     const SmallVectorImpl<unsigned> &RegList = getRegList();
1588     for (SmallVectorImpl<unsigned>::const_iterator
1589            I = RegList.begin(), E = RegList.end(); I != E; ) {
1590       OS << *I;
1591       if (++I < E) OS << ", ";
1592     }
1593
1594     OS << ">";
1595     break;
1596   }
1597   case Token:
1598     OS << "'" << getToken() << "'";
1599     break;
1600   }
1601 }
1602
1603 /// @name Auto-generated Match Functions
1604 /// {
1605
1606 static unsigned MatchRegisterName(StringRef Name);
1607
1608 /// }
1609
1610 bool ARMAsmParser::ParseRegister(unsigned &RegNo,
1611                                  SMLoc &StartLoc, SMLoc &EndLoc) {
1612   RegNo = tryParseRegister();
1613
1614   return (RegNo == (unsigned)-1);
1615 }
1616
1617 /// Try to parse a register name.  The token must be an Identifier when called,
1618 /// and if it is a register name the token is eaten and the register number is
1619 /// returned.  Otherwise return -1.
1620 ///
1621 int ARMAsmParser::tryParseRegister() {
1622   const AsmToken &Tok = Parser.getTok();
1623   if (Tok.isNot(AsmToken::Identifier)) return -1;
1624
1625   // FIXME: Validate register for the current architecture; we have to do
1626   // validation later, so maybe there is no need for this here.
1627   std::string upperCase = Tok.getString().str();
1628   std::string lowerCase = LowercaseString(upperCase);
1629   unsigned RegNum = MatchRegisterName(lowerCase);
1630   if (!RegNum) {
1631     RegNum = StringSwitch<unsigned>(lowerCase)
1632       .Case("r13", ARM::SP)
1633       .Case("r14", ARM::LR)
1634       .Case("r15", ARM::PC)
1635       .Case("ip", ARM::R12)
1636       .Default(0);
1637   }
1638   if (!RegNum) return -1;
1639
1640   Parser.Lex(); // Eat identifier token.
1641   return RegNum;
1642 }
1643
1644 // Try to parse a shifter  (e.g., "lsl <amt>"). On success, return 0.
1645 // If a recoverable error occurs, return 1. If an irrecoverable error
1646 // occurs, return -1. An irrecoverable error is one where tokens have been
1647 // consumed in the process of trying to parse the shifter (i.e., when it is
1648 // indeed a shifter operand, but malformed).
1649 int ARMAsmParser::tryParseShiftRegister(
1650                                SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1651   SMLoc S = Parser.getTok().getLoc();
1652   const AsmToken &Tok = Parser.getTok();
1653   assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
1654
1655   std::string upperCase = Tok.getString().str();
1656   std::string lowerCase = LowercaseString(upperCase);
1657   ARM_AM::ShiftOpc ShiftTy = StringSwitch<ARM_AM::ShiftOpc>(lowerCase)
1658       .Case("lsl", ARM_AM::lsl)
1659       .Case("lsr", ARM_AM::lsr)
1660       .Case("asr", ARM_AM::asr)
1661       .Case("ror", ARM_AM::ror)
1662       .Case("rrx", ARM_AM::rrx)
1663       .Default(ARM_AM::no_shift);
1664
1665   if (ShiftTy == ARM_AM::no_shift)
1666     return 1;
1667
1668   Parser.Lex(); // Eat the operator.
1669
1670   // The source register for the shift has already been added to the
1671   // operand list, so we need to pop it off and combine it into the shifted
1672   // register operand instead.
1673   OwningPtr<ARMOperand> PrevOp((ARMOperand*)Operands.pop_back_val());
1674   if (!PrevOp->isReg())
1675     return Error(PrevOp->getStartLoc(), "shift must be of a register");
1676   int SrcReg = PrevOp->getReg();
1677   int64_t Imm = 0;
1678   int ShiftReg = 0;
1679   if (ShiftTy == ARM_AM::rrx) {
1680     // RRX Doesn't have an explicit shift amount. The encoder expects
1681     // the shift register to be the same as the source register. Seems odd,
1682     // but OK.
1683     ShiftReg = SrcReg;
1684   } else {
1685     // Figure out if this is shifted by a constant or a register (for non-RRX).
1686     if (Parser.getTok().is(AsmToken::Hash)) {
1687       Parser.Lex(); // Eat hash.
1688       SMLoc ImmLoc = Parser.getTok().getLoc();
1689       const MCExpr *ShiftExpr = 0;
1690       if (getParser().ParseExpression(ShiftExpr)) {
1691         Error(ImmLoc, "invalid immediate shift value");
1692         return -1;
1693       }
1694       // The expression must be evaluatable as an immediate.
1695       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftExpr);
1696       if (!CE) {
1697         Error(ImmLoc, "invalid immediate shift value");
1698         return -1;
1699       }
1700       // Range check the immediate.
1701       // lsl, ror: 0 <= imm <= 31
1702       // lsr, asr: 0 <= imm <= 32
1703       Imm = CE->getValue();
1704       if (Imm < 0 ||
1705           ((ShiftTy == ARM_AM::lsl || ShiftTy == ARM_AM::ror) && Imm > 31) ||
1706           ((ShiftTy == ARM_AM::lsr || ShiftTy == ARM_AM::asr) && Imm > 32)) {
1707         Error(ImmLoc, "immediate shift value out of range");
1708         return -1;
1709       }
1710     } else if (Parser.getTok().is(AsmToken::Identifier)) {
1711       ShiftReg = tryParseRegister();
1712       SMLoc L = Parser.getTok().getLoc();
1713       if (ShiftReg == -1) {
1714         Error (L, "expected immediate or register in shift operand");
1715         return -1;
1716       }
1717     } else {
1718       Error (Parser.getTok().getLoc(),
1719                     "expected immediate or register in shift operand");
1720       return -1;
1721     }
1722   }
1723
1724   if (ShiftReg && ShiftTy != ARM_AM::rrx)
1725     Operands.push_back(ARMOperand::CreateShiftedRegister(ShiftTy, SrcReg,
1726                                                          ShiftReg, Imm,
1727                                                S, Parser.getTok().getLoc()));
1728   else
1729     Operands.push_back(ARMOperand::CreateShiftedImmediate(ShiftTy, SrcReg, Imm,
1730                                                S, Parser.getTok().getLoc()));
1731
1732   return 0;
1733 }
1734
1735
1736 /// Try to parse a register name.  The token must be an Identifier when called.
1737 /// If it's a register, an AsmOperand is created. Another AsmOperand is created
1738 /// if there is a "writeback". 'true' if it's not a register.
1739 ///
1740 /// TODO this is likely to change to allow different register types and or to
1741 /// parse for a specific register type.
1742 bool ARMAsmParser::
1743 tryParseRegisterWithWriteBack(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1744   SMLoc S = Parser.getTok().getLoc();
1745   int RegNo = tryParseRegister();
1746   if (RegNo == -1)
1747     return true;
1748
1749   Operands.push_back(ARMOperand::CreateReg(RegNo, S, Parser.getTok().getLoc()));
1750
1751   const AsmToken &ExclaimTok = Parser.getTok();
1752   if (ExclaimTok.is(AsmToken::Exclaim)) {
1753     Operands.push_back(ARMOperand::CreateToken(ExclaimTok.getString(),
1754                                                ExclaimTok.getLoc()));
1755     Parser.Lex(); // Eat exclaim token
1756   }
1757
1758   return false;
1759 }
1760
1761 /// MatchCoprocessorOperandName - Try to parse an coprocessor related
1762 /// instruction with a symbolic operand name. Example: "p1", "p7", "c3",
1763 /// "c5", ...
1764 static int MatchCoprocessorOperandName(StringRef Name, char CoprocOp) {
1765   // Use the same layout as the tablegen'erated register name matcher. Ugly,
1766   // but efficient.
1767   switch (Name.size()) {
1768   default: break;
1769   case 2:
1770     if (Name[0] != CoprocOp)
1771       return -1;
1772     switch (Name[1]) {
1773     default:  return -1;
1774     case '0': return 0;
1775     case '1': return 1;
1776     case '2': return 2;
1777     case '3': return 3;
1778     case '4': return 4;
1779     case '5': return 5;
1780     case '6': return 6;
1781     case '7': return 7;
1782     case '8': return 8;
1783     case '9': return 9;
1784     }
1785     break;
1786   case 3:
1787     if (Name[0] != CoprocOp || Name[1] != '1')
1788       return -1;
1789     switch (Name[2]) {
1790     default:  return -1;
1791     case '0': return 10;
1792     case '1': return 11;
1793     case '2': return 12;
1794     case '3': return 13;
1795     case '4': return 14;
1796     case '5': return 15;
1797     }
1798     break;
1799   }
1800
1801   return -1;
1802 }
1803
1804 /// parseITCondCode - Try to parse a condition code for an IT instruction.
1805 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
1806 parseITCondCode(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1807   SMLoc S = Parser.getTok().getLoc();
1808   const AsmToken &Tok = Parser.getTok();
1809   if (!Tok.is(AsmToken::Identifier))
1810     return MatchOperand_NoMatch;
1811   unsigned CC = StringSwitch<unsigned>(Tok.getString())
1812     .Case("eq", ARMCC::EQ)
1813     .Case("ne", ARMCC::NE)
1814     .Case("hs", ARMCC::HS)
1815     .Case("cs", ARMCC::HS)
1816     .Case("lo", ARMCC::LO)
1817     .Case("cc", ARMCC::LO)
1818     .Case("mi", ARMCC::MI)
1819     .Case("pl", ARMCC::PL)
1820     .Case("vs", ARMCC::VS)
1821     .Case("vc", ARMCC::VC)
1822     .Case("hi", ARMCC::HI)
1823     .Case("ls", ARMCC::LS)
1824     .Case("ge", ARMCC::GE)
1825     .Case("lt", ARMCC::LT)
1826     .Case("gt", ARMCC::GT)
1827     .Case("le", ARMCC::LE)
1828     .Case("al", ARMCC::AL)
1829     .Default(~0U);
1830   if (CC == ~0U)
1831     return MatchOperand_NoMatch;
1832   Parser.Lex(); // Eat the token.
1833
1834   Operands.push_back(ARMOperand::CreateCondCode(ARMCC::CondCodes(CC), S));
1835
1836   return MatchOperand_Success;
1837 }
1838
1839 /// parseCoprocNumOperand - Try to parse an coprocessor number operand. The
1840 /// token must be an Identifier when called, and if it is a coprocessor
1841 /// number, the token is eaten and the operand is added to the operand list.
1842 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
1843 parseCoprocNumOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1844   SMLoc S = Parser.getTok().getLoc();
1845   const AsmToken &Tok = Parser.getTok();
1846   assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
1847
1848   int Num = MatchCoprocessorOperandName(Tok.getString(), 'p');
1849   if (Num == -1)
1850     return MatchOperand_NoMatch;
1851
1852   Parser.Lex(); // Eat identifier token.
1853   Operands.push_back(ARMOperand::CreateCoprocNum(Num, S));
1854   return MatchOperand_Success;
1855 }
1856
1857 /// parseCoprocRegOperand - Try to parse an coprocessor register operand. The
1858 /// token must be an Identifier when called, and if it is a coprocessor
1859 /// number, the token is eaten and the operand is added to the operand list.
1860 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
1861 parseCoprocRegOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1862   SMLoc S = Parser.getTok().getLoc();
1863   const AsmToken &Tok = Parser.getTok();
1864   assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
1865
1866   int Reg = MatchCoprocessorOperandName(Tok.getString(), 'c');
1867   if (Reg == -1)
1868     return MatchOperand_NoMatch;
1869
1870   Parser.Lex(); // Eat identifier token.
1871   Operands.push_back(ARMOperand::CreateCoprocReg(Reg, S));
1872   return MatchOperand_Success;
1873 }
1874
1875 // For register list parsing, we need to map from raw GPR register numbering
1876 // to the enumeration values. The enumeration values aren't sorted by
1877 // register number due to our using "sp", "lr" and "pc" as canonical names.
1878 static unsigned getNextRegister(unsigned Reg) {
1879   // If this is a GPR, we need to do it manually, otherwise we can rely
1880   // on the sort ordering of the enumeration since the other reg-classes
1881   // are sane.
1882   if (!ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
1883     return Reg + 1;
1884   switch(Reg) {
1885   default: assert(0 && "Invalid GPR number!");
1886   case ARM::R0:  return ARM::R1;  case ARM::R1:  return ARM::R2;
1887   case ARM::R2:  return ARM::R3;  case ARM::R3:  return ARM::R4;
1888   case ARM::R4:  return ARM::R5;  case ARM::R5:  return ARM::R6;
1889   case ARM::R6:  return ARM::R7;  case ARM::R7:  return ARM::R8;
1890   case ARM::R8:  return ARM::R9;  case ARM::R9:  return ARM::R10;
1891   case ARM::R10: return ARM::R11; case ARM::R11: return ARM::R12;
1892   case ARM::R12: return ARM::SP;  case ARM::SP:  return ARM::LR;
1893   case ARM::LR:  return ARM::PC;  case ARM::PC:  return ARM::R0;
1894   }
1895 }
1896
1897 /// Parse a register list.
1898 bool ARMAsmParser::
1899 parseRegisterList(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1900   assert(Parser.getTok().is(AsmToken::LCurly) &&
1901          "Token is not a Left Curly Brace");
1902   SMLoc S = Parser.getTok().getLoc();
1903   Parser.Lex(); // Eat '{' token.
1904   SMLoc RegLoc = Parser.getTok().getLoc();
1905
1906   // Check the first register in the list to see what register class
1907   // this is a list of.
1908   int Reg = tryParseRegister();
1909   if (Reg == -1)
1910     return Error(RegLoc, "register expected");
1911
1912   MCRegisterClass *RC;
1913   if (ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
1914     RC = &ARMMCRegisterClasses[ARM::GPRRegClassID];
1915   else if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Reg))
1916     RC = &ARMMCRegisterClasses[ARM::DPRRegClassID];
1917   else if (ARMMCRegisterClasses[ARM::SPRRegClassID].contains(Reg))
1918     RC = &ARMMCRegisterClasses[ARM::SPRRegClassID];
1919   else
1920     return Error(RegLoc, "invalid register in register list");
1921
1922   // The reglist instructions have at most 16 registers, so reserve
1923   // space for that many.
1924   SmallVector<std::pair<unsigned, SMLoc>, 16> Registers;
1925   // Store the first register.
1926   Registers.push_back(std::pair<unsigned, SMLoc>(Reg, RegLoc));
1927
1928   // This starts immediately after the first register token in the list,
1929   // so we can see either a comma or a minus (range separator) as a legal
1930   // next token.
1931   while (Parser.getTok().is(AsmToken::Comma) ||
1932          Parser.getTok().is(AsmToken::Minus)) {
1933     if (Parser.getTok().is(AsmToken::Minus)) {
1934       Parser.Lex(); // Eat the comma.
1935       SMLoc EndLoc = Parser.getTok().getLoc();
1936       int EndReg = tryParseRegister();
1937       if (EndReg == -1)
1938         return Error(EndLoc, "register expected");
1939       // If the register is the same as the start reg, there's nothing
1940       // more to do.
1941       if (Reg == EndReg)
1942         continue;
1943       // The register must be in the same register class as the first.
1944       if (!RC->contains(EndReg))
1945         return Error(EndLoc, "invalid register in register list");
1946       // Ranges must go from low to high.
1947       if (getARMRegisterNumbering(Reg) > getARMRegisterNumbering(EndReg))
1948         return Error(EndLoc, "bad range in register list");
1949
1950       // Add all the registers in the range to the register list.
1951       while (Reg != EndReg) {
1952         Reg = getNextRegister(Reg);
1953         Registers.push_back(std::pair<unsigned, SMLoc>(Reg, RegLoc));
1954       }
1955       continue;
1956     }
1957     Parser.Lex(); // Eat the comma.
1958     RegLoc = Parser.getTok().getLoc();
1959     int OldReg = Reg;
1960     Reg = tryParseRegister();
1961     if (Reg == -1)
1962       return Error(RegLoc, "register expected");
1963     // The register must be in the same register class as the first.
1964     if (!RC->contains(Reg))
1965       return Error(RegLoc, "invalid register in register list");
1966     // List must be monotonically increasing.
1967     if (getARMRegisterNumbering(Reg) <= getARMRegisterNumbering(OldReg))
1968       return Error(RegLoc, "register list not in ascending order");
1969     // VFP register lists must also be contiguous.
1970     // It's OK to use the enumeration values directly here rather, as the
1971     // VFP register classes have the enum sorted properly.
1972     if (RC != &ARMMCRegisterClasses[ARM::GPRRegClassID] &&
1973         Reg != OldReg + 1)
1974       return Error(RegLoc, "non-contiguous register range");
1975     Registers.push_back(std::pair<unsigned, SMLoc>(Reg, RegLoc));
1976   }
1977
1978   SMLoc E = Parser.getTok().getLoc();
1979   if (Parser.getTok().isNot(AsmToken::RCurly))
1980     return Error(E, "'}' expected");
1981   Parser.Lex(); // Eat '}' token.
1982
1983   Operands.push_back(ARMOperand::CreateRegList(Registers, S, E));
1984   return false;
1985 }
1986
1987 /// parseMemBarrierOptOperand - Try to parse DSB/DMB data barrier options.
1988 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
1989 parseMemBarrierOptOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
1990   SMLoc S = Parser.getTok().getLoc();
1991   const AsmToken &Tok = Parser.getTok();
1992   assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
1993   StringRef OptStr = Tok.getString();
1994
1995   unsigned Opt = StringSwitch<unsigned>(OptStr.slice(0, OptStr.size()))
1996     .Case("sy",    ARM_MB::SY)
1997     .Case("st",    ARM_MB::ST)
1998     .Case("sh",    ARM_MB::ISH)
1999     .Case("ish",   ARM_MB::ISH)
2000     .Case("shst",  ARM_MB::ISHST)
2001     .Case("ishst", ARM_MB::ISHST)
2002     .Case("nsh",   ARM_MB::NSH)
2003     .Case("un",    ARM_MB::NSH)
2004     .Case("nshst", ARM_MB::NSHST)
2005     .Case("unst",  ARM_MB::NSHST)
2006     .Case("osh",   ARM_MB::OSH)
2007     .Case("oshst", ARM_MB::OSHST)
2008     .Default(~0U);
2009
2010   if (Opt == ~0U)
2011     return MatchOperand_NoMatch;
2012
2013   Parser.Lex(); // Eat identifier token.
2014   Operands.push_back(ARMOperand::CreateMemBarrierOpt((ARM_MB::MemBOpt)Opt, S));
2015   return MatchOperand_Success;
2016 }
2017
2018 /// parseProcIFlagsOperand - Try to parse iflags from CPS instruction.
2019 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
2020 parseProcIFlagsOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2021   SMLoc S = Parser.getTok().getLoc();
2022   const AsmToken &Tok = Parser.getTok();
2023   assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
2024   StringRef IFlagsStr = Tok.getString();
2025
2026   unsigned IFlags = 0;
2027   for (int i = 0, e = IFlagsStr.size(); i != e; ++i) {
2028     unsigned Flag = StringSwitch<unsigned>(IFlagsStr.substr(i, 1))
2029     .Case("a", ARM_PROC::A)
2030     .Case("i", ARM_PROC::I)
2031     .Case("f", ARM_PROC::F)
2032     .Default(~0U);
2033
2034     // If some specific iflag is already set, it means that some letter is
2035     // present more than once, this is not acceptable.
2036     if (Flag == ~0U || (IFlags & Flag))
2037       return MatchOperand_NoMatch;
2038
2039     IFlags |= Flag;
2040   }
2041
2042   Parser.Lex(); // Eat identifier token.
2043   Operands.push_back(ARMOperand::CreateProcIFlags((ARM_PROC::IFlags)IFlags, S));
2044   return MatchOperand_Success;
2045 }
2046
2047 /// parseMSRMaskOperand - Try to parse mask flags from MSR instruction.
2048 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
2049 parseMSRMaskOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2050   SMLoc S = Parser.getTok().getLoc();
2051   const AsmToken &Tok = Parser.getTok();
2052   assert(Tok.is(AsmToken::Identifier) && "Token is not an Identifier");
2053   StringRef Mask = Tok.getString();
2054
2055   // Split spec_reg from flag, example: CPSR_sxf => "CPSR" and "sxf"
2056   size_t Start = 0, Next = Mask.find('_');
2057   StringRef Flags = "";
2058   std::string SpecReg = LowercaseString(Mask.slice(Start, Next));
2059   if (Next != StringRef::npos)
2060     Flags = Mask.slice(Next+1, Mask.size());
2061
2062   // FlagsVal contains the complete mask:
2063   // 3-0: Mask
2064   // 4: Special Reg (cpsr, apsr => 0; spsr => 1)
2065   unsigned FlagsVal = 0;
2066
2067   if (SpecReg == "apsr") {
2068     FlagsVal = StringSwitch<unsigned>(Flags)
2069     .Case("nzcvq",  0x8) // same as CPSR_f
2070     .Case("g",      0x4) // same as CPSR_s
2071     .Case("nzcvqg", 0xc) // same as CPSR_fs
2072     .Default(~0U);
2073
2074     if (FlagsVal == ~0U) {
2075       if (!Flags.empty())
2076         return MatchOperand_NoMatch;
2077       else
2078         FlagsVal = 8; // No flag
2079     }
2080   } else if (SpecReg == "cpsr" || SpecReg == "spsr") {
2081     if (Flags == "all") // cpsr_all is an alias for cpsr_fc
2082       Flags = "fc";
2083     for (int i = 0, e = Flags.size(); i != e; ++i) {
2084       unsigned Flag = StringSwitch<unsigned>(Flags.substr(i, 1))
2085       .Case("c", 1)
2086       .Case("x", 2)
2087       .Case("s", 4)
2088       .Case("f", 8)
2089       .Default(~0U);
2090
2091       // If some specific flag is already set, it means that some letter is
2092       // present more than once, this is not acceptable.
2093       if (FlagsVal == ~0U || (FlagsVal & Flag))
2094         return MatchOperand_NoMatch;
2095       FlagsVal |= Flag;
2096     }
2097   } else // No match for special register.
2098     return MatchOperand_NoMatch;
2099
2100   // Special register without flags are equivalent to "fc" flags.
2101   if (!FlagsVal)
2102     FlagsVal = 0x9;
2103
2104   // Bit 4: Special Reg (cpsr, apsr => 0; spsr => 1)
2105   if (SpecReg == "spsr")
2106     FlagsVal |= 16;
2107
2108   Parser.Lex(); // Eat identifier token.
2109   Operands.push_back(ARMOperand::CreateMSRMask(FlagsVal, S));
2110   return MatchOperand_Success;
2111 }
2112
2113 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
2114 parsePKHImm(SmallVectorImpl<MCParsedAsmOperand*> &Operands, StringRef Op,
2115             int Low, int High) {
2116   const AsmToken &Tok = Parser.getTok();
2117   if (Tok.isNot(AsmToken::Identifier)) {
2118     Error(Parser.getTok().getLoc(), Op + " operand expected.");
2119     return MatchOperand_ParseFail;
2120   }
2121   StringRef ShiftName = Tok.getString();
2122   std::string LowerOp = LowercaseString(Op);
2123   std::string UpperOp = UppercaseString(Op);
2124   if (ShiftName != LowerOp && ShiftName != UpperOp) {
2125     Error(Parser.getTok().getLoc(), Op + " operand expected.");
2126     return MatchOperand_ParseFail;
2127   }
2128   Parser.Lex(); // Eat shift type token.
2129
2130   // There must be a '#' and a shift amount.
2131   if (Parser.getTok().isNot(AsmToken::Hash)) {
2132     Error(Parser.getTok().getLoc(), "'#' expected");
2133     return MatchOperand_ParseFail;
2134   }
2135   Parser.Lex(); // Eat hash token.
2136
2137   const MCExpr *ShiftAmount;
2138   SMLoc Loc = Parser.getTok().getLoc();
2139   if (getParser().ParseExpression(ShiftAmount)) {
2140     Error(Loc, "illegal expression");
2141     return MatchOperand_ParseFail;
2142   }
2143   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
2144   if (!CE) {
2145     Error(Loc, "constant expression expected");
2146     return MatchOperand_ParseFail;
2147   }
2148   int Val = CE->getValue();
2149   if (Val < Low || Val > High) {
2150     Error(Loc, "immediate value out of range");
2151     return MatchOperand_ParseFail;
2152   }
2153
2154   Operands.push_back(ARMOperand::CreateImm(CE, Loc, Parser.getTok().getLoc()));
2155
2156   return MatchOperand_Success;
2157 }
2158
2159 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
2160 parseSetEndImm(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2161   const AsmToken &Tok = Parser.getTok();
2162   SMLoc S = Tok.getLoc();
2163   if (Tok.isNot(AsmToken::Identifier)) {
2164     Error(Tok.getLoc(), "'be' or 'le' operand expected");
2165     return MatchOperand_ParseFail;
2166   }
2167   int Val = StringSwitch<int>(Tok.getString())
2168     .Case("be", 1)
2169     .Case("le", 0)
2170     .Default(-1);
2171   Parser.Lex(); // Eat the token.
2172
2173   if (Val == -1) {
2174     Error(Tok.getLoc(), "'be' or 'le' operand expected");
2175     return MatchOperand_ParseFail;
2176   }
2177   Operands.push_back(ARMOperand::CreateImm(MCConstantExpr::Create(Val,
2178                                                                   getContext()),
2179                                            S, Parser.getTok().getLoc()));
2180   return MatchOperand_Success;
2181 }
2182
2183 /// parseShifterImm - Parse the shifter immediate operand for SSAT/USAT
2184 /// instructions. Legal values are:
2185 ///     lsl #n  'n' in [0,31]
2186 ///     asr #n  'n' in [1,32]
2187 ///             n == 32 encoded as n == 0.
2188 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
2189 parseShifterImm(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2190   const AsmToken &Tok = Parser.getTok();
2191   SMLoc S = Tok.getLoc();
2192   if (Tok.isNot(AsmToken::Identifier)) {
2193     Error(S, "shift operator 'asr' or 'lsl' expected");
2194     return MatchOperand_ParseFail;
2195   }
2196   StringRef ShiftName = Tok.getString();
2197   bool isASR;
2198   if (ShiftName == "lsl" || ShiftName == "LSL")
2199     isASR = false;
2200   else if (ShiftName == "asr" || ShiftName == "ASR")
2201     isASR = true;
2202   else {
2203     Error(S, "shift operator 'asr' or 'lsl' expected");
2204     return MatchOperand_ParseFail;
2205   }
2206   Parser.Lex(); // Eat the operator.
2207
2208   // A '#' and a shift amount.
2209   if (Parser.getTok().isNot(AsmToken::Hash)) {
2210     Error(Parser.getTok().getLoc(), "'#' expected");
2211     return MatchOperand_ParseFail;
2212   }
2213   Parser.Lex(); // Eat hash token.
2214
2215   const MCExpr *ShiftAmount;
2216   SMLoc E = Parser.getTok().getLoc();
2217   if (getParser().ParseExpression(ShiftAmount)) {
2218     Error(E, "malformed shift expression");
2219     return MatchOperand_ParseFail;
2220   }
2221   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
2222   if (!CE) {
2223     Error(E, "shift amount must be an immediate");
2224     return MatchOperand_ParseFail;
2225   }
2226
2227   int64_t Val = CE->getValue();
2228   if (isASR) {
2229     // Shift amount must be in [1,32]
2230     if (Val < 1 || Val > 32) {
2231       Error(E, "'asr' shift amount must be in range [1,32]");
2232       return MatchOperand_ParseFail;
2233     }
2234     // asr #32 encoded as asr #0.
2235     if (Val == 32) Val = 0;
2236   } else {
2237     // Shift amount must be in [1,32]
2238     if (Val < 0 || Val > 31) {
2239       Error(E, "'lsr' shift amount must be in range [0,31]");
2240       return MatchOperand_ParseFail;
2241     }
2242   }
2243
2244   E = Parser.getTok().getLoc();
2245   Operands.push_back(ARMOperand::CreateShifterImm(isASR, Val, S, E));
2246
2247   return MatchOperand_Success;
2248 }
2249
2250 /// parseRotImm - Parse the shifter immediate operand for SXTB/UXTB family
2251 /// of instructions. Legal values are:
2252 ///     ror #n  'n' in {0, 8, 16, 24}
2253 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
2254 parseRotImm(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2255   const AsmToken &Tok = Parser.getTok();
2256   SMLoc S = Tok.getLoc();
2257   if (Tok.isNot(AsmToken::Identifier)) {
2258     Error(S, "rotate operator 'ror' expected");
2259     return MatchOperand_ParseFail;
2260   }
2261   StringRef ShiftName = Tok.getString();
2262   if (ShiftName != "ror" && ShiftName != "ROR") {
2263     Error(S, "rotate operator 'ror' expected");
2264     return MatchOperand_ParseFail;
2265   }
2266   Parser.Lex(); // Eat the operator.
2267
2268   // A '#' and a rotate amount.
2269   if (Parser.getTok().isNot(AsmToken::Hash)) {
2270     Error(Parser.getTok().getLoc(), "'#' expected");
2271     return MatchOperand_ParseFail;
2272   }
2273   Parser.Lex(); // Eat hash token.
2274
2275   const MCExpr *ShiftAmount;
2276   SMLoc E = Parser.getTok().getLoc();
2277   if (getParser().ParseExpression(ShiftAmount)) {
2278     Error(E, "malformed rotate expression");
2279     return MatchOperand_ParseFail;
2280   }
2281   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
2282   if (!CE) {
2283     Error(E, "rotate amount must be an immediate");
2284     return MatchOperand_ParseFail;
2285   }
2286
2287   int64_t Val = CE->getValue();
2288   // Shift amount must be in {0, 8, 16, 24} (0 is undocumented extension)
2289   // normally, zero is represented in asm by omitting the rotate operand
2290   // entirely.
2291   if (Val != 8 && Val != 16 && Val != 24 && Val != 0) {
2292     Error(E, "'ror' rotate amount must be 8, 16, or 24");
2293     return MatchOperand_ParseFail;
2294   }
2295
2296   E = Parser.getTok().getLoc();
2297   Operands.push_back(ARMOperand::CreateRotImm(Val, S, E));
2298
2299   return MatchOperand_Success;
2300 }
2301
2302 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
2303 parseBitfield(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2304   SMLoc S = Parser.getTok().getLoc();
2305   // The bitfield descriptor is really two operands, the LSB and the width.
2306   if (Parser.getTok().isNot(AsmToken::Hash)) {
2307     Error(Parser.getTok().getLoc(), "'#' expected");
2308     return MatchOperand_ParseFail;
2309   }
2310   Parser.Lex(); // Eat hash token.
2311
2312   const MCExpr *LSBExpr;
2313   SMLoc E = Parser.getTok().getLoc();
2314   if (getParser().ParseExpression(LSBExpr)) {
2315     Error(E, "malformed immediate expression");
2316     return MatchOperand_ParseFail;
2317   }
2318   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(LSBExpr);
2319   if (!CE) {
2320     Error(E, "'lsb' operand must be an immediate");
2321     return MatchOperand_ParseFail;
2322   }
2323
2324   int64_t LSB = CE->getValue();
2325   // The LSB must be in the range [0,31]
2326   if (LSB < 0 || LSB > 31) {
2327     Error(E, "'lsb' operand must be in the range [0,31]");
2328     return MatchOperand_ParseFail;
2329   }
2330   E = Parser.getTok().getLoc();
2331
2332   // Expect another immediate operand.
2333   if (Parser.getTok().isNot(AsmToken::Comma)) {
2334     Error(Parser.getTok().getLoc(), "too few operands");
2335     return MatchOperand_ParseFail;
2336   }
2337   Parser.Lex(); // Eat hash token.
2338   if (Parser.getTok().isNot(AsmToken::Hash)) {
2339     Error(Parser.getTok().getLoc(), "'#' expected");
2340     return MatchOperand_ParseFail;
2341   }
2342   Parser.Lex(); // Eat hash token.
2343
2344   const MCExpr *WidthExpr;
2345   if (getParser().ParseExpression(WidthExpr)) {
2346     Error(E, "malformed immediate expression");
2347     return MatchOperand_ParseFail;
2348   }
2349   CE = dyn_cast<MCConstantExpr>(WidthExpr);
2350   if (!CE) {
2351     Error(E, "'width' operand must be an immediate");
2352     return MatchOperand_ParseFail;
2353   }
2354
2355   int64_t Width = CE->getValue();
2356   // The LSB must be in the range [1,32-lsb]
2357   if (Width < 1 || Width > 32 - LSB) {
2358     Error(E, "'width' operand must be in the range [1,32-lsb]");
2359     return MatchOperand_ParseFail;
2360   }
2361   E = Parser.getTok().getLoc();
2362
2363   Operands.push_back(ARMOperand::CreateBitfield(LSB, Width, S, E));
2364
2365   return MatchOperand_Success;
2366 }
2367
2368 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
2369 parsePostIdxReg(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2370   // Check for a post-index addressing register operand. Specifically:
2371   // postidx_reg := '+' register {, shift}
2372   //              | '-' register {, shift}
2373   //              | register {, shift}
2374
2375   // This method must return MatchOperand_NoMatch without consuming any tokens
2376   // in the case where there is no match, as other alternatives take other
2377   // parse methods.
2378   AsmToken Tok = Parser.getTok();
2379   SMLoc S = Tok.getLoc();
2380   bool haveEaten = false;
2381   bool isAdd = true;
2382   int Reg = -1;
2383   if (Tok.is(AsmToken::Plus)) {
2384     Parser.Lex(); // Eat the '+' token.
2385     haveEaten = true;
2386   } else if (Tok.is(AsmToken::Minus)) {
2387     Parser.Lex(); // Eat the '-' token.
2388     isAdd = false;
2389     haveEaten = true;
2390   }
2391   if (Parser.getTok().is(AsmToken::Identifier))
2392     Reg = tryParseRegister();
2393   if (Reg == -1) {
2394     if (!haveEaten)
2395       return MatchOperand_NoMatch;
2396     Error(Parser.getTok().getLoc(), "register expected");
2397     return MatchOperand_ParseFail;
2398   }
2399   SMLoc E = Parser.getTok().getLoc();
2400
2401   ARM_AM::ShiftOpc ShiftTy = ARM_AM::no_shift;
2402   unsigned ShiftImm = 0;
2403   if (Parser.getTok().is(AsmToken::Comma)) {
2404     Parser.Lex(); // Eat the ','.
2405     if (parseMemRegOffsetShift(ShiftTy, ShiftImm))
2406       return MatchOperand_ParseFail;
2407   }
2408
2409   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ShiftTy,
2410                                                   ShiftImm, S, E));
2411
2412   return MatchOperand_Success;
2413 }
2414
2415 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
2416 parseAM3Offset(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2417   // Check for a post-index addressing register operand. Specifically:
2418   // am3offset := '+' register
2419   //              | '-' register
2420   //              | register
2421   //              | # imm
2422   //              | # + imm
2423   //              | # - imm
2424
2425   // This method must return MatchOperand_NoMatch without consuming any tokens
2426   // in the case where there is no match, as other alternatives take other
2427   // parse methods.
2428   AsmToken Tok = Parser.getTok();
2429   SMLoc S = Tok.getLoc();
2430
2431   // Do immediates first, as we always parse those if we have a '#'.
2432   if (Parser.getTok().is(AsmToken::Hash)) {
2433     Parser.Lex(); // Eat the '#'.
2434     // Explicitly look for a '-', as we need to encode negative zero
2435     // differently.
2436     bool isNegative = Parser.getTok().is(AsmToken::Minus);
2437     const MCExpr *Offset;
2438     if (getParser().ParseExpression(Offset))
2439       return MatchOperand_ParseFail;
2440     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
2441     if (!CE) {
2442       Error(S, "constant expression expected");
2443       return MatchOperand_ParseFail;
2444     }
2445     SMLoc E = Tok.getLoc();
2446     // Negative zero is encoded as the flag value INT32_MIN.
2447     int32_t Val = CE->getValue();
2448     if (isNegative && Val == 0)
2449       Val = INT32_MIN;
2450
2451     Operands.push_back(
2452       ARMOperand::CreateImm(MCConstantExpr::Create(Val, getContext()), S, E));
2453
2454     return MatchOperand_Success;
2455   }
2456
2457
2458   bool haveEaten = false;
2459   bool isAdd = true;
2460   int Reg = -1;
2461   if (Tok.is(AsmToken::Plus)) {
2462     Parser.Lex(); // Eat the '+' token.
2463     haveEaten = true;
2464   } else if (Tok.is(AsmToken::Minus)) {
2465     Parser.Lex(); // Eat the '-' token.
2466     isAdd = false;
2467     haveEaten = true;
2468   }
2469   if (Parser.getTok().is(AsmToken::Identifier))
2470     Reg = tryParseRegister();
2471   if (Reg == -1) {
2472     if (!haveEaten)
2473       return MatchOperand_NoMatch;
2474     Error(Parser.getTok().getLoc(), "register expected");
2475     return MatchOperand_ParseFail;
2476   }
2477   SMLoc E = Parser.getTok().getLoc();
2478
2479   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ARM_AM::no_shift,
2480                                                   0, S, E));
2481
2482   return MatchOperand_Success;
2483 }
2484
2485 /// cvtT2LdrdPre - Convert parsed operands to MCInst.
2486 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2487 /// when they refer multiple MIOperands inside a single one.
2488 bool ARMAsmParser::
2489 cvtT2LdrdPre(MCInst &Inst, unsigned Opcode,
2490              const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2491   // Rt, Rt2
2492   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2493   ((ARMOperand*)Operands[3])->addRegOperands(Inst, 1);
2494   // Create a writeback register dummy placeholder.
2495   Inst.addOperand(MCOperand::CreateReg(0));
2496   // addr
2497   ((ARMOperand*)Operands[4])->addMemImm8s4OffsetOperands(Inst, 2);
2498   // pred
2499   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2500   return true;
2501 }
2502
2503 /// cvtT2StrdPre - Convert parsed operands to MCInst.
2504 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2505 /// when they refer multiple MIOperands inside a single one.
2506 bool ARMAsmParser::
2507 cvtT2StrdPre(MCInst &Inst, unsigned Opcode,
2508              const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2509   // Create a writeback register dummy placeholder.
2510   Inst.addOperand(MCOperand::CreateReg(0));
2511   // Rt, Rt2
2512   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2513   ((ARMOperand*)Operands[3])->addRegOperands(Inst, 1);
2514   // addr
2515   ((ARMOperand*)Operands[4])->addMemImm8s4OffsetOperands(Inst, 2);
2516   // pred
2517   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2518   return true;
2519 }
2520
2521 /// cvtLdWriteBackRegT2AddrModeImm8 - Convert parsed operands to MCInst.
2522 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2523 /// when they refer multiple MIOperands inside a single one.
2524 bool ARMAsmParser::
2525 cvtLdWriteBackRegT2AddrModeImm8(MCInst &Inst, unsigned Opcode,
2526                          const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2527   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2528
2529   // Create a writeback register dummy placeholder.
2530   Inst.addOperand(MCOperand::CreateImm(0));
2531
2532   ((ARMOperand*)Operands[3])->addMemImm8OffsetOperands(Inst, 2);
2533   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2534   return true;
2535 }
2536
2537 /// cvtStWriteBackRegT2AddrModeImm8 - Convert parsed operands to MCInst.
2538 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2539 /// when they refer multiple MIOperands inside a single one.
2540 bool ARMAsmParser::
2541 cvtStWriteBackRegT2AddrModeImm8(MCInst &Inst, unsigned Opcode,
2542                          const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2543   // Create a writeback register dummy placeholder.
2544   Inst.addOperand(MCOperand::CreateImm(0));
2545   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2546   ((ARMOperand*)Operands[3])->addMemImm8OffsetOperands(Inst, 2);
2547   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2548   return true;
2549 }
2550
2551 /// cvtLdWriteBackRegAddrMode2 - Convert parsed operands to MCInst.
2552 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2553 /// when they refer multiple MIOperands inside a single one.
2554 bool ARMAsmParser::
2555 cvtLdWriteBackRegAddrMode2(MCInst &Inst, unsigned Opcode,
2556                          const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2557   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2558
2559   // Create a writeback register dummy placeholder.
2560   Inst.addOperand(MCOperand::CreateImm(0));
2561
2562   ((ARMOperand*)Operands[3])->addAddrMode2Operands(Inst, 3);
2563   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2564   return true;
2565 }
2566
2567 /// cvtLdWriteBackRegAddrModeImm12 - Convert parsed operands to MCInst.
2568 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2569 /// when they refer multiple MIOperands inside a single one.
2570 bool ARMAsmParser::
2571 cvtLdWriteBackRegAddrModeImm12(MCInst &Inst, unsigned Opcode,
2572                          const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2573   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2574
2575   // Create a writeback register dummy placeholder.
2576   Inst.addOperand(MCOperand::CreateImm(0));
2577
2578   ((ARMOperand*)Operands[3])->addMemImm12OffsetOperands(Inst, 2);
2579   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2580   return true;
2581 }
2582
2583
2584 /// cvtStWriteBackRegAddrModeImm12 - Convert parsed operands to MCInst.
2585 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2586 /// when they refer multiple MIOperands inside a single one.
2587 bool ARMAsmParser::
2588 cvtStWriteBackRegAddrModeImm12(MCInst &Inst, unsigned Opcode,
2589                          const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2590   // Create a writeback register dummy placeholder.
2591   Inst.addOperand(MCOperand::CreateImm(0));
2592   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2593   ((ARMOperand*)Operands[3])->addMemImm12OffsetOperands(Inst, 2);
2594   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2595   return true;
2596 }
2597
2598 /// cvtStWriteBackRegAddrMode2 - Convert parsed operands to MCInst.
2599 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2600 /// when they refer multiple MIOperands inside a single one.
2601 bool ARMAsmParser::
2602 cvtStWriteBackRegAddrMode2(MCInst &Inst, unsigned Opcode,
2603                          const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2604   // Create a writeback register dummy placeholder.
2605   Inst.addOperand(MCOperand::CreateImm(0));
2606   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2607   ((ARMOperand*)Operands[3])->addAddrMode2Operands(Inst, 3);
2608   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2609   return true;
2610 }
2611
2612 /// cvtStWriteBackRegAddrMode3 - Convert parsed operands to MCInst.
2613 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2614 /// when they refer multiple MIOperands inside a single one.
2615 bool ARMAsmParser::
2616 cvtStWriteBackRegAddrMode3(MCInst &Inst, unsigned Opcode,
2617                          const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2618   // Create a writeback register dummy placeholder.
2619   Inst.addOperand(MCOperand::CreateImm(0));
2620   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2621   ((ARMOperand*)Operands[3])->addAddrMode3Operands(Inst, 3);
2622   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2623   return true;
2624 }
2625
2626 /// cvtLdExtTWriteBackImm - Convert parsed operands to MCInst.
2627 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2628 /// when they refer multiple MIOperands inside a single one.
2629 bool ARMAsmParser::
2630 cvtLdExtTWriteBackImm(MCInst &Inst, unsigned Opcode,
2631                       const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2632   // Rt
2633   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2634   // Create a writeback register dummy placeholder.
2635   Inst.addOperand(MCOperand::CreateImm(0));
2636   // addr
2637   ((ARMOperand*)Operands[3])->addMemNoOffsetOperands(Inst, 1);
2638   // offset
2639   ((ARMOperand*)Operands[4])->addPostIdxImm8Operands(Inst, 1);
2640   // pred
2641   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2642   return true;
2643 }
2644
2645 /// cvtLdExtTWriteBackReg - Convert parsed operands to MCInst.
2646 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2647 /// when they refer multiple MIOperands inside a single one.
2648 bool ARMAsmParser::
2649 cvtLdExtTWriteBackReg(MCInst &Inst, unsigned Opcode,
2650                       const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2651   // Rt
2652   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2653   // Create a writeback register dummy placeholder.
2654   Inst.addOperand(MCOperand::CreateImm(0));
2655   // addr
2656   ((ARMOperand*)Operands[3])->addMemNoOffsetOperands(Inst, 1);
2657   // offset
2658   ((ARMOperand*)Operands[4])->addPostIdxRegOperands(Inst, 2);
2659   // pred
2660   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2661   return true;
2662 }
2663
2664 /// cvtStExtTWriteBackImm - Convert parsed operands to MCInst.
2665 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2666 /// when they refer multiple MIOperands inside a single one.
2667 bool ARMAsmParser::
2668 cvtStExtTWriteBackImm(MCInst &Inst, unsigned Opcode,
2669                       const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2670   // Create a writeback register dummy placeholder.
2671   Inst.addOperand(MCOperand::CreateImm(0));
2672   // Rt
2673   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2674   // addr
2675   ((ARMOperand*)Operands[3])->addMemNoOffsetOperands(Inst, 1);
2676   // offset
2677   ((ARMOperand*)Operands[4])->addPostIdxImm8Operands(Inst, 1);
2678   // pred
2679   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2680   return true;
2681 }
2682
2683 /// cvtStExtTWriteBackReg - Convert parsed operands to MCInst.
2684 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2685 /// when they refer multiple MIOperands inside a single one.
2686 bool ARMAsmParser::
2687 cvtStExtTWriteBackReg(MCInst &Inst, unsigned Opcode,
2688                       const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2689   // Create a writeback register dummy placeholder.
2690   Inst.addOperand(MCOperand::CreateImm(0));
2691   // Rt
2692   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2693   // addr
2694   ((ARMOperand*)Operands[3])->addMemNoOffsetOperands(Inst, 1);
2695   // offset
2696   ((ARMOperand*)Operands[4])->addPostIdxRegOperands(Inst, 2);
2697   // pred
2698   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2699   return true;
2700 }
2701
2702 /// cvtLdrdPre - Convert parsed operands to MCInst.
2703 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2704 /// when they refer multiple MIOperands inside a single one.
2705 bool ARMAsmParser::
2706 cvtLdrdPre(MCInst &Inst, unsigned Opcode,
2707            const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2708   // Rt, Rt2
2709   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2710   ((ARMOperand*)Operands[3])->addRegOperands(Inst, 1);
2711   // Create a writeback register dummy placeholder.
2712   Inst.addOperand(MCOperand::CreateImm(0));
2713   // addr
2714   ((ARMOperand*)Operands[4])->addAddrMode3Operands(Inst, 3);
2715   // pred
2716   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2717   return true;
2718 }
2719
2720 /// cvtStrdPre - Convert parsed operands to MCInst.
2721 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2722 /// when they refer multiple MIOperands inside a single one.
2723 bool ARMAsmParser::
2724 cvtStrdPre(MCInst &Inst, unsigned Opcode,
2725            const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2726   // Create a writeback register dummy placeholder.
2727   Inst.addOperand(MCOperand::CreateImm(0));
2728   // Rt, Rt2
2729   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2730   ((ARMOperand*)Operands[3])->addRegOperands(Inst, 1);
2731   // addr
2732   ((ARMOperand*)Operands[4])->addAddrMode3Operands(Inst, 3);
2733   // pred
2734   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2735   return true;
2736 }
2737
2738 /// cvtLdWriteBackRegAddrMode3 - Convert parsed operands to MCInst.
2739 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2740 /// when they refer multiple MIOperands inside a single one.
2741 bool ARMAsmParser::
2742 cvtLdWriteBackRegAddrMode3(MCInst &Inst, unsigned Opcode,
2743                          const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2744   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2745   // Create a writeback register dummy placeholder.
2746   Inst.addOperand(MCOperand::CreateImm(0));
2747   ((ARMOperand*)Operands[3])->addAddrMode3Operands(Inst, 3);
2748   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2749   return true;
2750 }
2751
2752 /// cvtThumbMultiple- Convert parsed operands to MCInst.
2753 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2754 /// when they refer multiple MIOperands inside a single one.
2755 bool ARMAsmParser::
2756 cvtThumbMultiply(MCInst &Inst, unsigned Opcode,
2757            const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2758   // The second source operand must be the same register as the destination
2759   // operand.
2760   if (Operands.size() == 6 &&
2761       (((ARMOperand*)Operands[3])->getReg() !=
2762        ((ARMOperand*)Operands[5])->getReg()) &&
2763       (((ARMOperand*)Operands[3])->getReg() !=
2764        ((ARMOperand*)Operands[4])->getReg())) {
2765     Error(Operands[3]->getStartLoc(),
2766           "destination register must match source register");
2767     return false;
2768   }
2769   ((ARMOperand*)Operands[3])->addRegOperands(Inst, 1);
2770   ((ARMOperand*)Operands[1])->addCCOutOperands(Inst, 1);
2771   ((ARMOperand*)Operands[4])->addRegOperands(Inst, 1);
2772   // If we have a three-operand form, use that, else the second source operand
2773   // is just the destination operand again.
2774   if (Operands.size() == 6)
2775     ((ARMOperand*)Operands[5])->addRegOperands(Inst, 1);
2776   else
2777     Inst.addOperand(Inst.getOperand(0));
2778   ((ARMOperand*)Operands[2])->addCondCodeOperands(Inst, 2);
2779
2780   return true;
2781 }
2782
2783 /// Parse an ARM memory expression, return false if successful else return true
2784 /// or an error.  The first token must be a '[' when called.
2785 bool ARMAsmParser::
2786 parseMemory(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2787   SMLoc S, E;
2788   assert(Parser.getTok().is(AsmToken::LBrac) &&
2789          "Token is not a Left Bracket");
2790   S = Parser.getTok().getLoc();
2791   Parser.Lex(); // Eat left bracket token.
2792
2793   const AsmToken &BaseRegTok = Parser.getTok();
2794   int BaseRegNum = tryParseRegister();
2795   if (BaseRegNum == -1)
2796     return Error(BaseRegTok.getLoc(), "register expected");
2797
2798   // The next token must either be a comma or a closing bracket.
2799   const AsmToken &Tok = Parser.getTok();
2800   if (!Tok.is(AsmToken::Comma) && !Tok.is(AsmToken::RBrac))
2801     return Error(Tok.getLoc(), "malformed memory operand");
2802
2803   if (Tok.is(AsmToken::RBrac)) {
2804     E = Tok.getLoc();
2805     Parser.Lex(); // Eat right bracket token.
2806
2807     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, 0, 0, ARM_AM::no_shift,
2808                                              0, false, S, E));
2809
2810     return false;
2811   }
2812
2813   assert(Tok.is(AsmToken::Comma) && "Lost comma in memory operand?!");
2814   Parser.Lex(); // Eat the comma.
2815
2816   // If we have a '#' it's an immediate offset, else assume it's a register
2817   // offset.
2818   if (Parser.getTok().is(AsmToken::Hash)) {
2819     Parser.Lex(); // Eat the '#'.
2820     E = Parser.getTok().getLoc();
2821
2822     bool isNegative = getParser().getTok().is(AsmToken::Minus);
2823     const MCExpr *Offset;
2824     if (getParser().ParseExpression(Offset))
2825      return true;
2826
2827     // The expression has to be a constant. Memory references with relocations
2828     // don't come through here, as they use the <label> forms of the relevant
2829     // instructions.
2830     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
2831     if (!CE)
2832       return Error (E, "constant expression expected");
2833
2834     // If the constant was #-0, represent it as INT32_MIN.
2835     int32_t Val = CE->getValue();
2836     if (isNegative && Val == 0)
2837       CE = MCConstantExpr::Create(INT32_MIN, getContext());
2838
2839     // Now we should have the closing ']'
2840     E = Parser.getTok().getLoc();
2841     if (Parser.getTok().isNot(AsmToken::RBrac))
2842       return Error(E, "']' expected");
2843     Parser.Lex(); // Eat right bracket token.
2844
2845     // Don't worry about range checking the value here. That's handled by
2846     // the is*() predicates.
2847     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, CE, 0,
2848                                              ARM_AM::no_shift, 0, false, S,E));
2849
2850     // If there's a pre-indexing writeback marker, '!', just add it as a token
2851     // operand.
2852     if (Parser.getTok().is(AsmToken::Exclaim)) {
2853       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
2854       Parser.Lex(); // Eat the '!'.
2855     }
2856
2857     return false;
2858   }
2859
2860   // The register offset is optionally preceded by a '+' or '-'
2861   bool isNegative = false;
2862   if (Parser.getTok().is(AsmToken::Minus)) {
2863     isNegative = true;
2864     Parser.Lex(); // Eat the '-'.
2865   } else if (Parser.getTok().is(AsmToken::Plus)) {
2866     // Nothing to do.
2867     Parser.Lex(); // Eat the '+'.
2868   }
2869
2870   E = Parser.getTok().getLoc();
2871   int OffsetRegNum = tryParseRegister();
2872   if (OffsetRegNum == -1)
2873     return Error(E, "register expected");
2874
2875   // If there's a shift operator, handle it.
2876   ARM_AM::ShiftOpc ShiftType = ARM_AM::no_shift;
2877   unsigned ShiftImm = 0;
2878   if (Parser.getTok().is(AsmToken::Comma)) {
2879     Parser.Lex(); // Eat the ','.
2880     if (parseMemRegOffsetShift(ShiftType, ShiftImm))
2881       return true;
2882   }
2883
2884   // Now we should have the closing ']'
2885   E = Parser.getTok().getLoc();
2886   if (Parser.getTok().isNot(AsmToken::RBrac))
2887     return Error(E, "']' expected");
2888   Parser.Lex(); // Eat right bracket token.
2889
2890   Operands.push_back(ARMOperand::CreateMem(BaseRegNum, 0, OffsetRegNum,
2891                                            ShiftType, ShiftImm, isNegative,
2892                                            S, E));
2893
2894   // If there's a pre-indexing writeback marker, '!', just add it as a token
2895   // operand.
2896   if (Parser.getTok().is(AsmToken::Exclaim)) {
2897     Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
2898     Parser.Lex(); // Eat the '!'.
2899   }
2900
2901   return false;
2902 }
2903
2904 /// parseMemRegOffsetShift - one of these two:
2905 ///   ( lsl | lsr | asr | ror ) , # shift_amount
2906 ///   rrx
2907 /// return true if it parses a shift otherwise it returns false.
2908 bool ARMAsmParser::parseMemRegOffsetShift(ARM_AM::ShiftOpc &St,
2909                                           unsigned &Amount) {
2910   SMLoc Loc = Parser.getTok().getLoc();
2911   const AsmToken &Tok = Parser.getTok();
2912   if (Tok.isNot(AsmToken::Identifier))
2913     return true;
2914   StringRef ShiftName = Tok.getString();
2915   if (ShiftName == "lsl" || ShiftName == "LSL")
2916     St = ARM_AM::lsl;
2917   else if (ShiftName == "lsr" || ShiftName == "LSR")
2918     St = ARM_AM::lsr;
2919   else if (ShiftName == "asr" || ShiftName == "ASR")
2920     St = ARM_AM::asr;
2921   else if (ShiftName == "ror" || ShiftName == "ROR")
2922     St = ARM_AM::ror;
2923   else if (ShiftName == "rrx" || ShiftName == "RRX")
2924     St = ARM_AM::rrx;
2925   else
2926     return Error(Loc, "illegal shift operator");
2927   Parser.Lex(); // Eat shift type token.
2928
2929   // rrx stands alone.
2930   Amount = 0;
2931   if (St != ARM_AM::rrx) {
2932     Loc = Parser.getTok().getLoc();
2933     // A '#' and a shift amount.
2934     const AsmToken &HashTok = Parser.getTok();
2935     if (HashTok.isNot(AsmToken::Hash))
2936       return Error(HashTok.getLoc(), "'#' expected");
2937     Parser.Lex(); // Eat hash token.
2938
2939     const MCExpr *Expr;
2940     if (getParser().ParseExpression(Expr))
2941       return true;
2942     // Range check the immediate.
2943     // lsl, ror: 0 <= imm <= 31
2944     // lsr, asr: 0 <= imm <= 32
2945     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
2946     if (!CE)
2947       return Error(Loc, "shift amount must be an immediate");
2948     int64_t Imm = CE->getValue();
2949     if (Imm < 0 ||
2950         ((St == ARM_AM::lsl || St == ARM_AM::ror) && Imm > 31) ||
2951         ((St == ARM_AM::lsr || St == ARM_AM::asr) && Imm > 32))
2952       return Error(Loc, "immediate shift value out of range");
2953     Amount = Imm;
2954   }
2955
2956   return false;
2957 }
2958
2959 /// Parse a arm instruction operand.  For now this parses the operand regardless
2960 /// of the mnemonic.
2961 bool ARMAsmParser::parseOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands,
2962                                 StringRef Mnemonic) {
2963   SMLoc S, E;
2964
2965   // Check if the current operand has a custom associated parser, if so, try to
2966   // custom parse the operand, or fallback to the general approach.
2967   OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
2968   if (ResTy == MatchOperand_Success)
2969     return false;
2970   // If there wasn't a custom match, try the generic matcher below. Otherwise,
2971   // there was a match, but an error occurred, in which case, just return that
2972   // the operand parsing failed.
2973   if (ResTy == MatchOperand_ParseFail)
2974     return true;
2975
2976   switch (getLexer().getKind()) {
2977   default:
2978     Error(Parser.getTok().getLoc(), "unexpected token in operand");
2979     return true;
2980   case AsmToken::Identifier: {
2981     if (!tryParseRegisterWithWriteBack(Operands))
2982       return false;
2983     int Res = tryParseShiftRegister(Operands);
2984     if (Res == 0) // success
2985       return false;
2986     else if (Res == -1) // irrecoverable error
2987       return true;
2988
2989     // Fall though for the Identifier case that is not a register or a
2990     // special name.
2991   }
2992   case AsmToken::Integer: // things like 1f and 2b as a branch targets
2993   case AsmToken::Dot: {   // . as a branch target
2994     // This was not a register so parse other operands that start with an
2995     // identifier (like labels) as expressions and create them as immediates.
2996     const MCExpr *IdVal;
2997     S = Parser.getTok().getLoc();
2998     if (getParser().ParseExpression(IdVal))
2999       return true;
3000     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
3001     Operands.push_back(ARMOperand::CreateImm(IdVal, S, E));
3002     return false;
3003   }
3004   case AsmToken::LBrac:
3005     return parseMemory(Operands);
3006   case AsmToken::LCurly:
3007     return parseRegisterList(Operands);
3008   case AsmToken::Hash: {
3009     // #42 -> immediate.
3010     // TODO: ":lower16:" and ":upper16:" modifiers after # before immediate
3011     S = Parser.getTok().getLoc();
3012     Parser.Lex();
3013     bool isNegative = Parser.getTok().is(AsmToken::Minus);
3014     const MCExpr *ImmVal;
3015     if (getParser().ParseExpression(ImmVal))
3016       return true;
3017     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ImmVal);
3018     if (!CE) {
3019       Error(S, "constant expression expected");
3020       return MatchOperand_ParseFail;
3021     }
3022     int32_t Val = CE->getValue();
3023     if (isNegative && Val == 0)
3024       ImmVal = MCConstantExpr::Create(INT32_MIN, getContext());
3025     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
3026     Operands.push_back(ARMOperand::CreateImm(ImmVal, S, E));
3027     return false;
3028   }
3029   case AsmToken::Colon: {
3030     // ":lower16:" and ":upper16:" expression prefixes
3031     // FIXME: Check it's an expression prefix,
3032     // e.g. (FOO - :lower16:BAR) isn't legal.
3033     ARMMCExpr::VariantKind RefKind;
3034     if (parsePrefix(RefKind))
3035       return true;
3036
3037     const MCExpr *SubExprVal;
3038     if (getParser().ParseExpression(SubExprVal))
3039       return true;
3040
3041     const MCExpr *ExprVal = ARMMCExpr::Create(RefKind, SubExprVal,
3042                                                    getContext());
3043     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
3044     Operands.push_back(ARMOperand::CreateImm(ExprVal, S, E));
3045     return false;
3046   }
3047   }
3048 }
3049
3050 // parsePrefix - Parse ARM 16-bit relocations expression prefix, i.e.
3051 //  :lower16: and :upper16:.
3052 bool ARMAsmParser::parsePrefix(ARMMCExpr::VariantKind &RefKind) {
3053   RefKind = ARMMCExpr::VK_ARM_None;
3054
3055   // :lower16: and :upper16: modifiers
3056   assert(getLexer().is(AsmToken::Colon) && "expected a :");
3057   Parser.Lex(); // Eat ':'
3058
3059   if (getLexer().isNot(AsmToken::Identifier)) {
3060     Error(Parser.getTok().getLoc(), "expected prefix identifier in operand");
3061     return true;
3062   }
3063
3064   StringRef IDVal = Parser.getTok().getIdentifier();
3065   if (IDVal == "lower16") {
3066     RefKind = ARMMCExpr::VK_ARM_LO16;
3067   } else if (IDVal == "upper16") {
3068     RefKind = ARMMCExpr::VK_ARM_HI16;
3069   } else {
3070     Error(Parser.getTok().getLoc(), "unexpected prefix in operand");
3071     return true;
3072   }
3073   Parser.Lex();
3074
3075   if (getLexer().isNot(AsmToken::Colon)) {
3076     Error(Parser.getTok().getLoc(), "unexpected token after prefix");
3077     return true;
3078   }
3079   Parser.Lex(); // Eat the last ':'
3080   return false;
3081 }
3082
3083 /// \brief Given a mnemonic, split out possible predication code and carry
3084 /// setting letters to form a canonical mnemonic and flags.
3085 //
3086 // FIXME: Would be nice to autogen this.
3087 // FIXME: This is a bit of a maze of special cases.
3088 StringRef ARMAsmParser::splitMnemonic(StringRef Mnemonic,
3089                                       unsigned &PredicationCode,
3090                                       bool &CarrySetting,
3091                                       unsigned &ProcessorIMod,
3092                                       StringRef &ITMask) {
3093   PredicationCode = ARMCC::AL;
3094   CarrySetting = false;
3095   ProcessorIMod = 0;
3096
3097   // Ignore some mnemonics we know aren't predicated forms.
3098   //
3099   // FIXME: Would be nice to autogen this.
3100   if ((Mnemonic == "movs" && isThumb()) ||
3101       Mnemonic == "teq"   || Mnemonic == "vceq"   || Mnemonic == "svc"   ||
3102       Mnemonic == "mls"   || Mnemonic == "smmls"  || Mnemonic == "vcls"  ||
3103       Mnemonic == "vmls"  || Mnemonic == "vnmls"  || Mnemonic == "vacge" ||
3104       Mnemonic == "vcge"  || Mnemonic == "vclt"   || Mnemonic == "vacgt" ||
3105       Mnemonic == "vcgt"  || Mnemonic == "vcle"   || Mnemonic == "smlal" ||
3106       Mnemonic == "umaal" || Mnemonic == "umlal"  || Mnemonic == "vabal" ||
3107       Mnemonic == "vmlal" || Mnemonic == "vpadal" || Mnemonic == "vqdmlal")
3108     return Mnemonic;
3109
3110   // First, split out any predication code. Ignore mnemonics we know aren't
3111   // predicated but do have a carry-set and so weren't caught above.
3112   if (Mnemonic != "adcs" && Mnemonic != "bics" && Mnemonic != "movs" &&
3113       Mnemonic != "muls" && Mnemonic != "smlals" && Mnemonic != "smulls" &&
3114       Mnemonic != "umlals" && Mnemonic != "umulls" && Mnemonic != "lsls" &&
3115       Mnemonic != "sbcs" && Mnemonic != "rscs") {
3116     unsigned CC = StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2))
3117       .Case("eq", ARMCC::EQ)
3118       .Case("ne", ARMCC::NE)
3119       .Case("hs", ARMCC::HS)
3120       .Case("cs", ARMCC::HS)
3121       .Case("lo", ARMCC::LO)
3122       .Case("cc", ARMCC::LO)
3123       .Case("mi", ARMCC::MI)
3124       .Case("pl", ARMCC::PL)
3125       .Case("vs", ARMCC::VS)
3126       .Case("vc", ARMCC::VC)
3127       .Case("hi", ARMCC::HI)
3128       .Case("ls", ARMCC::LS)
3129       .Case("ge", ARMCC::GE)
3130       .Case("lt", ARMCC::LT)
3131       .Case("gt", ARMCC::GT)
3132       .Case("le", ARMCC::LE)
3133       .Case("al", ARMCC::AL)
3134       .Default(~0U);
3135     if (CC != ~0U) {
3136       Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 2);
3137       PredicationCode = CC;
3138     }
3139   }
3140
3141   // Next, determine if we have a carry setting bit. We explicitly ignore all
3142   // the instructions we know end in 's'.
3143   if (Mnemonic.endswith("s") &&
3144       !(Mnemonic == "cps" || Mnemonic == "mls" ||
3145         Mnemonic == "mrs" || Mnemonic == "smmls" || Mnemonic == "vabs" ||
3146         Mnemonic == "vcls" || Mnemonic == "vmls" || Mnemonic == "vmrs" ||
3147         Mnemonic == "vnmls" || Mnemonic == "vqabs" || Mnemonic == "vrecps" ||
3148         Mnemonic == "vrsqrts" || Mnemonic == "srs" ||
3149         (Mnemonic == "movs" && isThumb()))) {
3150     Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 1);
3151     CarrySetting = true;
3152   }
3153
3154   // The "cps" instruction can have a interrupt mode operand which is glued into
3155   // the mnemonic. Check if this is the case, split it and parse the imod op
3156   if (Mnemonic.startswith("cps")) {
3157     // Split out any imod code.
3158     unsigned IMod =
3159       StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2, 2))
3160       .Case("ie", ARM_PROC::IE)
3161       .Case("id", ARM_PROC::ID)
3162       .Default(~0U);
3163     if (IMod != ~0U) {
3164       Mnemonic = Mnemonic.slice(0, Mnemonic.size()-2);
3165       ProcessorIMod = IMod;
3166     }
3167   }
3168
3169   // The "it" instruction has the condition mask on the end of the mnemonic.
3170   if (Mnemonic.startswith("it")) {
3171     ITMask = Mnemonic.slice(2, Mnemonic.size());
3172     Mnemonic = Mnemonic.slice(0, 2);
3173   }
3174
3175   return Mnemonic;
3176 }
3177
3178 /// \brief Given a canonical mnemonic, determine if the instruction ever allows
3179 /// inclusion of carry set or predication code operands.
3180 //
3181 // FIXME: It would be nice to autogen this.
3182 void ARMAsmParser::
3183 getMnemonicAcceptInfo(StringRef Mnemonic, bool &CanAcceptCarrySet,
3184                       bool &CanAcceptPredicationCode) {
3185   if (Mnemonic == "and" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
3186       Mnemonic == "rrx" || Mnemonic == "ror" || Mnemonic == "sub" ||
3187       Mnemonic == "add" || Mnemonic == "adc" ||
3188       Mnemonic == "mul" || Mnemonic == "bic" || Mnemonic == "asr" ||
3189       Mnemonic == "umlal" || Mnemonic == "orr" || Mnemonic == "mvn" ||
3190       Mnemonic == "rsb" || Mnemonic == "rsc" || Mnemonic == "orn" ||
3191       Mnemonic == "sbc" || Mnemonic == "umull" || Mnemonic == "eor" ||
3192       Mnemonic == "neg" ||
3193       (!isThumb() && (Mnemonic == "smull" || Mnemonic == "mov" ||
3194                       Mnemonic == "mla" || Mnemonic == "smlal"))) {
3195     CanAcceptCarrySet = true;
3196   } else
3197     CanAcceptCarrySet = false;
3198
3199   if (Mnemonic == "cbnz" || Mnemonic == "setend" || Mnemonic == "dmb" ||
3200       Mnemonic == "cps" || Mnemonic == "mcr2" || Mnemonic == "it" ||
3201       Mnemonic == "mcrr2" || Mnemonic == "cbz" || Mnemonic == "cdp2" ||
3202       Mnemonic == "trap" || Mnemonic == "mrc2" || Mnemonic == "mrrc2" ||
3203       Mnemonic == "dsb" || Mnemonic == "isb" || Mnemonic == "setend" ||
3204       (Mnemonic == "clrex" && !isThumb()) ||
3205       (Mnemonic == "nop" && isThumbOne()) ||
3206       ((Mnemonic == "pld" || Mnemonic == "pli" || Mnemonic == "pldw") &&
3207        !isThumb()) ||
3208       ((Mnemonic.startswith("rfe") || Mnemonic.startswith("srs")) &&
3209        !isThumb()) ||
3210       Mnemonic.startswith("cps") || (Mnemonic == "movs" && isThumbOne())) {
3211     CanAcceptPredicationCode = false;
3212   } else
3213     CanAcceptPredicationCode = true;
3214
3215   if (isThumb()) {
3216     if (Mnemonic == "bkpt" || Mnemonic == "mcr" || Mnemonic == "mcrr" ||
3217         Mnemonic == "mrc" || Mnemonic == "mrrc" || Mnemonic == "cdp")
3218       CanAcceptPredicationCode = false;
3219   }
3220 }
3221
3222 bool ARMAsmParser::shouldOmitCCOutOperand(StringRef Mnemonic,
3223                                SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
3224   // FIXME: This is all horribly hacky. We really need a better way to deal
3225   // with optional operands like this in the matcher table.
3226
3227   // The 'mov' mnemonic is special. One variant has a cc_out operand, while
3228   // another does not. Specifically, the MOVW instruction does not. So we
3229   // special case it here and remove the defaulted (non-setting) cc_out
3230   // operand if that's the instruction we're trying to match.
3231   //
3232   // We do this as post-processing of the explicit operands rather than just
3233   // conditionally adding the cc_out in the first place because we need
3234   // to check the type of the parsed immediate operand.
3235   if (Mnemonic == "mov" && Operands.size() > 4 && !isThumb() &&
3236       !static_cast<ARMOperand*>(Operands[4])->isARMSOImm() &&
3237       static_cast<ARMOperand*>(Operands[4])->isImm0_65535Expr() &&
3238       static_cast<ARMOperand*>(Operands[1])->getReg() == 0)
3239     return true;
3240
3241   // Register-register 'add' for thumb does not have a cc_out operand
3242   // when there are only two register operands.
3243   if (isThumb() && Mnemonic == "add" && Operands.size() == 5 &&
3244       static_cast<ARMOperand*>(Operands[3])->isReg() &&
3245       static_cast<ARMOperand*>(Operands[4])->isReg() &&
3246       static_cast<ARMOperand*>(Operands[1])->getReg() == 0)
3247     return true;
3248   // Register-register 'add' for thumb does not have a cc_out operand
3249   // when it's an ADD Rdm, SP, {Rdm|#imm0_255} instruction. We do
3250   // have to check the immediate range here since Thumb2 has a variant
3251   // that can handle a different range and has a cc_out operand.
3252   if (((isThumb() && Mnemonic == "add") ||
3253        (isThumbTwo() && Mnemonic == "sub")) &&
3254       Operands.size() == 6 &&
3255       static_cast<ARMOperand*>(Operands[3])->isReg() &&
3256       static_cast<ARMOperand*>(Operands[4])->isReg() &&
3257       static_cast<ARMOperand*>(Operands[4])->getReg() == ARM::SP &&
3258       static_cast<ARMOperand*>(Operands[1])->getReg() == 0 &&
3259       (static_cast<ARMOperand*>(Operands[5])->isReg() ||
3260        static_cast<ARMOperand*>(Operands[5])->isImm0_1020s4()))
3261     return true;
3262   // For Thumb2, add/sub immediate does not have a cc_out operand for the
3263   // imm0_4095 variant. That's the least-preferred variant when
3264   // selecting via the generic "add" mnemonic, so to know that we
3265   // should remove the cc_out operand, we have to explicitly check that
3266   // it's not one of the other variants. Ugh.
3267   if (isThumbTwo() && (Mnemonic == "add" || Mnemonic == "sub") &&
3268       Operands.size() == 6 &&
3269       static_cast<ARMOperand*>(Operands[3])->isReg() &&
3270       static_cast<ARMOperand*>(Operands[4])->isReg() &&
3271       static_cast<ARMOperand*>(Operands[5])->isImm()) {
3272     // Nest conditions rather than one big 'if' statement for readability.
3273     //
3274     // If either register is a high reg, it's either one of the SP
3275     // variants (handled above) or a 32-bit encoding, so we just
3276     // check against T3.
3277     if ((!isARMLowRegister(static_cast<ARMOperand*>(Operands[3])->getReg()) ||
3278          !isARMLowRegister(static_cast<ARMOperand*>(Operands[4])->getReg())) &&
3279         static_cast<ARMOperand*>(Operands[5])->isT2SOImm())
3280       return false;
3281     // If both registers are low, we're in an IT block, and the immediate is
3282     // in range, we should use encoding T1 instead, which has a cc_out.
3283     if (inITBlock() &&
3284         isARMLowRegister(static_cast<ARMOperand*>(Operands[3])->getReg()) &&
3285         isARMLowRegister(static_cast<ARMOperand*>(Operands[4])->getReg()) &&
3286         static_cast<ARMOperand*>(Operands[5])->isImm0_7())
3287       return false;
3288
3289     // Otherwise, we use encoding T4, which does not have a cc_out
3290     // operand.
3291     return true;
3292   }
3293
3294   // The thumb2 multiply instruction doesn't have a CCOut register, so
3295   // if we have a "mul" mnemonic in Thumb mode, check if we'll be able to
3296   // use the 16-bit encoding or not.
3297   if (isThumbTwo() && Mnemonic == "mul" && Operands.size() == 6 &&
3298       static_cast<ARMOperand*>(Operands[1])->getReg() == 0 &&
3299       static_cast<ARMOperand*>(Operands[3])->isReg() &&
3300       static_cast<ARMOperand*>(Operands[4])->isReg() &&
3301       static_cast<ARMOperand*>(Operands[5])->isReg() &&
3302       // If the registers aren't low regs, the destination reg isn't the
3303       // same as one of the source regs, or the cc_out operand is zero
3304       // outside of an IT block, we have to use the 32-bit encoding, so
3305       // remove the cc_out operand.
3306       (!isARMLowRegister(static_cast<ARMOperand*>(Operands[3])->getReg()) ||
3307        !isARMLowRegister(static_cast<ARMOperand*>(Operands[4])->getReg()) ||
3308        !inITBlock() ||
3309        (static_cast<ARMOperand*>(Operands[3])->getReg() !=
3310         static_cast<ARMOperand*>(Operands[5])->getReg() &&
3311         static_cast<ARMOperand*>(Operands[3])->getReg() !=
3312         static_cast<ARMOperand*>(Operands[4])->getReg())))
3313     return true;
3314
3315
3316
3317   // Register-register 'add/sub' for thumb does not have a cc_out operand
3318   // when it's an ADD/SUB SP, #imm. Be lenient on count since there's also
3319   // the "add/sub SP, SP, #imm" version. If the follow-up operands aren't
3320   // right, this will result in better diagnostics (which operand is off)
3321   // anyway.
3322   if (isThumb() && (Mnemonic == "add" || Mnemonic == "sub") &&
3323       (Operands.size() == 5 || Operands.size() == 6) &&
3324       static_cast<ARMOperand*>(Operands[3])->isReg() &&
3325       static_cast<ARMOperand*>(Operands[3])->getReg() == ARM::SP &&
3326       static_cast<ARMOperand*>(Operands[1])->getReg() == 0)
3327     return true;
3328
3329   return false;
3330 }
3331
3332 /// Parse an arm instruction mnemonic followed by its operands.
3333 bool ARMAsmParser::ParseInstruction(StringRef Name, SMLoc NameLoc,
3334                                SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
3335   // Create the leading tokens for the mnemonic, split by '.' characters.
3336   size_t Start = 0, Next = Name.find('.');
3337   StringRef Mnemonic = Name.slice(Start, Next);
3338
3339   // Split out the predication code and carry setting flag from the mnemonic.
3340   unsigned PredicationCode;
3341   unsigned ProcessorIMod;
3342   bool CarrySetting;
3343   StringRef ITMask;
3344   Mnemonic = splitMnemonic(Mnemonic, PredicationCode, CarrySetting,
3345                            ProcessorIMod, ITMask);
3346
3347   // In Thumb1, only the branch (B) instruction can be predicated.
3348   if (isThumbOne() && PredicationCode != ARMCC::AL && Mnemonic != "b") {
3349     Parser.EatToEndOfStatement();
3350     return Error(NameLoc, "conditional execution not supported in Thumb1");
3351   }
3352
3353   Operands.push_back(ARMOperand::CreateToken(Mnemonic, NameLoc));
3354
3355   // Handle the IT instruction ITMask. Convert it to a bitmask. This
3356   // is the mask as it will be for the IT encoding if the conditional
3357   // encoding has a '1' as it's bit0 (i.e. 't' ==> '1'). In the case
3358   // where the conditional bit0 is zero, the instruction post-processing
3359   // will adjust the mask accordingly.
3360   if (Mnemonic == "it") {
3361     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + 2);
3362     if (ITMask.size() > 3) {
3363       Parser.EatToEndOfStatement();
3364       return Error(Loc, "too many conditions on IT instruction");
3365     }
3366     unsigned Mask = 8;
3367     for (unsigned i = ITMask.size(); i != 0; --i) {
3368       char pos = ITMask[i - 1];
3369       if (pos != 't' && pos != 'e') {
3370         Parser.EatToEndOfStatement();
3371         return Error(Loc, "illegal IT block condition mask '" + ITMask + "'");
3372       }
3373       Mask >>= 1;
3374       if (ITMask[i - 1] == 't')
3375         Mask |= 8;
3376     }
3377     Operands.push_back(ARMOperand::CreateITMask(Mask, Loc));
3378   }
3379
3380   // FIXME: This is all a pretty gross hack. We should automatically handle
3381   // optional operands like this via tblgen.
3382
3383   // Next, add the CCOut and ConditionCode operands, if needed.
3384   //
3385   // For mnemonics which can ever incorporate a carry setting bit or predication
3386   // code, our matching model involves us always generating CCOut and
3387   // ConditionCode operands to match the mnemonic "as written" and then we let
3388   // the matcher deal with finding the right instruction or generating an
3389   // appropriate error.
3390   bool CanAcceptCarrySet, CanAcceptPredicationCode;
3391   getMnemonicAcceptInfo(Mnemonic, CanAcceptCarrySet, CanAcceptPredicationCode);
3392
3393   // If we had a carry-set on an instruction that can't do that, issue an
3394   // error.
3395   if (!CanAcceptCarrySet && CarrySetting) {
3396     Parser.EatToEndOfStatement();
3397     return Error(NameLoc, "instruction '" + Mnemonic +
3398                  "' can not set flags, but 's' suffix specified");
3399   }
3400   // If we had a predication code on an instruction that can't do that, issue an
3401   // error.
3402   if (!CanAcceptPredicationCode && PredicationCode != ARMCC::AL) {
3403     Parser.EatToEndOfStatement();
3404     return Error(NameLoc, "instruction '" + Mnemonic +
3405                  "' is not predicable, but condition code specified");
3406   }
3407
3408   // Add the carry setting operand, if necessary.
3409   if (CanAcceptCarrySet) {
3410     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size());
3411     Operands.push_back(ARMOperand::CreateCCOut(CarrySetting ? ARM::CPSR : 0,
3412                                                Loc));
3413   }
3414
3415   // Add the predication code operand, if necessary.
3416   if (CanAcceptPredicationCode) {
3417     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size() +
3418                                       CarrySetting);
3419     Operands.push_back(ARMOperand::CreateCondCode(
3420                          ARMCC::CondCodes(PredicationCode), Loc));
3421   }
3422
3423   // Add the processor imod operand, if necessary.
3424   if (ProcessorIMod) {
3425     Operands.push_back(ARMOperand::CreateImm(
3426           MCConstantExpr::Create(ProcessorIMod, getContext()),
3427                                  NameLoc, NameLoc));
3428   }
3429
3430   // Add the remaining tokens in the mnemonic.
3431   while (Next != StringRef::npos) {
3432     Start = Next;
3433     Next = Name.find('.', Start + 1);
3434     StringRef ExtraToken = Name.slice(Start, Next);
3435
3436     // For now, we're only parsing Thumb1 (for the most part), so
3437     // just ignore ".n" qualifiers. We'll use them to restrict
3438     // matching when we do Thumb2.
3439     if (ExtraToken != ".n") {
3440       SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Start);
3441       Operands.push_back(ARMOperand::CreateToken(ExtraToken, Loc));
3442     }
3443   }
3444
3445   // Read the remaining operands.
3446   if (getLexer().isNot(AsmToken::EndOfStatement)) {
3447     // Read the first operand.
3448     if (parseOperand(Operands, Mnemonic)) {
3449       Parser.EatToEndOfStatement();
3450       return true;
3451     }
3452
3453     while (getLexer().is(AsmToken::Comma)) {
3454       Parser.Lex();  // Eat the comma.
3455
3456       // Parse and remember the operand.
3457       if (parseOperand(Operands, Mnemonic)) {
3458         Parser.EatToEndOfStatement();
3459         return true;
3460       }
3461     }
3462   }
3463
3464   if (getLexer().isNot(AsmToken::EndOfStatement)) {
3465     Parser.EatToEndOfStatement();
3466     return TokError("unexpected token in argument list");
3467   }
3468
3469   Parser.Lex(); // Consume the EndOfStatement
3470
3471   // Some instructions, mostly Thumb, have forms for the same mnemonic that
3472   // do and don't have a cc_out optional-def operand. With some spot-checks
3473   // of the operand list, we can figure out which variant we're trying to
3474   // parse and adjust accordingly before actually matching. We shouldn't ever
3475   // try to remove a cc_out operand that was explicitly set on the the
3476   // mnemonic, of course (CarrySetting == true). Reason number #317 the
3477   // table driven matcher doesn't fit well with the ARM instruction set.
3478   if (!CarrySetting && shouldOmitCCOutOperand(Mnemonic, Operands)) {
3479     ARMOperand *Op = static_cast<ARMOperand*>(Operands[1]);
3480     Operands.erase(Operands.begin() + 1);
3481     delete Op;
3482   }
3483
3484   // ARM mode 'blx' need special handling, as the register operand version
3485   // is predicable, but the label operand version is not. So, we can't rely
3486   // on the Mnemonic based checking to correctly figure out when to put
3487   // a CondCode operand in the list. If we're trying to match the label
3488   // version, remove the CondCode operand here.
3489   if (!isThumb() && Mnemonic == "blx" && Operands.size() == 3 &&
3490       static_cast<ARMOperand*>(Operands[2])->isImm()) {
3491     ARMOperand *Op = static_cast<ARMOperand*>(Operands[1]);
3492     Operands.erase(Operands.begin() + 1);
3493     delete Op;
3494   }
3495
3496   // The vector-compare-to-zero instructions have a literal token "#0" at
3497   // the end that comes to here as an immediate operand. Convert it to a
3498   // token to play nicely with the matcher.
3499   if ((Mnemonic == "vceq" || Mnemonic == "vcge" || Mnemonic == "vcgt" ||
3500       Mnemonic == "vcle" || Mnemonic == "vclt") && Operands.size() == 6 &&
3501       static_cast<ARMOperand*>(Operands[5])->isImm()) {
3502     ARMOperand *Op = static_cast<ARMOperand*>(Operands[5]);
3503     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op->getImm());
3504     if (CE && CE->getValue() == 0) {
3505       Operands.erase(Operands.begin() + 5);
3506       Operands.push_back(ARMOperand::CreateToken("#0", Op->getStartLoc()));
3507       delete Op;
3508     }
3509   }
3510   // Similarly, the Thumb1 "RSB" instruction has a literal "#0" on the
3511   // end. Convert it to a token here.
3512   if (Mnemonic == "rsb" && isThumb() && Operands.size() == 6 &&
3513       static_cast<ARMOperand*>(Operands[5])->isImm()) {
3514     ARMOperand *Op = static_cast<ARMOperand*>(Operands[5]);
3515     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op->getImm());
3516     if (CE && CE->getValue() == 0) {
3517       Operands.erase(Operands.begin() + 5);
3518       Operands.push_back(ARMOperand::CreateToken("#0", Op->getStartLoc()));
3519       delete Op;
3520     }
3521   }
3522
3523   return false;
3524 }
3525
3526 // Validate context-sensitive operand constraints.
3527
3528 // return 'true' if register list contains non-low GPR registers,
3529 // 'false' otherwise. If Reg is in the register list or is HiReg, set
3530 // 'containsReg' to true.
3531 static bool checkLowRegisterList(MCInst Inst, unsigned OpNo, unsigned Reg,
3532                                  unsigned HiReg, bool &containsReg) {
3533   containsReg = false;
3534   for (unsigned i = OpNo; i < Inst.getNumOperands(); ++i) {
3535     unsigned OpReg = Inst.getOperand(i).getReg();
3536     if (OpReg == Reg)
3537       containsReg = true;
3538     // Anything other than a low register isn't legal here.
3539     if (!isARMLowRegister(OpReg) && (!HiReg || OpReg != HiReg))
3540       return true;
3541   }
3542   return false;
3543 }
3544
3545 // Check if the specified regisgter is in the register list of the inst,
3546 // starting at the indicated operand number.
3547 static bool listContainsReg(MCInst &Inst, unsigned OpNo, unsigned Reg) {
3548   for (unsigned i = OpNo; i < Inst.getNumOperands(); ++i) {
3549     unsigned OpReg = Inst.getOperand(i).getReg();
3550     if (OpReg == Reg)
3551       return true;
3552   }
3553   return false;
3554 }
3555
3556 // FIXME: We would really prefer to have MCInstrInfo (the wrapper around
3557 // the ARMInsts array) instead. Getting that here requires awkward
3558 // API changes, though. Better way?
3559 namespace llvm {
3560 extern MCInstrDesc ARMInsts[];
3561 }
3562 static MCInstrDesc &getInstDesc(unsigned Opcode) {
3563   return ARMInsts[Opcode];
3564 }
3565
3566 // FIXME: We would really like to be able to tablegen'erate this.
3567 bool ARMAsmParser::
3568 validateInstruction(MCInst &Inst,
3569                     const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
3570   MCInstrDesc &MCID = getInstDesc(Inst.getOpcode());
3571   SMLoc Loc = Operands[0]->getStartLoc();
3572   // Check the IT block state first.
3573   // NOTE: In Thumb mode, the BKPT instruction has the interesting property of
3574   // being allowed in IT blocks, but not being predicable.  It just always
3575   // executes.
3576   if (inITBlock() && Inst.getOpcode() != ARM::tBKPT) {
3577     unsigned bit = 1;
3578     if (ITState.FirstCond)
3579       ITState.FirstCond = false;
3580     else
3581       bit = (ITState.Mask >> (5 - ITState.CurPosition)) & 1;
3582     // The instruction must be predicable.
3583     if (!MCID.isPredicable())
3584       return Error(Loc, "instructions in IT block must be predicable");
3585     unsigned Cond = Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm();
3586     unsigned ITCond = bit ? ITState.Cond :
3587       ARMCC::getOppositeCondition(ITState.Cond);
3588     if (Cond != ITCond) {
3589       // Find the condition code Operand to get its SMLoc information.
3590       SMLoc CondLoc;
3591       for (unsigned i = 1; i < Operands.size(); ++i)
3592         if (static_cast<ARMOperand*>(Operands[i])->isCondCode())
3593           CondLoc = Operands[i]->getStartLoc();
3594       return Error(CondLoc, "incorrect condition in IT block; got '" +
3595                    StringRef(ARMCondCodeToString(ARMCC::CondCodes(Cond))) +
3596                    "', but expected '" +
3597                    ARMCondCodeToString(ARMCC::CondCodes(ITCond)) + "'");
3598     }
3599   // Check for non-'al' condition codes outside of the IT block.
3600   } else if (isThumbTwo() && MCID.isPredicable() &&
3601              Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm() !=
3602              ARMCC::AL && Inst.getOpcode() != ARM::tB &&
3603              Inst.getOpcode() != ARM::t2B)
3604     return Error(Loc, "predicated instructions must be in IT block");
3605
3606   switch (Inst.getOpcode()) {
3607   case ARM::LDRD:
3608   case ARM::LDRD_PRE:
3609   case ARM::LDRD_POST:
3610   case ARM::LDREXD: {
3611     // Rt2 must be Rt + 1.
3612     unsigned Rt = getARMRegisterNumbering(Inst.getOperand(0).getReg());
3613     unsigned Rt2 = getARMRegisterNumbering(Inst.getOperand(1).getReg());
3614     if (Rt2 != Rt + 1)
3615       return Error(Operands[3]->getStartLoc(),
3616                    "destination operands must be sequential");
3617     return false;
3618   }
3619   case ARM::STRD: {
3620     // Rt2 must be Rt + 1.
3621     unsigned Rt = getARMRegisterNumbering(Inst.getOperand(0).getReg());
3622     unsigned Rt2 = getARMRegisterNumbering(Inst.getOperand(1).getReg());
3623     if (Rt2 != Rt + 1)
3624       return Error(Operands[3]->getStartLoc(),
3625                    "source operands must be sequential");
3626     return false;
3627   }
3628   case ARM::STRD_PRE:
3629   case ARM::STRD_POST:
3630   case ARM::STREXD: {
3631     // Rt2 must be Rt + 1.
3632     unsigned Rt = getARMRegisterNumbering(Inst.getOperand(1).getReg());
3633     unsigned Rt2 = getARMRegisterNumbering(Inst.getOperand(2).getReg());
3634     if (Rt2 != Rt + 1)
3635       return Error(Operands[3]->getStartLoc(),
3636                    "source operands must be sequential");
3637     return false;
3638   }
3639   case ARM::SBFX:
3640   case ARM::UBFX: {
3641     // width must be in range [1, 32-lsb]
3642     unsigned lsb = Inst.getOperand(2).getImm();
3643     unsigned widthm1 = Inst.getOperand(3).getImm();
3644     if (widthm1 >= 32 - lsb)
3645       return Error(Operands[5]->getStartLoc(),
3646                    "bitfield width must be in range [1,32-lsb]");
3647     return false;
3648   }
3649   case ARM::tLDMIA: {
3650     // If we're parsing Thumb2, the .w variant is available and handles
3651     // most cases that are normally illegal for a Thumb1 LDM
3652     // instruction. We'll make the transformation in processInstruction()
3653     // if necessary.
3654     //
3655     // Thumb LDM instructions are writeback iff the base register is not
3656     // in the register list.
3657     unsigned Rn = Inst.getOperand(0).getReg();
3658     bool hasWritebackToken =
3659       (static_cast<ARMOperand*>(Operands[3])->isToken() &&
3660        static_cast<ARMOperand*>(Operands[3])->getToken() == "!");
3661     bool listContainsBase;
3662     if (checkLowRegisterList(Inst, 3, Rn, 0, listContainsBase) && !isThumbTwo())
3663       return Error(Operands[3 + hasWritebackToken]->getStartLoc(),
3664                    "registers must be in range r0-r7");
3665     // If we should have writeback, then there should be a '!' token.
3666     if (!listContainsBase && !hasWritebackToken && !isThumbTwo())
3667       return Error(Operands[2]->getStartLoc(),
3668                    "writeback operator '!' expected");
3669     // If we should not have writeback, there must not be a '!'. This is
3670     // true even for the 32-bit wide encodings.
3671     if (listContainsBase && hasWritebackToken)
3672       return Error(Operands[3]->getStartLoc(),
3673                    "writeback operator '!' not allowed when base register "
3674                    "in register list");
3675
3676     break;
3677   }
3678   case ARM::t2LDMIA_UPD: {
3679     if (listContainsReg(Inst, 3, Inst.getOperand(0).getReg()))
3680       return Error(Operands[4]->getStartLoc(),
3681                    "writeback operator '!' not allowed when base register "
3682                    "in register list");
3683     break;
3684   }
3685   case ARM::tPOP: {
3686     bool listContainsBase;
3687     if (checkLowRegisterList(Inst, 3, 0, ARM::PC, listContainsBase))
3688       return Error(Operands[2]->getStartLoc(),
3689                    "registers must be in range r0-r7 or pc");
3690     break;
3691   }
3692   case ARM::tPUSH: {
3693     bool listContainsBase;
3694     if (checkLowRegisterList(Inst, 3, 0, ARM::LR, listContainsBase))
3695       return Error(Operands[2]->getStartLoc(),
3696                    "registers must be in range r0-r7 or lr");
3697     break;
3698   }
3699   case ARM::tSTMIA_UPD: {
3700     bool listContainsBase;
3701     if (checkLowRegisterList(Inst, 4, 0, 0, listContainsBase) && !isThumbTwo())
3702       return Error(Operands[4]->getStartLoc(),
3703                    "registers must be in range r0-r7");
3704     break;
3705   }
3706   }
3707
3708   return false;
3709 }
3710
3711 void ARMAsmParser::
3712 processInstruction(MCInst &Inst,
3713                    const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
3714   switch (Inst.getOpcode()) {
3715   case ARM::LDMIA_UPD:
3716     // If this is a load of a single register via a 'pop', then we should use
3717     // a post-indexed LDR instruction instead, per the ARM ARM.
3718     if (static_cast<ARMOperand*>(Operands[0])->getToken() == "pop" &&
3719         Inst.getNumOperands() == 5) {
3720       MCInst TmpInst;
3721       TmpInst.setOpcode(ARM::LDR_POST_IMM);
3722       TmpInst.addOperand(Inst.getOperand(4)); // Rt
3723       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
3724       TmpInst.addOperand(Inst.getOperand(1)); // Rn
3725       TmpInst.addOperand(MCOperand::CreateReg(0));  // am2offset
3726       TmpInst.addOperand(MCOperand::CreateImm(4));
3727       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
3728       TmpInst.addOperand(Inst.getOperand(3));
3729       Inst = TmpInst;
3730     }
3731     break;
3732   case ARM::STMDB_UPD:
3733     // If this is a store of a single register via a 'push', then we should use
3734     // a pre-indexed STR instruction instead, per the ARM ARM.
3735     if (static_cast<ARMOperand*>(Operands[0])->getToken() == "push" &&
3736         Inst.getNumOperands() == 5) {
3737       MCInst TmpInst;
3738       TmpInst.setOpcode(ARM::STR_PRE_IMM);
3739       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
3740       TmpInst.addOperand(Inst.getOperand(4)); // Rt
3741       TmpInst.addOperand(Inst.getOperand(1)); // addrmode_imm12
3742       TmpInst.addOperand(MCOperand::CreateImm(-4));
3743       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
3744       TmpInst.addOperand(Inst.getOperand(3));
3745       Inst = TmpInst;
3746     }
3747     break;
3748   case ARM::tADDi8:
3749     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
3750     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
3751     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
3752     // to encoding T1 if <Rd> is omitted."
3753     if (Inst.getOperand(3).getImm() < 8 && Operands.size() == 6)
3754       Inst.setOpcode(ARM::tADDi3);
3755     break;
3756   case ARM::tSUBi8:
3757     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
3758     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
3759     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
3760     // to encoding T1 if <Rd> is omitted."
3761     if (Inst.getOperand(3).getImm() < 8 && Operands.size() == 6)
3762       Inst.setOpcode(ARM::tSUBi3);
3763     break;
3764   case ARM::tB:
3765     // A Thumb conditional branch outside of an IT block is a tBcc.
3766     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock())
3767       Inst.setOpcode(ARM::tBcc);
3768     break;
3769   case ARM::t2B:
3770     // A Thumb2 conditional branch outside of an IT block is a t2Bcc.
3771     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock())
3772       Inst.setOpcode(ARM::t2Bcc);
3773     break;
3774   case ARM::t2Bcc:
3775     // If the conditional is AL or we're in an IT block, we really want t2B.
3776     if (Inst.getOperand(1).getImm() == ARMCC::AL || inITBlock())
3777       Inst.setOpcode(ARM::t2B);
3778     break;
3779   case ARM::tBcc:
3780     // If the conditional is AL, we really want tB.
3781     if (Inst.getOperand(1).getImm() == ARMCC::AL)
3782       Inst.setOpcode(ARM::tB);
3783     break;
3784   case ARM::tLDMIA: {
3785     // If the register list contains any high registers, or if the writeback
3786     // doesn't match what tLDMIA can do, we need to use the 32-bit encoding
3787     // instead if we're in Thumb2. Otherwise, this should have generated
3788     // an error in validateInstruction().
3789     unsigned Rn = Inst.getOperand(0).getReg();
3790     bool hasWritebackToken =
3791       (static_cast<ARMOperand*>(Operands[3])->isToken() &&
3792        static_cast<ARMOperand*>(Operands[3])->getToken() == "!");
3793     bool listContainsBase;
3794     if (checkLowRegisterList(Inst, 3, Rn, 0, listContainsBase) ||
3795         (!listContainsBase && !hasWritebackToken) ||
3796         (listContainsBase && hasWritebackToken)) {
3797       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
3798       assert (isThumbTwo());
3799       Inst.setOpcode(hasWritebackToken ? ARM::t2LDMIA_UPD : ARM::t2LDMIA);
3800       // If we're switching to the updating version, we need to insert
3801       // the writeback tied operand.
3802       if (hasWritebackToken)
3803         Inst.insert(Inst.begin(),
3804                     MCOperand::CreateReg(Inst.getOperand(0).getReg()));
3805     }
3806     break;
3807   }
3808   case ARM::tSTMIA_UPD: {
3809     // If the register list contains any high registers, we need to use
3810     // the 32-bit encoding instead if we're in Thumb2. Otherwise, this
3811     // should have generated an error in validateInstruction().
3812     unsigned Rn = Inst.getOperand(0).getReg();
3813     bool listContainsBase;
3814     if (checkLowRegisterList(Inst, 4, Rn, 0, listContainsBase)) {
3815       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
3816       assert (isThumbTwo());
3817       Inst.setOpcode(ARM::t2STMIA_UPD);
3818     }
3819     break;
3820   }
3821   case ARM::t2MOVi: {
3822     // If we can use the 16-bit encoding and the user didn't explicitly
3823     // request the 32-bit variant, transform it here.
3824     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
3825         Inst.getOperand(1).getImm() <= 255 &&
3826         ((!inITBlock() && Inst.getOperand(2).getImm() == ARMCC::AL &&
3827          Inst.getOperand(4).getReg() == ARM::CPSR) ||
3828         (inITBlock() && Inst.getOperand(4).getReg() == 0)) &&
3829         (!static_cast<ARMOperand*>(Operands[2])->isToken() ||
3830          static_cast<ARMOperand*>(Operands[2])->getToken() != ".w")) {
3831       // The operands aren't in the same order for tMOVi8...
3832       MCInst TmpInst;
3833       TmpInst.setOpcode(ARM::tMOVi8);
3834       TmpInst.addOperand(Inst.getOperand(0));
3835       TmpInst.addOperand(Inst.getOperand(4));
3836       TmpInst.addOperand(Inst.getOperand(1));
3837       TmpInst.addOperand(Inst.getOperand(2));
3838       TmpInst.addOperand(Inst.getOperand(3));
3839       Inst = TmpInst;
3840     }
3841     break;
3842   }
3843   case ARM::t2MOVr: {
3844     // If we can use the 16-bit encoding and the user didn't explicitly
3845     // request the 32-bit variant, transform it here.
3846     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
3847         isARMLowRegister(Inst.getOperand(1).getReg()) &&
3848         Inst.getOperand(2).getImm() == ARMCC::AL &&
3849         Inst.getOperand(4).getReg() == ARM::CPSR &&
3850         (!static_cast<ARMOperand*>(Operands[2])->isToken() ||
3851          static_cast<ARMOperand*>(Operands[2])->getToken() != ".w")) {
3852       // The operands aren't the same for tMOV[S]r... (no cc_out)
3853       MCInst TmpInst;
3854       TmpInst.setOpcode(Inst.getOperand(4).getReg() ? ARM::tMOVSr : ARM::tMOVr);
3855       TmpInst.addOperand(Inst.getOperand(0));
3856       TmpInst.addOperand(Inst.getOperand(1));
3857       TmpInst.addOperand(Inst.getOperand(2));
3858       TmpInst.addOperand(Inst.getOperand(3));
3859       Inst = TmpInst;
3860     }
3861     break;
3862   }
3863   case ARM::t2IT: {
3864     // The mask bits for all but the first condition are represented as
3865     // the low bit of the condition code value implies 't'. We currently
3866     // always have 1 implies 't', so XOR toggle the bits if the low bit
3867     // of the condition code is zero. The encoding also expects the low
3868     // bit of the condition to be encoded as bit 4 of the mask operand,
3869     // so mask that in if needed
3870     MCOperand &MO = Inst.getOperand(1);
3871     unsigned Mask = MO.getImm();
3872     unsigned OrigMask = Mask;
3873     unsigned TZ = CountTrailingZeros_32(Mask);
3874     if ((Inst.getOperand(0).getImm() & 1) == 0) {
3875       assert(Mask && TZ <= 3 && "illegal IT mask value!");
3876       for (unsigned i = 3; i != TZ; --i)
3877         Mask ^= 1 << i;
3878     } else
3879       Mask |= 0x10;
3880     MO.setImm(Mask);
3881
3882     // Set up the IT block state according to the IT instruction we just
3883     // matched.
3884     assert(!inITBlock() && "nested IT blocks?!");
3885     ITState.Cond = ARMCC::CondCodes(Inst.getOperand(0).getImm());
3886     ITState.Mask = OrigMask; // Use the original mask, not the updated one.
3887     ITState.CurPosition = 0;
3888     ITState.FirstCond = true;
3889     break;
3890   }
3891   }
3892 }
3893
3894 unsigned ARMAsmParser::checkTargetMatchPredicate(MCInst &Inst) {
3895   // 16-bit thumb arithmetic instructions either require or preclude the 'S'
3896   // suffix depending on whether they're in an IT block or not.
3897   unsigned Opc = Inst.getOpcode();
3898   MCInstrDesc &MCID = getInstDesc(Opc);
3899   if (MCID.TSFlags & ARMII::ThumbArithFlagSetting) {
3900     assert(MCID.hasOptionalDef() &&
3901            "optionally flag setting instruction missing optional def operand");
3902     assert(MCID.NumOperands == Inst.getNumOperands() &&
3903            "operand count mismatch!");
3904     // Find the optional-def operand (cc_out).
3905     unsigned OpNo;
3906     for (OpNo = 0;
3907          !MCID.OpInfo[OpNo].isOptionalDef() && OpNo < MCID.NumOperands;
3908          ++OpNo)
3909       ;
3910     // If we're parsing Thumb1, reject it completely.
3911     if (isThumbOne() && Inst.getOperand(OpNo).getReg() != ARM::CPSR)
3912       return Match_MnemonicFail;
3913     // If we're parsing Thumb2, which form is legal depends on whether we're
3914     // in an IT block.
3915     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() != ARM::CPSR &&
3916         !inITBlock())
3917       return Match_RequiresITBlock;
3918     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() == ARM::CPSR &&
3919         inITBlock())
3920       return Match_RequiresNotITBlock;
3921   }
3922   // Some high-register supporting Thumb1 encodings only allow both registers
3923   // to be from r0-r7 when in Thumb2.
3924   else if (Opc == ARM::tADDhirr && isThumbOne() &&
3925            isARMLowRegister(Inst.getOperand(1).getReg()) &&
3926            isARMLowRegister(Inst.getOperand(2).getReg()))
3927     return Match_RequiresThumb2;
3928   // Others only require ARMv6 or later.
3929   else if (Opc == ARM::tMOVr && isThumbOne() && !hasV6Ops() &&
3930            isARMLowRegister(Inst.getOperand(0).getReg()) &&
3931            isARMLowRegister(Inst.getOperand(1).getReg()))
3932     return Match_RequiresV6;
3933   return Match_Success;
3934 }
3935
3936 bool ARMAsmParser::
3937 MatchAndEmitInstruction(SMLoc IDLoc,
3938                         SmallVectorImpl<MCParsedAsmOperand*> &Operands,
3939                         MCStreamer &Out) {
3940   MCInst Inst;
3941   unsigned ErrorInfo;
3942   unsigned MatchResult;
3943   MatchResult = MatchInstructionImpl(Operands, Inst, ErrorInfo);
3944   switch (MatchResult) {
3945   default: break;
3946   case Match_Success:
3947     // Context sensitive operand constraints aren't handled by the matcher,
3948     // so check them here.
3949     if (validateInstruction(Inst, Operands)) {
3950       // Still progress the IT block, otherwise one wrong condition causes
3951       // nasty cascading errors.
3952       forwardITPosition();
3953       return true;
3954     }
3955
3956     // Some instructions need post-processing to, for example, tweak which
3957     // encoding is selected.
3958     processInstruction(Inst, Operands);
3959
3960     // Only move forward at the very end so that everything in validate
3961     // and process gets a consistent answer about whether we're in an IT
3962     // block.
3963     forwardITPosition();
3964
3965     Out.EmitInstruction(Inst);
3966     return false;
3967   case Match_MissingFeature:
3968     Error(IDLoc, "instruction requires a CPU feature not currently enabled");
3969     return true;
3970   case Match_InvalidOperand: {
3971     SMLoc ErrorLoc = IDLoc;
3972     if (ErrorInfo != ~0U) {
3973       if (ErrorInfo >= Operands.size())
3974         return Error(IDLoc, "too few operands for instruction");
3975
3976       ErrorLoc = ((ARMOperand*)Operands[ErrorInfo])->getStartLoc();
3977       if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
3978     }
3979
3980     return Error(ErrorLoc, "invalid operand for instruction");
3981   }
3982   case Match_MnemonicFail:
3983     return Error(IDLoc, "invalid instruction");
3984   case Match_ConversionFail:
3985     // The converter function will have already emited a diagnostic.
3986     return true;
3987   case Match_RequiresNotITBlock:
3988     return Error(IDLoc, "flag setting instruction only valid outside IT block");
3989   case Match_RequiresITBlock:
3990     return Error(IDLoc, "instruction only valid inside IT block");
3991   case Match_RequiresV6:
3992     return Error(IDLoc, "instruction variant requires ARMv6 or later");
3993   case Match_RequiresThumb2:
3994     return Error(IDLoc, "instruction variant requires Thumb2");
3995   }
3996
3997   llvm_unreachable("Implement any new match types added!");
3998   return true;
3999 }
4000
4001 /// parseDirective parses the arm specific directives
4002 bool ARMAsmParser::ParseDirective(AsmToken DirectiveID) {
4003   StringRef IDVal = DirectiveID.getIdentifier();
4004   if (IDVal == ".word")
4005     return parseDirectiveWord(4, DirectiveID.getLoc());
4006   else if (IDVal == ".thumb")
4007     return parseDirectiveThumb(DirectiveID.getLoc());
4008   else if (IDVal == ".thumb_func")
4009     return parseDirectiveThumbFunc(DirectiveID.getLoc());
4010   else if (IDVal == ".code")
4011     return parseDirectiveCode(DirectiveID.getLoc());
4012   else if (IDVal == ".syntax")
4013     return parseDirectiveSyntax(DirectiveID.getLoc());
4014   return true;
4015 }
4016
4017 /// parseDirectiveWord
4018 ///  ::= .word [ expression (, expression)* ]
4019 bool ARMAsmParser::parseDirectiveWord(unsigned Size, SMLoc L) {
4020   if (getLexer().isNot(AsmToken::EndOfStatement)) {
4021     for (;;) {
4022       const MCExpr *Value;
4023       if (getParser().ParseExpression(Value))
4024         return true;
4025
4026       getParser().getStreamer().EmitValue(Value, Size, 0/*addrspace*/);
4027
4028       if (getLexer().is(AsmToken::EndOfStatement))
4029         break;
4030
4031       // FIXME: Improve diagnostic.
4032       if (getLexer().isNot(AsmToken::Comma))
4033         return Error(L, "unexpected token in directive");
4034       Parser.Lex();
4035     }
4036   }
4037
4038   Parser.Lex();
4039   return false;
4040 }
4041
4042 /// parseDirectiveThumb
4043 ///  ::= .thumb
4044 bool ARMAsmParser::parseDirectiveThumb(SMLoc L) {
4045   if (getLexer().isNot(AsmToken::EndOfStatement))
4046     return Error(L, "unexpected token in directive");
4047   Parser.Lex();
4048
4049   // TODO: set thumb mode
4050   // TODO: tell the MC streamer the mode
4051   // getParser().getStreamer().Emit???();
4052   return false;
4053 }
4054
4055 /// parseDirectiveThumbFunc
4056 ///  ::= .thumbfunc symbol_name
4057 bool ARMAsmParser::parseDirectiveThumbFunc(SMLoc L) {
4058   const MCAsmInfo &MAI = getParser().getStreamer().getContext().getAsmInfo();
4059   bool isMachO = MAI.hasSubsectionsViaSymbols();
4060   StringRef Name;
4061
4062   // Darwin asm has function name after .thumb_func direction
4063   // ELF doesn't
4064   if (isMachO) {
4065     const AsmToken &Tok = Parser.getTok();
4066     if (Tok.isNot(AsmToken::Identifier) && Tok.isNot(AsmToken::String))
4067       return Error(L, "unexpected token in .thumb_func directive");
4068     Name = Tok.getString();
4069     Parser.Lex(); // Consume the identifier token.
4070   }
4071
4072   if (getLexer().isNot(AsmToken::EndOfStatement))
4073     return Error(L, "unexpected token in directive");
4074   Parser.Lex();
4075
4076   // FIXME: assuming function name will be the line following .thumb_func
4077   if (!isMachO) {
4078     Name = Parser.getTok().getString();
4079   }
4080
4081   // Mark symbol as a thumb symbol.
4082   MCSymbol *Func = getParser().getContext().GetOrCreateSymbol(Name);
4083   getParser().getStreamer().EmitThumbFunc(Func);
4084   return false;
4085 }
4086
4087 /// parseDirectiveSyntax
4088 ///  ::= .syntax unified | divided
4089 bool ARMAsmParser::parseDirectiveSyntax(SMLoc L) {
4090   const AsmToken &Tok = Parser.getTok();
4091   if (Tok.isNot(AsmToken::Identifier))
4092     return Error(L, "unexpected token in .syntax directive");
4093   StringRef Mode = Tok.getString();
4094   if (Mode == "unified" || Mode == "UNIFIED")
4095     Parser.Lex();
4096   else if (Mode == "divided" || Mode == "DIVIDED")
4097     return Error(L, "'.syntax divided' arm asssembly not supported");
4098   else
4099     return Error(L, "unrecognized syntax mode in .syntax directive");
4100
4101   if (getLexer().isNot(AsmToken::EndOfStatement))
4102     return Error(Parser.getTok().getLoc(), "unexpected token in directive");
4103   Parser.Lex();
4104
4105   // TODO tell the MC streamer the mode
4106   // getParser().getStreamer().Emit???();
4107   return false;
4108 }
4109
4110 /// parseDirectiveCode
4111 ///  ::= .code 16 | 32
4112 bool ARMAsmParser::parseDirectiveCode(SMLoc L) {
4113   const AsmToken &Tok = Parser.getTok();
4114   if (Tok.isNot(AsmToken::Integer))
4115     return Error(L, "unexpected token in .code directive");
4116   int64_t Val = Parser.getTok().getIntVal();
4117   if (Val == 16)
4118     Parser.Lex();
4119   else if (Val == 32)
4120     Parser.Lex();
4121   else
4122     return Error(L, "invalid operand to .code directive");
4123
4124   if (getLexer().isNot(AsmToken::EndOfStatement))
4125     return Error(Parser.getTok().getLoc(), "unexpected token in directive");
4126   Parser.Lex();
4127
4128   if (Val == 16) {
4129     if (!isThumb())
4130       SwitchMode();
4131     getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
4132   } else {
4133     if (isThumb())
4134       SwitchMode();
4135     getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
4136   }
4137
4138   return false;
4139 }
4140
4141 extern "C" void LLVMInitializeARMAsmLexer();
4142
4143 /// Force static initialization.
4144 extern "C" void LLVMInitializeARMAsmParser() {
4145   RegisterMCAsmParser<ARMAsmParser> X(TheARMTarget);
4146   RegisterMCAsmParser<ARMAsmParser> Y(TheThumbTarget);
4147   LLVMInitializeARMAsmLexer();
4148 }
4149
4150 #define GET_REGISTER_MATCHER
4151 #define GET_MATCHER_IMPLEMENTATION
4152 #include "ARMGenAsmMatcher.inc"