Introduce CPUStringIsValid() into MCSubtargetInfo and use it for ARM .cpu parsing.
[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 "ARMFPUName.h"
11 #include "ARMFeatures.h"
12 #include "MCTargetDesc/ARMAddressingModes.h"
13 #include "MCTargetDesc/ARMArchName.h"
14 #include "MCTargetDesc/ARMBaseInfo.h"
15 #include "MCTargetDesc/ARMMCExpr.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/ADT/StringSwitch.h"
20 #include "llvm/ADT/Twine.h"
21 #include "llvm/MC/MCAsmInfo.h"
22 #include "llvm/MC/MCAssembler.h"
23 #include "llvm/MC/MCContext.h"
24 #include "llvm/MC/MCDisassembler.h"
25 #include "llvm/MC/MCELFStreamer.h"
26 #include "llvm/MC/MCExpr.h"
27 #include "llvm/MC/MCInst.h"
28 #include "llvm/MC/MCInstrDesc.h"
29 #include "llvm/MC/MCInstrInfo.h"
30 #include "llvm/MC/MCObjectFileInfo.h"
31 #include "llvm/MC/MCParser/MCAsmLexer.h"
32 #include "llvm/MC/MCParser/MCAsmParser.h"
33 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
34 #include "llvm/MC/MCRegisterInfo.h"
35 #include "llvm/MC/MCSection.h"
36 #include "llvm/MC/MCStreamer.h"
37 #include "llvm/MC/MCSubtargetInfo.h"
38 #include "llvm/MC/MCSymbol.h"
39 #include "llvm/MC/MCTargetAsmParser.h"
40 #include "llvm/Support/ARMBuildAttributes.h"
41 #include "llvm/Support/ARMEHABI.h"
42 #include "llvm/Support/COFF.h"
43 #include "llvm/Support/Debug.h"
44 #include "llvm/Support/ELF.h"
45 #include "llvm/Support/MathExtras.h"
46 #include "llvm/Support/SourceMgr.h"
47 #include "llvm/Support/TargetRegistry.h"
48 #include "llvm/Support/raw_ostream.h"
49
50 using namespace llvm;
51
52 namespace {
53
54 class ARMOperand;
55
56 enum VectorLaneTy { NoLanes, AllLanes, IndexedLane };
57
58 class UnwindContext {
59   MCAsmParser &Parser;
60
61   typedef SmallVector<SMLoc, 4> Locs;
62
63   Locs FnStartLocs;
64   Locs CantUnwindLocs;
65   Locs PersonalityLocs;
66   Locs PersonalityIndexLocs;
67   Locs HandlerDataLocs;
68   int FPReg;
69
70 public:
71   UnwindContext(MCAsmParser &P) : Parser(P), FPReg(ARM::SP) {}
72
73   bool hasFnStart() const { return !FnStartLocs.empty(); }
74   bool cantUnwind() const { return !CantUnwindLocs.empty(); }
75   bool hasHandlerData() const { return !HandlerDataLocs.empty(); }
76   bool hasPersonality() const {
77     return !(PersonalityLocs.empty() && PersonalityIndexLocs.empty());
78   }
79
80   void recordFnStart(SMLoc L) { FnStartLocs.push_back(L); }
81   void recordCantUnwind(SMLoc L) { CantUnwindLocs.push_back(L); }
82   void recordPersonality(SMLoc L) { PersonalityLocs.push_back(L); }
83   void recordHandlerData(SMLoc L) { HandlerDataLocs.push_back(L); }
84   void recordPersonalityIndex(SMLoc L) { PersonalityIndexLocs.push_back(L); }
85
86   void saveFPReg(int Reg) { FPReg = Reg; }
87   int getFPReg() const { return FPReg; }
88
89   void emitFnStartLocNotes() const {
90     for (Locs::const_iterator FI = FnStartLocs.begin(), FE = FnStartLocs.end();
91          FI != FE; ++FI)
92       Parser.Note(*FI, ".fnstart was specified here");
93   }
94   void emitCantUnwindLocNotes() const {
95     for (Locs::const_iterator UI = CantUnwindLocs.begin(),
96                               UE = CantUnwindLocs.end(); UI != UE; ++UI)
97       Parser.Note(*UI, ".cantunwind was specified here");
98   }
99   void emitHandlerDataLocNotes() const {
100     for (Locs::const_iterator HI = HandlerDataLocs.begin(),
101                               HE = HandlerDataLocs.end(); HI != HE; ++HI)
102       Parser.Note(*HI, ".handlerdata was specified here");
103   }
104   void emitPersonalityLocNotes() const {
105     for (Locs::const_iterator PI = PersonalityLocs.begin(),
106                               PE = PersonalityLocs.end(),
107                               PII = PersonalityIndexLocs.begin(),
108                               PIE = PersonalityIndexLocs.end();
109          PI != PE || PII != PIE;) {
110       if (PI != PE && (PII == PIE || PI->getPointer() < PII->getPointer()))
111         Parser.Note(*PI++, ".personality was specified here");
112       else if (PII != PIE && (PI == PE || PII->getPointer() < PI->getPointer()))
113         Parser.Note(*PII++, ".personalityindex was specified here");
114       else
115         llvm_unreachable(".personality and .personalityindex cannot be "
116                          "at the same location");
117     }
118   }
119
120   void reset() {
121     FnStartLocs = Locs();
122     CantUnwindLocs = Locs();
123     PersonalityLocs = Locs();
124     HandlerDataLocs = Locs();
125     PersonalityIndexLocs = Locs();
126     FPReg = ARM::SP;
127   }
128 };
129
130 class ARMAsmParser : public MCTargetAsmParser {
131   MCSubtargetInfo &STI;
132   const MCInstrInfo &MII;
133   const MCRegisterInfo *MRI;
134   UnwindContext UC;
135
136   ARMTargetStreamer &getTargetStreamer() {
137     assert(getParser().getStreamer().getTargetStreamer() &&
138            "do not have a target streamer");
139     MCTargetStreamer &TS = *getParser().getStreamer().getTargetStreamer();
140     return static_cast<ARMTargetStreamer &>(TS);
141   }
142
143   // Map of register aliases registers via the .req directive.
144   StringMap<unsigned> RegisterReqs;
145
146   bool NextSymbolIsThumb;
147
148   struct {
149     ARMCC::CondCodes Cond;    // Condition for IT block.
150     unsigned Mask:4;          // Condition mask for instructions.
151                               // Starting at first 1 (from lsb).
152                               //   '1'  condition as indicated in IT.
153                               //   '0'  inverse of condition (else).
154                               // Count of instructions in IT block is
155                               // 4 - trailingzeroes(mask)
156
157     bool FirstCond;           // Explicit flag for when we're parsing the
158                               // First instruction in the IT block. It's
159                               // implied in the mask, so needs special
160                               // handling.
161
162     unsigned CurPosition;     // Current position in parsing of IT
163                               // block. In range [0,3]. Initialized
164                               // according to count of instructions in block.
165                               // ~0U if no active IT block.
166   } ITState;
167   bool inITBlock() { return ITState.CurPosition != ~0U;}
168   void forwardITPosition() {
169     if (!inITBlock()) return;
170     // Move to the next instruction in the IT block, if there is one. If not,
171     // mark the block as done.
172     unsigned TZ = countTrailingZeros(ITState.Mask);
173     if (++ITState.CurPosition == 5 - TZ)
174       ITState.CurPosition = ~0U; // Done with the IT block after this.
175   }
176
177   void Note(SMLoc L, const Twine &Msg, ArrayRef<SMRange> Ranges = None) {
178     return getParser().Note(L, Msg, Ranges);
179   }
180   bool Warning(SMLoc L, const Twine &Msg,
181                ArrayRef<SMRange> Ranges = None) {
182     return getParser().Warning(L, Msg, Ranges);
183   }
184   bool Error(SMLoc L, const Twine &Msg,
185              ArrayRef<SMRange> Ranges = None) {
186     return getParser().Error(L, Msg, Ranges);
187   }
188
189   int tryParseRegister();
190   bool tryParseRegisterWithWriteBack(OperandVector &);
191   int tryParseShiftRegister(OperandVector &);
192   bool parseRegisterList(OperandVector &);
193   bool parseMemory(OperandVector &);
194   bool parseOperand(OperandVector &, StringRef Mnemonic);
195   bool parsePrefix(ARMMCExpr::VariantKind &RefKind);
196   bool parseMemRegOffsetShift(ARM_AM::ShiftOpc &ShiftType,
197                               unsigned &ShiftAmount);
198   bool parseLiteralValues(unsigned Size, SMLoc L);
199   bool parseDirectiveThumb(SMLoc L);
200   bool parseDirectiveARM(SMLoc L);
201   bool parseDirectiveThumbFunc(SMLoc L);
202   bool parseDirectiveCode(SMLoc L);
203   bool parseDirectiveSyntax(SMLoc L);
204   bool parseDirectiveReq(StringRef Name, SMLoc L);
205   bool parseDirectiveUnreq(SMLoc L);
206   bool parseDirectiveArch(SMLoc L);
207   bool parseDirectiveEabiAttr(SMLoc L);
208   bool parseDirectiveCPU(SMLoc L);
209   bool parseDirectiveFPU(SMLoc L);
210   bool parseDirectiveFnStart(SMLoc L);
211   bool parseDirectiveFnEnd(SMLoc L);
212   bool parseDirectiveCantUnwind(SMLoc L);
213   bool parseDirectivePersonality(SMLoc L);
214   bool parseDirectiveHandlerData(SMLoc L);
215   bool parseDirectiveSetFP(SMLoc L);
216   bool parseDirectivePad(SMLoc L);
217   bool parseDirectiveRegSave(SMLoc L, bool IsVector);
218   bool parseDirectiveInst(SMLoc L, char Suffix = '\0');
219   bool parseDirectiveLtorg(SMLoc L);
220   bool parseDirectiveEven(SMLoc L);
221   bool parseDirectivePersonalityIndex(SMLoc L);
222   bool parseDirectiveUnwindRaw(SMLoc L);
223   bool parseDirectiveTLSDescSeq(SMLoc L);
224   bool parseDirectiveMovSP(SMLoc L);
225   bool parseDirectiveObjectArch(SMLoc L);
226   bool parseDirectiveArchExtension(SMLoc L);
227   bool parseDirectiveAlign(SMLoc L);
228   bool parseDirectiveThumbSet(SMLoc L);
229
230   StringRef splitMnemonic(StringRef Mnemonic, unsigned &PredicationCode,
231                           bool &CarrySetting, unsigned &ProcessorIMod,
232                           StringRef &ITMask);
233   void getMnemonicAcceptInfo(StringRef Mnemonic, StringRef FullInst,
234                              bool &CanAcceptCarrySet,
235                              bool &CanAcceptPredicationCode);
236
237   bool isThumb() const {
238     // FIXME: Can tablegen auto-generate this?
239     return (STI.getFeatureBits() & ARM::ModeThumb) != 0;
240   }
241   bool isThumbOne() const {
242     return isThumb() && (STI.getFeatureBits() & ARM::FeatureThumb2) == 0;
243   }
244   bool isThumbTwo() const {
245     return isThumb() && (STI.getFeatureBits() & ARM::FeatureThumb2);
246   }
247   bool hasThumb() const {
248     return STI.getFeatureBits() & ARM::HasV4TOps;
249   }
250   bool hasV6Ops() const {
251     return STI.getFeatureBits() & ARM::HasV6Ops;
252   }
253   bool hasV6MOps() const {
254     return STI.getFeatureBits() & ARM::HasV6MOps;
255   }
256   bool hasV7Ops() const {
257     return STI.getFeatureBits() & ARM::HasV7Ops;
258   }
259   bool hasV8Ops() const {
260     return STI.getFeatureBits() & ARM::HasV8Ops;
261   }
262   bool hasARM() const {
263     return !(STI.getFeatureBits() & ARM::FeatureNoARM);
264   }
265   bool hasThumb2DSP() const {
266     return STI.getFeatureBits() & ARM::FeatureDSPThumb2;
267   }
268   bool hasD16() const {
269     return STI.getFeatureBits() & ARM::FeatureD16;
270   }
271
272   void SwitchMode() {
273     uint64_t FB = ComputeAvailableFeatures(STI.ToggleFeature(ARM::ModeThumb));
274     setAvailableFeatures(FB);
275   }
276   bool isMClass() const {
277     return STI.getFeatureBits() & ARM::FeatureMClass;
278   }
279
280   /// @name Auto-generated Match Functions
281   /// {
282
283 #define GET_ASSEMBLER_HEADER
284 #include "ARMGenAsmMatcher.inc"
285
286   /// }
287
288   OperandMatchResultTy parseITCondCode(OperandVector &);
289   OperandMatchResultTy parseCoprocNumOperand(OperandVector &);
290   OperandMatchResultTy parseCoprocRegOperand(OperandVector &);
291   OperandMatchResultTy parseCoprocOptionOperand(OperandVector &);
292   OperandMatchResultTy parseMemBarrierOptOperand(OperandVector &);
293   OperandMatchResultTy parseInstSyncBarrierOptOperand(OperandVector &);
294   OperandMatchResultTy parseProcIFlagsOperand(OperandVector &);
295   OperandMatchResultTy parseMSRMaskOperand(OperandVector &);
296   OperandMatchResultTy parseBankedRegOperand(OperandVector &);
297   OperandMatchResultTy parsePKHImm(OperandVector &O, StringRef Op, int Low,
298                                    int High);
299   OperandMatchResultTy parsePKHLSLImm(OperandVector &O) {
300     return parsePKHImm(O, "lsl", 0, 31);
301   }
302   OperandMatchResultTy parsePKHASRImm(OperandVector &O) {
303     return parsePKHImm(O, "asr", 1, 32);
304   }
305   OperandMatchResultTy parseSetEndImm(OperandVector &);
306   OperandMatchResultTy parseShifterImm(OperandVector &);
307   OperandMatchResultTy parseRotImm(OperandVector &);
308   OperandMatchResultTy parseModImm(OperandVector &);
309   OperandMatchResultTy parseBitfield(OperandVector &);
310   OperandMatchResultTy parsePostIdxReg(OperandVector &);
311   OperandMatchResultTy parseAM3Offset(OperandVector &);
312   OperandMatchResultTy parseFPImm(OperandVector &);
313   OperandMatchResultTy parseVectorList(OperandVector &);
314   OperandMatchResultTy parseVectorLane(VectorLaneTy &LaneKind, unsigned &Index,
315                                        SMLoc &EndLoc);
316
317   // Asm Match Converter Methods
318   void cvtThumbMultiply(MCInst &Inst, const OperandVector &);
319   void cvtThumbBranches(MCInst &Inst, const OperandVector &);
320
321   bool validateInstruction(MCInst &Inst, const OperandVector &Ops);
322   bool processInstruction(MCInst &Inst, const OperandVector &Ops, MCStreamer &Out);
323   bool shouldOmitCCOutOperand(StringRef Mnemonic, OperandVector &Operands);
324   bool shouldOmitPredicateOperand(StringRef Mnemonic, OperandVector &Operands);
325
326 public:
327   enum ARMMatchResultTy {
328     Match_RequiresITBlock = FIRST_TARGET_MATCH_RESULT_TY,
329     Match_RequiresNotITBlock,
330     Match_RequiresV6,
331     Match_RequiresThumb2,
332 #define GET_OPERAND_DIAGNOSTIC_TYPES
333 #include "ARMGenAsmMatcher.inc"
334
335   };
336
337   ARMAsmParser(MCSubtargetInfo & _STI, MCAsmParser & _Parser,
338                const MCInstrInfo &MII, const MCTargetOptions &Options)
339       : MCTargetAsmParser(), STI(_STI), MII(MII), UC(_Parser) {
340     MCAsmParserExtension::Initialize(_Parser);
341
342     // Cache the MCRegisterInfo.
343     MRI = getContext().getRegisterInfo();
344
345     // Initialize the set of available features.
346     setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
347
348     // Not in an ITBlock to start with.
349     ITState.CurPosition = ~0U;
350
351     NextSymbolIsThumb = false;
352   }
353
354   // Implementation of the MCTargetAsmParser interface:
355   bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc) override;
356   bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
357                         SMLoc NameLoc, OperandVector &Operands) override;
358   bool ParseDirective(AsmToken DirectiveID) override;
359
360   unsigned validateTargetOperandClass(MCParsedAsmOperand &Op,
361                                       unsigned Kind) override;
362   unsigned checkTargetMatchPredicate(MCInst &Inst) override;
363
364   bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
365                                OperandVector &Operands, MCStreamer &Out,
366                                uint64_t &ErrorInfo,
367                                bool MatchingInlineAsm) override;
368   void onLabelParsed(MCSymbol *Symbol) override;
369 };
370 } // end anonymous namespace
371
372 namespace {
373
374 /// ARMOperand - Instances of this class represent a parsed ARM machine
375 /// operand.
376 class ARMOperand : public MCParsedAsmOperand {
377   enum KindTy {
378     k_CondCode,
379     k_CCOut,
380     k_ITCondMask,
381     k_CoprocNum,
382     k_CoprocReg,
383     k_CoprocOption,
384     k_Immediate,
385     k_MemBarrierOpt,
386     k_InstSyncBarrierOpt,
387     k_Memory,
388     k_PostIndexRegister,
389     k_MSRMask,
390     k_BankedReg,
391     k_ProcIFlags,
392     k_VectorIndex,
393     k_Register,
394     k_RegisterList,
395     k_DPRRegisterList,
396     k_SPRRegisterList,
397     k_VectorList,
398     k_VectorListAllLanes,
399     k_VectorListIndexed,
400     k_ShiftedRegister,
401     k_ShiftedImmediate,
402     k_ShifterImmediate,
403     k_RotateImmediate,
404     k_ModifiedImmediate,
405     k_BitfieldDescriptor,
406     k_Token
407   } Kind;
408
409   SMLoc StartLoc, EndLoc, AlignmentLoc;
410   SmallVector<unsigned, 8> Registers;
411
412   struct CCOp {
413     ARMCC::CondCodes Val;
414   };
415
416   struct CopOp {
417     unsigned Val;
418   };
419
420   struct CoprocOptionOp {
421     unsigned Val;
422   };
423
424   struct ITMaskOp {
425     unsigned Mask:4;
426   };
427
428   struct MBOptOp {
429     ARM_MB::MemBOpt Val;
430   };
431
432   struct ISBOptOp {
433     ARM_ISB::InstSyncBOpt Val;
434   };
435
436   struct IFlagsOp {
437     ARM_PROC::IFlags Val;
438   };
439
440   struct MMaskOp {
441     unsigned Val;
442   };
443
444   struct BankedRegOp {
445     unsigned Val;
446   };
447
448   struct TokOp {
449     const char *Data;
450     unsigned Length;
451   };
452
453   struct RegOp {
454     unsigned RegNum;
455   };
456
457   // A vector register list is a sequential list of 1 to 4 registers.
458   struct VectorListOp {
459     unsigned RegNum;
460     unsigned Count;
461     unsigned LaneIndex;
462     bool isDoubleSpaced;
463   };
464
465   struct VectorIndexOp {
466     unsigned Val;
467   };
468
469   struct ImmOp {
470     const MCExpr *Val;
471   };
472
473   /// Combined record for all forms of ARM address expressions.
474   struct MemoryOp {
475     unsigned BaseRegNum;
476     // Offset is in OffsetReg or OffsetImm. If both are zero, no offset
477     // was specified.
478     const MCConstantExpr *OffsetImm;  // Offset immediate value
479     unsigned OffsetRegNum;    // Offset register num, when OffsetImm == NULL
480     ARM_AM::ShiftOpc ShiftType; // Shift type for OffsetReg
481     unsigned ShiftImm;        // shift for OffsetReg.
482     unsigned Alignment;       // 0 = no alignment specified
483     // n = alignment in bytes (2, 4, 8, 16, or 32)
484     unsigned isNegative : 1;  // Negated OffsetReg? (~'U' bit)
485   };
486
487   struct PostIdxRegOp {
488     unsigned RegNum;
489     bool isAdd;
490     ARM_AM::ShiftOpc ShiftTy;
491     unsigned ShiftImm;
492   };
493
494   struct ShifterImmOp {
495     bool isASR;
496     unsigned Imm;
497   };
498
499   struct RegShiftedRegOp {
500     ARM_AM::ShiftOpc ShiftTy;
501     unsigned SrcReg;
502     unsigned ShiftReg;
503     unsigned ShiftImm;
504   };
505
506   struct RegShiftedImmOp {
507     ARM_AM::ShiftOpc ShiftTy;
508     unsigned SrcReg;
509     unsigned ShiftImm;
510   };
511
512   struct RotImmOp {
513     unsigned Imm;
514   };
515
516   struct ModImmOp {
517     unsigned Bits;
518     unsigned Rot;
519   };
520
521   struct BitfieldOp {
522     unsigned LSB;
523     unsigned Width;
524   };
525
526   union {
527     struct CCOp CC;
528     struct CopOp Cop;
529     struct CoprocOptionOp CoprocOption;
530     struct MBOptOp MBOpt;
531     struct ISBOptOp ISBOpt;
532     struct ITMaskOp ITMask;
533     struct IFlagsOp IFlags;
534     struct MMaskOp MMask;
535     struct BankedRegOp BankedReg;
536     struct TokOp Tok;
537     struct RegOp Reg;
538     struct VectorListOp VectorList;
539     struct VectorIndexOp VectorIndex;
540     struct ImmOp Imm;
541     struct MemoryOp Memory;
542     struct PostIdxRegOp PostIdxReg;
543     struct ShifterImmOp ShifterImm;
544     struct RegShiftedRegOp RegShiftedReg;
545     struct RegShiftedImmOp RegShiftedImm;
546     struct RotImmOp RotImm;
547     struct ModImmOp ModImm;
548     struct BitfieldOp Bitfield;
549   };
550
551 public:
552   ARMOperand(KindTy K) : MCParsedAsmOperand(), Kind(K) {}
553   ARMOperand(const ARMOperand &o) : MCParsedAsmOperand() {
554     Kind = o.Kind;
555     StartLoc = o.StartLoc;
556     EndLoc = o.EndLoc;
557     switch (Kind) {
558     case k_CondCode:
559       CC = o.CC;
560       break;
561     case k_ITCondMask:
562       ITMask = o.ITMask;
563       break;
564     case k_Token:
565       Tok = o.Tok;
566       break;
567     case k_CCOut:
568     case k_Register:
569       Reg = o.Reg;
570       break;
571     case k_RegisterList:
572     case k_DPRRegisterList:
573     case k_SPRRegisterList:
574       Registers = o.Registers;
575       break;
576     case k_VectorList:
577     case k_VectorListAllLanes:
578     case k_VectorListIndexed:
579       VectorList = o.VectorList;
580       break;
581     case k_CoprocNum:
582     case k_CoprocReg:
583       Cop = o.Cop;
584       break;
585     case k_CoprocOption:
586       CoprocOption = o.CoprocOption;
587       break;
588     case k_Immediate:
589       Imm = o.Imm;
590       break;
591     case k_MemBarrierOpt:
592       MBOpt = o.MBOpt;
593       break;
594     case k_InstSyncBarrierOpt:
595       ISBOpt = o.ISBOpt;
596     case k_Memory:
597       Memory = o.Memory;
598       break;
599     case k_PostIndexRegister:
600       PostIdxReg = o.PostIdxReg;
601       break;
602     case k_MSRMask:
603       MMask = o.MMask;
604       break;
605     case k_BankedReg:
606       BankedReg = o.BankedReg;
607       break;
608     case k_ProcIFlags:
609       IFlags = o.IFlags;
610       break;
611     case k_ShifterImmediate:
612       ShifterImm = o.ShifterImm;
613       break;
614     case k_ShiftedRegister:
615       RegShiftedReg = o.RegShiftedReg;
616       break;
617     case k_ShiftedImmediate:
618       RegShiftedImm = o.RegShiftedImm;
619       break;
620     case k_RotateImmediate:
621       RotImm = o.RotImm;
622       break;
623     case k_ModifiedImmediate:
624       ModImm = o.ModImm;
625       break;
626     case k_BitfieldDescriptor:
627       Bitfield = o.Bitfield;
628       break;
629     case k_VectorIndex:
630       VectorIndex = o.VectorIndex;
631       break;
632     }
633   }
634
635   /// getStartLoc - Get the location of the first token of this operand.
636   SMLoc getStartLoc() const override { return StartLoc; }
637   /// getEndLoc - Get the location of the last token of this operand.
638   SMLoc getEndLoc() const override { return EndLoc; }
639   /// getLocRange - Get the range between the first and last token of this
640   /// operand.
641   SMRange getLocRange() const { return SMRange(StartLoc, EndLoc); }
642
643   /// getAlignmentLoc - Get the location of the Alignment token of this operand.
644   SMLoc getAlignmentLoc() const {
645     assert(Kind == k_Memory && "Invalid access!");
646     return AlignmentLoc;
647   }
648
649   ARMCC::CondCodes getCondCode() const {
650     assert(Kind == k_CondCode && "Invalid access!");
651     return CC.Val;
652   }
653
654   unsigned getCoproc() const {
655     assert((Kind == k_CoprocNum || Kind == k_CoprocReg) && "Invalid access!");
656     return Cop.Val;
657   }
658
659   StringRef getToken() const {
660     assert(Kind == k_Token && "Invalid access!");
661     return StringRef(Tok.Data, Tok.Length);
662   }
663
664   unsigned getReg() const override {
665     assert((Kind == k_Register || Kind == k_CCOut) && "Invalid access!");
666     return Reg.RegNum;
667   }
668
669   const SmallVectorImpl<unsigned> &getRegList() const {
670     assert((Kind == k_RegisterList || Kind == k_DPRRegisterList ||
671             Kind == k_SPRRegisterList) && "Invalid access!");
672     return Registers;
673   }
674
675   const MCExpr *getImm() const {
676     assert(isImm() && "Invalid access!");
677     return Imm.Val;
678   }
679
680   unsigned getVectorIndex() const {
681     assert(Kind == k_VectorIndex && "Invalid access!");
682     return VectorIndex.Val;
683   }
684
685   ARM_MB::MemBOpt getMemBarrierOpt() const {
686     assert(Kind == k_MemBarrierOpt && "Invalid access!");
687     return MBOpt.Val;
688   }
689
690   ARM_ISB::InstSyncBOpt getInstSyncBarrierOpt() const {
691     assert(Kind == k_InstSyncBarrierOpt && "Invalid access!");
692     return ISBOpt.Val;
693   }
694
695   ARM_PROC::IFlags getProcIFlags() const {
696     assert(Kind == k_ProcIFlags && "Invalid access!");
697     return IFlags.Val;
698   }
699
700   unsigned getMSRMask() const {
701     assert(Kind == k_MSRMask && "Invalid access!");
702     return MMask.Val;
703   }
704
705   unsigned getBankedReg() const {
706     assert(Kind == k_BankedReg && "Invalid access!");
707     return BankedReg.Val;
708   }
709
710   bool isCoprocNum() const { return Kind == k_CoprocNum; }
711   bool isCoprocReg() const { return Kind == k_CoprocReg; }
712   bool isCoprocOption() const { return Kind == k_CoprocOption; }
713   bool isCondCode() const { return Kind == k_CondCode; }
714   bool isCCOut() const { return Kind == k_CCOut; }
715   bool isITMask() const { return Kind == k_ITCondMask; }
716   bool isITCondCode() const { return Kind == k_CondCode; }
717   bool isImm() const override { return Kind == k_Immediate; }
718   // checks whether this operand is an unsigned offset which fits is a field
719   // of specified width and scaled by a specific number of bits
720   template<unsigned width, unsigned scale>
721   bool isUnsignedOffset() const {
722     if (!isImm()) return false;
723     if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
724     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val)) {
725       int64_t Val = CE->getValue();
726       int64_t Align = 1LL << scale;
727       int64_t Max = Align * ((1LL << width) - 1);
728       return ((Val % Align) == 0) && (Val >= 0) && (Val <= Max);
729     }
730     return false;
731   }
732   // checks whether this operand is an signed offset which fits is a field
733   // of specified width and scaled by a specific number of bits
734   template<unsigned width, unsigned scale>
735   bool isSignedOffset() const {
736     if (!isImm()) return false;
737     if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
738     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val)) {
739       int64_t Val = CE->getValue();
740       int64_t Align = 1LL << scale;
741       int64_t Max = Align * ((1LL << (width-1)) - 1);
742       int64_t Min = -Align * (1LL << (width-1));
743       return ((Val % Align) == 0) && (Val >= Min) && (Val <= Max);
744     }
745     return false;
746   }
747
748   // checks whether this operand is a memory operand computed as an offset
749   // applied to PC. the offset may have 8 bits of magnitude and is represented
750   // with two bits of shift. textually it may be either [pc, #imm], #imm or 
751   // relocable expression...
752   bool isThumbMemPC() const {
753     int64_t Val = 0;
754     if (isImm()) {
755       if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
756       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val);
757       if (!CE) return false;
758       Val = CE->getValue();
759     }
760     else if (isMem()) {
761       if(!Memory.OffsetImm || Memory.OffsetRegNum) return false;
762       if(Memory.BaseRegNum != ARM::PC) return false;
763       Val = Memory.OffsetImm->getValue();
764     }
765     else return false;
766     return ((Val % 4) == 0) && (Val >= 0) && (Val <= 1020);
767   }
768   bool isFPImm() const {
769     if (!isImm()) return false;
770     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
771     if (!CE) return false;
772     int Val = ARM_AM::getFP32Imm(APInt(32, CE->getValue()));
773     return Val != -1;
774   }
775   bool isFBits16() const {
776     if (!isImm()) return false;
777     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
778     if (!CE) return false;
779     int64_t Value = CE->getValue();
780     return Value >= 0 && Value <= 16;
781   }
782   bool isFBits32() const {
783     if (!isImm()) return false;
784     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
785     if (!CE) return false;
786     int64_t Value = CE->getValue();
787     return Value >= 1 && Value <= 32;
788   }
789   bool isImm8s4() const {
790     if (!isImm()) return false;
791     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
792     if (!CE) return false;
793     int64_t Value = CE->getValue();
794     return ((Value & 3) == 0) && Value >= -1020 && Value <= 1020;
795   }
796   bool isImm0_1020s4() const {
797     if (!isImm()) return false;
798     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
799     if (!CE) return false;
800     int64_t Value = CE->getValue();
801     return ((Value & 3) == 0) && Value >= 0 && Value <= 1020;
802   }
803   bool isImm0_508s4() const {
804     if (!isImm()) return false;
805     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
806     if (!CE) return false;
807     int64_t Value = CE->getValue();
808     return ((Value & 3) == 0) && Value >= 0 && Value <= 508;
809   }
810   bool isImm0_508s4Neg() const {
811     if (!isImm()) return false;
812     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
813     if (!CE) return false;
814     int64_t Value = -CE->getValue();
815     // explicitly exclude zero. we want that to use the normal 0_508 version.
816     return ((Value & 3) == 0) && Value > 0 && Value <= 508;
817   }
818   bool isImm0_239() const {
819     if (!isImm()) return false;
820     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
821     if (!CE) return false;
822     int64_t Value = CE->getValue();
823     return Value >= 0 && Value < 240;
824   }
825   bool isImm0_255() const {
826     if (!isImm()) return false;
827     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
828     if (!CE) return false;
829     int64_t Value = CE->getValue();
830     return Value >= 0 && Value < 256;
831   }
832   bool isImm0_4095() const {
833     if (!isImm()) return false;
834     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
835     if (!CE) return false;
836     int64_t Value = CE->getValue();
837     return Value >= 0 && Value < 4096;
838   }
839   bool isImm0_4095Neg() const {
840     if (!isImm()) return false;
841     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
842     if (!CE) return false;
843     int64_t Value = -CE->getValue();
844     return Value > 0 && Value < 4096;
845   }
846   bool isImm0_1() const {
847     if (!isImm()) return false;
848     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
849     if (!CE) return false;
850     int64_t Value = CE->getValue();
851     return Value >= 0 && Value < 2;
852   }
853   bool isImm0_3() const {
854     if (!isImm()) return false;
855     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
856     if (!CE) return false;
857     int64_t Value = CE->getValue();
858     return Value >= 0 && Value < 4;
859   }
860   bool isImm0_7() const {
861     if (!isImm()) return false;
862     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
863     if (!CE) return false;
864     int64_t Value = CE->getValue();
865     return Value >= 0 && Value < 8;
866   }
867   bool isImm0_15() const {
868     if (!isImm()) return false;
869     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
870     if (!CE) return false;
871     int64_t Value = CE->getValue();
872     return Value >= 0 && Value < 16;
873   }
874   bool isImm0_31() const {
875     if (!isImm()) return false;
876     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
877     if (!CE) return false;
878     int64_t Value = CE->getValue();
879     return Value >= 0 && Value < 32;
880   }
881   bool isImm0_63() const {
882     if (!isImm()) return false;
883     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
884     if (!CE) return false;
885     int64_t Value = CE->getValue();
886     return Value >= 0 && Value < 64;
887   }
888   bool isImm8() const {
889     if (!isImm()) return false;
890     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
891     if (!CE) return false;
892     int64_t Value = CE->getValue();
893     return Value == 8;
894   }
895   bool isImm16() const {
896     if (!isImm()) return false;
897     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
898     if (!CE) return false;
899     int64_t Value = CE->getValue();
900     return Value == 16;
901   }
902   bool isImm32() const {
903     if (!isImm()) return false;
904     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
905     if (!CE) return false;
906     int64_t Value = CE->getValue();
907     return Value == 32;
908   }
909   bool isShrImm8() const {
910     if (!isImm()) return false;
911     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
912     if (!CE) return false;
913     int64_t Value = CE->getValue();
914     return Value > 0 && Value <= 8;
915   }
916   bool isShrImm16() const {
917     if (!isImm()) return false;
918     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
919     if (!CE) return false;
920     int64_t Value = CE->getValue();
921     return Value > 0 && Value <= 16;
922   }
923   bool isShrImm32() const {
924     if (!isImm()) return false;
925     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
926     if (!CE) return false;
927     int64_t Value = CE->getValue();
928     return Value > 0 && Value <= 32;
929   }
930   bool isShrImm64() const {
931     if (!isImm()) return false;
932     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
933     if (!CE) return false;
934     int64_t Value = CE->getValue();
935     return Value > 0 && Value <= 64;
936   }
937   bool isImm1_7() const {
938     if (!isImm()) return false;
939     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
940     if (!CE) return false;
941     int64_t Value = CE->getValue();
942     return Value > 0 && Value < 8;
943   }
944   bool isImm1_15() const {
945     if (!isImm()) return false;
946     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
947     if (!CE) return false;
948     int64_t Value = CE->getValue();
949     return Value > 0 && Value < 16;
950   }
951   bool isImm1_31() const {
952     if (!isImm()) return false;
953     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
954     if (!CE) return false;
955     int64_t Value = CE->getValue();
956     return Value > 0 && Value < 32;
957   }
958   bool isImm1_16() const {
959     if (!isImm()) return false;
960     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
961     if (!CE) return false;
962     int64_t Value = CE->getValue();
963     return Value > 0 && Value < 17;
964   }
965   bool isImm1_32() const {
966     if (!isImm()) return false;
967     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
968     if (!CE) return false;
969     int64_t Value = CE->getValue();
970     return Value > 0 && Value < 33;
971   }
972   bool isImm0_32() const {
973     if (!isImm()) return false;
974     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
975     if (!CE) return false;
976     int64_t Value = CE->getValue();
977     return Value >= 0 && Value < 33;
978   }
979   bool isImm0_65535() const {
980     if (!isImm()) return false;
981     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
982     if (!CE) return false;
983     int64_t Value = CE->getValue();
984     return Value >= 0 && Value < 65536;
985   }
986   bool isImm256_65535Expr() const {
987     if (!isImm()) return false;
988     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
989     // If it's not a constant expression, it'll generate a fixup and be
990     // handled later.
991     if (!CE) return true;
992     int64_t Value = CE->getValue();
993     return Value >= 256 && Value < 65536;
994   }
995   bool isImm0_65535Expr() const {
996     if (!isImm()) return false;
997     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
998     // If it's not a constant expression, it'll generate a fixup and be
999     // handled later.
1000     if (!CE) return true;
1001     int64_t Value = CE->getValue();
1002     return Value >= 0 && Value < 65536;
1003   }
1004   bool isImm24bit() const {
1005     if (!isImm()) return false;
1006     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1007     if (!CE) return false;
1008     int64_t Value = CE->getValue();
1009     return Value >= 0 && Value <= 0xffffff;
1010   }
1011   bool isImmThumbSR() const {
1012     if (!isImm()) return false;
1013     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1014     if (!CE) return false;
1015     int64_t Value = CE->getValue();
1016     return Value > 0 && Value < 33;
1017   }
1018   bool isPKHLSLImm() const {
1019     if (!isImm()) return false;
1020     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1021     if (!CE) return false;
1022     int64_t Value = CE->getValue();
1023     return Value >= 0 && Value < 32;
1024   }
1025   bool isPKHASRImm() const {
1026     if (!isImm()) return false;
1027     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1028     if (!CE) return false;
1029     int64_t Value = CE->getValue();
1030     return Value > 0 && Value <= 32;
1031   }
1032   bool isAdrLabel() const {
1033     // If we have an immediate that's not a constant, treat it as a label
1034     // reference needing a fixup. If it is a constant, but it can't fit 
1035     // into shift immediate encoding, we reject it.
1036     if (isImm() && !isa<MCConstantExpr>(getImm())) return true;
1037     else return (isARMSOImm() || isARMSOImmNeg());
1038   }
1039   bool isARMSOImm() const {
1040     if (!isImm()) return false;
1041     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1042     if (!CE) return false;
1043     int64_t Value = CE->getValue();
1044     return ARM_AM::getSOImmVal(Value) != -1;
1045   }
1046   bool isARMSOImmNot() const {
1047     if (!isImm()) return false;
1048     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1049     if (!CE) return false;
1050     int64_t Value = CE->getValue();
1051     return ARM_AM::getSOImmVal(~Value) != -1;
1052   }
1053   bool isARMSOImmNeg() const {
1054     if (!isImm()) return false;
1055     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1056     if (!CE) return false;
1057     int64_t Value = CE->getValue();
1058     // Only use this when not representable as a plain so_imm.
1059     return ARM_AM::getSOImmVal(Value) == -1 &&
1060       ARM_AM::getSOImmVal(-Value) != -1;
1061   }
1062   bool isT2SOImm() const {
1063     if (!isImm()) return false;
1064     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1065     if (!CE) return false;
1066     int64_t Value = CE->getValue();
1067     return ARM_AM::getT2SOImmVal(Value) != -1;
1068   }
1069   bool isT2SOImmNot() const {
1070     if (!isImm()) return false;
1071     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1072     if (!CE) return false;
1073     int64_t Value = CE->getValue();
1074     return ARM_AM::getT2SOImmVal(Value) == -1 &&
1075       ARM_AM::getT2SOImmVal(~Value) != -1;
1076   }
1077   bool isT2SOImmNeg() const {
1078     if (!isImm()) return false;
1079     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1080     if (!CE) return false;
1081     int64_t Value = CE->getValue();
1082     // Only use this when not representable as a plain so_imm.
1083     return ARM_AM::getT2SOImmVal(Value) == -1 &&
1084       ARM_AM::getT2SOImmVal(-Value) != -1;
1085   }
1086   bool isSetEndImm() const {
1087     if (!isImm()) return false;
1088     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1089     if (!CE) return false;
1090     int64_t Value = CE->getValue();
1091     return Value == 1 || Value == 0;
1092   }
1093   bool isReg() const override { return Kind == k_Register; }
1094   bool isRegList() const { return Kind == k_RegisterList; }
1095   bool isDPRRegList() const { return Kind == k_DPRRegisterList; }
1096   bool isSPRRegList() const { return Kind == k_SPRRegisterList; }
1097   bool isToken() const override { return Kind == k_Token; }
1098   bool isMemBarrierOpt() const { return Kind == k_MemBarrierOpt; }
1099   bool isInstSyncBarrierOpt() const { return Kind == k_InstSyncBarrierOpt; }
1100   bool isMem() const override { return Kind == k_Memory; }
1101   bool isShifterImm() const { return Kind == k_ShifterImmediate; }
1102   bool isRegShiftedReg() const { return Kind == k_ShiftedRegister; }
1103   bool isRegShiftedImm() const { return Kind == k_ShiftedImmediate; }
1104   bool isRotImm() const { return Kind == k_RotateImmediate; }
1105   bool isModImm() const { return Kind == k_ModifiedImmediate; }
1106   bool isModImmNot() const {
1107     if (!isImm()) return false;
1108     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1109     if (!CE) return false;
1110     int64_t Value = CE->getValue();
1111     return ARM_AM::getSOImmVal(~Value) != -1;
1112   }
1113   bool isModImmNeg() const {
1114     if (!isImm()) return false;
1115     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1116     if (!CE) return false;
1117     int64_t Value = CE->getValue();
1118     return ARM_AM::getSOImmVal(Value) == -1 &&
1119       ARM_AM::getSOImmVal(-Value) != -1;
1120   }
1121   bool isBitfield() const { return Kind == k_BitfieldDescriptor; }
1122   bool isPostIdxRegShifted() const { return Kind == k_PostIndexRegister; }
1123   bool isPostIdxReg() const {
1124     return Kind == k_PostIndexRegister && PostIdxReg.ShiftTy ==ARM_AM::no_shift;
1125   }
1126   bool isMemNoOffset(bool alignOK = false, unsigned Alignment = 0) const {
1127     if (!isMem())
1128       return false;
1129     // No offset of any kind.
1130     return Memory.OffsetRegNum == 0 && Memory.OffsetImm == nullptr &&
1131      (alignOK || Memory.Alignment == Alignment);
1132   }
1133   bool isMemPCRelImm12() const {
1134     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1135       return false;
1136     // Base register must be PC.
1137     if (Memory.BaseRegNum != ARM::PC)
1138       return false;
1139     // Immediate offset in range [-4095, 4095].
1140     if (!Memory.OffsetImm) return true;
1141     int64_t Val = Memory.OffsetImm->getValue();
1142     return (Val > -4096 && Val < 4096) || (Val == INT32_MIN);
1143   }
1144   bool isAlignedMemory() const {
1145     return isMemNoOffset(true);
1146   }
1147   bool isAlignedMemoryNone() const {
1148     return isMemNoOffset(false, 0);
1149   }
1150   bool isDupAlignedMemoryNone() const {
1151     return isMemNoOffset(false, 0);
1152   }
1153   bool isAlignedMemory16() const {
1154     if (isMemNoOffset(false, 2)) // alignment in bytes for 16-bits is 2.
1155       return true;
1156     return isMemNoOffset(false, 0);
1157   }
1158   bool isDupAlignedMemory16() const {
1159     if (isMemNoOffset(false, 2)) // alignment in bytes for 16-bits is 2.
1160       return true;
1161     return isMemNoOffset(false, 0);
1162   }
1163   bool isAlignedMemory32() const {
1164     if (isMemNoOffset(false, 4)) // alignment in bytes for 32-bits is 4.
1165       return true;
1166     return isMemNoOffset(false, 0);
1167   }
1168   bool isDupAlignedMemory32() const {
1169     if (isMemNoOffset(false, 4)) // alignment in bytes for 32-bits is 4.
1170       return true;
1171     return isMemNoOffset(false, 0);
1172   }
1173   bool isAlignedMemory64() const {
1174     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1175       return true;
1176     return isMemNoOffset(false, 0);
1177   }
1178   bool isDupAlignedMemory64() const {
1179     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1180       return true;
1181     return isMemNoOffset(false, 0);
1182   }
1183   bool isAlignedMemory64or128() const {
1184     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1185       return true;
1186     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1187       return true;
1188     return isMemNoOffset(false, 0);
1189   }
1190   bool isDupAlignedMemory64or128() const {
1191     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1192       return true;
1193     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1194       return true;
1195     return isMemNoOffset(false, 0);
1196   }
1197   bool isAlignedMemory64or128or256() const {
1198     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1199       return true;
1200     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1201       return true;
1202     if (isMemNoOffset(false, 32)) // alignment in bytes for 256-bits is 32.
1203       return true;
1204     return isMemNoOffset(false, 0);
1205   }
1206   bool isAddrMode2() const {
1207     if (!isMem() || Memory.Alignment != 0) return false;
1208     // Check for register offset.
1209     if (Memory.OffsetRegNum) return true;
1210     // Immediate offset in range [-4095, 4095].
1211     if (!Memory.OffsetImm) return true;
1212     int64_t Val = Memory.OffsetImm->getValue();
1213     return Val > -4096 && Val < 4096;
1214   }
1215   bool isAM2OffsetImm() const {
1216     if (!isImm()) return false;
1217     // Immediate offset in range [-4095, 4095].
1218     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1219     if (!CE) return false;
1220     int64_t Val = CE->getValue();
1221     return (Val == INT32_MIN) || (Val > -4096 && Val < 4096);
1222   }
1223   bool isAddrMode3() const {
1224     // If we have an immediate that's not a constant, treat it as a label
1225     // reference needing a fixup. If it is a constant, it's something else
1226     // and we reject it.
1227     if (isImm() && !isa<MCConstantExpr>(getImm()))
1228       return true;
1229     if (!isMem() || Memory.Alignment != 0) return false;
1230     // No shifts are legal for AM3.
1231     if (Memory.ShiftType != ARM_AM::no_shift) return false;
1232     // Check for register offset.
1233     if (Memory.OffsetRegNum) return true;
1234     // Immediate offset in range [-255, 255].
1235     if (!Memory.OffsetImm) return true;
1236     int64_t Val = Memory.OffsetImm->getValue();
1237     // The #-0 offset is encoded as INT32_MIN, and we have to check 
1238     // for this too.
1239     return (Val > -256 && Val < 256) || Val == INT32_MIN;
1240   }
1241   bool isAM3Offset() const {
1242     if (Kind != k_Immediate && Kind != k_PostIndexRegister)
1243       return false;
1244     if (Kind == k_PostIndexRegister)
1245       return PostIdxReg.ShiftTy == ARM_AM::no_shift;
1246     // Immediate offset in range [-255, 255].
1247     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1248     if (!CE) return false;
1249     int64_t Val = CE->getValue();
1250     // Special case, #-0 is INT32_MIN.
1251     return (Val > -256 && Val < 256) || Val == INT32_MIN;
1252   }
1253   bool isAddrMode5() const {
1254     // If we have an immediate that's not a constant, treat it as a label
1255     // reference needing a fixup. If it is a constant, it's something else
1256     // and we reject it.
1257     if (isImm() && !isa<MCConstantExpr>(getImm()))
1258       return true;
1259     if (!isMem() || Memory.Alignment != 0) return false;
1260     // Check for register offset.
1261     if (Memory.OffsetRegNum) return false;
1262     // Immediate offset in range [-1020, 1020] and a multiple of 4.
1263     if (!Memory.OffsetImm) return true;
1264     int64_t Val = Memory.OffsetImm->getValue();
1265     return (Val >= -1020 && Val <= 1020 && ((Val & 3) == 0)) ||
1266       Val == INT32_MIN;
1267   }
1268   bool isMemTBB() const {
1269     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1270         Memory.ShiftType != ARM_AM::no_shift || Memory.Alignment != 0)
1271       return false;
1272     return true;
1273   }
1274   bool isMemTBH() const {
1275     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1276         Memory.ShiftType != ARM_AM::lsl || Memory.ShiftImm != 1 ||
1277         Memory.Alignment != 0 )
1278       return false;
1279     return true;
1280   }
1281   bool isMemRegOffset() const {
1282     if (!isMem() || !Memory.OffsetRegNum || Memory.Alignment != 0)
1283       return false;
1284     return true;
1285   }
1286   bool isT2MemRegOffset() const {
1287     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1288         Memory.Alignment != 0)
1289       return false;
1290     // Only lsl #{0, 1, 2, 3} allowed.
1291     if (Memory.ShiftType == ARM_AM::no_shift)
1292       return true;
1293     if (Memory.ShiftType != ARM_AM::lsl || Memory.ShiftImm > 3)
1294       return false;
1295     return true;
1296   }
1297   bool isMemThumbRR() const {
1298     // Thumb reg+reg addressing is simple. Just two registers, a base and
1299     // an offset. No shifts, negations or any other complicating factors.
1300     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1301         Memory.ShiftType != ARM_AM::no_shift || Memory.Alignment != 0)
1302       return false;
1303     return isARMLowRegister(Memory.BaseRegNum) &&
1304       (!Memory.OffsetRegNum || isARMLowRegister(Memory.OffsetRegNum));
1305   }
1306   bool isMemThumbRIs4() const {
1307     if (!isMem() || Memory.OffsetRegNum != 0 ||
1308         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1309       return false;
1310     // Immediate offset, multiple of 4 in range [0, 124].
1311     if (!Memory.OffsetImm) return true;
1312     int64_t Val = Memory.OffsetImm->getValue();
1313     return Val >= 0 && Val <= 124 && (Val % 4) == 0;
1314   }
1315   bool isMemThumbRIs2() const {
1316     if (!isMem() || Memory.OffsetRegNum != 0 ||
1317         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1318       return false;
1319     // Immediate offset, multiple of 4 in range [0, 62].
1320     if (!Memory.OffsetImm) return true;
1321     int64_t Val = Memory.OffsetImm->getValue();
1322     return Val >= 0 && Val <= 62 && (Val % 2) == 0;
1323   }
1324   bool isMemThumbRIs1() const {
1325     if (!isMem() || Memory.OffsetRegNum != 0 ||
1326         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1327       return false;
1328     // Immediate offset in range [0, 31].
1329     if (!Memory.OffsetImm) return true;
1330     int64_t Val = Memory.OffsetImm->getValue();
1331     return Val >= 0 && Val <= 31;
1332   }
1333   bool isMemThumbSPI() const {
1334     if (!isMem() || Memory.OffsetRegNum != 0 ||
1335         Memory.BaseRegNum != ARM::SP || Memory.Alignment != 0)
1336       return false;
1337     // Immediate offset, multiple of 4 in range [0, 1020].
1338     if (!Memory.OffsetImm) return true;
1339     int64_t Val = Memory.OffsetImm->getValue();
1340     return Val >= 0 && Val <= 1020 && (Val % 4) == 0;
1341   }
1342   bool isMemImm8s4Offset() const {
1343     // If we have an immediate that's not a constant, treat it as a label
1344     // reference needing a fixup. If it is a constant, it's something else
1345     // and we reject it.
1346     if (isImm() && !isa<MCConstantExpr>(getImm()))
1347       return true;
1348     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1349       return false;
1350     // Immediate offset a multiple of 4 in range [-1020, 1020].
1351     if (!Memory.OffsetImm) return true;
1352     int64_t Val = Memory.OffsetImm->getValue();
1353     // Special case, #-0 is INT32_MIN.
1354     return (Val >= -1020 && Val <= 1020 && (Val & 3) == 0) || Val == INT32_MIN;
1355   }
1356   bool isMemImm0_1020s4Offset() const {
1357     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1358       return false;
1359     // Immediate offset a multiple of 4 in range [0, 1020].
1360     if (!Memory.OffsetImm) return true;
1361     int64_t Val = Memory.OffsetImm->getValue();
1362     return Val >= 0 && Val <= 1020 && (Val & 3) == 0;
1363   }
1364   bool isMemImm8Offset() const {
1365     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1366       return false;
1367     // Base reg of PC isn't allowed for these encodings.
1368     if (Memory.BaseRegNum == ARM::PC) return false;
1369     // Immediate offset in range [-255, 255].
1370     if (!Memory.OffsetImm) return true;
1371     int64_t Val = Memory.OffsetImm->getValue();
1372     return (Val == INT32_MIN) || (Val > -256 && Val < 256);
1373   }
1374   bool isMemPosImm8Offset() const {
1375     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1376       return false;
1377     // Immediate offset in range [0, 255].
1378     if (!Memory.OffsetImm) return true;
1379     int64_t Val = Memory.OffsetImm->getValue();
1380     return Val >= 0 && Val < 256;
1381   }
1382   bool isMemNegImm8Offset() const {
1383     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1384       return false;
1385     // Base reg of PC isn't allowed for these encodings.
1386     if (Memory.BaseRegNum == ARM::PC) return false;
1387     // Immediate offset in range [-255, -1].
1388     if (!Memory.OffsetImm) return false;
1389     int64_t Val = Memory.OffsetImm->getValue();
1390     return (Val == INT32_MIN) || (Val > -256 && Val < 0);
1391   }
1392   bool isMemUImm12Offset() const {
1393     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1394       return false;
1395     // Immediate offset in range [0, 4095].
1396     if (!Memory.OffsetImm) return true;
1397     int64_t Val = Memory.OffsetImm->getValue();
1398     return (Val >= 0 && Val < 4096);
1399   }
1400   bool isMemImm12Offset() const {
1401     // If we have an immediate that's not a constant, treat it as a label
1402     // reference needing a fixup. If it is a constant, it's something else
1403     // and we reject it.
1404     if (isImm() && !isa<MCConstantExpr>(getImm()))
1405       return true;
1406
1407     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1408       return false;
1409     // Immediate offset in range [-4095, 4095].
1410     if (!Memory.OffsetImm) return true;
1411     int64_t Val = Memory.OffsetImm->getValue();
1412     return (Val > -4096 && Val < 4096) || (Val == INT32_MIN);
1413   }
1414   bool isPostIdxImm8() const {
1415     if (!isImm()) return false;
1416     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1417     if (!CE) return false;
1418     int64_t Val = CE->getValue();
1419     return (Val > -256 && Val < 256) || (Val == INT32_MIN);
1420   }
1421   bool isPostIdxImm8s4() const {
1422     if (!isImm()) return false;
1423     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1424     if (!CE) return false;
1425     int64_t Val = CE->getValue();
1426     return ((Val & 3) == 0 && Val >= -1020 && Val <= 1020) ||
1427       (Val == INT32_MIN);
1428   }
1429
1430   bool isMSRMask() const { return Kind == k_MSRMask; }
1431   bool isBankedReg() const { return Kind == k_BankedReg; }
1432   bool isProcIFlags() const { return Kind == k_ProcIFlags; }
1433
1434   // NEON operands.
1435   bool isSingleSpacedVectorList() const {
1436     return Kind == k_VectorList && !VectorList.isDoubleSpaced;
1437   }
1438   bool isDoubleSpacedVectorList() const {
1439     return Kind == k_VectorList && VectorList.isDoubleSpaced;
1440   }
1441   bool isVecListOneD() const {
1442     if (!isSingleSpacedVectorList()) return false;
1443     return VectorList.Count == 1;
1444   }
1445
1446   bool isVecListDPair() const {
1447     if (!isSingleSpacedVectorList()) return false;
1448     return (ARMMCRegisterClasses[ARM::DPairRegClassID]
1449               .contains(VectorList.RegNum));
1450   }
1451
1452   bool isVecListThreeD() const {
1453     if (!isSingleSpacedVectorList()) return false;
1454     return VectorList.Count == 3;
1455   }
1456
1457   bool isVecListFourD() const {
1458     if (!isSingleSpacedVectorList()) return false;
1459     return VectorList.Count == 4;
1460   }
1461
1462   bool isVecListDPairSpaced() const {
1463     if (Kind != k_VectorList) return false;
1464     if (isSingleSpacedVectorList()) return false;
1465     return (ARMMCRegisterClasses[ARM::DPairSpcRegClassID]
1466               .contains(VectorList.RegNum));
1467   }
1468
1469   bool isVecListThreeQ() const {
1470     if (!isDoubleSpacedVectorList()) return false;
1471     return VectorList.Count == 3;
1472   }
1473
1474   bool isVecListFourQ() const {
1475     if (!isDoubleSpacedVectorList()) return false;
1476     return VectorList.Count == 4;
1477   }
1478
1479   bool isSingleSpacedVectorAllLanes() const {
1480     return Kind == k_VectorListAllLanes && !VectorList.isDoubleSpaced;
1481   }
1482   bool isDoubleSpacedVectorAllLanes() const {
1483     return Kind == k_VectorListAllLanes && VectorList.isDoubleSpaced;
1484   }
1485   bool isVecListOneDAllLanes() const {
1486     if (!isSingleSpacedVectorAllLanes()) return false;
1487     return VectorList.Count == 1;
1488   }
1489
1490   bool isVecListDPairAllLanes() const {
1491     if (!isSingleSpacedVectorAllLanes()) return false;
1492     return (ARMMCRegisterClasses[ARM::DPairRegClassID]
1493               .contains(VectorList.RegNum));
1494   }
1495
1496   bool isVecListDPairSpacedAllLanes() const {
1497     if (!isDoubleSpacedVectorAllLanes()) return false;
1498     return VectorList.Count == 2;
1499   }
1500
1501   bool isVecListThreeDAllLanes() const {
1502     if (!isSingleSpacedVectorAllLanes()) return false;
1503     return VectorList.Count == 3;
1504   }
1505
1506   bool isVecListThreeQAllLanes() const {
1507     if (!isDoubleSpacedVectorAllLanes()) return false;
1508     return VectorList.Count == 3;
1509   }
1510
1511   bool isVecListFourDAllLanes() const {
1512     if (!isSingleSpacedVectorAllLanes()) return false;
1513     return VectorList.Count == 4;
1514   }
1515
1516   bool isVecListFourQAllLanes() const {
1517     if (!isDoubleSpacedVectorAllLanes()) return false;
1518     return VectorList.Count == 4;
1519   }
1520
1521   bool isSingleSpacedVectorIndexed() const {
1522     return Kind == k_VectorListIndexed && !VectorList.isDoubleSpaced;
1523   }
1524   bool isDoubleSpacedVectorIndexed() const {
1525     return Kind == k_VectorListIndexed && VectorList.isDoubleSpaced;
1526   }
1527   bool isVecListOneDByteIndexed() const {
1528     if (!isSingleSpacedVectorIndexed()) return false;
1529     return VectorList.Count == 1 && VectorList.LaneIndex <= 7;
1530   }
1531
1532   bool isVecListOneDHWordIndexed() const {
1533     if (!isSingleSpacedVectorIndexed()) return false;
1534     return VectorList.Count == 1 && VectorList.LaneIndex <= 3;
1535   }
1536
1537   bool isVecListOneDWordIndexed() const {
1538     if (!isSingleSpacedVectorIndexed()) return false;
1539     return VectorList.Count == 1 && VectorList.LaneIndex <= 1;
1540   }
1541
1542   bool isVecListTwoDByteIndexed() const {
1543     if (!isSingleSpacedVectorIndexed()) return false;
1544     return VectorList.Count == 2 && VectorList.LaneIndex <= 7;
1545   }
1546
1547   bool isVecListTwoDHWordIndexed() const {
1548     if (!isSingleSpacedVectorIndexed()) return false;
1549     return VectorList.Count == 2 && VectorList.LaneIndex <= 3;
1550   }
1551
1552   bool isVecListTwoQWordIndexed() const {
1553     if (!isDoubleSpacedVectorIndexed()) return false;
1554     return VectorList.Count == 2 && VectorList.LaneIndex <= 1;
1555   }
1556
1557   bool isVecListTwoQHWordIndexed() const {
1558     if (!isDoubleSpacedVectorIndexed()) return false;
1559     return VectorList.Count == 2 && VectorList.LaneIndex <= 3;
1560   }
1561
1562   bool isVecListTwoDWordIndexed() const {
1563     if (!isSingleSpacedVectorIndexed()) return false;
1564     return VectorList.Count == 2 && VectorList.LaneIndex <= 1;
1565   }
1566
1567   bool isVecListThreeDByteIndexed() const {
1568     if (!isSingleSpacedVectorIndexed()) return false;
1569     return VectorList.Count == 3 && VectorList.LaneIndex <= 7;
1570   }
1571
1572   bool isVecListThreeDHWordIndexed() const {
1573     if (!isSingleSpacedVectorIndexed()) return false;
1574     return VectorList.Count == 3 && VectorList.LaneIndex <= 3;
1575   }
1576
1577   bool isVecListThreeQWordIndexed() const {
1578     if (!isDoubleSpacedVectorIndexed()) return false;
1579     return VectorList.Count == 3 && VectorList.LaneIndex <= 1;
1580   }
1581
1582   bool isVecListThreeQHWordIndexed() const {
1583     if (!isDoubleSpacedVectorIndexed()) return false;
1584     return VectorList.Count == 3 && VectorList.LaneIndex <= 3;
1585   }
1586
1587   bool isVecListThreeDWordIndexed() const {
1588     if (!isSingleSpacedVectorIndexed()) return false;
1589     return VectorList.Count == 3 && VectorList.LaneIndex <= 1;
1590   }
1591
1592   bool isVecListFourDByteIndexed() const {
1593     if (!isSingleSpacedVectorIndexed()) return false;
1594     return VectorList.Count == 4 && VectorList.LaneIndex <= 7;
1595   }
1596
1597   bool isVecListFourDHWordIndexed() const {
1598     if (!isSingleSpacedVectorIndexed()) return false;
1599     return VectorList.Count == 4 && VectorList.LaneIndex <= 3;
1600   }
1601
1602   bool isVecListFourQWordIndexed() const {
1603     if (!isDoubleSpacedVectorIndexed()) return false;
1604     return VectorList.Count == 4 && VectorList.LaneIndex <= 1;
1605   }
1606
1607   bool isVecListFourQHWordIndexed() const {
1608     if (!isDoubleSpacedVectorIndexed()) return false;
1609     return VectorList.Count == 4 && VectorList.LaneIndex <= 3;
1610   }
1611
1612   bool isVecListFourDWordIndexed() const {
1613     if (!isSingleSpacedVectorIndexed()) return false;
1614     return VectorList.Count == 4 && VectorList.LaneIndex <= 1;
1615   }
1616
1617   bool isVectorIndex8() const {
1618     if (Kind != k_VectorIndex) return false;
1619     return VectorIndex.Val < 8;
1620   }
1621   bool isVectorIndex16() const {
1622     if (Kind != k_VectorIndex) return false;
1623     return VectorIndex.Val < 4;
1624   }
1625   bool isVectorIndex32() const {
1626     if (Kind != k_VectorIndex) return false;
1627     return VectorIndex.Val < 2;
1628   }
1629
1630   bool isNEONi8splat() const {
1631     if (!isImm()) return false;
1632     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1633     // Must be a constant.
1634     if (!CE) return false;
1635     int64_t Value = CE->getValue();
1636     // i8 value splatted across 8 bytes. The immediate is just the 8 byte
1637     // value.
1638     return Value >= 0 && Value < 256;
1639   }
1640
1641   bool isNEONi16splat() const {
1642     if (isNEONByteReplicate(2))
1643       return false; // Leave that for bytes replication and forbid by default.
1644     if (!isImm())
1645       return false;
1646     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1647     // Must be a constant.
1648     if (!CE) return false;
1649     unsigned Value = CE->getValue();
1650     return ARM_AM::isNEONi16splat(Value);
1651   }
1652
1653   bool isNEONi16splatNot() const {
1654     if (!isImm())
1655       return false;
1656     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1657     // Must be a constant.
1658     if (!CE) return false;
1659     unsigned Value = CE->getValue();
1660     return ARM_AM::isNEONi16splat(~Value & 0xffff);
1661   }
1662
1663   bool isNEONi32splat() const {
1664     if (isNEONByteReplicate(4))
1665       return false; // Leave that for bytes replication and forbid by default.
1666     if (!isImm())
1667       return false;
1668     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1669     // Must be a constant.
1670     if (!CE) return false;
1671     unsigned Value = CE->getValue();
1672     return ARM_AM::isNEONi32splat(Value);
1673   }
1674
1675   bool isNEONi32splatNot() const {
1676     if (!isImm())
1677       return false;
1678     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1679     // Must be a constant.
1680     if (!CE) return false;
1681     unsigned Value = CE->getValue();
1682     return ARM_AM::isNEONi32splat(~Value);
1683   }
1684
1685   bool isNEONByteReplicate(unsigned NumBytes) const {
1686     if (!isImm())
1687       return false;
1688     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1689     // Must be a constant.
1690     if (!CE)
1691       return false;
1692     int64_t Value = CE->getValue();
1693     if (!Value)
1694       return false; // Don't bother with zero.
1695
1696     unsigned char B = Value & 0xff;
1697     for (unsigned i = 1; i < NumBytes; ++i) {
1698       Value >>= 8;
1699       if ((Value & 0xff) != B)
1700         return false;
1701     }
1702     return true;
1703   }
1704   bool isNEONi16ByteReplicate() const { return isNEONByteReplicate(2); }
1705   bool isNEONi32ByteReplicate() const { return isNEONByteReplicate(4); }
1706   bool isNEONi32vmov() const {
1707     if (isNEONByteReplicate(4))
1708       return false; // Let it to be classified as byte-replicate case.
1709     if (!isImm())
1710       return false;
1711     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1712     // Must be a constant.
1713     if (!CE)
1714       return false;
1715     int64_t Value = CE->getValue();
1716     // i32 value with set bits only in one byte X000, 0X00, 00X0, or 000X,
1717     // for VMOV/VMVN only, 00Xf or 0Xff are also accepted.
1718     // FIXME: This is probably wrong and a copy and paste from previous example
1719     return (Value >= 0 && Value < 256) ||
1720       (Value >= 0x0100 && Value <= 0xff00) ||
1721       (Value >= 0x010000 && Value <= 0xff0000) ||
1722       (Value >= 0x01000000 && Value <= 0xff000000) ||
1723       (Value >= 0x01ff && Value <= 0xffff && (Value & 0xff) == 0xff) ||
1724       (Value >= 0x01ffff && Value <= 0xffffff && (Value & 0xffff) == 0xffff);
1725   }
1726   bool isNEONi32vmovNeg() const {
1727     if (!isImm()) return false;
1728     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1729     // Must be a constant.
1730     if (!CE) return false;
1731     int64_t Value = ~CE->getValue();
1732     // i32 value with set bits only in one byte X000, 0X00, 00X0, or 000X,
1733     // for VMOV/VMVN only, 00Xf or 0Xff are also accepted.
1734     // FIXME: This is probably wrong and a copy and paste from previous example
1735     return (Value >= 0 && Value < 256) ||
1736       (Value >= 0x0100 && Value <= 0xff00) ||
1737       (Value >= 0x010000 && Value <= 0xff0000) ||
1738       (Value >= 0x01000000 && Value <= 0xff000000) ||
1739       (Value >= 0x01ff && Value <= 0xffff && (Value & 0xff) == 0xff) ||
1740       (Value >= 0x01ffff && Value <= 0xffffff && (Value & 0xffff) == 0xffff);
1741   }
1742
1743   bool isNEONi64splat() const {
1744     if (!isImm()) return false;
1745     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1746     // Must be a constant.
1747     if (!CE) return false;
1748     uint64_t Value = CE->getValue();
1749     // i64 value with each byte being either 0 or 0xff.
1750     for (unsigned i = 0; i < 8; ++i)
1751       if ((Value & 0xff) != 0 && (Value & 0xff) != 0xff) return false;
1752     return true;
1753   }
1754
1755   void addExpr(MCInst &Inst, const MCExpr *Expr) const {
1756     // Add as immediates when possible.  Null MCExpr = 0.
1757     if (!Expr)
1758       Inst.addOperand(MCOperand::CreateImm(0));
1759     else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
1760       Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
1761     else
1762       Inst.addOperand(MCOperand::CreateExpr(Expr));
1763   }
1764
1765   void addCondCodeOperands(MCInst &Inst, unsigned N) const {
1766     assert(N == 2 && "Invalid number of operands!");
1767     Inst.addOperand(MCOperand::CreateImm(unsigned(getCondCode())));
1768     unsigned RegNum = getCondCode() == ARMCC::AL ? 0: ARM::CPSR;
1769     Inst.addOperand(MCOperand::CreateReg(RegNum));
1770   }
1771
1772   void addCoprocNumOperands(MCInst &Inst, unsigned N) const {
1773     assert(N == 1 && "Invalid number of operands!");
1774     Inst.addOperand(MCOperand::CreateImm(getCoproc()));
1775   }
1776
1777   void addCoprocRegOperands(MCInst &Inst, unsigned N) const {
1778     assert(N == 1 && "Invalid number of operands!");
1779     Inst.addOperand(MCOperand::CreateImm(getCoproc()));
1780   }
1781
1782   void addCoprocOptionOperands(MCInst &Inst, unsigned N) const {
1783     assert(N == 1 && "Invalid number of operands!");
1784     Inst.addOperand(MCOperand::CreateImm(CoprocOption.Val));
1785   }
1786
1787   void addITMaskOperands(MCInst &Inst, unsigned N) const {
1788     assert(N == 1 && "Invalid number of operands!");
1789     Inst.addOperand(MCOperand::CreateImm(ITMask.Mask));
1790   }
1791
1792   void addITCondCodeOperands(MCInst &Inst, unsigned N) const {
1793     assert(N == 1 && "Invalid number of operands!");
1794     Inst.addOperand(MCOperand::CreateImm(unsigned(getCondCode())));
1795   }
1796
1797   void addCCOutOperands(MCInst &Inst, unsigned N) const {
1798     assert(N == 1 && "Invalid number of operands!");
1799     Inst.addOperand(MCOperand::CreateReg(getReg()));
1800   }
1801
1802   void addRegOperands(MCInst &Inst, unsigned N) const {
1803     assert(N == 1 && "Invalid number of operands!");
1804     Inst.addOperand(MCOperand::CreateReg(getReg()));
1805   }
1806
1807   void addRegShiftedRegOperands(MCInst &Inst, unsigned N) const {
1808     assert(N == 3 && "Invalid number of operands!");
1809     assert(isRegShiftedReg() &&
1810            "addRegShiftedRegOperands() on non-RegShiftedReg!");
1811     Inst.addOperand(MCOperand::CreateReg(RegShiftedReg.SrcReg));
1812     Inst.addOperand(MCOperand::CreateReg(RegShiftedReg.ShiftReg));
1813     Inst.addOperand(MCOperand::CreateImm(
1814       ARM_AM::getSORegOpc(RegShiftedReg.ShiftTy, RegShiftedReg.ShiftImm)));
1815   }
1816
1817   void addRegShiftedImmOperands(MCInst &Inst, unsigned N) const {
1818     assert(N == 2 && "Invalid number of operands!");
1819     assert(isRegShiftedImm() &&
1820            "addRegShiftedImmOperands() on non-RegShiftedImm!");
1821     Inst.addOperand(MCOperand::CreateReg(RegShiftedImm.SrcReg));
1822     // Shift of #32 is encoded as 0 where permitted
1823     unsigned Imm = (RegShiftedImm.ShiftImm == 32 ? 0 : RegShiftedImm.ShiftImm);
1824     Inst.addOperand(MCOperand::CreateImm(
1825       ARM_AM::getSORegOpc(RegShiftedImm.ShiftTy, Imm)));
1826   }
1827
1828   void addShifterImmOperands(MCInst &Inst, unsigned N) const {
1829     assert(N == 1 && "Invalid number of operands!");
1830     Inst.addOperand(MCOperand::CreateImm((ShifterImm.isASR << 5) |
1831                                          ShifterImm.Imm));
1832   }
1833
1834   void addRegListOperands(MCInst &Inst, unsigned N) const {
1835     assert(N == 1 && "Invalid number of operands!");
1836     const SmallVectorImpl<unsigned> &RegList = getRegList();
1837     for (SmallVectorImpl<unsigned>::const_iterator
1838            I = RegList.begin(), E = RegList.end(); I != E; ++I)
1839       Inst.addOperand(MCOperand::CreateReg(*I));
1840   }
1841
1842   void addDPRRegListOperands(MCInst &Inst, unsigned N) const {
1843     addRegListOperands(Inst, N);
1844   }
1845
1846   void addSPRRegListOperands(MCInst &Inst, unsigned N) const {
1847     addRegListOperands(Inst, N);
1848   }
1849
1850   void addRotImmOperands(MCInst &Inst, unsigned N) const {
1851     assert(N == 1 && "Invalid number of operands!");
1852     // Encoded as val>>3. The printer handles display as 8, 16, 24.
1853     Inst.addOperand(MCOperand::CreateImm(RotImm.Imm >> 3));
1854   }
1855
1856   void addModImmOperands(MCInst &Inst, unsigned N) const {
1857     assert(N == 1 && "Invalid number of operands!");
1858
1859     // Support for fixups (MCFixup)
1860     if (isImm())
1861       return addImmOperands(Inst, N);
1862
1863     if (Inst.getOpcode() == ARM::ADDri &&
1864       Inst.getOperand(1).getReg() == ARM::PC) {
1865       // Instructions of the form [ADD <rd>, pc, #imm] are manually aliased
1866       // in processInstruction() to use ADR. We must keep the immediate in
1867       // its unencoded form in order to not clash with this aliasing.
1868       Inst.addOperand(MCOperand::CreateImm(ARM_AM::rotr32(ModImm.Bits,
1869                                                           ModImm.Rot)));
1870     } else {
1871       Inst.addOperand(MCOperand::CreateImm(ModImm.Bits | (ModImm.Rot << 7)));
1872     }
1873   }
1874
1875   void addModImmNotOperands(MCInst &Inst, unsigned N) const {
1876     assert(N == 1 && "Invalid number of operands!");
1877     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1878     uint32_t Enc = ARM_AM::getSOImmVal(~CE->getValue());
1879     Inst.addOperand(MCOperand::CreateImm(Enc));
1880   }
1881
1882   void addModImmNegOperands(MCInst &Inst, unsigned N) const {
1883     assert(N == 1 && "Invalid number of operands!");
1884     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1885     uint32_t Enc = ARM_AM::getSOImmVal(-CE->getValue());
1886     Inst.addOperand(MCOperand::CreateImm(Enc));
1887   }
1888
1889   void addBitfieldOperands(MCInst &Inst, unsigned N) const {
1890     assert(N == 1 && "Invalid number of operands!");
1891     // Munge the lsb/width into a bitfield mask.
1892     unsigned lsb = Bitfield.LSB;
1893     unsigned width = Bitfield.Width;
1894     // Make a 32-bit mask w/ the referenced bits clear and all other bits set.
1895     uint32_t Mask = ~(((uint32_t)0xffffffff >> lsb) << (32 - width) >>
1896                       (32 - (lsb + width)));
1897     Inst.addOperand(MCOperand::CreateImm(Mask));
1898   }
1899
1900   void addImmOperands(MCInst &Inst, unsigned N) const {
1901     assert(N == 1 && "Invalid number of operands!");
1902     addExpr(Inst, getImm());
1903   }
1904
1905   void addFBits16Operands(MCInst &Inst, unsigned N) const {
1906     assert(N == 1 && "Invalid number of operands!");
1907     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1908     Inst.addOperand(MCOperand::CreateImm(16 - CE->getValue()));
1909   }
1910
1911   void addFBits32Operands(MCInst &Inst, unsigned N) const {
1912     assert(N == 1 && "Invalid number of operands!");
1913     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1914     Inst.addOperand(MCOperand::CreateImm(32 - CE->getValue()));
1915   }
1916
1917   void addFPImmOperands(MCInst &Inst, unsigned N) const {
1918     assert(N == 1 && "Invalid number of operands!");
1919     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1920     int Val = ARM_AM::getFP32Imm(APInt(32, CE->getValue()));
1921     Inst.addOperand(MCOperand::CreateImm(Val));
1922   }
1923
1924   void addImm8s4Operands(MCInst &Inst, unsigned N) const {
1925     assert(N == 1 && "Invalid number of operands!");
1926     // FIXME: We really want to scale the value here, but the LDRD/STRD
1927     // instruction don't encode operands that way yet.
1928     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1929     Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
1930   }
1931
1932   void addImm0_1020s4Operands(MCInst &Inst, unsigned N) const {
1933     assert(N == 1 && "Invalid number of operands!");
1934     // The immediate is scaled by four in the encoding and is stored
1935     // in the MCInst as such. Lop off the low two bits here.
1936     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1937     Inst.addOperand(MCOperand::CreateImm(CE->getValue() / 4));
1938   }
1939
1940   void addImm0_508s4NegOperands(MCInst &Inst, unsigned N) const {
1941     assert(N == 1 && "Invalid number of operands!");
1942     // The immediate is scaled by four in the encoding and is stored
1943     // in the MCInst as such. Lop off the low two bits here.
1944     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1945     Inst.addOperand(MCOperand::CreateImm(-(CE->getValue() / 4)));
1946   }
1947
1948   void addImm0_508s4Operands(MCInst &Inst, unsigned N) const {
1949     assert(N == 1 && "Invalid number of operands!");
1950     // The immediate is scaled by four in the encoding and is stored
1951     // in the MCInst as such. Lop off the low two bits here.
1952     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1953     Inst.addOperand(MCOperand::CreateImm(CE->getValue() / 4));
1954   }
1955
1956   void addImm1_16Operands(MCInst &Inst, unsigned N) const {
1957     assert(N == 1 && "Invalid number of operands!");
1958     // The constant encodes as the immediate-1, and we store in the instruction
1959     // the bits as encoded, so subtract off one here.
1960     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1961     Inst.addOperand(MCOperand::CreateImm(CE->getValue() - 1));
1962   }
1963
1964   void addImm1_32Operands(MCInst &Inst, unsigned N) const {
1965     assert(N == 1 && "Invalid number of operands!");
1966     // The constant encodes as the immediate-1, and we store in the instruction
1967     // the bits as encoded, so subtract off one here.
1968     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1969     Inst.addOperand(MCOperand::CreateImm(CE->getValue() - 1));
1970   }
1971
1972   void addImmThumbSROperands(MCInst &Inst, unsigned N) const {
1973     assert(N == 1 && "Invalid number of operands!");
1974     // The constant encodes as the immediate, except for 32, which encodes as
1975     // zero.
1976     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1977     unsigned Imm = CE->getValue();
1978     Inst.addOperand(MCOperand::CreateImm((Imm == 32 ? 0 : Imm)));
1979   }
1980
1981   void addPKHASRImmOperands(MCInst &Inst, unsigned N) const {
1982     assert(N == 1 && "Invalid number of operands!");
1983     // An ASR value of 32 encodes as 0, so that's how we want to add it to
1984     // the instruction as well.
1985     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1986     int Val = CE->getValue();
1987     Inst.addOperand(MCOperand::CreateImm(Val == 32 ? 0 : Val));
1988   }
1989
1990   void addT2SOImmNotOperands(MCInst &Inst, unsigned N) const {
1991     assert(N == 1 && "Invalid number of operands!");
1992     // The operand is actually a t2_so_imm, but we have its bitwise
1993     // negation in the assembly source, so twiddle it here.
1994     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1995     Inst.addOperand(MCOperand::CreateImm(~CE->getValue()));
1996   }
1997
1998   void addT2SOImmNegOperands(MCInst &Inst, unsigned N) const {
1999     assert(N == 1 && "Invalid number of operands!");
2000     // The operand is actually a t2_so_imm, but we have its
2001     // negation in the assembly source, so twiddle it here.
2002     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2003     Inst.addOperand(MCOperand::CreateImm(-CE->getValue()));
2004   }
2005
2006   void addImm0_4095NegOperands(MCInst &Inst, unsigned N) const {
2007     assert(N == 1 && "Invalid number of operands!");
2008     // The operand is actually an imm0_4095, but we have its
2009     // negation in the assembly source, so twiddle it here.
2010     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2011     Inst.addOperand(MCOperand::CreateImm(-CE->getValue()));
2012   }
2013
2014   void addUnsignedOffset_b8s2Operands(MCInst &Inst, unsigned N) const {
2015     if(const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm())) {
2016       Inst.addOperand(MCOperand::CreateImm(CE->getValue() >> 2));
2017       return;
2018     }
2019
2020     const MCSymbolRefExpr *SR = dyn_cast<MCSymbolRefExpr>(Imm.Val);
2021     assert(SR && "Unknown value type!");
2022     Inst.addOperand(MCOperand::CreateExpr(SR));
2023   }
2024
2025   void addThumbMemPCOperands(MCInst &Inst, unsigned N) const {
2026     assert(N == 1 && "Invalid number of operands!");
2027     if (isImm()) {
2028       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2029       if (CE) {
2030         Inst.addOperand(MCOperand::CreateImm(CE->getValue()));
2031         return;
2032       }
2033
2034       const MCSymbolRefExpr *SR = dyn_cast<MCSymbolRefExpr>(Imm.Val);
2035       assert(SR && "Unknown value type!");
2036       Inst.addOperand(MCOperand::CreateExpr(SR));
2037       return;
2038     }
2039
2040     assert(isMem()  && "Unknown value type!");
2041     assert(isa<MCConstantExpr>(Memory.OffsetImm) && "Unknown value type!");
2042     Inst.addOperand(MCOperand::CreateImm(Memory.OffsetImm->getValue()));
2043   }
2044
2045   void addARMSOImmNotOperands(MCInst &Inst, unsigned N) const {
2046     assert(N == 1 && "Invalid number of operands!");
2047     // The operand is actually a so_imm, but we have its bitwise
2048     // negation in the assembly source, so twiddle it here.
2049     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2050     Inst.addOperand(MCOperand::CreateImm(~CE->getValue()));
2051   }
2052
2053   void addARMSOImmNegOperands(MCInst &Inst, unsigned N) const {
2054     assert(N == 1 && "Invalid number of operands!");
2055     // The operand is actually a so_imm, but we have its
2056     // negation in the assembly source, so twiddle it here.
2057     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2058     Inst.addOperand(MCOperand::CreateImm(-CE->getValue()));
2059   }
2060
2061   void addMemBarrierOptOperands(MCInst &Inst, unsigned N) const {
2062     assert(N == 1 && "Invalid number of operands!");
2063     Inst.addOperand(MCOperand::CreateImm(unsigned(getMemBarrierOpt())));
2064   }
2065
2066   void addInstSyncBarrierOptOperands(MCInst &Inst, unsigned N) const {
2067     assert(N == 1 && "Invalid number of operands!");
2068     Inst.addOperand(MCOperand::CreateImm(unsigned(getInstSyncBarrierOpt())));
2069   }
2070
2071   void addMemNoOffsetOperands(MCInst &Inst, unsigned N) const {
2072     assert(N == 1 && "Invalid number of operands!");
2073     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
2074   }
2075
2076   void addMemPCRelImm12Operands(MCInst &Inst, unsigned N) const {
2077     assert(N == 1 && "Invalid number of operands!");
2078     int32_t Imm = Memory.OffsetImm->getValue();
2079     Inst.addOperand(MCOperand::CreateImm(Imm));
2080   }
2081
2082   void addAdrLabelOperands(MCInst &Inst, unsigned N) const {
2083     assert(N == 1 && "Invalid number of operands!");
2084     assert(isImm() && "Not an immediate!");
2085
2086     // If we have an immediate that's not a constant, treat it as a label
2087     // reference needing a fixup. 
2088     if (!isa<MCConstantExpr>(getImm())) {
2089       Inst.addOperand(MCOperand::CreateExpr(getImm()));
2090       return;
2091     }
2092
2093     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2094     int Val = CE->getValue();
2095     Inst.addOperand(MCOperand::CreateImm(Val));
2096   }
2097
2098   void addAlignedMemoryOperands(MCInst &Inst, unsigned N) const {
2099     assert(N == 2 && "Invalid number of operands!");
2100     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
2101     Inst.addOperand(MCOperand::CreateImm(Memory.Alignment));
2102   }
2103
2104   void addDupAlignedMemoryNoneOperands(MCInst &Inst, unsigned N) const {
2105     addAlignedMemoryOperands(Inst, N);
2106   }
2107
2108   void addAlignedMemoryNoneOperands(MCInst &Inst, unsigned N) const {
2109     addAlignedMemoryOperands(Inst, N);
2110   }
2111
2112   void addAlignedMemory16Operands(MCInst &Inst, unsigned N) const {
2113     addAlignedMemoryOperands(Inst, N);
2114   }
2115
2116   void addDupAlignedMemory16Operands(MCInst &Inst, unsigned N) const {
2117     addAlignedMemoryOperands(Inst, N);
2118   }
2119
2120   void addAlignedMemory32Operands(MCInst &Inst, unsigned N) const {
2121     addAlignedMemoryOperands(Inst, N);
2122   }
2123
2124   void addDupAlignedMemory32Operands(MCInst &Inst, unsigned N) const {
2125     addAlignedMemoryOperands(Inst, N);
2126   }
2127
2128   void addAlignedMemory64Operands(MCInst &Inst, unsigned N) const {
2129     addAlignedMemoryOperands(Inst, N);
2130   }
2131
2132   void addDupAlignedMemory64Operands(MCInst &Inst, unsigned N) const {
2133     addAlignedMemoryOperands(Inst, N);
2134   }
2135
2136   void addAlignedMemory64or128Operands(MCInst &Inst, unsigned N) const {
2137     addAlignedMemoryOperands(Inst, N);
2138   }
2139
2140   void addDupAlignedMemory64or128Operands(MCInst &Inst, unsigned N) const {
2141     addAlignedMemoryOperands(Inst, N);
2142   }
2143
2144   void addAlignedMemory64or128or256Operands(MCInst &Inst, unsigned N) const {
2145     addAlignedMemoryOperands(Inst, N);
2146   }
2147
2148   void addAddrMode2Operands(MCInst &Inst, unsigned N) const {
2149     assert(N == 3 && "Invalid number of operands!");
2150     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2151     if (!Memory.OffsetRegNum) {
2152       ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2153       // Special case for #-0
2154       if (Val == INT32_MIN) Val = 0;
2155       if (Val < 0) Val = -Val;
2156       Val = ARM_AM::getAM2Opc(AddSub, Val, ARM_AM::no_shift);
2157     } else {
2158       // For register offset, we encode the shift type and negation flag
2159       // here.
2160       Val = ARM_AM::getAM2Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add,
2161                               Memory.ShiftImm, Memory.ShiftType);
2162     }
2163     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
2164     Inst.addOperand(MCOperand::CreateReg(Memory.OffsetRegNum));
2165     Inst.addOperand(MCOperand::CreateImm(Val));
2166   }
2167
2168   void addAM2OffsetImmOperands(MCInst &Inst, unsigned N) const {
2169     assert(N == 2 && "Invalid number of operands!");
2170     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2171     assert(CE && "non-constant AM2OffsetImm operand!");
2172     int32_t Val = CE->getValue();
2173     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2174     // Special case for #-0
2175     if (Val == INT32_MIN) Val = 0;
2176     if (Val < 0) Val = -Val;
2177     Val = ARM_AM::getAM2Opc(AddSub, Val, ARM_AM::no_shift);
2178     Inst.addOperand(MCOperand::CreateReg(0));
2179     Inst.addOperand(MCOperand::CreateImm(Val));
2180   }
2181
2182   void addAddrMode3Operands(MCInst &Inst, unsigned N) const {
2183     assert(N == 3 && "Invalid number of operands!");
2184     // If we have an immediate that's not a constant, treat it as a label
2185     // reference needing a fixup. If it is a constant, it's something else
2186     // and we reject it.
2187     if (isImm()) {
2188       Inst.addOperand(MCOperand::CreateExpr(getImm()));
2189       Inst.addOperand(MCOperand::CreateReg(0));
2190       Inst.addOperand(MCOperand::CreateImm(0));
2191       return;
2192     }
2193
2194     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2195     if (!Memory.OffsetRegNum) {
2196       ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2197       // Special case for #-0
2198       if (Val == INT32_MIN) Val = 0;
2199       if (Val < 0) Val = -Val;
2200       Val = ARM_AM::getAM3Opc(AddSub, Val);
2201     } else {
2202       // For register offset, we encode the shift type and negation flag
2203       // here.
2204       Val = ARM_AM::getAM3Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add, 0);
2205     }
2206     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
2207     Inst.addOperand(MCOperand::CreateReg(Memory.OffsetRegNum));
2208     Inst.addOperand(MCOperand::CreateImm(Val));
2209   }
2210
2211   void addAM3OffsetOperands(MCInst &Inst, unsigned N) const {
2212     assert(N == 2 && "Invalid number of operands!");
2213     if (Kind == k_PostIndexRegister) {
2214       int32_t Val =
2215         ARM_AM::getAM3Opc(PostIdxReg.isAdd ? ARM_AM::add : ARM_AM::sub, 0);
2216       Inst.addOperand(MCOperand::CreateReg(PostIdxReg.RegNum));
2217       Inst.addOperand(MCOperand::CreateImm(Val));
2218       return;
2219     }
2220
2221     // Constant offset.
2222     const MCConstantExpr *CE = static_cast<const MCConstantExpr*>(getImm());
2223     int32_t Val = CE->getValue();
2224     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2225     // Special case for #-0
2226     if (Val == INT32_MIN) Val = 0;
2227     if (Val < 0) Val = -Val;
2228     Val = ARM_AM::getAM3Opc(AddSub, Val);
2229     Inst.addOperand(MCOperand::CreateReg(0));
2230     Inst.addOperand(MCOperand::CreateImm(Val));
2231   }
2232
2233   void addAddrMode5Operands(MCInst &Inst, unsigned N) const {
2234     assert(N == 2 && "Invalid number of operands!");
2235     // If we have an immediate that's not a constant, treat it as a label
2236     // reference needing a fixup. If it is a constant, it's something else
2237     // and we reject it.
2238     if (isImm()) {
2239       Inst.addOperand(MCOperand::CreateExpr(getImm()));
2240       Inst.addOperand(MCOperand::CreateImm(0));
2241       return;
2242     }
2243
2244     // The lower two bits are always zero and as such are not encoded.
2245     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 4 : 0;
2246     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2247     // Special case for #-0
2248     if (Val == INT32_MIN) Val = 0;
2249     if (Val < 0) Val = -Val;
2250     Val = ARM_AM::getAM5Opc(AddSub, Val);
2251     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
2252     Inst.addOperand(MCOperand::CreateImm(Val));
2253   }
2254
2255   void addMemImm8s4OffsetOperands(MCInst &Inst, unsigned N) const {
2256     assert(N == 2 && "Invalid number of operands!");
2257     // If we have an immediate that's not a constant, treat it as a label
2258     // reference needing a fixup. If it is a constant, it's something else
2259     // and we reject it.
2260     if (isImm()) {
2261       Inst.addOperand(MCOperand::CreateExpr(getImm()));
2262       Inst.addOperand(MCOperand::CreateImm(0));
2263       return;
2264     }
2265
2266     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2267     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
2268     Inst.addOperand(MCOperand::CreateImm(Val));
2269   }
2270
2271   void addMemImm0_1020s4OffsetOperands(MCInst &Inst, unsigned N) const {
2272     assert(N == 2 && "Invalid number of operands!");
2273     // The lower two bits are always zero and as such are not encoded.
2274     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 4 : 0;
2275     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
2276     Inst.addOperand(MCOperand::CreateImm(Val));
2277   }
2278
2279   void addMemImm8OffsetOperands(MCInst &Inst, unsigned N) const {
2280     assert(N == 2 && "Invalid number of operands!");
2281     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2282     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
2283     Inst.addOperand(MCOperand::CreateImm(Val));
2284   }
2285
2286   void addMemPosImm8OffsetOperands(MCInst &Inst, unsigned N) const {
2287     addMemImm8OffsetOperands(Inst, N);
2288   }
2289
2290   void addMemNegImm8OffsetOperands(MCInst &Inst, unsigned N) const {
2291     addMemImm8OffsetOperands(Inst, N);
2292   }
2293
2294   void addMemUImm12OffsetOperands(MCInst &Inst, unsigned N) const {
2295     assert(N == 2 && "Invalid number of operands!");
2296     // If this is an immediate, it's a label reference.
2297     if (isImm()) {
2298       addExpr(Inst, getImm());
2299       Inst.addOperand(MCOperand::CreateImm(0));
2300       return;
2301     }
2302
2303     // Otherwise, it's a normal memory reg+offset.
2304     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2305     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
2306     Inst.addOperand(MCOperand::CreateImm(Val));
2307   }
2308
2309   void addMemImm12OffsetOperands(MCInst &Inst, unsigned N) const {
2310     assert(N == 2 && "Invalid number of operands!");
2311     // If this is an immediate, it's a label reference.
2312     if (isImm()) {
2313       addExpr(Inst, getImm());
2314       Inst.addOperand(MCOperand::CreateImm(0));
2315       return;
2316     }
2317
2318     // Otherwise, it's a normal memory reg+offset.
2319     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2320     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
2321     Inst.addOperand(MCOperand::CreateImm(Val));
2322   }
2323
2324   void addMemTBBOperands(MCInst &Inst, unsigned N) const {
2325     assert(N == 2 && "Invalid number of operands!");
2326     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
2327     Inst.addOperand(MCOperand::CreateReg(Memory.OffsetRegNum));
2328   }
2329
2330   void addMemTBHOperands(MCInst &Inst, unsigned N) const {
2331     assert(N == 2 && "Invalid number of operands!");
2332     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
2333     Inst.addOperand(MCOperand::CreateReg(Memory.OffsetRegNum));
2334   }
2335
2336   void addMemRegOffsetOperands(MCInst &Inst, unsigned N) const {
2337     assert(N == 3 && "Invalid number of operands!");
2338     unsigned Val =
2339       ARM_AM::getAM2Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add,
2340                         Memory.ShiftImm, Memory.ShiftType);
2341     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
2342     Inst.addOperand(MCOperand::CreateReg(Memory.OffsetRegNum));
2343     Inst.addOperand(MCOperand::CreateImm(Val));
2344   }
2345
2346   void addT2MemRegOffsetOperands(MCInst &Inst, unsigned N) const {
2347     assert(N == 3 && "Invalid number of operands!");
2348     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
2349     Inst.addOperand(MCOperand::CreateReg(Memory.OffsetRegNum));
2350     Inst.addOperand(MCOperand::CreateImm(Memory.ShiftImm));
2351   }
2352
2353   void addMemThumbRROperands(MCInst &Inst, unsigned N) const {
2354     assert(N == 2 && "Invalid number of operands!");
2355     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
2356     Inst.addOperand(MCOperand::CreateReg(Memory.OffsetRegNum));
2357   }
2358
2359   void addMemThumbRIs4Operands(MCInst &Inst, unsigned N) const {
2360     assert(N == 2 && "Invalid number of operands!");
2361     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 4) : 0;
2362     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
2363     Inst.addOperand(MCOperand::CreateImm(Val));
2364   }
2365
2366   void addMemThumbRIs2Operands(MCInst &Inst, unsigned N) const {
2367     assert(N == 2 && "Invalid number of operands!");
2368     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 2) : 0;
2369     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
2370     Inst.addOperand(MCOperand::CreateImm(Val));
2371   }
2372
2373   void addMemThumbRIs1Operands(MCInst &Inst, unsigned N) const {
2374     assert(N == 2 && "Invalid number of operands!");
2375     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue()) : 0;
2376     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
2377     Inst.addOperand(MCOperand::CreateImm(Val));
2378   }
2379
2380   void addMemThumbSPIOperands(MCInst &Inst, unsigned N) const {
2381     assert(N == 2 && "Invalid number of operands!");
2382     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 4) : 0;
2383     Inst.addOperand(MCOperand::CreateReg(Memory.BaseRegNum));
2384     Inst.addOperand(MCOperand::CreateImm(Val));
2385   }
2386
2387   void addPostIdxImm8Operands(MCInst &Inst, unsigned N) const {
2388     assert(N == 1 && "Invalid number of operands!");
2389     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2390     assert(CE && "non-constant post-idx-imm8 operand!");
2391     int Imm = CE->getValue();
2392     bool isAdd = Imm >= 0;
2393     if (Imm == INT32_MIN) Imm = 0;
2394     Imm = (Imm < 0 ? -Imm : Imm) | (int)isAdd << 8;
2395     Inst.addOperand(MCOperand::CreateImm(Imm));
2396   }
2397
2398   void addPostIdxImm8s4Operands(MCInst &Inst, unsigned N) const {
2399     assert(N == 1 && "Invalid number of operands!");
2400     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2401     assert(CE && "non-constant post-idx-imm8s4 operand!");
2402     int Imm = CE->getValue();
2403     bool isAdd = Imm >= 0;
2404     if (Imm == INT32_MIN) Imm = 0;
2405     // Immediate is scaled by 4.
2406     Imm = ((Imm < 0 ? -Imm : Imm) / 4) | (int)isAdd << 8;
2407     Inst.addOperand(MCOperand::CreateImm(Imm));
2408   }
2409
2410   void addPostIdxRegOperands(MCInst &Inst, unsigned N) const {
2411     assert(N == 2 && "Invalid number of operands!");
2412     Inst.addOperand(MCOperand::CreateReg(PostIdxReg.RegNum));
2413     Inst.addOperand(MCOperand::CreateImm(PostIdxReg.isAdd));
2414   }
2415
2416   void addPostIdxRegShiftedOperands(MCInst &Inst, unsigned N) const {
2417     assert(N == 2 && "Invalid number of operands!");
2418     Inst.addOperand(MCOperand::CreateReg(PostIdxReg.RegNum));
2419     // The sign, shift type, and shift amount are encoded in a single operand
2420     // using the AM2 encoding helpers.
2421     ARM_AM::AddrOpc opc = PostIdxReg.isAdd ? ARM_AM::add : ARM_AM::sub;
2422     unsigned Imm = ARM_AM::getAM2Opc(opc, PostIdxReg.ShiftImm,
2423                                      PostIdxReg.ShiftTy);
2424     Inst.addOperand(MCOperand::CreateImm(Imm));
2425   }
2426
2427   void addMSRMaskOperands(MCInst &Inst, unsigned N) const {
2428     assert(N == 1 && "Invalid number of operands!");
2429     Inst.addOperand(MCOperand::CreateImm(unsigned(getMSRMask())));
2430   }
2431
2432   void addBankedRegOperands(MCInst &Inst, unsigned N) const {
2433     assert(N == 1 && "Invalid number of operands!");
2434     Inst.addOperand(MCOperand::CreateImm(unsigned(getBankedReg())));
2435   }
2436
2437   void addProcIFlagsOperands(MCInst &Inst, unsigned N) const {
2438     assert(N == 1 && "Invalid number of operands!");
2439     Inst.addOperand(MCOperand::CreateImm(unsigned(getProcIFlags())));
2440   }
2441
2442   void addVecListOperands(MCInst &Inst, unsigned N) const {
2443     assert(N == 1 && "Invalid number of operands!");
2444     Inst.addOperand(MCOperand::CreateReg(VectorList.RegNum));
2445   }
2446
2447   void addVecListIndexedOperands(MCInst &Inst, unsigned N) const {
2448     assert(N == 2 && "Invalid number of operands!");
2449     Inst.addOperand(MCOperand::CreateReg(VectorList.RegNum));
2450     Inst.addOperand(MCOperand::CreateImm(VectorList.LaneIndex));
2451   }
2452
2453   void addVectorIndex8Operands(MCInst &Inst, unsigned N) const {
2454     assert(N == 1 && "Invalid number of operands!");
2455     Inst.addOperand(MCOperand::CreateImm(getVectorIndex()));
2456   }
2457
2458   void addVectorIndex16Operands(MCInst &Inst, unsigned N) const {
2459     assert(N == 1 && "Invalid number of operands!");
2460     Inst.addOperand(MCOperand::CreateImm(getVectorIndex()));
2461   }
2462
2463   void addVectorIndex32Operands(MCInst &Inst, unsigned N) const {
2464     assert(N == 1 && "Invalid number of operands!");
2465     Inst.addOperand(MCOperand::CreateImm(getVectorIndex()));
2466   }
2467
2468   void addNEONi8splatOperands(MCInst &Inst, unsigned N) const {
2469     assert(N == 1 && "Invalid number of operands!");
2470     // The immediate encodes the type of constant as well as the value.
2471     // Mask in that this is an i8 splat.
2472     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2473     Inst.addOperand(MCOperand::CreateImm(CE->getValue() | 0xe00));
2474   }
2475
2476   void addNEONi16splatOperands(MCInst &Inst, unsigned N) const {
2477     assert(N == 1 && "Invalid number of operands!");
2478     // The immediate encodes the type of constant as well as the value.
2479     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2480     unsigned Value = CE->getValue();
2481     Value = ARM_AM::encodeNEONi16splat(Value);
2482     Inst.addOperand(MCOperand::CreateImm(Value));
2483   }
2484
2485   void addNEONi16splatNotOperands(MCInst &Inst, unsigned N) const {
2486     assert(N == 1 && "Invalid number of operands!");
2487     // The immediate encodes the type of constant as well as the value.
2488     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2489     unsigned Value = CE->getValue();
2490     Value = ARM_AM::encodeNEONi16splat(~Value & 0xffff);
2491     Inst.addOperand(MCOperand::CreateImm(Value));
2492   }
2493
2494   void addNEONi32splatOperands(MCInst &Inst, unsigned N) const {
2495     assert(N == 1 && "Invalid number of operands!");
2496     // The immediate encodes the type of constant as well as the value.
2497     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2498     unsigned Value = CE->getValue();
2499     Value = ARM_AM::encodeNEONi32splat(Value);
2500     Inst.addOperand(MCOperand::CreateImm(Value));
2501   }
2502
2503   void addNEONi32splatNotOperands(MCInst &Inst, unsigned N) const {
2504     assert(N == 1 && "Invalid number of operands!");
2505     // The immediate encodes the type of constant as well as the value.
2506     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2507     unsigned Value = CE->getValue();
2508     Value = ARM_AM::encodeNEONi32splat(~Value);
2509     Inst.addOperand(MCOperand::CreateImm(Value));
2510   }
2511
2512   void addNEONinvByteReplicateOperands(MCInst &Inst, unsigned N) const {
2513     assert(N == 1 && "Invalid number of operands!");
2514     // The immediate encodes the type of constant as well as the value.
2515     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2516     unsigned Value = CE->getValue();
2517     assert((Inst.getOpcode() == ARM::VMOVv8i8 ||
2518             Inst.getOpcode() == ARM::VMOVv16i8) &&
2519            "All vmvn instructions that wants to replicate non-zero byte "
2520            "always must be replaced with VMOVv8i8 or VMOVv16i8.");
2521     unsigned B = ((~Value) & 0xff);
2522     B |= 0xe00; // cmode = 0b1110
2523     Inst.addOperand(MCOperand::CreateImm(B));
2524   }
2525   void addNEONi32vmovOperands(MCInst &Inst, unsigned N) const {
2526     assert(N == 1 && "Invalid number of operands!");
2527     // The immediate encodes the type of constant as well as the value.
2528     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2529     unsigned Value = CE->getValue();
2530     if (Value >= 256 && Value <= 0xffff)
2531       Value = (Value >> 8) | ((Value & 0xff) ? 0xc00 : 0x200);
2532     else if (Value > 0xffff && Value <= 0xffffff)
2533       Value = (Value >> 16) | ((Value & 0xff) ? 0xd00 : 0x400);
2534     else if (Value > 0xffffff)
2535       Value = (Value >> 24) | 0x600;
2536     Inst.addOperand(MCOperand::CreateImm(Value));
2537   }
2538
2539   void addNEONvmovByteReplicateOperands(MCInst &Inst, unsigned N) const {
2540     assert(N == 1 && "Invalid number of operands!");
2541     // The immediate encodes the type of constant as well as the value.
2542     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2543     unsigned Value = CE->getValue();
2544     assert((Inst.getOpcode() == ARM::VMOVv8i8 ||
2545             Inst.getOpcode() == ARM::VMOVv16i8) &&
2546            "All instructions that wants to replicate non-zero byte "
2547            "always must be replaced with VMOVv8i8 or VMOVv16i8.");
2548     unsigned B = Value & 0xff;
2549     B |= 0xe00; // cmode = 0b1110
2550     Inst.addOperand(MCOperand::CreateImm(B));
2551   }
2552   void addNEONi32vmovNegOperands(MCInst &Inst, unsigned N) const {
2553     assert(N == 1 && "Invalid number of operands!");
2554     // The immediate encodes the type of constant as well as the value.
2555     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2556     unsigned Value = ~CE->getValue();
2557     if (Value >= 256 && Value <= 0xffff)
2558       Value = (Value >> 8) | ((Value & 0xff) ? 0xc00 : 0x200);
2559     else if (Value > 0xffff && Value <= 0xffffff)
2560       Value = (Value >> 16) | ((Value & 0xff) ? 0xd00 : 0x400);
2561     else if (Value > 0xffffff)
2562       Value = (Value >> 24) | 0x600;
2563     Inst.addOperand(MCOperand::CreateImm(Value));
2564   }
2565
2566   void addNEONi64splatOperands(MCInst &Inst, unsigned N) const {
2567     assert(N == 1 && "Invalid number of operands!");
2568     // The immediate encodes the type of constant as well as the value.
2569     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2570     uint64_t Value = CE->getValue();
2571     unsigned Imm = 0;
2572     for (unsigned i = 0; i < 8; ++i, Value >>= 8) {
2573       Imm |= (Value & 1) << i;
2574     }
2575     Inst.addOperand(MCOperand::CreateImm(Imm | 0x1e00));
2576   }
2577
2578   void print(raw_ostream &OS) const override;
2579
2580   static std::unique_ptr<ARMOperand> CreateITMask(unsigned Mask, SMLoc S) {
2581     auto Op = make_unique<ARMOperand>(k_ITCondMask);
2582     Op->ITMask.Mask = Mask;
2583     Op->StartLoc = S;
2584     Op->EndLoc = S;
2585     return Op;
2586   }
2587
2588   static std::unique_ptr<ARMOperand> CreateCondCode(ARMCC::CondCodes CC,
2589                                                     SMLoc S) {
2590     auto Op = make_unique<ARMOperand>(k_CondCode);
2591     Op->CC.Val = CC;
2592     Op->StartLoc = S;
2593     Op->EndLoc = S;
2594     return Op;
2595   }
2596
2597   static std::unique_ptr<ARMOperand> CreateCoprocNum(unsigned CopVal, SMLoc S) {
2598     auto Op = make_unique<ARMOperand>(k_CoprocNum);
2599     Op->Cop.Val = CopVal;
2600     Op->StartLoc = S;
2601     Op->EndLoc = S;
2602     return Op;
2603   }
2604
2605   static std::unique_ptr<ARMOperand> CreateCoprocReg(unsigned CopVal, SMLoc S) {
2606     auto Op = make_unique<ARMOperand>(k_CoprocReg);
2607     Op->Cop.Val = CopVal;
2608     Op->StartLoc = S;
2609     Op->EndLoc = S;
2610     return Op;
2611   }
2612
2613   static std::unique_ptr<ARMOperand> CreateCoprocOption(unsigned Val, SMLoc S,
2614                                                         SMLoc E) {
2615     auto Op = make_unique<ARMOperand>(k_CoprocOption);
2616     Op->Cop.Val = Val;
2617     Op->StartLoc = S;
2618     Op->EndLoc = E;
2619     return Op;
2620   }
2621
2622   static std::unique_ptr<ARMOperand> CreateCCOut(unsigned RegNum, SMLoc S) {
2623     auto Op = make_unique<ARMOperand>(k_CCOut);
2624     Op->Reg.RegNum = RegNum;
2625     Op->StartLoc = S;
2626     Op->EndLoc = S;
2627     return Op;
2628   }
2629
2630   static std::unique_ptr<ARMOperand> CreateToken(StringRef Str, SMLoc S) {
2631     auto Op = make_unique<ARMOperand>(k_Token);
2632     Op->Tok.Data = Str.data();
2633     Op->Tok.Length = Str.size();
2634     Op->StartLoc = S;
2635     Op->EndLoc = S;
2636     return Op;
2637   }
2638
2639   static std::unique_ptr<ARMOperand> CreateReg(unsigned RegNum, SMLoc S,
2640                                                SMLoc E) {
2641     auto Op = make_unique<ARMOperand>(k_Register);
2642     Op->Reg.RegNum = RegNum;
2643     Op->StartLoc = S;
2644     Op->EndLoc = E;
2645     return Op;
2646   }
2647
2648   static std::unique_ptr<ARMOperand>
2649   CreateShiftedRegister(ARM_AM::ShiftOpc ShTy, unsigned SrcReg,
2650                         unsigned ShiftReg, unsigned ShiftImm, SMLoc S,
2651                         SMLoc E) {
2652     auto Op = make_unique<ARMOperand>(k_ShiftedRegister);
2653     Op->RegShiftedReg.ShiftTy = ShTy;
2654     Op->RegShiftedReg.SrcReg = SrcReg;
2655     Op->RegShiftedReg.ShiftReg = ShiftReg;
2656     Op->RegShiftedReg.ShiftImm = ShiftImm;
2657     Op->StartLoc = S;
2658     Op->EndLoc = E;
2659     return Op;
2660   }
2661
2662   static std::unique_ptr<ARMOperand>
2663   CreateShiftedImmediate(ARM_AM::ShiftOpc ShTy, unsigned SrcReg,
2664                          unsigned ShiftImm, SMLoc S, SMLoc E) {
2665     auto Op = make_unique<ARMOperand>(k_ShiftedImmediate);
2666     Op->RegShiftedImm.ShiftTy = ShTy;
2667     Op->RegShiftedImm.SrcReg = SrcReg;
2668     Op->RegShiftedImm.ShiftImm = ShiftImm;
2669     Op->StartLoc = S;
2670     Op->EndLoc = E;
2671     return Op;
2672   }
2673
2674   static std::unique_ptr<ARMOperand> CreateShifterImm(bool isASR, unsigned Imm,
2675                                                       SMLoc S, SMLoc E) {
2676     auto Op = make_unique<ARMOperand>(k_ShifterImmediate);
2677     Op->ShifterImm.isASR = isASR;
2678     Op->ShifterImm.Imm = Imm;
2679     Op->StartLoc = S;
2680     Op->EndLoc = E;
2681     return Op;
2682   }
2683
2684   static std::unique_ptr<ARMOperand> CreateRotImm(unsigned Imm, SMLoc S,
2685                                                   SMLoc E) {
2686     auto Op = make_unique<ARMOperand>(k_RotateImmediate);
2687     Op->RotImm.Imm = Imm;
2688     Op->StartLoc = S;
2689     Op->EndLoc = E;
2690     return Op;
2691   }
2692
2693   static std::unique_ptr<ARMOperand> CreateModImm(unsigned Bits, unsigned Rot,
2694                                                   SMLoc S, SMLoc E) {
2695     auto Op = make_unique<ARMOperand>(k_ModifiedImmediate);
2696     Op->ModImm.Bits = Bits;
2697     Op->ModImm.Rot = Rot;
2698     Op->StartLoc = S;
2699     Op->EndLoc = E;
2700     return Op;
2701   }
2702
2703   static std::unique_ptr<ARMOperand>
2704   CreateBitfield(unsigned LSB, unsigned Width, SMLoc S, SMLoc E) {
2705     auto Op = make_unique<ARMOperand>(k_BitfieldDescriptor);
2706     Op->Bitfield.LSB = LSB;
2707     Op->Bitfield.Width = Width;
2708     Op->StartLoc = S;
2709     Op->EndLoc = E;
2710     return Op;
2711   }
2712
2713   static std::unique_ptr<ARMOperand>
2714   CreateRegList(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs,
2715                 SMLoc StartLoc, SMLoc EndLoc) {
2716     assert (Regs.size() > 0 && "RegList contains no registers?");
2717     KindTy Kind = k_RegisterList;
2718
2719     if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Regs.front().second))
2720       Kind = k_DPRRegisterList;
2721     else if (ARMMCRegisterClasses[ARM::SPRRegClassID].
2722              contains(Regs.front().second))
2723       Kind = k_SPRRegisterList;
2724
2725     // Sort based on the register encoding values.
2726     array_pod_sort(Regs.begin(), Regs.end());
2727
2728     auto Op = make_unique<ARMOperand>(Kind);
2729     for (SmallVectorImpl<std::pair<unsigned, unsigned> >::const_iterator
2730            I = Regs.begin(), E = Regs.end(); I != E; ++I)
2731       Op->Registers.push_back(I->second);
2732     Op->StartLoc = StartLoc;
2733     Op->EndLoc = EndLoc;
2734     return Op;
2735   }
2736
2737   static std::unique_ptr<ARMOperand> CreateVectorList(unsigned RegNum,
2738                                                       unsigned Count,
2739                                                       bool isDoubleSpaced,
2740                                                       SMLoc S, SMLoc E) {
2741     auto Op = make_unique<ARMOperand>(k_VectorList);
2742     Op->VectorList.RegNum = RegNum;
2743     Op->VectorList.Count = Count;
2744     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
2745     Op->StartLoc = S;
2746     Op->EndLoc = E;
2747     return Op;
2748   }
2749
2750   static std::unique_ptr<ARMOperand>
2751   CreateVectorListAllLanes(unsigned RegNum, unsigned Count, bool isDoubleSpaced,
2752                            SMLoc S, SMLoc E) {
2753     auto Op = make_unique<ARMOperand>(k_VectorListAllLanes);
2754     Op->VectorList.RegNum = RegNum;
2755     Op->VectorList.Count = Count;
2756     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
2757     Op->StartLoc = S;
2758     Op->EndLoc = E;
2759     return Op;
2760   }
2761
2762   static std::unique_ptr<ARMOperand>
2763   CreateVectorListIndexed(unsigned RegNum, unsigned Count, unsigned Index,
2764                           bool isDoubleSpaced, SMLoc S, SMLoc E) {
2765     auto Op = make_unique<ARMOperand>(k_VectorListIndexed);
2766     Op->VectorList.RegNum = RegNum;
2767     Op->VectorList.Count = Count;
2768     Op->VectorList.LaneIndex = Index;
2769     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
2770     Op->StartLoc = S;
2771     Op->EndLoc = E;
2772     return Op;
2773   }
2774
2775   static std::unique_ptr<ARMOperand>
2776   CreateVectorIndex(unsigned Idx, SMLoc S, SMLoc E, MCContext &Ctx) {
2777     auto Op = make_unique<ARMOperand>(k_VectorIndex);
2778     Op->VectorIndex.Val = Idx;
2779     Op->StartLoc = S;
2780     Op->EndLoc = E;
2781     return Op;
2782   }
2783
2784   static std::unique_ptr<ARMOperand> CreateImm(const MCExpr *Val, SMLoc S,
2785                                                SMLoc E) {
2786     auto Op = make_unique<ARMOperand>(k_Immediate);
2787     Op->Imm.Val = Val;
2788     Op->StartLoc = S;
2789     Op->EndLoc = E;
2790     return Op;
2791   }
2792
2793   static std::unique_ptr<ARMOperand>
2794   CreateMem(unsigned BaseRegNum, const MCConstantExpr *OffsetImm,
2795             unsigned OffsetRegNum, ARM_AM::ShiftOpc ShiftType,
2796             unsigned ShiftImm, unsigned Alignment, bool isNegative, SMLoc S,
2797             SMLoc E, SMLoc AlignmentLoc = SMLoc()) {
2798     auto Op = make_unique<ARMOperand>(k_Memory);
2799     Op->Memory.BaseRegNum = BaseRegNum;
2800     Op->Memory.OffsetImm = OffsetImm;
2801     Op->Memory.OffsetRegNum = OffsetRegNum;
2802     Op->Memory.ShiftType = ShiftType;
2803     Op->Memory.ShiftImm = ShiftImm;
2804     Op->Memory.Alignment = Alignment;
2805     Op->Memory.isNegative = isNegative;
2806     Op->StartLoc = S;
2807     Op->EndLoc = E;
2808     Op->AlignmentLoc = AlignmentLoc;
2809     return Op;
2810   }
2811
2812   static std::unique_ptr<ARMOperand>
2813   CreatePostIdxReg(unsigned RegNum, bool isAdd, ARM_AM::ShiftOpc ShiftTy,
2814                    unsigned ShiftImm, SMLoc S, SMLoc E) {
2815     auto Op = make_unique<ARMOperand>(k_PostIndexRegister);
2816     Op->PostIdxReg.RegNum = RegNum;
2817     Op->PostIdxReg.isAdd = isAdd;
2818     Op->PostIdxReg.ShiftTy = ShiftTy;
2819     Op->PostIdxReg.ShiftImm = ShiftImm;
2820     Op->StartLoc = S;
2821     Op->EndLoc = E;
2822     return Op;
2823   }
2824
2825   static std::unique_ptr<ARMOperand> CreateMemBarrierOpt(ARM_MB::MemBOpt Opt,
2826                                                          SMLoc S) {
2827     auto Op = make_unique<ARMOperand>(k_MemBarrierOpt);
2828     Op->MBOpt.Val = Opt;
2829     Op->StartLoc = S;
2830     Op->EndLoc = S;
2831     return Op;
2832   }
2833
2834   static std::unique_ptr<ARMOperand>
2835   CreateInstSyncBarrierOpt(ARM_ISB::InstSyncBOpt Opt, SMLoc S) {
2836     auto Op = make_unique<ARMOperand>(k_InstSyncBarrierOpt);
2837     Op->ISBOpt.Val = Opt;
2838     Op->StartLoc = S;
2839     Op->EndLoc = S;
2840     return Op;
2841   }
2842
2843   static std::unique_ptr<ARMOperand> CreateProcIFlags(ARM_PROC::IFlags IFlags,
2844                                                       SMLoc S) {
2845     auto Op = make_unique<ARMOperand>(k_ProcIFlags);
2846     Op->IFlags.Val = IFlags;
2847     Op->StartLoc = S;
2848     Op->EndLoc = S;
2849     return Op;
2850   }
2851
2852   static std::unique_ptr<ARMOperand> CreateMSRMask(unsigned MMask, SMLoc S) {
2853     auto Op = make_unique<ARMOperand>(k_MSRMask);
2854     Op->MMask.Val = MMask;
2855     Op->StartLoc = S;
2856     Op->EndLoc = S;
2857     return Op;
2858   }
2859
2860   static std::unique_ptr<ARMOperand> CreateBankedReg(unsigned Reg, SMLoc S) {
2861     auto Op = make_unique<ARMOperand>(k_BankedReg);
2862     Op->BankedReg.Val = Reg;
2863     Op->StartLoc = S;
2864     Op->EndLoc = S;
2865     return Op;
2866   }
2867 };
2868
2869 } // end anonymous namespace.
2870
2871 void ARMOperand::print(raw_ostream &OS) const {
2872   switch (Kind) {
2873   case k_CondCode:
2874     OS << "<ARMCC::" << ARMCondCodeToString(getCondCode()) << ">";
2875     break;
2876   case k_CCOut:
2877     OS << "<ccout " << getReg() << ">";
2878     break;
2879   case k_ITCondMask: {
2880     static const char *const MaskStr[] = {
2881       "()", "(t)", "(e)", "(tt)", "(et)", "(te)", "(ee)", "(ttt)", "(ett)",
2882       "(tet)", "(eet)", "(tte)", "(ete)", "(tee)", "(eee)"
2883     };
2884     assert((ITMask.Mask & 0xf) == ITMask.Mask);
2885     OS << "<it-mask " << MaskStr[ITMask.Mask] << ">";
2886     break;
2887   }
2888   case k_CoprocNum:
2889     OS << "<coprocessor number: " << getCoproc() << ">";
2890     break;
2891   case k_CoprocReg:
2892     OS << "<coprocessor register: " << getCoproc() << ">";
2893     break;
2894   case k_CoprocOption:
2895     OS << "<coprocessor option: " << CoprocOption.Val << ">";
2896     break;
2897   case k_MSRMask:
2898     OS << "<mask: " << getMSRMask() << ">";
2899     break;
2900   case k_BankedReg:
2901     OS << "<banked reg: " << getBankedReg() << ">";
2902     break;
2903   case k_Immediate:
2904     getImm()->print(OS);
2905     break;
2906   case k_MemBarrierOpt:
2907     OS << "<ARM_MB::" << MemBOptToString(getMemBarrierOpt(), false) << ">";
2908     break;
2909   case k_InstSyncBarrierOpt:
2910     OS << "<ARM_ISB::" << InstSyncBOptToString(getInstSyncBarrierOpt()) << ">";
2911     break;
2912   case k_Memory:
2913     OS << "<memory "
2914        << " base:" << Memory.BaseRegNum;
2915     OS << ">";
2916     break;
2917   case k_PostIndexRegister:
2918     OS << "post-idx register " << (PostIdxReg.isAdd ? "" : "-")
2919        << PostIdxReg.RegNum;
2920     if (PostIdxReg.ShiftTy != ARM_AM::no_shift)
2921       OS << ARM_AM::getShiftOpcStr(PostIdxReg.ShiftTy) << " "
2922          << PostIdxReg.ShiftImm;
2923     OS << ">";
2924     break;
2925   case k_ProcIFlags: {
2926     OS << "<ARM_PROC::";
2927     unsigned IFlags = getProcIFlags();
2928     for (int i=2; i >= 0; --i)
2929       if (IFlags & (1 << i))
2930         OS << ARM_PROC::IFlagsToString(1 << i);
2931     OS << ">";
2932     break;
2933   }
2934   case k_Register:
2935     OS << "<register " << getReg() << ">";
2936     break;
2937   case k_ShifterImmediate:
2938     OS << "<shift " << (ShifterImm.isASR ? "asr" : "lsl")
2939        << " #" << ShifterImm.Imm << ">";
2940     break;
2941   case k_ShiftedRegister:
2942     OS << "<so_reg_reg "
2943        << RegShiftedReg.SrcReg << " "
2944        << ARM_AM::getShiftOpcStr(RegShiftedReg.ShiftTy)
2945        << " " << RegShiftedReg.ShiftReg << ">";
2946     break;
2947   case k_ShiftedImmediate:
2948     OS << "<so_reg_imm "
2949        << RegShiftedImm.SrcReg << " "
2950        << ARM_AM::getShiftOpcStr(RegShiftedImm.ShiftTy)
2951        << " #" << RegShiftedImm.ShiftImm << ">";
2952     break;
2953   case k_RotateImmediate:
2954     OS << "<ror " << " #" << (RotImm.Imm * 8) << ">";
2955     break;
2956   case k_ModifiedImmediate:
2957     OS << "<mod_imm #" << ModImm.Bits << ", #"
2958        <<  ModImm.Rot << ")>";
2959     break;
2960   case k_BitfieldDescriptor:
2961     OS << "<bitfield " << "lsb: " << Bitfield.LSB
2962        << ", width: " << Bitfield.Width << ">";
2963     break;
2964   case k_RegisterList:
2965   case k_DPRRegisterList:
2966   case k_SPRRegisterList: {
2967     OS << "<register_list ";
2968
2969     const SmallVectorImpl<unsigned> &RegList = getRegList();
2970     for (SmallVectorImpl<unsigned>::const_iterator
2971            I = RegList.begin(), E = RegList.end(); I != E; ) {
2972       OS << *I;
2973       if (++I < E) OS << ", ";
2974     }
2975
2976     OS << ">";
2977     break;
2978   }
2979   case k_VectorList:
2980     OS << "<vector_list " << VectorList.Count << " * "
2981        << VectorList.RegNum << ">";
2982     break;
2983   case k_VectorListAllLanes:
2984     OS << "<vector_list(all lanes) " << VectorList.Count << " * "
2985        << VectorList.RegNum << ">";
2986     break;
2987   case k_VectorListIndexed:
2988     OS << "<vector_list(lane " << VectorList.LaneIndex << ") "
2989        << VectorList.Count << " * " << VectorList.RegNum << ">";
2990     break;
2991   case k_Token:
2992     OS << "'" << getToken() << "'";
2993     break;
2994   case k_VectorIndex:
2995     OS << "<vectorindex " << getVectorIndex() << ">";
2996     break;
2997   }
2998 }
2999
3000 /// @name Auto-generated Match Functions
3001 /// {
3002
3003 static unsigned MatchRegisterName(StringRef Name);
3004
3005 /// }
3006
3007 bool ARMAsmParser::ParseRegister(unsigned &RegNo,
3008                                  SMLoc &StartLoc, SMLoc &EndLoc) {
3009   const AsmToken &Tok = getParser().getTok();
3010   StartLoc = Tok.getLoc();
3011   EndLoc = Tok.getEndLoc();
3012   RegNo = tryParseRegister();
3013
3014   return (RegNo == (unsigned)-1);
3015 }
3016
3017 /// Try to parse a register name.  The token must be an Identifier when called,
3018 /// and if it is a register name the token is eaten and the register number is
3019 /// returned.  Otherwise return -1.
3020 ///
3021 int ARMAsmParser::tryParseRegister() {
3022   MCAsmParser &Parser = getParser();
3023   const AsmToken &Tok = Parser.getTok();
3024   if (Tok.isNot(AsmToken::Identifier)) return -1;
3025
3026   std::string lowerCase = Tok.getString().lower();
3027   unsigned RegNum = MatchRegisterName(lowerCase);
3028   if (!RegNum) {
3029     RegNum = StringSwitch<unsigned>(lowerCase)
3030       .Case("r13", ARM::SP)
3031       .Case("r14", ARM::LR)
3032       .Case("r15", ARM::PC)
3033       .Case("ip", ARM::R12)
3034       // Additional register name aliases for 'gas' compatibility.
3035       .Case("a1", ARM::R0)
3036       .Case("a2", ARM::R1)
3037       .Case("a3", ARM::R2)
3038       .Case("a4", ARM::R3)
3039       .Case("v1", ARM::R4)
3040       .Case("v2", ARM::R5)
3041       .Case("v3", ARM::R6)
3042       .Case("v4", ARM::R7)
3043       .Case("v5", ARM::R8)
3044       .Case("v6", ARM::R9)
3045       .Case("v7", ARM::R10)
3046       .Case("v8", ARM::R11)
3047       .Case("sb", ARM::R9)
3048       .Case("sl", ARM::R10)
3049       .Case("fp", ARM::R11)
3050       .Default(0);
3051   }
3052   if (!RegNum) {
3053     // Check for aliases registered via .req. Canonicalize to lower case.
3054     // That's more consistent since register names are case insensitive, and
3055     // it's how the original entry was passed in from MC/MCParser/AsmParser.
3056     StringMap<unsigned>::const_iterator Entry = RegisterReqs.find(lowerCase);
3057     // If no match, return failure.
3058     if (Entry == RegisterReqs.end())
3059       return -1;
3060     Parser.Lex(); // Eat identifier token.
3061     return Entry->getValue();
3062   }
3063
3064   // Some FPUs only have 16 D registers, so D16-D31 are invalid
3065   if (hasD16() && RegNum >= ARM::D16 && RegNum <= ARM::D31)
3066     return -1;
3067
3068   Parser.Lex(); // Eat identifier token.
3069
3070   return RegNum;
3071 }
3072
3073 // Try to parse a shifter  (e.g., "lsl <amt>"). On success, return 0.
3074 // If a recoverable error occurs, return 1. If an irrecoverable error
3075 // occurs, return -1. An irrecoverable error is one where tokens have been
3076 // consumed in the process of trying to parse the shifter (i.e., when it is
3077 // indeed a shifter operand, but malformed).
3078 int ARMAsmParser::tryParseShiftRegister(OperandVector &Operands) {
3079   MCAsmParser &Parser = getParser();
3080   SMLoc S = Parser.getTok().getLoc();
3081   const AsmToken &Tok = Parser.getTok();
3082   if (Tok.isNot(AsmToken::Identifier))
3083     return -1; 
3084
3085   std::string lowerCase = Tok.getString().lower();
3086   ARM_AM::ShiftOpc ShiftTy = StringSwitch<ARM_AM::ShiftOpc>(lowerCase)
3087       .Case("asl", ARM_AM::lsl)
3088       .Case("lsl", ARM_AM::lsl)
3089       .Case("lsr", ARM_AM::lsr)
3090       .Case("asr", ARM_AM::asr)
3091       .Case("ror", ARM_AM::ror)
3092       .Case("rrx", ARM_AM::rrx)
3093       .Default(ARM_AM::no_shift);
3094
3095   if (ShiftTy == ARM_AM::no_shift)
3096     return 1;
3097
3098   Parser.Lex(); // Eat the operator.
3099
3100   // The source register for the shift has already been added to the
3101   // operand list, so we need to pop it off and combine it into the shifted
3102   // register operand instead.
3103   std::unique_ptr<ARMOperand> PrevOp(
3104       (ARMOperand *)Operands.pop_back_val().release());
3105   if (!PrevOp->isReg())
3106     return Error(PrevOp->getStartLoc(), "shift must be of a register");
3107   int SrcReg = PrevOp->getReg();
3108
3109   SMLoc EndLoc;
3110   int64_t Imm = 0;
3111   int ShiftReg = 0;
3112   if (ShiftTy == ARM_AM::rrx) {
3113     // RRX Doesn't have an explicit shift amount. The encoder expects
3114     // the shift register to be the same as the source register. Seems odd,
3115     // but OK.
3116     ShiftReg = SrcReg;
3117   } else {
3118     // Figure out if this is shifted by a constant or a register (for non-RRX).
3119     if (Parser.getTok().is(AsmToken::Hash) ||
3120         Parser.getTok().is(AsmToken::Dollar)) {
3121       Parser.Lex(); // Eat hash.
3122       SMLoc ImmLoc = Parser.getTok().getLoc();
3123       const MCExpr *ShiftExpr = nullptr;
3124       if (getParser().parseExpression(ShiftExpr, EndLoc)) {
3125         Error(ImmLoc, "invalid immediate shift value");
3126         return -1;
3127       }
3128       // The expression must be evaluatable as an immediate.
3129       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftExpr);
3130       if (!CE) {
3131         Error(ImmLoc, "invalid immediate shift value");
3132         return -1;
3133       }
3134       // Range check the immediate.
3135       // lsl, ror: 0 <= imm <= 31
3136       // lsr, asr: 0 <= imm <= 32
3137       Imm = CE->getValue();
3138       if (Imm < 0 ||
3139           ((ShiftTy == ARM_AM::lsl || ShiftTy == ARM_AM::ror) && Imm > 31) ||
3140           ((ShiftTy == ARM_AM::lsr || ShiftTy == ARM_AM::asr) && Imm > 32)) {
3141         Error(ImmLoc, "immediate shift value out of range");
3142         return -1;
3143       }
3144       // shift by zero is a nop. Always send it through as lsl.
3145       // ('as' compatibility)
3146       if (Imm == 0)
3147         ShiftTy = ARM_AM::lsl;
3148     } else if (Parser.getTok().is(AsmToken::Identifier)) {
3149       SMLoc L = Parser.getTok().getLoc();
3150       EndLoc = Parser.getTok().getEndLoc();
3151       ShiftReg = tryParseRegister();
3152       if (ShiftReg == -1) {
3153         Error(L, "expected immediate or register in shift operand");
3154         return -1;
3155       }
3156     } else {
3157       Error(Parser.getTok().getLoc(),
3158             "expected immediate or register in shift operand");
3159       return -1;
3160     }
3161   }
3162
3163   if (ShiftReg && ShiftTy != ARM_AM::rrx)
3164     Operands.push_back(ARMOperand::CreateShiftedRegister(ShiftTy, SrcReg,
3165                                                          ShiftReg, Imm,
3166                                                          S, EndLoc));
3167   else
3168     Operands.push_back(ARMOperand::CreateShiftedImmediate(ShiftTy, SrcReg, Imm,
3169                                                           S, EndLoc));
3170
3171   return 0;
3172 }
3173
3174
3175 /// Try to parse a register name.  The token must be an Identifier when called.
3176 /// If it's a register, an AsmOperand is created. Another AsmOperand is created
3177 /// if there is a "writeback". 'true' if it's not a register.
3178 ///
3179 /// TODO this is likely to change to allow different register types and or to
3180 /// parse for a specific register type.
3181 bool ARMAsmParser::tryParseRegisterWithWriteBack(OperandVector &Operands) {
3182   MCAsmParser &Parser = getParser();
3183   const AsmToken &RegTok = Parser.getTok();
3184   int RegNo = tryParseRegister();
3185   if (RegNo == -1)
3186     return true;
3187
3188   Operands.push_back(ARMOperand::CreateReg(RegNo, RegTok.getLoc(),
3189                                            RegTok.getEndLoc()));
3190
3191   const AsmToken &ExclaimTok = Parser.getTok();
3192   if (ExclaimTok.is(AsmToken::Exclaim)) {
3193     Operands.push_back(ARMOperand::CreateToken(ExclaimTok.getString(),
3194                                                ExclaimTok.getLoc()));
3195     Parser.Lex(); // Eat exclaim token
3196     return false;
3197   }
3198
3199   // Also check for an index operand. This is only legal for vector registers,
3200   // but that'll get caught OK in operand matching, so we don't need to
3201   // explicitly filter everything else out here.
3202   if (Parser.getTok().is(AsmToken::LBrac)) {
3203     SMLoc SIdx = Parser.getTok().getLoc();
3204     Parser.Lex(); // Eat left bracket token.
3205
3206     const MCExpr *ImmVal;
3207     if (getParser().parseExpression(ImmVal))
3208       return true;
3209     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(ImmVal);
3210     if (!MCE)
3211       return TokError("immediate value expected for vector index");
3212
3213     if (Parser.getTok().isNot(AsmToken::RBrac))
3214       return Error(Parser.getTok().getLoc(), "']' expected");
3215
3216     SMLoc E = Parser.getTok().getEndLoc();
3217     Parser.Lex(); // Eat right bracket token.
3218
3219     Operands.push_back(ARMOperand::CreateVectorIndex(MCE->getValue(),
3220                                                      SIdx, E,
3221                                                      getContext()));
3222   }
3223
3224   return false;
3225 }
3226
3227 /// MatchCoprocessorOperandName - Try to parse an coprocessor related
3228 /// instruction with a symbolic operand name.
3229 /// We accept "crN" syntax for GAS compatibility.
3230 /// <operand-name> ::= <prefix><number>
3231 /// If CoprocOp is 'c', then:
3232 ///   <prefix> ::= c | cr
3233 /// If CoprocOp is 'p', then :
3234 ///   <prefix> ::= p
3235 /// <number> ::= integer in range [0, 15]
3236 static int MatchCoprocessorOperandName(StringRef Name, char CoprocOp) {
3237   // Use the same layout as the tablegen'erated register name matcher. Ugly,
3238   // but efficient.
3239   if (Name.size() < 2 || Name[0] != CoprocOp)
3240     return -1;
3241   Name = (Name[1] == 'r') ? Name.drop_front(2) : Name.drop_front();
3242
3243   switch (Name.size()) {
3244   default: return -1;
3245   case 1:
3246     switch (Name[0]) {
3247     default:  return -1;
3248     case '0': return 0;
3249     case '1': return 1;
3250     case '2': return 2;
3251     case '3': return 3;
3252     case '4': return 4;
3253     case '5': return 5;
3254     case '6': return 6;
3255     case '7': return 7;
3256     case '8': return 8;
3257     case '9': return 9;
3258     }
3259   case 2:
3260     if (Name[0] != '1')
3261       return -1;
3262     switch (Name[1]) {
3263     default:  return -1;
3264     // CP10 and CP11 are VFP/NEON and so vector instructions should be used.
3265     // However, old cores (v5/v6) did use them in that way.
3266     case '0': return 10;
3267     case '1': return 11;
3268     case '2': return 12;
3269     case '3': return 13;
3270     case '4': return 14;
3271     case '5': return 15;
3272     }
3273   }
3274 }
3275
3276 /// parseITCondCode - Try to parse a condition code for an IT instruction.
3277 ARMAsmParser::OperandMatchResultTy
3278 ARMAsmParser::parseITCondCode(OperandVector &Operands) {
3279   MCAsmParser &Parser = getParser();
3280   SMLoc S = Parser.getTok().getLoc();
3281   const AsmToken &Tok = Parser.getTok();
3282   if (!Tok.is(AsmToken::Identifier))
3283     return MatchOperand_NoMatch;
3284   unsigned CC = StringSwitch<unsigned>(Tok.getString().lower())
3285     .Case("eq", ARMCC::EQ)
3286     .Case("ne", ARMCC::NE)
3287     .Case("hs", ARMCC::HS)
3288     .Case("cs", ARMCC::HS)
3289     .Case("lo", ARMCC::LO)
3290     .Case("cc", ARMCC::LO)
3291     .Case("mi", ARMCC::MI)
3292     .Case("pl", ARMCC::PL)
3293     .Case("vs", ARMCC::VS)
3294     .Case("vc", ARMCC::VC)
3295     .Case("hi", ARMCC::HI)
3296     .Case("ls", ARMCC::LS)
3297     .Case("ge", ARMCC::GE)
3298     .Case("lt", ARMCC::LT)
3299     .Case("gt", ARMCC::GT)
3300     .Case("le", ARMCC::LE)
3301     .Case("al", ARMCC::AL)
3302     .Default(~0U);
3303   if (CC == ~0U)
3304     return MatchOperand_NoMatch;
3305   Parser.Lex(); // Eat the token.
3306
3307   Operands.push_back(ARMOperand::CreateCondCode(ARMCC::CondCodes(CC), S));
3308
3309   return MatchOperand_Success;
3310 }
3311
3312 /// parseCoprocNumOperand - Try to parse an coprocessor number operand. The
3313 /// token must be an Identifier when called, and if it is a coprocessor
3314 /// number, the token is eaten and the operand is added to the operand list.
3315 ARMAsmParser::OperandMatchResultTy
3316 ARMAsmParser::parseCoprocNumOperand(OperandVector &Operands) {
3317   MCAsmParser &Parser = getParser();
3318   SMLoc S = Parser.getTok().getLoc();
3319   const AsmToken &Tok = Parser.getTok();
3320   if (Tok.isNot(AsmToken::Identifier))
3321     return MatchOperand_NoMatch;
3322
3323   int Num = MatchCoprocessorOperandName(Tok.getString(), 'p');
3324   if (Num == -1)
3325     return MatchOperand_NoMatch;
3326   // ARMv7 and v8 don't allow cp10/cp11 due to VFP/NEON specific instructions
3327   if ((hasV7Ops() || hasV8Ops()) && (Num == 10 || Num == 11))
3328     return MatchOperand_NoMatch;
3329
3330   Parser.Lex(); // Eat identifier token.
3331   Operands.push_back(ARMOperand::CreateCoprocNum(Num, S));
3332   return MatchOperand_Success;
3333 }
3334
3335 /// parseCoprocRegOperand - Try to parse an coprocessor register operand. The
3336 /// token must be an Identifier when called, and if it is a coprocessor
3337 /// number, the token is eaten and the operand is added to the operand list.
3338 ARMAsmParser::OperandMatchResultTy
3339 ARMAsmParser::parseCoprocRegOperand(OperandVector &Operands) {
3340   MCAsmParser &Parser = getParser();
3341   SMLoc S = Parser.getTok().getLoc();
3342   const AsmToken &Tok = Parser.getTok();
3343   if (Tok.isNot(AsmToken::Identifier))
3344     return MatchOperand_NoMatch;
3345
3346   int Reg = MatchCoprocessorOperandName(Tok.getString(), 'c');
3347   if (Reg == -1)
3348     return MatchOperand_NoMatch;
3349
3350   Parser.Lex(); // Eat identifier token.
3351   Operands.push_back(ARMOperand::CreateCoprocReg(Reg, S));
3352   return MatchOperand_Success;
3353 }
3354
3355 /// parseCoprocOptionOperand - Try to parse an coprocessor option operand.
3356 /// coproc_option : '{' imm0_255 '}'
3357 ARMAsmParser::OperandMatchResultTy
3358 ARMAsmParser::parseCoprocOptionOperand(OperandVector &Operands) {
3359   MCAsmParser &Parser = getParser();
3360   SMLoc S = Parser.getTok().getLoc();
3361
3362   // If this isn't a '{', this isn't a coprocessor immediate operand.
3363   if (Parser.getTok().isNot(AsmToken::LCurly))
3364     return MatchOperand_NoMatch;
3365   Parser.Lex(); // Eat the '{'
3366
3367   const MCExpr *Expr;
3368   SMLoc Loc = Parser.getTok().getLoc();
3369   if (getParser().parseExpression(Expr)) {
3370     Error(Loc, "illegal expression");
3371     return MatchOperand_ParseFail;
3372   }
3373   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
3374   if (!CE || CE->getValue() < 0 || CE->getValue() > 255) {
3375     Error(Loc, "coprocessor option must be an immediate in range [0, 255]");
3376     return MatchOperand_ParseFail;
3377   }
3378   int Val = CE->getValue();
3379
3380   // Check for and consume the closing '}'
3381   if (Parser.getTok().isNot(AsmToken::RCurly))
3382     return MatchOperand_ParseFail;
3383   SMLoc E = Parser.getTok().getEndLoc();
3384   Parser.Lex(); // Eat the '}'
3385
3386   Operands.push_back(ARMOperand::CreateCoprocOption(Val, S, E));
3387   return MatchOperand_Success;
3388 }
3389
3390 // For register list parsing, we need to map from raw GPR register numbering
3391 // to the enumeration values. The enumeration values aren't sorted by
3392 // register number due to our using "sp", "lr" and "pc" as canonical names.
3393 static unsigned getNextRegister(unsigned Reg) {
3394   // If this is a GPR, we need to do it manually, otherwise we can rely
3395   // on the sort ordering of the enumeration since the other reg-classes
3396   // are sane.
3397   if (!ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
3398     return Reg + 1;
3399   switch(Reg) {
3400   default: llvm_unreachable("Invalid GPR number!");
3401   case ARM::R0:  return ARM::R1;  case ARM::R1:  return ARM::R2;
3402   case ARM::R2:  return ARM::R3;  case ARM::R3:  return ARM::R4;
3403   case ARM::R4:  return ARM::R5;  case ARM::R5:  return ARM::R6;
3404   case ARM::R6:  return ARM::R7;  case ARM::R7:  return ARM::R8;
3405   case ARM::R8:  return ARM::R9;  case ARM::R9:  return ARM::R10;
3406   case ARM::R10: return ARM::R11; case ARM::R11: return ARM::R12;
3407   case ARM::R12: return ARM::SP;  case ARM::SP:  return ARM::LR;
3408   case ARM::LR:  return ARM::PC;  case ARM::PC:  return ARM::R0;
3409   }
3410 }
3411
3412 // Return the low-subreg of a given Q register.
3413 static unsigned getDRegFromQReg(unsigned QReg) {
3414   switch (QReg) {
3415   default: llvm_unreachable("expected a Q register!");
3416   case ARM::Q0:  return ARM::D0;
3417   case ARM::Q1:  return ARM::D2;
3418   case ARM::Q2:  return ARM::D4;
3419   case ARM::Q3:  return ARM::D6;
3420   case ARM::Q4:  return ARM::D8;
3421   case ARM::Q5:  return ARM::D10;
3422   case ARM::Q6:  return ARM::D12;
3423   case ARM::Q7:  return ARM::D14;
3424   case ARM::Q8:  return ARM::D16;
3425   case ARM::Q9:  return ARM::D18;
3426   case ARM::Q10: return ARM::D20;
3427   case ARM::Q11: return ARM::D22;
3428   case ARM::Q12: return ARM::D24;
3429   case ARM::Q13: return ARM::D26;
3430   case ARM::Q14: return ARM::D28;
3431   case ARM::Q15: return ARM::D30;
3432   }
3433 }
3434
3435 /// Parse a register list.
3436 bool ARMAsmParser::parseRegisterList(OperandVector &Operands) {
3437   MCAsmParser &Parser = getParser();
3438   assert(Parser.getTok().is(AsmToken::LCurly) &&
3439          "Token is not a Left Curly Brace");
3440   SMLoc S = Parser.getTok().getLoc();
3441   Parser.Lex(); // Eat '{' token.
3442   SMLoc RegLoc = Parser.getTok().getLoc();
3443
3444   // Check the first register in the list to see what register class
3445   // this is a list of.
3446   int Reg = tryParseRegister();
3447   if (Reg == -1)
3448     return Error(RegLoc, "register expected");
3449
3450   // The reglist instructions have at most 16 registers, so reserve
3451   // space for that many.
3452   int EReg = 0;
3453   SmallVector<std::pair<unsigned, unsigned>, 16> Registers;
3454
3455   // Allow Q regs and just interpret them as the two D sub-registers.
3456   if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3457     Reg = getDRegFromQReg(Reg);
3458     EReg = MRI->getEncodingValue(Reg);
3459     Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3460     ++Reg;
3461   }
3462   const MCRegisterClass *RC;
3463   if (ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
3464     RC = &ARMMCRegisterClasses[ARM::GPRRegClassID];
3465   else if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Reg))
3466     RC = &ARMMCRegisterClasses[ARM::DPRRegClassID];
3467   else if (ARMMCRegisterClasses[ARM::SPRRegClassID].contains(Reg))
3468     RC = &ARMMCRegisterClasses[ARM::SPRRegClassID];
3469   else
3470     return Error(RegLoc, "invalid register in register list");
3471
3472   // Store the register.
3473   EReg = MRI->getEncodingValue(Reg);
3474   Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3475
3476   // This starts immediately after the first register token in the list,
3477   // so we can see either a comma or a minus (range separator) as a legal
3478   // next token.
3479   while (Parser.getTok().is(AsmToken::Comma) ||
3480          Parser.getTok().is(AsmToken::Minus)) {
3481     if (Parser.getTok().is(AsmToken::Minus)) {
3482       Parser.Lex(); // Eat the minus.
3483       SMLoc AfterMinusLoc = Parser.getTok().getLoc();
3484       int EndReg = tryParseRegister();
3485       if (EndReg == -1)
3486         return Error(AfterMinusLoc, "register expected");
3487       // Allow Q regs and just interpret them as the two D sub-registers.
3488       if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(EndReg))
3489         EndReg = getDRegFromQReg(EndReg) + 1;
3490       // If the register is the same as the start reg, there's nothing
3491       // more to do.
3492       if (Reg == EndReg)
3493         continue;
3494       // The register must be in the same register class as the first.
3495       if (!RC->contains(EndReg))
3496         return Error(AfterMinusLoc, "invalid register in register list");
3497       // Ranges must go from low to high.
3498       if (MRI->getEncodingValue(Reg) > MRI->getEncodingValue(EndReg))
3499         return Error(AfterMinusLoc, "bad range in register list");
3500
3501       // Add all the registers in the range to the register list.
3502       while (Reg != EndReg) {
3503         Reg = getNextRegister(Reg);
3504         EReg = MRI->getEncodingValue(Reg);
3505         Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3506       }
3507       continue;
3508     }
3509     Parser.Lex(); // Eat the comma.
3510     RegLoc = Parser.getTok().getLoc();
3511     int OldReg = Reg;
3512     const AsmToken RegTok = Parser.getTok();
3513     Reg = tryParseRegister();
3514     if (Reg == -1)
3515       return Error(RegLoc, "register expected");
3516     // Allow Q regs and just interpret them as the two D sub-registers.
3517     bool isQReg = false;
3518     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3519       Reg = getDRegFromQReg(Reg);
3520       isQReg = true;
3521     }
3522     // The register must be in the same register class as the first.
3523     if (!RC->contains(Reg))
3524       return Error(RegLoc, "invalid register in register list");
3525     // List must be monotonically increasing.
3526     if (MRI->getEncodingValue(Reg) < MRI->getEncodingValue(OldReg)) {
3527       if (ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
3528         Warning(RegLoc, "register list not in ascending order");
3529       else
3530         return Error(RegLoc, "register list not in ascending order");
3531     }
3532     if (MRI->getEncodingValue(Reg) == MRI->getEncodingValue(OldReg)) {
3533       Warning(RegLoc, "duplicated register (" + RegTok.getString() +
3534               ") in register list");
3535       continue;
3536     }
3537     // VFP register lists must also be contiguous.
3538     if (RC != &ARMMCRegisterClasses[ARM::GPRRegClassID] &&
3539         Reg != OldReg + 1)
3540       return Error(RegLoc, "non-contiguous register range");
3541     EReg = MRI->getEncodingValue(Reg);
3542     Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3543     if (isQReg) {
3544       EReg = MRI->getEncodingValue(++Reg);
3545       Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3546     }
3547   }
3548
3549   if (Parser.getTok().isNot(AsmToken::RCurly))
3550     return Error(Parser.getTok().getLoc(), "'}' expected");
3551   SMLoc E = Parser.getTok().getEndLoc();
3552   Parser.Lex(); // Eat '}' token.
3553
3554   // Push the register list operand.
3555   Operands.push_back(ARMOperand::CreateRegList(Registers, S, E));
3556
3557   // The ARM system instruction variants for LDM/STM have a '^' token here.
3558   if (Parser.getTok().is(AsmToken::Caret)) {
3559     Operands.push_back(ARMOperand::CreateToken("^",Parser.getTok().getLoc()));
3560     Parser.Lex(); // Eat '^' token.
3561   }
3562
3563   return false;
3564 }
3565
3566 // Helper function to parse the lane index for vector lists.
3567 ARMAsmParser::OperandMatchResultTy ARMAsmParser::
3568 parseVectorLane(VectorLaneTy &LaneKind, unsigned &Index, SMLoc &EndLoc) {
3569   MCAsmParser &Parser = getParser();
3570   Index = 0; // Always return a defined index value.
3571   if (Parser.getTok().is(AsmToken::LBrac)) {
3572     Parser.Lex(); // Eat the '['.
3573     if (Parser.getTok().is(AsmToken::RBrac)) {
3574       // "Dn[]" is the 'all lanes' syntax.
3575       LaneKind = AllLanes;
3576       EndLoc = Parser.getTok().getEndLoc();
3577       Parser.Lex(); // Eat the ']'.
3578       return MatchOperand_Success;
3579     }
3580
3581     // There's an optional '#' token here. Normally there wouldn't be, but
3582     // inline assemble puts one in, and it's friendly to accept that.
3583     if (Parser.getTok().is(AsmToken::Hash))
3584       Parser.Lex(); // Eat '#' or '$'.
3585
3586     const MCExpr *LaneIndex;
3587     SMLoc Loc = Parser.getTok().getLoc();
3588     if (getParser().parseExpression(LaneIndex)) {
3589       Error(Loc, "illegal expression");
3590       return MatchOperand_ParseFail;
3591     }
3592     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(LaneIndex);
3593     if (!CE) {
3594       Error(Loc, "lane index must be empty or an integer");
3595       return MatchOperand_ParseFail;
3596     }
3597     if (Parser.getTok().isNot(AsmToken::RBrac)) {
3598       Error(Parser.getTok().getLoc(), "']' expected");
3599       return MatchOperand_ParseFail;
3600     }
3601     EndLoc = Parser.getTok().getEndLoc();
3602     Parser.Lex(); // Eat the ']'.
3603     int64_t Val = CE->getValue();
3604
3605     // FIXME: Make this range check context sensitive for .8, .16, .32.
3606     if (Val < 0 || Val > 7) {
3607       Error(Parser.getTok().getLoc(), "lane index out of range");
3608       return MatchOperand_ParseFail;
3609     }
3610     Index = Val;
3611     LaneKind = IndexedLane;
3612     return MatchOperand_Success;
3613   }
3614   LaneKind = NoLanes;
3615   return MatchOperand_Success;
3616 }
3617
3618 // parse a vector register list
3619 ARMAsmParser::OperandMatchResultTy
3620 ARMAsmParser::parseVectorList(OperandVector &Operands) {
3621   MCAsmParser &Parser = getParser();
3622   VectorLaneTy LaneKind;
3623   unsigned LaneIndex;
3624   SMLoc S = Parser.getTok().getLoc();
3625   // As an extension (to match gas), support a plain D register or Q register
3626   // (without encosing curly braces) as a single or double entry list,
3627   // respectively.
3628   if (Parser.getTok().is(AsmToken::Identifier)) {
3629     SMLoc E = Parser.getTok().getEndLoc();
3630     int Reg = tryParseRegister();
3631     if (Reg == -1)
3632       return MatchOperand_NoMatch;
3633     if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Reg)) {
3634       OperandMatchResultTy Res = parseVectorLane(LaneKind, LaneIndex, E);
3635       if (Res != MatchOperand_Success)
3636         return Res;
3637       switch (LaneKind) {
3638       case NoLanes:
3639         Operands.push_back(ARMOperand::CreateVectorList(Reg, 1, false, S, E));
3640         break;
3641       case AllLanes:
3642         Operands.push_back(ARMOperand::CreateVectorListAllLanes(Reg, 1, false,
3643                                                                 S, E));
3644         break;
3645       case IndexedLane:
3646         Operands.push_back(ARMOperand::CreateVectorListIndexed(Reg, 1,
3647                                                                LaneIndex,
3648                                                                false, S, E));
3649         break;
3650       }
3651       return MatchOperand_Success;
3652     }
3653     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3654       Reg = getDRegFromQReg(Reg);
3655       OperandMatchResultTy Res = parseVectorLane(LaneKind, LaneIndex, E);
3656       if (Res != MatchOperand_Success)
3657         return Res;
3658       switch (LaneKind) {
3659       case NoLanes:
3660         Reg = MRI->getMatchingSuperReg(Reg, ARM::dsub_0,
3661                                    &ARMMCRegisterClasses[ARM::DPairRegClassID]);
3662         Operands.push_back(ARMOperand::CreateVectorList(Reg, 2, false, S, E));
3663         break;
3664       case AllLanes:
3665         Reg = MRI->getMatchingSuperReg(Reg, ARM::dsub_0,
3666                                    &ARMMCRegisterClasses[ARM::DPairRegClassID]);
3667         Operands.push_back(ARMOperand::CreateVectorListAllLanes(Reg, 2, false,
3668                                                                 S, E));
3669         break;
3670       case IndexedLane:
3671         Operands.push_back(ARMOperand::CreateVectorListIndexed(Reg, 2,
3672                                                                LaneIndex,
3673                                                                false, S, E));
3674         break;
3675       }
3676       return MatchOperand_Success;
3677     }
3678     Error(S, "vector register expected");
3679     return MatchOperand_ParseFail;
3680   }
3681
3682   if (Parser.getTok().isNot(AsmToken::LCurly))
3683     return MatchOperand_NoMatch;
3684
3685   Parser.Lex(); // Eat '{' token.
3686   SMLoc RegLoc = Parser.getTok().getLoc();
3687
3688   int Reg = tryParseRegister();
3689   if (Reg == -1) {
3690     Error(RegLoc, "register expected");
3691     return MatchOperand_ParseFail;
3692   }
3693   unsigned Count = 1;
3694   int Spacing = 0;
3695   unsigned FirstReg = Reg;
3696   // The list is of D registers, but we also allow Q regs and just interpret
3697   // them as the two D sub-registers.
3698   if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3699     FirstReg = Reg = getDRegFromQReg(Reg);
3700     Spacing = 1; // double-spacing requires explicit D registers, otherwise
3701                  // it's ambiguous with four-register single spaced.
3702     ++Reg;
3703     ++Count;
3704   }
3705
3706   SMLoc E;
3707   if (parseVectorLane(LaneKind, LaneIndex, E) != MatchOperand_Success)
3708     return MatchOperand_ParseFail;
3709
3710   while (Parser.getTok().is(AsmToken::Comma) ||
3711          Parser.getTok().is(AsmToken::Minus)) {
3712     if (Parser.getTok().is(AsmToken::Minus)) {
3713       if (!Spacing)
3714         Spacing = 1; // Register range implies a single spaced list.
3715       else if (Spacing == 2) {
3716         Error(Parser.getTok().getLoc(),
3717               "sequential registers in double spaced list");
3718         return MatchOperand_ParseFail;
3719       }
3720       Parser.Lex(); // Eat the minus.
3721       SMLoc AfterMinusLoc = Parser.getTok().getLoc();
3722       int EndReg = tryParseRegister();
3723       if (EndReg == -1) {
3724         Error(AfterMinusLoc, "register expected");
3725         return MatchOperand_ParseFail;
3726       }
3727       // Allow Q regs and just interpret them as the two D sub-registers.
3728       if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(EndReg))
3729         EndReg = getDRegFromQReg(EndReg) + 1;
3730       // If the register is the same as the start reg, there's nothing
3731       // more to do.
3732       if (Reg == EndReg)
3733         continue;
3734       // The register must be in the same register class as the first.
3735       if (!ARMMCRegisterClasses[ARM::DPRRegClassID].contains(EndReg)) {
3736         Error(AfterMinusLoc, "invalid register in register list");
3737         return MatchOperand_ParseFail;
3738       }
3739       // Ranges must go from low to high.
3740       if (Reg > EndReg) {
3741         Error(AfterMinusLoc, "bad range in register list");
3742         return MatchOperand_ParseFail;
3743       }
3744       // Parse the lane specifier if present.
3745       VectorLaneTy NextLaneKind;
3746       unsigned NextLaneIndex;
3747       if (parseVectorLane(NextLaneKind, NextLaneIndex, E) !=
3748           MatchOperand_Success)
3749         return MatchOperand_ParseFail;
3750       if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
3751         Error(AfterMinusLoc, "mismatched lane index in register list");
3752         return MatchOperand_ParseFail;
3753       }
3754
3755       // Add all the registers in the range to the register list.
3756       Count += EndReg - Reg;
3757       Reg = EndReg;
3758       continue;
3759     }
3760     Parser.Lex(); // Eat the comma.
3761     RegLoc = Parser.getTok().getLoc();
3762     int OldReg = Reg;
3763     Reg = tryParseRegister();
3764     if (Reg == -1) {
3765       Error(RegLoc, "register expected");
3766       return MatchOperand_ParseFail;
3767     }
3768     // vector register lists must be contiguous.
3769     // It's OK to use the enumeration values directly here rather, as the
3770     // VFP register classes have the enum sorted properly.
3771     //
3772     // The list is of D registers, but we also allow Q regs and just interpret
3773     // them as the two D sub-registers.
3774     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3775       if (!Spacing)
3776         Spacing = 1; // Register range implies a single spaced list.
3777       else if (Spacing == 2) {
3778         Error(RegLoc,
3779               "invalid register in double-spaced list (must be 'D' register')");
3780         return MatchOperand_ParseFail;
3781       }
3782       Reg = getDRegFromQReg(Reg);
3783       if (Reg != OldReg + 1) {
3784         Error(RegLoc, "non-contiguous register range");
3785         return MatchOperand_ParseFail;
3786       }
3787       ++Reg;
3788       Count += 2;
3789       // Parse the lane specifier if present.
3790       VectorLaneTy NextLaneKind;
3791       unsigned NextLaneIndex;
3792       SMLoc LaneLoc = Parser.getTok().getLoc();
3793       if (parseVectorLane(NextLaneKind, NextLaneIndex, E) !=
3794           MatchOperand_Success)
3795         return MatchOperand_ParseFail;
3796       if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
3797         Error(LaneLoc, "mismatched lane index in register list");
3798         return MatchOperand_ParseFail;
3799       }
3800       continue;
3801     }
3802     // Normal D register.
3803     // Figure out the register spacing (single or double) of the list if
3804     // we don't know it already.
3805     if (!Spacing)
3806       Spacing = 1 + (Reg == OldReg + 2);
3807
3808     // Just check that it's contiguous and keep going.
3809     if (Reg != OldReg + Spacing) {
3810       Error(RegLoc, "non-contiguous register range");
3811       return MatchOperand_ParseFail;
3812     }
3813     ++Count;
3814     // Parse the lane specifier if present.
3815     VectorLaneTy NextLaneKind;
3816     unsigned NextLaneIndex;
3817     SMLoc EndLoc = Parser.getTok().getLoc();
3818     if (parseVectorLane(NextLaneKind, NextLaneIndex, E) != MatchOperand_Success)
3819       return MatchOperand_ParseFail;
3820     if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
3821       Error(EndLoc, "mismatched lane index in register list");
3822       return MatchOperand_ParseFail;
3823     }
3824   }
3825
3826   if (Parser.getTok().isNot(AsmToken::RCurly)) {
3827     Error(Parser.getTok().getLoc(), "'}' expected");
3828     return MatchOperand_ParseFail;
3829   }
3830   E = Parser.getTok().getEndLoc();
3831   Parser.Lex(); // Eat '}' token.
3832
3833   switch (LaneKind) {
3834   case NoLanes:
3835     // Two-register operands have been converted to the
3836     // composite register classes.
3837     if (Count == 2) {
3838       const MCRegisterClass *RC = (Spacing == 1) ?
3839         &ARMMCRegisterClasses[ARM::DPairRegClassID] :
3840         &ARMMCRegisterClasses[ARM::DPairSpcRegClassID];
3841       FirstReg = MRI->getMatchingSuperReg(FirstReg, ARM::dsub_0, RC);
3842     }
3843
3844     Operands.push_back(ARMOperand::CreateVectorList(FirstReg, Count,
3845                                                     (Spacing == 2), S, E));
3846     break;
3847   case AllLanes:
3848     // Two-register operands have been converted to the
3849     // composite register classes.
3850     if (Count == 2) {
3851       const MCRegisterClass *RC = (Spacing == 1) ?
3852         &ARMMCRegisterClasses[ARM::DPairRegClassID] :
3853         &ARMMCRegisterClasses[ARM::DPairSpcRegClassID];
3854       FirstReg = MRI->getMatchingSuperReg(FirstReg, ARM::dsub_0, RC);
3855     }
3856     Operands.push_back(ARMOperand::CreateVectorListAllLanes(FirstReg, Count,
3857                                                             (Spacing == 2),
3858                                                             S, E));
3859     break;
3860   case IndexedLane:
3861     Operands.push_back(ARMOperand::CreateVectorListIndexed(FirstReg, Count,
3862                                                            LaneIndex,
3863                                                            (Spacing == 2),
3864                                                            S, E));
3865     break;
3866   }
3867   return MatchOperand_Success;
3868 }
3869
3870 /// parseMemBarrierOptOperand - Try to parse DSB/DMB data barrier options.
3871 ARMAsmParser::OperandMatchResultTy
3872 ARMAsmParser::parseMemBarrierOptOperand(OperandVector &Operands) {
3873   MCAsmParser &Parser = getParser();
3874   SMLoc S = Parser.getTok().getLoc();
3875   const AsmToken &Tok = Parser.getTok();
3876   unsigned Opt;
3877
3878   if (Tok.is(AsmToken::Identifier)) {
3879     StringRef OptStr = Tok.getString();
3880
3881     Opt = StringSwitch<unsigned>(OptStr.slice(0, OptStr.size()).lower())
3882       .Case("sy",    ARM_MB::SY)
3883       .Case("st",    ARM_MB::ST)
3884       .Case("ld",    ARM_MB::LD)
3885       .Case("sh",    ARM_MB::ISH)
3886       .Case("ish",   ARM_MB::ISH)
3887       .Case("shst",  ARM_MB::ISHST)
3888       .Case("ishst", ARM_MB::ISHST)
3889       .Case("ishld", ARM_MB::ISHLD)
3890       .Case("nsh",   ARM_MB::NSH)
3891       .Case("un",    ARM_MB::NSH)
3892       .Case("nshst", ARM_MB::NSHST)
3893       .Case("nshld", ARM_MB::NSHLD)
3894       .Case("unst",  ARM_MB::NSHST)
3895       .Case("osh",   ARM_MB::OSH)
3896       .Case("oshst", ARM_MB::OSHST)
3897       .Case("oshld", ARM_MB::OSHLD)
3898       .Default(~0U);
3899
3900     // ishld, oshld, nshld and ld are only available from ARMv8.
3901     if (!hasV8Ops() && (Opt == ARM_MB::ISHLD || Opt == ARM_MB::OSHLD ||
3902                         Opt == ARM_MB::NSHLD || Opt == ARM_MB::LD))
3903       Opt = ~0U;
3904
3905     if (Opt == ~0U)
3906       return MatchOperand_NoMatch;
3907
3908     Parser.Lex(); // Eat identifier token.
3909   } else if (Tok.is(AsmToken::Hash) ||
3910              Tok.is(AsmToken::Dollar) ||
3911              Tok.is(AsmToken::Integer)) {
3912     if (Parser.getTok().isNot(AsmToken::Integer))
3913       Parser.Lex(); // Eat '#' or '$'.
3914     SMLoc Loc = Parser.getTok().getLoc();
3915
3916     const MCExpr *MemBarrierID;
3917     if (getParser().parseExpression(MemBarrierID)) {
3918       Error(Loc, "illegal expression");
3919       return MatchOperand_ParseFail;
3920     }
3921
3922     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(MemBarrierID);
3923     if (!CE) {
3924       Error(Loc, "constant expression expected");
3925       return MatchOperand_ParseFail;
3926     }
3927
3928     int Val = CE->getValue();
3929     if (Val & ~0xf) {
3930       Error(Loc, "immediate value out of range");
3931       return MatchOperand_ParseFail;
3932     }
3933
3934     Opt = ARM_MB::RESERVED_0 + Val;
3935   } else
3936     return MatchOperand_ParseFail;
3937
3938   Operands.push_back(ARMOperand::CreateMemBarrierOpt((ARM_MB::MemBOpt)Opt, S));
3939   return MatchOperand_Success;
3940 }
3941
3942 /// parseInstSyncBarrierOptOperand - Try to parse ISB inst sync barrier options.
3943 ARMAsmParser::OperandMatchResultTy
3944 ARMAsmParser::parseInstSyncBarrierOptOperand(OperandVector &Operands) {
3945   MCAsmParser &Parser = getParser();
3946   SMLoc S = Parser.getTok().getLoc();
3947   const AsmToken &Tok = Parser.getTok();
3948   unsigned Opt;
3949
3950   if (Tok.is(AsmToken::Identifier)) {
3951     StringRef OptStr = Tok.getString();
3952
3953     if (OptStr.equals_lower("sy"))
3954       Opt = ARM_ISB::SY;
3955     else
3956       return MatchOperand_NoMatch;
3957
3958     Parser.Lex(); // Eat identifier token.
3959   } else if (Tok.is(AsmToken::Hash) ||
3960              Tok.is(AsmToken::Dollar) ||
3961              Tok.is(AsmToken::Integer)) {
3962     if (Parser.getTok().isNot(AsmToken::Integer))
3963       Parser.Lex(); // Eat '#' or '$'.
3964     SMLoc Loc = Parser.getTok().getLoc();
3965
3966     const MCExpr *ISBarrierID;
3967     if (getParser().parseExpression(ISBarrierID)) {
3968       Error(Loc, "illegal expression");
3969       return MatchOperand_ParseFail;
3970     }
3971
3972     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ISBarrierID);
3973     if (!CE) {
3974       Error(Loc, "constant expression expected");
3975       return MatchOperand_ParseFail;
3976     }
3977
3978     int Val = CE->getValue();
3979     if (Val & ~0xf) {
3980       Error(Loc, "immediate value out of range");
3981       return MatchOperand_ParseFail;
3982     }
3983
3984     Opt = ARM_ISB::RESERVED_0 + Val;
3985   } else
3986     return MatchOperand_ParseFail;
3987
3988   Operands.push_back(ARMOperand::CreateInstSyncBarrierOpt(
3989           (ARM_ISB::InstSyncBOpt)Opt, S));
3990   return MatchOperand_Success;
3991 }
3992
3993
3994 /// parseProcIFlagsOperand - Try to parse iflags from CPS instruction.
3995 ARMAsmParser::OperandMatchResultTy
3996 ARMAsmParser::parseProcIFlagsOperand(OperandVector &Operands) {
3997   MCAsmParser &Parser = getParser();
3998   SMLoc S = Parser.getTok().getLoc();
3999   const AsmToken &Tok = Parser.getTok();
4000   if (!Tok.is(AsmToken::Identifier)) 
4001     return MatchOperand_NoMatch;
4002   StringRef IFlagsStr = Tok.getString();
4003
4004   // An iflags string of "none" is interpreted to mean that none of the AIF
4005   // bits are set.  Not a terribly useful instruction, but a valid encoding.
4006   unsigned IFlags = 0;
4007   if (IFlagsStr != "none") {
4008         for (int i = 0, e = IFlagsStr.size(); i != e; ++i) {
4009       unsigned Flag = StringSwitch<unsigned>(IFlagsStr.substr(i, 1))
4010         .Case("a", ARM_PROC::A)
4011         .Case("i", ARM_PROC::I)
4012         .Case("f", ARM_PROC::F)
4013         .Default(~0U);
4014
4015       // If some specific iflag is already set, it means that some letter is
4016       // present more than once, this is not acceptable.
4017       if (Flag == ~0U || (IFlags & Flag))
4018         return MatchOperand_NoMatch;
4019
4020       IFlags |= Flag;
4021     }
4022   }
4023
4024   Parser.Lex(); // Eat identifier token.
4025   Operands.push_back(ARMOperand::CreateProcIFlags((ARM_PROC::IFlags)IFlags, S));
4026   return MatchOperand_Success;
4027 }
4028
4029 /// parseMSRMaskOperand - Try to parse mask flags from MSR instruction.
4030 ARMAsmParser::OperandMatchResultTy
4031 ARMAsmParser::parseMSRMaskOperand(OperandVector &Operands) {
4032   MCAsmParser &Parser = getParser();
4033   SMLoc S = Parser.getTok().getLoc();
4034   const AsmToken &Tok = Parser.getTok();
4035   if (!Tok.is(AsmToken::Identifier))
4036     return MatchOperand_NoMatch;
4037   StringRef Mask = Tok.getString();
4038
4039   if (isMClass()) {
4040     // See ARMv6-M 10.1.1
4041     std::string Name = Mask.lower();
4042     unsigned FlagsVal = StringSwitch<unsigned>(Name)
4043       // Note: in the documentation:
4044       //  ARM deprecates using MSR APSR without a _<bits> qualifier as an alias
4045       //  for MSR APSR_nzcvq.
4046       // but we do make it an alias here.  This is so to get the "mask encoding"
4047       // bits correct on MSR APSR writes.
4048       //
4049       // FIXME: Note the 0xc00 "mask encoding" bits version of the registers
4050       // should really only be allowed when writing a special register.  Note
4051       // they get dropped in the MRS instruction reading a special register as
4052       // the SYSm field is only 8 bits.
4053       .Case("apsr", 0x800)
4054       .Case("apsr_nzcvq", 0x800)
4055       .Case("apsr_g", 0x400)
4056       .Case("apsr_nzcvqg", 0xc00)
4057       .Case("iapsr", 0x801)
4058       .Case("iapsr_nzcvq", 0x801)
4059       .Case("iapsr_g", 0x401)
4060       .Case("iapsr_nzcvqg", 0xc01)
4061       .Case("eapsr", 0x802)
4062       .Case("eapsr_nzcvq", 0x802)
4063       .Case("eapsr_g", 0x402)
4064       .Case("eapsr_nzcvqg", 0xc02)
4065       .Case("xpsr", 0x803)
4066       .Case("xpsr_nzcvq", 0x803)
4067       .Case("xpsr_g", 0x403)
4068       .Case("xpsr_nzcvqg", 0xc03)
4069       .Case("ipsr", 0x805)
4070       .Case("epsr", 0x806)
4071       .Case("iepsr", 0x807)
4072       .Case("msp", 0x808)
4073       .Case("psp", 0x809)
4074       .Case("primask", 0x810)
4075       .Case("basepri", 0x811)
4076       .Case("basepri_max", 0x812)
4077       .Case("faultmask", 0x813)
4078       .Case("control", 0x814)
4079       .Default(~0U);
4080
4081     if (FlagsVal == ~0U)
4082       return MatchOperand_NoMatch;
4083
4084     if (!hasThumb2DSP() && (FlagsVal & 0x400))
4085       // The _g and _nzcvqg versions are only valid if the DSP extension is
4086       // available.
4087       return MatchOperand_NoMatch;
4088
4089     if (!hasV7Ops() && FlagsVal >= 0x811 && FlagsVal <= 0x813)
4090       // basepri, basepri_max and faultmask only valid for V7m.
4091       return MatchOperand_NoMatch;
4092
4093     Parser.Lex(); // Eat identifier token.
4094     Operands.push_back(ARMOperand::CreateMSRMask(FlagsVal, S));
4095     return MatchOperand_Success;
4096   }
4097
4098   // Split spec_reg from flag, example: CPSR_sxf => "CPSR" and "sxf"
4099   size_t Start = 0, Next = Mask.find('_');
4100   StringRef Flags = "";
4101   std::string SpecReg = Mask.slice(Start, Next).lower();
4102   if (Next != StringRef::npos)
4103     Flags = Mask.slice(Next+1, Mask.size());
4104
4105   // FlagsVal contains the complete mask:
4106   // 3-0: Mask
4107   // 4: Special Reg (cpsr, apsr => 0; spsr => 1)
4108   unsigned FlagsVal = 0;
4109
4110   if (SpecReg == "apsr") {
4111     FlagsVal = StringSwitch<unsigned>(Flags)
4112     .Case("nzcvq",  0x8) // same as CPSR_f
4113     .Case("g",      0x4) // same as CPSR_s
4114     .Case("nzcvqg", 0xc) // same as CPSR_fs
4115     .Default(~0U);
4116
4117     if (FlagsVal == ~0U) {
4118       if (!Flags.empty())
4119         return MatchOperand_NoMatch;
4120       else
4121         FlagsVal = 8; // No flag
4122     }
4123   } else if (SpecReg == "cpsr" || SpecReg == "spsr") {
4124     // cpsr_all is an alias for cpsr_fc, as is plain cpsr.
4125     if (Flags == "all" || Flags == "")
4126       Flags = "fc";
4127     for (int i = 0, e = Flags.size(); i != e; ++i) {
4128       unsigned Flag = StringSwitch<unsigned>(Flags.substr(i, 1))
4129       .Case("c", 1)
4130       .Case("x", 2)
4131       .Case("s", 4)
4132       .Case("f", 8)
4133       .Default(~0U);
4134
4135       // If some specific flag is already set, it means that some letter is
4136       // present more than once, this is not acceptable.
4137       if (FlagsVal == ~0U || (FlagsVal & Flag))
4138         return MatchOperand_NoMatch;
4139       FlagsVal |= Flag;
4140     }
4141   } else // No match for special register.
4142     return MatchOperand_NoMatch;
4143
4144   // Special register without flags is NOT equivalent to "fc" flags.
4145   // NOTE: This is a divergence from gas' behavior.  Uncommenting the following
4146   // two lines would enable gas compatibility at the expense of breaking
4147   // round-tripping.
4148   //
4149   // if (!FlagsVal)
4150   //  FlagsVal = 0x9;
4151
4152   // Bit 4: Special Reg (cpsr, apsr => 0; spsr => 1)
4153   if (SpecReg == "spsr")
4154     FlagsVal |= 16;
4155
4156   Parser.Lex(); // Eat identifier token.
4157   Operands.push_back(ARMOperand::CreateMSRMask(FlagsVal, S));
4158   return MatchOperand_Success;
4159 }
4160
4161 /// parseBankedRegOperand - Try to parse a banked register (e.g. "lr_irq") for
4162 /// use in the MRS/MSR instructions added to support virtualization.
4163 ARMAsmParser::OperandMatchResultTy
4164 ARMAsmParser::parseBankedRegOperand(OperandVector &Operands) {
4165   MCAsmParser &Parser = getParser();
4166   SMLoc S = Parser.getTok().getLoc();
4167   const AsmToken &Tok = Parser.getTok();
4168   if (!Tok.is(AsmToken::Identifier))
4169     return MatchOperand_NoMatch;
4170   StringRef RegName = Tok.getString();
4171
4172   // The values here come from B9.2.3 of the ARM ARM, where bits 4-0 are SysM
4173   // and bit 5 is R.
4174   unsigned Encoding = StringSwitch<unsigned>(RegName.lower())
4175                           .Case("r8_usr", 0x00)
4176                           .Case("r9_usr", 0x01)
4177                           .Case("r10_usr", 0x02)
4178                           .Case("r11_usr", 0x03)
4179                           .Case("r12_usr", 0x04)
4180                           .Case("sp_usr", 0x05)
4181                           .Case("lr_usr", 0x06)
4182                           .Case("r8_fiq", 0x08)
4183                           .Case("r9_fiq", 0x09)
4184                           .Case("r10_fiq", 0x0a)
4185                           .Case("r11_fiq", 0x0b)
4186                           .Case("r12_fiq", 0x0c)
4187                           .Case("sp_fiq", 0x0d)
4188                           .Case("lr_fiq", 0x0e)
4189                           .Case("lr_irq", 0x10)
4190                           .Case("sp_irq", 0x11)
4191                           .Case("lr_svc", 0x12)
4192                           .Case("sp_svc", 0x13)
4193                           .Case("lr_abt", 0x14)
4194                           .Case("sp_abt", 0x15)
4195                           .Case("lr_und", 0x16)
4196                           .Case("sp_und", 0x17)
4197                           .Case("lr_mon", 0x1c)
4198                           .Case("sp_mon", 0x1d)
4199                           .Case("elr_hyp", 0x1e)
4200                           .Case("sp_hyp", 0x1f)
4201                           .Case("spsr_fiq", 0x2e)
4202                           .Case("spsr_irq", 0x30)
4203                           .Case("spsr_svc", 0x32)
4204                           .Case("spsr_abt", 0x34)
4205                           .Case("spsr_und", 0x36)
4206                           .Case("spsr_mon", 0x3c)
4207                           .Case("spsr_hyp", 0x3e)
4208                           .Default(~0U);
4209
4210   if (Encoding == ~0U)
4211     return MatchOperand_NoMatch;
4212
4213   Parser.Lex(); // Eat identifier token.
4214   Operands.push_back(ARMOperand::CreateBankedReg(Encoding, S));
4215   return MatchOperand_Success;
4216 }
4217
4218 ARMAsmParser::OperandMatchResultTy
4219 ARMAsmParser::parsePKHImm(OperandVector &Operands, StringRef Op, int Low,
4220                           int High) {
4221   MCAsmParser &Parser = getParser();
4222   const AsmToken &Tok = Parser.getTok();
4223   if (Tok.isNot(AsmToken::Identifier)) {
4224     Error(Parser.getTok().getLoc(), Op + " operand expected.");
4225     return MatchOperand_ParseFail;
4226   }
4227   StringRef ShiftName = Tok.getString();
4228   std::string LowerOp = Op.lower();
4229   std::string UpperOp = Op.upper();
4230   if (ShiftName != LowerOp && ShiftName != UpperOp) {
4231     Error(Parser.getTok().getLoc(), Op + " operand expected.");
4232     return MatchOperand_ParseFail;
4233   }
4234   Parser.Lex(); // Eat shift type token.
4235
4236   // There must be a '#' and a shift amount.
4237   if (Parser.getTok().isNot(AsmToken::Hash) &&
4238       Parser.getTok().isNot(AsmToken::Dollar)) {
4239     Error(Parser.getTok().getLoc(), "'#' expected");
4240     return MatchOperand_ParseFail;
4241   }
4242   Parser.Lex(); // Eat hash token.
4243
4244   const MCExpr *ShiftAmount;
4245   SMLoc Loc = Parser.getTok().getLoc();
4246   SMLoc EndLoc;
4247   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
4248     Error(Loc, "illegal expression");
4249     return MatchOperand_ParseFail;
4250   }
4251   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
4252   if (!CE) {
4253     Error(Loc, "constant expression expected");
4254     return MatchOperand_ParseFail;
4255   }
4256   int Val = CE->getValue();
4257   if (Val < Low || Val > High) {
4258     Error(Loc, "immediate value out of range");
4259     return MatchOperand_ParseFail;
4260   }
4261
4262   Operands.push_back(ARMOperand::CreateImm(CE, Loc, EndLoc));
4263
4264   return MatchOperand_Success;
4265 }
4266
4267 ARMAsmParser::OperandMatchResultTy
4268 ARMAsmParser::parseSetEndImm(OperandVector &Operands) {
4269   MCAsmParser &Parser = getParser();
4270   const AsmToken &Tok = Parser.getTok();
4271   SMLoc S = Tok.getLoc();
4272   if (Tok.isNot(AsmToken::Identifier)) {
4273     Error(S, "'be' or 'le' operand expected");
4274     return MatchOperand_ParseFail;
4275   }
4276   int Val = StringSwitch<int>(Tok.getString().lower())
4277     .Case("be", 1)
4278     .Case("le", 0)
4279     .Default(-1);
4280   Parser.Lex(); // Eat the token.
4281
4282   if (Val == -1) {
4283     Error(S, "'be' or 'le' operand expected");
4284     return MatchOperand_ParseFail;
4285   }
4286   Operands.push_back(ARMOperand::CreateImm(MCConstantExpr::Create(Val,
4287                                                                   getContext()),
4288                                            S, Tok.getEndLoc()));
4289   return MatchOperand_Success;
4290 }
4291
4292 /// parseShifterImm - Parse the shifter immediate operand for SSAT/USAT
4293 /// instructions. Legal values are:
4294 ///     lsl #n  'n' in [0,31]
4295 ///     asr #n  'n' in [1,32]
4296 ///             n == 32 encoded as n == 0.
4297 ARMAsmParser::OperandMatchResultTy
4298 ARMAsmParser::parseShifterImm(OperandVector &Operands) {
4299   MCAsmParser &Parser = getParser();
4300   const AsmToken &Tok = Parser.getTok();
4301   SMLoc S = Tok.getLoc();
4302   if (Tok.isNot(AsmToken::Identifier)) {
4303     Error(S, "shift operator 'asr' or 'lsl' expected");
4304     return MatchOperand_ParseFail;
4305   }
4306   StringRef ShiftName = Tok.getString();
4307   bool isASR;
4308   if (ShiftName == "lsl" || ShiftName == "LSL")
4309     isASR = false;
4310   else if (ShiftName == "asr" || ShiftName == "ASR")
4311     isASR = true;
4312   else {
4313     Error(S, "shift operator 'asr' or 'lsl' expected");
4314     return MatchOperand_ParseFail;
4315   }
4316   Parser.Lex(); // Eat the operator.
4317
4318   // A '#' and a shift amount.
4319   if (Parser.getTok().isNot(AsmToken::Hash) &&
4320       Parser.getTok().isNot(AsmToken::Dollar)) {
4321     Error(Parser.getTok().getLoc(), "'#' expected");
4322     return MatchOperand_ParseFail;
4323   }
4324   Parser.Lex(); // Eat hash token.
4325   SMLoc ExLoc = Parser.getTok().getLoc();
4326
4327   const MCExpr *ShiftAmount;
4328   SMLoc EndLoc;
4329   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
4330     Error(ExLoc, "malformed shift expression");
4331     return MatchOperand_ParseFail;
4332   }
4333   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
4334   if (!CE) {
4335     Error(ExLoc, "shift amount must be an immediate");
4336     return MatchOperand_ParseFail;
4337   }
4338
4339   int64_t Val = CE->getValue();
4340   if (isASR) {
4341     // Shift amount must be in [1,32]
4342     if (Val < 1 || Val > 32) {
4343       Error(ExLoc, "'asr' shift amount must be in range [1,32]");
4344       return MatchOperand_ParseFail;
4345     }
4346     // asr #32 encoded as asr #0, but is not allowed in Thumb2 mode.
4347     if (isThumb() && Val == 32) {
4348       Error(ExLoc, "'asr #32' shift amount not allowed in Thumb mode");
4349       return MatchOperand_ParseFail;
4350     }
4351     if (Val == 32) Val = 0;
4352   } else {
4353     // Shift amount must be in [1,32]
4354     if (Val < 0 || Val > 31) {
4355       Error(ExLoc, "'lsr' shift amount must be in range [0,31]");
4356       return MatchOperand_ParseFail;
4357     }
4358   }
4359
4360   Operands.push_back(ARMOperand::CreateShifterImm(isASR, Val, S, EndLoc));
4361
4362   return MatchOperand_Success;
4363 }
4364
4365 /// parseRotImm - Parse the shifter immediate operand for SXTB/UXTB family
4366 /// of instructions. Legal values are:
4367 ///     ror #n  'n' in {0, 8, 16, 24}
4368 ARMAsmParser::OperandMatchResultTy
4369 ARMAsmParser::parseRotImm(OperandVector &Operands) {
4370   MCAsmParser &Parser = getParser();
4371   const AsmToken &Tok = Parser.getTok();
4372   SMLoc S = Tok.getLoc();
4373   if (Tok.isNot(AsmToken::Identifier))
4374     return MatchOperand_NoMatch;
4375   StringRef ShiftName = Tok.getString();
4376   if (ShiftName != "ror" && ShiftName != "ROR")
4377     return MatchOperand_NoMatch;
4378   Parser.Lex(); // Eat the operator.
4379
4380   // A '#' and a rotate amount.
4381   if (Parser.getTok().isNot(AsmToken::Hash) &&
4382       Parser.getTok().isNot(AsmToken::Dollar)) {
4383     Error(Parser.getTok().getLoc(), "'#' expected");
4384     return MatchOperand_ParseFail;
4385   }
4386   Parser.Lex(); // Eat hash token.
4387   SMLoc ExLoc = Parser.getTok().getLoc();
4388
4389   const MCExpr *ShiftAmount;
4390   SMLoc EndLoc;
4391   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
4392     Error(ExLoc, "malformed rotate expression");
4393     return MatchOperand_ParseFail;
4394   }
4395   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
4396   if (!CE) {
4397     Error(ExLoc, "rotate amount must be an immediate");
4398     return MatchOperand_ParseFail;
4399   }
4400
4401   int64_t Val = CE->getValue();
4402   // Shift amount must be in {0, 8, 16, 24} (0 is undocumented extension)
4403   // normally, zero is represented in asm by omitting the rotate operand
4404   // entirely.
4405   if (Val != 8 && Val != 16 && Val != 24 && Val != 0) {
4406     Error(ExLoc, "'ror' rotate amount must be 8, 16, or 24");
4407     return MatchOperand_ParseFail;
4408   }
4409
4410   Operands.push_back(ARMOperand::CreateRotImm(Val, S, EndLoc));
4411
4412   return MatchOperand_Success;
4413 }
4414
4415 ARMAsmParser::OperandMatchResultTy
4416 ARMAsmParser::parseModImm(OperandVector &Operands) {
4417   MCAsmParser &Parser = getParser();
4418   MCAsmLexer &Lexer = getLexer();
4419   int64_t Imm1, Imm2;
4420
4421   if ((Parser.getTok().isNot(AsmToken::Hash) &&
4422        Parser.getTok().isNot(AsmToken::Dollar) /* looking for an immediate */ )
4423       || Lexer.peekTok().is(AsmToken::Colon)
4424       || Lexer.peekTok().is(AsmToken::LParen) /* avoid complex operands */ )
4425     return MatchOperand_NoMatch;
4426
4427   SMLoc S = Parser.getTok().getLoc();
4428
4429   // Eat the hash (or dollar)
4430   Parser.Lex();
4431
4432   SMLoc Sx1, Ex1;
4433   Sx1 = Parser.getTok().getLoc();
4434   const MCExpr *Imm1Exp;
4435   if (getParser().parseExpression(Imm1Exp, Ex1)) {
4436     Error(Sx1, "malformed expression");
4437     return MatchOperand_ParseFail;
4438   }
4439
4440   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm1Exp);
4441
4442   if (CE) {
4443     // immediate must fit within 32-bits
4444     Imm1 = CE->getValue();
4445     if (Imm1 < INT32_MIN || Imm1 > UINT32_MAX) {
4446       Error(Sx1, "immediate operand must be representable with 32 bits");
4447       return MatchOperand_ParseFail;
4448     }
4449
4450     int Enc = ARM_AM::getSOImmVal(Imm1);
4451     if (Enc != -1 && Parser.getTok().is(AsmToken::EndOfStatement)) {
4452       // We have a match!
4453       Operands.push_back(ARMOperand::CreateModImm((Enc & 0xFF),
4454                                                   (Enc & 0xF00) >> 7,
4455                                                   Sx1, Ex1));
4456       return MatchOperand_Success;
4457     }
4458   } else {
4459     Error(Sx1, "constant expression expected");
4460     return MatchOperand_ParseFail;
4461   }
4462
4463   if (Parser.getTok().isNot(AsmToken::Comma)) {
4464     // Consider [mov r0, #-10], which is aliased with mvn. We cannot fail
4465     // the parse here.
4466     Operands.push_back(ARMOperand::CreateImm(Imm1Exp, Sx1, Ex1));
4467     return MatchOperand_Success;
4468   }
4469
4470   // From this point onward, we expect the input to be a (#bits, #rot) pair
4471   if (Imm1 & ~0xFF) {
4472     Error(Sx1, "immediate operand must a number in the range [0, 255]");
4473     return MatchOperand_ParseFail;
4474   }
4475
4476   if (Lexer.peekTok().isNot(AsmToken::Hash) &&
4477        Lexer.peekTok().isNot(AsmToken::Dollar)) {
4478     Error(Lexer.peekTok().getLoc(), "immediate operand expected");
4479     return MatchOperand_ParseFail;
4480   }
4481
4482   // Eat the comma
4483   Parser.Lex();
4484
4485   // Repeat for #rot
4486   SMLoc Sx2, Ex2;
4487   Sx2 = Parser.getTok().getLoc();
4488
4489   // Eat the hash (or dollar)
4490   Parser.Lex();
4491
4492   const MCExpr *Imm2Exp;
4493   if (getParser().parseExpression(Imm2Exp, Ex2)) {
4494     Error(Sx2, "malformed expression");
4495     return MatchOperand_ParseFail;
4496   }
4497
4498   CE = dyn_cast<MCConstantExpr>(Imm2Exp);
4499
4500   if (CE) {
4501     Imm2 = CE->getValue();
4502     if (!(Imm2 & ~0x1E)) {
4503       // We have a match!
4504       Operands.push_back(ARMOperand::CreateModImm(Imm1, Imm2, S, Ex2));
4505       return MatchOperand_Success;
4506     }
4507     Error(Sx2, "immediate operand must an even number in the range [0, 30]");
4508     return MatchOperand_ParseFail;
4509   } else {
4510     Error(Sx2, "constant expression expected");
4511     return MatchOperand_ParseFail;
4512   }
4513 }
4514
4515 ARMAsmParser::OperandMatchResultTy
4516 ARMAsmParser::parseBitfield(OperandVector &Operands) {
4517   MCAsmParser &Parser = getParser();
4518   SMLoc S = Parser.getTok().getLoc();
4519   // The bitfield descriptor is really two operands, the LSB and the width.
4520   if (Parser.getTok().isNot(AsmToken::Hash) &&
4521       Parser.getTok().isNot(AsmToken::Dollar)) {
4522     Error(Parser.getTok().getLoc(), "'#' expected");
4523     return MatchOperand_ParseFail;
4524   }
4525   Parser.Lex(); // Eat hash token.
4526
4527   const MCExpr *LSBExpr;
4528   SMLoc E = Parser.getTok().getLoc();
4529   if (getParser().parseExpression(LSBExpr)) {
4530     Error(E, "malformed immediate expression");
4531     return MatchOperand_ParseFail;
4532   }
4533   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(LSBExpr);
4534   if (!CE) {
4535     Error(E, "'lsb' operand must be an immediate");
4536     return MatchOperand_ParseFail;
4537   }
4538
4539   int64_t LSB = CE->getValue();
4540   // The LSB must be in the range [0,31]
4541   if (LSB < 0 || LSB > 31) {
4542     Error(E, "'lsb' operand must be in the range [0,31]");
4543     return MatchOperand_ParseFail;
4544   }
4545   E = Parser.getTok().getLoc();
4546
4547   // Expect another immediate operand.
4548   if (Parser.getTok().isNot(AsmToken::Comma)) {
4549     Error(Parser.getTok().getLoc(), "too few operands");
4550     return MatchOperand_ParseFail;
4551   }
4552   Parser.Lex(); // Eat hash token.
4553   if (Parser.getTok().isNot(AsmToken::Hash) &&
4554       Parser.getTok().isNot(AsmToken::Dollar)) {
4555     Error(Parser.getTok().getLoc(), "'#' expected");
4556     return MatchOperand_ParseFail;
4557   }
4558   Parser.Lex(); // Eat hash token.
4559
4560   const MCExpr *WidthExpr;
4561   SMLoc EndLoc;
4562   if (getParser().parseExpression(WidthExpr, EndLoc)) {
4563     Error(E, "malformed immediate expression");
4564     return MatchOperand_ParseFail;
4565   }
4566   CE = dyn_cast<MCConstantExpr>(WidthExpr);
4567   if (!CE) {
4568     Error(E, "'width' operand must be an immediate");
4569     return MatchOperand_ParseFail;
4570   }
4571
4572   int64_t Width = CE->getValue();
4573   // The LSB must be in the range [1,32-lsb]
4574   if (Width < 1 || Width > 32 - LSB) {
4575     Error(E, "'width' operand must be in the range [1,32-lsb]");
4576     return MatchOperand_ParseFail;
4577   }
4578
4579   Operands.push_back(ARMOperand::CreateBitfield(LSB, Width, S, EndLoc));
4580
4581   return MatchOperand_Success;
4582 }
4583
4584 ARMAsmParser::OperandMatchResultTy
4585 ARMAsmParser::parsePostIdxReg(OperandVector &Operands) {
4586   // Check for a post-index addressing register operand. Specifically:
4587   // postidx_reg := '+' register {, shift}
4588   //              | '-' register {, shift}
4589   //              | register {, shift}
4590
4591   // This method must return MatchOperand_NoMatch without consuming any tokens
4592   // in the case where there is no match, as other alternatives take other
4593   // parse methods.
4594   MCAsmParser &Parser = getParser();
4595   AsmToken Tok = Parser.getTok();
4596   SMLoc S = Tok.getLoc();
4597   bool haveEaten = false;
4598   bool isAdd = true;
4599   if (Tok.is(AsmToken::Plus)) {
4600     Parser.Lex(); // Eat the '+' token.
4601     haveEaten = true;
4602   } else if (Tok.is(AsmToken::Minus)) {
4603     Parser.Lex(); // Eat the '-' token.
4604     isAdd = false;
4605     haveEaten = true;
4606   }
4607
4608   SMLoc E = Parser.getTok().getEndLoc();
4609   int Reg = tryParseRegister();
4610   if (Reg == -1) {
4611     if (!haveEaten)
4612       return MatchOperand_NoMatch;
4613     Error(Parser.getTok().getLoc(), "register expected");
4614     return MatchOperand_ParseFail;
4615   }
4616
4617   ARM_AM::ShiftOpc ShiftTy = ARM_AM::no_shift;
4618   unsigned ShiftImm = 0;
4619   if (Parser.getTok().is(AsmToken::Comma)) {
4620     Parser.Lex(); // Eat the ','.
4621     if (parseMemRegOffsetShift(ShiftTy, ShiftImm))
4622       return MatchOperand_ParseFail;
4623
4624     // FIXME: Only approximates end...may include intervening whitespace.
4625     E = Parser.getTok().getLoc();
4626   }
4627
4628   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ShiftTy,
4629                                                   ShiftImm, S, E));
4630
4631   return MatchOperand_Success;
4632 }
4633
4634 ARMAsmParser::OperandMatchResultTy
4635 ARMAsmParser::parseAM3Offset(OperandVector &Operands) {
4636   // Check for a post-index addressing register operand. Specifically:
4637   // am3offset := '+' register
4638   //              | '-' register
4639   //              | register
4640   //              | # imm
4641   //              | # + imm
4642   //              | # - imm
4643
4644   // This method must return MatchOperand_NoMatch without consuming any tokens
4645   // in the case where there is no match, as other alternatives take other
4646   // parse methods.
4647   MCAsmParser &Parser = getParser();
4648   AsmToken Tok = Parser.getTok();
4649   SMLoc S = Tok.getLoc();
4650
4651   // Do immediates first, as we always parse those if we have a '#'.
4652   if (Parser.getTok().is(AsmToken::Hash) ||
4653       Parser.getTok().is(AsmToken::Dollar)) {
4654     Parser.Lex(); // Eat '#' or '$'.
4655     // Explicitly look for a '-', as we need to encode negative zero
4656     // differently.
4657     bool isNegative = Parser.getTok().is(AsmToken::Minus);
4658     const MCExpr *Offset;
4659     SMLoc E;
4660     if (getParser().parseExpression(Offset, E))
4661       return MatchOperand_ParseFail;
4662     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
4663     if (!CE) {
4664       Error(S, "constant expression expected");
4665       return MatchOperand_ParseFail;
4666     }
4667     // Negative zero is encoded as the flag value INT32_MIN.
4668     int32_t Val = CE->getValue();
4669     if (isNegative && Val == 0)
4670       Val = INT32_MIN;
4671
4672     Operands.push_back(
4673       ARMOperand::CreateImm(MCConstantExpr::Create(Val, getContext()), S, E));
4674
4675     return MatchOperand_Success;
4676   }
4677
4678
4679   bool haveEaten = false;
4680   bool isAdd = true;
4681   if (Tok.is(AsmToken::Plus)) {
4682     Parser.Lex(); // Eat the '+' token.
4683     haveEaten = true;
4684   } else if (Tok.is(AsmToken::Minus)) {
4685     Parser.Lex(); // Eat the '-' token.
4686     isAdd = false;
4687     haveEaten = true;
4688   }
4689
4690   Tok = Parser.getTok();
4691   int Reg = tryParseRegister();
4692   if (Reg == -1) {
4693     if (!haveEaten)
4694       return MatchOperand_NoMatch;
4695     Error(Tok.getLoc(), "register expected");
4696     return MatchOperand_ParseFail;
4697   }
4698
4699   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ARM_AM::no_shift,
4700                                                   0, S, Tok.getEndLoc()));
4701
4702   return MatchOperand_Success;
4703 }
4704
4705 /// Convert parsed operands to MCInst.  Needed here because this instruction
4706 /// only has two register operands, but multiplication is commutative so
4707 /// assemblers should accept both "mul rD, rN, rD" and "mul rD, rD, rN".
4708 void ARMAsmParser::cvtThumbMultiply(MCInst &Inst,
4709                                     const OperandVector &Operands) {
4710   ((ARMOperand &)*Operands[3]).addRegOperands(Inst, 1);
4711   ((ARMOperand &)*Operands[1]).addCCOutOperands(Inst, 1);
4712   // If we have a three-operand form, make sure to set Rn to be the operand
4713   // that isn't the same as Rd.
4714   unsigned RegOp = 4;
4715   if (Operands.size() == 6 &&
4716       ((ARMOperand &)*Operands[4]).getReg() ==
4717           ((ARMOperand &)*Operands[3]).getReg())
4718     RegOp = 5;
4719   ((ARMOperand &)*Operands[RegOp]).addRegOperands(Inst, 1);
4720   Inst.addOperand(Inst.getOperand(0));
4721   ((ARMOperand &)*Operands[2]).addCondCodeOperands(Inst, 2);
4722 }
4723
4724 void ARMAsmParser::cvtThumbBranches(MCInst &Inst,
4725                                     const OperandVector &Operands) {
4726   int CondOp = -1, ImmOp = -1;
4727   switch(Inst.getOpcode()) {
4728     case ARM::tB:
4729     case ARM::tBcc:  CondOp = 1; ImmOp = 2; break;
4730
4731     case ARM::t2B:
4732     case ARM::t2Bcc: CondOp = 1; ImmOp = 3; break;
4733
4734     default: llvm_unreachable("Unexpected instruction in cvtThumbBranches");
4735   }
4736   // first decide whether or not the branch should be conditional
4737   // by looking at it's location relative to an IT block
4738   if(inITBlock()) {
4739     // inside an IT block we cannot have any conditional branches. any 
4740     // such instructions needs to be converted to unconditional form
4741     switch(Inst.getOpcode()) {
4742       case ARM::tBcc: Inst.setOpcode(ARM::tB); break;
4743       case ARM::t2Bcc: Inst.setOpcode(ARM::t2B); break;
4744     }
4745   } else {
4746     // outside IT blocks we can only have unconditional branches with AL
4747     // condition code or conditional branches with non-AL condition code
4748     unsigned Cond = static_cast<ARMOperand &>(*Operands[CondOp]).getCondCode();
4749     switch(Inst.getOpcode()) {
4750       case ARM::tB:
4751       case ARM::tBcc: 
4752         Inst.setOpcode(Cond == ARMCC::AL ? ARM::tB : ARM::tBcc); 
4753         break;
4754       case ARM::t2B:
4755       case ARM::t2Bcc: 
4756         Inst.setOpcode(Cond == ARMCC::AL ? ARM::t2B : ARM::t2Bcc);
4757         break;
4758     }
4759   }
4760
4761   // now decide on encoding size based on branch target range
4762   switch(Inst.getOpcode()) {
4763     // classify tB as either t2B or t1B based on range of immediate operand
4764     case ARM::tB: {
4765       ARMOperand &op = static_cast<ARMOperand &>(*Operands[ImmOp]);
4766       if (!op.isSignedOffset<11, 1>() && isThumbTwo())
4767         Inst.setOpcode(ARM::t2B);
4768       break;
4769     }
4770     // classify tBcc as either t2Bcc or t1Bcc based on range of immediate operand
4771     case ARM::tBcc: {
4772       ARMOperand &op = static_cast<ARMOperand &>(*Operands[ImmOp]);
4773       if (!op.isSignedOffset<8, 1>() && isThumbTwo())
4774         Inst.setOpcode(ARM::t2Bcc);
4775       break;
4776     }
4777   }
4778   ((ARMOperand &)*Operands[ImmOp]).addImmOperands(Inst, 1);
4779   ((ARMOperand &)*Operands[CondOp]).addCondCodeOperands(Inst, 2);
4780 }
4781
4782 /// Parse an ARM memory expression, return false if successful else return true
4783 /// or an error.  The first token must be a '[' when called.
4784 bool ARMAsmParser::parseMemory(OperandVector &Operands) {
4785   MCAsmParser &Parser = getParser();
4786   SMLoc S, E;
4787   assert(Parser.getTok().is(AsmToken::LBrac) &&
4788          "Token is not a Left Bracket");
4789   S = Parser.getTok().getLoc();
4790   Parser.Lex(); // Eat left bracket token.
4791
4792   const AsmToken &BaseRegTok = Parser.getTok();
4793   int BaseRegNum = tryParseRegister();
4794   if (BaseRegNum == -1)
4795     return Error(BaseRegTok.getLoc(), "register expected");
4796
4797   // The next token must either be a comma, a colon or a closing bracket.
4798   const AsmToken &Tok = Parser.getTok();
4799   if (!Tok.is(AsmToken::Colon) && !Tok.is(AsmToken::Comma) &&
4800       !Tok.is(AsmToken::RBrac))
4801     return Error(Tok.getLoc(), "malformed memory operand");
4802
4803   if (Tok.is(AsmToken::RBrac)) {
4804     E = Tok.getEndLoc();
4805     Parser.Lex(); // Eat right bracket token.
4806
4807     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, 0,
4808                                              ARM_AM::no_shift, 0, 0, false,
4809                                              S, E));
4810
4811     // If there's a pre-indexing writeback marker, '!', just add it as a token
4812     // operand. It's rather odd, but syntactically valid.
4813     if (Parser.getTok().is(AsmToken::Exclaim)) {
4814       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
4815       Parser.Lex(); // Eat the '!'.
4816     }
4817
4818     return false;
4819   }
4820
4821   assert((Tok.is(AsmToken::Colon) || Tok.is(AsmToken::Comma)) &&
4822          "Lost colon or comma in memory operand?!");
4823   if (Tok.is(AsmToken::Comma)) {
4824     Parser.Lex(); // Eat the comma.
4825   }
4826
4827   // If we have a ':', it's an alignment specifier.
4828   if (Parser.getTok().is(AsmToken::Colon)) {
4829     Parser.Lex(); // Eat the ':'.
4830     E = Parser.getTok().getLoc();
4831     SMLoc AlignmentLoc = Tok.getLoc();
4832
4833     const MCExpr *Expr;
4834     if (getParser().parseExpression(Expr))
4835      return true;
4836
4837     // The expression has to be a constant. Memory references with relocations
4838     // don't come through here, as they use the <label> forms of the relevant
4839     // instructions.
4840     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
4841     if (!CE)
4842       return Error (E, "constant expression expected");
4843
4844     unsigned Align = 0;
4845     switch (CE->getValue()) {
4846     default:
4847       return Error(E,
4848                    "alignment specifier must be 16, 32, 64, 128, or 256 bits");
4849     case 16:  Align = 2; break;
4850     case 32:  Align = 4; break;
4851     case 64:  Align = 8; break;
4852     case 128: Align = 16; break;
4853     case 256: Align = 32; break;
4854     }
4855
4856     // Now we should have the closing ']'
4857     if (Parser.getTok().isNot(AsmToken::RBrac))
4858       return Error(Parser.getTok().getLoc(), "']' expected");
4859     E = Parser.getTok().getEndLoc();
4860     Parser.Lex(); // Eat right bracket token.
4861
4862     // Don't worry about range checking the value here. That's handled by
4863     // the is*() predicates.
4864     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, 0,
4865                                              ARM_AM::no_shift, 0, Align,
4866                                              false, S, E, AlignmentLoc));
4867
4868     // If there's a pre-indexing writeback marker, '!', just add it as a token
4869     // operand.
4870     if (Parser.getTok().is(AsmToken::Exclaim)) {
4871       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
4872       Parser.Lex(); // Eat the '!'.
4873     }
4874
4875     return false;
4876   }
4877
4878   // If we have a '#', it's an immediate offset, else assume it's a register
4879   // offset. Be friendly and also accept a plain integer (without a leading
4880   // hash) for gas compatibility.
4881   if (Parser.getTok().is(AsmToken::Hash) ||
4882       Parser.getTok().is(AsmToken::Dollar) ||
4883       Parser.getTok().is(AsmToken::Integer)) {
4884     if (Parser.getTok().isNot(AsmToken::Integer))
4885       Parser.Lex(); // Eat '#' or '$'.
4886     E = Parser.getTok().getLoc();
4887
4888     bool isNegative = getParser().getTok().is(AsmToken::Minus);
4889     const MCExpr *Offset;
4890     if (getParser().parseExpression(Offset))
4891      return true;
4892
4893     // The expression has to be a constant. Memory references with relocations
4894     // don't come through here, as they use the <label> forms of the relevant
4895     // instructions.
4896     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
4897     if (!CE)
4898       return Error (E, "constant expression expected");
4899
4900     // If the constant was #-0, represent it as INT32_MIN.
4901     int32_t Val = CE->getValue();
4902     if (isNegative && Val == 0)
4903       CE = MCConstantExpr::Create(INT32_MIN, getContext());
4904
4905     // Now we should have the closing ']'
4906     if (Parser.getTok().isNot(AsmToken::RBrac))
4907       return Error(Parser.getTok().getLoc(), "']' expected");
4908     E = Parser.getTok().getEndLoc();
4909     Parser.Lex(); // Eat right bracket token.
4910
4911     // Don't worry about range checking the value here. That's handled by
4912     // the is*() predicates.
4913     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, CE, 0,
4914                                              ARM_AM::no_shift, 0, 0,
4915                                              false, S, E));
4916
4917     // If there's a pre-indexing writeback marker, '!', just add it as a token
4918     // operand.
4919     if (Parser.getTok().is(AsmToken::Exclaim)) {
4920       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
4921       Parser.Lex(); // Eat the '!'.
4922     }
4923
4924     return false;
4925   }
4926
4927   // The register offset is optionally preceded by a '+' or '-'
4928   bool isNegative = false;
4929   if (Parser.getTok().is(AsmToken::Minus)) {
4930     isNegative = true;
4931     Parser.Lex(); // Eat the '-'.
4932   } else if (Parser.getTok().is(AsmToken::Plus)) {
4933     // Nothing to do.
4934     Parser.Lex(); // Eat the '+'.
4935   }
4936
4937   E = Parser.getTok().getLoc();
4938   int OffsetRegNum = tryParseRegister();
4939   if (OffsetRegNum == -1)
4940     return Error(E, "register expected");
4941
4942   // If there's a shift operator, handle it.
4943   ARM_AM::ShiftOpc ShiftType = ARM_AM::no_shift;
4944   unsigned ShiftImm = 0;
4945   if (Parser.getTok().is(AsmToken::Comma)) {
4946     Parser.Lex(); // Eat the ','.
4947     if (parseMemRegOffsetShift(ShiftType, ShiftImm))
4948       return true;
4949   }
4950
4951   // Now we should have the closing ']'
4952   if (Parser.getTok().isNot(AsmToken::RBrac))
4953     return Error(Parser.getTok().getLoc(), "']' expected");
4954   E = Parser.getTok().getEndLoc();
4955   Parser.Lex(); // Eat right bracket token.
4956
4957   Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, OffsetRegNum,
4958                                            ShiftType, ShiftImm, 0, isNegative,
4959                                            S, E));
4960
4961   // If there's a pre-indexing writeback marker, '!', just add it as a token
4962   // operand.
4963   if (Parser.getTok().is(AsmToken::Exclaim)) {
4964     Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
4965     Parser.Lex(); // Eat the '!'.
4966   }
4967
4968   return false;
4969 }
4970
4971 /// parseMemRegOffsetShift - one of these two:
4972 ///   ( lsl | lsr | asr | ror ) , # shift_amount
4973 ///   rrx
4974 /// return true if it parses a shift otherwise it returns false.
4975 bool ARMAsmParser::parseMemRegOffsetShift(ARM_AM::ShiftOpc &St,
4976                                           unsigned &Amount) {
4977   MCAsmParser &Parser = getParser();
4978   SMLoc Loc = Parser.getTok().getLoc();
4979   const AsmToken &Tok = Parser.getTok();
4980   if (Tok.isNot(AsmToken::Identifier))
4981     return true;
4982   StringRef ShiftName = Tok.getString();
4983   if (ShiftName == "lsl" || ShiftName == "LSL" ||
4984       ShiftName == "asl" || ShiftName == "ASL")
4985     St = ARM_AM::lsl;
4986   else if (ShiftName == "lsr" || ShiftName == "LSR")
4987     St = ARM_AM::lsr;
4988   else if (ShiftName == "asr" || ShiftName == "ASR")
4989     St = ARM_AM::asr;
4990   else if (ShiftName == "ror" || ShiftName == "ROR")
4991     St = ARM_AM::ror;
4992   else if (ShiftName == "rrx" || ShiftName == "RRX")
4993     St = ARM_AM::rrx;
4994   else
4995     return Error(Loc, "illegal shift operator");
4996   Parser.Lex(); // Eat shift type token.
4997
4998   // rrx stands alone.
4999   Amount = 0;
5000   if (St != ARM_AM::rrx) {
5001     Loc = Parser.getTok().getLoc();
5002     // A '#' and a shift amount.
5003     const AsmToken &HashTok = Parser.getTok();
5004     if (HashTok.isNot(AsmToken::Hash) &&
5005         HashTok.isNot(AsmToken::Dollar))
5006       return Error(HashTok.getLoc(), "'#' expected");
5007     Parser.Lex(); // Eat hash token.
5008
5009     const MCExpr *Expr;
5010     if (getParser().parseExpression(Expr))
5011       return true;
5012     // Range check the immediate.
5013     // lsl, ror: 0 <= imm <= 31
5014     // lsr, asr: 0 <= imm <= 32
5015     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
5016     if (!CE)
5017       return Error(Loc, "shift amount must be an immediate");
5018     int64_t Imm = CE->getValue();
5019     if (Imm < 0 ||
5020         ((St == ARM_AM::lsl || St == ARM_AM::ror) && Imm > 31) ||
5021         ((St == ARM_AM::lsr || St == ARM_AM::asr) && Imm > 32))
5022       return Error(Loc, "immediate shift value out of range");
5023     // If <ShiftTy> #0, turn it into a no_shift.
5024     if (Imm == 0)
5025       St = ARM_AM::lsl;
5026     // For consistency, treat lsr #32 and asr #32 as having immediate value 0.
5027     if (Imm == 32)
5028       Imm = 0;
5029     Amount = Imm;
5030   }
5031
5032   return false;
5033 }
5034
5035 /// parseFPImm - A floating point immediate expression operand.
5036 ARMAsmParser::OperandMatchResultTy
5037 ARMAsmParser::parseFPImm(OperandVector &Operands) {
5038   MCAsmParser &Parser = getParser();
5039   // Anything that can accept a floating point constant as an operand
5040   // needs to go through here, as the regular parseExpression is
5041   // integer only.
5042   //
5043   // This routine still creates a generic Immediate operand, containing
5044   // a bitcast of the 64-bit floating point value. The various operands
5045   // that accept floats can check whether the value is valid for them
5046   // via the standard is*() predicates.
5047
5048   SMLoc S = Parser.getTok().getLoc();
5049
5050   if (Parser.getTok().isNot(AsmToken::Hash) &&
5051       Parser.getTok().isNot(AsmToken::Dollar))
5052     return MatchOperand_NoMatch;
5053
5054   // Disambiguate the VMOV forms that can accept an FP immediate.
5055   // vmov.f32 <sreg>, #imm
5056   // vmov.f64 <dreg>, #imm
5057   // vmov.f32 <dreg>, #imm  @ vector f32x2
5058   // vmov.f32 <qreg>, #imm  @ vector f32x4
5059   //
5060   // There are also the NEON VMOV instructions which expect an
5061   // integer constant. Make sure we don't try to parse an FPImm
5062   // for these:
5063   // vmov.i{8|16|32|64} <dreg|qreg>, #imm
5064   ARMOperand &TyOp = static_cast<ARMOperand &>(*Operands[2]);
5065   bool isVmovf = TyOp.isToken() &&
5066                  (TyOp.getToken() == ".f32" || TyOp.getToken() == ".f64");
5067   ARMOperand &Mnemonic = static_cast<ARMOperand &>(*Operands[0]);
5068   bool isFconst = Mnemonic.isToken() && (Mnemonic.getToken() == "fconstd" ||
5069                                          Mnemonic.getToken() == "fconsts");
5070   if (!(isVmovf || isFconst))
5071     return MatchOperand_NoMatch;
5072
5073   Parser.Lex(); // Eat '#' or '$'.
5074
5075   // Handle negation, as that still comes through as a separate token.
5076   bool isNegative = false;
5077   if (Parser.getTok().is(AsmToken::Minus)) {
5078     isNegative = true;
5079     Parser.Lex();
5080   }
5081   const AsmToken &Tok = Parser.getTok();
5082   SMLoc Loc = Tok.getLoc();
5083   if (Tok.is(AsmToken::Real) && isVmovf) {
5084     APFloat RealVal(APFloat::IEEEsingle, Tok.getString());
5085     uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
5086     // If we had a '-' in front, toggle the sign bit.
5087     IntVal ^= (uint64_t)isNegative << 31;
5088     Parser.Lex(); // Eat the token.
5089     Operands.push_back(ARMOperand::CreateImm(
5090           MCConstantExpr::Create(IntVal, getContext()),
5091           S, Parser.getTok().getLoc()));
5092     return MatchOperand_Success;
5093   }
5094   // Also handle plain integers. Instructions which allow floating point
5095   // immediates also allow a raw encoded 8-bit value.
5096   if (Tok.is(AsmToken::Integer) && isFconst) {
5097     int64_t Val = Tok.getIntVal();
5098     Parser.Lex(); // Eat the token.
5099     if (Val > 255 || Val < 0) {
5100       Error(Loc, "encoded floating point value out of range");
5101       return MatchOperand_ParseFail;
5102     }
5103     float RealVal = ARM_AM::getFPImmFloat(Val);
5104     Val = APFloat(RealVal).bitcastToAPInt().getZExtValue();
5105
5106     Operands.push_back(ARMOperand::CreateImm(
5107         MCConstantExpr::Create(Val, getContext()), S,
5108         Parser.getTok().getLoc()));
5109     return MatchOperand_Success;
5110   }
5111
5112   Error(Loc, "invalid floating point immediate");
5113   return MatchOperand_ParseFail;
5114 }
5115
5116 /// Parse a arm instruction operand.  For now this parses the operand regardless
5117 /// of the mnemonic.
5118 bool ARMAsmParser::parseOperand(OperandVector &Operands, StringRef Mnemonic) {
5119   MCAsmParser &Parser = getParser();
5120   SMLoc S, E;
5121
5122   // Check if the current operand has a custom associated parser, if so, try to
5123   // custom parse the operand, or fallback to the general approach.
5124   OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
5125   if (ResTy == MatchOperand_Success)
5126     return false;
5127   // If there wasn't a custom match, try the generic matcher below. Otherwise,
5128   // there was a match, but an error occurred, in which case, just return that
5129   // the operand parsing failed.
5130   if (ResTy == MatchOperand_ParseFail)
5131     return true;
5132
5133   switch (getLexer().getKind()) {
5134   default:
5135     Error(Parser.getTok().getLoc(), "unexpected token in operand");
5136     return true;
5137   case AsmToken::Identifier: {
5138     // If we've seen a branch mnemonic, the next operand must be a label.  This
5139     // is true even if the label is a register name.  So "br r1" means branch to
5140     // label "r1".
5141     bool ExpectLabel = Mnemonic == "b" || Mnemonic == "bl";
5142     if (!ExpectLabel) {
5143       if (!tryParseRegisterWithWriteBack(Operands))
5144         return false;
5145       int Res = tryParseShiftRegister(Operands);
5146       if (Res == 0) // success
5147         return false;
5148       else if (Res == -1) // irrecoverable error
5149         return true;
5150       // If this is VMRS, check for the apsr_nzcv operand.
5151       if (Mnemonic == "vmrs" &&
5152           Parser.getTok().getString().equals_lower("apsr_nzcv")) {
5153         S = Parser.getTok().getLoc();
5154         Parser.Lex();
5155         Operands.push_back(ARMOperand::CreateToken("APSR_nzcv", S));
5156         return false;
5157       }
5158     }
5159
5160     // Fall though for the Identifier case that is not a register or a
5161     // special name.
5162   }
5163   case AsmToken::LParen:  // parenthesized expressions like (_strcmp-4)
5164   case AsmToken::Integer: // things like 1f and 2b as a branch targets
5165   case AsmToken::String:  // quoted label names.
5166   case AsmToken::Dot: {   // . as a branch target
5167     // This was not a register so parse other operands that start with an
5168     // identifier (like labels) as expressions and create them as immediates.
5169     const MCExpr *IdVal;
5170     S = Parser.getTok().getLoc();
5171     if (getParser().parseExpression(IdVal))
5172       return true;
5173     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5174     Operands.push_back(ARMOperand::CreateImm(IdVal, S, E));
5175     return false;
5176   }
5177   case AsmToken::LBrac:
5178     return parseMemory(Operands);
5179   case AsmToken::LCurly:
5180     return parseRegisterList(Operands);
5181   case AsmToken::Dollar:
5182   case AsmToken::Hash: {
5183     // #42 -> immediate.
5184     S = Parser.getTok().getLoc();
5185     Parser.Lex();
5186
5187     if (Parser.getTok().isNot(AsmToken::Colon)) {
5188       bool isNegative = Parser.getTok().is(AsmToken::Minus);
5189       const MCExpr *ImmVal;
5190       if (getParser().parseExpression(ImmVal))
5191         return true;
5192       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ImmVal);
5193       if (CE) {
5194         int32_t Val = CE->getValue();
5195         if (isNegative && Val == 0)
5196           ImmVal = MCConstantExpr::Create(INT32_MIN, getContext());
5197       }
5198       E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5199       Operands.push_back(ARMOperand::CreateImm(ImmVal, S, E));
5200
5201       // There can be a trailing '!' on operands that we want as a separate
5202       // '!' Token operand. Handle that here. For example, the compatibility
5203       // alias for 'srsdb sp!, #imm' is 'srsdb #imm!'.
5204       if (Parser.getTok().is(AsmToken::Exclaim)) {
5205         Operands.push_back(ARMOperand::CreateToken(Parser.getTok().getString(),
5206                                                    Parser.getTok().getLoc()));
5207         Parser.Lex(); // Eat exclaim token
5208       }
5209       return false;
5210     }
5211     // w/ a ':' after the '#', it's just like a plain ':'.
5212     // FALLTHROUGH
5213   }
5214   case AsmToken::Colon: {
5215     // ":lower16:" and ":upper16:" expression prefixes
5216     // FIXME: Check it's an expression prefix,
5217     // e.g. (FOO - :lower16:BAR) isn't legal.
5218     ARMMCExpr::VariantKind RefKind;
5219     if (parsePrefix(RefKind))
5220       return true;
5221
5222     const MCExpr *SubExprVal;
5223     if (getParser().parseExpression(SubExprVal))
5224       return true;
5225
5226     const MCExpr *ExprVal = ARMMCExpr::Create(RefKind, SubExprVal,
5227                                               getContext());
5228     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5229     Operands.push_back(ARMOperand::CreateImm(ExprVal, S, E));
5230     return false;
5231   }
5232   case AsmToken::Equal: {
5233     if (Mnemonic != "ldr") // only parse for ldr pseudo (e.g. ldr r0, =val)
5234       return Error(Parser.getTok().getLoc(), "unexpected token in operand");
5235
5236     Parser.Lex(); // Eat '='
5237     const MCExpr *SubExprVal;
5238     if (getParser().parseExpression(SubExprVal))
5239       return true;
5240     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5241
5242     const MCExpr *CPLoc = getTargetStreamer().addConstantPoolEntry(SubExprVal);
5243     Operands.push_back(ARMOperand::CreateImm(CPLoc, S, E));
5244     return false;
5245   }
5246   }
5247 }
5248
5249 // parsePrefix - Parse ARM 16-bit relocations expression prefix, i.e.
5250 //  :lower16: and :upper16:.
5251 bool ARMAsmParser::parsePrefix(ARMMCExpr::VariantKind &RefKind) {
5252   MCAsmParser &Parser = getParser();
5253   RefKind = ARMMCExpr::VK_ARM_None;
5254
5255   // consume an optional '#' (GNU compatibility)
5256   if (getLexer().is(AsmToken::Hash))
5257     Parser.Lex();
5258
5259   // :lower16: and :upper16: modifiers
5260   assert(getLexer().is(AsmToken::Colon) && "expected a :");
5261   Parser.Lex(); // Eat ':'
5262
5263   if (getLexer().isNot(AsmToken::Identifier)) {
5264     Error(Parser.getTok().getLoc(), "expected prefix identifier in operand");
5265     return true;
5266   }
5267
5268   StringRef IDVal = Parser.getTok().getIdentifier();
5269   if (IDVal == "lower16") {
5270     RefKind = ARMMCExpr::VK_ARM_LO16;
5271   } else if (IDVal == "upper16") {
5272     RefKind = ARMMCExpr::VK_ARM_HI16;
5273   } else {
5274     Error(Parser.getTok().getLoc(), "unexpected prefix in operand");
5275     return true;
5276   }
5277   Parser.Lex();
5278
5279   if (getLexer().isNot(AsmToken::Colon)) {
5280     Error(Parser.getTok().getLoc(), "unexpected token after prefix");
5281     return true;
5282   }
5283   Parser.Lex(); // Eat the last ':'
5284   return false;
5285 }
5286
5287 /// \brief Given a mnemonic, split out possible predication code and carry
5288 /// setting letters to form a canonical mnemonic and flags.
5289 //
5290 // FIXME: Would be nice to autogen this.
5291 // FIXME: This is a bit of a maze of special cases.
5292 StringRef ARMAsmParser::splitMnemonic(StringRef Mnemonic,
5293                                       unsigned &PredicationCode,
5294                                       bool &CarrySetting,
5295                                       unsigned &ProcessorIMod,
5296                                       StringRef &ITMask) {
5297   PredicationCode = ARMCC::AL;
5298   CarrySetting = false;
5299   ProcessorIMod = 0;
5300
5301   // Ignore some mnemonics we know aren't predicated forms.
5302   //
5303   // FIXME: Would be nice to autogen this.
5304   if ((Mnemonic == "movs" && isThumb()) ||
5305       Mnemonic == "teq"   || Mnemonic == "vceq"   || Mnemonic == "svc"   ||
5306       Mnemonic == "mls"   || Mnemonic == "smmls"  || Mnemonic == "vcls"  ||
5307       Mnemonic == "vmls"  || Mnemonic == "vnmls"  || Mnemonic == "vacge" ||
5308       Mnemonic == "vcge"  || Mnemonic == "vclt"   || Mnemonic == "vacgt" ||
5309       Mnemonic == "vaclt" || Mnemonic == "vacle"  || Mnemonic == "hlt" ||
5310       Mnemonic == "vcgt"  || Mnemonic == "vcle"   || Mnemonic == "smlal" ||
5311       Mnemonic == "umaal" || Mnemonic == "umlal"  || Mnemonic == "vabal" ||
5312       Mnemonic == "vmlal" || Mnemonic == "vpadal" || Mnemonic == "vqdmlal" ||
5313       Mnemonic == "fmuls" || Mnemonic == "vmaxnm" || Mnemonic == "vminnm" ||
5314       Mnemonic == "vcvta" || Mnemonic == "vcvtn"  || Mnemonic == "vcvtp" ||
5315       Mnemonic == "vcvtm" || Mnemonic == "vrinta" || Mnemonic == "vrintn" ||
5316       Mnemonic == "vrintp" || Mnemonic == "vrintm" || Mnemonic == "hvc" ||
5317       Mnemonic.startswith("vsel"))
5318     return Mnemonic;
5319
5320   // First, split out any predication code. Ignore mnemonics we know aren't
5321   // predicated but do have a carry-set and so weren't caught above.
5322   if (Mnemonic != "adcs" && Mnemonic != "bics" && Mnemonic != "movs" &&
5323       Mnemonic != "muls" && Mnemonic != "smlals" && Mnemonic != "smulls" &&
5324       Mnemonic != "umlals" && Mnemonic != "umulls" && Mnemonic != "lsls" &&
5325       Mnemonic != "sbcs" && Mnemonic != "rscs") {
5326     unsigned CC = StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2))
5327       .Case("eq", ARMCC::EQ)
5328       .Case("ne", ARMCC::NE)
5329       .Case("hs", ARMCC::HS)
5330       .Case("cs", ARMCC::HS)
5331       .Case("lo", ARMCC::LO)
5332       .Case("cc", ARMCC::LO)
5333       .Case("mi", ARMCC::MI)
5334       .Case("pl", ARMCC::PL)
5335       .Case("vs", ARMCC::VS)
5336       .Case("vc", ARMCC::VC)
5337       .Case("hi", ARMCC::HI)
5338       .Case("ls", ARMCC::LS)
5339       .Case("ge", ARMCC::GE)
5340       .Case("lt", ARMCC::LT)
5341       .Case("gt", ARMCC::GT)
5342       .Case("le", ARMCC::LE)
5343       .Case("al", ARMCC::AL)
5344       .Default(~0U);
5345     if (CC != ~0U) {
5346       Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 2);
5347       PredicationCode = CC;
5348     }
5349   }
5350
5351   // Next, determine if we have a carry setting bit. We explicitly ignore all
5352   // the instructions we know end in 's'.
5353   if (Mnemonic.endswith("s") &&
5354       !(Mnemonic == "cps" || Mnemonic == "mls" ||
5355         Mnemonic == "mrs" || Mnemonic == "smmls" || Mnemonic == "vabs" ||
5356         Mnemonic == "vcls" || Mnemonic == "vmls" || Mnemonic == "vmrs" ||
5357         Mnemonic == "vnmls" || Mnemonic == "vqabs" || Mnemonic == "vrecps" ||
5358         Mnemonic == "vrsqrts" || Mnemonic == "srs" || Mnemonic == "flds" ||
5359         Mnemonic == "fmrs" || Mnemonic == "fsqrts" || Mnemonic == "fsubs" ||
5360         Mnemonic == "fsts" || Mnemonic == "fcpys" || Mnemonic == "fdivs" ||
5361         Mnemonic == "fmuls" || Mnemonic == "fcmps" || Mnemonic == "fcmpzs" ||
5362         Mnemonic == "vfms" || Mnemonic == "vfnms" || Mnemonic == "fconsts" ||
5363         (Mnemonic == "movs" && isThumb()))) {
5364     Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 1);
5365     CarrySetting = true;
5366   }
5367
5368   // The "cps" instruction can have a interrupt mode operand which is glued into
5369   // the mnemonic. Check if this is the case, split it and parse the imod op
5370   if (Mnemonic.startswith("cps")) {
5371     // Split out any imod code.
5372     unsigned IMod =
5373       StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2, 2))
5374       .Case("ie", ARM_PROC::IE)
5375       .Case("id", ARM_PROC::ID)
5376       .Default(~0U);
5377     if (IMod != ~0U) {
5378       Mnemonic = Mnemonic.slice(0, Mnemonic.size()-2);
5379       ProcessorIMod = IMod;
5380     }
5381   }
5382
5383   // The "it" instruction has the condition mask on the end of the mnemonic.
5384   if (Mnemonic.startswith("it")) {
5385     ITMask = Mnemonic.slice(2, Mnemonic.size());
5386     Mnemonic = Mnemonic.slice(0, 2);
5387   }
5388
5389   return Mnemonic;
5390 }
5391
5392 /// \brief Given a canonical mnemonic, determine if the instruction ever allows
5393 /// inclusion of carry set or predication code operands.
5394 //
5395 // FIXME: It would be nice to autogen this.
5396 void ARMAsmParser::
5397 getMnemonicAcceptInfo(StringRef Mnemonic, StringRef FullInst,
5398                      bool &CanAcceptCarrySet, bool &CanAcceptPredicationCode) {
5399   if (Mnemonic == "and" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
5400       Mnemonic == "rrx" || Mnemonic == "ror" || Mnemonic == "sub" ||
5401       Mnemonic == "add" || Mnemonic == "adc" ||
5402       Mnemonic == "mul" || Mnemonic == "bic" || Mnemonic == "asr" ||
5403       Mnemonic == "orr" || Mnemonic == "mvn" ||
5404       Mnemonic == "rsb" || Mnemonic == "rsc" || Mnemonic == "orn" ||
5405       Mnemonic == "sbc" || Mnemonic == "eor" || Mnemonic == "neg" ||
5406       Mnemonic == "vfm" || Mnemonic == "vfnm" ||
5407       (!isThumb() && (Mnemonic == "smull" || Mnemonic == "mov" ||
5408                       Mnemonic == "mla" || Mnemonic == "smlal" ||
5409                       Mnemonic == "umlal" || Mnemonic == "umull"))) {
5410     CanAcceptCarrySet = true;
5411   } else
5412     CanAcceptCarrySet = false;
5413
5414   if (Mnemonic == "bkpt" || Mnemonic == "cbnz" || Mnemonic == "setend" ||
5415       Mnemonic == "cps" ||  Mnemonic == "it" ||  Mnemonic == "cbz" ||
5416       Mnemonic == "trap" || Mnemonic == "hlt" || Mnemonic == "udf" ||
5417       Mnemonic.startswith("crc32") || Mnemonic.startswith("cps") ||
5418       Mnemonic.startswith("vsel") ||
5419       Mnemonic == "vmaxnm" || Mnemonic == "vminnm" || Mnemonic == "vcvta" ||
5420       Mnemonic == "vcvtn" || Mnemonic == "vcvtp" || Mnemonic == "vcvtm" ||
5421       Mnemonic == "vrinta" || Mnemonic == "vrintn" || Mnemonic == "vrintp" ||
5422       Mnemonic == "vrintm" || Mnemonic.startswith("aes") || Mnemonic == "hvc" ||
5423       Mnemonic.startswith("sha1") || Mnemonic.startswith("sha256") ||
5424       (FullInst.startswith("vmull") && FullInst.endswith(".p64"))) {
5425     // These mnemonics are never predicable
5426     CanAcceptPredicationCode = false;
5427   } else if (!isThumb()) {
5428     // Some instructions are only predicable in Thumb mode
5429     CanAcceptPredicationCode
5430       = Mnemonic != "cdp2" && Mnemonic != "clrex" && Mnemonic != "mcr2" &&
5431         Mnemonic != "mcrr2" && Mnemonic != "mrc2" && Mnemonic != "mrrc2" &&
5432         Mnemonic != "dmb" && Mnemonic != "dsb" && Mnemonic != "isb" &&
5433         Mnemonic != "pld" && Mnemonic != "pli" && Mnemonic != "pldw" &&
5434         Mnemonic != "ldc2" && Mnemonic != "ldc2l" &&
5435         Mnemonic != "stc2" && Mnemonic != "stc2l" &&
5436         !Mnemonic.startswith("rfe") && !Mnemonic.startswith("srs");
5437   } else if (isThumbOne()) {
5438     if (hasV6MOps())
5439       CanAcceptPredicationCode = Mnemonic != "movs";
5440     else
5441       CanAcceptPredicationCode = Mnemonic != "nop" && Mnemonic != "movs";
5442   } else
5443     CanAcceptPredicationCode = true;
5444 }
5445
5446 bool ARMAsmParser::shouldOmitCCOutOperand(StringRef Mnemonic,
5447                                           OperandVector &Operands) {
5448   // FIXME: This is all horribly hacky. We really need a better way to deal
5449   // with optional operands like this in the matcher table.
5450
5451   // The 'mov' mnemonic is special. One variant has a cc_out operand, while
5452   // another does not. Specifically, the MOVW instruction does not. So we
5453   // special case it here and remove the defaulted (non-setting) cc_out
5454   // operand if that's the instruction we're trying to match.
5455   //
5456   // We do this as post-processing of the explicit operands rather than just
5457   // conditionally adding the cc_out in the first place because we need
5458   // to check the type of the parsed immediate operand.
5459   if (Mnemonic == "mov" && Operands.size() > 4 && !isThumb() &&
5460       !static_cast<ARMOperand &>(*Operands[4]).isARMSOImm() &&
5461       static_cast<ARMOperand &>(*Operands[4]).isImm0_65535Expr() &&
5462       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0)
5463     return true;
5464
5465   // Register-register 'add' for thumb does not have a cc_out operand
5466   // when there are only two register operands.
5467   if (isThumb() && Mnemonic == "add" && Operands.size() == 5 &&
5468       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5469       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5470       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0)
5471     return true;
5472   // Register-register 'add' for thumb does not have a cc_out operand
5473   // when it's an ADD Rdm, SP, {Rdm|#imm0_255} instruction. We do
5474   // have to check the immediate range here since Thumb2 has a variant
5475   // that can handle a different range and has a cc_out operand.
5476   if (((isThumb() && Mnemonic == "add") ||
5477        (isThumbTwo() && Mnemonic == "sub")) &&
5478       Operands.size() == 6 && static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5479       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5480       static_cast<ARMOperand &>(*Operands[4]).getReg() == ARM::SP &&
5481       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5482       ((Mnemonic == "add" && static_cast<ARMOperand &>(*Operands[5]).isReg()) ||
5483        static_cast<ARMOperand &>(*Operands[5]).isImm0_1020s4()))
5484     return true;
5485   // For Thumb2, add/sub immediate does not have a cc_out operand for the
5486   // imm0_4095 variant. That's the least-preferred variant when
5487   // selecting via the generic "add" mnemonic, so to know that we
5488   // should remove the cc_out operand, we have to explicitly check that
5489   // it's not one of the other variants. Ugh.
5490   if (isThumbTwo() && (Mnemonic == "add" || Mnemonic == "sub") &&
5491       Operands.size() == 6 && static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5492       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5493       static_cast<ARMOperand &>(*Operands[5]).isImm()) {
5494     // Nest conditions rather than one big 'if' statement for readability.
5495     //
5496     // If both registers are low, we're in an IT block, and the immediate is
5497     // in range, we should use encoding T1 instead, which has a cc_out.
5498     if (inITBlock() &&
5499         isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) &&
5500         isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) &&
5501         static_cast<ARMOperand &>(*Operands[5]).isImm0_7())
5502       return false;
5503     // Check against T3. If the second register is the PC, this is an
5504     // alternate form of ADR, which uses encoding T4, so check for that too.
5505     if (static_cast<ARMOperand &>(*Operands[4]).getReg() != ARM::PC &&
5506         static_cast<ARMOperand &>(*Operands[5]).isT2SOImm())
5507       return false;
5508
5509     // Otherwise, we use encoding T4, which does not have a cc_out
5510     // operand.
5511     return true;
5512   }
5513
5514   // The thumb2 multiply instruction doesn't have a CCOut register, so
5515   // if we have a "mul" mnemonic in Thumb mode, check if we'll be able to
5516   // use the 16-bit encoding or not.
5517   if (isThumbTwo() && Mnemonic == "mul" && Operands.size() == 6 &&
5518       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5519       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5520       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5521       static_cast<ARMOperand &>(*Operands[5]).isReg() &&
5522       // If the registers aren't low regs, the destination reg isn't the
5523       // same as one of the source regs, or the cc_out operand is zero
5524       // outside of an IT block, we have to use the 32-bit encoding, so
5525       // remove the cc_out operand.
5526       (!isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) ||
5527        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) ||
5528        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[5]).getReg()) ||
5529        !inITBlock() || (static_cast<ARMOperand &>(*Operands[3]).getReg() !=
5530                             static_cast<ARMOperand &>(*Operands[5]).getReg() &&
5531                         static_cast<ARMOperand &>(*Operands[3]).getReg() !=
5532                             static_cast<ARMOperand &>(*Operands[4]).getReg())))
5533     return true;
5534
5535   // Also check the 'mul' syntax variant that doesn't specify an explicit
5536   // destination register.
5537   if (isThumbTwo() && Mnemonic == "mul" && Operands.size() == 5 &&
5538       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5539       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5540       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5541       // If the registers aren't low regs  or the cc_out operand is zero
5542       // outside of an IT block, we have to use the 32-bit encoding, so
5543       // remove the cc_out operand.
5544       (!isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) ||
5545        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) ||
5546        !inITBlock()))
5547     return true;
5548
5549
5550
5551   // Register-register 'add/sub' for thumb does not have a cc_out operand
5552   // when it's an ADD/SUB SP, #imm. Be lenient on count since there's also
5553   // the "add/sub SP, SP, #imm" version. If the follow-up operands aren't
5554   // right, this will result in better diagnostics (which operand is off)
5555   // anyway.
5556   if (isThumb() && (Mnemonic == "add" || Mnemonic == "sub") &&
5557       (Operands.size() == 5 || Operands.size() == 6) &&
5558       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5559       static_cast<ARMOperand &>(*Operands[3]).getReg() == ARM::SP &&
5560       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5561       (static_cast<ARMOperand &>(*Operands[4]).isImm() ||
5562        (Operands.size() == 6 &&
5563         static_cast<ARMOperand &>(*Operands[5]).isImm())))
5564     return true;
5565
5566   return false;
5567 }
5568
5569 bool ARMAsmParser::shouldOmitPredicateOperand(StringRef Mnemonic,
5570                                               OperandVector &Operands) {
5571   // VRINT{Z, R, X} have a predicate operand in VFP, but not in NEON
5572   unsigned RegIdx = 3;
5573   if ((Mnemonic == "vrintz" || Mnemonic == "vrintx" || Mnemonic == "vrintr") &&
5574       static_cast<ARMOperand &>(*Operands[2]).getToken() == ".f32") {
5575     if (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
5576         static_cast<ARMOperand &>(*Operands[3]).getToken() == ".f32")
5577       RegIdx = 4;
5578
5579     if (static_cast<ARMOperand &>(*Operands[RegIdx]).isReg() &&
5580         (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(
5581              static_cast<ARMOperand &>(*Operands[RegIdx]).getReg()) ||
5582          ARMMCRegisterClasses[ARM::QPRRegClassID].contains(
5583              static_cast<ARMOperand &>(*Operands[RegIdx]).getReg())))
5584       return true;
5585   }
5586   return false;
5587 }
5588
5589 static bool isDataTypeToken(StringRef Tok) {
5590   return Tok == ".8" || Tok == ".16" || Tok == ".32" || Tok == ".64" ||
5591     Tok == ".i8" || Tok == ".i16" || Tok == ".i32" || Tok == ".i64" ||
5592     Tok == ".u8" || Tok == ".u16" || Tok == ".u32" || Tok == ".u64" ||
5593     Tok == ".s8" || Tok == ".s16" || Tok == ".s32" || Tok == ".s64" ||
5594     Tok == ".p8" || Tok == ".p16" || Tok == ".f32" || Tok == ".f64" ||
5595     Tok == ".f" || Tok == ".d";
5596 }
5597
5598 // FIXME: This bit should probably be handled via an explicit match class
5599 // in the .td files that matches the suffix instead of having it be
5600 // a literal string token the way it is now.
5601 static bool doesIgnoreDataTypeSuffix(StringRef Mnemonic, StringRef DT) {
5602   return Mnemonic.startswith("vldm") || Mnemonic.startswith("vstm");
5603 }
5604 static void applyMnemonicAliases(StringRef &Mnemonic, uint64_t Features,
5605                                  unsigned VariantID);
5606
5607 static bool RequiresVFPRegListValidation(StringRef Inst,
5608                                          bool &AcceptSinglePrecisionOnly,
5609                                          bool &AcceptDoublePrecisionOnly) {
5610   if (Inst.size() < 7)
5611     return false;
5612
5613   if (Inst.startswith("fldm") || Inst.startswith("fstm")) {
5614     StringRef AddressingMode = Inst.substr(4, 2);
5615     if (AddressingMode == "ia" || AddressingMode == "db" ||
5616         AddressingMode == "ea" || AddressingMode == "fd") {
5617       AcceptSinglePrecisionOnly = Inst[6] == 's';
5618       AcceptDoublePrecisionOnly = Inst[6] == 'd' || Inst[6] == 'x';
5619       return true;
5620     }
5621   }
5622
5623   return false;
5624 }
5625
5626 /// Parse an arm instruction mnemonic followed by its operands.
5627 bool ARMAsmParser::ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
5628                                     SMLoc NameLoc, OperandVector &Operands) {
5629   MCAsmParser &Parser = getParser();
5630   // FIXME: Can this be done via tablegen in some fashion?
5631   bool RequireVFPRegisterListCheck;
5632   bool AcceptSinglePrecisionOnly;
5633   bool AcceptDoublePrecisionOnly;
5634   RequireVFPRegisterListCheck =
5635     RequiresVFPRegListValidation(Name, AcceptSinglePrecisionOnly,
5636                                  AcceptDoublePrecisionOnly);
5637
5638   // Apply mnemonic aliases before doing anything else, as the destination
5639   // mnemonic may include suffices and we want to handle them normally.
5640   // The generic tblgen'erated code does this later, at the start of
5641   // MatchInstructionImpl(), but that's too late for aliases that include
5642   // any sort of suffix.
5643   uint64_t AvailableFeatures = getAvailableFeatures();
5644   unsigned AssemblerDialect = getParser().getAssemblerDialect();
5645   applyMnemonicAliases(Name, AvailableFeatures, AssemblerDialect);
5646
5647   // First check for the ARM-specific .req directive.
5648   if (Parser.getTok().is(AsmToken::Identifier) &&
5649       Parser.getTok().getIdentifier() == ".req") {
5650     parseDirectiveReq(Name, NameLoc);
5651     // We always return 'error' for this, as we're done with this
5652     // statement and don't need to match the 'instruction."
5653     return true;
5654   }
5655
5656   // Create the leading tokens for the mnemonic, split by '.' characters.
5657   size_t Start = 0, Next = Name.find('.');
5658   StringRef Mnemonic = Name.slice(Start, Next);
5659
5660   // Split out the predication code and carry setting flag from the mnemonic.
5661   unsigned PredicationCode;
5662   unsigned ProcessorIMod;
5663   bool CarrySetting;
5664   StringRef ITMask;
5665   Mnemonic = splitMnemonic(Mnemonic, PredicationCode, CarrySetting,
5666                            ProcessorIMod, ITMask);
5667
5668   // In Thumb1, only the branch (B) instruction can be predicated.
5669   if (isThumbOne() && PredicationCode != ARMCC::AL && Mnemonic != "b") {
5670     Parser.eatToEndOfStatement();
5671     return Error(NameLoc, "conditional execution not supported in Thumb1");
5672   }
5673
5674   Operands.push_back(ARMOperand::CreateToken(Mnemonic, NameLoc));
5675
5676   // Handle the IT instruction ITMask. Convert it to a bitmask. This
5677   // is the mask as it will be for the IT encoding if the conditional
5678   // encoding has a '1' as it's bit0 (i.e. 't' ==> '1'). In the case
5679   // where the conditional bit0 is zero, the instruction post-processing
5680   // will adjust the mask accordingly.
5681   if (Mnemonic == "it") {
5682     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + 2);
5683     if (ITMask.size() > 3) {
5684       Parser.eatToEndOfStatement();
5685       return Error(Loc, "too many conditions on IT instruction");
5686     }
5687     unsigned Mask = 8;
5688     for (unsigned i = ITMask.size(); i != 0; --i) {
5689       char pos = ITMask[i - 1];
5690       if (pos != 't' && pos != 'e') {
5691         Parser.eatToEndOfStatement();
5692         return Error(Loc, "illegal IT block condition mask '" + ITMask + "'");
5693       }
5694       Mask >>= 1;
5695       if (ITMask[i - 1] == 't')
5696         Mask |= 8;
5697     }
5698     Operands.push_back(ARMOperand::CreateITMask(Mask, Loc));
5699   }
5700
5701   // FIXME: This is all a pretty gross hack. We should automatically handle
5702   // optional operands like this via tblgen.
5703
5704   // Next, add the CCOut and ConditionCode operands, if needed.
5705   //
5706   // For mnemonics which can ever incorporate a carry setting bit or predication
5707   // code, our matching model involves us always generating CCOut and
5708   // ConditionCode operands to match the mnemonic "as written" and then we let
5709   // the matcher deal with finding the right instruction or generating an
5710   // appropriate error.
5711   bool CanAcceptCarrySet, CanAcceptPredicationCode;
5712   getMnemonicAcceptInfo(Mnemonic, Name, CanAcceptCarrySet, CanAcceptPredicationCode);
5713
5714   // If we had a carry-set on an instruction that can't do that, issue an
5715   // error.
5716   if (!CanAcceptCarrySet && CarrySetting) {
5717     Parser.eatToEndOfStatement();
5718     return Error(NameLoc, "instruction '" + Mnemonic +
5719                  "' can not set flags, but 's' suffix specified");
5720   }
5721   // If we had a predication code on an instruction that can't do that, issue an
5722   // error.
5723   if (!CanAcceptPredicationCode && PredicationCode != ARMCC::AL) {
5724     Parser.eatToEndOfStatement();
5725     return Error(NameLoc, "instruction '" + Mnemonic +
5726                  "' is not predicable, but condition code specified");
5727   }
5728
5729   // Add the carry setting operand, if necessary.
5730   if (CanAcceptCarrySet) {
5731     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size());
5732     Operands.push_back(ARMOperand::CreateCCOut(CarrySetting ? ARM::CPSR : 0,
5733                                                Loc));
5734   }
5735
5736   // Add the predication code operand, if necessary.
5737   if (CanAcceptPredicationCode) {
5738     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size() +
5739                                       CarrySetting);
5740     Operands.push_back(ARMOperand::CreateCondCode(
5741                          ARMCC::CondCodes(PredicationCode), Loc));
5742   }
5743
5744   // Add the processor imod operand, if necessary.
5745   if (ProcessorIMod) {
5746     Operands.push_back(ARMOperand::CreateImm(
5747           MCConstantExpr::Create(ProcessorIMod, getContext()),
5748                                  NameLoc, NameLoc));
5749   } else if (Mnemonic == "cps" && isMClass()) {
5750     return Error(NameLoc, "instruction 'cps' requires effect for M-class");
5751   }
5752
5753   // Add the remaining tokens in the mnemonic.
5754   while (Next != StringRef::npos) {
5755     Start = Next;
5756     Next = Name.find('.', Start + 1);
5757     StringRef ExtraToken = Name.slice(Start, Next);
5758
5759     // Some NEON instructions have an optional datatype suffix that is
5760     // completely ignored. Check for that.
5761     if (isDataTypeToken(ExtraToken) &&
5762         doesIgnoreDataTypeSuffix(Mnemonic, ExtraToken))
5763       continue;
5764
5765     // For for ARM mode generate an error if the .n qualifier is used.
5766     if (ExtraToken == ".n" && !isThumb()) {
5767       SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Start);
5768       Parser.eatToEndOfStatement();
5769       return Error(Loc, "instruction with .n (narrow) qualifier not allowed in "
5770                    "arm mode");
5771     }
5772
5773     // The .n qualifier is always discarded as that is what the tables
5774     // and matcher expect.  In ARM mode the .w qualifier has no effect,
5775     // so discard it to avoid errors that can be caused by the matcher.
5776     if (ExtraToken != ".n" && (isThumb() || ExtraToken != ".w")) {
5777       SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Start);
5778       Operands.push_back(ARMOperand::CreateToken(ExtraToken, Loc));
5779     }
5780   }
5781
5782   // Read the remaining operands.
5783   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5784     // Read the first operand.
5785     if (parseOperand(Operands, Mnemonic)) {
5786       Parser.eatToEndOfStatement();
5787       return true;
5788     }
5789
5790     while (getLexer().is(AsmToken::Comma)) {
5791       Parser.Lex();  // Eat the comma.
5792
5793       // Parse and remember the operand.
5794       if (parseOperand(Operands, Mnemonic)) {
5795         Parser.eatToEndOfStatement();
5796         return true;
5797       }
5798     }
5799   }
5800
5801   if (getLexer().isNot(AsmToken::EndOfStatement)) {
5802     SMLoc Loc = getLexer().getLoc();
5803     Parser.eatToEndOfStatement();
5804     return Error(Loc, "unexpected token in argument list");
5805   }
5806
5807   Parser.Lex(); // Consume the EndOfStatement
5808
5809   if (RequireVFPRegisterListCheck) {
5810     ARMOperand &Op = static_cast<ARMOperand &>(*Operands.back());
5811     if (AcceptSinglePrecisionOnly && !Op.isSPRRegList())
5812       return Error(Op.getStartLoc(),
5813                    "VFP/Neon single precision register expected");
5814     if (AcceptDoublePrecisionOnly && !Op.isDPRRegList())
5815       return Error(Op.getStartLoc(),
5816                    "VFP/Neon double precision register expected");
5817   }
5818
5819   // Some instructions, mostly Thumb, have forms for the same mnemonic that
5820   // do and don't have a cc_out optional-def operand. With some spot-checks
5821   // of the operand list, we can figure out which variant we're trying to
5822   // parse and adjust accordingly before actually matching. We shouldn't ever
5823   // try to remove a cc_out operand that was explicitly set on the the
5824   // mnemonic, of course (CarrySetting == true). Reason number #317 the
5825   // table driven matcher doesn't fit well with the ARM instruction set.
5826   if (!CarrySetting && shouldOmitCCOutOperand(Mnemonic, Operands))
5827     Operands.erase(Operands.begin() + 1);
5828
5829   // Some instructions have the same mnemonic, but don't always
5830   // have a predicate. Distinguish them here and delete the
5831   // predicate if needed.
5832   if (shouldOmitPredicateOperand(Mnemonic, Operands))
5833     Operands.erase(Operands.begin() + 1);
5834
5835   // ARM mode 'blx' need special handling, as the register operand version
5836   // is predicable, but the label operand version is not. So, we can't rely
5837   // on the Mnemonic based checking to correctly figure out when to put
5838   // a k_CondCode operand in the list. If we're trying to match the label
5839   // version, remove the k_CondCode operand here.
5840   if (!isThumb() && Mnemonic == "blx" && Operands.size() == 3 &&
5841       static_cast<ARMOperand &>(*Operands[2]).isImm())
5842     Operands.erase(Operands.begin() + 1);
5843
5844   // Adjust operands of ldrexd/strexd to MCK_GPRPair.
5845   // ldrexd/strexd require even/odd GPR pair. To enforce this constraint,
5846   // a single GPRPair reg operand is used in the .td file to replace the two
5847   // GPRs. However, when parsing from asm, the two GRPs cannot be automatically
5848   // expressed as a GPRPair, so we have to manually merge them.
5849   // FIXME: We would really like to be able to tablegen'erate this.
5850   if (!isThumb() && Operands.size() > 4 &&
5851       (Mnemonic == "ldrexd" || Mnemonic == "strexd" || Mnemonic == "ldaexd" ||
5852        Mnemonic == "stlexd")) {
5853     bool isLoad = (Mnemonic == "ldrexd" || Mnemonic == "ldaexd");
5854     unsigned Idx = isLoad ? 2 : 3;
5855     ARMOperand &Op1 = static_cast<ARMOperand &>(*Operands[Idx]);
5856     ARMOperand &Op2 = static_cast<ARMOperand &>(*Operands[Idx + 1]);
5857
5858     const MCRegisterClass& MRC = MRI->getRegClass(ARM::GPRRegClassID);
5859     // Adjust only if Op1 and Op2 are GPRs.
5860     if (Op1.isReg() && Op2.isReg() && MRC.contains(Op1.getReg()) &&
5861         MRC.contains(Op2.getReg())) {
5862       unsigned Reg1 = Op1.getReg();
5863       unsigned Reg2 = Op2.getReg();
5864       unsigned Rt = MRI->getEncodingValue(Reg1);
5865       unsigned Rt2 = MRI->getEncodingValue(Reg2);
5866
5867       // Rt2 must be Rt + 1 and Rt must be even.
5868       if (Rt + 1 != Rt2 || (Rt & 1)) {
5869         Error(Op2.getStartLoc(), isLoad
5870                                      ? "destination operands must be sequential"
5871                                      : "source operands must be sequential");
5872         return true;
5873       }
5874       unsigned NewReg = MRI->getMatchingSuperReg(Reg1, ARM::gsub_0,
5875           &(MRI->getRegClass(ARM::GPRPairRegClassID)));
5876       Operands[Idx] =
5877           ARMOperand::CreateReg(NewReg, Op1.getStartLoc(), Op2.getEndLoc());
5878       Operands.erase(Operands.begin() + Idx + 1);
5879     }
5880   }
5881
5882   // If first 2 operands of a 3 operand instruction are the same
5883   // then transform to 2 operand version of the same instruction
5884   // e.g. 'adds r0, r0, #1' transforms to 'adds r0, #1'
5885   // FIXME: We would really like to be able to tablegen'erate this.
5886   if (isThumbOne() && Operands.size() == 6 &&
5887        (Mnemonic == "add" || Mnemonic == "sub" || Mnemonic == "and" ||
5888         Mnemonic == "eor" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
5889         Mnemonic == "asr" || Mnemonic == "adc" || Mnemonic == "sbc" ||
5890         Mnemonic == "ror" || Mnemonic == "orr" || Mnemonic == "bic")) {
5891       ARMOperand &Op3 = static_cast<ARMOperand &>(*Operands[3]);
5892       ARMOperand &Op4 = static_cast<ARMOperand &>(*Operands[4]);
5893       ARMOperand &Op5 = static_cast<ARMOperand &>(*Operands[5]);
5894
5895       // If both registers are the same then remove one of them from
5896       // the operand list.
5897       if (Op3.isReg() && Op4.isReg() && Op3.getReg() == Op4.getReg()) {
5898           // If 3rd operand (variable Op5) is a register and the instruction is adds/sub
5899           // then do not transform as the backend already handles this instruction
5900           // correctly.
5901           if (!Op5.isReg() || !((Mnemonic == "add" && CarrySetting) || Mnemonic == "sub")) {
5902               Operands.erase(Operands.begin() + 3);
5903               if (Mnemonic == "add" && !CarrySetting) {
5904                   // Special case for 'add' (not 'adds') instruction must
5905                   // remove the CCOut operand as well.
5906                   Operands.erase(Operands.begin() + 1);
5907               }
5908           }
5909       }
5910   }
5911
5912   // If instruction is 'add' and first two register operands
5913   // use SP register, then remove one of the SP registers from
5914   // the instruction.
5915   // FIXME: We would really like to be able to tablegen'erate this.
5916   if (isThumbOne() && Operands.size() == 5 && Mnemonic == "add" && !CarrySetting) {
5917       ARMOperand &Op2 = static_cast<ARMOperand &>(*Operands[2]);
5918       ARMOperand &Op3 = static_cast<ARMOperand &>(*Operands[3]);
5919       if (Op2.isReg() && Op3.isReg() && Op2.getReg() == ARM::SP && Op3.getReg() == ARM::SP) {
5920           Operands.erase(Operands.begin() + 2);
5921       }
5922   }
5923
5924   // GNU Assembler extension (compatibility)
5925   if ((Mnemonic == "ldrd" || Mnemonic == "strd")) {
5926     ARMOperand &Op2 = static_cast<ARMOperand &>(*Operands[2]);
5927     ARMOperand &Op3 = static_cast<ARMOperand &>(*Operands[3]);
5928     if (Op3.isMem()) {
5929       assert(Op2.isReg() && "expected register argument");
5930
5931       unsigned SuperReg = MRI->getMatchingSuperReg(
5932           Op2.getReg(), ARM::gsub_0, &MRI->getRegClass(ARM::GPRPairRegClassID));
5933
5934       assert(SuperReg && "expected register pair");
5935
5936       unsigned PairedReg = MRI->getSubReg(SuperReg, ARM::gsub_1);
5937
5938       Operands.insert(
5939           Operands.begin() + 3,
5940           ARMOperand::CreateReg(PairedReg, Op2.getStartLoc(), Op2.getEndLoc()));
5941     }
5942   }
5943
5944   // FIXME: As said above, this is all a pretty gross hack.  This instruction
5945   // does not fit with other "subs" and tblgen.
5946   // Adjust operands of B9.3.19 SUBS PC, LR, #imm (Thumb2) system instruction
5947   // so the Mnemonic is the original name "subs" and delete the predicate
5948   // operand so it will match the table entry.
5949   if (isThumbTwo() && Mnemonic == "sub" && Operands.size() == 6 &&
5950       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5951       static_cast<ARMOperand &>(*Operands[3]).getReg() == ARM::PC &&
5952       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5953       static_cast<ARMOperand &>(*Operands[4]).getReg() == ARM::LR &&
5954       static_cast<ARMOperand &>(*Operands[5]).isImm()) {
5955     Operands.front() = ARMOperand::CreateToken(Name, NameLoc);
5956     Operands.erase(Operands.begin() + 1);
5957   }
5958   return false;
5959 }
5960
5961 // Validate context-sensitive operand constraints.
5962
5963 // return 'true' if register list contains non-low GPR registers,
5964 // 'false' otherwise. If Reg is in the register list or is HiReg, set
5965 // 'containsReg' to true.
5966 static bool checkLowRegisterList(MCInst Inst, unsigned OpNo, unsigned Reg,
5967                                  unsigned HiReg, bool &containsReg) {
5968   containsReg = false;
5969   for (unsigned i = OpNo; i < Inst.getNumOperands(); ++i) {
5970     unsigned OpReg = Inst.getOperand(i).getReg();
5971     if (OpReg == Reg)
5972       containsReg = true;
5973     // Anything other than a low register isn't legal here.
5974     if (!isARMLowRegister(OpReg) && (!HiReg || OpReg != HiReg))
5975       return true;
5976   }
5977   return false;
5978 }
5979
5980 // Check if the specified regisgter is in the register list of the inst,
5981 // starting at the indicated operand number.
5982 static bool listContainsReg(MCInst &Inst, unsigned OpNo, unsigned Reg) {
5983   for (unsigned i = OpNo; i < Inst.getNumOperands(); ++i) {
5984     unsigned OpReg = Inst.getOperand(i).getReg();
5985     if (OpReg == Reg)
5986       return true;
5987   }
5988   return false;
5989 }
5990
5991 // Return true if instruction has the interesting property of being
5992 // allowed in IT blocks, but not being predicable.
5993 static bool instIsBreakpoint(const MCInst &Inst) {
5994     return Inst.getOpcode() == ARM::tBKPT ||
5995            Inst.getOpcode() == ARM::BKPT ||
5996            Inst.getOpcode() == ARM::tHLT ||
5997            Inst.getOpcode() == ARM::HLT;
5998
5999 }
6000
6001 // FIXME: We would really like to be able to tablegen'erate this.
6002 bool ARMAsmParser::validateInstruction(MCInst &Inst,
6003                                        const OperandVector &Operands) {
6004   const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
6005   SMLoc Loc = Operands[0]->getStartLoc();
6006
6007   // Check the IT block state first.
6008   // NOTE: BKPT and HLT instructions have the interesting property of being
6009   // allowed in IT blocks, but not being predicable. They just always execute.
6010   if (inITBlock() && !instIsBreakpoint(Inst)) {
6011     unsigned Bit = 1;
6012     if (ITState.FirstCond)
6013       ITState.FirstCond = false;
6014     else
6015       Bit = (ITState.Mask >> (5 - ITState.CurPosition)) & 1;
6016     // The instruction must be predicable.
6017     if (!MCID.isPredicable())
6018       return Error(Loc, "instructions in IT block must be predicable");
6019     unsigned Cond = Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm();
6020     unsigned ITCond = Bit ? ITState.Cond :
6021       ARMCC::getOppositeCondition(ITState.Cond);
6022     if (Cond != ITCond) {
6023       // Find the condition code Operand to get its SMLoc information.
6024       SMLoc CondLoc;
6025       for (unsigned I = 1; I < Operands.size(); ++I)
6026         if (static_cast<ARMOperand &>(*Operands[I]).isCondCode())
6027           CondLoc = Operands[I]->getStartLoc();
6028       return Error(CondLoc, "incorrect condition in IT block; got '" +
6029                    StringRef(ARMCondCodeToString(ARMCC::CondCodes(Cond))) +
6030                    "', but expected '" +
6031                    ARMCondCodeToString(ARMCC::CondCodes(ITCond)) + "'");
6032     }
6033   // Check for non-'al' condition codes outside of the IT block.
6034   } else if (isThumbTwo() && MCID.isPredicable() &&
6035              Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm() !=
6036              ARMCC::AL && Inst.getOpcode() != ARM::tBcc &&
6037              Inst.getOpcode() != ARM::t2Bcc)
6038     return Error(Loc, "predicated instructions must be in IT block");
6039
6040   const unsigned Opcode = Inst.getOpcode();
6041   switch (Opcode) {
6042   case ARM::LDRD:
6043   case ARM::LDRD_PRE:
6044   case ARM::LDRD_POST: {
6045     const unsigned RtReg = Inst.getOperand(0).getReg();
6046
6047     // Rt can't be R14.
6048     if (RtReg == ARM::LR)
6049       return Error(Operands[3]->getStartLoc(),
6050                    "Rt can't be R14");
6051
6052     const unsigned Rt = MRI->getEncodingValue(RtReg);
6053     // Rt must be even-numbered.
6054     if ((Rt & 1) == 1)
6055       return Error(Operands[3]->getStartLoc(),
6056                    "Rt must be even-numbered");
6057
6058     // Rt2 must be Rt + 1.
6059     const unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6060     if (Rt2 != Rt + 1)
6061       return Error(Operands[3]->getStartLoc(),
6062                    "destination operands must be sequential");
6063
6064     if (Opcode == ARM::LDRD_PRE || Opcode == ARM::LDRD_POST) {
6065       const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(3).getReg());
6066       // For addressing modes with writeback, the base register needs to be
6067       // different from the destination registers.
6068       if (Rn == Rt || Rn == Rt2)
6069         return Error(Operands[3]->getStartLoc(),
6070                      "base register needs to be different from destination "
6071                      "registers");
6072     }
6073
6074     return false;
6075   }
6076   case ARM::t2LDRDi8:
6077   case ARM::t2LDRD_PRE:
6078   case ARM::t2LDRD_POST: {
6079     // Rt2 must be different from Rt.
6080     unsigned Rt = MRI->getEncodingValue(Inst.getOperand(0).getReg());
6081     unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6082     if (Rt2 == Rt)
6083       return Error(Operands[3]->getStartLoc(),
6084                    "destination operands can't be identical");
6085     return false;
6086   }
6087   case ARM::STRD: {
6088     // Rt2 must be Rt + 1.
6089     unsigned Rt = MRI->getEncodingValue(Inst.getOperand(0).getReg());
6090     unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6091     if (Rt2 != Rt + 1)
6092       return Error(Operands[3]->getStartLoc(),
6093                    "source operands must be sequential");
6094     return false;
6095   }
6096   case ARM::STRD_PRE:
6097   case ARM::STRD_POST: {
6098     // Rt2 must be Rt + 1.
6099     unsigned Rt = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6100     unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(2).getReg());
6101     if (Rt2 != Rt + 1)
6102       return Error(Operands[3]->getStartLoc(),
6103                    "source operands must be sequential");
6104     return false;
6105   }
6106   case ARM::STR_PRE_IMM:
6107   case ARM::STR_PRE_REG:
6108   case ARM::STR_POST_IMM:
6109   case ARM::STR_POST_REG:
6110   case ARM::STRH_PRE:
6111   case ARM::STRH_POST:
6112   case ARM::STRB_PRE_IMM:
6113   case ARM::STRB_PRE_REG:
6114   case ARM::STRB_POST_IMM:
6115   case ARM::STRB_POST_REG: {
6116     // Rt must be different from Rn.
6117     const unsigned Rt = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6118     const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(2).getReg());
6119
6120     if (Rt == Rn)
6121       return Error(Operands[3]->getStartLoc(),
6122                    "source register and base register can't be identical");
6123     return false;
6124   }
6125   case ARM::LDR_PRE_IMM:
6126   case ARM::LDR_PRE_REG:
6127   case ARM::LDR_POST_IMM:
6128   case ARM::LDR_POST_REG:
6129   case ARM::LDRH_PRE:
6130   case ARM::LDRH_POST:
6131   case ARM::LDRSH_PRE:
6132   case ARM::LDRSH_POST:
6133   case ARM::LDRB_PRE_IMM:
6134   case ARM::LDRB_PRE_REG:
6135   case ARM::LDRB_POST_IMM:
6136   case ARM::LDRB_POST_REG:
6137   case ARM::LDRSB_PRE:
6138   case ARM::LDRSB_POST: {
6139     // Rt must be different from Rn.
6140     const unsigned Rt = MRI->getEncodingValue(Inst.getOperand(0).getReg());
6141     const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(2).getReg());
6142
6143     if (Rt == Rn)
6144       return Error(Operands[3]->getStartLoc(),
6145                    "destination register and base register can't be identical");
6146     return false;
6147   }
6148   case ARM::SBFX:
6149   case ARM::UBFX: {
6150     // Width must be in range [1, 32-lsb].
6151     unsigned LSB = Inst.getOperand(2).getImm();
6152     unsigned Widthm1 = Inst.getOperand(3).getImm();
6153     if (Widthm1 >= 32 - LSB)
6154       return Error(Operands[5]->getStartLoc(),
6155                    "bitfield width must be in range [1,32-lsb]");
6156     return false;
6157   }
6158   // Notionally handles ARM::tLDMIA_UPD too.
6159   case ARM::tLDMIA: {
6160     // If we're parsing Thumb2, the .w variant is available and handles
6161     // most cases that are normally illegal for a Thumb1 LDM instruction.
6162     // We'll make the transformation in processInstruction() if necessary.
6163     //
6164     // Thumb LDM instructions are writeback iff the base register is not
6165     // in the register list.
6166     unsigned Rn = Inst.getOperand(0).getReg();
6167     bool HasWritebackToken =
6168         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
6169          static_cast<ARMOperand &>(*Operands[3]).getToken() == "!");
6170     bool ListContainsBase;
6171     if (checkLowRegisterList(Inst, 3, Rn, 0, ListContainsBase) && !isThumbTwo())
6172       return Error(Operands[3 + HasWritebackToken]->getStartLoc(),
6173                    "registers must be in range r0-r7");
6174     // If we should have writeback, then there should be a '!' token.
6175     if (!ListContainsBase && !HasWritebackToken && !isThumbTwo())
6176       return Error(Operands[2]->getStartLoc(),
6177                    "writeback operator '!' expected");
6178     // If we should not have writeback, there must not be a '!'. This is
6179     // true even for the 32-bit wide encodings.
6180     if (ListContainsBase && HasWritebackToken)
6181       return Error(Operands[3]->getStartLoc(),
6182                    "writeback operator '!' not allowed when base register "
6183                    "in register list");
6184     if (listContainsReg(Inst, 3 + HasWritebackToken, ARM::SP))
6185       return Error(Operands[3 + HasWritebackToken]->getStartLoc(),
6186                    "SP not allowed in register list");
6187     break;
6188   }
6189   case ARM::LDMIA_UPD:
6190   case ARM::LDMDB_UPD:
6191   case ARM::LDMIB_UPD:
6192   case ARM::LDMDA_UPD:
6193     // ARM variants loading and updating the same register are only officially
6194     // UNPREDICTABLE on v7 upwards. Goodness knows what they did before.
6195     if (!hasV7Ops())
6196       break;
6197     if (listContainsReg(Inst, 3, Inst.getOperand(0).getReg()))
6198       return Error(Operands.back()->getStartLoc(),
6199                    "writeback register not allowed in register list");
6200     break;
6201   case ARM::t2LDMIA:
6202   case ARM::t2LDMDB:
6203   case ARM::t2STMIA:
6204   case ARM::t2STMDB: {
6205     if (listContainsReg(Inst, 3, ARM::SP))
6206       return Error(Operands.back()->getStartLoc(),
6207                    "SP not allowed in register list");
6208     break;
6209   }
6210   case ARM::t2LDMIA_UPD:
6211   case ARM::t2LDMDB_UPD:
6212   case ARM::t2STMIA_UPD:
6213   case ARM::t2STMDB_UPD: {
6214     if (listContainsReg(Inst, 3, Inst.getOperand(0).getReg()))
6215       return Error(Operands.back()->getStartLoc(),
6216                    "writeback register not allowed in register list");
6217
6218     if (listContainsReg(Inst, 4, ARM::SP))
6219       return Error(Operands.back()->getStartLoc(),
6220                    "SP not allowed in register list");
6221     break;
6222   }
6223   case ARM::sysLDMIA_UPD:
6224   case ARM::sysLDMDA_UPD:
6225   case ARM::sysLDMDB_UPD:
6226   case ARM::sysLDMIB_UPD:
6227     if (!listContainsReg(Inst, 3, ARM::PC))
6228       return Error(Operands[4]->getStartLoc(),
6229                    "writeback register only allowed on system LDM "
6230                    "if PC in register-list");
6231     break;
6232   case ARM::sysSTMIA_UPD:
6233   case ARM::sysSTMDA_UPD:
6234   case ARM::sysSTMDB_UPD:
6235   case ARM::sysSTMIB_UPD:
6236     return Error(Operands[2]->getStartLoc(),
6237                  "system STM cannot have writeback register");
6238   case ARM::tMUL: {
6239     // The second source operand must be the same register as the destination
6240     // operand.
6241     //
6242     // In this case, we must directly check the parsed operands because the
6243     // cvtThumbMultiply() function is written in such a way that it guarantees
6244     // this first statement is always true for the new Inst.  Essentially, the
6245     // destination is unconditionally copied into the second source operand
6246     // without checking to see if it matches what we actually parsed.
6247     if (Operands.size() == 6 && (((ARMOperand &)*Operands[3]).getReg() !=
6248                                  ((ARMOperand &)*Operands[5]).getReg()) &&
6249         (((ARMOperand &)*Operands[3]).getReg() !=
6250          ((ARMOperand &)*Operands[4]).getReg())) {
6251       return Error(Operands[3]->getStartLoc(),
6252                    "destination register must match source register");
6253     }
6254     break;
6255   }
6256   // Like for ldm/stm, push and pop have hi-reg handling version in Thumb2,
6257   // so only issue a diagnostic for thumb1. The instructions will be
6258   // switched to the t2 encodings in processInstruction() if necessary.
6259   case ARM::tPOP: {
6260     bool ListContainsBase;
6261     if (checkLowRegisterList(Inst, 2, 0, ARM::PC, ListContainsBase) &&
6262         !isThumbTwo())
6263       return Error(Operands[2]->getStartLoc(),
6264                    "registers must be in range r0-r7 or pc");
6265     break;
6266   }
6267   case ARM::tPUSH: {
6268     bool ListContainsBase;
6269     if (checkLowRegisterList(Inst, 2, 0, ARM::LR, ListContainsBase) &&
6270         !isThumbTwo())
6271       return Error(Operands[2]->getStartLoc(),
6272                    "registers must be in range r0-r7 or lr");
6273     break;
6274   }
6275   case ARM::tSTMIA_UPD: {
6276     bool ListContainsBase, InvalidLowList;
6277     InvalidLowList = checkLowRegisterList(Inst, 4, Inst.getOperand(0).getReg(),
6278                                           0, ListContainsBase);
6279     if (InvalidLowList && !isThumbTwo())
6280       return Error(Operands[4]->getStartLoc(),
6281                    "registers must be in range r0-r7");
6282
6283     // This would be converted to a 32-bit stm, but that's not valid if the
6284     // writeback register is in the list.
6285     if (InvalidLowList && ListContainsBase)
6286       return Error(Operands[4]->getStartLoc(),
6287                    "writeback operator '!' not allowed when base register "
6288                    "in register list");
6289     if (listContainsReg(Inst, 4, ARM::SP) && !inITBlock())
6290       return Error(Operands.back()->getStartLoc(),
6291                    "SP not allowed in register list");
6292     break;
6293   }
6294   case ARM::tADDrSP: {
6295     // If the non-SP source operand and the destination operand are not the
6296     // same, we need thumb2 (for the wide encoding), or we have an error.
6297     if (!isThumbTwo() &&
6298         Inst.getOperand(0).getReg() != Inst.getOperand(2).getReg()) {
6299       return Error(Operands[4]->getStartLoc(),
6300                    "source register must be the same as destination");
6301     }
6302     break;
6303   }
6304   // Final range checking for Thumb unconditional branch instructions.
6305   case ARM::tB:
6306     if (!(static_cast<ARMOperand &>(*Operands[2])).isSignedOffset<11, 1>())
6307       return Error(Operands[2]->getStartLoc(), "branch target out of range");
6308     break;
6309   case ARM::t2B: {
6310     int op = (Operands[2]->isImm()) ? 2 : 3;
6311     if (!static_cast<ARMOperand &>(*Operands[op]).isSignedOffset<24, 1>())
6312       return Error(Operands[op]->getStartLoc(), "branch target out of range");
6313     break;
6314   }
6315   // Final range checking for Thumb conditional branch instructions.
6316   case ARM::tBcc:
6317     if (!static_cast<ARMOperand &>(*Operands[2]).isSignedOffset<8, 1>())
6318       return Error(Operands[2]->getStartLoc(), "branch target out of range");
6319     break;
6320   case ARM::t2Bcc: {
6321     int Op = (Operands[2]->isImm()) ? 2 : 3;
6322     if (!static_cast<ARMOperand &>(*Operands[Op]).isSignedOffset<20, 1>())
6323       return Error(Operands[Op]->getStartLoc(), "branch target out of range");
6324     break;
6325   }
6326   case ARM::MOVi16:
6327   case ARM::t2MOVi16:
6328   case ARM::t2MOVTi16:
6329     {
6330     // We want to avoid misleadingly allowing something like "mov r0, <symbol>"
6331     // especially when we turn it into a movw and the expression <symbol> does
6332     // not have a :lower16: or :upper16 as part of the expression.  We don't
6333     // want the behavior of silently truncating, which can be unexpected and
6334     // lead to bugs that are difficult to find since this is an easy mistake
6335     // to make.
6336     int i = (Operands[3]->isImm()) ? 3 : 4;
6337     ARMOperand &Op = static_cast<ARMOperand &>(*Operands[i]);
6338     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm());
6339     if (CE) break;
6340     const MCExpr *E = dyn_cast<MCExpr>(Op.getImm());
6341     if (!E) break;
6342     const ARMMCExpr *ARM16Expr = dyn_cast<ARMMCExpr>(E);
6343     if (!ARM16Expr || (ARM16Expr->getKind() != ARMMCExpr::VK_ARM_HI16 &&
6344                        ARM16Expr->getKind() != ARMMCExpr::VK_ARM_LO16))
6345       return Error(
6346           Op.getStartLoc(),
6347           "immediate expression for mov requires :lower16: or :upper16");
6348     break;
6349   }
6350   }
6351
6352   return false;
6353 }
6354
6355 static unsigned getRealVSTOpcode(unsigned Opc, unsigned &Spacing) {
6356   switch(Opc) {
6357   default: llvm_unreachable("unexpected opcode!");
6358   // VST1LN
6359   case ARM::VST1LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST1LNd8_UPD;
6360   case ARM::VST1LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST1LNd16_UPD;
6361   case ARM::VST1LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST1LNd32_UPD;
6362   case ARM::VST1LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST1LNd8_UPD;
6363   case ARM::VST1LNdWB_register_Asm_16: Spacing = 1; return ARM::VST1LNd16_UPD;
6364   case ARM::VST1LNdWB_register_Asm_32: Spacing = 1; return ARM::VST1LNd32_UPD;
6365   case ARM::VST1LNdAsm_8:  Spacing = 1; return ARM::VST1LNd8;
6366   case ARM::VST1LNdAsm_16: Spacing = 1; return ARM::VST1LNd16;
6367   case ARM::VST1LNdAsm_32: Spacing = 1; return ARM::VST1LNd32;
6368
6369   // VST2LN
6370   case ARM::VST2LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST2LNd8_UPD;
6371   case ARM::VST2LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST2LNd16_UPD;
6372   case ARM::VST2LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST2LNd32_UPD;
6373   case ARM::VST2LNqWB_fixed_Asm_16: Spacing = 2; return ARM::VST2LNq16_UPD;
6374   case ARM::VST2LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST2LNq32_UPD;
6375
6376   case ARM::VST2LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST2LNd8_UPD;
6377   case ARM::VST2LNdWB_register_Asm_16: Spacing = 1; return ARM::VST2LNd16_UPD;
6378   case ARM::VST2LNdWB_register_Asm_32: Spacing = 1; return ARM::VST2LNd32_UPD;
6379   case ARM::VST2LNqWB_register_Asm_16: Spacing = 2; return ARM::VST2LNq16_UPD;
6380   case ARM::VST2LNqWB_register_Asm_32: Spacing = 2; return ARM::VST2LNq32_UPD;
6381
6382   case ARM::VST2LNdAsm_8:  Spacing = 1; return ARM::VST2LNd8;
6383   case ARM::VST2LNdAsm_16: Spacing = 1; return ARM::VST2LNd16;
6384   case ARM::VST2LNdAsm_32: Spacing = 1; return ARM::VST2LNd32;
6385   case ARM::VST2LNqAsm_16: Spacing = 2; return ARM::VST2LNq16;
6386   case ARM::VST2LNqAsm_32: Spacing = 2; return ARM::VST2LNq32;
6387
6388   // VST3LN
6389   case ARM::VST3LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST3LNd8_UPD;
6390   case ARM::VST3LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST3LNd16_UPD;
6391   case ARM::VST3LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST3LNd32_UPD;
6392   case ARM::VST3LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VST3LNq16_UPD;
6393   case ARM::VST3LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST3LNq32_UPD;
6394   case ARM::VST3LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST3LNd8_UPD;
6395   case ARM::VST3LNdWB_register_Asm_16: Spacing = 1; return ARM::VST3LNd16_UPD;
6396   case ARM::VST3LNdWB_register_Asm_32: Spacing = 1; return ARM::VST3LNd32_UPD;
6397   case ARM::VST3LNqWB_register_Asm_16: Spacing = 2; return ARM::VST3LNq16_UPD;
6398   case ARM::VST3LNqWB_register_Asm_32: Spacing = 2; return ARM::VST3LNq32_UPD;
6399   case ARM::VST3LNdAsm_8:  Spacing = 1; return ARM::VST3LNd8;
6400   case ARM::VST3LNdAsm_16: Spacing = 1; return ARM::VST3LNd16;
6401   case ARM::VST3LNdAsm_32: Spacing = 1; return ARM::VST3LNd32;
6402   case ARM::VST3LNqAsm_16: Spacing = 2; return ARM::VST3LNq16;
6403   case ARM::VST3LNqAsm_32: Spacing = 2; return ARM::VST3LNq32;
6404
6405   // VST3
6406   case ARM::VST3dWB_fixed_Asm_8:  Spacing = 1; return ARM::VST3d8_UPD;
6407   case ARM::VST3dWB_fixed_Asm_16: Spacing = 1; return ARM::VST3d16_UPD;
6408   case ARM::VST3dWB_fixed_Asm_32: Spacing = 1; return ARM::VST3d32_UPD;
6409   case ARM::VST3qWB_fixed_Asm_8:  Spacing = 2; return ARM::VST3q8_UPD;
6410   case ARM::VST3qWB_fixed_Asm_16: Spacing = 2; return ARM::VST3q16_UPD;
6411   case ARM::VST3qWB_fixed_Asm_32: Spacing = 2; return ARM::VST3q32_UPD;
6412   case ARM::VST3dWB_register_Asm_8:  Spacing = 1; return ARM::VST3d8_UPD;
6413   case ARM::VST3dWB_register_Asm_16: Spacing = 1; return ARM::VST3d16_UPD;
6414   case ARM::VST3dWB_register_Asm_32: Spacing = 1; return ARM::VST3d32_UPD;
6415   case ARM::VST3qWB_register_Asm_8:  Spacing = 2; return ARM::VST3q8_UPD;
6416   case ARM::VST3qWB_register_Asm_16: Spacing = 2; return ARM::VST3q16_UPD;
6417   case ARM::VST3qWB_register_Asm_32: Spacing = 2; return ARM::VST3q32_UPD;
6418   case ARM::VST3dAsm_8:  Spacing = 1; return ARM::VST3d8;
6419   case ARM::VST3dAsm_16: Spacing = 1; return ARM::VST3d16;
6420   case ARM::VST3dAsm_32: Spacing = 1; return ARM::VST3d32;
6421   case ARM::VST3qAsm_8:  Spacing = 2; return ARM::VST3q8;
6422   case ARM::VST3qAsm_16: Spacing = 2; return ARM::VST3q16;
6423   case ARM::VST3qAsm_32: Spacing = 2; return ARM::VST3q32;
6424
6425   // VST4LN
6426   case ARM::VST4LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST4LNd8_UPD;
6427   case ARM::VST4LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST4LNd16_UPD;
6428   case ARM::VST4LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST4LNd32_UPD;
6429   case ARM::VST4LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VST4LNq16_UPD;
6430   case ARM::VST4LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST4LNq32_UPD;
6431   case ARM::VST4LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST4LNd8_UPD;
6432   case ARM::VST4LNdWB_register_Asm_16: Spacing = 1; return ARM::VST4LNd16_UPD;
6433   case ARM::VST4LNdWB_register_Asm_32: Spacing = 1; return ARM::VST4LNd32_UPD;
6434   case ARM::VST4LNqWB_register_Asm_16: Spacing = 2; return ARM::VST4LNq16_UPD;
6435   case ARM::VST4LNqWB_register_Asm_32: Spacing = 2; return ARM::VST4LNq32_UPD;
6436   case ARM::VST4LNdAsm_8:  Spacing = 1; return ARM::VST4LNd8;
6437   case ARM::VST4LNdAsm_16: Spacing = 1; return ARM::VST4LNd16;
6438   case ARM::VST4LNdAsm_32: Spacing = 1; return ARM::VST4LNd32;
6439   case ARM::VST4LNqAsm_16: Spacing = 2; return ARM::VST4LNq16;
6440   case ARM::VST4LNqAsm_32: Spacing = 2; return ARM::VST4LNq32;
6441
6442   // VST4
6443   case ARM::VST4dWB_fixed_Asm_8:  Spacing = 1; return ARM::VST4d8_UPD;
6444   case ARM::VST4dWB_fixed_Asm_16: Spacing = 1; return ARM::VST4d16_UPD;
6445   case ARM::VST4dWB_fixed_Asm_32: Spacing = 1; return ARM::VST4d32_UPD;
6446   case ARM::VST4qWB_fixed_Asm_8:  Spacing = 2; return ARM::VST4q8_UPD;
6447   case ARM::VST4qWB_fixed_Asm_16: Spacing = 2; return ARM::VST4q16_UPD;
6448   case ARM::VST4qWB_fixed_Asm_32: Spacing = 2; return ARM::VST4q32_UPD;
6449   case ARM::VST4dWB_register_Asm_8:  Spacing = 1; return ARM::VST4d8_UPD;
6450   case ARM::VST4dWB_register_Asm_16: Spacing = 1; return ARM::VST4d16_UPD;
6451   case ARM::VST4dWB_register_Asm_32: Spacing = 1; return ARM::VST4d32_UPD;
6452   case ARM::VST4qWB_register_Asm_8:  Spacing = 2; return ARM::VST4q8_UPD;
6453   case ARM::VST4qWB_register_Asm_16: Spacing = 2; return ARM::VST4q16_UPD;
6454   case ARM::VST4qWB_register_Asm_32: Spacing = 2; return ARM::VST4q32_UPD;
6455   case ARM::VST4dAsm_8:  Spacing = 1; return ARM::VST4d8;
6456   case ARM::VST4dAsm_16: Spacing = 1; return ARM::VST4d16;
6457   case ARM::VST4dAsm_32: Spacing = 1; return ARM::VST4d32;
6458   case ARM::VST4qAsm_8:  Spacing = 2; return ARM::VST4q8;
6459   case ARM::VST4qAsm_16: Spacing = 2; return ARM::VST4q16;
6460   case ARM::VST4qAsm_32: Spacing = 2; return ARM::VST4q32;
6461   }
6462 }
6463
6464 static unsigned getRealVLDOpcode(unsigned Opc, unsigned &Spacing) {
6465   switch(Opc) {
6466   default: llvm_unreachable("unexpected opcode!");
6467   // VLD1LN
6468   case ARM::VLD1LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD1LNd8_UPD;
6469   case ARM::VLD1LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD1LNd16_UPD;
6470   case ARM::VLD1LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD1LNd32_UPD;
6471   case ARM::VLD1LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD1LNd8_UPD;
6472   case ARM::VLD1LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD1LNd16_UPD;
6473   case ARM::VLD1LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD1LNd32_UPD;
6474   case ARM::VLD1LNdAsm_8:  Spacing = 1; return ARM::VLD1LNd8;
6475   case ARM::VLD1LNdAsm_16: Spacing = 1; return ARM::VLD1LNd16;
6476   case ARM::VLD1LNdAsm_32: Spacing = 1; return ARM::VLD1LNd32;
6477
6478   // VLD2LN
6479   case ARM::VLD2LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD2LNd8_UPD;
6480   case ARM::VLD2LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD2LNd16_UPD;
6481   case ARM::VLD2LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD2LNd32_UPD;
6482   case ARM::VLD2LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD2LNq16_UPD;
6483   case ARM::VLD2LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD2LNq32_UPD;
6484   case ARM::VLD2LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD2LNd8_UPD;
6485   case ARM::VLD2LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD2LNd16_UPD;
6486   case ARM::VLD2LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD2LNd32_UPD;
6487   case ARM::VLD2LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD2LNq16_UPD;
6488   case ARM::VLD2LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD2LNq32_UPD;
6489   case ARM::VLD2LNdAsm_8:  Spacing = 1; return ARM::VLD2LNd8;
6490   case ARM::VLD2LNdAsm_16: Spacing = 1; return ARM::VLD2LNd16;
6491   case ARM::VLD2LNdAsm_32: Spacing = 1; return ARM::VLD2LNd32;
6492   case ARM::VLD2LNqAsm_16: Spacing = 2; return ARM::VLD2LNq16;
6493   case ARM::VLD2LNqAsm_32: Spacing = 2; return ARM::VLD2LNq32;
6494
6495   // VLD3DUP
6496   case ARM::VLD3DUPdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3DUPd8_UPD;
6497   case ARM::VLD3DUPdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3DUPd16_UPD;
6498   case ARM::VLD3DUPdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3DUPd32_UPD;
6499   case ARM::VLD3DUPqWB_fixed_Asm_8: Spacing = 1; return ARM::VLD3DUPq8_UPD;
6500   case ARM::VLD3DUPqWB_fixed_Asm_16: Spacing = 2; return ARM::VLD3DUPq16_UPD;
6501   case ARM::VLD3DUPqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3DUPq32_UPD;
6502   case ARM::VLD3DUPdWB_register_Asm_8:  Spacing = 1; return ARM::VLD3DUPd8_UPD;
6503   case ARM::VLD3DUPdWB_register_Asm_16: Spacing = 1; return ARM::VLD3DUPd16_UPD;
6504   case ARM::VLD3DUPdWB_register_Asm_32: Spacing = 1; return ARM::VLD3DUPd32_UPD;
6505   case ARM::VLD3DUPqWB_register_Asm_8: Spacing = 2; return ARM::VLD3DUPq8_UPD;
6506   case ARM::VLD3DUPqWB_register_Asm_16: Spacing = 2; return ARM::VLD3DUPq16_UPD;
6507   case ARM::VLD3DUPqWB_register_Asm_32: Spacing = 2; return ARM::VLD3DUPq32_UPD;
6508   case ARM::VLD3DUPdAsm_8:  Spacing = 1; return ARM::VLD3DUPd8;
6509   case ARM::VLD3DUPdAsm_16: Spacing = 1; return ARM::VLD3DUPd16;
6510   case ARM::VLD3DUPdAsm_32: Spacing = 1; return ARM::VLD3DUPd32;
6511   case ARM::VLD3DUPqAsm_8: Spacing = 2; return ARM::VLD3DUPq8;
6512   case ARM::VLD3DUPqAsm_16: Spacing = 2; return ARM::VLD3DUPq16;
6513   case ARM::VLD3DUPqAsm_32: Spacing = 2; return ARM::VLD3DUPq32;
6514
6515   // VLD3LN
6516   case ARM::VLD3LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3LNd8_UPD;
6517   case ARM::VLD3LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3LNd16_UPD;
6518   case ARM::VLD3LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3LNd32_UPD;
6519   case ARM::VLD3LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3LNq16_UPD;
6520   case ARM::VLD3LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3LNq32_UPD;
6521   case ARM::VLD3LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD3LNd8_UPD;
6522   case ARM::VLD3LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD3LNd16_UPD;
6523   case ARM::VLD3LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD3LNd32_UPD;
6524   case ARM::VLD3LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD3LNq16_UPD;
6525   case ARM::VLD3LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD3LNq32_UPD;
6526   case ARM::VLD3LNdAsm_8:  Spacing = 1; return ARM::VLD3LNd8;
6527   case ARM::VLD3LNdAsm_16: Spacing = 1; return ARM::VLD3LNd16;
6528   case ARM::VLD3LNdAsm_32: Spacing = 1; return ARM::VLD3LNd32;
6529   case ARM::VLD3LNqAsm_16: Spacing = 2; return ARM::VLD3LNq16;
6530   case ARM::VLD3LNqAsm_32: Spacing = 2; return ARM::VLD3LNq32;
6531
6532   // VLD3
6533   case ARM::VLD3dWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3d8_UPD;
6534   case ARM::VLD3dWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3d16_UPD;
6535   case ARM::VLD3dWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3d32_UPD;
6536   case ARM::VLD3qWB_fixed_Asm_8:  Spacing = 2; return ARM::VLD3q8_UPD;
6537   case ARM::VLD3qWB_fixed_Asm_16: Spacing = 2; return ARM::VLD3q16_UPD;
6538   case ARM::VLD3qWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3q32_UPD;
6539   case ARM::VLD3dWB_register_Asm_8:  Spacing = 1; return ARM::VLD3d8_UPD;
6540   case ARM::VLD3dWB_register_Asm_16: Spacing = 1; return ARM::VLD3d16_UPD;
6541   case ARM::VLD3dWB_register_Asm_32: Spacing = 1; return ARM::VLD3d32_UPD;
6542   case ARM::VLD3qWB_register_Asm_8:  Spacing = 2; return ARM::VLD3q8_UPD;
6543   case ARM::VLD3qWB_register_Asm_16: Spacing = 2; return ARM::VLD3q16_UPD;
6544   case ARM::VLD3qWB_register_Asm_32: Spacing = 2; return ARM::VLD3q32_UPD;
6545   case ARM::VLD3dAsm_8:  Spacing = 1; return ARM::VLD3d8;
6546   case ARM::VLD3dAsm_16: Spacing = 1; return ARM::VLD3d16;
6547   case ARM::VLD3dAsm_32: Spacing = 1; return ARM::VLD3d32;
6548   case ARM::VLD3qAsm_8:  Spacing = 2; return ARM::VLD3q8;
6549   case ARM::VLD3qAsm_16: Spacing = 2; return ARM::VLD3q16;
6550   case ARM::VLD3qAsm_32: Spacing = 2; return ARM::VLD3q32;
6551
6552   // VLD4LN
6553   case ARM::VLD4LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4LNd8_UPD;
6554   case ARM::VLD4LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4LNd16_UPD;
6555   case ARM::VLD4LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4LNd32_UPD;
6556   case ARM::VLD4LNqWB_fixed_Asm_16: Spacing = 2; return ARM::VLD4LNq16_UPD;
6557   case ARM::VLD4LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4LNq32_UPD;
6558   case ARM::VLD4LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD4LNd8_UPD;
6559   case ARM::VLD4LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD4LNd16_UPD;
6560   case ARM::VLD4LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD4LNd32_UPD;
6561   case ARM::VLD4LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD4LNq16_UPD;
6562   case ARM::VLD4LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD4LNq32_UPD;
6563   case ARM::VLD4LNdAsm_8:  Spacing = 1; return ARM::VLD4LNd8;
6564   case ARM::VLD4LNdAsm_16: Spacing = 1; return ARM::VLD4LNd16;
6565   case ARM::VLD4LNdAsm_32: Spacing = 1; return ARM::VLD4LNd32;
6566   case ARM::VLD4LNqAsm_16: Spacing = 2; return ARM::VLD4LNq16;
6567   case ARM::VLD4LNqAsm_32: Spacing = 2; return ARM::VLD4LNq32;
6568
6569   // VLD4DUP
6570   case ARM::VLD4DUPdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4DUPd8_UPD;
6571   case ARM::VLD4DUPdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4DUPd16_UPD;
6572   case ARM::VLD4DUPdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4DUPd32_UPD;
6573   case ARM::VLD4DUPqWB_fixed_Asm_8: Spacing = 1; return ARM::VLD4DUPq8_UPD;
6574   case ARM::VLD4DUPqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4DUPq16_UPD;
6575   case ARM::VLD4DUPqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4DUPq32_UPD;
6576   case ARM::VLD4DUPdWB_register_Asm_8:  Spacing = 1; return ARM::VLD4DUPd8_UPD;
6577   case ARM::VLD4DUPdWB_register_Asm_16: Spacing = 1; return ARM::VLD4DUPd16_UPD;
6578   case ARM::VLD4DUPdWB_register_Asm_32: Spacing = 1; return ARM::VLD4DUPd32_UPD;
6579   case ARM::VLD4DUPqWB_register_Asm_8: Spacing = 2; return ARM::VLD4DUPq8_UPD;
6580   case ARM::VLD4DUPqWB_register_Asm_16: Spacing = 2; return ARM::VLD4DUPq16_UPD;
6581   case ARM::VLD4DUPqWB_register_Asm_32: Spacing = 2; return ARM::VLD4DUPq32_UPD;
6582   case ARM::VLD4DUPdAsm_8:  Spacing = 1; return ARM::VLD4DUPd8;
6583   case ARM::VLD4DUPdAsm_16: Spacing = 1; return ARM::VLD4DUPd16;
6584   case ARM::VLD4DUPdAsm_32: Spacing = 1; return ARM::VLD4DUPd32;
6585   case ARM::VLD4DUPqAsm_8: Spacing = 2; return ARM::VLD4DUPq8;
6586   case ARM::VLD4DUPqAsm_16: Spacing = 2; return ARM::VLD4DUPq16;
6587   case ARM::VLD4DUPqAsm_32: Spacing = 2; return ARM::VLD4DUPq32;
6588
6589   // VLD4
6590   case ARM::VLD4dWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4d8_UPD;
6591   case ARM::VLD4dWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4d16_UPD;
6592   case ARM::VLD4dWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4d32_UPD;
6593   case ARM::VLD4qWB_fixed_Asm_8:  Spacing = 2; return ARM::VLD4q8_UPD;
6594   case ARM::VLD4qWB_fixed_Asm_16: Spacing = 2; return ARM::VLD4q16_UPD;
6595   case ARM::VLD4qWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4q32_UPD;
6596   case ARM::VLD4dWB_register_Asm_8:  Spacing = 1; return ARM::VLD4d8_UPD;
6597   case ARM::VLD4dWB_register_Asm_16: Spacing = 1; return ARM::VLD4d16_UPD;
6598   case ARM::VLD4dWB_register_Asm_32: Spacing = 1; return ARM::VLD4d32_UPD;
6599   case ARM::VLD4qWB_register_Asm_8:  Spacing = 2; return ARM::VLD4q8_UPD;
6600   case ARM::VLD4qWB_register_Asm_16: Spacing = 2; return ARM::VLD4q16_UPD;
6601   case ARM::VLD4qWB_register_Asm_32: Spacing = 2; return ARM::VLD4q32_UPD;
6602   case ARM::VLD4dAsm_8:  Spacing = 1; return ARM::VLD4d8;
6603   case ARM::VLD4dAsm_16: Spacing = 1; return ARM::VLD4d16;
6604   case ARM::VLD4dAsm_32: Spacing = 1; return ARM::VLD4d32;
6605   case ARM::VLD4qAsm_8:  Spacing = 2; return ARM::VLD4q8;
6606   case ARM::VLD4qAsm_16: Spacing = 2; return ARM::VLD4q16;
6607   case ARM::VLD4qAsm_32: Spacing = 2; return ARM::VLD4q32;
6608   }
6609 }
6610
6611 bool ARMAsmParser::processInstruction(MCInst &Inst,
6612                                       const OperandVector &Operands,
6613                                       MCStreamer &Out) {
6614   switch (Inst.getOpcode()) {
6615   // Alias for alternate form of 'ldr{,b}t Rt, [Rn], #imm' instruction.
6616   case ARM::LDRT_POST:
6617   case ARM::LDRBT_POST: {
6618     const unsigned Opcode =
6619       (Inst.getOpcode() == ARM::LDRT_POST) ? ARM::LDRT_POST_IMM
6620                                            : ARM::LDRBT_POST_IMM;
6621     MCInst TmpInst;
6622     TmpInst.setOpcode(Opcode);
6623     TmpInst.addOperand(Inst.getOperand(0));
6624     TmpInst.addOperand(Inst.getOperand(1));
6625     TmpInst.addOperand(Inst.getOperand(1));
6626     TmpInst.addOperand(MCOperand::CreateReg(0));
6627     TmpInst.addOperand(MCOperand::CreateImm(0));
6628     TmpInst.addOperand(Inst.getOperand(2));
6629     TmpInst.addOperand(Inst.getOperand(3));
6630     Inst = TmpInst;
6631     return true;
6632   }
6633   // Alias for alternate form of 'str{,b}t Rt, [Rn], #imm' instruction.
6634   case ARM::STRT_POST:
6635   case ARM::STRBT_POST: {
6636     const unsigned Opcode =
6637       (Inst.getOpcode() == ARM::STRT_POST) ? ARM::STRT_POST_IMM
6638                                            : ARM::STRBT_POST_IMM;
6639     MCInst TmpInst;
6640     TmpInst.setOpcode(Opcode);
6641     TmpInst.addOperand(Inst.getOperand(1));
6642     TmpInst.addOperand(Inst.getOperand(0));
6643     TmpInst.addOperand(Inst.getOperand(1));
6644     TmpInst.addOperand(MCOperand::CreateReg(0));
6645     TmpInst.addOperand(MCOperand::CreateImm(0));
6646     TmpInst.addOperand(Inst.getOperand(2));
6647     TmpInst.addOperand(Inst.getOperand(3));
6648     Inst = TmpInst;
6649     return true;
6650   }
6651   // Alias for alternate form of 'ADR Rd, #imm' instruction.
6652   case ARM::ADDri: {
6653     if (Inst.getOperand(1).getReg() != ARM::PC ||
6654         Inst.getOperand(5).getReg() != 0 ||
6655         !(Inst.getOperand(2).isExpr() || Inst.getOperand(2).isImm()))
6656       return false;
6657     MCInst TmpInst;
6658     TmpInst.setOpcode(ARM::ADR);
6659     TmpInst.addOperand(Inst.getOperand(0));
6660     if (Inst.getOperand(2).isImm()) {
6661       TmpInst.addOperand(Inst.getOperand(2));
6662     } else {
6663       // Turn PC-relative expression into absolute expression.
6664       // Reading PC provides the start of the current instruction + 8 and
6665       // the transform to adr is biased by that.
6666       MCSymbol *Dot = getContext().CreateTempSymbol();
6667       Out.EmitLabel(Dot);
6668       const MCExpr *OpExpr = Inst.getOperand(2).getExpr();
6669       const MCExpr *InstPC = MCSymbolRefExpr::Create(Dot,
6670                                                      MCSymbolRefExpr::VK_None,
6671                                                      getContext());
6672       const MCExpr *Const8 = MCConstantExpr::Create(8, getContext());
6673       const MCExpr *ReadPC = MCBinaryExpr::CreateAdd(InstPC, Const8,
6674                                                      getContext());
6675       const MCExpr *FixupAddr = MCBinaryExpr::CreateAdd(ReadPC, OpExpr,
6676                                                         getContext());
6677       TmpInst.addOperand(MCOperand::CreateExpr(FixupAddr));
6678     }
6679     TmpInst.addOperand(Inst.getOperand(3));
6680     TmpInst.addOperand(Inst.getOperand(4));
6681     Inst = TmpInst;
6682     return true;
6683   }
6684   // Aliases for alternate PC+imm syntax of LDR instructions.
6685   case ARM::t2LDRpcrel:
6686     // Select the narrow version if the immediate will fit.
6687     if (Inst.getOperand(1).getImm() > 0 &&
6688         Inst.getOperand(1).getImm() <= 0xff &&
6689         !(static_cast<ARMOperand &>(*Operands[2]).isToken() &&
6690           static_cast<ARMOperand &>(*Operands[2]).getToken() == ".w"))
6691       Inst.setOpcode(ARM::tLDRpci);
6692     else
6693       Inst.setOpcode(ARM::t2LDRpci);
6694     return true;
6695   case ARM::t2LDRBpcrel:
6696     Inst.setOpcode(ARM::t2LDRBpci);
6697     return true;
6698   case ARM::t2LDRHpcrel:
6699     Inst.setOpcode(ARM::t2LDRHpci);
6700     return true;
6701   case ARM::t2LDRSBpcrel:
6702     Inst.setOpcode(ARM::t2LDRSBpci);
6703     return true;
6704   case ARM::t2LDRSHpcrel:
6705     Inst.setOpcode(ARM::t2LDRSHpci);
6706     return true;
6707   // Handle NEON VST complex aliases.
6708   case ARM::VST1LNdWB_register_Asm_8:
6709   case ARM::VST1LNdWB_register_Asm_16:
6710   case ARM::VST1LNdWB_register_Asm_32: {
6711     MCInst TmpInst;
6712     // Shuffle the operands around so the lane index operand is in the
6713     // right place.
6714     unsigned Spacing;
6715     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
6716     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
6717     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6718     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6719     TmpInst.addOperand(Inst.getOperand(4)); // Rm
6720     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6721     TmpInst.addOperand(Inst.getOperand(1)); // lane
6722     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
6723     TmpInst.addOperand(Inst.getOperand(6));
6724     Inst = TmpInst;
6725     return true;
6726   }
6727
6728   case ARM::VST2LNdWB_register_Asm_8:
6729   case ARM::VST2LNdWB_register_Asm_16:
6730   case ARM::VST2LNdWB_register_Asm_32:
6731   case ARM::VST2LNqWB_register_Asm_16:
6732   case ARM::VST2LNqWB_register_Asm_32: {
6733     MCInst TmpInst;
6734     // Shuffle the operands around so the lane index operand is in the
6735     // right place.
6736     unsigned Spacing;
6737     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
6738     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
6739     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6740     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6741     TmpInst.addOperand(Inst.getOperand(4)); // Rm
6742     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6743     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
6744                                             Spacing));
6745     TmpInst.addOperand(Inst.getOperand(1)); // lane
6746     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
6747     TmpInst.addOperand(Inst.getOperand(6));
6748     Inst = TmpInst;
6749     return true;
6750   }
6751
6752   case ARM::VST3LNdWB_register_Asm_8:
6753   case ARM::VST3LNdWB_register_Asm_16:
6754   case ARM::VST3LNdWB_register_Asm_32:
6755   case ARM::VST3LNqWB_register_Asm_16:
6756   case ARM::VST3LNqWB_register_Asm_32: {
6757     MCInst TmpInst;
6758     // Shuffle the operands around so the lane index operand is in the
6759     // right place.
6760     unsigned Spacing;
6761     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
6762     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
6763     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6764     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6765     TmpInst.addOperand(Inst.getOperand(4)); // Rm
6766     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6767     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
6768                                             Spacing));
6769     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
6770                                             Spacing * 2));
6771     TmpInst.addOperand(Inst.getOperand(1)); // lane
6772     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
6773     TmpInst.addOperand(Inst.getOperand(6));
6774     Inst = TmpInst;
6775     return true;
6776   }
6777
6778   case ARM::VST4LNdWB_register_Asm_8:
6779   case ARM::VST4LNdWB_register_Asm_16:
6780   case ARM::VST4LNdWB_register_Asm_32:
6781   case ARM::VST4LNqWB_register_Asm_16:
6782   case ARM::VST4LNqWB_register_Asm_32: {
6783     MCInst TmpInst;
6784     // Shuffle the operands around so the lane index operand is in the
6785     // right place.
6786     unsigned Spacing;
6787     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
6788     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
6789     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6790     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6791     TmpInst.addOperand(Inst.getOperand(4)); // Rm
6792     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6793     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
6794                                             Spacing));
6795     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
6796                                             Spacing * 2));
6797     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
6798                                             Spacing * 3));
6799     TmpInst.addOperand(Inst.getOperand(1)); // lane
6800     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
6801     TmpInst.addOperand(Inst.getOperand(6));
6802     Inst = TmpInst;
6803     return true;
6804   }
6805
6806   case ARM::VST1LNdWB_fixed_Asm_8:
6807   case ARM::VST1LNdWB_fixed_Asm_16:
6808   case ARM::VST1LNdWB_fixed_Asm_32: {
6809     MCInst TmpInst;
6810     // Shuffle the operands around so the lane index operand is in the
6811     // right place.
6812     unsigned Spacing;
6813     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
6814     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
6815     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6816     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6817     TmpInst.addOperand(MCOperand::CreateReg(0)); // Rm
6818     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6819     TmpInst.addOperand(Inst.getOperand(1)); // lane
6820     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
6821     TmpInst.addOperand(Inst.getOperand(5));
6822     Inst = TmpInst;
6823     return true;
6824   }
6825
6826   case ARM::VST2LNdWB_fixed_Asm_8:
6827   case ARM::VST2LNdWB_fixed_Asm_16:
6828   case ARM::VST2LNdWB_fixed_Asm_32:
6829   case ARM::VST2LNqWB_fixed_Asm_16:
6830   case ARM::VST2LNqWB_fixed_Asm_32: {
6831     MCInst TmpInst;
6832     // Shuffle the operands around so the lane index operand is in the
6833     // right place.
6834     unsigned Spacing;
6835     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
6836     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
6837     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6838     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6839     TmpInst.addOperand(MCOperand::CreateReg(0)); // Rm
6840     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6841     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
6842                                             Spacing));
6843     TmpInst.addOperand(Inst.getOperand(1)); // lane
6844     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
6845     TmpInst.addOperand(Inst.getOperand(5));
6846     Inst = TmpInst;
6847     return true;
6848   }
6849
6850   case ARM::VST3LNdWB_fixed_Asm_8:
6851   case ARM::VST3LNdWB_fixed_Asm_16:
6852   case ARM::VST3LNdWB_fixed_Asm_32:
6853   case ARM::VST3LNqWB_fixed_Asm_16:
6854   case ARM::VST3LNqWB_fixed_Asm_32: {
6855     MCInst TmpInst;
6856     // Shuffle the operands around so the lane index operand is in the
6857     // right place.
6858     unsigned Spacing;
6859     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
6860     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
6861     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6862     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6863     TmpInst.addOperand(MCOperand::CreateReg(0)); // Rm
6864     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6865     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
6866                                             Spacing));
6867     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
6868                                             Spacing * 2));
6869     TmpInst.addOperand(Inst.getOperand(1)); // lane
6870     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
6871     TmpInst.addOperand(Inst.getOperand(5));
6872     Inst = TmpInst;
6873     return true;
6874   }
6875
6876   case ARM::VST4LNdWB_fixed_Asm_8:
6877   case ARM::VST4LNdWB_fixed_Asm_16:
6878   case ARM::VST4LNdWB_fixed_Asm_32:
6879   case ARM::VST4LNqWB_fixed_Asm_16:
6880   case ARM::VST4LNqWB_fixed_Asm_32: {
6881     MCInst TmpInst;
6882     // Shuffle the operands around so the lane index operand is in the
6883     // right place.
6884     unsigned Spacing;
6885     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
6886     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
6887     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6888     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6889     TmpInst.addOperand(MCOperand::CreateReg(0)); // Rm
6890     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6891     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
6892                                             Spacing));
6893     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
6894                                             Spacing * 2));
6895     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
6896                                             Spacing * 3));
6897     TmpInst.addOperand(Inst.getOperand(1)); // lane
6898     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
6899     TmpInst.addOperand(Inst.getOperand(5));
6900     Inst = TmpInst;
6901     return true;
6902   }
6903
6904   case ARM::VST1LNdAsm_8:
6905   case ARM::VST1LNdAsm_16:
6906   case ARM::VST1LNdAsm_32: {
6907     MCInst TmpInst;
6908     // Shuffle the operands around so the lane index operand is in the
6909     // right place.
6910     unsigned Spacing;
6911     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
6912     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6913     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6914     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6915     TmpInst.addOperand(Inst.getOperand(1)); // lane
6916     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
6917     TmpInst.addOperand(Inst.getOperand(5));
6918     Inst = TmpInst;
6919     return true;
6920   }
6921
6922   case ARM::VST2LNdAsm_8:
6923   case ARM::VST2LNdAsm_16:
6924   case ARM::VST2LNdAsm_32:
6925   case ARM::VST2LNqAsm_16:
6926   case ARM::VST2LNqAsm_32: {
6927     MCInst TmpInst;
6928     // Shuffle the operands around so the lane index operand is in the
6929     // right place.
6930     unsigned Spacing;
6931     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
6932     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6933     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6934     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6935     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
6936                                             Spacing));
6937     TmpInst.addOperand(Inst.getOperand(1)); // lane
6938     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
6939     TmpInst.addOperand(Inst.getOperand(5));
6940     Inst = TmpInst;
6941     return true;
6942   }
6943
6944   case ARM::VST3LNdAsm_8:
6945   case ARM::VST3LNdAsm_16:
6946   case ARM::VST3LNdAsm_32:
6947   case ARM::VST3LNqAsm_16:
6948   case ARM::VST3LNqAsm_32: {
6949     MCInst TmpInst;
6950     // Shuffle the operands around so the lane index operand is in the
6951     // right place.
6952     unsigned Spacing;
6953     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
6954     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6955     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6956     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6957     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
6958                                             Spacing));
6959     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
6960                                             Spacing * 2));
6961     TmpInst.addOperand(Inst.getOperand(1)); // lane
6962     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
6963     TmpInst.addOperand(Inst.getOperand(5));
6964     Inst = TmpInst;
6965     return true;
6966   }
6967
6968   case ARM::VST4LNdAsm_8:
6969   case ARM::VST4LNdAsm_16:
6970   case ARM::VST4LNdAsm_32:
6971   case ARM::VST4LNqAsm_16:
6972   case ARM::VST4LNqAsm_32: {
6973     MCInst TmpInst;
6974     // Shuffle the operands around so the lane index operand is in the
6975     // right place.
6976     unsigned Spacing;
6977     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
6978     TmpInst.addOperand(Inst.getOperand(2)); // Rn
6979     TmpInst.addOperand(Inst.getOperand(3)); // alignment
6980     TmpInst.addOperand(Inst.getOperand(0)); // Vd
6981     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
6982                                             Spacing));
6983     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
6984                                             Spacing * 2));
6985     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
6986                                             Spacing * 3));
6987     TmpInst.addOperand(Inst.getOperand(1)); // lane
6988     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
6989     TmpInst.addOperand(Inst.getOperand(5));
6990     Inst = TmpInst;
6991     return true;
6992   }
6993
6994   // Handle NEON VLD complex aliases.
6995   case ARM::VLD1LNdWB_register_Asm_8:
6996   case ARM::VLD1LNdWB_register_Asm_16:
6997   case ARM::VLD1LNdWB_register_Asm_32: {
6998     MCInst TmpInst;
6999     // Shuffle the operands around so the lane index operand is in the
7000     // right place.
7001     unsigned Spacing;
7002     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7003     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7004     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7005     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7006     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7007     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7008     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7009     TmpInst.addOperand(Inst.getOperand(1)); // lane
7010     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7011     TmpInst.addOperand(Inst.getOperand(6));
7012     Inst = TmpInst;
7013     return true;
7014   }
7015
7016   case ARM::VLD2LNdWB_register_Asm_8:
7017   case ARM::VLD2LNdWB_register_Asm_16:
7018   case ARM::VLD2LNdWB_register_Asm_32:
7019   case ARM::VLD2LNqWB_register_Asm_16:
7020   case ARM::VLD2LNqWB_register_Asm_32: {
7021     MCInst TmpInst;
7022     // Shuffle the operands around so the lane index operand is in the
7023     // right place.
7024     unsigned Spacing;
7025     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7026     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7027     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7028                                             Spacing));
7029     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7030     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7031     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7032     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7033     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7034     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7035                                             Spacing));
7036     TmpInst.addOperand(Inst.getOperand(1)); // lane
7037     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7038     TmpInst.addOperand(Inst.getOperand(6));
7039     Inst = TmpInst;
7040     return true;
7041   }
7042
7043   case ARM::VLD3LNdWB_register_Asm_8:
7044   case ARM::VLD3LNdWB_register_Asm_16:
7045   case ARM::VLD3LNdWB_register_Asm_32:
7046   case ARM::VLD3LNqWB_register_Asm_16:
7047   case ARM::VLD3LNqWB_register_Asm_32: {
7048     MCInst TmpInst;
7049     // Shuffle the operands around so the lane index operand is in the
7050     // right place.
7051     unsigned Spacing;
7052     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7053     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7054     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7055                                             Spacing));
7056     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7057                                             Spacing * 2));
7058     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7059     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7060     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7061     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7062     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7063     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7064                                             Spacing));
7065     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7066                                             Spacing * 2));
7067     TmpInst.addOperand(Inst.getOperand(1)); // lane
7068     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7069     TmpInst.addOperand(Inst.getOperand(6));
7070     Inst = TmpInst;
7071     return true;
7072   }
7073
7074   case ARM::VLD4LNdWB_register_Asm_8:
7075   case ARM::VLD4LNdWB_register_Asm_16:
7076   case ARM::VLD4LNdWB_register_Asm_32:
7077   case ARM::VLD4LNqWB_register_Asm_16:
7078   case ARM::VLD4LNqWB_register_Asm_32: {
7079     MCInst TmpInst;
7080     // Shuffle the operands around so the lane index operand is in the
7081     // right place.
7082     unsigned Spacing;
7083     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7084     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7085     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7086                                             Spacing));
7087     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7088                                             Spacing * 2));
7089     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7090                                             Spacing * 3));
7091     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7092     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7093     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7094     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7095     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7096     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7097                                             Spacing));
7098     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7099                                             Spacing * 2));
7100     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7101                                             Spacing * 3));
7102     TmpInst.addOperand(Inst.getOperand(1)); // lane
7103     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7104     TmpInst.addOperand(Inst.getOperand(6));
7105     Inst = TmpInst;
7106     return true;
7107   }
7108
7109   case ARM::VLD1LNdWB_fixed_Asm_8:
7110   case ARM::VLD1LNdWB_fixed_Asm_16:
7111   case ARM::VLD1LNdWB_fixed_Asm_32: {
7112     MCInst TmpInst;
7113     // Shuffle the operands around so the lane index operand is in the
7114     // right place.
7115     unsigned Spacing;
7116     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7117     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7118     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7119     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7120     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7121     TmpInst.addOperand(MCOperand::CreateReg(0)); // Rm
7122     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7123     TmpInst.addOperand(Inst.getOperand(1)); // lane
7124     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7125     TmpInst.addOperand(Inst.getOperand(5));
7126     Inst = TmpInst;
7127     return true;
7128   }
7129
7130   case ARM::VLD2LNdWB_fixed_Asm_8:
7131   case ARM::VLD2LNdWB_fixed_Asm_16:
7132   case ARM::VLD2LNdWB_fixed_Asm_32:
7133   case ARM::VLD2LNqWB_fixed_Asm_16:
7134   case ARM::VLD2LNqWB_fixed_Asm_32: {
7135     MCInst TmpInst;
7136     // Shuffle the operands around so the lane index operand is in the
7137     // right place.
7138     unsigned Spacing;
7139     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7140     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7141     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7142                                             Spacing));
7143     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7144     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7145     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7146     TmpInst.addOperand(MCOperand::CreateReg(0)); // Rm
7147     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7148     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7149                                             Spacing));
7150     TmpInst.addOperand(Inst.getOperand(1)); // lane
7151     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7152     TmpInst.addOperand(Inst.getOperand(5));
7153     Inst = TmpInst;
7154     return true;
7155   }
7156
7157   case ARM::VLD3LNdWB_fixed_Asm_8:
7158   case ARM::VLD3LNdWB_fixed_Asm_16:
7159   case ARM::VLD3LNdWB_fixed_Asm_32:
7160   case ARM::VLD3LNqWB_fixed_Asm_16:
7161   case ARM::VLD3LNqWB_fixed_Asm_32: {
7162     MCInst TmpInst;
7163     // Shuffle the operands around so the lane index operand is in the
7164     // right place.
7165     unsigned Spacing;
7166     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7167     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7168     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7169                                             Spacing));
7170     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7171                                             Spacing * 2));
7172     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7173     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7174     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7175     TmpInst.addOperand(MCOperand::CreateReg(0)); // Rm
7176     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7177     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7178                                             Spacing));
7179     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7180                                             Spacing * 2));
7181     TmpInst.addOperand(Inst.getOperand(1)); // lane
7182     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7183     TmpInst.addOperand(Inst.getOperand(5));
7184     Inst = TmpInst;
7185     return true;
7186   }
7187
7188   case ARM::VLD4LNdWB_fixed_Asm_8:
7189   case ARM::VLD4LNdWB_fixed_Asm_16:
7190   case ARM::VLD4LNdWB_fixed_Asm_32:
7191   case ARM::VLD4LNqWB_fixed_Asm_16:
7192   case ARM::VLD4LNqWB_fixed_Asm_32: {
7193     MCInst TmpInst;
7194     // Shuffle the operands around so the lane index operand is in the
7195     // right place.
7196     unsigned Spacing;
7197     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7198     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7199     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7200                                             Spacing));
7201     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7202                                             Spacing * 2));
7203     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7204                                             Spacing * 3));
7205     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7206     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7207     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7208     TmpInst.addOperand(MCOperand::CreateReg(0)); // Rm
7209     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7210     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7211                                             Spacing));
7212     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7213                                             Spacing * 2));
7214     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7215                                             Spacing * 3));
7216     TmpInst.addOperand(Inst.getOperand(1)); // lane
7217     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7218     TmpInst.addOperand(Inst.getOperand(5));
7219     Inst = TmpInst;
7220     return true;
7221   }
7222
7223   case ARM::VLD1LNdAsm_8:
7224   case ARM::VLD1LNdAsm_16:
7225   case ARM::VLD1LNdAsm_32: {
7226     MCInst TmpInst;
7227     // Shuffle the operands around so the lane index operand is in the
7228     // right place.
7229     unsigned Spacing;
7230     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7231     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7232     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7233     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7234     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7235     TmpInst.addOperand(Inst.getOperand(1)); // lane
7236     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7237     TmpInst.addOperand(Inst.getOperand(5));
7238     Inst = TmpInst;
7239     return true;
7240   }
7241
7242   case ARM::VLD2LNdAsm_8:
7243   case ARM::VLD2LNdAsm_16:
7244   case ARM::VLD2LNdAsm_32:
7245   case ARM::VLD2LNqAsm_16:
7246   case ARM::VLD2LNqAsm_32: {
7247     MCInst TmpInst;
7248     // Shuffle the operands around so the lane index operand is in the
7249     // right place.
7250     unsigned Spacing;
7251     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7252     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7253     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7254                                             Spacing));
7255     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7256     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7257     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7258     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7259                                             Spacing));
7260     TmpInst.addOperand(Inst.getOperand(1)); // lane
7261     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7262     TmpInst.addOperand(Inst.getOperand(5));
7263     Inst = TmpInst;
7264     return true;
7265   }
7266
7267   case ARM::VLD3LNdAsm_8:
7268   case ARM::VLD3LNdAsm_16:
7269   case ARM::VLD3LNdAsm_32:
7270   case ARM::VLD3LNqAsm_16:
7271   case ARM::VLD3LNqAsm_32: {
7272     MCInst TmpInst;
7273     // Shuffle the operands around so the lane index operand is in the
7274     // right place.
7275     unsigned Spacing;
7276     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7277     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7278     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7279                                             Spacing));
7280     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7281                                             Spacing * 2));
7282     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7283     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7284     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7285     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7286                                             Spacing));
7287     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7288                                             Spacing * 2));
7289     TmpInst.addOperand(Inst.getOperand(1)); // lane
7290     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7291     TmpInst.addOperand(Inst.getOperand(5));
7292     Inst = TmpInst;
7293     return true;
7294   }
7295
7296   case ARM::VLD4LNdAsm_8:
7297   case ARM::VLD4LNdAsm_16:
7298   case ARM::VLD4LNdAsm_32:
7299   case ARM::VLD4LNqAsm_16:
7300   case ARM::VLD4LNqAsm_32: {
7301     MCInst TmpInst;
7302     // Shuffle the operands around so the lane index operand is in the
7303     // right place.
7304     unsigned Spacing;
7305     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7306     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7307     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7308                                             Spacing));
7309     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7310                                             Spacing * 2));
7311     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7312                                             Spacing * 3));
7313     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7314     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7315     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7316     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7317                                             Spacing));
7318     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7319                                             Spacing * 2));
7320     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7321                                             Spacing * 3));
7322     TmpInst.addOperand(Inst.getOperand(1)); // lane
7323     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7324     TmpInst.addOperand(Inst.getOperand(5));
7325     Inst = TmpInst;
7326     return true;
7327   }
7328
7329   // VLD3DUP single 3-element structure to all lanes instructions.
7330   case ARM::VLD3DUPdAsm_8:
7331   case ARM::VLD3DUPdAsm_16:
7332   case ARM::VLD3DUPdAsm_32:
7333   case ARM::VLD3DUPqAsm_8:
7334   case ARM::VLD3DUPqAsm_16:
7335   case ARM::VLD3DUPqAsm_32: {
7336     MCInst TmpInst;
7337     unsigned Spacing;
7338     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7339     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7340     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7341                                             Spacing));
7342     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7343                                             Spacing * 2));
7344     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7345     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7346     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7347     TmpInst.addOperand(Inst.getOperand(4));
7348     Inst = TmpInst;
7349     return true;
7350   }
7351
7352   case ARM::VLD3DUPdWB_fixed_Asm_8:
7353   case ARM::VLD3DUPdWB_fixed_Asm_16:
7354   case ARM::VLD3DUPdWB_fixed_Asm_32:
7355   case ARM::VLD3DUPqWB_fixed_Asm_8:
7356   case ARM::VLD3DUPqWB_fixed_Asm_16:
7357   case ARM::VLD3DUPqWB_fixed_Asm_32: {
7358     MCInst TmpInst;
7359     unsigned Spacing;
7360     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7361     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7362     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7363                                             Spacing));
7364     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7365                                             Spacing * 2));
7366     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7367     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7368     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7369     TmpInst.addOperand(MCOperand::CreateReg(0)); // Rm
7370     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7371     TmpInst.addOperand(Inst.getOperand(4));
7372     Inst = TmpInst;
7373     return true;
7374   }
7375
7376   case ARM::VLD3DUPdWB_register_Asm_8:
7377   case ARM::VLD3DUPdWB_register_Asm_16:
7378   case ARM::VLD3DUPdWB_register_Asm_32:
7379   case ARM::VLD3DUPqWB_register_Asm_8:
7380   case ARM::VLD3DUPqWB_register_Asm_16:
7381   case ARM::VLD3DUPqWB_register_Asm_32: {
7382     MCInst TmpInst;
7383     unsigned Spacing;
7384     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7385     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7386     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7387                                             Spacing));
7388     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7389                                             Spacing * 2));
7390     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7391     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7392     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7393     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7394     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7395     TmpInst.addOperand(Inst.getOperand(5));
7396     Inst = TmpInst;
7397     return true;
7398   }
7399
7400   // VLD3 multiple 3-element structure instructions.
7401   case ARM::VLD3dAsm_8:
7402   case ARM::VLD3dAsm_16:
7403   case ARM::VLD3dAsm_32:
7404   case ARM::VLD3qAsm_8:
7405   case ARM::VLD3qAsm_16:
7406   case ARM::VLD3qAsm_32: {
7407     MCInst TmpInst;
7408     unsigned Spacing;
7409     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7410     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7411     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7412                                             Spacing));
7413     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7414                                             Spacing * 2));
7415     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7416     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7417     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7418     TmpInst.addOperand(Inst.getOperand(4));
7419     Inst = TmpInst;
7420     return true;
7421   }
7422
7423   case ARM::VLD3dWB_fixed_Asm_8:
7424   case ARM::VLD3dWB_fixed_Asm_16:
7425   case ARM::VLD3dWB_fixed_Asm_32:
7426   case ARM::VLD3qWB_fixed_Asm_8:
7427   case ARM::VLD3qWB_fixed_Asm_16:
7428   case ARM::VLD3qWB_fixed_Asm_32: {
7429     MCInst TmpInst;
7430     unsigned Spacing;
7431     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7432     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7433     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7434                                             Spacing));
7435     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7436                                             Spacing * 2));
7437     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7438     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7439     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7440     TmpInst.addOperand(MCOperand::CreateReg(0)); // Rm
7441     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7442     TmpInst.addOperand(Inst.getOperand(4));
7443     Inst = TmpInst;
7444     return true;
7445   }
7446
7447   case ARM::VLD3dWB_register_Asm_8:
7448   case ARM::VLD3dWB_register_Asm_16:
7449   case ARM::VLD3dWB_register_Asm_32:
7450   case ARM::VLD3qWB_register_Asm_8:
7451   case ARM::VLD3qWB_register_Asm_16:
7452   case ARM::VLD3qWB_register_Asm_32: {
7453     MCInst TmpInst;
7454     unsigned Spacing;
7455     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7456     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7457     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7458                                             Spacing));
7459     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7460                                             Spacing * 2));
7461     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7462     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7463     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7464     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7465     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7466     TmpInst.addOperand(Inst.getOperand(5));
7467     Inst = TmpInst;
7468     return true;
7469   }
7470
7471   // VLD4DUP single 3-element structure to all lanes instructions.
7472   case ARM::VLD4DUPdAsm_8:
7473   case ARM::VLD4DUPdAsm_16:
7474   case ARM::VLD4DUPdAsm_32:
7475   case ARM::VLD4DUPqAsm_8:
7476   case ARM::VLD4DUPqAsm_16:
7477   case ARM::VLD4DUPqAsm_32: {
7478     MCInst TmpInst;
7479     unsigned Spacing;
7480     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7481     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7482     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7483                                             Spacing));
7484     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7485                                             Spacing * 2));
7486     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7487                                             Spacing * 3));
7488     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7489     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7490     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7491     TmpInst.addOperand(Inst.getOperand(4));
7492     Inst = TmpInst;
7493     return true;
7494   }
7495
7496   case ARM::VLD4DUPdWB_fixed_Asm_8:
7497   case ARM::VLD4DUPdWB_fixed_Asm_16:
7498   case ARM::VLD4DUPdWB_fixed_Asm_32:
7499   case ARM::VLD4DUPqWB_fixed_Asm_8:
7500   case ARM::VLD4DUPqWB_fixed_Asm_16:
7501   case ARM::VLD4DUPqWB_fixed_Asm_32: {
7502     MCInst TmpInst;
7503     unsigned Spacing;
7504     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7505     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7506     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7507                                             Spacing));
7508     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7509                                             Spacing * 2));
7510     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7511                                             Spacing * 3));
7512     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7513     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7514     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7515     TmpInst.addOperand(MCOperand::CreateReg(0)); // Rm
7516     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7517     TmpInst.addOperand(Inst.getOperand(4));
7518     Inst = TmpInst;
7519     return true;
7520   }
7521
7522   case ARM::VLD4DUPdWB_register_Asm_8:
7523   case ARM::VLD4DUPdWB_register_Asm_16:
7524   case ARM::VLD4DUPdWB_register_Asm_32:
7525   case ARM::VLD4DUPqWB_register_Asm_8:
7526   case ARM::VLD4DUPqWB_register_Asm_16:
7527   case ARM::VLD4DUPqWB_register_Asm_32: {
7528     MCInst TmpInst;
7529     unsigned Spacing;
7530     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7531     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7532     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7533                                             Spacing));
7534     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7535                                             Spacing * 2));
7536     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7537                                             Spacing * 3));
7538     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7539     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7540     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7541     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7542     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7543     TmpInst.addOperand(Inst.getOperand(5));
7544     Inst = TmpInst;
7545     return true;
7546   }
7547
7548   // VLD4 multiple 4-element structure instructions.
7549   case ARM::VLD4dAsm_8:
7550   case ARM::VLD4dAsm_16:
7551   case ARM::VLD4dAsm_32:
7552   case ARM::VLD4qAsm_8:
7553   case ARM::VLD4qAsm_16:
7554   case ARM::VLD4qAsm_32: {
7555     MCInst TmpInst;
7556     unsigned Spacing;
7557     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7558     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7559     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7560                                             Spacing));
7561     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7562                                             Spacing * 2));
7563     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7564                                             Spacing * 3));
7565     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7566     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7567     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7568     TmpInst.addOperand(Inst.getOperand(4));
7569     Inst = TmpInst;
7570     return true;
7571   }
7572
7573   case ARM::VLD4dWB_fixed_Asm_8:
7574   case ARM::VLD4dWB_fixed_Asm_16:
7575   case ARM::VLD4dWB_fixed_Asm_32:
7576   case ARM::VLD4qWB_fixed_Asm_8:
7577   case ARM::VLD4qWB_fixed_Asm_16:
7578   case ARM::VLD4qWB_fixed_Asm_32: {
7579     MCInst TmpInst;
7580     unsigned Spacing;
7581     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7582     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7583     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7584                                             Spacing));
7585     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7586                                             Spacing * 2));
7587     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7588                                             Spacing * 3));
7589     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7590     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7591     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7592     TmpInst.addOperand(MCOperand::CreateReg(0)); // Rm
7593     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7594     TmpInst.addOperand(Inst.getOperand(4));
7595     Inst = TmpInst;
7596     return true;
7597   }
7598
7599   case ARM::VLD4dWB_register_Asm_8:
7600   case ARM::VLD4dWB_register_Asm_16:
7601   case ARM::VLD4dWB_register_Asm_32:
7602   case ARM::VLD4qWB_register_Asm_8:
7603   case ARM::VLD4qWB_register_Asm_16:
7604   case ARM::VLD4qWB_register_Asm_32: {
7605     MCInst TmpInst;
7606     unsigned Spacing;
7607     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7608     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7609     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7610                                             Spacing));
7611     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7612                                             Spacing * 2));
7613     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7614                                             Spacing * 3));
7615     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7616     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7617     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7618     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7619     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7620     TmpInst.addOperand(Inst.getOperand(5));
7621     Inst = TmpInst;
7622     return true;
7623   }
7624
7625   // VST3 multiple 3-element structure instructions.
7626   case ARM::VST3dAsm_8:
7627   case ARM::VST3dAsm_16:
7628   case ARM::VST3dAsm_32:
7629   case ARM::VST3qAsm_8:
7630   case ARM::VST3qAsm_16:
7631   case ARM::VST3qAsm_32: {
7632     MCInst TmpInst;
7633     unsigned Spacing;
7634     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7635     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7636     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7637     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7638     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7639                                             Spacing));
7640     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7641                                             Spacing * 2));
7642     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7643     TmpInst.addOperand(Inst.getOperand(4));
7644     Inst = TmpInst;
7645     return true;
7646   }
7647
7648   case ARM::VST3dWB_fixed_Asm_8:
7649   case ARM::VST3dWB_fixed_Asm_16:
7650   case ARM::VST3dWB_fixed_Asm_32:
7651   case ARM::VST3qWB_fixed_Asm_8:
7652   case ARM::VST3qWB_fixed_Asm_16:
7653   case ARM::VST3qWB_fixed_Asm_32: {
7654     MCInst TmpInst;
7655     unsigned Spacing;
7656     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7657     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7658     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7659     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7660     TmpInst.addOperand(MCOperand::CreateReg(0)); // Rm
7661     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7662     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7663                                             Spacing));
7664     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7665                                             Spacing * 2));
7666     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7667     TmpInst.addOperand(Inst.getOperand(4));
7668     Inst = TmpInst;
7669     return true;
7670   }
7671
7672   case ARM::VST3dWB_register_Asm_8:
7673   case ARM::VST3dWB_register_Asm_16:
7674   case ARM::VST3dWB_register_Asm_32:
7675   case ARM::VST3qWB_register_Asm_8:
7676   case ARM::VST3qWB_register_Asm_16:
7677   case ARM::VST3qWB_register_Asm_32: {
7678     MCInst TmpInst;
7679     unsigned Spacing;
7680     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7681     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7682     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7683     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7684     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7685     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7686     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7687                                             Spacing));
7688     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7689                                             Spacing * 2));
7690     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7691     TmpInst.addOperand(Inst.getOperand(5));
7692     Inst = TmpInst;
7693     return true;
7694   }
7695
7696   // VST4 multiple 3-element structure instructions.
7697   case ARM::VST4dAsm_8:
7698   case ARM::VST4dAsm_16:
7699   case ARM::VST4dAsm_32:
7700   case ARM::VST4qAsm_8:
7701   case ARM::VST4qAsm_16:
7702   case ARM::VST4qAsm_32: {
7703     MCInst TmpInst;
7704     unsigned Spacing;
7705     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7706     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7707     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7708     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7709     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7710                                             Spacing));
7711     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7712                                             Spacing * 2));
7713     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7714                                             Spacing * 3));
7715     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7716     TmpInst.addOperand(Inst.getOperand(4));
7717     Inst = TmpInst;
7718     return true;
7719   }
7720
7721   case ARM::VST4dWB_fixed_Asm_8:
7722   case ARM::VST4dWB_fixed_Asm_16:
7723   case ARM::VST4dWB_fixed_Asm_32:
7724   case ARM::VST4qWB_fixed_Asm_8:
7725   case ARM::VST4qWB_fixed_Asm_16:
7726   case ARM::VST4qWB_fixed_Asm_32: {
7727     MCInst TmpInst;
7728     unsigned Spacing;
7729     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7730     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7731     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7732     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7733     TmpInst.addOperand(MCOperand::CreateReg(0)); // Rm
7734     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7735     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7736                                             Spacing));
7737     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7738                                             Spacing * 2));
7739     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7740                                             Spacing * 3));
7741     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7742     TmpInst.addOperand(Inst.getOperand(4));
7743     Inst = TmpInst;
7744     return true;
7745   }
7746
7747   case ARM::VST4dWB_register_Asm_8:
7748   case ARM::VST4dWB_register_Asm_16:
7749   case ARM::VST4dWB_register_Asm_32:
7750   case ARM::VST4qWB_register_Asm_8:
7751   case ARM::VST4qWB_register_Asm_16:
7752   case ARM::VST4qWB_register_Asm_32: {
7753     MCInst TmpInst;
7754     unsigned Spacing;
7755     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7756     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7757     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7758     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7759     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7760     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7761     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7762                                             Spacing));
7763     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7764                                             Spacing * 2));
7765     TmpInst.addOperand(MCOperand::CreateReg(Inst.getOperand(0).getReg() +
7766                                             Spacing * 3));
7767     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7768     TmpInst.addOperand(Inst.getOperand(5));
7769     Inst = TmpInst;
7770     return true;
7771   }
7772
7773   // Handle encoding choice for the shift-immediate instructions.
7774   case ARM::t2LSLri:
7775   case ARM::t2LSRri:
7776   case ARM::t2ASRri: {
7777     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
7778         Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() &&
7779         Inst.getOperand(5).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
7780         !(static_cast<ARMOperand &>(*Operands[3]).isToken() &&
7781           static_cast<ARMOperand &>(*Operands[3]).getToken() == ".w")) {
7782       unsigned NewOpc;
7783       switch (Inst.getOpcode()) {
7784       default: llvm_unreachable("unexpected opcode");
7785       case ARM::t2LSLri: NewOpc = ARM::tLSLri; break;
7786       case ARM::t2LSRri: NewOpc = ARM::tLSRri; break;
7787       case ARM::t2ASRri: NewOpc = ARM::tASRri; break;
7788       }
7789       // The Thumb1 operands aren't in the same order. Awesome, eh?
7790       MCInst TmpInst;
7791       TmpInst.setOpcode(NewOpc);
7792       TmpInst.addOperand(Inst.getOperand(0));
7793       TmpInst.addOperand(Inst.getOperand(5));
7794       TmpInst.addOperand(Inst.getOperand(1));
7795       TmpInst.addOperand(Inst.getOperand(2));
7796       TmpInst.addOperand(Inst.getOperand(3));
7797       TmpInst.addOperand(Inst.getOperand(4));
7798       Inst = TmpInst;
7799       return true;
7800     }
7801     return false;
7802   }
7803
7804   // Handle the Thumb2 mode MOV complex aliases.
7805   case ARM::t2MOVsr:
7806   case ARM::t2MOVSsr: {
7807     // Which instruction to expand to depends on the CCOut operand and
7808     // whether we're in an IT block if the register operands are low
7809     // registers.
7810     bool isNarrow = false;
7811     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
7812         isARMLowRegister(Inst.getOperand(1).getReg()) &&
7813         isARMLowRegister(Inst.getOperand(2).getReg()) &&
7814         Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() &&
7815         inITBlock() == (Inst.getOpcode() == ARM::t2MOVsr))
7816       isNarrow = true;
7817     MCInst TmpInst;
7818     unsigned newOpc;
7819     switch(ARM_AM::getSORegShOp(Inst.getOperand(3).getImm())) {
7820     default: llvm_unreachable("unexpected opcode!");
7821     case ARM_AM::asr: newOpc = isNarrow ? ARM::tASRrr : ARM::t2ASRrr; break;
7822     case ARM_AM::lsr: newOpc = isNarrow ? ARM::tLSRrr : ARM::t2LSRrr; break;
7823     case ARM_AM::lsl: newOpc = isNarrow ? ARM::tLSLrr : ARM::t2LSLrr; break;
7824     case ARM_AM::ror: newOpc = isNarrow ? ARM::tROR   : ARM::t2RORrr; break;
7825     }
7826     TmpInst.setOpcode(newOpc);
7827     TmpInst.addOperand(Inst.getOperand(0)); // Rd
7828     if (isNarrow)
7829       TmpInst.addOperand(MCOperand::CreateReg(
7830           Inst.getOpcode() == ARM::t2MOVSsr ? ARM::CPSR : 0));
7831     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7832     TmpInst.addOperand(Inst.getOperand(2)); // Rm
7833     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7834     TmpInst.addOperand(Inst.getOperand(5));
7835     if (!isNarrow)
7836       TmpInst.addOperand(MCOperand::CreateReg(
7837           Inst.getOpcode() == ARM::t2MOVSsr ? ARM::CPSR : 0));
7838     Inst = TmpInst;
7839     return true;
7840   }
7841   case ARM::t2MOVsi:
7842   case ARM::t2MOVSsi: {
7843     // Which instruction to expand to depends on the CCOut operand and
7844     // whether we're in an IT block if the register operands are low
7845     // registers.
7846     bool isNarrow = false;
7847     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
7848         isARMLowRegister(Inst.getOperand(1).getReg()) &&
7849         inITBlock() == (Inst.getOpcode() == ARM::t2MOVsi))
7850       isNarrow = true;
7851     MCInst TmpInst;
7852     unsigned newOpc;
7853     switch(ARM_AM::getSORegShOp(Inst.getOperand(2).getImm())) {
7854     default: llvm_unreachable("unexpected opcode!");
7855     case ARM_AM::asr: newOpc = isNarrow ? ARM::tASRri : ARM::t2ASRri; break;
7856     case ARM_AM::lsr: newOpc = isNarrow ? ARM::tLSRri : ARM::t2LSRri; break;
7857     case ARM_AM::lsl: newOpc = isNarrow ? ARM::tLSLri : ARM::t2LSLri; break;
7858     case ARM_AM::ror: newOpc = ARM::t2RORri; isNarrow = false; break;
7859     case ARM_AM::rrx: isNarrow = false; newOpc = ARM::t2RRX; break;
7860     }
7861     unsigned Amount = ARM_AM::getSORegOffset(Inst.getOperand(2).getImm());
7862     if (Amount == 32) Amount = 0;
7863     TmpInst.setOpcode(newOpc);
7864     TmpInst.addOperand(Inst.getOperand(0)); // Rd
7865     if (isNarrow)
7866       TmpInst.addOperand(MCOperand::CreateReg(
7867           Inst.getOpcode() == ARM::t2MOVSsi ? ARM::CPSR : 0));
7868     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7869     if (newOpc != ARM::t2RRX)
7870       TmpInst.addOperand(MCOperand::CreateImm(Amount));
7871     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7872     TmpInst.addOperand(Inst.getOperand(4));
7873     if (!isNarrow)
7874       TmpInst.addOperand(MCOperand::CreateReg(
7875           Inst.getOpcode() == ARM::t2MOVSsi ? ARM::CPSR : 0));
7876     Inst = TmpInst;
7877     return true;
7878   }
7879   // Handle the ARM mode MOV complex aliases.
7880   case ARM::ASRr:
7881   case ARM::LSRr:
7882   case ARM::LSLr:
7883   case ARM::RORr: {
7884     ARM_AM::ShiftOpc ShiftTy;
7885     switch(Inst.getOpcode()) {
7886     default: llvm_unreachable("unexpected opcode!");
7887     case ARM::ASRr: ShiftTy = ARM_AM::asr; break;
7888     case ARM::LSRr: ShiftTy = ARM_AM::lsr; break;
7889     case ARM::LSLr: ShiftTy = ARM_AM::lsl; break;
7890     case ARM::RORr: ShiftTy = ARM_AM::ror; break;
7891     }
7892     unsigned Shifter = ARM_AM::getSORegOpc(ShiftTy, 0);
7893     MCInst TmpInst;
7894     TmpInst.setOpcode(ARM::MOVsr);
7895     TmpInst.addOperand(Inst.getOperand(0)); // Rd
7896     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7897     TmpInst.addOperand(Inst.getOperand(2)); // Rm
7898     TmpInst.addOperand(MCOperand::CreateImm(Shifter)); // Shift value and ty
7899     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7900     TmpInst.addOperand(Inst.getOperand(4));
7901     TmpInst.addOperand(Inst.getOperand(5)); // cc_out
7902     Inst = TmpInst;
7903     return true;
7904   }
7905   case ARM::ASRi:
7906   case ARM::LSRi:
7907   case ARM::LSLi:
7908   case ARM::RORi: {
7909     ARM_AM::ShiftOpc ShiftTy;
7910     switch(Inst.getOpcode()) {
7911     default: llvm_unreachable("unexpected opcode!");
7912     case ARM::ASRi: ShiftTy = ARM_AM::asr; break;
7913     case ARM::LSRi: ShiftTy = ARM_AM::lsr; break;
7914     case ARM::LSLi: ShiftTy = ARM_AM::lsl; break;
7915     case ARM::RORi: ShiftTy = ARM_AM::ror; break;
7916     }
7917     // A shift by zero is a plain MOVr, not a MOVsi.
7918     unsigned Amt = Inst.getOperand(2).getImm();
7919     unsigned Opc = Amt == 0 ? ARM::MOVr : ARM::MOVsi;
7920     // A shift by 32 should be encoded as 0 when permitted
7921     if (Amt == 32 && (ShiftTy == ARM_AM::lsr || ShiftTy == ARM_AM::asr))
7922       Amt = 0;
7923     unsigned Shifter = ARM_AM::getSORegOpc(ShiftTy, Amt);
7924     MCInst TmpInst;
7925     TmpInst.setOpcode(Opc);
7926     TmpInst.addOperand(Inst.getOperand(0)); // Rd
7927     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7928     if (Opc == ARM::MOVsi)
7929       TmpInst.addOperand(MCOperand::CreateImm(Shifter)); // Shift value and ty
7930     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7931     TmpInst.addOperand(Inst.getOperand(4));
7932     TmpInst.addOperand(Inst.getOperand(5)); // cc_out
7933     Inst = TmpInst;
7934     return true;
7935   }
7936   case ARM::RRXi: {
7937     unsigned Shifter = ARM_AM::getSORegOpc(ARM_AM::rrx, 0);
7938     MCInst TmpInst;
7939     TmpInst.setOpcode(ARM::MOVsi);
7940     TmpInst.addOperand(Inst.getOperand(0)); // Rd
7941     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7942     TmpInst.addOperand(MCOperand::CreateImm(Shifter)); // Shift value and ty
7943     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
7944     TmpInst.addOperand(Inst.getOperand(3));
7945     TmpInst.addOperand(Inst.getOperand(4)); // cc_out
7946     Inst = TmpInst;
7947     return true;
7948   }
7949   case ARM::t2LDMIA_UPD: {
7950     // If this is a load of a single register, then we should use
7951     // a post-indexed LDR instruction instead, per the ARM ARM.
7952     if (Inst.getNumOperands() != 5)
7953       return false;
7954     MCInst TmpInst;
7955     TmpInst.setOpcode(ARM::t2LDR_POST);
7956     TmpInst.addOperand(Inst.getOperand(4)); // Rt
7957     TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
7958     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7959     TmpInst.addOperand(MCOperand::CreateImm(4));
7960     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
7961     TmpInst.addOperand(Inst.getOperand(3));
7962     Inst = TmpInst;
7963     return true;
7964   }
7965   case ARM::t2STMDB_UPD: {
7966     // If this is a store of a single register, then we should use
7967     // a pre-indexed STR instruction instead, per the ARM ARM.
7968     if (Inst.getNumOperands() != 5)
7969       return false;
7970     MCInst TmpInst;
7971     TmpInst.setOpcode(ARM::t2STR_PRE);
7972     TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
7973     TmpInst.addOperand(Inst.getOperand(4)); // Rt
7974     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7975     TmpInst.addOperand(MCOperand::CreateImm(-4));
7976     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
7977     TmpInst.addOperand(Inst.getOperand(3));
7978     Inst = TmpInst;
7979     return true;
7980   }
7981   case ARM::LDMIA_UPD:
7982     // If this is a load of a single register via a 'pop', then we should use
7983     // a post-indexed LDR instruction instead, per the ARM ARM.
7984     if (static_cast<ARMOperand &>(*Operands[0]).getToken() == "pop" &&
7985         Inst.getNumOperands() == 5) {
7986       MCInst TmpInst;
7987       TmpInst.setOpcode(ARM::LDR_POST_IMM);
7988       TmpInst.addOperand(Inst.getOperand(4)); // Rt
7989       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
7990       TmpInst.addOperand(Inst.getOperand(1)); // Rn
7991       TmpInst.addOperand(MCOperand::CreateReg(0));  // am2offset
7992       TmpInst.addOperand(MCOperand::CreateImm(4));
7993       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
7994       TmpInst.addOperand(Inst.getOperand(3));
7995       Inst = TmpInst;
7996       return true;
7997     }
7998     break;
7999   case ARM::STMDB_UPD:
8000     // If this is a store of a single register via a 'push', then we should use
8001     // a pre-indexed STR instruction instead, per the ARM ARM.
8002     if (static_cast<ARMOperand &>(*Operands[0]).getToken() == "push" &&
8003         Inst.getNumOperands() == 5) {
8004       MCInst TmpInst;
8005       TmpInst.setOpcode(ARM::STR_PRE_IMM);
8006       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8007       TmpInst.addOperand(Inst.getOperand(4)); // Rt
8008       TmpInst.addOperand(Inst.getOperand(1)); // addrmode_imm12
8009       TmpInst.addOperand(MCOperand::CreateImm(-4));
8010       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8011       TmpInst.addOperand(Inst.getOperand(3));
8012       Inst = TmpInst;
8013     }
8014     break;
8015   case ARM::t2ADDri12:
8016     // If the immediate fits for encoding T3 (t2ADDri) and the generic "add"
8017     // mnemonic was used (not "addw"), encoding T3 is preferred.
8018     if (static_cast<ARMOperand &>(*Operands[0]).getToken() != "add" ||
8019         ARM_AM::getT2SOImmVal(Inst.getOperand(2).getImm()) == -1)
8020       break;
8021     Inst.setOpcode(ARM::t2ADDri);
8022     Inst.addOperand(MCOperand::CreateReg(0)); // cc_out
8023     break;
8024   case ARM::t2SUBri12:
8025     // If the immediate fits for encoding T3 (t2SUBri) and the generic "sub"
8026     // mnemonic was used (not "subw"), encoding T3 is preferred.
8027     if (static_cast<ARMOperand &>(*Operands[0]).getToken() != "sub" ||
8028         ARM_AM::getT2SOImmVal(Inst.getOperand(2).getImm()) == -1)
8029       break;
8030     Inst.setOpcode(ARM::t2SUBri);
8031     Inst.addOperand(MCOperand::CreateReg(0)); // cc_out
8032     break;
8033   case ARM::tADDi8:
8034     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
8035     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
8036     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
8037     // to encoding T1 if <Rd> is omitted."
8038     if ((unsigned)Inst.getOperand(3).getImm() < 8 && Operands.size() == 6) {
8039       Inst.setOpcode(ARM::tADDi3);
8040       return true;
8041     }
8042     break;
8043   case ARM::tSUBi8:
8044     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
8045     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
8046     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
8047     // to encoding T1 if <Rd> is omitted."
8048     if ((unsigned)Inst.getOperand(3).getImm() < 8 && Operands.size() == 6) {
8049       Inst.setOpcode(ARM::tSUBi3);
8050       return true;
8051     }
8052     break;
8053   case ARM::t2ADDri:
8054   case ARM::t2SUBri: {
8055     // If the destination and first source operand are the same, and
8056     // the flags are compatible with the current IT status, use encoding T2
8057     // instead of T3. For compatibility with the system 'as'. Make sure the
8058     // wide encoding wasn't explicit.
8059     if (Inst.getOperand(0).getReg() != Inst.getOperand(1).getReg() ||
8060         !isARMLowRegister(Inst.getOperand(0).getReg()) ||
8061         (unsigned)Inst.getOperand(2).getImm() > 255 ||
8062         ((!inITBlock() && Inst.getOperand(5).getReg() != ARM::CPSR) ||
8063          (inITBlock() && Inst.getOperand(5).getReg() != 0)) ||
8064         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
8065          static_cast<ARMOperand &>(*Operands[3]).getToken() == ".w"))
8066       break;
8067     MCInst TmpInst;
8068     TmpInst.setOpcode(Inst.getOpcode() == ARM::t2ADDri ?
8069                       ARM::tADDi8 : ARM::tSUBi8);
8070     TmpInst.addOperand(Inst.getOperand(0));
8071     TmpInst.addOperand(Inst.getOperand(5));
8072     TmpInst.addOperand(Inst.getOperand(0));
8073     TmpInst.addOperand(Inst.getOperand(2));
8074     TmpInst.addOperand(Inst.getOperand(3));
8075     TmpInst.addOperand(Inst.getOperand(4));
8076     Inst = TmpInst;
8077     return true;
8078   }
8079   case ARM::t2ADDrr: {
8080     // If the destination and first source operand are the same, and
8081     // there's no setting of the flags, use encoding T2 instead of T3.
8082     // Note that this is only for ADD, not SUB. This mirrors the system
8083     // 'as' behaviour. Make sure the wide encoding wasn't explicit.
8084     if (Inst.getOperand(0).getReg() != Inst.getOperand(1).getReg() ||
8085         Inst.getOperand(5).getReg() != 0 ||
8086         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
8087          static_cast<ARMOperand &>(*Operands[3]).getToken() == ".w"))
8088       break;
8089     MCInst TmpInst;
8090     TmpInst.setOpcode(ARM::tADDhirr);
8091     TmpInst.addOperand(Inst.getOperand(0));
8092     TmpInst.addOperand(Inst.getOperand(0));
8093     TmpInst.addOperand(Inst.getOperand(2));
8094     TmpInst.addOperand(Inst.getOperand(3));
8095     TmpInst.addOperand(Inst.getOperand(4));
8096     Inst = TmpInst;
8097     return true;
8098   }
8099   case ARM::tADDrSP: {
8100     // If the non-SP source operand and the destination operand are not the
8101     // same, we need to use the 32-bit encoding if it's available.
8102     if (Inst.getOperand(0).getReg() != Inst.getOperand(2).getReg()) {
8103       Inst.setOpcode(ARM::t2ADDrr);
8104       Inst.addOperand(MCOperand::CreateReg(0)); // cc_out
8105       return true;
8106     }
8107     break;
8108   }
8109   case ARM::tB:
8110     // A Thumb conditional branch outside of an IT block is a tBcc.
8111     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock()) {
8112       Inst.setOpcode(ARM::tBcc);
8113       return true;
8114     }
8115     break;
8116   case ARM::t2B:
8117     // A Thumb2 conditional branch outside of an IT block is a t2Bcc.
8118     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock()){
8119       Inst.setOpcode(ARM::t2Bcc);
8120       return true;
8121     }
8122     break;
8123   case ARM::t2Bcc:
8124     // If the conditional is AL or we're in an IT block, we really want t2B.
8125     if (Inst.getOperand(1).getImm() == ARMCC::AL || inITBlock()) {
8126       Inst.setOpcode(ARM::t2B);
8127       return true;
8128     }
8129     break;
8130   case ARM::tBcc:
8131     // If the conditional is AL, we really want tB.
8132     if (Inst.getOperand(1).getImm() == ARMCC::AL) {
8133       Inst.setOpcode(ARM::tB);
8134       return true;
8135     }
8136     break;
8137   case ARM::tLDMIA: {
8138     // If the register list contains any high registers, or if the writeback
8139     // doesn't match what tLDMIA can do, we need to use the 32-bit encoding
8140     // instead if we're in Thumb2. Otherwise, this should have generated
8141     // an error in validateInstruction().
8142     unsigned Rn = Inst.getOperand(0).getReg();
8143     bool hasWritebackToken =
8144         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
8145          static_cast<ARMOperand &>(*Operands[3]).getToken() == "!");
8146     bool listContainsBase;
8147     if (checkLowRegisterList(Inst, 3, Rn, 0, listContainsBase) ||
8148         (!listContainsBase && !hasWritebackToken) ||
8149         (listContainsBase && hasWritebackToken)) {
8150       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
8151       assert (isThumbTwo());
8152       Inst.setOpcode(hasWritebackToken ? ARM::t2LDMIA_UPD : ARM::t2LDMIA);
8153       // If we're switching to the updating version, we need to insert
8154       // the writeback tied operand.
8155       if (hasWritebackToken)
8156         Inst.insert(Inst.begin(),
8157                     MCOperand::CreateReg(Inst.getOperand(0).getReg()));
8158       return true;
8159     }
8160     break;
8161   }
8162   case ARM::tSTMIA_UPD: {
8163     // If the register list contains any high registers, we need to use
8164     // the 32-bit encoding instead if we're in Thumb2. Otherwise, this
8165     // should have generated an error in validateInstruction().
8166     unsigned Rn = Inst.getOperand(0).getReg();
8167     bool listContainsBase;
8168     if (checkLowRegisterList(Inst, 4, Rn, 0, listContainsBase)) {
8169       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
8170       assert (isThumbTwo());
8171       Inst.setOpcode(ARM::t2STMIA_UPD);
8172       return true;
8173     }
8174     break;
8175   }
8176   case ARM::tPOP: {
8177     bool listContainsBase;
8178     // If the register list contains any high registers, we need to use
8179     // the 32-bit encoding instead if we're in Thumb2. Otherwise, this
8180     // should have generated an error in validateInstruction().
8181     if (!checkLowRegisterList(Inst, 2, 0, ARM::PC, listContainsBase))
8182       return false;
8183     assert (isThumbTwo());
8184     Inst.setOpcode(ARM::t2LDMIA_UPD);
8185     // Add the base register and writeback operands.
8186     Inst.insert(Inst.begin(), MCOperand::CreateReg(ARM::SP));
8187     Inst.insert(Inst.begin(), MCOperand::CreateReg(ARM::SP));
8188     return true;
8189   }
8190   case ARM::tPUSH: {
8191     bool listContainsBase;
8192     if (!checkLowRegisterList(Inst, 2, 0, ARM::LR, listContainsBase))
8193       return false;
8194     assert (isThumbTwo());
8195     Inst.setOpcode(ARM::t2STMDB_UPD);
8196     // Add the base register and writeback operands.
8197     Inst.insert(Inst.begin(), MCOperand::CreateReg(ARM::SP));
8198     Inst.insert(Inst.begin(), MCOperand::CreateReg(ARM::SP));
8199     return true;
8200   }
8201   case ARM::t2MOVi: {
8202     // If we can use the 16-bit encoding and the user didn't explicitly
8203     // request the 32-bit variant, transform it here.
8204     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8205         (unsigned)Inst.getOperand(1).getImm() <= 255 &&
8206         ((!inITBlock() && Inst.getOperand(2).getImm() == ARMCC::AL &&
8207           Inst.getOperand(4).getReg() == ARM::CPSR) ||
8208          (inITBlock() && Inst.getOperand(4).getReg() == 0)) &&
8209         (!static_cast<ARMOperand &>(*Operands[2]).isToken() ||
8210          static_cast<ARMOperand &>(*Operands[2]).getToken() != ".w")) {
8211       // The operands aren't in the same order for tMOVi8...
8212       MCInst TmpInst;
8213       TmpInst.setOpcode(ARM::tMOVi8);
8214       TmpInst.addOperand(Inst.getOperand(0));
8215       TmpInst.addOperand(Inst.getOperand(4));
8216       TmpInst.addOperand(Inst.getOperand(1));
8217       TmpInst.addOperand(Inst.getOperand(2));
8218       TmpInst.addOperand(Inst.getOperand(3));
8219       Inst = TmpInst;
8220       return true;
8221     }
8222     break;
8223   }
8224   case ARM::t2MOVr: {
8225     // If we can use the 16-bit encoding and the user didn't explicitly
8226     // request the 32-bit variant, transform it here.
8227     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8228         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8229         Inst.getOperand(2).getImm() == ARMCC::AL &&
8230         Inst.getOperand(4).getReg() == ARM::CPSR &&
8231         (!static_cast<ARMOperand &>(*Operands[2]).isToken() ||
8232          static_cast<ARMOperand &>(*Operands[2]).getToken() != ".w")) {
8233       // The operands aren't the same for tMOV[S]r... (no cc_out)
8234       MCInst TmpInst;
8235       TmpInst.setOpcode(Inst.getOperand(4).getReg() ? ARM::tMOVSr : ARM::tMOVr);
8236       TmpInst.addOperand(Inst.getOperand(0));
8237       TmpInst.addOperand(Inst.getOperand(1));
8238       TmpInst.addOperand(Inst.getOperand(2));
8239       TmpInst.addOperand(Inst.getOperand(3));
8240       Inst = TmpInst;
8241       return true;
8242     }
8243     break;
8244   }
8245   case ARM::t2SXTH:
8246   case ARM::t2SXTB:
8247   case ARM::t2UXTH:
8248   case ARM::t2UXTB: {
8249     // If we can use the 16-bit encoding and the user didn't explicitly
8250     // request the 32-bit variant, transform it here.
8251     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8252         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8253         Inst.getOperand(2).getImm() == 0 &&
8254         (!static_cast<ARMOperand &>(*Operands[2]).isToken() ||
8255          static_cast<ARMOperand &>(*Operands[2]).getToken() != ".w")) {
8256       unsigned NewOpc;
8257       switch (Inst.getOpcode()) {
8258       default: llvm_unreachable("Illegal opcode!");
8259       case ARM::t2SXTH: NewOpc = ARM::tSXTH; break;
8260       case ARM::t2SXTB: NewOpc = ARM::tSXTB; break;
8261       case ARM::t2UXTH: NewOpc = ARM::tUXTH; break;
8262       case ARM::t2UXTB: NewOpc = ARM::tUXTB; break;
8263       }
8264       // The operands aren't the same for thumb1 (no rotate operand).
8265       MCInst TmpInst;
8266       TmpInst.setOpcode(NewOpc);
8267       TmpInst.addOperand(Inst.getOperand(0));
8268       TmpInst.addOperand(Inst.getOperand(1));
8269       TmpInst.addOperand(Inst.getOperand(3));
8270       TmpInst.addOperand(Inst.getOperand(4));
8271       Inst = TmpInst;
8272       return true;
8273     }
8274     break;
8275   }
8276   case ARM::MOVsi: {
8277     ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(Inst.getOperand(2).getImm());
8278     // rrx shifts and asr/lsr of #32 is encoded as 0
8279     if (SOpc == ARM_AM::rrx || SOpc == ARM_AM::asr || SOpc == ARM_AM::lsr) 
8280       return false;
8281     if (ARM_AM::getSORegOffset(Inst.getOperand(2).getImm()) == 0) {
8282       // Shifting by zero is accepted as a vanilla 'MOVr'
8283       MCInst TmpInst;
8284       TmpInst.setOpcode(ARM::MOVr);
8285       TmpInst.addOperand(Inst.getOperand(0));
8286       TmpInst.addOperand(Inst.getOperand(1));
8287       TmpInst.addOperand(Inst.getOperand(3));
8288       TmpInst.addOperand(Inst.getOperand(4));
8289       TmpInst.addOperand(Inst.getOperand(5));
8290       Inst = TmpInst;
8291       return true;
8292     }
8293     return false;
8294   }
8295   case ARM::ANDrsi:
8296   case ARM::ORRrsi:
8297   case ARM::EORrsi:
8298   case ARM::BICrsi:
8299   case ARM::SUBrsi:
8300   case ARM::ADDrsi: {
8301     unsigned newOpc;
8302     ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(Inst.getOperand(3).getImm());
8303     if (SOpc == ARM_AM::rrx) return false;
8304     switch (Inst.getOpcode()) {
8305     default: llvm_unreachable("unexpected opcode!");
8306     case ARM::ANDrsi: newOpc = ARM::ANDrr; break;
8307     case ARM::ORRrsi: newOpc = ARM::ORRrr; break;
8308     case ARM::EORrsi: newOpc = ARM::EORrr; break;
8309     case ARM::BICrsi: newOpc = ARM::BICrr; break;
8310     case ARM::SUBrsi: newOpc = ARM::SUBrr; break;
8311     case ARM::ADDrsi: newOpc = ARM::ADDrr; break;
8312     }
8313     // If the shift is by zero, use the non-shifted instruction definition.
8314     // The exception is for right shifts, where 0 == 32
8315     if (ARM_AM::getSORegOffset(Inst.getOperand(3).getImm()) == 0 &&
8316         !(SOpc == ARM_AM::lsr || SOpc == ARM_AM::asr)) {
8317       MCInst TmpInst;
8318       TmpInst.setOpcode(newOpc);
8319       TmpInst.addOperand(Inst.getOperand(0));
8320       TmpInst.addOperand(Inst.getOperand(1));
8321       TmpInst.addOperand(Inst.getOperand(2));
8322       TmpInst.addOperand(Inst.getOperand(4));
8323       TmpInst.addOperand(Inst.getOperand(5));
8324       TmpInst.addOperand(Inst.getOperand(6));
8325       Inst = TmpInst;
8326       return true;
8327     }
8328     return false;
8329   }
8330   case ARM::ITasm:
8331   case ARM::t2IT: {
8332     // The mask bits for all but the first condition are represented as
8333     // the low bit of the condition code value implies 't'. We currently
8334     // always have 1 implies 't', so XOR toggle the bits if the low bit
8335     // of the condition code is zero. 
8336     MCOperand &MO = Inst.getOperand(1);
8337     unsigned Mask = MO.getImm();
8338     unsigned OrigMask = Mask;
8339     unsigned TZ = countTrailingZeros(Mask);
8340     if ((Inst.getOperand(0).getImm() & 1) == 0) {
8341       assert(Mask && TZ <= 3 && "illegal IT mask value!");
8342       Mask ^= (0xE << TZ) & 0xF;
8343     }
8344     MO.setImm(Mask);
8345
8346     // Set up the IT block state according to the IT instruction we just
8347     // matched.
8348     assert(!inITBlock() && "nested IT blocks?!");
8349     ITState.Cond = ARMCC::CondCodes(Inst.getOperand(0).getImm());
8350     ITState.Mask = OrigMask; // Use the original mask, not the updated one.
8351     ITState.CurPosition = 0;
8352     ITState.FirstCond = true;
8353     break;
8354   }
8355   case ARM::t2LSLrr:
8356   case ARM::t2LSRrr:
8357   case ARM::t2ASRrr:
8358   case ARM::t2SBCrr:
8359   case ARM::t2RORrr:
8360   case ARM::t2BICrr:
8361   {
8362     // Assemblers should use the narrow encodings of these instructions when permissible.
8363     if ((isARMLowRegister(Inst.getOperand(1).getReg()) &&
8364          isARMLowRegister(Inst.getOperand(2).getReg())) &&
8365         Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() &&
8366         ((!inITBlock() && Inst.getOperand(5).getReg() == ARM::CPSR) ||
8367          (inITBlock() && Inst.getOperand(5).getReg() != ARM::CPSR)) &&
8368         (!static_cast<ARMOperand &>(*Operands[3]).isToken() ||
8369          !static_cast<ARMOperand &>(*Operands[3]).getToken().equals_lower(
8370              ".w"))) {
8371       unsigned NewOpc;
8372       switch (Inst.getOpcode()) {
8373         default: llvm_unreachable("unexpected opcode");
8374         case ARM::t2LSLrr: NewOpc = ARM::tLSLrr; break;
8375         case ARM::t2LSRrr: NewOpc = ARM::tLSRrr; break;
8376         case ARM::t2ASRrr: NewOpc = ARM::tASRrr; break;
8377         case ARM::t2SBCrr: NewOpc = ARM::tSBC; break;
8378         case ARM::t2RORrr: NewOpc = ARM::tROR; break;
8379         case ARM::t2BICrr: NewOpc = ARM::tBIC; break;
8380       }
8381       MCInst TmpInst;
8382       TmpInst.setOpcode(NewOpc);
8383       TmpInst.addOperand(Inst.getOperand(0));
8384       TmpInst.addOperand(Inst.getOperand(5));
8385       TmpInst.addOperand(Inst.getOperand(1));
8386       TmpInst.addOperand(Inst.getOperand(2));
8387       TmpInst.addOperand(Inst.getOperand(3));
8388       TmpInst.addOperand(Inst.getOperand(4));
8389       Inst = TmpInst;
8390       return true;
8391     }
8392     return false;
8393   }
8394   case ARM::t2ANDrr:
8395   case ARM::t2EORrr:
8396   case ARM::t2ADCrr:
8397   case ARM::t2ORRrr:
8398   {
8399     // Assemblers should use the narrow encodings of these instructions when permissible.
8400     // These instructions are special in that they are commutable, so shorter encodings
8401     // are available more often.
8402     if ((isARMLowRegister(Inst.getOperand(1).getReg()) &&
8403          isARMLowRegister(Inst.getOperand(2).getReg())) &&
8404         (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() ||
8405          Inst.getOperand(0).getReg() == Inst.getOperand(2).getReg()) &&
8406         ((!inITBlock() && Inst.getOperand(5).getReg() == ARM::CPSR) ||
8407          (inITBlock() && Inst.getOperand(5).getReg() != ARM::CPSR)) &&
8408         (!static_cast<ARMOperand &>(*Operands[3]).isToken() ||
8409          !static_cast<ARMOperand &>(*Operands[3]).getToken().equals_lower(
8410              ".w"))) {
8411       unsigned NewOpc;
8412       switch (Inst.getOpcode()) {
8413         default: llvm_unreachable("unexpected opcode");
8414         case ARM::t2ADCrr: NewOpc = ARM::tADC; break;
8415         case ARM::t2ANDrr: NewOpc = ARM::tAND; break;
8416         case ARM::t2EORrr: NewOpc = ARM::tEOR; break;
8417         case ARM::t2ORRrr: NewOpc = ARM::tORR; break;
8418       }
8419       MCInst TmpInst;
8420       TmpInst.setOpcode(NewOpc);
8421       TmpInst.addOperand(Inst.getOperand(0));
8422       TmpInst.addOperand(Inst.getOperand(5));
8423       if (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg()) {
8424         TmpInst.addOperand(Inst.getOperand(1));
8425         TmpInst.addOperand(Inst.getOperand(2));
8426       } else {
8427         TmpInst.addOperand(Inst.getOperand(2));
8428         TmpInst.addOperand(Inst.getOperand(1));
8429       }
8430       TmpInst.addOperand(Inst.getOperand(3));
8431       TmpInst.addOperand(Inst.getOperand(4));
8432       Inst = TmpInst;
8433       return true;
8434     }
8435     return false;
8436   }
8437   }
8438   return false;
8439 }
8440
8441 unsigned ARMAsmParser::checkTargetMatchPredicate(MCInst &Inst) {
8442   // 16-bit thumb arithmetic instructions either require or preclude the 'S'
8443   // suffix depending on whether they're in an IT block or not.
8444   unsigned Opc = Inst.getOpcode();
8445   const MCInstrDesc &MCID = MII.get(Opc);
8446   if (MCID.TSFlags & ARMII::ThumbArithFlagSetting) {
8447     assert(MCID.hasOptionalDef() &&
8448            "optionally flag setting instruction missing optional def operand");
8449     assert(MCID.NumOperands == Inst.getNumOperands() &&
8450            "operand count mismatch!");
8451     // Find the optional-def operand (cc_out).
8452     unsigned OpNo;
8453     for (OpNo = 0;
8454          !MCID.OpInfo[OpNo].isOptionalDef() && OpNo < MCID.NumOperands;
8455          ++OpNo)
8456       ;
8457     // If we're parsing Thumb1, reject it completely.
8458     if (isThumbOne() && Inst.getOperand(OpNo).getReg() != ARM::CPSR)
8459       return Match_MnemonicFail;
8460     // If we're parsing Thumb2, which form is legal depends on whether we're
8461     // in an IT block.
8462     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() != ARM::CPSR &&
8463         !inITBlock())
8464       return Match_RequiresITBlock;
8465     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() == ARM::CPSR &&
8466         inITBlock())
8467       return Match_RequiresNotITBlock;
8468   }
8469   // Some high-register supporting Thumb1 encodings only allow both registers
8470   // to be from r0-r7 when in Thumb2.
8471   else if (Opc == ARM::tADDhirr && isThumbOne() && !hasV6MOps() &&
8472            isARMLowRegister(Inst.getOperand(1).getReg()) &&
8473            isARMLowRegister(Inst.getOperand(2).getReg()))
8474     return Match_RequiresThumb2;
8475   // Others only require ARMv6 or later.
8476   else if (Opc == ARM::tMOVr && isThumbOne() && !hasV6Ops() &&
8477            isARMLowRegister(Inst.getOperand(0).getReg()) &&
8478            isARMLowRegister(Inst.getOperand(1).getReg()))
8479     return Match_RequiresV6;
8480   return Match_Success;
8481 }
8482
8483 namespace llvm {
8484 template <> inline bool IsCPSRDead<MCInst>(MCInst *Instr) {
8485   return true; // In an assembly source, no need to second-guess
8486 }
8487 }
8488
8489 static const char *getSubtargetFeatureName(uint64_t Val);
8490 bool ARMAsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
8491                                            OperandVector &Operands,
8492                                            MCStreamer &Out, uint64_t &ErrorInfo,
8493                                            bool MatchingInlineAsm) {
8494   MCInst Inst;
8495   unsigned MatchResult;
8496
8497   MatchResult = MatchInstructionImpl(Operands, Inst, ErrorInfo,
8498                                      MatchingInlineAsm);
8499   switch (MatchResult) {
8500   default: break;
8501   case Match_Success:
8502     // Context sensitive operand constraints aren't handled by the matcher,
8503     // so check them here.
8504     if (validateInstruction(Inst, Operands)) {
8505       // Still progress the IT block, otherwise one wrong condition causes
8506       // nasty cascading errors.
8507       forwardITPosition();
8508       return true;
8509     }
8510
8511     { // processInstruction() updates inITBlock state, we need to save it away
8512       bool wasInITBlock = inITBlock();
8513
8514       // Some instructions need post-processing to, for example, tweak which
8515       // encoding is selected. Loop on it while changes happen so the
8516       // individual transformations can chain off each other. E.g.,
8517       // tPOP(r8)->t2LDMIA_UPD(sp,r8)->t2STR_POST(sp,r8)
8518       while (processInstruction(Inst, Operands, Out))
8519         ;
8520
8521       // Only after the instruction is fully processed, we can validate it
8522       if (wasInITBlock && hasV8Ops() && isThumb() &&
8523           !isV8EligibleForIT(&Inst)) {
8524         Warning(IDLoc, "deprecated instruction in IT block");
8525       }
8526     }
8527
8528     // Only move forward at the very end so that everything in validate
8529     // and process gets a consistent answer about whether we're in an IT
8530     // block.
8531     forwardITPosition();
8532
8533     // ITasm is an ARM mode pseudo-instruction that just sets the ITblock and
8534     // doesn't actually encode.
8535     if (Inst.getOpcode() == ARM::ITasm)
8536       return false;
8537
8538     Inst.setLoc(IDLoc);
8539     Out.EmitInstruction(Inst, STI);
8540     return false;
8541   case Match_MissingFeature: {
8542     assert(ErrorInfo && "Unknown missing feature!");
8543     // Special case the error message for the very common case where only
8544     // a single subtarget feature is missing (Thumb vs. ARM, e.g.).
8545     std::string Msg = "instruction requires:";
8546     uint64_t Mask = 1;
8547     for (unsigned i = 0; i < (sizeof(ErrorInfo)*8-1); ++i) {
8548       if (ErrorInfo & Mask) {
8549         Msg += " ";
8550         Msg += getSubtargetFeatureName(ErrorInfo & Mask);
8551       }
8552       Mask <<= 1;
8553     }
8554     return Error(IDLoc, Msg);
8555   }
8556   case Match_InvalidOperand: {
8557     SMLoc ErrorLoc = IDLoc;
8558     if (ErrorInfo != ~0ULL) {
8559       if (ErrorInfo >= Operands.size())
8560         return Error(IDLoc, "too few operands for instruction");
8561
8562       ErrorLoc = ((ARMOperand &)*Operands[ErrorInfo]).getStartLoc();
8563       if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
8564     }
8565
8566     return Error(ErrorLoc, "invalid operand for instruction");
8567   }
8568   case Match_MnemonicFail:
8569     return Error(IDLoc, "invalid instruction",
8570                  ((ARMOperand &)*Operands[0]).getLocRange());
8571   case Match_RequiresNotITBlock:
8572     return Error(IDLoc, "flag setting instruction only valid outside IT block");
8573   case Match_RequiresITBlock:
8574     return Error(IDLoc, "instruction only valid inside IT block");
8575   case Match_RequiresV6:
8576     return Error(IDLoc, "instruction variant requires ARMv6 or later");
8577   case Match_RequiresThumb2:
8578     return Error(IDLoc, "instruction variant requires Thumb2");
8579   case Match_ImmRange0_15: {
8580     SMLoc ErrorLoc = ((ARMOperand &)*Operands[ErrorInfo]).getStartLoc();
8581     if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
8582     return Error(ErrorLoc, "immediate operand must be in the range [0,15]");
8583   }
8584   case Match_ImmRange0_239: {
8585     SMLoc ErrorLoc = ((ARMOperand &)*Operands[ErrorInfo]).getStartLoc();
8586     if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
8587     return Error(ErrorLoc, "immediate operand must be in the range [0,239]");
8588   }
8589   case Match_AlignedMemoryRequiresNone:
8590   case Match_DupAlignedMemoryRequiresNone:
8591   case Match_AlignedMemoryRequires16:
8592   case Match_DupAlignedMemoryRequires16:
8593   case Match_AlignedMemoryRequires32:
8594   case Match_DupAlignedMemoryRequires32:
8595   case Match_AlignedMemoryRequires64:
8596   case Match_DupAlignedMemoryRequires64:
8597   case Match_AlignedMemoryRequires64or128:
8598   case Match_DupAlignedMemoryRequires64or128:
8599   case Match_AlignedMemoryRequires64or128or256:
8600   {
8601     SMLoc ErrorLoc = ((ARMOperand &)*Operands[ErrorInfo]).getAlignmentLoc();
8602     if (ErrorLoc == SMLoc()) ErrorLoc = IDLoc;
8603     switch (MatchResult) {
8604       default:
8605         llvm_unreachable("Missing Match_Aligned type");
8606       case Match_AlignedMemoryRequiresNone:
8607       case Match_DupAlignedMemoryRequiresNone:
8608         return Error(ErrorLoc, "alignment must be omitted");
8609       case Match_AlignedMemoryRequires16:
8610       case Match_DupAlignedMemoryRequires16:
8611         return Error(ErrorLoc, "alignment must be 16 or omitted");
8612       case Match_AlignedMemoryRequires32:
8613       case Match_DupAlignedMemoryRequires32:
8614         return Error(ErrorLoc, "alignment must be 32 or omitted");
8615       case Match_AlignedMemoryRequires64:
8616       case Match_DupAlignedMemoryRequires64:
8617         return Error(ErrorLoc, "alignment must be 64 or omitted");
8618       case Match_AlignedMemoryRequires64or128:
8619       case Match_DupAlignedMemoryRequires64or128:
8620         return Error(ErrorLoc, "alignment must be 64, 128 or omitted");
8621       case Match_AlignedMemoryRequires64or128or256:
8622         return Error(ErrorLoc, "alignment must be 64, 128, 256 or omitted");
8623     }
8624   }
8625   }
8626
8627   llvm_unreachable("Implement any new match types added!");
8628 }
8629
8630 /// parseDirective parses the arm specific directives
8631 bool ARMAsmParser::ParseDirective(AsmToken DirectiveID) {
8632   const MCObjectFileInfo::Environment Format =
8633     getContext().getObjectFileInfo()->getObjectFileType();
8634   bool IsMachO = Format == MCObjectFileInfo::IsMachO;
8635   bool IsCOFF = Format == MCObjectFileInfo::IsCOFF;
8636
8637   StringRef IDVal = DirectiveID.getIdentifier();
8638   if (IDVal == ".word")
8639     return parseLiteralValues(4, DirectiveID.getLoc());
8640   else if (IDVal == ".short" || IDVal == ".hword")
8641     return parseLiteralValues(2, DirectiveID.getLoc());
8642   else if (IDVal == ".thumb")
8643     return parseDirectiveThumb(DirectiveID.getLoc());
8644   else if (IDVal == ".arm")
8645     return parseDirectiveARM(DirectiveID.getLoc());
8646   else if (IDVal == ".thumb_func")
8647     return parseDirectiveThumbFunc(DirectiveID.getLoc());
8648   else if (IDVal == ".code")
8649     return parseDirectiveCode(DirectiveID.getLoc());
8650   else if (IDVal == ".syntax")
8651     return parseDirectiveSyntax(DirectiveID.getLoc());
8652   else if (IDVal == ".unreq")
8653     return parseDirectiveUnreq(DirectiveID.getLoc());
8654   else if (IDVal == ".fnend")
8655     return parseDirectiveFnEnd(DirectiveID.getLoc());
8656   else if (IDVal == ".cantunwind")
8657     return parseDirectiveCantUnwind(DirectiveID.getLoc());
8658   else if (IDVal == ".personality")
8659     return parseDirectivePersonality(DirectiveID.getLoc());
8660   else if (IDVal == ".handlerdata")
8661     return parseDirectiveHandlerData(DirectiveID.getLoc());
8662   else if (IDVal == ".setfp")
8663     return parseDirectiveSetFP(DirectiveID.getLoc());
8664   else if (IDVal == ".pad")
8665     return parseDirectivePad(DirectiveID.getLoc());
8666   else if (IDVal == ".save")
8667     return parseDirectiveRegSave(DirectiveID.getLoc(), false);
8668   else if (IDVal == ".vsave")
8669     return parseDirectiveRegSave(DirectiveID.getLoc(), true);
8670   else if (IDVal == ".ltorg" || IDVal == ".pool")
8671     return parseDirectiveLtorg(DirectiveID.getLoc());
8672   else if (IDVal == ".even")
8673     return parseDirectiveEven(DirectiveID.getLoc());
8674   else if (IDVal == ".personalityindex")
8675     return parseDirectivePersonalityIndex(DirectiveID.getLoc());
8676   else if (IDVal == ".unwind_raw")
8677     return parseDirectiveUnwindRaw(DirectiveID.getLoc());
8678   else if (IDVal == ".movsp")
8679     return parseDirectiveMovSP(DirectiveID.getLoc());
8680   else if (IDVal == ".arch_extension")
8681     return parseDirectiveArchExtension(DirectiveID.getLoc());
8682   else if (IDVal == ".align")
8683     return parseDirectiveAlign(DirectiveID.getLoc());
8684   else if (IDVal == ".thumb_set")
8685     return parseDirectiveThumbSet(DirectiveID.getLoc());
8686
8687   if (!IsMachO && !IsCOFF) {
8688     if (IDVal == ".arch")
8689       return parseDirectiveArch(DirectiveID.getLoc());
8690     else if (IDVal == ".cpu")
8691       return parseDirectiveCPU(DirectiveID.getLoc());
8692     else if (IDVal == ".eabi_attribute")
8693       return parseDirectiveEabiAttr(DirectiveID.getLoc());
8694     else if (IDVal == ".fpu")
8695       return parseDirectiveFPU(DirectiveID.getLoc());
8696     else if (IDVal == ".fnstart")
8697       return parseDirectiveFnStart(DirectiveID.getLoc());
8698     else if (IDVal == ".inst")
8699       return parseDirectiveInst(DirectiveID.getLoc());
8700     else if (IDVal == ".inst.n")
8701       return parseDirectiveInst(DirectiveID.getLoc(), 'n');
8702     else if (IDVal == ".inst.w")
8703       return parseDirectiveInst(DirectiveID.getLoc(), 'w');
8704     else if (IDVal == ".object_arch")
8705       return parseDirectiveObjectArch(DirectiveID.getLoc());
8706     else if (IDVal == ".tlsdescseq")
8707       return parseDirectiveTLSDescSeq(DirectiveID.getLoc());
8708   }
8709
8710   return true;
8711 }
8712
8713 /// parseLiteralValues
8714 ///  ::= .hword expression [, expression]*
8715 ///  ::= .short expression [, expression]*
8716 ///  ::= .word expression [, expression]*
8717 bool ARMAsmParser::parseLiteralValues(unsigned Size, SMLoc L) {
8718   MCAsmParser &Parser = getParser();
8719   if (getLexer().isNot(AsmToken::EndOfStatement)) {
8720     for (;;) {
8721       const MCExpr *Value;
8722       if (getParser().parseExpression(Value)) {
8723         Parser.eatToEndOfStatement();
8724         return false;
8725       }
8726
8727       getParser().getStreamer().EmitValue(Value, Size);
8728
8729       if (getLexer().is(AsmToken::EndOfStatement))
8730         break;
8731
8732       // FIXME: Improve diagnostic.
8733       if (getLexer().isNot(AsmToken::Comma)) {
8734         Error(L, "unexpected token in directive");
8735         return false;
8736       }
8737       Parser.Lex();
8738     }
8739   }
8740
8741   Parser.Lex();
8742   return false;
8743 }
8744
8745 /// parseDirectiveThumb
8746 ///  ::= .thumb
8747 bool ARMAsmParser::parseDirectiveThumb(SMLoc L) {
8748   MCAsmParser &Parser = getParser();
8749   if (getLexer().isNot(AsmToken::EndOfStatement)) {
8750     Error(L, "unexpected token in directive");
8751     return false;
8752   }
8753   Parser.Lex();
8754
8755   if (!hasThumb()) {
8756     Error(L, "target does not support Thumb mode");
8757     return false;
8758   }
8759
8760   if (!isThumb())
8761     SwitchMode();
8762
8763   getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
8764   return false;
8765 }
8766
8767 /// parseDirectiveARM
8768 ///  ::= .arm
8769 bool ARMAsmParser::parseDirectiveARM(SMLoc L) {
8770   MCAsmParser &Parser = getParser();
8771   if (getLexer().isNot(AsmToken::EndOfStatement)) {
8772     Error(L, "unexpected token in directive");
8773     return false;
8774   }
8775   Parser.Lex();
8776
8777   if (!hasARM()) {
8778     Error(L, "target does not support ARM mode");
8779     return false;
8780   }
8781
8782   if (isThumb())
8783     SwitchMode();
8784
8785   getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
8786   return false;
8787 }
8788
8789 void ARMAsmParser::onLabelParsed(MCSymbol *Symbol) {
8790   if (NextSymbolIsThumb) {
8791     getParser().getStreamer().EmitThumbFunc(Symbol);
8792     NextSymbolIsThumb = false;
8793   }
8794 }
8795
8796 /// parseDirectiveThumbFunc
8797 ///  ::= .thumbfunc symbol_name
8798 bool ARMAsmParser::parseDirectiveThumbFunc(SMLoc L) {
8799   MCAsmParser &Parser = getParser();
8800   const auto Format = getContext().getObjectFileInfo()->getObjectFileType();
8801   bool IsMachO = Format == MCObjectFileInfo::IsMachO;
8802
8803   // Darwin asm has (optionally) function name after .thumb_func direction
8804   // ELF doesn't
8805   if (IsMachO) {
8806     const AsmToken &Tok = Parser.getTok();
8807     if (Tok.isNot(AsmToken::EndOfStatement)) {
8808       if (Tok.isNot(AsmToken::Identifier) && Tok.isNot(AsmToken::String)) {
8809         Error(L, "unexpected token in .thumb_func directive");
8810         return false;
8811       }
8812
8813       MCSymbol *Func =
8814           getParser().getContext().GetOrCreateSymbol(Tok.getIdentifier());
8815       getParser().getStreamer().EmitThumbFunc(Func);
8816       Parser.Lex(); // Consume the identifier token.
8817       return false;
8818     }
8819   }
8820
8821   if (getLexer().isNot(AsmToken::EndOfStatement)) {
8822     Error(Parser.getTok().getLoc(), "unexpected token in directive");
8823     Parser.eatToEndOfStatement();
8824     return false;
8825   }
8826
8827   NextSymbolIsThumb = true;
8828   return false;
8829 }
8830
8831 /// parseDirectiveSyntax
8832 ///  ::= .syntax unified | divided
8833 bool ARMAsmParser::parseDirectiveSyntax(SMLoc L) {
8834   MCAsmParser &Parser = getParser();
8835   const AsmToken &Tok = Parser.getTok();
8836   if (Tok.isNot(AsmToken::Identifier)) {
8837     Error(L, "unexpected token in .syntax directive");
8838     return false;
8839   }
8840
8841   StringRef Mode = Tok.getString();
8842   if (Mode == "unified" || Mode == "UNIFIED") {
8843     Parser.Lex();
8844   } else if (Mode == "divided" || Mode == "DIVIDED") {
8845     Error(L, "'.syntax divided' arm asssembly not supported");
8846     return false;
8847   } else {
8848     Error(L, "unrecognized syntax mode in .syntax directive");
8849     return false;
8850   }
8851
8852   if (getLexer().isNot(AsmToken::EndOfStatement)) {
8853     Error(Parser.getTok().getLoc(), "unexpected token in directive");
8854     return false;
8855   }
8856   Parser.Lex();
8857
8858   // TODO tell the MC streamer the mode
8859   // getParser().getStreamer().Emit???();
8860   return false;
8861 }
8862
8863 /// parseDirectiveCode
8864 ///  ::= .code 16 | 32
8865 bool ARMAsmParser::parseDirectiveCode(SMLoc L) {
8866   MCAsmParser &Parser = getParser();
8867   const AsmToken &Tok = Parser.getTok();
8868   if (Tok.isNot(AsmToken::Integer)) {
8869     Error(L, "unexpected token in .code directive");
8870     return false;
8871   }
8872   int64_t Val = Parser.getTok().getIntVal();
8873   if (Val != 16 && Val != 32) {
8874     Error(L, "invalid operand to .code directive");
8875     return false;
8876   }
8877   Parser.Lex();
8878
8879   if (getLexer().isNot(AsmToken::EndOfStatement)) {
8880     Error(Parser.getTok().getLoc(), "unexpected token in directive");
8881     return false;
8882   }
8883   Parser.Lex();
8884
8885   if (Val == 16) {
8886     if (!hasThumb()) {
8887       Error(L, "target does not support Thumb mode");
8888       return false;
8889     }
8890
8891     if (!isThumb())
8892       SwitchMode();
8893     getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
8894   } else {
8895     if (!hasARM()) {
8896       Error(L, "target does not support ARM mode");
8897       return false;
8898     }
8899
8900     if (isThumb())
8901       SwitchMode();
8902     getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
8903   }
8904
8905   return false;
8906 }
8907
8908 /// parseDirectiveReq
8909 ///  ::= name .req registername
8910 bool ARMAsmParser::parseDirectiveReq(StringRef Name, SMLoc L) {
8911   MCAsmParser &Parser = getParser();
8912   Parser.Lex(); // Eat the '.req' token.
8913   unsigned Reg;
8914   SMLoc SRegLoc, ERegLoc;
8915   if (ParseRegister(Reg, SRegLoc, ERegLoc)) {
8916     Parser.eatToEndOfStatement();
8917     Error(SRegLoc, "register name expected");
8918     return false;
8919   }
8920
8921   // Shouldn't be anything else.
8922   if (Parser.getTok().isNot(AsmToken::EndOfStatement)) {
8923     Parser.eatToEndOfStatement();
8924     Error(Parser.getTok().getLoc(), "unexpected input in .req directive.");
8925     return false;
8926   }
8927
8928   Parser.Lex(); // Consume the EndOfStatement
8929
8930   if (!RegisterReqs.insert(std::make_pair(Name, Reg)).second) {
8931     Error(SRegLoc, "redefinition of '" + Name + "' does not match original.");
8932     return false;
8933   }
8934
8935   return false;
8936 }
8937
8938 /// parseDirectiveUneq
8939 ///  ::= .unreq registername
8940 bool ARMAsmParser::parseDirectiveUnreq(SMLoc L) {
8941   MCAsmParser &Parser = getParser();
8942   if (Parser.getTok().isNot(AsmToken::Identifier)) {
8943     Parser.eatToEndOfStatement();
8944     Error(L, "unexpected input in .unreq directive.");
8945     return false;
8946   }
8947   RegisterReqs.erase(Parser.getTok().getIdentifier().lower());
8948   Parser.Lex(); // Eat the identifier.
8949   return false;
8950 }
8951
8952 /// parseDirectiveArch
8953 ///  ::= .arch token
8954 bool ARMAsmParser::parseDirectiveArch(SMLoc L) {
8955   StringRef Arch = getParser().parseStringToEndOfStatement().trim();
8956
8957   unsigned ID = StringSwitch<unsigned>(Arch)
8958 #define ARM_ARCH_NAME(NAME, ID, DEFAULT_CPU_NAME, DEFAULT_CPU_ARCH) \
8959     .Case(NAME, ARM::ID)
8960 #define ARM_ARCH_ALIAS(NAME, ID) \
8961     .Case(NAME, ARM::ID)
8962 #include "MCTargetDesc/ARMArchName.def"
8963     .Default(ARM::INVALID_ARCH);
8964
8965   if (ID == ARM::INVALID_ARCH) {
8966     Error(L, "Unknown arch name");
8967     return false;
8968   }
8969
8970   getTargetStreamer().emitArch(ID);
8971   return false;
8972 }
8973
8974 /// parseDirectiveEabiAttr
8975 ///  ::= .eabi_attribute int, int [, "str"]
8976 ///  ::= .eabi_attribute Tag_name, int [, "str"]
8977 bool ARMAsmParser::parseDirectiveEabiAttr(SMLoc L) {
8978   MCAsmParser &Parser = getParser();
8979   int64_t Tag;
8980   SMLoc TagLoc;
8981   TagLoc = Parser.getTok().getLoc();
8982   if (Parser.getTok().is(AsmToken::Identifier)) {
8983     StringRef Name = Parser.getTok().getIdentifier();
8984     Tag = ARMBuildAttrs::AttrTypeFromString(Name);
8985     if (Tag == -1) {
8986       Error(TagLoc, "attribute name not recognised: " + Name);
8987       Parser.eatToEndOfStatement();
8988       return false;
8989     }
8990     Parser.Lex();
8991   } else {
8992     const MCExpr *AttrExpr;
8993
8994     TagLoc = Parser.getTok().getLoc();
8995     if (Parser.parseExpression(AttrExpr)) {
8996       Parser.eatToEndOfStatement();
8997       return false;
8998     }
8999
9000     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(AttrExpr);
9001     if (!CE) {
9002       Error(TagLoc, "expected numeric constant");
9003       Parser.eatToEndOfStatement();
9004       return false;
9005     }
9006
9007     Tag = CE->getValue();
9008   }
9009
9010   if (Parser.getTok().isNot(AsmToken::Comma)) {
9011     Error(Parser.getTok().getLoc(), "comma expected");
9012     Parser.eatToEndOfStatement();
9013     return false;
9014   }
9015   Parser.Lex(); // skip comma
9016
9017   StringRef StringValue = "";
9018   bool IsStringValue = false;
9019
9020   int64_t IntegerValue = 0;
9021   bool IsIntegerValue = false;
9022
9023   if (Tag == ARMBuildAttrs::CPU_raw_name || Tag == ARMBuildAttrs::CPU_name)
9024     IsStringValue = true;
9025   else if (Tag == ARMBuildAttrs::compatibility) {
9026     IsStringValue = true;
9027     IsIntegerValue = true;
9028   } else if (Tag < 32 || Tag % 2 == 0)
9029     IsIntegerValue = true;
9030   else if (Tag % 2 == 1)
9031     IsStringValue = true;
9032   else
9033     llvm_unreachable("invalid tag type");
9034
9035   if (IsIntegerValue) {
9036     const MCExpr *ValueExpr;
9037     SMLoc ValueExprLoc = Parser.getTok().getLoc();
9038     if (Parser.parseExpression(ValueExpr)) {
9039       Parser.eatToEndOfStatement();
9040       return false;
9041     }
9042
9043     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ValueExpr);
9044     if (!CE) {
9045       Error(ValueExprLoc, "expected numeric constant");
9046       Parser.eatToEndOfStatement();
9047       return false;
9048     }
9049
9050     IntegerValue = CE->getValue();
9051   }
9052
9053   if (Tag == ARMBuildAttrs::compatibility) {
9054     if (Parser.getTok().isNot(AsmToken::Comma))
9055       IsStringValue = false;
9056     else
9057       Parser.Lex();
9058   }
9059
9060   if (IsStringValue) {
9061     if (Parser.getTok().isNot(AsmToken::String)) {
9062       Error(Parser.getTok().getLoc(), "bad string constant");
9063       Parser.eatToEndOfStatement();
9064       return false;
9065     }
9066
9067     StringValue = Parser.getTok().getStringContents();
9068     Parser.Lex();
9069   }
9070
9071   if (IsIntegerValue && IsStringValue) {
9072     assert(Tag == ARMBuildAttrs::compatibility);
9073     getTargetStreamer().emitIntTextAttribute(Tag, IntegerValue, StringValue);
9074   } else if (IsIntegerValue)
9075     getTargetStreamer().emitAttribute(Tag, IntegerValue);
9076   else if (IsStringValue)
9077     getTargetStreamer().emitTextAttribute(Tag, StringValue);
9078   return false;
9079 }
9080
9081 /// parseDirectiveCPU
9082 ///  ::= .cpu str
9083 bool ARMAsmParser::parseDirectiveCPU(SMLoc L) {
9084   StringRef CPU = getParser().parseStringToEndOfStatement().trim();
9085   getTargetStreamer().emitTextAttribute(ARMBuildAttrs::CPU_name, CPU);
9086
9087   if (!STI.CPUStringIsValid(CPU)) {
9088     Error(L, "Unknown CPU name");
9089     return false;
9090   }
9091
9092   STI.InitMCProcessorInfo(CPU, "");
9093   STI.InitCPUSchedModel(CPU);
9094   unsigned FB = ComputeAvailableFeatures(STI.getFeatureBits());
9095   setAvailableFeatures(FB);
9096
9097   return false;
9098 }
9099
9100 // FIXME: This is duplicated in getARMFPUFeatures() in
9101 // tools/clang/lib/Driver/Tools.cpp
9102 static const struct {
9103   const unsigned Fpu;
9104   const uint64_t Enabled;
9105   const uint64_t Disabled;
9106 } Fpus[] = {
9107       {ARM::VFP, ARM::FeatureVFP2, ARM::FeatureNEON},
9108       {ARM::VFPV2, ARM::FeatureVFP2, ARM::FeatureNEON},
9109       {ARM::VFPV3, ARM::FeatureVFP3, ARM::FeatureNEON},
9110       {ARM::VFPV3_D16, ARM::FeatureVFP3 | ARM::FeatureD16, ARM::FeatureNEON},
9111       {ARM::VFPV4, ARM::FeatureVFP4, ARM::FeatureNEON},
9112       {ARM::VFPV4_D16, ARM::FeatureVFP4 | ARM::FeatureD16, ARM::FeatureNEON},
9113       {ARM::FPV5_D16, ARM::FeatureFPARMv8 | ARM::FeatureD16,
9114        ARM::FeatureNEON | ARM::FeatureCrypto},
9115       {ARM::FP_ARMV8, ARM::FeatureFPARMv8,
9116        ARM::FeatureNEON | ARM::FeatureCrypto},
9117       {ARM::NEON, ARM::FeatureNEON, 0},
9118       {ARM::NEON_VFPV4, ARM::FeatureVFP4 | ARM::FeatureNEON, 0},
9119       {ARM::NEON_FP_ARMV8, ARM::FeatureFPARMv8 | ARM::FeatureNEON,
9120        ARM::FeatureCrypto},
9121       {ARM::CRYPTO_NEON_FP_ARMV8,
9122        ARM::FeatureFPARMv8 | ARM::FeatureNEON | ARM::FeatureCrypto, 0},
9123       {ARM::SOFTVFP, 0, 0},
9124 };
9125
9126 /// parseDirectiveFPU
9127 ///  ::= .fpu str
9128 bool ARMAsmParser::parseDirectiveFPU(SMLoc L) {
9129   StringRef FPU = getParser().parseStringToEndOfStatement().trim();
9130
9131   unsigned ID = StringSwitch<unsigned>(FPU)
9132 #define ARM_FPU_NAME(NAME, ID) .Case(NAME, ARM::ID)
9133 #include "ARMFPUName.def"
9134     .Default(ARM::INVALID_FPU);
9135
9136   if (ID == ARM::INVALID_FPU) {
9137     Error(L, "Unknown FPU name");
9138     return false;
9139   }
9140
9141   for (const auto &Fpu : Fpus) {
9142     if (Fpu.Fpu != ID)
9143       continue;
9144
9145     // Need to toggle features that should be on but are off and that
9146     // should off but are on.
9147     uint64_t Toggle = (Fpu.Enabled & ~STI.getFeatureBits()) |
9148                       (Fpu.Disabled & STI.getFeatureBits());
9149     setAvailableFeatures(ComputeAvailableFeatures(STI.ToggleFeature(Toggle)));
9150     break;
9151   }
9152
9153   getTargetStreamer().emitFPU(ID);
9154   return false;
9155 }
9156
9157 /// parseDirectiveFnStart
9158 ///  ::= .fnstart
9159 bool ARMAsmParser::parseDirectiveFnStart(SMLoc L) {
9160   if (UC.hasFnStart()) {
9161     Error(L, ".fnstart starts before the end of previous one");
9162     UC.emitFnStartLocNotes();
9163     return false;
9164   }
9165
9166   // Reset the unwind directives parser state
9167   UC.reset();
9168
9169   getTargetStreamer().emitFnStart();
9170
9171   UC.recordFnStart(L);
9172   return false;
9173 }
9174
9175 /// parseDirectiveFnEnd
9176 ///  ::= .fnend
9177 bool ARMAsmParser::parseDirectiveFnEnd(SMLoc L) {
9178   // Check the ordering of unwind directives
9179   if (!UC.hasFnStart()) {
9180     Error(L, ".fnstart must precede .fnend directive");
9181     return false;
9182   }
9183
9184   // Reset the unwind directives parser state
9185   getTargetStreamer().emitFnEnd();
9186
9187   UC.reset();
9188   return false;
9189 }
9190
9191 /// parseDirectiveCantUnwind
9192 ///  ::= .cantunwind
9193 bool ARMAsmParser::parseDirectiveCantUnwind(SMLoc L) {
9194   UC.recordCantUnwind(L);
9195
9196   // Check the ordering of unwind directives
9197   if (!UC.hasFnStart()) {
9198     Error(L, ".fnstart must precede .cantunwind directive");
9199     return false;
9200   }
9201   if (UC.hasHandlerData()) {
9202     Error(L, ".cantunwind can't be used with .handlerdata directive");
9203     UC.emitHandlerDataLocNotes();
9204     return false;
9205   }
9206   if (UC.hasPersonality()) {
9207     Error(L, ".cantunwind can't be used with .personality directive");
9208     UC.emitPersonalityLocNotes();
9209     return false;
9210   }
9211
9212   getTargetStreamer().emitCantUnwind();
9213   return false;
9214 }
9215
9216 /// parseDirectivePersonality
9217 ///  ::= .personality name
9218 bool ARMAsmParser::parseDirectivePersonality(SMLoc L) {
9219   MCAsmParser &Parser = getParser();
9220   bool HasExistingPersonality = UC.hasPersonality();
9221
9222   UC.recordPersonality(L);
9223
9224   // Check the ordering of unwind directives
9225   if (!UC.hasFnStart()) {
9226     Error(L, ".fnstart must precede .personality directive");
9227     return false;
9228   }
9229   if (UC.cantUnwind()) {
9230     Error(L, ".personality can't be used with .cantunwind directive");
9231     UC.emitCantUnwindLocNotes();
9232     return false;
9233   }
9234   if (UC.hasHandlerData()) {
9235     Error(L, ".personality must precede .handlerdata directive");
9236     UC.emitHandlerDataLocNotes();
9237     return false;
9238   }
9239   if (HasExistingPersonality) {
9240     Parser.eatToEndOfStatement();
9241     Error(L, "multiple personality directives");
9242     UC.emitPersonalityLocNotes();
9243     return false;
9244   }
9245
9246   // Parse the name of the personality routine
9247   if (Parser.getTok().isNot(AsmToken::Identifier)) {
9248     Parser.eatToEndOfStatement();
9249     Error(L, "unexpected input in .personality directive.");
9250     return false;
9251   }
9252   StringRef Name(Parser.getTok().getIdentifier());
9253   Parser.Lex();
9254
9255   MCSymbol *PR = getParser().getContext().GetOrCreateSymbol(Name);
9256   getTargetStreamer().emitPersonality(PR);
9257   return false;
9258 }
9259
9260 /// parseDirectiveHandlerData
9261 ///  ::= .handlerdata
9262 bool ARMAsmParser::parseDirectiveHandlerData(SMLoc L) {
9263   UC.recordHandlerData(L);
9264
9265   // Check the ordering of unwind directives
9266   if (!UC.hasFnStart()) {
9267     Error(L, ".fnstart must precede .personality directive");
9268     return false;
9269   }
9270   if (UC.cantUnwind()) {
9271     Error(L, ".handlerdata can't be used with .cantunwind directive");
9272     UC.emitCantUnwindLocNotes();
9273     return false;
9274   }
9275
9276   getTargetStreamer().emitHandlerData();
9277   return false;
9278 }
9279
9280 /// parseDirectiveSetFP
9281 ///  ::= .setfp fpreg, spreg [, offset]
9282 bool ARMAsmParser::parseDirectiveSetFP(SMLoc L) {
9283   MCAsmParser &Parser = getParser();
9284   // Check the ordering of unwind directives
9285   if (!UC.hasFnStart()) {
9286     Error(L, ".fnstart must precede .setfp directive");
9287     return false;
9288   }
9289   if (UC.hasHandlerData()) {
9290     Error(L, ".setfp must precede .handlerdata directive");
9291     return false;
9292   }
9293
9294   // Parse fpreg
9295   SMLoc FPRegLoc = Parser.getTok().getLoc();
9296   int FPReg = tryParseRegister();
9297   if (FPReg == -1) {
9298     Error(FPRegLoc, "frame pointer register expected");
9299     return false;
9300   }
9301
9302   // Consume comma
9303   if (Parser.getTok().isNot(AsmToken::Comma)) {
9304     Error(Parser.getTok().getLoc(), "comma expected");
9305     return false;
9306   }
9307   Parser.Lex(); // skip comma
9308
9309   // Parse spreg
9310   SMLoc SPRegLoc = Parser.getTok().getLoc();
9311   int SPReg = tryParseRegister();
9312   if (SPReg == -1) {
9313     Error(SPRegLoc, "stack pointer register expected");
9314     return false;
9315   }
9316
9317   if (SPReg != ARM::SP && SPReg != UC.getFPReg()) {
9318     Error(SPRegLoc, "register should be either $sp or the latest fp register");
9319     return false;
9320   }
9321
9322   // Update the frame pointer register
9323   UC.saveFPReg(FPReg);
9324
9325   // Parse offset
9326   int64_t Offset = 0;
9327   if (Parser.getTok().is(AsmToken::Comma)) {
9328     Parser.Lex(); // skip comma
9329
9330     if (Parser.getTok().isNot(AsmToken::Hash) &&
9331         Parser.getTok().isNot(AsmToken::Dollar)) {
9332       Error(Parser.getTok().getLoc(), "'#' expected");
9333       return false;
9334     }
9335     Parser.Lex(); // skip hash token.
9336
9337     const MCExpr *OffsetExpr;
9338     SMLoc ExLoc = Parser.getTok().getLoc();
9339     SMLoc EndLoc;
9340     if (getParser().parseExpression(OffsetExpr, EndLoc)) {
9341       Error(ExLoc, "malformed setfp offset");
9342       return false;
9343     }
9344     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
9345     if (!CE) {
9346       Error(ExLoc, "setfp offset must be an immediate");
9347       return false;
9348     }
9349
9350     Offset = CE->getValue();
9351   }
9352
9353   getTargetStreamer().emitSetFP(static_cast<unsigned>(FPReg),
9354                                 static_cast<unsigned>(SPReg), Offset);
9355   return false;
9356 }
9357
9358 /// parseDirective
9359 ///  ::= .pad offset
9360 bool ARMAsmParser::parseDirectivePad(SMLoc L) {
9361   MCAsmParser &Parser = getParser();
9362   // Check the ordering of unwind directives
9363   if (!UC.hasFnStart()) {
9364     Error(L, ".fnstart must precede .pad directive");
9365     return false;
9366   }
9367   if (UC.hasHandlerData()) {
9368     Error(L, ".pad must precede .handlerdata directive");
9369     return false;
9370   }
9371
9372   // Parse the offset
9373   if (Parser.getTok().isNot(AsmToken::Hash) &&
9374       Parser.getTok().isNot(AsmToken::Dollar)) {
9375     Error(Parser.getTok().getLoc(), "'#' expected");
9376     return false;
9377   }
9378   Parser.Lex(); // skip hash token.
9379
9380   const MCExpr *OffsetExpr;
9381   SMLoc ExLoc = Parser.getTok().getLoc();
9382   SMLoc EndLoc;
9383   if (getParser().parseExpression(OffsetExpr, EndLoc)) {
9384     Error(ExLoc, "malformed pad offset");
9385     return false;
9386   }
9387   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
9388   if (!CE) {
9389     Error(ExLoc, "pad offset must be an immediate");
9390     return false;
9391   }
9392
9393   getTargetStreamer().emitPad(CE->getValue());
9394   return false;
9395 }
9396
9397 /// parseDirectiveRegSave
9398 ///  ::= .save  { registers }
9399 ///  ::= .vsave { registers }
9400 bool ARMAsmParser::parseDirectiveRegSave(SMLoc L, bool IsVector) {
9401   // Check the ordering of unwind directives
9402   if (!UC.hasFnStart()) {
9403     Error(L, ".fnstart must precede .save or .vsave directives");
9404     return false;
9405   }
9406   if (UC.hasHandlerData()) {
9407     Error(L, ".save or .vsave must precede .handlerdata directive");
9408     return false;
9409   }
9410
9411   // RAII object to make sure parsed operands are deleted.
9412   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> Operands;
9413
9414   // Parse the register list
9415   if (parseRegisterList(Operands))
9416     return false;
9417   ARMOperand &Op = (ARMOperand &)*Operands[0];
9418   if (!IsVector && !Op.isRegList()) {
9419     Error(L, ".save expects GPR registers");
9420     return false;
9421   }
9422   if (IsVector && !Op.isDPRRegList()) {
9423     Error(L, ".vsave expects DPR registers");
9424     return false;
9425   }
9426
9427   getTargetStreamer().emitRegSave(Op.getRegList(), IsVector);
9428   return false;
9429 }
9430
9431 /// parseDirectiveInst
9432 ///  ::= .inst opcode [, ...]
9433 ///  ::= .inst.n opcode [, ...]
9434 ///  ::= .inst.w opcode [, ...]
9435 bool ARMAsmParser::parseDirectiveInst(SMLoc Loc, char Suffix) {
9436   MCAsmParser &Parser = getParser();
9437   int Width;
9438
9439   if (isThumb()) {
9440     switch (Suffix) {
9441     case 'n':
9442       Width = 2;
9443       break;
9444     case 'w':
9445       Width = 4;
9446       break;
9447     default:
9448       Parser.eatToEndOfStatement();
9449       Error(Loc, "cannot determine Thumb instruction size, "
9450                  "use inst.n/inst.w instead");
9451       return false;
9452     }
9453   } else {
9454     if (Suffix) {
9455       Parser.eatToEndOfStatement();
9456       Error(Loc, "width suffixes are invalid in ARM mode");
9457       return false;
9458     }
9459     Width = 4;
9460   }
9461
9462   if (getLexer().is(AsmToken::EndOfStatement)) {
9463     Parser.eatToEndOfStatement();
9464     Error(Loc, "expected expression following directive");
9465     return false;
9466   }
9467
9468   for (;;) {
9469     const MCExpr *Expr;
9470
9471     if (getParser().parseExpression(Expr)) {
9472       Error(Loc, "expected expression");
9473       return false;
9474     }
9475
9476     const MCConstantExpr *Value = dyn_cast_or_null<MCConstantExpr>(Expr);
9477     if (!Value) {
9478       Error(Loc, "expected constant expression");
9479       return false;
9480     }
9481
9482     switch (Width) {
9483     case 2:
9484       if (Value->getValue() > 0xffff) {
9485         Error(Loc, "inst.n operand is too big, use inst.w instead");
9486         return false;
9487       }
9488       break;
9489     case 4:
9490       if (Value->getValue() > 0xffffffff) {
9491         Error(Loc,
9492               StringRef(Suffix ? "inst.w" : "inst") + " operand is too big");
9493         return false;
9494       }
9495       break;
9496     default:
9497       llvm_unreachable("only supported widths are 2 and 4");
9498     }
9499
9500     getTargetStreamer().emitInst(Value->getValue(), Suffix);
9501
9502     if (getLexer().is(AsmToken::EndOfStatement))
9503       break;
9504
9505     if (getLexer().isNot(AsmToken::Comma)) {
9506       Error(Loc, "unexpected token in directive");
9507       return false;
9508     }
9509
9510     Parser.Lex();
9511   }
9512
9513   Parser.Lex();
9514   return false;
9515 }
9516
9517 /// parseDirectiveLtorg
9518 ///  ::= .ltorg | .pool
9519 bool ARMAsmParser::parseDirectiveLtorg(SMLoc L) {
9520   getTargetStreamer().emitCurrentConstantPool();
9521   return false;
9522 }
9523
9524 bool ARMAsmParser::parseDirectiveEven(SMLoc L) {
9525   const MCSection *Section = getStreamer().getCurrentSection().first;
9526
9527   if (getLexer().isNot(AsmToken::EndOfStatement)) {
9528     TokError("unexpected token in directive");
9529     return false;
9530   }
9531
9532   if (!Section) {
9533     getStreamer().InitSections(false);
9534     Section = getStreamer().getCurrentSection().first;
9535   }
9536
9537   assert(Section && "must have section to emit alignment");
9538   if (Section->UseCodeAlign())
9539     getStreamer().EmitCodeAlignment(2);
9540   else
9541     getStreamer().EmitValueToAlignment(2);
9542
9543   return false;
9544 }
9545
9546 /// parseDirectivePersonalityIndex
9547 ///   ::= .personalityindex index
9548 bool ARMAsmParser::parseDirectivePersonalityIndex(SMLoc L) {
9549   MCAsmParser &Parser = getParser();
9550   bool HasExistingPersonality = UC.hasPersonality();
9551
9552   UC.recordPersonalityIndex(L);
9553
9554   if (!UC.hasFnStart()) {
9555     Parser.eatToEndOfStatement();
9556     Error(L, ".fnstart must precede .personalityindex directive");
9557     return false;
9558   }
9559   if (UC.cantUnwind()) {
9560     Parser.eatToEndOfStatement();
9561     Error(L, ".personalityindex cannot be used with .cantunwind");
9562     UC.emitCantUnwindLocNotes();
9563     return false;
9564   }
9565   if (UC.hasHandlerData()) {
9566     Parser.eatToEndOfStatement();
9567     Error(L, ".personalityindex must precede .handlerdata directive");
9568     UC.emitHandlerDataLocNotes();
9569     return false;
9570   }
9571   if (HasExistingPersonality) {
9572     Parser.eatToEndOfStatement();
9573     Error(L, "multiple personality directives");
9574     UC.emitPersonalityLocNotes();
9575     return false;
9576   }
9577
9578   const MCExpr *IndexExpression;
9579   SMLoc IndexLoc = Parser.getTok().getLoc();
9580   if (Parser.parseExpression(IndexExpression)) {
9581     Parser.eatToEndOfStatement();
9582     return false;
9583   }
9584
9585   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(IndexExpression);
9586   if (!CE) {
9587     Parser.eatToEndOfStatement();
9588     Error(IndexLoc, "index must be a constant number");
9589     return false;
9590   }
9591   if (CE->getValue() < 0 ||
9592       CE->getValue() >= ARM::EHABI::NUM_PERSONALITY_INDEX) {
9593     Parser.eatToEndOfStatement();
9594     Error(IndexLoc, "personality routine index should be in range [0-3]");
9595     return false;
9596   }
9597
9598   getTargetStreamer().emitPersonalityIndex(CE->getValue());
9599   return false;
9600 }
9601
9602 /// parseDirectiveUnwindRaw
9603 ///   ::= .unwind_raw offset, opcode [, opcode...]
9604 bool ARMAsmParser::parseDirectiveUnwindRaw(SMLoc L) {
9605   MCAsmParser &Parser = getParser();
9606   if (!UC.hasFnStart()) {
9607     Parser.eatToEndOfStatement();
9608     Error(L, ".fnstart must precede .unwind_raw directives");
9609     return false;
9610   }
9611
9612   int64_t StackOffset;
9613
9614   const MCExpr *OffsetExpr;
9615   SMLoc OffsetLoc = getLexer().getLoc();
9616   if (getLexer().is(AsmToken::EndOfStatement) ||
9617       getParser().parseExpression(OffsetExpr)) {
9618     Error(OffsetLoc, "expected expression");
9619     Parser.eatToEndOfStatement();
9620     return false;
9621   }
9622
9623   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
9624   if (!CE) {
9625     Error(OffsetLoc, "offset must be a constant");
9626     Parser.eatToEndOfStatement();
9627     return false;
9628   }
9629
9630   StackOffset = CE->getValue();
9631
9632   if (getLexer().isNot(AsmToken::Comma)) {
9633     Error(getLexer().getLoc(), "expected comma");
9634     Parser.eatToEndOfStatement();
9635     return false;
9636   }
9637   Parser.Lex();
9638
9639   SmallVector<uint8_t, 16> Opcodes;
9640   for (;;) {
9641     const MCExpr *OE;
9642
9643     SMLoc OpcodeLoc = getLexer().getLoc();
9644     if (getLexer().is(AsmToken::EndOfStatement) || Parser.parseExpression(OE)) {
9645       Error(OpcodeLoc, "expected opcode expression");
9646       Parser.eatToEndOfStatement();
9647       return false;
9648     }
9649
9650     const MCConstantExpr *OC = dyn_cast<MCConstantExpr>(OE);
9651     if (!OC) {
9652       Error(OpcodeLoc, "opcode value must be a constant");
9653       Parser.eatToEndOfStatement();
9654       return false;
9655     }
9656
9657     const int64_t Opcode = OC->getValue();
9658     if (Opcode & ~0xff) {
9659       Error(OpcodeLoc, "invalid opcode");
9660       Parser.eatToEndOfStatement();
9661       return false;
9662     }
9663
9664     Opcodes.push_back(uint8_t(Opcode));
9665
9666     if (getLexer().is(AsmToken::EndOfStatement))
9667       break;
9668
9669     if (getLexer().isNot(AsmToken::Comma)) {
9670       Error(getLexer().getLoc(), "unexpected token in directive");
9671       Parser.eatToEndOfStatement();
9672       return false;
9673     }
9674
9675     Parser.Lex();
9676   }
9677
9678   getTargetStreamer().emitUnwindRaw(StackOffset, Opcodes);
9679
9680   Parser.Lex();
9681   return false;
9682 }
9683
9684 /// parseDirectiveTLSDescSeq
9685 ///   ::= .tlsdescseq tls-variable
9686 bool ARMAsmParser::parseDirectiveTLSDescSeq(SMLoc L) {
9687   MCAsmParser &Parser = getParser();
9688
9689   if (getLexer().isNot(AsmToken::Identifier)) {
9690     TokError("expected variable after '.tlsdescseq' directive");
9691     Parser.eatToEndOfStatement();
9692     return false;
9693   }
9694
9695   const MCSymbolRefExpr *SRE =
9696     MCSymbolRefExpr::Create(Parser.getTok().getIdentifier(),
9697                             MCSymbolRefExpr::VK_ARM_TLSDESCSEQ, getContext());
9698   Lex();
9699
9700   if (getLexer().isNot(AsmToken::EndOfStatement)) {
9701     Error(Parser.getTok().getLoc(), "unexpected token");
9702     Parser.eatToEndOfStatement();
9703     return false;
9704   }
9705
9706   getTargetStreamer().AnnotateTLSDescriptorSequence(SRE);
9707   return false;
9708 }
9709
9710 /// parseDirectiveMovSP
9711 ///  ::= .movsp reg [, #offset]
9712 bool ARMAsmParser::parseDirectiveMovSP(SMLoc L) {
9713   MCAsmParser &Parser = getParser();
9714   if (!UC.hasFnStart()) {
9715     Parser.eatToEndOfStatement();
9716     Error(L, ".fnstart must precede .movsp directives");
9717     return false;
9718   }
9719   if (UC.getFPReg() != ARM::SP) {
9720     Parser.eatToEndOfStatement();
9721     Error(L, "unexpected .movsp directive");
9722     return false;
9723   }
9724
9725   SMLoc SPRegLoc = Parser.getTok().getLoc();
9726   int SPReg = tryParseRegister();
9727   if (SPReg == -1) {
9728     Parser.eatToEndOfStatement();
9729     Error(SPRegLoc, "register expected");
9730     return false;
9731   }
9732
9733   if (SPReg == ARM::SP || SPReg == ARM::PC) {
9734     Parser.eatToEndOfStatement();
9735     Error(SPRegLoc, "sp and pc are not permitted in .movsp directive");
9736     return false;
9737   }
9738
9739   int64_t Offset = 0;
9740   if (Parser.getTok().is(AsmToken::Comma)) {
9741     Parser.Lex();
9742
9743     if (Parser.getTok().isNot(AsmToken::Hash)) {
9744       Error(Parser.getTok().getLoc(), "expected #constant");
9745       Parser.eatToEndOfStatement();
9746       return false;
9747     }
9748     Parser.Lex();
9749
9750     const MCExpr *OffsetExpr;
9751     SMLoc OffsetLoc = Parser.getTok().getLoc();
9752     if (Parser.parseExpression(OffsetExpr)) {
9753       Parser.eatToEndOfStatement();
9754       Error(OffsetLoc, "malformed offset expression");
9755       return false;
9756     }
9757
9758     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
9759     if (!CE) {
9760       Parser.eatToEndOfStatement();
9761       Error(OffsetLoc, "offset must be an immediate constant");
9762       return false;
9763     }
9764
9765     Offset = CE->getValue();
9766   }
9767
9768   getTargetStreamer().emitMovSP(SPReg, Offset);
9769   UC.saveFPReg(SPReg);
9770
9771   return false;
9772 }
9773
9774 /// parseDirectiveObjectArch
9775 ///   ::= .object_arch name
9776 bool ARMAsmParser::parseDirectiveObjectArch(SMLoc L) {
9777   MCAsmParser &Parser = getParser();
9778   if (getLexer().isNot(AsmToken::Identifier)) {
9779     Error(getLexer().getLoc(), "unexpected token");
9780     Parser.eatToEndOfStatement();
9781     return false;
9782   }
9783
9784   StringRef Arch = Parser.getTok().getString();
9785   SMLoc ArchLoc = Parser.getTok().getLoc();
9786   getLexer().Lex();
9787
9788   unsigned ID = StringSwitch<unsigned>(Arch)
9789 #define ARM_ARCH_NAME(NAME, ID, DEFAULT_CPU_NAME, DEFAULT_CPU_ARCH) \
9790     .Case(NAME, ARM::ID)
9791 #define ARM_ARCH_ALIAS(NAME, ID) \
9792     .Case(NAME, ARM::ID)
9793 #include "MCTargetDesc/ARMArchName.def"
9794 #undef ARM_ARCH_NAME
9795 #undef ARM_ARCH_ALIAS
9796     .Default(ARM::INVALID_ARCH);
9797
9798   if (ID == ARM::INVALID_ARCH) {
9799     Error(ArchLoc, "unknown architecture '" + Arch + "'");
9800     Parser.eatToEndOfStatement();
9801     return false;
9802   }
9803
9804   getTargetStreamer().emitObjectArch(ID);
9805
9806   if (getLexer().isNot(AsmToken::EndOfStatement)) {
9807     Error(getLexer().getLoc(), "unexpected token");
9808     Parser.eatToEndOfStatement();
9809   }
9810
9811   return false;
9812 }
9813
9814 /// parseDirectiveAlign
9815 ///   ::= .align
9816 bool ARMAsmParser::parseDirectiveAlign(SMLoc L) {
9817   // NOTE: if this is not the end of the statement, fall back to the target
9818   // agnostic handling for this directive which will correctly handle this.
9819   if (getLexer().isNot(AsmToken::EndOfStatement))
9820     return true;
9821
9822   // '.align' is target specifically handled to mean 2**2 byte alignment.
9823   if (getStreamer().getCurrentSection().first->UseCodeAlign())
9824     getStreamer().EmitCodeAlignment(4, 0);
9825   else
9826     getStreamer().EmitValueToAlignment(4, 0, 1, 0);
9827
9828   return false;
9829 }
9830
9831 /// parseDirectiveThumbSet
9832 ///  ::= .thumb_set name, value
9833 bool ARMAsmParser::parseDirectiveThumbSet(SMLoc L) {
9834   MCAsmParser &Parser = getParser();
9835
9836   StringRef Name;
9837   if (Parser.parseIdentifier(Name)) {
9838     TokError("expected identifier after '.thumb_set'");
9839     Parser.eatToEndOfStatement();
9840     return false;
9841   }
9842
9843   if (getLexer().isNot(AsmToken::Comma)) {
9844     TokError("expected comma after name '" + Name + "'");
9845     Parser.eatToEndOfStatement();
9846     return false;
9847   }
9848   Lex();
9849
9850   const MCExpr *Value;
9851   if (Parser.parseExpression(Value)) {
9852     TokError("missing expression");
9853     Parser.eatToEndOfStatement();
9854     return false;
9855   }
9856
9857   if (getLexer().isNot(AsmToken::EndOfStatement)) {
9858     TokError("unexpected token");
9859     Parser.eatToEndOfStatement();
9860     return false;
9861   }
9862   Lex();
9863
9864   MCSymbol *Alias = getContext().GetOrCreateSymbol(Name);
9865   getTargetStreamer().emitThumbSet(Alias, Value);
9866   return false;
9867 }
9868
9869 /// Force static initialization.
9870 extern "C" void LLVMInitializeARMAsmParser() {
9871   RegisterMCAsmParser<ARMAsmParser> X(TheARMLETarget);
9872   RegisterMCAsmParser<ARMAsmParser> Y(TheARMBETarget);
9873   RegisterMCAsmParser<ARMAsmParser> A(TheThumbLETarget);
9874   RegisterMCAsmParser<ARMAsmParser> B(TheThumbBETarget);
9875 }
9876
9877 #define GET_REGISTER_MATCHER
9878 #define GET_SUBTARGET_FEATURE_NAME
9879 #define GET_MATCHER_IMPLEMENTATION
9880 #include "ARMGenAsmMatcher.inc"
9881
9882 static const struct {
9883   const char *Name;
9884   const unsigned ArchCheck;
9885   const uint64_t Features;
9886 } Extensions[] = {
9887   { "crc", Feature_HasV8, ARM::FeatureCRC },
9888   { "crypto",  Feature_HasV8,
9889     ARM::FeatureCrypto | ARM::FeatureNEON | ARM::FeatureFPARMv8 },
9890   { "fp", Feature_HasV8, ARM::FeatureFPARMv8 },
9891   { "idiv", Feature_HasV7 | Feature_IsNotMClass,
9892     ARM::FeatureHWDiv | ARM::FeatureHWDivARM },
9893   // FIXME: iWMMXT not supported
9894   { "iwmmxt", Feature_None, 0 },
9895   // FIXME: iWMMXT2 not supported
9896   { "iwmmxt2", Feature_None, 0 },
9897   // FIXME: Maverick not supported
9898   { "maverick", Feature_None, 0 },
9899   { "mp", Feature_HasV7 | Feature_IsNotMClass, ARM::FeatureMP },
9900   // FIXME: ARMv6-m OS Extensions feature not checked
9901   { "os", Feature_None, 0 },
9902   // FIXME: Also available in ARMv6-K
9903   { "sec", Feature_HasV7, ARM::FeatureTrustZone },
9904   { "simd", Feature_HasV8, ARM::FeatureNEON | ARM::FeatureFPARMv8 },
9905   // FIXME: Only available in A-class, isel not predicated
9906   { "virt", Feature_HasV7, ARM::FeatureVirtualization },
9907   // FIXME: xscale not supported
9908   { "xscale", Feature_None, 0 },
9909 };
9910
9911 /// parseDirectiveArchExtension
9912 ///   ::= .arch_extension [no]feature
9913 bool ARMAsmParser::parseDirectiveArchExtension(SMLoc L) {
9914   MCAsmParser &Parser = getParser();
9915
9916   if (getLexer().isNot(AsmToken::Identifier)) {
9917     Error(getLexer().getLoc(), "unexpected token");
9918     Parser.eatToEndOfStatement();
9919     return false;
9920   }
9921
9922   StringRef Name = Parser.getTok().getString();
9923   SMLoc ExtLoc = Parser.getTok().getLoc();
9924   getLexer().Lex();
9925
9926   bool EnableFeature = true;
9927   if (Name.startswith_lower("no")) {
9928     EnableFeature = false;
9929     Name = Name.substr(2);
9930   }
9931
9932   for (const auto &Extension : Extensions) {
9933     if (Extension.Name != Name)
9934       continue;
9935
9936     if (!Extension.Features)
9937       report_fatal_error("unsupported architectural extension: " + Name);
9938
9939     if ((getAvailableFeatures() & Extension.ArchCheck) != Extension.ArchCheck) {
9940       Error(ExtLoc, "architectural extension '" + Name + "' is not "
9941             "allowed for the current base architecture");
9942       return false;
9943     }
9944
9945     uint64_t ToggleFeatures = EnableFeature
9946                                   ? (~STI.getFeatureBits() & Extension.Features)
9947                                   : ( STI.getFeatureBits() & Extension.Features);
9948     uint64_t Features =
9949         ComputeAvailableFeatures(STI.ToggleFeature(ToggleFeatures));
9950     setAvailableFeatures(Features);
9951     return false;
9952   }
9953
9954   Error(ExtLoc, "unknown architectural extension: " + Name);
9955   Parser.eatToEndOfStatement();
9956   return false;
9957 }
9958
9959 // Define this matcher function after the auto-generated include so we
9960 // have the match class enum definitions.
9961 unsigned ARMAsmParser::validateTargetOperandClass(MCParsedAsmOperand &AsmOp,
9962                                                   unsigned Kind) {
9963   ARMOperand &Op = static_cast<ARMOperand &>(AsmOp);
9964   // If the kind is a token for a literal immediate, check if our asm
9965   // operand matches. This is for InstAliases which have a fixed-value
9966   // immediate in the syntax.
9967   switch (Kind) {
9968   default: break;
9969   case MCK__35_0:
9970     if (Op.isImm())
9971       if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm()))
9972         if (CE->getValue() == 0)
9973           return Match_Success;
9974     break;
9975   case MCK_ModImm:
9976   case MCK_ARMSOImm:
9977     if (Op.isImm()) {
9978       const MCExpr *SOExpr = Op.getImm();
9979       int64_t Value;
9980       if (!SOExpr->EvaluateAsAbsolute(Value))
9981         return Match_Success;
9982       assert((Value >= INT32_MIN && Value <= UINT32_MAX) &&
9983              "expression value must be representable in 32 bits");
9984     }
9985     break;
9986   case MCK_GPRPair:
9987     if (Op.isReg() &&
9988         MRI->getRegClass(ARM::GPRRegClassID).contains(Op.getReg()))
9989       return Match_Success;
9990     break;
9991   }
9992   return Match_InvalidOperand;
9993 }