Thumb2 assembly parsing and encoding for UMAAL/UMLAL/UMULL.
[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 > -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.
2259     if (Val == 32) Val = 0;
2260   } else {
2261     // Shift amount must be in [1,32]
2262     if (Val < 0 || Val > 31) {
2263       Error(E, "'lsr' shift amount must be in range [0,31]");
2264       return MatchOperand_ParseFail;
2265     }
2266   }
2267
2268   E = Parser.getTok().getLoc();
2269   Operands.push_back(ARMOperand::CreateShifterImm(isASR, Val, S, E));
2270
2271   return MatchOperand_Success;
2272 }
2273
2274 /// parseRotImm - Parse the shifter immediate operand for SXTB/UXTB family
2275 /// of instructions. Legal values are:
2276 ///     ror #n  'n' in {0, 8, 16, 24}
2277 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
2278 parseRotImm(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2279   const AsmToken &Tok = Parser.getTok();
2280   SMLoc S = Tok.getLoc();
2281   if (Tok.isNot(AsmToken::Identifier))
2282     return MatchOperand_NoMatch;
2283   StringRef ShiftName = Tok.getString();
2284   if (ShiftName != "ror" && ShiftName != "ROR")
2285     return MatchOperand_NoMatch;
2286   Parser.Lex(); // Eat the operator.
2287
2288   // A '#' and a rotate amount.
2289   if (Parser.getTok().isNot(AsmToken::Hash)) {
2290     Error(Parser.getTok().getLoc(), "'#' expected");
2291     return MatchOperand_ParseFail;
2292   }
2293   Parser.Lex(); // Eat hash token.
2294
2295   const MCExpr *ShiftAmount;
2296   SMLoc E = Parser.getTok().getLoc();
2297   if (getParser().ParseExpression(ShiftAmount)) {
2298     Error(E, "malformed rotate expression");
2299     return MatchOperand_ParseFail;
2300   }
2301   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
2302   if (!CE) {
2303     Error(E, "rotate amount must be an immediate");
2304     return MatchOperand_ParseFail;
2305   }
2306
2307   int64_t Val = CE->getValue();
2308   // Shift amount must be in {0, 8, 16, 24} (0 is undocumented extension)
2309   // normally, zero is represented in asm by omitting the rotate operand
2310   // entirely.
2311   if (Val != 8 && Val != 16 && Val != 24 && Val != 0) {
2312     Error(E, "'ror' rotate amount must be 8, 16, or 24");
2313     return MatchOperand_ParseFail;
2314   }
2315
2316   E = Parser.getTok().getLoc();
2317   Operands.push_back(ARMOperand::CreateRotImm(Val, S, E));
2318
2319   return MatchOperand_Success;
2320 }
2321
2322 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
2323 parseBitfield(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2324   SMLoc S = Parser.getTok().getLoc();
2325   // The bitfield descriptor is really two operands, the LSB and the width.
2326   if (Parser.getTok().isNot(AsmToken::Hash)) {
2327     Error(Parser.getTok().getLoc(), "'#' expected");
2328     return MatchOperand_ParseFail;
2329   }
2330   Parser.Lex(); // Eat hash token.
2331
2332   const MCExpr *LSBExpr;
2333   SMLoc E = Parser.getTok().getLoc();
2334   if (getParser().ParseExpression(LSBExpr)) {
2335     Error(E, "malformed immediate expression");
2336     return MatchOperand_ParseFail;
2337   }
2338   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(LSBExpr);
2339   if (!CE) {
2340     Error(E, "'lsb' operand must be an immediate");
2341     return MatchOperand_ParseFail;
2342   }
2343
2344   int64_t LSB = CE->getValue();
2345   // The LSB must be in the range [0,31]
2346   if (LSB < 0 || LSB > 31) {
2347     Error(E, "'lsb' operand must be in the range [0,31]");
2348     return MatchOperand_ParseFail;
2349   }
2350   E = Parser.getTok().getLoc();
2351
2352   // Expect another immediate operand.
2353   if (Parser.getTok().isNot(AsmToken::Comma)) {
2354     Error(Parser.getTok().getLoc(), "too few operands");
2355     return MatchOperand_ParseFail;
2356   }
2357   Parser.Lex(); // Eat hash token.
2358   if (Parser.getTok().isNot(AsmToken::Hash)) {
2359     Error(Parser.getTok().getLoc(), "'#' expected");
2360     return MatchOperand_ParseFail;
2361   }
2362   Parser.Lex(); // Eat hash token.
2363
2364   const MCExpr *WidthExpr;
2365   if (getParser().ParseExpression(WidthExpr)) {
2366     Error(E, "malformed immediate expression");
2367     return MatchOperand_ParseFail;
2368   }
2369   CE = dyn_cast<MCConstantExpr>(WidthExpr);
2370   if (!CE) {
2371     Error(E, "'width' operand must be an immediate");
2372     return MatchOperand_ParseFail;
2373   }
2374
2375   int64_t Width = CE->getValue();
2376   // The LSB must be in the range [1,32-lsb]
2377   if (Width < 1 || Width > 32 - LSB) {
2378     Error(E, "'width' operand must be in the range [1,32-lsb]");
2379     return MatchOperand_ParseFail;
2380   }
2381   E = Parser.getTok().getLoc();
2382
2383   Operands.push_back(ARMOperand::CreateBitfield(LSB, Width, S, E));
2384
2385   return MatchOperand_Success;
2386 }
2387
2388 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
2389 parsePostIdxReg(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2390   // Check for a post-index addressing register operand. Specifically:
2391   // postidx_reg := '+' register {, shift}
2392   //              | '-' register {, shift}
2393   //              | register {, shift}
2394
2395   // This method must return MatchOperand_NoMatch without consuming any tokens
2396   // in the case where there is no match, as other alternatives take other
2397   // parse methods.
2398   AsmToken Tok = Parser.getTok();
2399   SMLoc S = Tok.getLoc();
2400   bool haveEaten = false;
2401   bool isAdd = true;
2402   int Reg = -1;
2403   if (Tok.is(AsmToken::Plus)) {
2404     Parser.Lex(); // Eat the '+' token.
2405     haveEaten = true;
2406   } else if (Tok.is(AsmToken::Minus)) {
2407     Parser.Lex(); // Eat the '-' token.
2408     isAdd = false;
2409     haveEaten = true;
2410   }
2411   if (Parser.getTok().is(AsmToken::Identifier))
2412     Reg = tryParseRegister();
2413   if (Reg == -1) {
2414     if (!haveEaten)
2415       return MatchOperand_NoMatch;
2416     Error(Parser.getTok().getLoc(), "register expected");
2417     return MatchOperand_ParseFail;
2418   }
2419   SMLoc E = Parser.getTok().getLoc();
2420
2421   ARM_AM::ShiftOpc ShiftTy = ARM_AM::no_shift;
2422   unsigned ShiftImm = 0;
2423   if (Parser.getTok().is(AsmToken::Comma)) {
2424     Parser.Lex(); // Eat the ','.
2425     if (parseMemRegOffsetShift(ShiftTy, ShiftImm))
2426       return MatchOperand_ParseFail;
2427   }
2428
2429   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ShiftTy,
2430                                                   ShiftImm, S, E));
2431
2432   return MatchOperand_Success;
2433 }
2434
2435 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
2436 parseAM3Offset(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2437   // Check for a post-index addressing register operand. Specifically:
2438   // am3offset := '+' register
2439   //              | '-' register
2440   //              | register
2441   //              | # imm
2442   //              | # + imm
2443   //              | # - imm
2444
2445   // This method must return MatchOperand_NoMatch without consuming any tokens
2446   // in the case where there is no match, as other alternatives take other
2447   // parse methods.
2448   AsmToken Tok = Parser.getTok();
2449   SMLoc S = Tok.getLoc();
2450
2451   // Do immediates first, as we always parse those if we have a '#'.
2452   if (Parser.getTok().is(AsmToken::Hash)) {
2453     Parser.Lex(); // Eat the '#'.
2454     // Explicitly look for a '-', as we need to encode negative zero
2455     // differently.
2456     bool isNegative = Parser.getTok().is(AsmToken::Minus);
2457     const MCExpr *Offset;
2458     if (getParser().ParseExpression(Offset))
2459       return MatchOperand_ParseFail;
2460     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
2461     if (!CE) {
2462       Error(S, "constant expression expected");
2463       return MatchOperand_ParseFail;
2464     }
2465     SMLoc E = Tok.getLoc();
2466     // Negative zero is encoded as the flag value INT32_MIN.
2467     int32_t Val = CE->getValue();
2468     if (isNegative && Val == 0)
2469       Val = INT32_MIN;
2470
2471     Operands.push_back(
2472       ARMOperand::CreateImm(MCConstantExpr::Create(Val, getContext()), S, E));
2473
2474     return MatchOperand_Success;
2475   }
2476
2477
2478   bool haveEaten = false;
2479   bool isAdd = true;
2480   int Reg = -1;
2481   if (Tok.is(AsmToken::Plus)) {
2482     Parser.Lex(); // Eat the '+' token.
2483     haveEaten = true;
2484   } else if (Tok.is(AsmToken::Minus)) {
2485     Parser.Lex(); // Eat the '-' token.
2486     isAdd = false;
2487     haveEaten = true;
2488   }
2489   if (Parser.getTok().is(AsmToken::Identifier))
2490     Reg = tryParseRegister();
2491   if (Reg == -1) {
2492     if (!haveEaten)
2493       return MatchOperand_NoMatch;
2494     Error(Parser.getTok().getLoc(), "register expected");
2495     return MatchOperand_ParseFail;
2496   }
2497   SMLoc E = Parser.getTok().getLoc();
2498
2499   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ARM_AM::no_shift,
2500                                                   0, S, E));
2501
2502   return MatchOperand_Success;
2503 }
2504
2505 /// cvtT2LdrdPre - Convert parsed operands to MCInst.
2506 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2507 /// when they refer multiple MIOperands inside a single one.
2508 bool ARMAsmParser::
2509 cvtT2LdrdPre(MCInst &Inst, unsigned Opcode,
2510              const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2511   // Rt, Rt2
2512   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2513   ((ARMOperand*)Operands[3])->addRegOperands(Inst, 1);
2514   // Create a writeback register dummy placeholder.
2515   Inst.addOperand(MCOperand::CreateReg(0));
2516   // addr
2517   ((ARMOperand*)Operands[4])->addMemImm8s4OffsetOperands(Inst, 2);
2518   // pred
2519   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2520   return true;
2521 }
2522
2523 /// cvtT2StrdPre - Convert parsed operands to MCInst.
2524 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2525 /// when they refer multiple MIOperands inside a single one.
2526 bool ARMAsmParser::
2527 cvtT2StrdPre(MCInst &Inst, unsigned Opcode,
2528              const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2529   // Create a writeback register dummy placeholder.
2530   Inst.addOperand(MCOperand::CreateReg(0));
2531   // Rt, Rt2
2532   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2533   ((ARMOperand*)Operands[3])->addRegOperands(Inst, 1);
2534   // addr
2535   ((ARMOperand*)Operands[4])->addMemImm8s4OffsetOperands(Inst, 2);
2536   // pred
2537   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2538   return true;
2539 }
2540
2541 /// cvtLdWriteBackRegT2AddrModeImm8 - Convert parsed operands to MCInst.
2542 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2543 /// when they refer multiple MIOperands inside a single one.
2544 bool ARMAsmParser::
2545 cvtLdWriteBackRegT2AddrModeImm8(MCInst &Inst, unsigned Opcode,
2546                          const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2547   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2548
2549   // Create a writeback register dummy placeholder.
2550   Inst.addOperand(MCOperand::CreateImm(0));
2551
2552   ((ARMOperand*)Operands[3])->addMemImm8OffsetOperands(Inst, 2);
2553   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2554   return true;
2555 }
2556
2557 /// cvtStWriteBackRegT2AddrModeImm8 - Convert parsed operands to MCInst.
2558 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2559 /// when they refer multiple MIOperands inside a single one.
2560 bool ARMAsmParser::
2561 cvtStWriteBackRegT2AddrModeImm8(MCInst &Inst, unsigned Opcode,
2562                          const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2563   // Create a writeback register dummy placeholder.
2564   Inst.addOperand(MCOperand::CreateImm(0));
2565   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2566   ((ARMOperand*)Operands[3])->addMemImm8OffsetOperands(Inst, 2);
2567   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2568   return true;
2569 }
2570
2571 /// cvtLdWriteBackRegAddrMode2 - Convert parsed operands to MCInst.
2572 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2573 /// when they refer multiple MIOperands inside a single one.
2574 bool ARMAsmParser::
2575 cvtLdWriteBackRegAddrMode2(MCInst &Inst, unsigned Opcode,
2576                          const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2577   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2578
2579   // Create a writeback register dummy placeholder.
2580   Inst.addOperand(MCOperand::CreateImm(0));
2581
2582   ((ARMOperand*)Operands[3])->addAddrMode2Operands(Inst, 3);
2583   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2584   return true;
2585 }
2586
2587 /// cvtLdWriteBackRegAddrModeImm12 - Convert parsed operands to MCInst.
2588 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2589 /// when they refer multiple MIOperands inside a single one.
2590 bool ARMAsmParser::
2591 cvtLdWriteBackRegAddrModeImm12(MCInst &Inst, unsigned Opcode,
2592                          const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2593   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2594
2595   // Create a writeback register dummy placeholder.
2596   Inst.addOperand(MCOperand::CreateImm(0));
2597
2598   ((ARMOperand*)Operands[3])->addMemImm12OffsetOperands(Inst, 2);
2599   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2600   return true;
2601 }
2602
2603
2604 /// cvtStWriteBackRegAddrModeImm12 - Convert parsed operands to MCInst.
2605 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2606 /// when they refer multiple MIOperands inside a single one.
2607 bool ARMAsmParser::
2608 cvtStWriteBackRegAddrModeImm12(MCInst &Inst, unsigned Opcode,
2609                          const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2610   // Create a writeback register dummy placeholder.
2611   Inst.addOperand(MCOperand::CreateImm(0));
2612   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2613   ((ARMOperand*)Operands[3])->addMemImm12OffsetOperands(Inst, 2);
2614   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2615   return true;
2616 }
2617
2618 /// cvtStWriteBackRegAddrMode2 - Convert parsed operands to MCInst.
2619 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2620 /// when they refer multiple MIOperands inside a single one.
2621 bool ARMAsmParser::
2622 cvtStWriteBackRegAddrMode2(MCInst &Inst, unsigned Opcode,
2623                          const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2624   // Create a writeback register dummy placeholder.
2625   Inst.addOperand(MCOperand::CreateImm(0));
2626   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2627   ((ARMOperand*)Operands[3])->addAddrMode2Operands(Inst, 3);
2628   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2629   return true;
2630 }
2631
2632 /// cvtStWriteBackRegAddrMode3 - Convert parsed operands to MCInst.
2633 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2634 /// when they refer multiple MIOperands inside a single one.
2635 bool ARMAsmParser::
2636 cvtStWriteBackRegAddrMode3(MCInst &Inst, unsigned Opcode,
2637                          const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2638   // Create a writeback register dummy placeholder.
2639   Inst.addOperand(MCOperand::CreateImm(0));
2640   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2641   ((ARMOperand*)Operands[3])->addAddrMode3Operands(Inst, 3);
2642   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2643   return true;
2644 }
2645
2646 /// cvtLdExtTWriteBackImm - Convert parsed operands to MCInst.
2647 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2648 /// when they refer multiple MIOperands inside a single one.
2649 bool ARMAsmParser::
2650 cvtLdExtTWriteBackImm(MCInst &Inst, unsigned Opcode,
2651                       const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2652   // Rt
2653   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2654   // Create a writeback register dummy placeholder.
2655   Inst.addOperand(MCOperand::CreateImm(0));
2656   // addr
2657   ((ARMOperand*)Operands[3])->addMemNoOffsetOperands(Inst, 1);
2658   // offset
2659   ((ARMOperand*)Operands[4])->addPostIdxImm8Operands(Inst, 1);
2660   // pred
2661   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2662   return true;
2663 }
2664
2665 /// cvtLdExtTWriteBackReg - Convert parsed operands to MCInst.
2666 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2667 /// when they refer multiple MIOperands inside a single one.
2668 bool ARMAsmParser::
2669 cvtLdExtTWriteBackReg(MCInst &Inst, unsigned Opcode,
2670                       const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2671   // Rt
2672   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2673   // Create a writeback register dummy placeholder.
2674   Inst.addOperand(MCOperand::CreateImm(0));
2675   // addr
2676   ((ARMOperand*)Operands[3])->addMemNoOffsetOperands(Inst, 1);
2677   // offset
2678   ((ARMOperand*)Operands[4])->addPostIdxRegOperands(Inst, 2);
2679   // pred
2680   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2681   return true;
2682 }
2683
2684 /// cvtStExtTWriteBackImm - Convert parsed operands to MCInst.
2685 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2686 /// when they refer multiple MIOperands inside a single one.
2687 bool ARMAsmParser::
2688 cvtStExtTWriteBackImm(MCInst &Inst, unsigned Opcode,
2689                       const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2690   // Create a writeback register dummy placeholder.
2691   Inst.addOperand(MCOperand::CreateImm(0));
2692   // Rt
2693   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2694   // addr
2695   ((ARMOperand*)Operands[3])->addMemNoOffsetOperands(Inst, 1);
2696   // offset
2697   ((ARMOperand*)Operands[4])->addPostIdxImm8Operands(Inst, 1);
2698   // pred
2699   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2700   return true;
2701 }
2702
2703 /// cvtStExtTWriteBackReg - Convert parsed operands to MCInst.
2704 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2705 /// when they refer multiple MIOperands inside a single one.
2706 bool ARMAsmParser::
2707 cvtStExtTWriteBackReg(MCInst &Inst, unsigned Opcode,
2708                       const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2709   // Create a writeback register dummy placeholder.
2710   Inst.addOperand(MCOperand::CreateImm(0));
2711   // Rt
2712   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2713   // addr
2714   ((ARMOperand*)Operands[3])->addMemNoOffsetOperands(Inst, 1);
2715   // offset
2716   ((ARMOperand*)Operands[4])->addPostIdxRegOperands(Inst, 2);
2717   // pred
2718   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2719   return true;
2720 }
2721
2722 /// cvtLdrdPre - Convert parsed operands to MCInst.
2723 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2724 /// when they refer multiple MIOperands inside a single one.
2725 bool ARMAsmParser::
2726 cvtLdrdPre(MCInst &Inst, unsigned Opcode,
2727            const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2728   // Rt, Rt2
2729   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2730   ((ARMOperand*)Operands[3])->addRegOperands(Inst, 1);
2731   // Create a writeback register dummy placeholder.
2732   Inst.addOperand(MCOperand::CreateImm(0));
2733   // addr
2734   ((ARMOperand*)Operands[4])->addAddrMode3Operands(Inst, 3);
2735   // pred
2736   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2737   return true;
2738 }
2739
2740 /// cvtStrdPre - Convert parsed operands to MCInst.
2741 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2742 /// when they refer multiple MIOperands inside a single one.
2743 bool ARMAsmParser::
2744 cvtStrdPre(MCInst &Inst, unsigned Opcode,
2745            const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2746   // Create a writeback register dummy placeholder.
2747   Inst.addOperand(MCOperand::CreateImm(0));
2748   // Rt, Rt2
2749   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2750   ((ARMOperand*)Operands[3])->addRegOperands(Inst, 1);
2751   // addr
2752   ((ARMOperand*)Operands[4])->addAddrMode3Operands(Inst, 3);
2753   // pred
2754   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2755   return true;
2756 }
2757
2758 /// cvtLdWriteBackRegAddrMode3 - Convert parsed operands to MCInst.
2759 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2760 /// when they refer multiple MIOperands inside a single one.
2761 bool ARMAsmParser::
2762 cvtLdWriteBackRegAddrMode3(MCInst &Inst, unsigned Opcode,
2763                          const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2764   ((ARMOperand*)Operands[2])->addRegOperands(Inst, 1);
2765   // Create a writeback register dummy placeholder.
2766   Inst.addOperand(MCOperand::CreateImm(0));
2767   ((ARMOperand*)Operands[3])->addAddrMode3Operands(Inst, 3);
2768   ((ARMOperand*)Operands[1])->addCondCodeOperands(Inst, 2);
2769   return true;
2770 }
2771
2772 /// cvtThumbMultiple- Convert parsed operands to MCInst.
2773 /// Needed here because the Asm Gen Matcher can't handle properly tied operands
2774 /// when they refer multiple MIOperands inside a single one.
2775 bool ARMAsmParser::
2776 cvtThumbMultiply(MCInst &Inst, unsigned Opcode,
2777            const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2778   // The second source operand must be the same register as the destination
2779   // operand.
2780   if (Operands.size() == 6 &&
2781       (((ARMOperand*)Operands[3])->getReg() !=
2782        ((ARMOperand*)Operands[5])->getReg()) &&
2783       (((ARMOperand*)Operands[3])->getReg() !=
2784        ((ARMOperand*)Operands[4])->getReg())) {
2785     Error(Operands[3]->getStartLoc(),
2786           "destination register must match source register");
2787     return false;
2788   }
2789   ((ARMOperand*)Operands[3])->addRegOperands(Inst, 1);
2790   ((ARMOperand*)Operands[1])->addCCOutOperands(Inst, 1);
2791   ((ARMOperand*)Operands[4])->addRegOperands(Inst, 1);
2792   // If we have a three-operand form, use that, else the second source operand
2793   // is just the destination operand again.
2794   if (Operands.size() == 6)
2795     ((ARMOperand*)Operands[5])->addRegOperands(Inst, 1);
2796   else
2797     Inst.addOperand(Inst.getOperand(0));
2798   ((ARMOperand*)Operands[2])->addCondCodeOperands(Inst, 2);
2799
2800   return true;
2801 }
2802
2803 /// Parse an ARM memory expression, return false if successful else return true
2804 /// or an error.  The first token must be a '[' when called.
2805 bool ARMAsmParser::
2806 parseMemory(SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
2807   SMLoc S, E;
2808   assert(Parser.getTok().is(AsmToken::LBrac) &&
2809          "Token is not a Left Bracket");
2810   S = Parser.getTok().getLoc();
2811   Parser.Lex(); // Eat left bracket token.
2812
2813   const AsmToken &BaseRegTok = Parser.getTok();
2814   int BaseRegNum = tryParseRegister();
2815   if (BaseRegNum == -1)
2816     return Error(BaseRegTok.getLoc(), "register expected");
2817
2818   // The next token must either be a comma or a closing bracket.
2819   const AsmToken &Tok = Parser.getTok();
2820   if (!Tok.is(AsmToken::Comma) && !Tok.is(AsmToken::RBrac))
2821     return Error(Tok.getLoc(), "malformed memory operand");
2822
2823   if (Tok.is(AsmToken::RBrac)) {
2824     E = Tok.getLoc();
2825     Parser.Lex(); // Eat right bracket token.
2826
2827     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, 0, 0, ARM_AM::no_shift,
2828                                              0, false, S, E));
2829
2830     // If there's a pre-indexing writeback marker, '!', just add it as a token
2831     // operand. It's rather odd, but syntactically valid.
2832     if (Parser.getTok().is(AsmToken::Exclaim)) {
2833       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
2834       Parser.Lex(); // Eat the '!'.
2835     }
2836
2837     return false;
2838   }
2839
2840   assert(Tok.is(AsmToken::Comma) && "Lost comma in memory operand?!");
2841   Parser.Lex(); // Eat the comma.
2842
2843   // If we have a '#' it's an immediate offset, else assume it's a register
2844   // offset.
2845   if (Parser.getTok().is(AsmToken::Hash)) {
2846     Parser.Lex(); // Eat the '#'.
2847     E = Parser.getTok().getLoc();
2848
2849     bool isNegative = getParser().getTok().is(AsmToken::Minus);
2850     const MCExpr *Offset;
2851     if (getParser().ParseExpression(Offset))
2852      return true;
2853
2854     // The expression has to be a constant. Memory references with relocations
2855     // don't come through here, as they use the <label> forms of the relevant
2856     // instructions.
2857     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
2858     if (!CE)
2859       return Error (E, "constant expression expected");
2860
2861     // If the constant was #-0, represent it as INT32_MIN.
2862     int32_t Val = CE->getValue();
2863     if (isNegative && Val == 0)
2864       CE = MCConstantExpr::Create(INT32_MIN, getContext());
2865
2866     // Now we should have the closing ']'
2867     E = Parser.getTok().getLoc();
2868     if (Parser.getTok().isNot(AsmToken::RBrac))
2869       return Error(E, "']' expected");
2870     Parser.Lex(); // Eat right bracket token.
2871
2872     // Don't worry about range checking the value here. That's handled by
2873     // the is*() predicates.
2874     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, CE, 0,
2875                                              ARM_AM::no_shift, 0, false, S,E));
2876
2877     // If there's a pre-indexing writeback marker, '!', just add it as a token
2878     // operand.
2879     if (Parser.getTok().is(AsmToken::Exclaim)) {
2880       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
2881       Parser.Lex(); // Eat the '!'.
2882     }
2883
2884     return false;
2885   }
2886
2887   // The register offset is optionally preceded by a '+' or '-'
2888   bool isNegative = false;
2889   if (Parser.getTok().is(AsmToken::Minus)) {
2890     isNegative = true;
2891     Parser.Lex(); // Eat the '-'.
2892   } else if (Parser.getTok().is(AsmToken::Plus)) {
2893     // Nothing to do.
2894     Parser.Lex(); // Eat the '+'.
2895   }
2896
2897   E = Parser.getTok().getLoc();
2898   int OffsetRegNum = tryParseRegister();
2899   if (OffsetRegNum == -1)
2900     return Error(E, "register expected");
2901
2902   // If there's a shift operator, handle it.
2903   ARM_AM::ShiftOpc ShiftType = ARM_AM::no_shift;
2904   unsigned ShiftImm = 0;
2905   if (Parser.getTok().is(AsmToken::Comma)) {
2906     Parser.Lex(); // Eat the ','.
2907     if (parseMemRegOffsetShift(ShiftType, ShiftImm))
2908       return true;
2909   }
2910
2911   // Now we should have the closing ']'
2912   E = Parser.getTok().getLoc();
2913   if (Parser.getTok().isNot(AsmToken::RBrac))
2914     return Error(E, "']' expected");
2915   Parser.Lex(); // Eat right bracket token.
2916
2917   Operands.push_back(ARMOperand::CreateMem(BaseRegNum, 0, OffsetRegNum,
2918                                            ShiftType, ShiftImm, isNegative,
2919                                            S, E));
2920
2921   // If there's a pre-indexing writeback marker, '!', just add it as a token
2922   // operand.
2923   if (Parser.getTok().is(AsmToken::Exclaim)) {
2924     Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
2925     Parser.Lex(); // Eat the '!'.
2926   }
2927
2928   return false;
2929 }
2930
2931 /// parseMemRegOffsetShift - one of these two:
2932 ///   ( lsl | lsr | asr | ror ) , # shift_amount
2933 ///   rrx
2934 /// return true if it parses a shift otherwise it returns false.
2935 bool ARMAsmParser::parseMemRegOffsetShift(ARM_AM::ShiftOpc &St,
2936                                           unsigned &Amount) {
2937   SMLoc Loc = Parser.getTok().getLoc();
2938   const AsmToken &Tok = Parser.getTok();
2939   if (Tok.isNot(AsmToken::Identifier))
2940     return true;
2941   StringRef ShiftName = Tok.getString();
2942   if (ShiftName == "lsl" || ShiftName == "LSL")
2943     St = ARM_AM::lsl;
2944   else if (ShiftName == "lsr" || ShiftName == "LSR")
2945     St = ARM_AM::lsr;
2946   else if (ShiftName == "asr" || ShiftName == "ASR")
2947     St = ARM_AM::asr;
2948   else if (ShiftName == "ror" || ShiftName == "ROR")
2949     St = ARM_AM::ror;
2950   else if (ShiftName == "rrx" || ShiftName == "RRX")
2951     St = ARM_AM::rrx;
2952   else
2953     return Error(Loc, "illegal shift operator");
2954   Parser.Lex(); // Eat shift type token.
2955
2956   // rrx stands alone.
2957   Amount = 0;
2958   if (St != ARM_AM::rrx) {
2959     Loc = Parser.getTok().getLoc();
2960     // A '#' and a shift amount.
2961     const AsmToken &HashTok = Parser.getTok();
2962     if (HashTok.isNot(AsmToken::Hash))
2963       return Error(HashTok.getLoc(), "'#' expected");
2964     Parser.Lex(); // Eat hash token.
2965
2966     const MCExpr *Expr;
2967     if (getParser().ParseExpression(Expr))
2968       return true;
2969     // Range check the immediate.
2970     // lsl, ror: 0 <= imm <= 31
2971     // lsr, asr: 0 <= imm <= 32
2972     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
2973     if (!CE)
2974       return Error(Loc, "shift amount must be an immediate");
2975     int64_t Imm = CE->getValue();
2976     if (Imm < 0 ||
2977         ((St == ARM_AM::lsl || St == ARM_AM::ror) && Imm > 31) ||
2978         ((St == ARM_AM::lsr || St == ARM_AM::asr) && Imm > 32))
2979       return Error(Loc, "immediate shift value out of range");
2980     Amount = Imm;
2981   }
2982
2983   return false;
2984 }
2985
2986 /// Parse a arm instruction operand.  For now this parses the operand regardless
2987 /// of the mnemonic.
2988 bool ARMAsmParser::parseOperand(SmallVectorImpl<MCParsedAsmOperand*> &Operands,
2989                                 StringRef Mnemonic) {
2990   SMLoc S, E;
2991
2992   // Check if the current operand has a custom associated parser, if so, try to
2993   // custom parse the operand, or fallback to the general approach.
2994   OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
2995   if (ResTy == MatchOperand_Success)
2996     return false;
2997   // If there wasn't a custom match, try the generic matcher below. Otherwise,
2998   // there was a match, but an error occurred, in which case, just return that
2999   // the operand parsing failed.
3000   if (ResTy == MatchOperand_ParseFail)
3001     return true;
3002
3003   switch (getLexer().getKind()) {
3004   default:
3005     Error(Parser.getTok().getLoc(), "unexpected token in operand");
3006     return true;
3007   case AsmToken::Identifier: {
3008     if (!tryParseRegisterWithWriteBack(Operands))
3009       return false;
3010     int Res = tryParseShiftRegister(Operands);
3011     if (Res == 0) // success
3012       return false;
3013     else if (Res == -1) // irrecoverable error
3014       return true;
3015
3016     // Fall though for the Identifier case that is not a register or a
3017     // special name.
3018   }
3019   case AsmToken::Integer: // things like 1f and 2b as a branch targets
3020   case AsmToken::Dot: {   // . as a branch target
3021     // This was not a register so parse other operands that start with an
3022     // identifier (like labels) as expressions and create them as immediates.
3023     const MCExpr *IdVal;
3024     S = Parser.getTok().getLoc();
3025     if (getParser().ParseExpression(IdVal))
3026       return true;
3027     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
3028     Operands.push_back(ARMOperand::CreateImm(IdVal, S, E));
3029     return false;
3030   }
3031   case AsmToken::LBrac:
3032     return parseMemory(Operands);
3033   case AsmToken::LCurly:
3034     return parseRegisterList(Operands);
3035   case AsmToken::Hash: {
3036     // #42 -> immediate.
3037     // TODO: ":lower16:" and ":upper16:" modifiers after # before immediate
3038     S = Parser.getTok().getLoc();
3039     Parser.Lex();
3040     bool isNegative = Parser.getTok().is(AsmToken::Minus);
3041     const MCExpr *ImmVal;
3042     if (getParser().ParseExpression(ImmVal))
3043       return true;
3044     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ImmVal);
3045     if (!CE) {
3046       Error(S, "constant expression expected");
3047       return MatchOperand_ParseFail;
3048     }
3049     int32_t Val = CE->getValue();
3050     if (isNegative && Val == 0)
3051       ImmVal = MCConstantExpr::Create(INT32_MIN, getContext());
3052     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
3053     Operands.push_back(ARMOperand::CreateImm(ImmVal, S, E));
3054     return false;
3055   }
3056   case AsmToken::Colon: {
3057     // ":lower16:" and ":upper16:" expression prefixes
3058     // FIXME: Check it's an expression prefix,
3059     // e.g. (FOO - :lower16:BAR) isn't legal.
3060     ARMMCExpr::VariantKind RefKind;
3061     if (parsePrefix(RefKind))
3062       return true;
3063
3064     const MCExpr *SubExprVal;
3065     if (getParser().ParseExpression(SubExprVal))
3066       return true;
3067
3068     const MCExpr *ExprVal = ARMMCExpr::Create(RefKind, SubExprVal,
3069                                                    getContext());
3070     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
3071     Operands.push_back(ARMOperand::CreateImm(ExprVal, S, E));
3072     return false;
3073   }
3074   }
3075 }
3076
3077 // parsePrefix - Parse ARM 16-bit relocations expression prefix, i.e.
3078 //  :lower16: and :upper16:.
3079 bool ARMAsmParser::parsePrefix(ARMMCExpr::VariantKind &RefKind) {
3080   RefKind = ARMMCExpr::VK_ARM_None;
3081
3082   // :lower16: and :upper16: modifiers
3083   assert(getLexer().is(AsmToken::Colon) && "expected a :");
3084   Parser.Lex(); // Eat ':'
3085
3086   if (getLexer().isNot(AsmToken::Identifier)) {
3087     Error(Parser.getTok().getLoc(), "expected prefix identifier in operand");
3088     return true;
3089   }
3090
3091   StringRef IDVal = Parser.getTok().getIdentifier();
3092   if (IDVal == "lower16") {
3093     RefKind = ARMMCExpr::VK_ARM_LO16;
3094   } else if (IDVal == "upper16") {
3095     RefKind = ARMMCExpr::VK_ARM_HI16;
3096   } else {
3097     Error(Parser.getTok().getLoc(), "unexpected prefix in operand");
3098     return true;
3099   }
3100   Parser.Lex();
3101
3102   if (getLexer().isNot(AsmToken::Colon)) {
3103     Error(Parser.getTok().getLoc(), "unexpected token after prefix");
3104     return true;
3105   }
3106   Parser.Lex(); // Eat the last ':'
3107   return false;
3108 }
3109
3110 /// \brief Given a mnemonic, split out possible predication code and carry
3111 /// setting letters to form a canonical mnemonic and flags.
3112 //
3113 // FIXME: Would be nice to autogen this.
3114 // FIXME: This is a bit of a maze of special cases.
3115 StringRef ARMAsmParser::splitMnemonic(StringRef Mnemonic,
3116                                       unsigned &PredicationCode,
3117                                       bool &CarrySetting,
3118                                       unsigned &ProcessorIMod,
3119                                       StringRef &ITMask) {
3120   PredicationCode = ARMCC::AL;
3121   CarrySetting = false;
3122   ProcessorIMod = 0;
3123
3124   // Ignore some mnemonics we know aren't predicated forms.
3125   //
3126   // FIXME: Would be nice to autogen this.
3127   if ((Mnemonic == "movs" && isThumb()) ||
3128       Mnemonic == "teq"   || Mnemonic == "vceq"   || Mnemonic == "svc"   ||
3129       Mnemonic == "mls"   || Mnemonic == "smmls"  || Mnemonic == "vcls"  ||
3130       Mnemonic == "vmls"  || Mnemonic == "vnmls"  || Mnemonic == "vacge" ||
3131       Mnemonic == "vcge"  || Mnemonic == "vclt"   || Mnemonic == "vacgt" ||
3132       Mnemonic == "vcgt"  || Mnemonic == "vcle"   || Mnemonic == "smlal" ||
3133       Mnemonic == "umaal" || Mnemonic == "umlal"  || Mnemonic == "vabal" ||
3134       Mnemonic == "vmlal" || Mnemonic == "vpadal" || Mnemonic == "vqdmlal")
3135     return Mnemonic;
3136
3137   // First, split out any predication code. Ignore mnemonics we know aren't
3138   // predicated but do have a carry-set and so weren't caught above.
3139   if (Mnemonic != "adcs" && Mnemonic != "bics" && Mnemonic != "movs" &&
3140       Mnemonic != "muls" && Mnemonic != "smlals" && Mnemonic != "smulls" &&
3141       Mnemonic != "umlals" && Mnemonic != "umulls" && Mnemonic != "lsls" &&
3142       Mnemonic != "sbcs" && Mnemonic != "rscs") {
3143     unsigned CC = StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2))
3144       .Case("eq", ARMCC::EQ)
3145       .Case("ne", ARMCC::NE)
3146       .Case("hs", ARMCC::HS)
3147       .Case("cs", ARMCC::HS)
3148       .Case("lo", ARMCC::LO)
3149       .Case("cc", ARMCC::LO)
3150       .Case("mi", ARMCC::MI)
3151       .Case("pl", ARMCC::PL)
3152       .Case("vs", ARMCC::VS)
3153       .Case("vc", ARMCC::VC)
3154       .Case("hi", ARMCC::HI)
3155       .Case("ls", ARMCC::LS)
3156       .Case("ge", ARMCC::GE)
3157       .Case("lt", ARMCC::LT)
3158       .Case("gt", ARMCC::GT)
3159       .Case("le", ARMCC::LE)
3160       .Case("al", ARMCC::AL)
3161       .Default(~0U);
3162     if (CC != ~0U) {
3163       Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 2);
3164       PredicationCode = CC;
3165     }
3166   }
3167
3168   // Next, determine if we have a carry setting bit. We explicitly ignore all
3169   // the instructions we know end in 's'.
3170   if (Mnemonic.endswith("s") &&
3171       !(Mnemonic == "cps" || Mnemonic == "mls" ||
3172         Mnemonic == "mrs" || Mnemonic == "smmls" || Mnemonic == "vabs" ||
3173         Mnemonic == "vcls" || Mnemonic == "vmls" || Mnemonic == "vmrs" ||
3174         Mnemonic == "vnmls" || Mnemonic == "vqabs" || Mnemonic == "vrecps" ||
3175         Mnemonic == "vrsqrts" || Mnemonic == "srs" ||
3176         (Mnemonic == "movs" && isThumb()))) {
3177     Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 1);
3178     CarrySetting = true;
3179   }
3180
3181   // The "cps" instruction can have a interrupt mode operand which is glued into
3182   // the mnemonic. Check if this is the case, split it and parse the imod op
3183   if (Mnemonic.startswith("cps")) {
3184     // Split out any imod code.
3185     unsigned IMod =
3186       StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2, 2))
3187       .Case("ie", ARM_PROC::IE)
3188       .Case("id", ARM_PROC::ID)
3189       .Default(~0U);
3190     if (IMod != ~0U) {
3191       Mnemonic = Mnemonic.slice(0, Mnemonic.size()-2);
3192       ProcessorIMod = IMod;
3193     }
3194   }
3195
3196   // The "it" instruction has the condition mask on the end of the mnemonic.
3197   if (Mnemonic.startswith("it")) {
3198     ITMask = Mnemonic.slice(2, Mnemonic.size());
3199     Mnemonic = Mnemonic.slice(0, 2);
3200   }
3201
3202   return Mnemonic;
3203 }
3204
3205 /// \brief Given a canonical mnemonic, determine if the instruction ever allows
3206 /// inclusion of carry set or predication code operands.
3207 //
3208 // FIXME: It would be nice to autogen this.
3209 void ARMAsmParser::
3210 getMnemonicAcceptInfo(StringRef Mnemonic, bool &CanAcceptCarrySet,
3211                       bool &CanAcceptPredicationCode) {
3212   if (Mnemonic == "and" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
3213       Mnemonic == "rrx" || Mnemonic == "ror" || Mnemonic == "sub" ||
3214       Mnemonic == "add" || Mnemonic == "adc" ||
3215       Mnemonic == "mul" || Mnemonic == "bic" || Mnemonic == "asr" ||
3216       Mnemonic == "orr" || Mnemonic == "mvn" ||
3217       Mnemonic == "rsb" || Mnemonic == "rsc" || Mnemonic == "orn" ||
3218       Mnemonic == "sbc" || Mnemonic == "eor" || Mnemonic == "neg" ||
3219       (!isThumb() && (Mnemonic == "smull" || Mnemonic == "mov" ||
3220                       Mnemonic == "mla" || Mnemonic == "smlal" ||
3221                       Mnemonic == "umlal" || Mnemonic == "umull"))) {
3222     CanAcceptCarrySet = true;
3223   } else
3224     CanAcceptCarrySet = false;
3225
3226   if (Mnemonic == "cbnz" || Mnemonic == "setend" || Mnemonic == "dmb" ||
3227       Mnemonic == "cps" || Mnemonic == "mcr2" || Mnemonic == "it" ||
3228       Mnemonic == "mcrr2" || Mnemonic == "cbz" || Mnemonic == "cdp2" ||
3229       Mnemonic == "trap" || Mnemonic == "mrc2" || Mnemonic == "mrrc2" ||
3230       Mnemonic == "dsb" || Mnemonic == "isb" || Mnemonic == "setend" ||
3231       (Mnemonic == "clrex" && !isThumb()) ||
3232       (Mnemonic == "nop" && isThumbOne()) ||
3233       ((Mnemonic == "pld" || Mnemonic == "pli" || Mnemonic == "pldw") &&
3234        !isThumb()) ||
3235       ((Mnemonic.startswith("rfe") || Mnemonic.startswith("srs")) &&
3236        !isThumb()) ||
3237       Mnemonic.startswith("cps") || (Mnemonic == "movs" && isThumbOne())) {
3238     CanAcceptPredicationCode = false;
3239   } else
3240     CanAcceptPredicationCode = true;
3241
3242   if (isThumb()) {
3243     if (Mnemonic == "bkpt" || Mnemonic == "mcr" || Mnemonic == "mcrr" ||
3244         Mnemonic == "mrc" || Mnemonic == "mrrc" || Mnemonic == "cdp")
3245       CanAcceptPredicationCode = false;
3246   }
3247 }
3248
3249 bool ARMAsmParser::shouldOmitCCOutOperand(StringRef Mnemonic,
3250                                SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
3251   // FIXME: This is all horribly hacky. We really need a better way to deal
3252   // with optional operands like this in the matcher table.
3253
3254   // The 'mov' mnemonic is special. One variant has a cc_out operand, while
3255   // another does not. Specifically, the MOVW instruction does not. So we
3256   // special case it here and remove the defaulted (non-setting) cc_out
3257   // operand if that's the instruction we're trying to match.
3258   //
3259   // We do this as post-processing of the explicit operands rather than just
3260   // conditionally adding the cc_out in the first place because we need
3261   // to check the type of the parsed immediate operand.
3262   if (Mnemonic == "mov" && Operands.size() > 4 && !isThumb() &&
3263       !static_cast<ARMOperand*>(Operands[4])->isARMSOImm() &&
3264       static_cast<ARMOperand*>(Operands[4])->isImm0_65535Expr() &&
3265       static_cast<ARMOperand*>(Operands[1])->getReg() == 0)
3266     return true;
3267
3268   // Register-register 'add' for thumb does not have a cc_out operand
3269   // when there are only two register operands.
3270   if (isThumb() && Mnemonic == "add" && Operands.size() == 5 &&
3271       static_cast<ARMOperand*>(Operands[3])->isReg() &&
3272       static_cast<ARMOperand*>(Operands[4])->isReg() &&
3273       static_cast<ARMOperand*>(Operands[1])->getReg() == 0)
3274     return true;
3275   // Register-register 'add' for thumb does not have a cc_out operand
3276   // when it's an ADD Rdm, SP, {Rdm|#imm0_255} instruction. We do
3277   // have to check the immediate range here since Thumb2 has a variant
3278   // that can handle a different range and has a cc_out operand.
3279   if (((isThumb() && Mnemonic == "add") ||
3280        (isThumbTwo() && Mnemonic == "sub")) &&
3281       Operands.size() == 6 &&
3282       static_cast<ARMOperand*>(Operands[3])->isReg() &&
3283       static_cast<ARMOperand*>(Operands[4])->isReg() &&
3284       static_cast<ARMOperand*>(Operands[4])->getReg() == ARM::SP &&
3285       static_cast<ARMOperand*>(Operands[1])->getReg() == 0 &&
3286       (static_cast<ARMOperand*>(Operands[5])->isReg() ||
3287        static_cast<ARMOperand*>(Operands[5])->isImm0_1020s4()))
3288     return true;
3289   // For Thumb2, add/sub immediate does not have a cc_out operand for the
3290   // imm0_4095 variant. That's the least-preferred variant when
3291   // selecting via the generic "add" mnemonic, so to know that we
3292   // should remove the cc_out operand, we have to explicitly check that
3293   // it's not one of the other variants. Ugh.
3294   if (isThumbTwo() && (Mnemonic == "add" || Mnemonic == "sub") &&
3295       Operands.size() == 6 &&
3296       static_cast<ARMOperand*>(Operands[3])->isReg() &&
3297       static_cast<ARMOperand*>(Operands[4])->isReg() &&
3298       static_cast<ARMOperand*>(Operands[5])->isImm()) {
3299     // Nest conditions rather than one big 'if' statement for readability.
3300     //
3301     // If either register is a high reg, it's either one of the SP
3302     // variants (handled above) or a 32-bit encoding, so we just
3303     // check against T3.
3304     if ((!isARMLowRegister(static_cast<ARMOperand*>(Operands[3])->getReg()) ||
3305          !isARMLowRegister(static_cast<ARMOperand*>(Operands[4])->getReg())) &&
3306         static_cast<ARMOperand*>(Operands[5])->isT2SOImm())
3307       return false;
3308     // If both registers are low, we're in an IT block, and the immediate is
3309     // in range, we should use encoding T1 instead, which has a cc_out.
3310     if (inITBlock() &&
3311         isARMLowRegister(static_cast<ARMOperand*>(Operands[3])->getReg()) &&
3312         isARMLowRegister(static_cast<ARMOperand*>(Operands[4])->getReg()) &&
3313         static_cast<ARMOperand*>(Operands[5])->isImm0_7())
3314       return false;
3315
3316     // Otherwise, we use encoding T4, which does not have a cc_out
3317     // operand.
3318     return true;
3319   }
3320
3321   // The thumb2 multiply instruction doesn't have a CCOut register, so
3322   // if we have a "mul" mnemonic in Thumb mode, check if we'll be able to
3323   // use the 16-bit encoding or not.
3324   if (isThumbTwo() && Mnemonic == "mul" && Operands.size() == 6 &&
3325       static_cast<ARMOperand*>(Operands[1])->getReg() == 0 &&
3326       static_cast<ARMOperand*>(Operands[3])->isReg() &&
3327       static_cast<ARMOperand*>(Operands[4])->isReg() &&
3328       static_cast<ARMOperand*>(Operands[5])->isReg() &&
3329       // If the registers aren't low regs, the destination reg isn't the
3330       // same as one of the source regs, or the cc_out operand is zero
3331       // outside of an IT block, we have to use the 32-bit encoding, so
3332       // remove the cc_out operand.
3333       (!isARMLowRegister(static_cast<ARMOperand*>(Operands[3])->getReg()) ||
3334        !isARMLowRegister(static_cast<ARMOperand*>(Operands[4])->getReg()) ||
3335        !inITBlock() ||
3336        (static_cast<ARMOperand*>(Operands[3])->getReg() !=
3337         static_cast<ARMOperand*>(Operands[5])->getReg() &&
3338         static_cast<ARMOperand*>(Operands[3])->getReg() !=
3339         static_cast<ARMOperand*>(Operands[4])->getReg())))
3340     return true;
3341
3342
3343
3344   // Register-register 'add/sub' for thumb does not have a cc_out operand
3345   // when it's an ADD/SUB SP, #imm. Be lenient on count since there's also
3346   // the "add/sub SP, SP, #imm" version. If the follow-up operands aren't
3347   // right, this will result in better diagnostics (which operand is off)
3348   // anyway.
3349   if (isThumb() && (Mnemonic == "add" || Mnemonic == "sub") &&
3350       (Operands.size() == 5 || Operands.size() == 6) &&
3351       static_cast<ARMOperand*>(Operands[3])->isReg() &&
3352       static_cast<ARMOperand*>(Operands[3])->getReg() == ARM::SP &&
3353       static_cast<ARMOperand*>(Operands[1])->getReg() == 0)
3354     return true;
3355
3356   return false;
3357 }
3358
3359 /// Parse an arm instruction mnemonic followed by its operands.
3360 bool ARMAsmParser::ParseInstruction(StringRef Name, SMLoc NameLoc,
3361                                SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
3362   // Create the leading tokens for the mnemonic, split by '.' characters.
3363   size_t Start = 0, Next = Name.find('.');
3364   StringRef Mnemonic = Name.slice(Start, Next);
3365
3366   // Split out the predication code and carry setting flag from the mnemonic.
3367   unsigned PredicationCode;
3368   unsigned ProcessorIMod;
3369   bool CarrySetting;
3370   StringRef ITMask;
3371   Mnemonic = splitMnemonic(Mnemonic, PredicationCode, CarrySetting,
3372                            ProcessorIMod, ITMask);
3373
3374   // In Thumb1, only the branch (B) instruction can be predicated.
3375   if (isThumbOne() && PredicationCode != ARMCC::AL && Mnemonic != "b") {
3376     Parser.EatToEndOfStatement();
3377     return Error(NameLoc, "conditional execution not supported in Thumb1");
3378   }
3379
3380   Operands.push_back(ARMOperand::CreateToken(Mnemonic, NameLoc));
3381
3382   // Handle the IT instruction ITMask. Convert it to a bitmask. This
3383   // is the mask as it will be for the IT encoding if the conditional
3384   // encoding has a '1' as it's bit0 (i.e. 't' ==> '1'). In the case
3385   // where the conditional bit0 is zero, the instruction post-processing
3386   // will adjust the mask accordingly.
3387   if (Mnemonic == "it") {
3388     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + 2);
3389     if (ITMask.size() > 3) {
3390       Parser.EatToEndOfStatement();
3391       return Error(Loc, "too many conditions on IT instruction");
3392     }
3393     unsigned Mask = 8;
3394     for (unsigned i = ITMask.size(); i != 0; --i) {
3395       char pos = ITMask[i - 1];
3396       if (pos != 't' && pos != 'e') {
3397         Parser.EatToEndOfStatement();
3398         return Error(Loc, "illegal IT block condition mask '" + ITMask + "'");
3399       }
3400       Mask >>= 1;
3401       if (ITMask[i - 1] == 't')
3402         Mask |= 8;
3403     }
3404     Operands.push_back(ARMOperand::CreateITMask(Mask, Loc));
3405   }
3406
3407   // FIXME: This is all a pretty gross hack. We should automatically handle
3408   // optional operands like this via tblgen.
3409
3410   // Next, add the CCOut and ConditionCode operands, if needed.
3411   //
3412   // For mnemonics which can ever incorporate a carry setting bit or predication
3413   // code, our matching model involves us always generating CCOut and
3414   // ConditionCode operands to match the mnemonic "as written" and then we let
3415   // the matcher deal with finding the right instruction or generating an
3416   // appropriate error.
3417   bool CanAcceptCarrySet, CanAcceptPredicationCode;
3418   getMnemonicAcceptInfo(Mnemonic, CanAcceptCarrySet, CanAcceptPredicationCode);
3419
3420   // If we had a carry-set on an instruction that can't do that, issue an
3421   // error.
3422   if (!CanAcceptCarrySet && CarrySetting) {
3423     Parser.EatToEndOfStatement();
3424     return Error(NameLoc, "instruction '" + Mnemonic +
3425                  "' can not set flags, but 's' suffix specified");
3426   }
3427   // If we had a predication code on an instruction that can't do that, issue an
3428   // error.
3429   if (!CanAcceptPredicationCode && PredicationCode != ARMCC::AL) {
3430     Parser.EatToEndOfStatement();
3431     return Error(NameLoc, "instruction '" + Mnemonic +
3432                  "' is not predicable, but condition code specified");
3433   }
3434
3435   // Add the carry setting operand, if necessary.
3436   if (CanAcceptCarrySet) {
3437     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size());
3438     Operands.push_back(ARMOperand::CreateCCOut(CarrySetting ? ARM::CPSR : 0,
3439                                                Loc));
3440   }
3441
3442   // Add the predication code operand, if necessary.
3443   if (CanAcceptPredicationCode) {
3444     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size() +
3445                                       CarrySetting);
3446     Operands.push_back(ARMOperand::CreateCondCode(
3447                          ARMCC::CondCodes(PredicationCode), Loc));
3448   }
3449
3450   // Add the processor imod operand, if necessary.
3451   if (ProcessorIMod) {
3452     Operands.push_back(ARMOperand::CreateImm(
3453           MCConstantExpr::Create(ProcessorIMod, getContext()),
3454                                  NameLoc, NameLoc));
3455   }
3456
3457   // Add the remaining tokens in the mnemonic.
3458   while (Next != StringRef::npos) {
3459     Start = Next;
3460     Next = Name.find('.', Start + 1);
3461     StringRef ExtraToken = Name.slice(Start, Next);
3462
3463     // For now, we're only parsing Thumb1 (for the most part), so
3464     // just ignore ".n" qualifiers. We'll use them to restrict
3465     // matching when we do Thumb2.
3466     if (ExtraToken != ".n") {
3467       SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Start);
3468       Operands.push_back(ARMOperand::CreateToken(ExtraToken, Loc));
3469     }
3470   }
3471
3472   // Read the remaining operands.
3473   if (getLexer().isNot(AsmToken::EndOfStatement)) {
3474     // Read the first operand.
3475     if (parseOperand(Operands, Mnemonic)) {
3476       Parser.EatToEndOfStatement();
3477       return true;
3478     }
3479
3480     while (getLexer().is(AsmToken::Comma)) {
3481       Parser.Lex();  // Eat the comma.
3482
3483       // Parse and remember the operand.
3484       if (parseOperand(Operands, Mnemonic)) {
3485         Parser.EatToEndOfStatement();
3486         return true;
3487       }
3488     }
3489   }
3490
3491   if (getLexer().isNot(AsmToken::EndOfStatement)) {
3492     Parser.EatToEndOfStatement();
3493     return TokError("unexpected token in argument list");
3494   }
3495
3496   Parser.Lex(); // Consume the EndOfStatement
3497
3498   // Some instructions, mostly Thumb, have forms for the same mnemonic that
3499   // do and don't have a cc_out optional-def operand. With some spot-checks
3500   // of the operand list, we can figure out which variant we're trying to
3501   // parse and adjust accordingly before actually matching. We shouldn't ever
3502   // try to remove a cc_out operand that was explicitly set on the the
3503   // mnemonic, of course (CarrySetting == true). Reason number #317 the
3504   // table driven matcher doesn't fit well with the ARM instruction set.
3505   if (!CarrySetting && shouldOmitCCOutOperand(Mnemonic, Operands)) {
3506     ARMOperand *Op = static_cast<ARMOperand*>(Operands[1]);
3507     Operands.erase(Operands.begin() + 1);
3508     delete Op;
3509   }
3510
3511   // ARM mode 'blx' need special handling, as the register operand version
3512   // is predicable, but the label operand version is not. So, we can't rely
3513   // on the Mnemonic based checking to correctly figure out when to put
3514   // a CondCode operand in the list. If we're trying to match the label
3515   // version, remove the CondCode operand here.
3516   if (!isThumb() && Mnemonic == "blx" && Operands.size() == 3 &&
3517       static_cast<ARMOperand*>(Operands[2])->isImm()) {
3518     ARMOperand *Op = static_cast<ARMOperand*>(Operands[1]);
3519     Operands.erase(Operands.begin() + 1);
3520     delete Op;
3521   }
3522
3523   // The vector-compare-to-zero instructions have a literal token "#0" at
3524   // the end that comes to here as an immediate operand. Convert it to a
3525   // token to play nicely with the matcher.
3526   if ((Mnemonic == "vceq" || Mnemonic == "vcge" || Mnemonic == "vcgt" ||
3527       Mnemonic == "vcle" || Mnemonic == "vclt") && Operands.size() == 6 &&
3528       static_cast<ARMOperand*>(Operands[5])->isImm()) {
3529     ARMOperand *Op = static_cast<ARMOperand*>(Operands[5]);
3530     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op->getImm());
3531     if (CE && CE->getValue() == 0) {
3532       Operands.erase(Operands.begin() + 5);
3533       Operands.push_back(ARMOperand::CreateToken("#0", Op->getStartLoc()));
3534       delete Op;
3535     }
3536   }
3537   // Similarly, the Thumb1 "RSB" instruction has a literal "#0" on the
3538   // end. Convert it to a token here.
3539   if (Mnemonic == "rsb" && isThumb() && Operands.size() == 6 &&
3540       static_cast<ARMOperand*>(Operands[5])->isImm()) {
3541     ARMOperand *Op = static_cast<ARMOperand*>(Operands[5]);
3542     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op->getImm());
3543     if (CE && CE->getValue() == 0) {
3544       Operands.erase(Operands.begin() + 5);
3545       Operands.push_back(ARMOperand::CreateToken("#0", Op->getStartLoc()));
3546       delete Op;
3547     }
3548   }
3549
3550   return false;
3551 }
3552
3553 // Validate context-sensitive operand constraints.
3554
3555 // return 'true' if register list contains non-low GPR registers,
3556 // 'false' otherwise. If Reg is in the register list or is HiReg, set
3557 // 'containsReg' to true.
3558 static bool checkLowRegisterList(MCInst Inst, unsigned OpNo, unsigned Reg,
3559                                  unsigned HiReg, bool &containsReg) {
3560   containsReg = false;
3561   for (unsigned i = OpNo; i < Inst.getNumOperands(); ++i) {
3562     unsigned OpReg = Inst.getOperand(i).getReg();
3563     if (OpReg == Reg)
3564       containsReg = true;
3565     // Anything other than a low register isn't legal here.
3566     if (!isARMLowRegister(OpReg) && (!HiReg || OpReg != HiReg))
3567       return true;
3568   }
3569   return false;
3570 }
3571
3572 // Check if the specified regisgter is in the register list of the inst,
3573 // starting at the indicated operand number.
3574 static bool listContainsReg(MCInst &Inst, unsigned OpNo, unsigned Reg) {
3575   for (unsigned i = OpNo; i < Inst.getNumOperands(); ++i) {
3576     unsigned OpReg = Inst.getOperand(i).getReg();
3577     if (OpReg == Reg)
3578       return true;
3579   }
3580   return false;
3581 }
3582
3583 // FIXME: We would really prefer to have MCInstrInfo (the wrapper around
3584 // the ARMInsts array) instead. Getting that here requires awkward
3585 // API changes, though. Better way?
3586 namespace llvm {
3587 extern MCInstrDesc ARMInsts[];
3588 }
3589 static MCInstrDesc &getInstDesc(unsigned Opcode) {
3590   return ARMInsts[Opcode];
3591 }
3592
3593 // FIXME: We would really like to be able to tablegen'erate this.
3594 bool ARMAsmParser::
3595 validateInstruction(MCInst &Inst,
3596                     const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
3597   MCInstrDesc &MCID = getInstDesc(Inst.getOpcode());
3598   SMLoc Loc = Operands[0]->getStartLoc();
3599   // Check the IT block state first.
3600   // NOTE: In Thumb mode, the BKPT instruction has the interesting property of
3601   // being allowed in IT blocks, but not being predicable.  It just always
3602   // executes.
3603   if (inITBlock() && Inst.getOpcode() != ARM::tBKPT) {
3604     unsigned bit = 1;
3605     if (ITState.FirstCond)
3606       ITState.FirstCond = false;
3607     else
3608       bit = (ITState.Mask >> (5 - ITState.CurPosition)) & 1;
3609     // The instruction must be predicable.
3610     if (!MCID.isPredicable())
3611       return Error(Loc, "instructions in IT block must be predicable");
3612     unsigned Cond = Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm();
3613     unsigned ITCond = bit ? ITState.Cond :
3614       ARMCC::getOppositeCondition(ITState.Cond);
3615     if (Cond != ITCond) {
3616       // Find the condition code Operand to get its SMLoc information.
3617       SMLoc CondLoc;
3618       for (unsigned i = 1; i < Operands.size(); ++i)
3619         if (static_cast<ARMOperand*>(Operands[i])->isCondCode())
3620           CondLoc = Operands[i]->getStartLoc();
3621       return Error(CondLoc, "incorrect condition in IT block; got '" +
3622                    StringRef(ARMCondCodeToString(ARMCC::CondCodes(Cond))) +
3623                    "', but expected '" +
3624                    ARMCondCodeToString(ARMCC::CondCodes(ITCond)) + "'");
3625     }
3626   // Check for non-'al' condition codes outside of the IT block.
3627   } else if (isThumbTwo() && MCID.isPredicable() &&
3628              Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm() !=
3629              ARMCC::AL && Inst.getOpcode() != ARM::tB &&
3630              Inst.getOpcode() != ARM::t2B)
3631     return Error(Loc, "predicated instructions must be in IT block");
3632
3633   switch (Inst.getOpcode()) {
3634   case ARM::LDRD:
3635   case ARM::LDRD_PRE:
3636   case ARM::LDRD_POST:
3637   case ARM::LDREXD: {
3638     // Rt2 must be Rt + 1.
3639     unsigned Rt = getARMRegisterNumbering(Inst.getOperand(0).getReg());
3640     unsigned Rt2 = getARMRegisterNumbering(Inst.getOperand(1).getReg());
3641     if (Rt2 != Rt + 1)
3642       return Error(Operands[3]->getStartLoc(),
3643                    "destination operands must be sequential");
3644     return false;
3645   }
3646   case ARM::STRD: {
3647     // Rt2 must be Rt + 1.
3648     unsigned Rt = getARMRegisterNumbering(Inst.getOperand(0).getReg());
3649     unsigned Rt2 = getARMRegisterNumbering(Inst.getOperand(1).getReg());
3650     if (Rt2 != Rt + 1)
3651       return Error(Operands[3]->getStartLoc(),
3652                    "source operands must be sequential");
3653     return false;
3654   }
3655   case ARM::STRD_PRE:
3656   case ARM::STRD_POST:
3657   case ARM::STREXD: {
3658     // Rt2 must be Rt + 1.
3659     unsigned Rt = getARMRegisterNumbering(Inst.getOperand(1).getReg());
3660     unsigned Rt2 = getARMRegisterNumbering(Inst.getOperand(2).getReg());
3661     if (Rt2 != Rt + 1)
3662       return Error(Operands[3]->getStartLoc(),
3663                    "source operands must be sequential");
3664     return false;
3665   }
3666   case ARM::SBFX:
3667   case ARM::UBFX: {
3668     // width must be in range [1, 32-lsb]
3669     unsigned lsb = Inst.getOperand(2).getImm();
3670     unsigned widthm1 = Inst.getOperand(3).getImm();
3671     if (widthm1 >= 32 - lsb)
3672       return Error(Operands[5]->getStartLoc(),
3673                    "bitfield width must be in range [1,32-lsb]");
3674     return false;
3675   }
3676   case ARM::tLDMIA: {
3677     // If we're parsing Thumb2, the .w variant is available and handles
3678     // most cases that are normally illegal for a Thumb1 LDM
3679     // instruction. We'll make the transformation in processInstruction()
3680     // if necessary.
3681     //
3682     // Thumb LDM instructions are writeback iff the base register is not
3683     // in the register list.
3684     unsigned Rn = Inst.getOperand(0).getReg();
3685     bool hasWritebackToken =
3686       (static_cast<ARMOperand*>(Operands[3])->isToken() &&
3687        static_cast<ARMOperand*>(Operands[3])->getToken() == "!");
3688     bool listContainsBase;
3689     if (checkLowRegisterList(Inst, 3, Rn, 0, listContainsBase) && !isThumbTwo())
3690       return Error(Operands[3 + hasWritebackToken]->getStartLoc(),
3691                    "registers must be in range r0-r7");
3692     // If we should have writeback, then there should be a '!' token.
3693     if (!listContainsBase && !hasWritebackToken && !isThumbTwo())
3694       return Error(Operands[2]->getStartLoc(),
3695                    "writeback operator '!' expected");
3696     // If we should not have writeback, there must not be a '!'. This is
3697     // true even for the 32-bit wide encodings.
3698     if (listContainsBase && hasWritebackToken)
3699       return Error(Operands[3]->getStartLoc(),
3700                    "writeback operator '!' not allowed when base register "
3701                    "in register list");
3702
3703     break;
3704   }
3705   case ARM::t2LDMIA_UPD: {
3706     if (listContainsReg(Inst, 3, Inst.getOperand(0).getReg()))
3707       return Error(Operands[4]->getStartLoc(),
3708                    "writeback operator '!' not allowed when base register "
3709                    "in register list");
3710     break;
3711   }
3712   case ARM::tPOP: {
3713     bool listContainsBase;
3714     if (checkLowRegisterList(Inst, 3, 0, ARM::PC, listContainsBase))
3715       return Error(Operands[2]->getStartLoc(),
3716                    "registers must be in range r0-r7 or pc");
3717     break;
3718   }
3719   case ARM::tPUSH: {
3720     bool listContainsBase;
3721     if (checkLowRegisterList(Inst, 3, 0, ARM::LR, listContainsBase))
3722       return Error(Operands[2]->getStartLoc(),
3723                    "registers must be in range r0-r7 or lr");
3724     break;
3725   }
3726   case ARM::tSTMIA_UPD: {
3727     bool listContainsBase;
3728     if (checkLowRegisterList(Inst, 4, 0, 0, listContainsBase) && !isThumbTwo())
3729       return Error(Operands[4]->getStartLoc(),
3730                    "registers must be in range r0-r7");
3731     break;
3732   }
3733   }
3734
3735   return false;
3736 }
3737
3738 void ARMAsmParser::
3739 processInstruction(MCInst &Inst,
3740                    const SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
3741   switch (Inst.getOpcode()) {
3742   case ARM::LDMIA_UPD:
3743     // If this is a load of a single register via a 'pop', then we should use
3744     // a post-indexed LDR instruction instead, per the ARM ARM.
3745     if (static_cast<ARMOperand*>(Operands[0])->getToken() == "pop" &&
3746         Inst.getNumOperands() == 5) {
3747       MCInst TmpInst;
3748       TmpInst.setOpcode(ARM::LDR_POST_IMM);
3749       TmpInst.addOperand(Inst.getOperand(4)); // Rt
3750       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
3751       TmpInst.addOperand(Inst.getOperand(1)); // Rn
3752       TmpInst.addOperand(MCOperand::CreateReg(0));  // am2offset
3753       TmpInst.addOperand(MCOperand::CreateImm(4));
3754       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
3755       TmpInst.addOperand(Inst.getOperand(3));
3756       Inst = TmpInst;
3757     }
3758     break;
3759   case ARM::STMDB_UPD:
3760     // If this is a store of a single register via a 'push', then we should use
3761     // a pre-indexed STR instruction instead, per the ARM ARM.
3762     if (static_cast<ARMOperand*>(Operands[0])->getToken() == "push" &&
3763         Inst.getNumOperands() == 5) {
3764       MCInst TmpInst;
3765       TmpInst.setOpcode(ARM::STR_PRE_IMM);
3766       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
3767       TmpInst.addOperand(Inst.getOperand(4)); // Rt
3768       TmpInst.addOperand(Inst.getOperand(1)); // addrmode_imm12
3769       TmpInst.addOperand(MCOperand::CreateImm(-4));
3770       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
3771       TmpInst.addOperand(Inst.getOperand(3));
3772       Inst = TmpInst;
3773     }
3774     break;
3775   case ARM::tADDi8:
3776     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
3777     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
3778     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
3779     // to encoding T1 if <Rd> is omitted."
3780     if (Inst.getOperand(3).getImm() < 8 && Operands.size() == 6)
3781       Inst.setOpcode(ARM::tADDi3);
3782     break;
3783   case ARM::tSUBi8:
3784     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
3785     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
3786     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
3787     // to encoding T1 if <Rd> is omitted."
3788     if (Inst.getOperand(3).getImm() < 8 && Operands.size() == 6)
3789       Inst.setOpcode(ARM::tSUBi3);
3790     break;
3791   case ARM::tB:
3792     // A Thumb conditional branch outside of an IT block is a tBcc.
3793     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock())
3794       Inst.setOpcode(ARM::tBcc);
3795     break;
3796   case ARM::t2B:
3797     // A Thumb2 conditional branch outside of an IT block is a t2Bcc.
3798     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock())
3799       Inst.setOpcode(ARM::t2Bcc);
3800     break;
3801   case ARM::t2Bcc:
3802     // If the conditional is AL or we're in an IT block, we really want t2B.
3803     if (Inst.getOperand(1).getImm() == ARMCC::AL || inITBlock())
3804       Inst.setOpcode(ARM::t2B);
3805     break;
3806   case ARM::tBcc:
3807     // If the conditional is AL, we really want tB.
3808     if (Inst.getOperand(1).getImm() == ARMCC::AL)
3809       Inst.setOpcode(ARM::tB);
3810     break;
3811   case ARM::tLDMIA: {
3812     // If the register list contains any high registers, or if the writeback
3813     // doesn't match what tLDMIA can do, we need to use the 32-bit encoding
3814     // instead if we're in Thumb2. Otherwise, this should have generated
3815     // an error in validateInstruction().
3816     unsigned Rn = Inst.getOperand(0).getReg();
3817     bool hasWritebackToken =
3818       (static_cast<ARMOperand*>(Operands[3])->isToken() &&
3819        static_cast<ARMOperand*>(Operands[3])->getToken() == "!");
3820     bool listContainsBase;
3821     if (checkLowRegisterList(Inst, 3, Rn, 0, listContainsBase) ||
3822         (!listContainsBase && !hasWritebackToken) ||
3823         (listContainsBase && hasWritebackToken)) {
3824       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
3825       assert (isThumbTwo());
3826       Inst.setOpcode(hasWritebackToken ? ARM::t2LDMIA_UPD : ARM::t2LDMIA);
3827       // If we're switching to the updating version, we need to insert
3828       // the writeback tied operand.
3829       if (hasWritebackToken)
3830         Inst.insert(Inst.begin(),
3831                     MCOperand::CreateReg(Inst.getOperand(0).getReg()));
3832     }
3833     break;
3834   }
3835   case ARM::tSTMIA_UPD: {
3836     // If the register list contains any high registers, we need to use
3837     // the 32-bit encoding instead if we're in Thumb2. Otherwise, this
3838     // should have generated an error in validateInstruction().
3839     unsigned Rn = Inst.getOperand(0).getReg();
3840     bool listContainsBase;
3841     if (checkLowRegisterList(Inst, 4, Rn, 0, listContainsBase)) {
3842       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
3843       assert (isThumbTwo());
3844       Inst.setOpcode(ARM::t2STMIA_UPD);
3845     }
3846     break;
3847   }
3848   case ARM::t2MOVi: {
3849     // If we can use the 16-bit encoding and the user didn't explicitly
3850     // request the 32-bit variant, transform it here.
3851     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
3852         Inst.getOperand(1).getImm() <= 255 &&
3853         ((!inITBlock() && Inst.getOperand(2).getImm() == ARMCC::AL &&
3854          Inst.getOperand(4).getReg() == ARM::CPSR) ||
3855         (inITBlock() && Inst.getOperand(4).getReg() == 0)) &&
3856         (!static_cast<ARMOperand*>(Operands[2])->isToken() ||
3857          static_cast<ARMOperand*>(Operands[2])->getToken() != ".w")) {
3858       // The operands aren't in the same order for tMOVi8...
3859       MCInst TmpInst;
3860       TmpInst.setOpcode(ARM::tMOVi8);
3861       TmpInst.addOperand(Inst.getOperand(0));
3862       TmpInst.addOperand(Inst.getOperand(4));
3863       TmpInst.addOperand(Inst.getOperand(1));
3864       TmpInst.addOperand(Inst.getOperand(2));
3865       TmpInst.addOperand(Inst.getOperand(3));
3866       Inst = TmpInst;
3867     }
3868     break;
3869   }
3870   case ARM::t2MOVr: {
3871     // If we can use the 16-bit encoding and the user didn't explicitly
3872     // request the 32-bit variant, transform it here.
3873     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
3874         isARMLowRegister(Inst.getOperand(1).getReg()) &&
3875         Inst.getOperand(2).getImm() == ARMCC::AL &&
3876         Inst.getOperand(4).getReg() == ARM::CPSR &&
3877         (!static_cast<ARMOperand*>(Operands[2])->isToken() ||
3878          static_cast<ARMOperand*>(Operands[2])->getToken() != ".w")) {
3879       // The operands aren't the same for tMOV[S]r... (no cc_out)
3880       MCInst TmpInst;
3881       TmpInst.setOpcode(Inst.getOperand(4).getReg() ? ARM::tMOVSr : ARM::tMOVr);
3882       TmpInst.addOperand(Inst.getOperand(0));
3883       TmpInst.addOperand(Inst.getOperand(1));
3884       TmpInst.addOperand(Inst.getOperand(2));
3885       TmpInst.addOperand(Inst.getOperand(3));
3886       Inst = TmpInst;
3887     }
3888     break;
3889   }
3890   case ARM::t2SXTH:
3891   case ARM::t2SXTB: {
3892     // If we can use the 16-bit encoding and the user didn't explicitly
3893     // request the 32-bit variant, transform it here.
3894     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
3895         isARMLowRegister(Inst.getOperand(1).getReg()) &&
3896         Inst.getOperand(2).getImm() == 0 &&
3897         (!static_cast<ARMOperand*>(Operands[2])->isToken() ||
3898          static_cast<ARMOperand*>(Operands[2])->getToken() != ".w")) {
3899       unsigned NewOpc = (Inst.getOpcode() == ARM::t2SXTH) ?
3900         ARM::tSXTH : ARM::tSXTB;
3901       // The operands aren't the same for thumb1 (no rotate operand).
3902       MCInst TmpInst;
3903       TmpInst.setOpcode(NewOpc);
3904       TmpInst.addOperand(Inst.getOperand(0));
3905       TmpInst.addOperand(Inst.getOperand(1));
3906       TmpInst.addOperand(Inst.getOperand(3));
3907       TmpInst.addOperand(Inst.getOperand(4));
3908       Inst = TmpInst;
3909     }
3910     break;
3911   }
3912   case ARM::t2IT: {
3913     // The mask bits for all but the first condition are represented as
3914     // the low bit of the condition code value implies 't'. We currently
3915     // always have 1 implies 't', so XOR toggle the bits if the low bit
3916     // of the condition code is zero. The encoding also expects the low
3917     // bit of the condition to be encoded as bit 4 of the mask operand,
3918     // so mask that in if needed
3919     MCOperand &MO = Inst.getOperand(1);
3920     unsigned Mask = MO.getImm();
3921     unsigned OrigMask = Mask;
3922     unsigned TZ = CountTrailingZeros_32(Mask);
3923     if ((Inst.getOperand(0).getImm() & 1) == 0) {
3924       assert(Mask && TZ <= 3 && "illegal IT mask value!");
3925       for (unsigned i = 3; i != TZ; --i)
3926         Mask ^= 1 << i;
3927     } else
3928       Mask |= 0x10;
3929     MO.setImm(Mask);
3930
3931     // Set up the IT block state according to the IT instruction we just
3932     // matched.
3933     assert(!inITBlock() && "nested IT blocks?!");
3934     ITState.Cond = ARMCC::CondCodes(Inst.getOperand(0).getImm());
3935     ITState.Mask = OrigMask; // Use the original mask, not the updated one.
3936     ITState.CurPosition = 0;
3937     ITState.FirstCond = true;
3938     break;
3939   }
3940   }
3941 }
3942
3943 unsigned ARMAsmParser::checkTargetMatchPredicate(MCInst &Inst) {
3944   // 16-bit thumb arithmetic instructions either require or preclude the 'S'
3945   // suffix depending on whether they're in an IT block or not.
3946   unsigned Opc = Inst.getOpcode();
3947   MCInstrDesc &MCID = getInstDesc(Opc);
3948   if (MCID.TSFlags & ARMII::ThumbArithFlagSetting) {
3949     assert(MCID.hasOptionalDef() &&
3950            "optionally flag setting instruction missing optional def operand");
3951     assert(MCID.NumOperands == Inst.getNumOperands() &&
3952            "operand count mismatch!");
3953     // Find the optional-def operand (cc_out).
3954     unsigned OpNo;
3955     for (OpNo = 0;
3956          !MCID.OpInfo[OpNo].isOptionalDef() && OpNo < MCID.NumOperands;
3957          ++OpNo)
3958       ;
3959     // If we're parsing Thumb1, reject it completely.
3960     if (isThumbOne() && Inst.getOperand(OpNo).getReg() != ARM::CPSR)
3961       return Match_MnemonicFail;
3962     // If we're parsing Thumb2, which form is legal depends on whether we're
3963     // in an IT block.
3964     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() != ARM::CPSR &&
3965         !inITBlock())
3966       return Match_RequiresITBlock;
3967     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() == ARM::CPSR &&
3968         inITBlock())
3969       return Match_RequiresNotITBlock;
3970   }
3971   // Some high-register supporting Thumb1 encodings only allow both registers
3972   // to be from r0-r7 when in Thumb2.
3973   else if (Opc == ARM::tADDhirr && isThumbOne() &&
3974            isARMLowRegister(Inst.getOperand(1).getReg()) &&
3975            isARMLowRegister(Inst.getOperand(2).getReg()))
3976     return Match_RequiresThumb2;
3977   // Others only require ARMv6 or later.
3978   else if (Opc == ARM::tMOVr && isThumbOne() && !hasV6Ops() &&
3979            isARMLowRegister(Inst.getOperand(0).getReg()) &&
3980            isARMLowRegister(Inst.getOperand(1).getReg()))
3981     return Match_RequiresV6;
3982   return Match_Success;
3983 }
3984
3985 bool ARMAsmParser::
3986 MatchAndEmitInstruction(SMLoc IDLoc,
3987                         SmallVectorImpl<MCParsedAsmOperand*> &Operands,
3988                         MCStreamer &Out) {
3989   MCInst Inst;
3990   unsigned ErrorInfo;
3991   unsigned MatchResult;
3992   MatchResult = MatchInstructionImpl(Operands, Inst, ErrorInfo);
3993   switch (MatchResult) {
3994   default: break;
3995   case Match_Success:
3996     // Context sensitive operand constraints aren't handled by the matcher,
3997     // so check them here.
3998     if (validateInstruction(Inst, Operands)) {
3999       // Still progress the IT block, otherwise one wrong condition causes
4000       // nasty cascading errors.
4001       forwardITPosition();
4002       return true;
4003     }
4004
4005     // Some instructions need post-processing to, for example, tweak which
4006     // encoding is selected.
4007     processInstruction(Inst, Operands);
4008
4009     // Only move forward at the very end so that everything in validate
4010     // and process gets a consistent answer about whether we're in an IT
4011     // block.
4012     forwardITPosition();
4013
4014     Out.EmitInstruction(Inst);
4015     return false;
4016   case Match_MissingFeature:
4017     Error(IDLoc, "instruction requires a CPU feature not currently enabled");
4018     return true;
4019   case Match_InvalidOperand: {
4020     SMLoc ErrorLoc = IDLoc;
4021     if (ErrorInfo != ~0U) {
4022       if (ErrorInfo >= Operands.size())
4023         return Error(IDLoc, "too few operands for instruction");
4024
4025       ErrorLoc = ((ARMOperand*)Operands[ErrorInfo])->getStartLoc();
4026       if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
4027     }
4028
4029     return Error(ErrorLoc, "invalid operand for instruction");
4030   }
4031   case Match_MnemonicFail:
4032     return Error(IDLoc, "invalid instruction");
4033   case Match_ConversionFail:
4034     // The converter function will have already emited a diagnostic.
4035     return true;
4036   case Match_RequiresNotITBlock:
4037     return Error(IDLoc, "flag setting instruction only valid outside IT block");
4038   case Match_RequiresITBlock:
4039     return Error(IDLoc, "instruction only valid inside IT block");
4040   case Match_RequiresV6:
4041     return Error(IDLoc, "instruction variant requires ARMv6 or later");
4042   case Match_RequiresThumb2:
4043     return Error(IDLoc, "instruction variant requires Thumb2");
4044   }
4045
4046   llvm_unreachable("Implement any new match types added!");
4047   return true;
4048 }
4049
4050 /// parseDirective parses the arm specific directives
4051 bool ARMAsmParser::ParseDirective(AsmToken DirectiveID) {
4052   StringRef IDVal = DirectiveID.getIdentifier();
4053   if (IDVal == ".word")
4054     return parseDirectiveWord(4, DirectiveID.getLoc());
4055   else if (IDVal == ".thumb")
4056     return parseDirectiveThumb(DirectiveID.getLoc());
4057   else if (IDVal == ".thumb_func")
4058     return parseDirectiveThumbFunc(DirectiveID.getLoc());
4059   else if (IDVal == ".code")
4060     return parseDirectiveCode(DirectiveID.getLoc());
4061   else if (IDVal == ".syntax")
4062     return parseDirectiveSyntax(DirectiveID.getLoc());
4063   return true;
4064 }
4065
4066 /// parseDirectiveWord
4067 ///  ::= .word [ expression (, expression)* ]
4068 bool ARMAsmParser::parseDirectiveWord(unsigned Size, SMLoc L) {
4069   if (getLexer().isNot(AsmToken::EndOfStatement)) {
4070     for (;;) {
4071       const MCExpr *Value;
4072       if (getParser().ParseExpression(Value))
4073         return true;
4074
4075       getParser().getStreamer().EmitValue(Value, Size, 0/*addrspace*/);
4076
4077       if (getLexer().is(AsmToken::EndOfStatement))
4078         break;
4079
4080       // FIXME: Improve diagnostic.
4081       if (getLexer().isNot(AsmToken::Comma))
4082         return Error(L, "unexpected token in directive");
4083       Parser.Lex();
4084     }
4085   }
4086
4087   Parser.Lex();
4088   return false;
4089 }
4090
4091 /// parseDirectiveThumb
4092 ///  ::= .thumb
4093 bool ARMAsmParser::parseDirectiveThumb(SMLoc L) {
4094   if (getLexer().isNot(AsmToken::EndOfStatement))
4095     return Error(L, "unexpected token in directive");
4096   Parser.Lex();
4097
4098   // TODO: set thumb mode
4099   // TODO: tell the MC streamer the mode
4100   // getParser().getStreamer().Emit???();
4101   return false;
4102 }
4103
4104 /// parseDirectiveThumbFunc
4105 ///  ::= .thumbfunc symbol_name
4106 bool ARMAsmParser::parseDirectiveThumbFunc(SMLoc L) {
4107   const MCAsmInfo &MAI = getParser().getStreamer().getContext().getAsmInfo();
4108   bool isMachO = MAI.hasSubsectionsViaSymbols();
4109   StringRef Name;
4110
4111   // Darwin asm has function name after .thumb_func direction
4112   // ELF doesn't
4113   if (isMachO) {
4114     const AsmToken &Tok = Parser.getTok();
4115     if (Tok.isNot(AsmToken::Identifier) && Tok.isNot(AsmToken::String))
4116       return Error(L, "unexpected token in .thumb_func directive");
4117     Name = Tok.getString();
4118     Parser.Lex(); // Consume the identifier token.
4119   }
4120
4121   if (getLexer().isNot(AsmToken::EndOfStatement))
4122     return Error(L, "unexpected token in directive");
4123   Parser.Lex();
4124
4125   // FIXME: assuming function name will be the line following .thumb_func
4126   if (!isMachO) {
4127     Name = Parser.getTok().getString();
4128   }
4129
4130   // Mark symbol as a thumb symbol.
4131   MCSymbol *Func = getParser().getContext().GetOrCreateSymbol(Name);
4132   getParser().getStreamer().EmitThumbFunc(Func);
4133   return false;
4134 }
4135
4136 /// parseDirectiveSyntax
4137 ///  ::= .syntax unified | divided
4138 bool ARMAsmParser::parseDirectiveSyntax(SMLoc L) {
4139   const AsmToken &Tok = Parser.getTok();
4140   if (Tok.isNot(AsmToken::Identifier))
4141     return Error(L, "unexpected token in .syntax directive");
4142   StringRef Mode = Tok.getString();
4143   if (Mode == "unified" || Mode == "UNIFIED")
4144     Parser.Lex();
4145   else if (Mode == "divided" || Mode == "DIVIDED")
4146     return Error(L, "'.syntax divided' arm asssembly not supported");
4147   else
4148     return Error(L, "unrecognized syntax mode in .syntax directive");
4149
4150   if (getLexer().isNot(AsmToken::EndOfStatement))
4151     return Error(Parser.getTok().getLoc(), "unexpected token in directive");
4152   Parser.Lex();
4153
4154   // TODO tell the MC streamer the mode
4155   // getParser().getStreamer().Emit???();
4156   return false;
4157 }
4158
4159 /// parseDirectiveCode
4160 ///  ::= .code 16 | 32
4161 bool ARMAsmParser::parseDirectiveCode(SMLoc L) {
4162   const AsmToken &Tok = Parser.getTok();
4163   if (Tok.isNot(AsmToken::Integer))
4164     return Error(L, "unexpected token in .code directive");
4165   int64_t Val = Parser.getTok().getIntVal();
4166   if (Val == 16)
4167     Parser.Lex();
4168   else if (Val == 32)
4169     Parser.Lex();
4170   else
4171     return Error(L, "invalid operand to .code directive");
4172
4173   if (getLexer().isNot(AsmToken::EndOfStatement))
4174     return Error(Parser.getTok().getLoc(), "unexpected token in directive");
4175   Parser.Lex();
4176
4177   if (Val == 16) {
4178     if (!isThumb())
4179       SwitchMode();
4180     getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
4181   } else {
4182     if (isThumb())
4183       SwitchMode();
4184     getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
4185   }
4186
4187   return false;
4188 }
4189
4190 extern "C" void LLVMInitializeARMAsmLexer();
4191
4192 /// Force static initialization.
4193 extern "C" void LLVMInitializeARMAsmParser() {
4194   RegisterMCAsmParser<ARMAsmParser> X(TheARMTarget);
4195   RegisterMCAsmParser<ARMAsmParser> Y(TheThumbTarget);
4196   LLVMInitializeARMAsmLexer();
4197 }
4198
4199 #define GET_REGISTER_MATCHER
4200 #define GET_MATCHER_IMPLEMENTATION
4201 #include "ARMGenAsmMatcher.inc"