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