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