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