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