1 //===- ARMAsmParser.cpp - Parse ARM assembly to MCInst instructions -------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "ARMFeatures.h"
10 #include "ARMBaseInstrInfo.h"
11 #include "Utils/ARMBaseInfo.h"
12 #include "MCTargetDesc/ARMAddressingModes.h"
13 #include "MCTargetDesc/ARMBaseInfo.h"
14 #include "MCTargetDesc/ARMInstPrinter.h"
15 #include "MCTargetDesc/ARMMCExpr.h"
16 #include "MCTargetDesc/ARMMCTargetDesc.h"
17 #include "TargetInfo/ARMTargetInfo.h"
18 #include "llvm/ADT/APFloat.h"
19 #include "llvm/ADT/APInt.h"
20 #include "llvm/ADT/None.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/StringMap.h"
25 #include "llvm/ADT/StringRef.h"
26 #include "llvm/ADT/StringSwitch.h"
27 #include "llvm/ADT/Triple.h"
28 #include "llvm/ADT/Twine.h"
29 #include "llvm/MC/MCContext.h"
30 #include "llvm/MC/MCExpr.h"
31 #include "llvm/MC/MCInst.h"
32 #include "llvm/MC/MCInstrDesc.h"
33 #include "llvm/MC/MCInstrInfo.h"
34 #include "llvm/MC/MCObjectFileInfo.h"
35 #include "llvm/MC/MCParser/MCAsmLexer.h"
36 #include "llvm/MC/MCParser/MCAsmParser.h"
37 #include "llvm/MC/MCParser/MCAsmParserExtension.h"
38 #include "llvm/MC/MCParser/MCAsmParserUtils.h"
39 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
40 #include "llvm/MC/MCParser/MCTargetAsmParser.h"
41 #include "llvm/MC/MCRegisterInfo.h"
42 #include "llvm/MC/MCSection.h"
43 #include "llvm/MC/MCStreamer.h"
44 #include "llvm/MC/MCSubtargetInfo.h"
45 #include "llvm/MC/MCSymbol.h"
46 #include "llvm/MC/SubtargetFeature.h"
47 #include "llvm/Support/ARMBuildAttributes.h"
48 #include "llvm/Support/ARMEHABI.h"
49 #include "llvm/Support/Casting.h"
50 #include "llvm/Support/CommandLine.h"
51 #include "llvm/Support/Compiler.h"
52 #include "llvm/Support/ErrorHandling.h"
53 #include "llvm/Support/MathExtras.h"
54 #include "llvm/Support/SMLoc.h"
55 #include "llvm/Support/TargetParser.h"
56 #include "llvm/Support/TargetRegistry.h"
57 #include "llvm/Support/raw_ostream.h"
58 #include <algorithm>
59 #include <cassert>
60 #include <cstddef>
61 #include <cstdint>
62 #include <iterator>
63 #include <limits>
64 #include <memory>
65 #include <string>
66 #include <utility>
67 #include <vector>
68 
69 #define DEBUG_TYPE "asm-parser"
70 
71 using namespace llvm;
72 
73 namespace llvm {
74 extern const MCInstrDesc ARMInsts[];
75 } // end namespace llvm
76 
77 namespace {
78 
79 enum class ImplicitItModeTy { Always, Never, ARMOnly, ThumbOnly };
80 
81 static cl::opt<ImplicitItModeTy> ImplicitItMode(
82     "arm-implicit-it", cl::init(ImplicitItModeTy::ARMOnly),
83     cl::desc("Allow conditional instructions outdside of an IT block"),
84     cl::values(clEnumValN(ImplicitItModeTy::Always, "always",
85                           "Accept in both ISAs, emit implicit ITs in Thumb"),
86                clEnumValN(ImplicitItModeTy::Never, "never",
87                           "Warn in ARM, reject in Thumb"),
88                clEnumValN(ImplicitItModeTy::ARMOnly, "arm",
89                           "Accept in ARM, reject in Thumb"),
90                clEnumValN(ImplicitItModeTy::ThumbOnly, "thumb",
91                           "Warn in ARM, emit implicit ITs in Thumb")));
92 
93 static cl::opt<bool> AddBuildAttributes("arm-add-build-attributes",
94                                         cl::init(false));
95 
96 enum VectorLaneTy { NoLanes, AllLanes, IndexedLane };
97 
98 static inline unsigned extractITMaskBit(unsigned Mask, unsigned Position) {
99   // Position==0 means we're not in an IT block at all. Position==1
100   // means we want the first state bit, which is always 0 (Then).
101   // Position==2 means we want the second state bit, stored at bit 3
102   // of Mask, and so on downwards. So (5 - Position) will shift the
103   // right bit down to bit 0, including the always-0 bit at bit 4 for
104   // the mandatory initial Then.
105   return (Mask >> (5 - Position) & 1);
106 }
107 
108 class UnwindContext {
109   using Locs = SmallVector<SMLoc, 4>;
110 
111   MCAsmParser &Parser;
112   Locs FnStartLocs;
113   Locs CantUnwindLocs;
114   Locs PersonalityLocs;
115   Locs PersonalityIndexLocs;
116   Locs HandlerDataLocs;
117   int FPReg;
118 
119 public:
120   UnwindContext(MCAsmParser &P) : Parser(P), FPReg(ARM::SP) {}
121 
122   bool hasFnStart() const { return !FnStartLocs.empty(); }
123   bool cantUnwind() const { return !CantUnwindLocs.empty(); }
124   bool hasHandlerData() const { return !HandlerDataLocs.empty(); }
125 
126   bool hasPersonality() const {
127     return !(PersonalityLocs.empty() && PersonalityIndexLocs.empty());
128   }
129 
130   void recordFnStart(SMLoc L) { FnStartLocs.push_back(L); }
131   void recordCantUnwind(SMLoc L) { CantUnwindLocs.push_back(L); }
132   void recordPersonality(SMLoc L) { PersonalityLocs.push_back(L); }
133   void recordHandlerData(SMLoc L) { HandlerDataLocs.push_back(L); }
134   void recordPersonalityIndex(SMLoc L) { PersonalityIndexLocs.push_back(L); }
135 
136   void saveFPReg(int Reg) { FPReg = Reg; }
137   int getFPReg() const { return FPReg; }
138 
139   void emitFnStartLocNotes() const {
140     for (Locs::const_iterator FI = FnStartLocs.begin(), FE = FnStartLocs.end();
141          FI != FE; ++FI)
142       Parser.Note(*FI, ".fnstart was specified here");
143   }
144 
145   void emitCantUnwindLocNotes() const {
146     for (Locs::const_iterator UI = CantUnwindLocs.begin(),
147                               UE = CantUnwindLocs.end(); UI != UE; ++UI)
148       Parser.Note(*UI, ".cantunwind was specified here");
149   }
150 
151   void emitHandlerDataLocNotes() const {
152     for (Locs::const_iterator HI = HandlerDataLocs.begin(),
153                               HE = HandlerDataLocs.end(); HI != HE; ++HI)
154       Parser.Note(*HI, ".handlerdata was specified here");
155   }
156 
157   void emitPersonalityLocNotes() const {
158     for (Locs::const_iterator PI = PersonalityLocs.begin(),
159                               PE = PersonalityLocs.end(),
160                               PII = PersonalityIndexLocs.begin(),
161                               PIE = PersonalityIndexLocs.end();
162          PI != PE || PII != PIE;) {
163       if (PI != PE && (PII == PIE || PI->getPointer() < PII->getPointer()))
164         Parser.Note(*PI++, ".personality was specified here");
165       else if (PII != PIE && (PI == PE || PII->getPointer() < PI->getPointer()))
166         Parser.Note(*PII++, ".personalityindex was specified here");
167       else
168         llvm_unreachable(".personality and .personalityindex cannot be "
169                          "at the same location");
170     }
171   }
172 
173   void reset() {
174     FnStartLocs = Locs();
175     CantUnwindLocs = Locs();
176     PersonalityLocs = Locs();
177     HandlerDataLocs = Locs();
178     PersonalityIndexLocs = Locs();
179     FPReg = ARM::SP;
180   }
181 };
182 
183 
184 class ARMAsmParser : public MCTargetAsmParser {
185   const MCRegisterInfo *MRI;
186   UnwindContext UC;
187 
188   ARMTargetStreamer &getTargetStreamer() {
189     assert(getParser().getStreamer().getTargetStreamer() &&
190            "do not have a target streamer");
191     MCTargetStreamer &TS = *getParser().getStreamer().getTargetStreamer();
192     return static_cast<ARMTargetStreamer &>(TS);
193   }
194 
195   // Map of register aliases registers via the .req directive.
196   StringMap<unsigned> RegisterReqs;
197 
198   bool NextSymbolIsThumb;
199 
200   bool useImplicitITThumb() const {
201     return ImplicitItMode == ImplicitItModeTy::Always ||
202            ImplicitItMode == ImplicitItModeTy::ThumbOnly;
203   }
204 
205   bool useImplicitITARM() const {
206     return ImplicitItMode == ImplicitItModeTy::Always ||
207            ImplicitItMode == ImplicitItModeTy::ARMOnly;
208   }
209 
210   struct {
211     ARMCC::CondCodes Cond;    // Condition for IT block.
212     unsigned Mask:4;          // Condition mask for instructions.
213                               // Starting at first 1 (from lsb).
214                               //   '1'  condition as indicated in IT.
215                               //   '0'  inverse of condition (else).
216                               // Count of instructions in IT block is
217                               // 4 - trailingzeroes(mask)
218                               // Note that this does not have the same encoding
219                               // as in the IT instruction, which also depends
220                               // on the low bit of the condition code.
221 
222     unsigned CurPosition;     // Current position in parsing of IT
223                               // block. In range [0,4], with 0 being the IT
224                               // instruction itself. Initialized according to
225                               // count of instructions in block.  ~0U if no
226                               // active IT block.
227 
228     bool IsExplicit;          // true  - The IT instruction was present in the
229                               //         input, we should not modify it.
230                               // false - The IT instruction was added
231                               //         implicitly, we can extend it if that
232                               //         would be legal.
233   } ITState;
234 
235   SmallVector<MCInst, 4> PendingConditionalInsts;
236 
237   void flushPendingInstructions(MCStreamer &Out) override {
238     if (!inImplicitITBlock()) {
239       assert(PendingConditionalInsts.size() == 0);
240       return;
241     }
242 
243     // Emit the IT instruction
244     MCInst ITInst;
245     ITInst.setOpcode(ARM::t2IT);
246     ITInst.addOperand(MCOperand::createImm(ITState.Cond));
247     ITInst.addOperand(MCOperand::createImm(ITState.Mask));
248     Out.EmitInstruction(ITInst, getSTI());
249 
250     // Emit the conditonal instructions
251     assert(PendingConditionalInsts.size() <= 4);
252     for (const MCInst &Inst : PendingConditionalInsts) {
253       Out.EmitInstruction(Inst, getSTI());
254     }
255     PendingConditionalInsts.clear();
256 
257     // Clear the IT state
258     ITState.Mask = 0;
259     ITState.CurPosition = ~0U;
260   }
261 
262   bool inITBlock() { return ITState.CurPosition != ~0U; }
263   bool inExplicitITBlock() { return inITBlock() && ITState.IsExplicit; }
264   bool inImplicitITBlock() { return inITBlock() && !ITState.IsExplicit; }
265 
266   bool lastInITBlock() {
267     return ITState.CurPosition == 4 - countTrailingZeros(ITState.Mask);
268   }
269 
270   void forwardITPosition() {
271     if (!inITBlock()) return;
272     // Move to the next instruction in the IT block, if there is one. If not,
273     // mark the block as done, except for implicit IT blocks, which we leave
274     // open until we find an instruction that can't be added to it.
275     unsigned TZ = countTrailingZeros(ITState.Mask);
276     if (++ITState.CurPosition == 5 - TZ && ITState.IsExplicit)
277       ITState.CurPosition = ~0U; // Done with the IT block after this.
278   }
279 
280   // Rewind the state of the current IT block, removing the last slot from it.
281   void rewindImplicitITPosition() {
282     assert(inImplicitITBlock());
283     assert(ITState.CurPosition > 1);
284     ITState.CurPosition--;
285     unsigned TZ = countTrailingZeros(ITState.Mask);
286     unsigned NewMask = 0;
287     NewMask |= ITState.Mask & (0xC << TZ);
288     NewMask |= 0x2 << TZ;
289     ITState.Mask = NewMask;
290   }
291 
292   // Rewind the state of the current IT block, removing the last slot from it.
293   // If we were at the first slot, this closes the IT block.
294   void discardImplicitITBlock() {
295     assert(inImplicitITBlock());
296     assert(ITState.CurPosition == 1);
297     ITState.CurPosition = ~0U;
298   }
299 
300   // Return the low-subreg of a given Q register.
301   unsigned getDRegFromQReg(unsigned QReg) const {
302     return MRI->getSubReg(QReg, ARM::dsub_0);
303   }
304 
305   // Get the condition code corresponding to the current IT block slot.
306   ARMCC::CondCodes currentITCond() {
307     unsigned MaskBit = extractITMaskBit(ITState.Mask, ITState.CurPosition);
308     return MaskBit ? ARMCC::getOppositeCondition(ITState.Cond) : ITState.Cond;
309   }
310 
311   // Invert the condition of the current IT block slot without changing any
312   // other slots in the same block.
313   void invertCurrentITCondition() {
314     if (ITState.CurPosition == 1) {
315       ITState.Cond = ARMCC::getOppositeCondition(ITState.Cond);
316     } else {
317       ITState.Mask ^= 1 << (5 - ITState.CurPosition);
318     }
319   }
320 
321   // Returns true if the current IT block is full (all 4 slots used).
322   bool isITBlockFull() {
323     return inITBlock() && (ITState.Mask & 1);
324   }
325 
326   // Extend the current implicit IT block to have one more slot with the given
327   // condition code.
328   void extendImplicitITBlock(ARMCC::CondCodes Cond) {
329     assert(inImplicitITBlock());
330     assert(!isITBlockFull());
331     assert(Cond == ITState.Cond ||
332            Cond == ARMCC::getOppositeCondition(ITState.Cond));
333     unsigned TZ = countTrailingZeros(ITState.Mask);
334     unsigned NewMask = 0;
335     // Keep any existing condition bits.
336     NewMask |= ITState.Mask & (0xE << TZ);
337     // Insert the new condition bit.
338     NewMask |= (Cond != ITState.Cond) << TZ;
339     // Move the trailing 1 down one bit.
340     NewMask |= 1 << (TZ - 1);
341     ITState.Mask = NewMask;
342   }
343 
344   // Create a new implicit IT block with a dummy condition code.
345   void startImplicitITBlock() {
346     assert(!inITBlock());
347     ITState.Cond = ARMCC::AL;
348     ITState.Mask = 8;
349     ITState.CurPosition = 1;
350     ITState.IsExplicit = false;
351   }
352 
353   // Create a new explicit IT block with the given condition and mask.
354   // The mask should be in the format used in ARMOperand and
355   // MCOperand, with a 1 implying 'e', regardless of the low bit of
356   // the condition.
357   void startExplicitITBlock(ARMCC::CondCodes Cond, unsigned Mask) {
358     assert(!inITBlock());
359     ITState.Cond = Cond;
360     ITState.Mask = Mask;
361     ITState.CurPosition = 0;
362     ITState.IsExplicit = true;
363   }
364 
365   struct {
366     unsigned Mask : 4;
367     unsigned CurPosition;
368   } VPTState;
369   bool inVPTBlock() { return VPTState.CurPosition != ~0U; }
370   void forwardVPTPosition() {
371     if (!inVPTBlock()) return;
372     unsigned TZ = countTrailingZeros(VPTState.Mask);
373     if (++VPTState.CurPosition == 5 - TZ)
374       VPTState.CurPosition = ~0U;
375   }
376 
377   void Note(SMLoc L, const Twine &Msg, SMRange Range = None) {
378     return getParser().Note(L, Msg, Range);
379   }
380 
381   bool Warning(SMLoc L, const Twine &Msg, SMRange Range = None) {
382     return getParser().Warning(L, Msg, Range);
383   }
384 
385   bool Error(SMLoc L, const Twine &Msg, SMRange Range = None) {
386     return getParser().Error(L, Msg, Range);
387   }
388 
389   bool validatetLDMRegList(const MCInst &Inst, const OperandVector &Operands,
390                            unsigned ListNo, bool IsARPop = false);
391   bool validatetSTMRegList(const MCInst &Inst, const OperandVector &Operands,
392                            unsigned ListNo);
393 
394   int tryParseRegister();
395   bool tryParseRegisterWithWriteBack(OperandVector &);
396   int tryParseShiftRegister(OperandVector &);
397   bool parseRegisterList(OperandVector &, bool EnforceOrder = true);
398   bool parseMemory(OperandVector &);
399   bool parseOperand(OperandVector &, StringRef Mnemonic);
400   bool parsePrefix(ARMMCExpr::VariantKind &RefKind);
401   bool parseMemRegOffsetShift(ARM_AM::ShiftOpc &ShiftType,
402                               unsigned &ShiftAmount);
403   bool parseLiteralValues(unsigned Size, SMLoc L);
404   bool parseDirectiveThumb(SMLoc L);
405   bool parseDirectiveARM(SMLoc L);
406   bool parseDirectiveThumbFunc(SMLoc L);
407   bool parseDirectiveCode(SMLoc L);
408   bool parseDirectiveSyntax(SMLoc L);
409   bool parseDirectiveReq(StringRef Name, SMLoc L);
410   bool parseDirectiveUnreq(SMLoc L);
411   bool parseDirectiveArch(SMLoc L);
412   bool parseDirectiveEabiAttr(SMLoc L);
413   bool parseDirectiveCPU(SMLoc L);
414   bool parseDirectiveFPU(SMLoc L);
415   bool parseDirectiveFnStart(SMLoc L);
416   bool parseDirectiveFnEnd(SMLoc L);
417   bool parseDirectiveCantUnwind(SMLoc L);
418   bool parseDirectivePersonality(SMLoc L);
419   bool parseDirectiveHandlerData(SMLoc L);
420   bool parseDirectiveSetFP(SMLoc L);
421   bool parseDirectivePad(SMLoc L);
422   bool parseDirectiveRegSave(SMLoc L, bool IsVector);
423   bool parseDirectiveInst(SMLoc L, char Suffix = '\0');
424   bool parseDirectiveLtorg(SMLoc L);
425   bool parseDirectiveEven(SMLoc L);
426   bool parseDirectivePersonalityIndex(SMLoc L);
427   bool parseDirectiveUnwindRaw(SMLoc L);
428   bool parseDirectiveTLSDescSeq(SMLoc L);
429   bool parseDirectiveMovSP(SMLoc L);
430   bool parseDirectiveObjectArch(SMLoc L);
431   bool parseDirectiveArchExtension(SMLoc L);
432   bool parseDirectiveAlign(SMLoc L);
433   bool parseDirectiveThumbSet(SMLoc L);
434 
435   bool isMnemonicVPTPredicable(StringRef Mnemonic, StringRef ExtraToken);
436   StringRef splitMnemonic(StringRef Mnemonic, StringRef ExtraToken,
437                           unsigned &PredicationCode,
438                           unsigned &VPTPredicationCode, bool &CarrySetting,
439                           unsigned &ProcessorIMod, StringRef &ITMask);
440   void getMnemonicAcceptInfo(StringRef Mnemonic, StringRef ExtraToken,
441                              StringRef FullInst, bool &CanAcceptCarrySet,
442                              bool &CanAcceptPredicationCode,
443                              bool &CanAcceptVPTPredicationCode);
444 
445   void tryConvertingToTwoOperandForm(StringRef Mnemonic, bool CarrySetting,
446                                      OperandVector &Operands);
447   bool isThumb() const {
448     // FIXME: Can tablegen auto-generate this?
449     return getSTI().getFeatureBits()[ARM::ModeThumb];
450   }
451 
452   bool isThumbOne() const {
453     return isThumb() && !getSTI().getFeatureBits()[ARM::FeatureThumb2];
454   }
455 
456   bool isThumbTwo() const {
457     return isThumb() && getSTI().getFeatureBits()[ARM::FeatureThumb2];
458   }
459 
460   bool hasThumb() const {
461     return getSTI().getFeatureBits()[ARM::HasV4TOps];
462   }
463 
464   bool hasThumb2() const {
465     return getSTI().getFeatureBits()[ARM::FeatureThumb2];
466   }
467 
468   bool hasV6Ops() const {
469     return getSTI().getFeatureBits()[ARM::HasV6Ops];
470   }
471 
472   bool hasV6T2Ops() const {
473     return getSTI().getFeatureBits()[ARM::HasV6T2Ops];
474   }
475 
476   bool hasV6MOps() const {
477     return getSTI().getFeatureBits()[ARM::HasV6MOps];
478   }
479 
480   bool hasV7Ops() const {
481     return getSTI().getFeatureBits()[ARM::HasV7Ops];
482   }
483 
484   bool hasV8Ops() const {
485     return getSTI().getFeatureBits()[ARM::HasV8Ops];
486   }
487 
488   bool hasV8MBaseline() const {
489     return getSTI().getFeatureBits()[ARM::HasV8MBaselineOps];
490   }
491 
492   bool hasV8MMainline() const {
493     return getSTI().getFeatureBits()[ARM::HasV8MMainlineOps];
494   }
495   bool hasV8_1MMainline() const {
496     return getSTI().getFeatureBits()[ARM::HasV8_1MMainlineOps];
497   }
498   bool hasMVE() const {
499     return getSTI().getFeatureBits()[ARM::HasMVEIntegerOps];
500   }
501   bool hasMVEFloat() const {
502     return getSTI().getFeatureBits()[ARM::HasMVEFloatOps];
503   }
504   bool has8MSecExt() const {
505     return getSTI().getFeatureBits()[ARM::Feature8MSecExt];
506   }
507 
508   bool hasARM() const {
509     return !getSTI().getFeatureBits()[ARM::FeatureNoARM];
510   }
511 
512   bool hasDSP() const {
513     return getSTI().getFeatureBits()[ARM::FeatureDSP];
514   }
515 
516   bool hasD32() const {
517     return getSTI().getFeatureBits()[ARM::FeatureD32];
518   }
519 
520   bool hasV8_1aOps() const {
521     return getSTI().getFeatureBits()[ARM::HasV8_1aOps];
522   }
523 
524   bool hasRAS() const {
525     return getSTI().getFeatureBits()[ARM::FeatureRAS];
526   }
527 
528   void SwitchMode() {
529     MCSubtargetInfo &STI = copySTI();
530     auto FB = ComputeAvailableFeatures(STI.ToggleFeature(ARM::ModeThumb));
531     setAvailableFeatures(FB);
532   }
533 
534   void FixModeAfterArchChange(bool WasThumb, SMLoc Loc);
535 
536   bool isMClass() const {
537     return getSTI().getFeatureBits()[ARM::FeatureMClass];
538   }
539 
540   /// @name Auto-generated Match Functions
541   /// {
542 
543 #define GET_ASSEMBLER_HEADER
544 #include "ARMGenAsmMatcher.inc"
545 
546   /// }
547 
548   OperandMatchResultTy parseITCondCode(OperandVector &);
549   OperandMatchResultTy parseCoprocNumOperand(OperandVector &);
550   OperandMatchResultTy parseCoprocRegOperand(OperandVector &);
551   OperandMatchResultTy parseCoprocOptionOperand(OperandVector &);
552   OperandMatchResultTy parseMemBarrierOptOperand(OperandVector &);
553   OperandMatchResultTy parseTraceSyncBarrierOptOperand(OperandVector &);
554   OperandMatchResultTy parseInstSyncBarrierOptOperand(OperandVector &);
555   OperandMatchResultTy parseProcIFlagsOperand(OperandVector &);
556   OperandMatchResultTy parseMSRMaskOperand(OperandVector &);
557   OperandMatchResultTy parseBankedRegOperand(OperandVector &);
558   OperandMatchResultTy parsePKHImm(OperandVector &O, StringRef Op, int Low,
559                                    int High);
560   OperandMatchResultTy parsePKHLSLImm(OperandVector &O) {
561     return parsePKHImm(O, "lsl", 0, 31);
562   }
563   OperandMatchResultTy parsePKHASRImm(OperandVector &O) {
564     return parsePKHImm(O, "asr", 1, 32);
565   }
566   OperandMatchResultTy parseSetEndImm(OperandVector &);
567   OperandMatchResultTy parseShifterImm(OperandVector &);
568   OperandMatchResultTy parseRotImm(OperandVector &);
569   OperandMatchResultTy parseModImm(OperandVector &);
570   OperandMatchResultTy parseBitfield(OperandVector &);
571   OperandMatchResultTy parsePostIdxReg(OperandVector &);
572   OperandMatchResultTy parseAM3Offset(OperandVector &);
573   OperandMatchResultTy parseFPImm(OperandVector &);
574   OperandMatchResultTy parseVectorList(OperandVector &);
575   OperandMatchResultTy parseVectorLane(VectorLaneTy &LaneKind, unsigned &Index,
576                                        SMLoc &EndLoc);
577 
578   // Asm Match Converter Methods
579   void cvtThumbMultiply(MCInst &Inst, const OperandVector &);
580   void cvtThumbBranches(MCInst &Inst, const OperandVector &);
581   void cvtMVEVMOVQtoDReg(MCInst &Inst, const OperandVector &);
582 
583   bool validateInstruction(MCInst &Inst, const OperandVector &Ops);
584   bool processInstruction(MCInst &Inst, const OperandVector &Ops, MCStreamer &Out);
585   bool shouldOmitCCOutOperand(StringRef Mnemonic, OperandVector &Operands);
586   bool shouldOmitPredicateOperand(StringRef Mnemonic, OperandVector &Operands);
587   bool shouldOmitVectorPredicateOperand(StringRef Mnemonic, OperandVector &Operands);
588   bool isITBlockTerminator(MCInst &Inst) const;
589   void fixupGNULDRDAlias(StringRef Mnemonic, OperandVector &Operands);
590   bool validateLDRDSTRD(MCInst &Inst, const OperandVector &Operands,
591                         bool Load, bool ARMMode, bool Writeback);
592 
593 public:
594   enum ARMMatchResultTy {
595     Match_RequiresITBlock = FIRST_TARGET_MATCH_RESULT_TY,
596     Match_RequiresNotITBlock,
597     Match_RequiresV6,
598     Match_RequiresThumb2,
599     Match_RequiresV8,
600     Match_RequiresFlagSetting,
601 #define GET_OPERAND_DIAGNOSTIC_TYPES
602 #include "ARMGenAsmMatcher.inc"
603 
604   };
605 
606   ARMAsmParser(const MCSubtargetInfo &STI, MCAsmParser &Parser,
607                const MCInstrInfo &MII, const MCTargetOptions &Options)
608     : MCTargetAsmParser(Options, STI, MII), UC(Parser) {
609     MCAsmParserExtension::Initialize(Parser);
610 
611     // Cache the MCRegisterInfo.
612     MRI = getContext().getRegisterInfo();
613 
614     // Initialize the set of available features.
615     setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
616 
617     // Add build attributes based on the selected target.
618     if (AddBuildAttributes)
619       getTargetStreamer().emitTargetAttributes(STI);
620 
621     // Not in an ITBlock to start with.
622     ITState.CurPosition = ~0U;
623 
624     VPTState.CurPosition = ~0U;
625 
626     NextSymbolIsThumb = false;
627   }
628 
629   // Implementation of the MCTargetAsmParser interface:
630   bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc) override;
631   bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
632                         SMLoc NameLoc, OperandVector &Operands) override;
633   bool ParseDirective(AsmToken DirectiveID) override;
634 
635   unsigned validateTargetOperandClass(MCParsedAsmOperand &Op,
636                                       unsigned Kind) override;
637   unsigned checkTargetMatchPredicate(MCInst &Inst) override;
638 
639   bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
640                                OperandVector &Operands, MCStreamer &Out,
641                                uint64_t &ErrorInfo,
642                                bool MatchingInlineAsm) override;
643   unsigned MatchInstruction(OperandVector &Operands, MCInst &Inst,
644                             SmallVectorImpl<NearMissInfo> &NearMisses,
645                             bool MatchingInlineAsm, bool &EmitInITBlock,
646                             MCStreamer &Out);
647 
648   struct NearMissMessage {
649     SMLoc Loc;
650     SmallString<128> Message;
651   };
652 
653   const char *getCustomOperandDiag(ARMMatchResultTy MatchError);
654 
655   void FilterNearMisses(SmallVectorImpl<NearMissInfo> &NearMissesIn,
656                         SmallVectorImpl<NearMissMessage> &NearMissesOut,
657                         SMLoc IDLoc, OperandVector &Operands);
658   void ReportNearMisses(SmallVectorImpl<NearMissInfo> &NearMisses, SMLoc IDLoc,
659                         OperandVector &Operands);
660 
661   void doBeforeLabelEmit(MCSymbol *Symbol) override;
662 
663   void onLabelParsed(MCSymbol *Symbol) override;
664 };
665 
666 /// ARMOperand - Instances of this class represent a parsed ARM machine
667 /// operand.
668 class ARMOperand : public MCParsedAsmOperand {
669   enum KindTy {
670     k_CondCode,
671     k_VPTPred,
672     k_CCOut,
673     k_ITCondMask,
674     k_CoprocNum,
675     k_CoprocReg,
676     k_CoprocOption,
677     k_Immediate,
678     k_MemBarrierOpt,
679     k_InstSyncBarrierOpt,
680     k_TraceSyncBarrierOpt,
681     k_Memory,
682     k_PostIndexRegister,
683     k_MSRMask,
684     k_BankedReg,
685     k_ProcIFlags,
686     k_VectorIndex,
687     k_Register,
688     k_RegisterList,
689     k_RegisterListWithAPSR,
690     k_DPRRegisterList,
691     k_SPRRegisterList,
692     k_FPSRegisterListWithVPR,
693     k_FPDRegisterListWithVPR,
694     k_VectorList,
695     k_VectorListAllLanes,
696     k_VectorListIndexed,
697     k_ShiftedRegister,
698     k_ShiftedImmediate,
699     k_ShifterImmediate,
700     k_RotateImmediate,
701     k_ModifiedImmediate,
702     k_ConstantPoolImmediate,
703     k_BitfieldDescriptor,
704     k_Token,
705   } Kind;
706 
707   SMLoc StartLoc, EndLoc, AlignmentLoc;
708   SmallVector<unsigned, 8> Registers;
709 
710   struct CCOp {
711     ARMCC::CondCodes Val;
712   };
713 
714   struct VCCOp {
715     ARMVCC::VPTCodes Val;
716   };
717 
718   struct CopOp {
719     unsigned Val;
720   };
721 
722   struct CoprocOptionOp {
723     unsigned Val;
724   };
725 
726   struct ITMaskOp {
727     unsigned Mask:4;
728   };
729 
730   struct MBOptOp {
731     ARM_MB::MemBOpt Val;
732   };
733 
734   struct ISBOptOp {
735     ARM_ISB::InstSyncBOpt Val;
736   };
737 
738   struct TSBOptOp {
739     ARM_TSB::TraceSyncBOpt Val;
740   };
741 
742   struct IFlagsOp {
743     ARM_PROC::IFlags Val;
744   };
745 
746   struct MMaskOp {
747     unsigned Val;
748   };
749 
750   struct BankedRegOp {
751     unsigned Val;
752   };
753 
754   struct TokOp {
755     const char *Data;
756     unsigned Length;
757   };
758 
759   struct RegOp {
760     unsigned RegNum;
761   };
762 
763   // A vector register list is a sequential list of 1 to 4 registers.
764   struct VectorListOp {
765     unsigned RegNum;
766     unsigned Count;
767     unsigned LaneIndex;
768     bool isDoubleSpaced;
769   };
770 
771   struct VectorIndexOp {
772     unsigned Val;
773   };
774 
775   struct ImmOp {
776     const MCExpr *Val;
777   };
778 
779   /// Combined record for all forms of ARM address expressions.
780   struct MemoryOp {
781     unsigned BaseRegNum;
782     // Offset is in OffsetReg or OffsetImm. If both are zero, no offset
783     // was specified.
784     const MCConstantExpr *OffsetImm;  // Offset immediate value
785     unsigned OffsetRegNum;    // Offset register num, when OffsetImm == NULL
786     ARM_AM::ShiftOpc ShiftType; // Shift type for OffsetReg
787     unsigned ShiftImm;        // shift for OffsetReg.
788     unsigned Alignment;       // 0 = no alignment specified
789     // n = alignment in bytes (2, 4, 8, 16, or 32)
790     unsigned isNegative : 1;  // Negated OffsetReg? (~'U' bit)
791   };
792 
793   struct PostIdxRegOp {
794     unsigned RegNum;
795     bool isAdd;
796     ARM_AM::ShiftOpc ShiftTy;
797     unsigned ShiftImm;
798   };
799 
800   struct ShifterImmOp {
801     bool isASR;
802     unsigned Imm;
803   };
804 
805   struct RegShiftedRegOp {
806     ARM_AM::ShiftOpc ShiftTy;
807     unsigned SrcReg;
808     unsigned ShiftReg;
809     unsigned ShiftImm;
810   };
811 
812   struct RegShiftedImmOp {
813     ARM_AM::ShiftOpc ShiftTy;
814     unsigned SrcReg;
815     unsigned ShiftImm;
816   };
817 
818   struct RotImmOp {
819     unsigned Imm;
820   };
821 
822   struct ModImmOp {
823     unsigned Bits;
824     unsigned Rot;
825   };
826 
827   struct BitfieldOp {
828     unsigned LSB;
829     unsigned Width;
830   };
831 
832   union {
833     struct CCOp CC;
834     struct VCCOp VCC;
835     struct CopOp Cop;
836     struct CoprocOptionOp CoprocOption;
837     struct MBOptOp MBOpt;
838     struct ISBOptOp ISBOpt;
839     struct TSBOptOp TSBOpt;
840     struct ITMaskOp ITMask;
841     struct IFlagsOp IFlags;
842     struct MMaskOp MMask;
843     struct BankedRegOp BankedReg;
844     struct TokOp Tok;
845     struct RegOp Reg;
846     struct VectorListOp VectorList;
847     struct VectorIndexOp VectorIndex;
848     struct ImmOp Imm;
849     struct MemoryOp Memory;
850     struct PostIdxRegOp PostIdxReg;
851     struct ShifterImmOp ShifterImm;
852     struct RegShiftedRegOp RegShiftedReg;
853     struct RegShiftedImmOp RegShiftedImm;
854     struct RotImmOp RotImm;
855     struct ModImmOp ModImm;
856     struct BitfieldOp Bitfield;
857   };
858 
859 public:
860   ARMOperand(KindTy K) : MCParsedAsmOperand(), Kind(K) {}
861 
862   /// getStartLoc - Get the location of the first token of this operand.
863   SMLoc getStartLoc() const override { return StartLoc; }
864 
865   /// getEndLoc - Get the location of the last token of this operand.
866   SMLoc getEndLoc() const override { return EndLoc; }
867 
868   /// getLocRange - Get the range between the first and last token of this
869   /// operand.
870   SMRange getLocRange() const { return SMRange(StartLoc, EndLoc); }
871 
872   /// getAlignmentLoc - Get the location of the Alignment token of this operand.
873   SMLoc getAlignmentLoc() const {
874     assert(Kind == k_Memory && "Invalid access!");
875     return AlignmentLoc;
876   }
877 
878   ARMCC::CondCodes getCondCode() const {
879     assert(Kind == k_CondCode && "Invalid access!");
880     return CC.Val;
881   }
882 
883   ARMVCC::VPTCodes getVPTPred() const {
884     assert(isVPTPred() && "Invalid access!");
885     return VCC.Val;
886   }
887 
888   unsigned getCoproc() const {
889     assert((Kind == k_CoprocNum || Kind == k_CoprocReg) && "Invalid access!");
890     return Cop.Val;
891   }
892 
893   StringRef getToken() const {
894     assert(Kind == k_Token && "Invalid access!");
895     return StringRef(Tok.Data, Tok.Length);
896   }
897 
898   unsigned getReg() const override {
899     assert((Kind == k_Register || Kind == k_CCOut) && "Invalid access!");
900     return Reg.RegNum;
901   }
902 
903   const SmallVectorImpl<unsigned> &getRegList() const {
904     assert((Kind == k_RegisterList || Kind == k_RegisterListWithAPSR ||
905             Kind == k_DPRRegisterList || Kind == k_SPRRegisterList ||
906             Kind == k_FPSRegisterListWithVPR ||
907             Kind == k_FPDRegisterListWithVPR) &&
908            "Invalid access!");
909     return Registers;
910   }
911 
912   const MCExpr *getImm() const {
913     assert(isImm() && "Invalid access!");
914     return Imm.Val;
915   }
916 
917   const MCExpr *getConstantPoolImm() const {
918     assert(isConstantPoolImm() && "Invalid access!");
919     return Imm.Val;
920   }
921 
922   unsigned getVectorIndex() const {
923     assert(Kind == k_VectorIndex && "Invalid access!");
924     return VectorIndex.Val;
925   }
926 
927   ARM_MB::MemBOpt getMemBarrierOpt() const {
928     assert(Kind == k_MemBarrierOpt && "Invalid access!");
929     return MBOpt.Val;
930   }
931 
932   ARM_ISB::InstSyncBOpt getInstSyncBarrierOpt() const {
933     assert(Kind == k_InstSyncBarrierOpt && "Invalid access!");
934     return ISBOpt.Val;
935   }
936 
937   ARM_TSB::TraceSyncBOpt getTraceSyncBarrierOpt() const {
938     assert(Kind == k_TraceSyncBarrierOpt && "Invalid access!");
939     return TSBOpt.Val;
940   }
941 
942   ARM_PROC::IFlags getProcIFlags() const {
943     assert(Kind == k_ProcIFlags && "Invalid access!");
944     return IFlags.Val;
945   }
946 
947   unsigned getMSRMask() const {
948     assert(Kind == k_MSRMask && "Invalid access!");
949     return MMask.Val;
950   }
951 
952   unsigned getBankedReg() const {
953     assert(Kind == k_BankedReg && "Invalid access!");
954     return BankedReg.Val;
955   }
956 
957   bool isCoprocNum() const { return Kind == k_CoprocNum; }
958   bool isCoprocReg() const { return Kind == k_CoprocReg; }
959   bool isCoprocOption() const { return Kind == k_CoprocOption; }
960   bool isCondCode() const { return Kind == k_CondCode; }
961   bool isVPTPred() const { return Kind == k_VPTPred; }
962   bool isCCOut() const { return Kind == k_CCOut; }
963   bool isITMask() const { return Kind == k_ITCondMask; }
964   bool isITCondCode() const { return Kind == k_CondCode; }
965   bool isImm() const override {
966     return Kind == k_Immediate;
967   }
968 
969   bool isARMBranchTarget() const {
970     if (!isImm()) return false;
971 
972     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm()))
973       return CE->getValue() % 4 == 0;
974     return true;
975   }
976 
977 
978   bool isThumbBranchTarget() const {
979     if (!isImm()) return false;
980 
981     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm()))
982       return CE->getValue() % 2 == 0;
983     return true;
984   }
985 
986   // checks whether this operand is an unsigned offset which fits is a field
987   // of specified width and scaled by a specific number of bits
988   template<unsigned width, unsigned scale>
989   bool isUnsignedOffset() const {
990     if (!isImm()) return false;
991     if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
992     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val)) {
993       int64_t Val = CE->getValue();
994       int64_t Align = 1LL << scale;
995       int64_t Max = Align * ((1LL << width) - 1);
996       return ((Val % Align) == 0) && (Val >= 0) && (Val <= Max);
997     }
998     return false;
999   }
1000 
1001   // checks whether this operand is an signed offset which fits is a field
1002   // of specified width and scaled by a specific number of bits
1003   template<unsigned width, unsigned scale>
1004   bool isSignedOffset() const {
1005     if (!isImm()) return false;
1006     if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
1007     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val)) {
1008       int64_t Val = CE->getValue();
1009       int64_t Align = 1LL << scale;
1010       int64_t Max = Align * ((1LL << (width-1)) - 1);
1011       int64_t Min = -Align * (1LL << (width-1));
1012       return ((Val % Align) == 0) && (Val >= Min) && (Val <= Max);
1013     }
1014     return false;
1015   }
1016 
1017   // checks whether this operand is an offset suitable for the LE /
1018   // LETP instructions in Arm v8.1M
1019   bool isLEOffset() const {
1020     if (!isImm()) return false;
1021     if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
1022     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val)) {
1023       int64_t Val = CE->getValue();
1024       return Val < 0 && Val >= -4094 && (Val & 1) == 0;
1025     }
1026     return false;
1027   }
1028 
1029   // checks whether this operand is a memory operand computed as an offset
1030   // applied to PC. the offset may have 8 bits of magnitude and is represented
1031   // with two bits of shift. textually it may be either [pc, #imm], #imm or
1032   // relocable expression...
1033   bool isThumbMemPC() const {
1034     int64_t Val = 0;
1035     if (isImm()) {
1036       if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
1037       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val);
1038       if (!CE) return false;
1039       Val = CE->getValue();
1040     }
1041     else if (isGPRMem()) {
1042       if(!Memory.OffsetImm || Memory.OffsetRegNum) return false;
1043       if(Memory.BaseRegNum != ARM::PC) return false;
1044       Val = Memory.OffsetImm->getValue();
1045     }
1046     else return false;
1047     return ((Val % 4) == 0) && (Val >= 0) && (Val <= 1020);
1048   }
1049 
1050   bool isFPImm() const {
1051     if (!isImm()) return false;
1052     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1053     if (!CE) return false;
1054     int Val = ARM_AM::getFP32Imm(APInt(32, CE->getValue()));
1055     return Val != -1;
1056   }
1057 
1058   template<int64_t N, int64_t M>
1059   bool isImmediate() const {
1060     if (!isImm()) return false;
1061     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1062     if (!CE) return false;
1063     int64_t Value = CE->getValue();
1064     return Value >= N && Value <= M;
1065   }
1066 
1067   template<int64_t N, int64_t M>
1068   bool isImmediateS4() const {
1069     if (!isImm()) return false;
1070     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1071     if (!CE) return false;
1072     int64_t Value = CE->getValue();
1073     return ((Value & 3) == 0) && Value >= N && Value <= M;
1074   }
1075   template<int64_t N, int64_t M>
1076   bool isImmediateS2() const {
1077     if (!isImm()) return false;
1078     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1079     if (!CE) return false;
1080     int64_t Value = CE->getValue();
1081     return ((Value & 1) == 0) && Value >= N && Value <= M;
1082   }
1083   bool isFBits16() const {
1084     return isImmediate<0, 17>();
1085   }
1086   bool isFBits32() const {
1087     return isImmediate<1, 33>();
1088   }
1089   bool isImm8s4() const {
1090     return isImmediateS4<-1020, 1020>();
1091   }
1092   bool isImm7s4() const {
1093     return isImmediateS4<-508, 508>();
1094   }
1095   bool isImm7Shift0() const {
1096     return isImmediate<-127, 127>();
1097   }
1098   bool isImm7Shift1() const {
1099     return isImmediateS2<-255, 255>();
1100   }
1101   bool isImm7Shift2() const {
1102     return isImmediateS4<-511, 511>();
1103   }
1104   bool isImm7() const {
1105     return isImmediate<-127, 127>();
1106   }
1107   bool isImm0_1020s4() const {
1108     return isImmediateS4<0, 1020>();
1109   }
1110   bool isImm0_508s4() const {
1111     return isImmediateS4<0, 508>();
1112   }
1113   bool isImm0_508s4Neg() const {
1114     if (!isImm()) return false;
1115     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1116     if (!CE) return false;
1117     int64_t Value = -CE->getValue();
1118     // explicitly exclude zero. we want that to use the normal 0_508 version.
1119     return ((Value & 3) == 0) && Value > 0 && Value <= 508;
1120   }
1121 
1122   bool isImm0_4095Neg() const {
1123     if (!isImm()) return false;
1124     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1125     if (!CE) return false;
1126     // isImm0_4095Neg is used with 32-bit immediates only.
1127     // 32-bit immediates are zero extended to 64-bit when parsed,
1128     // thus simple -CE->getValue() results in a big negative number,
1129     // not a small positive number as intended
1130     if ((CE->getValue() >> 32) > 0) return false;
1131     uint32_t Value = -static_cast<uint32_t>(CE->getValue());
1132     return Value > 0 && Value < 4096;
1133   }
1134 
1135   bool isImm0_7() const {
1136     return isImmediate<0, 7>();
1137   }
1138 
1139   bool isImm1_16() const {
1140     return isImmediate<1, 16>();
1141   }
1142 
1143   bool isImm1_32() const {
1144     return isImmediate<1, 32>();
1145   }
1146 
1147   bool isImm8_255() const {
1148     return isImmediate<8, 255>();
1149   }
1150 
1151   bool isImm256_65535Expr() const {
1152     if (!isImm()) return false;
1153     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1154     // If it's not a constant expression, it'll generate a fixup and be
1155     // handled later.
1156     if (!CE) return true;
1157     int64_t Value = CE->getValue();
1158     return Value >= 256 && Value < 65536;
1159   }
1160 
1161   bool isImm0_65535Expr() const {
1162     if (!isImm()) return false;
1163     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1164     // If it's not a constant expression, it'll generate a fixup and be
1165     // handled later.
1166     if (!CE) return true;
1167     int64_t Value = CE->getValue();
1168     return Value >= 0 && Value < 65536;
1169   }
1170 
1171   bool isImm24bit() const {
1172     return isImmediate<0, 0xffffff + 1>();
1173   }
1174 
1175   bool isImmThumbSR() const {
1176     return isImmediate<1, 33>();
1177   }
1178 
1179   template<int shift>
1180   bool isExpImmValue(uint64_t Value) const {
1181     uint64_t mask = (1 << shift) - 1;
1182     if ((Value & mask) != 0 || (Value >> shift) > 0xff)
1183       return false;
1184     return true;
1185   }
1186 
1187   template<int shift>
1188   bool isExpImm() const {
1189     if (!isImm()) return false;
1190     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1191     if (!CE) return false;
1192 
1193     return isExpImmValue<shift>(CE->getValue());
1194   }
1195 
1196   template<int shift, int size>
1197   bool isInvertedExpImm() const {
1198     if (!isImm()) return false;
1199     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1200     if (!CE) return false;
1201 
1202     uint64_t OriginalValue = CE->getValue();
1203     uint64_t InvertedValue = OriginalValue ^ (((uint64_t)1 << size) - 1);
1204     return isExpImmValue<shift>(InvertedValue);
1205   }
1206 
1207   bool isPKHLSLImm() const {
1208     return isImmediate<0, 32>();
1209   }
1210 
1211   bool isPKHASRImm() const {
1212     return isImmediate<0, 33>();
1213   }
1214 
1215   bool isAdrLabel() const {
1216     // If we have an immediate that's not a constant, treat it as a label
1217     // reference needing a fixup.
1218     if (isImm() && !isa<MCConstantExpr>(getImm()))
1219       return true;
1220 
1221     // If it is a constant, it must fit into a modified immediate encoding.
1222     if (!isImm()) return false;
1223     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1224     if (!CE) return false;
1225     int64_t Value = CE->getValue();
1226     return (ARM_AM::getSOImmVal(Value) != -1 ||
1227             ARM_AM::getSOImmVal(-Value) != -1);
1228   }
1229 
1230   bool isT2SOImm() const {
1231     // If we have an immediate that's not a constant, treat it as an expression
1232     // needing a fixup.
1233     if (isImm() && !isa<MCConstantExpr>(getImm())) {
1234       // We want to avoid matching :upper16: and :lower16: as we want these
1235       // expressions to match in isImm0_65535Expr()
1236       const ARMMCExpr *ARM16Expr = dyn_cast<ARMMCExpr>(getImm());
1237       return (!ARM16Expr || (ARM16Expr->getKind() != ARMMCExpr::VK_ARM_HI16 &&
1238                              ARM16Expr->getKind() != ARMMCExpr::VK_ARM_LO16));
1239     }
1240     if (!isImm()) return false;
1241     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1242     if (!CE) return false;
1243     int64_t Value = CE->getValue();
1244     return ARM_AM::getT2SOImmVal(Value) != -1;
1245   }
1246 
1247   bool isT2SOImmNot() const {
1248     if (!isImm()) return false;
1249     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1250     if (!CE) return false;
1251     int64_t Value = CE->getValue();
1252     return ARM_AM::getT2SOImmVal(Value) == -1 &&
1253       ARM_AM::getT2SOImmVal(~Value) != -1;
1254   }
1255 
1256   bool isT2SOImmNeg() const {
1257     if (!isImm()) return false;
1258     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1259     if (!CE) return false;
1260     int64_t Value = CE->getValue();
1261     // Only use this when not representable as a plain so_imm.
1262     return ARM_AM::getT2SOImmVal(Value) == -1 &&
1263       ARM_AM::getT2SOImmVal(-Value) != -1;
1264   }
1265 
1266   bool isSetEndImm() const {
1267     if (!isImm()) return false;
1268     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1269     if (!CE) return false;
1270     int64_t Value = CE->getValue();
1271     return Value == 1 || Value == 0;
1272   }
1273 
1274   bool isReg() const override { return Kind == k_Register; }
1275   bool isRegList() const { return Kind == k_RegisterList; }
1276   bool isRegListWithAPSR() const {
1277     return Kind == k_RegisterListWithAPSR || Kind == k_RegisterList;
1278   }
1279   bool isDPRRegList() const { return Kind == k_DPRRegisterList; }
1280   bool isSPRRegList() const { return Kind == k_SPRRegisterList; }
1281   bool isFPSRegListWithVPR() const { return Kind == k_FPSRegisterListWithVPR; }
1282   bool isFPDRegListWithVPR() const { return Kind == k_FPDRegisterListWithVPR; }
1283   bool isToken() const override { return Kind == k_Token; }
1284   bool isMemBarrierOpt() const { return Kind == k_MemBarrierOpt; }
1285   bool isInstSyncBarrierOpt() const { return Kind == k_InstSyncBarrierOpt; }
1286   bool isTraceSyncBarrierOpt() const { return Kind == k_TraceSyncBarrierOpt; }
1287   bool isMem() const override {
1288       return isGPRMem() || isMVEMem();
1289   }
1290   bool isMVEMem() const {
1291     if (Kind != k_Memory)
1292       return false;
1293     if (Memory.BaseRegNum &&
1294         !ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Memory.BaseRegNum) &&
1295         !ARMMCRegisterClasses[ARM::MQPRRegClassID].contains(Memory.BaseRegNum))
1296       return false;
1297     if (Memory.OffsetRegNum &&
1298         !ARMMCRegisterClasses[ARM::MQPRRegClassID].contains(
1299             Memory.OffsetRegNum))
1300       return false;
1301     return true;
1302   }
1303   bool isGPRMem() const {
1304     if (Kind != k_Memory)
1305       return false;
1306     if (Memory.BaseRegNum &&
1307         !ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Memory.BaseRegNum))
1308       return false;
1309     if (Memory.OffsetRegNum &&
1310         !ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Memory.OffsetRegNum))
1311       return false;
1312     return true;
1313   }
1314   bool isShifterImm() const { return Kind == k_ShifterImmediate; }
1315   bool isRegShiftedReg() const {
1316     return Kind == k_ShiftedRegister &&
1317            ARMMCRegisterClasses[ARM::GPRRegClassID].contains(
1318                RegShiftedReg.SrcReg) &&
1319            ARMMCRegisterClasses[ARM::GPRRegClassID].contains(
1320                RegShiftedReg.ShiftReg);
1321   }
1322   bool isRegShiftedImm() const {
1323     return Kind == k_ShiftedImmediate &&
1324            ARMMCRegisterClasses[ARM::GPRRegClassID].contains(
1325                RegShiftedImm.SrcReg);
1326   }
1327   bool isRotImm() const { return Kind == k_RotateImmediate; }
1328 
1329   template<unsigned Min, unsigned Max>
1330   bool isPowerTwoInRange() const {
1331     if (!isImm()) return false;
1332     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1333     if (!CE) return false;
1334     int64_t Value = CE->getValue();
1335     return Value > 0 && countPopulation((uint64_t)Value) == 1 &&
1336            Value >= Min && Value <= Max;
1337   }
1338   bool isModImm() const { return Kind == k_ModifiedImmediate; }
1339 
1340   bool isModImmNot() const {
1341     if (!isImm()) return false;
1342     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1343     if (!CE) return false;
1344     int64_t Value = CE->getValue();
1345     return ARM_AM::getSOImmVal(~Value) != -1;
1346   }
1347 
1348   bool isModImmNeg() const {
1349     if (!isImm()) return false;
1350     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1351     if (!CE) return false;
1352     int64_t Value = CE->getValue();
1353     return ARM_AM::getSOImmVal(Value) == -1 &&
1354       ARM_AM::getSOImmVal(-Value) != -1;
1355   }
1356 
1357   bool isThumbModImmNeg1_7() const {
1358     if (!isImm()) return false;
1359     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1360     if (!CE) return false;
1361     int32_t Value = -(int32_t)CE->getValue();
1362     return 0 < Value && Value < 8;
1363   }
1364 
1365   bool isThumbModImmNeg8_255() const {
1366     if (!isImm()) return false;
1367     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1368     if (!CE) return false;
1369     int32_t Value = -(int32_t)CE->getValue();
1370     return 7 < Value && Value < 256;
1371   }
1372 
1373   bool isConstantPoolImm() const { return Kind == k_ConstantPoolImmediate; }
1374   bool isBitfield() const { return Kind == k_BitfieldDescriptor; }
1375   bool isPostIdxRegShifted() const {
1376     return Kind == k_PostIndexRegister &&
1377            ARMMCRegisterClasses[ARM::GPRRegClassID].contains(PostIdxReg.RegNum);
1378   }
1379   bool isPostIdxReg() const {
1380     return isPostIdxRegShifted() && PostIdxReg.ShiftTy == ARM_AM::no_shift;
1381   }
1382   bool isMemNoOffset(bool alignOK = false, unsigned Alignment = 0) const {
1383     if (!isGPRMem())
1384       return false;
1385     // No offset of any kind.
1386     return Memory.OffsetRegNum == 0 && Memory.OffsetImm == nullptr &&
1387      (alignOK || Memory.Alignment == Alignment);
1388   }
1389   bool isMemNoOffsetT2(bool alignOK = false, unsigned Alignment = 0) const {
1390     if (!isGPRMem())
1391       return false;
1392 
1393     if (!ARMMCRegisterClasses[ARM::GPRnopcRegClassID].contains(
1394             Memory.BaseRegNum))
1395       return false;
1396 
1397     // No offset of any kind.
1398     return Memory.OffsetRegNum == 0 && Memory.OffsetImm == nullptr &&
1399      (alignOK || Memory.Alignment == Alignment);
1400   }
1401   bool isMemNoOffsetT2NoSp(bool alignOK = false, unsigned Alignment = 0) const {
1402     if (!isGPRMem())
1403       return false;
1404 
1405     if (!ARMMCRegisterClasses[ARM::rGPRRegClassID].contains(
1406             Memory.BaseRegNum))
1407       return false;
1408 
1409     // No offset of any kind.
1410     return Memory.OffsetRegNum == 0 && Memory.OffsetImm == nullptr &&
1411      (alignOK || Memory.Alignment == Alignment);
1412   }
1413   bool isMemNoOffsetT(bool alignOK = false, unsigned Alignment = 0) const {
1414     if (!isGPRMem())
1415       return false;
1416 
1417     if (!ARMMCRegisterClasses[ARM::tGPRRegClassID].contains(
1418             Memory.BaseRegNum))
1419       return false;
1420 
1421     // No offset of any kind.
1422     return Memory.OffsetRegNum == 0 && Memory.OffsetImm == nullptr &&
1423      (alignOK || Memory.Alignment == Alignment);
1424   }
1425   bool isMemPCRelImm12() const {
1426     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1427       return false;
1428     // Base register must be PC.
1429     if (Memory.BaseRegNum != ARM::PC)
1430       return false;
1431     // Immediate offset in range [-4095, 4095].
1432     if (!Memory.OffsetImm) return true;
1433     int64_t Val = Memory.OffsetImm->getValue();
1434     return (Val > -4096 && Val < 4096) ||
1435            (Val == std::numeric_limits<int32_t>::min());
1436   }
1437 
1438   bool isAlignedMemory() const {
1439     return isMemNoOffset(true);
1440   }
1441 
1442   bool isAlignedMemoryNone() const {
1443     return isMemNoOffset(false, 0);
1444   }
1445 
1446   bool isDupAlignedMemoryNone() const {
1447     return isMemNoOffset(false, 0);
1448   }
1449 
1450   bool isAlignedMemory16() const {
1451     if (isMemNoOffset(false, 2)) // alignment in bytes for 16-bits is 2.
1452       return true;
1453     return isMemNoOffset(false, 0);
1454   }
1455 
1456   bool isDupAlignedMemory16() const {
1457     if (isMemNoOffset(false, 2)) // alignment in bytes for 16-bits is 2.
1458       return true;
1459     return isMemNoOffset(false, 0);
1460   }
1461 
1462   bool isAlignedMemory32() const {
1463     if (isMemNoOffset(false, 4)) // alignment in bytes for 32-bits is 4.
1464       return true;
1465     return isMemNoOffset(false, 0);
1466   }
1467 
1468   bool isDupAlignedMemory32() const {
1469     if (isMemNoOffset(false, 4)) // alignment in bytes for 32-bits is 4.
1470       return true;
1471     return isMemNoOffset(false, 0);
1472   }
1473 
1474   bool isAlignedMemory64() const {
1475     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1476       return true;
1477     return isMemNoOffset(false, 0);
1478   }
1479 
1480   bool isDupAlignedMemory64() const {
1481     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1482       return true;
1483     return isMemNoOffset(false, 0);
1484   }
1485 
1486   bool isAlignedMemory64or128() const {
1487     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1488       return true;
1489     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1490       return true;
1491     return isMemNoOffset(false, 0);
1492   }
1493 
1494   bool isDupAlignedMemory64or128() const {
1495     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1496       return true;
1497     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1498       return true;
1499     return isMemNoOffset(false, 0);
1500   }
1501 
1502   bool isAlignedMemory64or128or256() const {
1503     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1504       return true;
1505     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1506       return true;
1507     if (isMemNoOffset(false, 32)) // alignment in bytes for 256-bits is 32.
1508       return true;
1509     return isMemNoOffset(false, 0);
1510   }
1511 
1512   bool isAddrMode2() const {
1513     if (!isGPRMem() || Memory.Alignment != 0) return false;
1514     // Check for register offset.
1515     if (Memory.OffsetRegNum) return true;
1516     // Immediate offset in range [-4095, 4095].
1517     if (!Memory.OffsetImm) return true;
1518     int64_t Val = Memory.OffsetImm->getValue();
1519     return Val > -4096 && Val < 4096;
1520   }
1521 
1522   bool isAM2OffsetImm() const {
1523     if (!isImm()) return false;
1524     // Immediate offset in range [-4095, 4095].
1525     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1526     if (!CE) return false;
1527     int64_t Val = CE->getValue();
1528     return (Val == std::numeric_limits<int32_t>::min()) ||
1529            (Val > -4096 && Val < 4096);
1530   }
1531 
1532   bool isAddrMode3() const {
1533     // If we have an immediate that's not a constant, treat it as a label
1534     // reference needing a fixup. If it is a constant, it's something else
1535     // and we reject it.
1536     if (isImm() && !isa<MCConstantExpr>(getImm()))
1537       return true;
1538     if (!isGPRMem() || Memory.Alignment != 0) return false;
1539     // No shifts are legal for AM3.
1540     if (Memory.ShiftType != ARM_AM::no_shift) return false;
1541     // Check for register offset.
1542     if (Memory.OffsetRegNum) return true;
1543     // Immediate offset in range [-255, 255].
1544     if (!Memory.OffsetImm) return true;
1545     int64_t Val = Memory.OffsetImm->getValue();
1546     // The #-0 offset is encoded as std::numeric_limits<int32_t>::min(), and we
1547     // have to check for this too.
1548     return (Val > -256 && Val < 256) ||
1549            Val == std::numeric_limits<int32_t>::min();
1550   }
1551 
1552   bool isAM3Offset() const {
1553     if (isPostIdxReg())
1554       return true;
1555     if (!isImm())
1556       return false;
1557     // Immediate offset in range [-255, 255].
1558     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1559     if (!CE) return false;
1560     int64_t Val = CE->getValue();
1561     // Special case, #-0 is std::numeric_limits<int32_t>::min().
1562     return (Val > -256 && Val < 256) ||
1563            Val == std::numeric_limits<int32_t>::min();
1564   }
1565 
1566   bool isAddrMode5() const {
1567     // If we have an immediate that's not a constant, treat it as a label
1568     // reference needing a fixup. If it is a constant, it's something else
1569     // and we reject it.
1570     if (isImm() && !isa<MCConstantExpr>(getImm()))
1571       return true;
1572     if (!isGPRMem() || Memory.Alignment != 0) return false;
1573     // Check for register offset.
1574     if (Memory.OffsetRegNum) return false;
1575     // Immediate offset in range [-1020, 1020] and a multiple of 4.
1576     if (!Memory.OffsetImm) return true;
1577     int64_t Val = Memory.OffsetImm->getValue();
1578     return (Val >= -1020 && Val <= 1020 && ((Val & 3) == 0)) ||
1579       Val == std::numeric_limits<int32_t>::min();
1580   }
1581 
1582   bool isAddrMode5FP16() const {
1583     // If we have an immediate that's not a constant, treat it as a label
1584     // reference needing a fixup. If it is a constant, it's something else
1585     // and we reject it.
1586     if (isImm() && !isa<MCConstantExpr>(getImm()))
1587       return true;
1588     if (!isGPRMem() || Memory.Alignment != 0) return false;
1589     // Check for register offset.
1590     if (Memory.OffsetRegNum) return false;
1591     // Immediate offset in range [-510, 510] and a multiple of 2.
1592     if (!Memory.OffsetImm) return true;
1593     int64_t Val = Memory.OffsetImm->getValue();
1594     return (Val >= -510 && Val <= 510 && ((Val & 1) == 0)) ||
1595            Val == std::numeric_limits<int32_t>::min();
1596   }
1597 
1598   bool isMemTBB() const {
1599     if (!isGPRMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1600         Memory.ShiftType != ARM_AM::no_shift || Memory.Alignment != 0)
1601       return false;
1602     return true;
1603   }
1604 
1605   bool isMemTBH() const {
1606     if (!isGPRMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1607         Memory.ShiftType != ARM_AM::lsl || Memory.ShiftImm != 1 ||
1608         Memory.Alignment != 0 )
1609       return false;
1610     return true;
1611   }
1612 
1613   bool isMemRegOffset() const {
1614     if (!isGPRMem() || !Memory.OffsetRegNum || Memory.Alignment != 0)
1615       return false;
1616     return true;
1617   }
1618 
1619   bool isT2MemRegOffset() const {
1620     if (!isGPRMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1621         Memory.Alignment != 0 || Memory.BaseRegNum == ARM::PC)
1622       return false;
1623     // Only lsl #{0, 1, 2, 3} allowed.
1624     if (Memory.ShiftType == ARM_AM::no_shift)
1625       return true;
1626     if (Memory.ShiftType != ARM_AM::lsl || Memory.ShiftImm > 3)
1627       return false;
1628     return true;
1629   }
1630 
1631   bool isMemThumbRR() const {
1632     // Thumb reg+reg addressing is simple. Just two registers, a base and
1633     // an offset. No shifts, negations or any other complicating factors.
1634     if (!isGPRMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1635         Memory.ShiftType != ARM_AM::no_shift || Memory.Alignment != 0)
1636       return false;
1637     return isARMLowRegister(Memory.BaseRegNum) &&
1638       (!Memory.OffsetRegNum || isARMLowRegister(Memory.OffsetRegNum));
1639   }
1640 
1641   bool isMemThumbRIs4() const {
1642     if (!isGPRMem() || Memory.OffsetRegNum != 0 ||
1643         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1644       return false;
1645     // Immediate offset, multiple of 4 in range [0, 124].
1646     if (!Memory.OffsetImm) return true;
1647     int64_t Val = Memory.OffsetImm->getValue();
1648     return Val >= 0 && Val <= 124 && (Val % 4) == 0;
1649   }
1650 
1651   bool isMemThumbRIs2() const {
1652     if (!isGPRMem() || Memory.OffsetRegNum != 0 ||
1653         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1654       return false;
1655     // Immediate offset, multiple of 4 in range [0, 62].
1656     if (!Memory.OffsetImm) return true;
1657     int64_t Val = Memory.OffsetImm->getValue();
1658     return Val >= 0 && Val <= 62 && (Val % 2) == 0;
1659   }
1660 
1661   bool isMemThumbRIs1() const {
1662     if (!isGPRMem() || Memory.OffsetRegNum != 0 ||
1663         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1664       return false;
1665     // Immediate offset in range [0, 31].
1666     if (!Memory.OffsetImm) return true;
1667     int64_t Val = Memory.OffsetImm->getValue();
1668     return Val >= 0 && Val <= 31;
1669   }
1670 
1671   bool isMemThumbSPI() const {
1672     if (!isGPRMem() || Memory.OffsetRegNum != 0 ||
1673         Memory.BaseRegNum != ARM::SP || Memory.Alignment != 0)
1674       return false;
1675     // Immediate offset, multiple of 4 in range [0, 1020].
1676     if (!Memory.OffsetImm) return true;
1677     int64_t Val = Memory.OffsetImm->getValue();
1678     return Val >= 0 && Val <= 1020 && (Val % 4) == 0;
1679   }
1680 
1681   bool isMemImm8s4Offset() const {
1682     // If we have an immediate that's not a constant, treat it as a label
1683     // reference needing a fixup. If it is a constant, it's something else
1684     // and we reject it.
1685     if (isImm() && !isa<MCConstantExpr>(getImm()))
1686       return true;
1687     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1688       return false;
1689     // Immediate offset a multiple of 4 in range [-1020, 1020].
1690     if (!Memory.OffsetImm) return true;
1691     int64_t Val = Memory.OffsetImm->getValue();
1692     // Special case, #-0 is std::numeric_limits<int32_t>::min().
1693     return (Val >= -1020 && Val <= 1020 && (Val & 3) == 0) ||
1694            Val == std::numeric_limits<int32_t>::min();
1695   }
1696   bool isMemImm7s4Offset() const {
1697     // If we have an immediate that's not a constant, treat it as a label
1698     // reference needing a fixup. If it is a constant, it's something else
1699     // and we reject it.
1700     if (isImm() && !isa<MCConstantExpr>(getImm()))
1701       return true;
1702     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0 ||
1703         !ARMMCRegisterClasses[ARM::GPRnopcRegClassID].contains(
1704             Memory.BaseRegNum))
1705       return false;
1706     // Immediate offset a multiple of 4 in range [-508, 508].
1707     if (!Memory.OffsetImm) return true;
1708     int64_t Val = Memory.OffsetImm->getValue();
1709     // Special case, #-0 is INT32_MIN.
1710     return (Val >= -508 && Val <= 508 && (Val & 3) == 0) || Val == INT32_MIN;
1711   }
1712   bool isMemImm0_1020s4Offset() const {
1713     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1714       return false;
1715     // Immediate offset a multiple of 4 in range [0, 1020].
1716     if (!Memory.OffsetImm) return true;
1717     int64_t Val = Memory.OffsetImm->getValue();
1718     return Val >= 0 && Val <= 1020 && (Val & 3) == 0;
1719   }
1720 
1721   bool isMemImm8Offset() const {
1722     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1723       return false;
1724     // Base reg of PC isn't allowed for these encodings.
1725     if (Memory.BaseRegNum == ARM::PC) return false;
1726     // Immediate offset in range [-255, 255].
1727     if (!Memory.OffsetImm) return true;
1728     int64_t Val = Memory.OffsetImm->getValue();
1729     return (Val == std::numeric_limits<int32_t>::min()) ||
1730            (Val > -256 && Val < 256);
1731   }
1732 
1733   template<unsigned Bits, unsigned RegClassID>
1734   bool isMemImm7ShiftedOffset() const {
1735     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0 ||
1736         !ARMMCRegisterClasses[RegClassID].contains(Memory.BaseRegNum))
1737       return false;
1738 
1739     // Expect an immediate offset equal to an element of the range
1740     // [-127, 127], shifted left by Bits.
1741 
1742     if (!Memory.OffsetImm) return true;
1743     int64_t Val = Memory.OffsetImm->getValue();
1744 
1745     // INT32_MIN is a special-case value (indicating the encoding with
1746     // zero offset and the subtract bit set)
1747     if (Val == INT32_MIN)
1748       return true;
1749 
1750     unsigned Divisor = 1U << Bits;
1751 
1752     // Check that the low bits are zero
1753     if (Val % Divisor != 0)
1754       return false;
1755 
1756     // Check that the remaining offset is within range.
1757     Val /= Divisor;
1758     return (Val >= -127 && Val <= 127);
1759   }
1760 
1761   template <int shift> bool isMemRegRQOffset() const {
1762     if (!isMVEMem() || Memory.OffsetImm != 0 || Memory.Alignment != 0)
1763       return false;
1764 
1765     if (!ARMMCRegisterClasses[ARM::GPRnopcRegClassID].contains(
1766             Memory.BaseRegNum))
1767       return false;
1768     if (!ARMMCRegisterClasses[ARM::MQPRRegClassID].contains(
1769             Memory.OffsetRegNum))
1770       return false;
1771 
1772     if (shift == 0 && Memory.ShiftType != ARM_AM::no_shift)
1773       return false;
1774 
1775     if (shift > 0 &&
1776         (Memory.ShiftType != ARM_AM::uxtw || Memory.ShiftImm != shift))
1777       return false;
1778 
1779     return true;
1780   }
1781 
1782   template <int shift> bool isMemRegQOffset() const {
1783     if (!isMVEMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1784       return false;
1785 
1786     if (!ARMMCRegisterClasses[ARM::MQPRRegClassID].contains(
1787             Memory.BaseRegNum))
1788       return false;
1789 
1790     if(!Memory.OffsetImm) return true;
1791     static_assert(shift < 56,
1792                   "Such that we dont shift by a value higher than 62");
1793     int64_t Val = Memory.OffsetImm->getValue();
1794 
1795     // The value must be a multiple of (1 << shift)
1796     if ((Val & ((1U << shift) - 1)) != 0)
1797       return false;
1798 
1799     // And be in the right range, depending on the amount that it is shifted
1800     // by.  Shift 0, is equal to 7 unsigned bits, the sign bit is set
1801     // separately.
1802     int64_t Range = (1U << (7+shift)) - 1;
1803     return (Val == INT32_MIN) || (Val > -Range && Val < Range);
1804   }
1805 
1806   bool isMemPosImm8Offset() const {
1807     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1808       return false;
1809     // Immediate offset in range [0, 255].
1810     if (!Memory.OffsetImm) return true;
1811     int64_t Val = Memory.OffsetImm->getValue();
1812     return Val >= 0 && Val < 256;
1813   }
1814 
1815   bool isMemNegImm8Offset() const {
1816     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1817       return false;
1818     // Base reg of PC isn't allowed for these encodings.
1819     if (Memory.BaseRegNum == ARM::PC) return false;
1820     // Immediate offset in range [-255, -1].
1821     if (!Memory.OffsetImm) return false;
1822     int64_t Val = Memory.OffsetImm->getValue();
1823     return (Val == std::numeric_limits<int32_t>::min()) ||
1824            (Val > -256 && Val < 0);
1825   }
1826 
1827   bool isMemUImm12Offset() const {
1828     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1829       return false;
1830     // Immediate offset in range [0, 4095].
1831     if (!Memory.OffsetImm) return true;
1832     int64_t Val = Memory.OffsetImm->getValue();
1833     return (Val >= 0 && Val < 4096);
1834   }
1835 
1836   bool isMemImm12Offset() const {
1837     // If we have an immediate that's not a constant, treat it as a label
1838     // reference needing a fixup. If it is a constant, it's something else
1839     // and we reject it.
1840 
1841     if (isImm() && !isa<MCConstantExpr>(getImm()))
1842       return true;
1843 
1844     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1845       return false;
1846     // Immediate offset in range [-4095, 4095].
1847     if (!Memory.OffsetImm) return true;
1848     int64_t Val = Memory.OffsetImm->getValue();
1849     return (Val > -4096 && Val < 4096) ||
1850            (Val == std::numeric_limits<int32_t>::min());
1851   }
1852 
1853   bool isConstPoolAsmImm() const {
1854     // Delay processing of Constant Pool Immediate, this will turn into
1855     // a constant. Match no other operand
1856     return (isConstantPoolImm());
1857   }
1858 
1859   bool isPostIdxImm8() const {
1860     if (!isImm()) return false;
1861     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1862     if (!CE) return false;
1863     int64_t Val = CE->getValue();
1864     return (Val > -256 && Val < 256) ||
1865            (Val == std::numeric_limits<int32_t>::min());
1866   }
1867 
1868   bool isPostIdxImm8s4() const {
1869     if (!isImm()) return false;
1870     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1871     if (!CE) return false;
1872     int64_t Val = CE->getValue();
1873     return ((Val & 3) == 0 && Val >= -1020 && Val <= 1020) ||
1874            (Val == std::numeric_limits<int32_t>::min());
1875   }
1876 
1877   bool isMSRMask() const { return Kind == k_MSRMask; }
1878   bool isBankedReg() const { return Kind == k_BankedReg; }
1879   bool isProcIFlags() const { return Kind == k_ProcIFlags; }
1880 
1881   // NEON operands.
1882   bool isSingleSpacedVectorList() const {
1883     return Kind == k_VectorList && !VectorList.isDoubleSpaced;
1884   }
1885 
1886   bool isDoubleSpacedVectorList() const {
1887     return Kind == k_VectorList && VectorList.isDoubleSpaced;
1888   }
1889 
1890   bool isVecListOneD() const {
1891     if (!isSingleSpacedVectorList()) return false;
1892     return VectorList.Count == 1;
1893   }
1894 
1895   bool isVecListTwoMQ() const {
1896     return isSingleSpacedVectorList() && VectorList.Count == 2 &&
1897            ARMMCRegisterClasses[ARM::MQPRRegClassID].contains(
1898                VectorList.RegNum);
1899   }
1900 
1901   bool isVecListDPair() const {
1902     if (!isSingleSpacedVectorList()) return false;
1903     return (ARMMCRegisterClasses[ARM::DPairRegClassID]
1904               .contains(VectorList.RegNum));
1905   }
1906 
1907   bool isVecListThreeD() const {
1908     if (!isSingleSpacedVectorList()) return false;
1909     return VectorList.Count == 3;
1910   }
1911 
1912   bool isVecListFourD() const {
1913     if (!isSingleSpacedVectorList()) return false;
1914     return VectorList.Count == 4;
1915   }
1916 
1917   bool isVecListDPairSpaced() const {
1918     if (Kind != k_VectorList) return false;
1919     if (isSingleSpacedVectorList()) return false;
1920     return (ARMMCRegisterClasses[ARM::DPairSpcRegClassID]
1921               .contains(VectorList.RegNum));
1922   }
1923 
1924   bool isVecListThreeQ() const {
1925     if (!isDoubleSpacedVectorList()) return false;
1926     return VectorList.Count == 3;
1927   }
1928 
1929   bool isVecListFourQ() const {
1930     if (!isDoubleSpacedVectorList()) return false;
1931     return VectorList.Count == 4;
1932   }
1933 
1934   bool isVecListFourMQ() const {
1935     return isSingleSpacedVectorList() && VectorList.Count == 4 &&
1936            ARMMCRegisterClasses[ARM::MQPRRegClassID].contains(
1937                VectorList.RegNum);
1938   }
1939 
1940   bool isSingleSpacedVectorAllLanes() const {
1941     return Kind == k_VectorListAllLanes && !VectorList.isDoubleSpaced;
1942   }
1943 
1944   bool isDoubleSpacedVectorAllLanes() const {
1945     return Kind == k_VectorListAllLanes && VectorList.isDoubleSpaced;
1946   }
1947 
1948   bool isVecListOneDAllLanes() const {
1949     if (!isSingleSpacedVectorAllLanes()) return false;
1950     return VectorList.Count == 1;
1951   }
1952 
1953   bool isVecListDPairAllLanes() const {
1954     if (!isSingleSpacedVectorAllLanes()) return false;
1955     return (ARMMCRegisterClasses[ARM::DPairRegClassID]
1956               .contains(VectorList.RegNum));
1957   }
1958 
1959   bool isVecListDPairSpacedAllLanes() const {
1960     if (!isDoubleSpacedVectorAllLanes()) return false;
1961     return VectorList.Count == 2;
1962   }
1963 
1964   bool isVecListThreeDAllLanes() const {
1965     if (!isSingleSpacedVectorAllLanes()) return false;
1966     return VectorList.Count == 3;
1967   }
1968 
1969   bool isVecListThreeQAllLanes() const {
1970     if (!isDoubleSpacedVectorAllLanes()) return false;
1971     return VectorList.Count == 3;
1972   }
1973 
1974   bool isVecListFourDAllLanes() const {
1975     if (!isSingleSpacedVectorAllLanes()) return false;
1976     return VectorList.Count == 4;
1977   }
1978 
1979   bool isVecListFourQAllLanes() const {
1980     if (!isDoubleSpacedVectorAllLanes()) return false;
1981     return VectorList.Count == 4;
1982   }
1983 
1984   bool isSingleSpacedVectorIndexed() const {
1985     return Kind == k_VectorListIndexed && !VectorList.isDoubleSpaced;
1986   }
1987 
1988   bool isDoubleSpacedVectorIndexed() const {
1989     return Kind == k_VectorListIndexed && VectorList.isDoubleSpaced;
1990   }
1991 
1992   bool isVecListOneDByteIndexed() const {
1993     if (!isSingleSpacedVectorIndexed()) return false;
1994     return VectorList.Count == 1 && VectorList.LaneIndex <= 7;
1995   }
1996 
1997   bool isVecListOneDHWordIndexed() const {
1998     if (!isSingleSpacedVectorIndexed()) return false;
1999     return VectorList.Count == 1 && VectorList.LaneIndex <= 3;
2000   }
2001 
2002   bool isVecListOneDWordIndexed() const {
2003     if (!isSingleSpacedVectorIndexed()) return false;
2004     return VectorList.Count == 1 && VectorList.LaneIndex <= 1;
2005   }
2006 
2007   bool isVecListTwoDByteIndexed() const {
2008     if (!isSingleSpacedVectorIndexed()) return false;
2009     return VectorList.Count == 2 && VectorList.LaneIndex <= 7;
2010   }
2011 
2012   bool isVecListTwoDHWordIndexed() const {
2013     if (!isSingleSpacedVectorIndexed()) return false;
2014     return VectorList.Count == 2 && VectorList.LaneIndex <= 3;
2015   }
2016 
2017   bool isVecListTwoQWordIndexed() const {
2018     if (!isDoubleSpacedVectorIndexed()) return false;
2019     return VectorList.Count == 2 && VectorList.LaneIndex <= 1;
2020   }
2021 
2022   bool isVecListTwoQHWordIndexed() const {
2023     if (!isDoubleSpacedVectorIndexed()) return false;
2024     return VectorList.Count == 2 && VectorList.LaneIndex <= 3;
2025   }
2026 
2027   bool isVecListTwoDWordIndexed() const {
2028     if (!isSingleSpacedVectorIndexed()) return false;
2029     return VectorList.Count == 2 && VectorList.LaneIndex <= 1;
2030   }
2031 
2032   bool isVecListThreeDByteIndexed() const {
2033     if (!isSingleSpacedVectorIndexed()) return false;
2034     return VectorList.Count == 3 && VectorList.LaneIndex <= 7;
2035   }
2036 
2037   bool isVecListThreeDHWordIndexed() const {
2038     if (!isSingleSpacedVectorIndexed()) return false;
2039     return VectorList.Count == 3 && VectorList.LaneIndex <= 3;
2040   }
2041 
2042   bool isVecListThreeQWordIndexed() const {
2043     if (!isDoubleSpacedVectorIndexed()) return false;
2044     return VectorList.Count == 3 && VectorList.LaneIndex <= 1;
2045   }
2046 
2047   bool isVecListThreeQHWordIndexed() const {
2048     if (!isDoubleSpacedVectorIndexed()) return false;
2049     return VectorList.Count == 3 && VectorList.LaneIndex <= 3;
2050   }
2051 
2052   bool isVecListThreeDWordIndexed() const {
2053     if (!isSingleSpacedVectorIndexed()) return false;
2054     return VectorList.Count == 3 && VectorList.LaneIndex <= 1;
2055   }
2056 
2057   bool isVecListFourDByteIndexed() const {
2058     if (!isSingleSpacedVectorIndexed()) return false;
2059     return VectorList.Count == 4 && VectorList.LaneIndex <= 7;
2060   }
2061 
2062   bool isVecListFourDHWordIndexed() const {
2063     if (!isSingleSpacedVectorIndexed()) return false;
2064     return VectorList.Count == 4 && VectorList.LaneIndex <= 3;
2065   }
2066 
2067   bool isVecListFourQWordIndexed() const {
2068     if (!isDoubleSpacedVectorIndexed()) return false;
2069     return VectorList.Count == 4 && VectorList.LaneIndex <= 1;
2070   }
2071 
2072   bool isVecListFourQHWordIndexed() const {
2073     if (!isDoubleSpacedVectorIndexed()) return false;
2074     return VectorList.Count == 4 && VectorList.LaneIndex <= 3;
2075   }
2076 
2077   bool isVecListFourDWordIndexed() const {
2078     if (!isSingleSpacedVectorIndexed()) return false;
2079     return VectorList.Count == 4 && VectorList.LaneIndex <= 1;
2080   }
2081 
2082   bool isVectorIndex() const { return Kind == k_VectorIndex; }
2083 
2084   template <unsigned NumLanes>
2085   bool isVectorIndexInRange() const {
2086     if (Kind != k_VectorIndex) return false;
2087     return VectorIndex.Val < NumLanes;
2088   }
2089 
2090   bool isVectorIndex8()  const { return isVectorIndexInRange<8>(); }
2091   bool isVectorIndex16() const { return isVectorIndexInRange<4>(); }
2092   bool isVectorIndex32() const { return isVectorIndexInRange<2>(); }
2093   bool isVectorIndex64() const { return isVectorIndexInRange<1>(); }
2094 
2095   template<int PermittedValue, int OtherPermittedValue>
2096   bool isMVEPairVectorIndex() const {
2097     if (Kind != k_VectorIndex) return false;
2098     return VectorIndex.Val == PermittedValue ||
2099            VectorIndex.Val == OtherPermittedValue;
2100   }
2101 
2102   bool isNEONi8splat() const {
2103     if (!isImm()) return false;
2104     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2105     // Must be a constant.
2106     if (!CE) return false;
2107     int64_t Value = CE->getValue();
2108     // i8 value splatted across 8 bytes. The immediate is just the 8 byte
2109     // value.
2110     return Value >= 0 && Value < 256;
2111   }
2112 
2113   bool isNEONi16splat() const {
2114     if (isNEONByteReplicate(2))
2115       return false; // Leave that for bytes replication and forbid by default.
2116     if (!isImm())
2117       return false;
2118     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2119     // Must be a constant.
2120     if (!CE) return false;
2121     unsigned Value = CE->getValue();
2122     return ARM_AM::isNEONi16splat(Value);
2123   }
2124 
2125   bool isNEONi16splatNot() const {
2126     if (!isImm())
2127       return false;
2128     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2129     // Must be a constant.
2130     if (!CE) return false;
2131     unsigned Value = CE->getValue();
2132     return ARM_AM::isNEONi16splat(~Value & 0xffff);
2133   }
2134 
2135   bool isNEONi32splat() const {
2136     if (isNEONByteReplicate(4))
2137       return false; // Leave that for bytes replication and forbid by default.
2138     if (!isImm())
2139       return false;
2140     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2141     // Must be a constant.
2142     if (!CE) return false;
2143     unsigned Value = CE->getValue();
2144     return ARM_AM::isNEONi32splat(Value);
2145   }
2146 
2147   bool isNEONi32splatNot() const {
2148     if (!isImm())
2149       return false;
2150     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2151     // Must be a constant.
2152     if (!CE) return false;
2153     unsigned Value = CE->getValue();
2154     return ARM_AM::isNEONi32splat(~Value);
2155   }
2156 
2157   static bool isValidNEONi32vmovImm(int64_t Value) {
2158     // i32 value with set bits only in one byte X000, 0X00, 00X0, or 000X,
2159     // for VMOV/VMVN only, 00Xf or 0Xff are also accepted.
2160     return ((Value & 0xffffffffffffff00) == 0) ||
2161            ((Value & 0xffffffffffff00ff) == 0) ||
2162            ((Value & 0xffffffffff00ffff) == 0) ||
2163            ((Value & 0xffffffff00ffffff) == 0) ||
2164            ((Value & 0xffffffffffff00ff) == 0xff) ||
2165            ((Value & 0xffffffffff00ffff) == 0xffff);
2166   }
2167 
2168   bool isNEONReplicate(unsigned Width, unsigned NumElems, bool Inv) const {
2169     assert((Width == 8 || Width == 16 || Width == 32) &&
2170            "Invalid element width");
2171     assert(NumElems * Width <= 64 && "Invalid result width");
2172 
2173     if (!isImm())
2174       return false;
2175     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2176     // Must be a constant.
2177     if (!CE)
2178       return false;
2179     int64_t Value = CE->getValue();
2180     if (!Value)
2181       return false; // Don't bother with zero.
2182     if (Inv)
2183       Value = ~Value;
2184 
2185     uint64_t Mask = (1ull << Width) - 1;
2186     uint64_t Elem = Value & Mask;
2187     if (Width == 16 && (Elem & 0x00ff) != 0 && (Elem & 0xff00) != 0)
2188       return false;
2189     if (Width == 32 && !isValidNEONi32vmovImm(Elem))
2190       return false;
2191 
2192     for (unsigned i = 1; i < NumElems; ++i) {
2193       Value >>= Width;
2194       if ((Value & Mask) != Elem)
2195         return false;
2196     }
2197     return true;
2198   }
2199 
2200   bool isNEONByteReplicate(unsigned NumBytes) const {
2201     return isNEONReplicate(8, NumBytes, false);
2202   }
2203 
2204   static void checkNeonReplicateArgs(unsigned FromW, unsigned ToW) {
2205     assert((FromW == 8 || FromW == 16 || FromW == 32) &&
2206            "Invalid source width");
2207     assert((ToW == 16 || ToW == 32 || ToW == 64) &&
2208            "Invalid destination width");
2209     assert(FromW < ToW && "ToW is not less than FromW");
2210   }
2211 
2212   template<unsigned FromW, unsigned ToW>
2213   bool isNEONmovReplicate() const {
2214     checkNeonReplicateArgs(FromW, ToW);
2215     if (ToW == 64 && isNEONi64splat())
2216       return false;
2217     return isNEONReplicate(FromW, ToW / FromW, false);
2218   }
2219 
2220   template<unsigned FromW, unsigned ToW>
2221   bool isNEONinvReplicate() const {
2222     checkNeonReplicateArgs(FromW, ToW);
2223     return isNEONReplicate(FromW, ToW / FromW, true);
2224   }
2225 
2226   bool isNEONi32vmov() const {
2227     if (isNEONByteReplicate(4))
2228       return false; // Let it to be classified as byte-replicate case.
2229     if (!isImm())
2230       return false;
2231     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2232     // Must be a constant.
2233     if (!CE)
2234       return false;
2235     return isValidNEONi32vmovImm(CE->getValue());
2236   }
2237 
2238   bool isNEONi32vmovNeg() const {
2239     if (!isImm()) return false;
2240     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2241     // Must be a constant.
2242     if (!CE) return false;
2243     return isValidNEONi32vmovImm(~CE->getValue());
2244   }
2245 
2246   bool isNEONi64splat() const {
2247     if (!isImm()) return false;
2248     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2249     // Must be a constant.
2250     if (!CE) return false;
2251     uint64_t Value = CE->getValue();
2252     // i64 value with each byte being either 0 or 0xff.
2253     for (unsigned i = 0; i < 8; ++i, Value >>= 8)
2254       if ((Value & 0xff) != 0 && (Value & 0xff) != 0xff) return false;
2255     return true;
2256   }
2257 
2258   template<int64_t Angle, int64_t Remainder>
2259   bool isComplexRotation() const {
2260     if (!isImm()) return false;
2261 
2262     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2263     if (!CE) return false;
2264     uint64_t Value = CE->getValue();
2265 
2266     return (Value % Angle == Remainder && Value <= 270);
2267   }
2268 
2269   bool isMVELongShift() const {
2270     if (!isImm()) return false;
2271     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2272     // Must be a constant.
2273     if (!CE) return false;
2274     uint64_t Value = CE->getValue();
2275     return Value >= 1 && Value <= 32;
2276   }
2277 
2278   bool isMveSaturateOp() const {
2279     if (!isImm()) return false;
2280     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2281     if (!CE) return false;
2282     uint64_t Value = CE->getValue();
2283     return Value == 48 || Value == 64;
2284   }
2285 
2286   bool isITCondCodeNoAL() const {
2287     if (!isITCondCode()) return false;
2288     ARMCC::CondCodes CC = getCondCode();
2289     return CC != ARMCC::AL;
2290   }
2291 
2292   bool isITCondCodeRestrictedI() const {
2293     if (!isITCondCode())
2294       return false;
2295     ARMCC::CondCodes CC = getCondCode();
2296     return CC == ARMCC::EQ || CC == ARMCC::NE;
2297   }
2298 
2299   bool isITCondCodeRestrictedS() const {
2300     if (!isITCondCode())
2301       return false;
2302     ARMCC::CondCodes CC = getCondCode();
2303     return CC == ARMCC::LT || CC == ARMCC::GT || CC == ARMCC::LE ||
2304            CC == ARMCC::GE;
2305   }
2306 
2307   bool isITCondCodeRestrictedU() const {
2308     if (!isITCondCode())
2309       return false;
2310     ARMCC::CondCodes CC = getCondCode();
2311     return CC == ARMCC::HS || CC == ARMCC::HI;
2312   }
2313 
2314   bool isITCondCodeRestrictedFP() const {
2315     if (!isITCondCode())
2316       return false;
2317     ARMCC::CondCodes CC = getCondCode();
2318     return CC == ARMCC::EQ || CC == ARMCC::NE || CC == ARMCC::LT ||
2319            CC == ARMCC::GT || CC == ARMCC::LE || CC == ARMCC::GE;
2320   }
2321 
2322   void addExpr(MCInst &Inst, const MCExpr *Expr) const {
2323     // Add as immediates when possible.  Null MCExpr = 0.
2324     if (!Expr)
2325       Inst.addOperand(MCOperand::createImm(0));
2326     else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
2327       Inst.addOperand(MCOperand::createImm(CE->getValue()));
2328     else
2329       Inst.addOperand(MCOperand::createExpr(Expr));
2330   }
2331 
2332   void addARMBranchTargetOperands(MCInst &Inst, unsigned N) const {
2333     assert(N == 1 && "Invalid number of operands!");
2334     addExpr(Inst, getImm());
2335   }
2336 
2337   void addThumbBranchTargetOperands(MCInst &Inst, unsigned N) const {
2338     assert(N == 1 && "Invalid number of operands!");
2339     addExpr(Inst, getImm());
2340   }
2341 
2342   void addCondCodeOperands(MCInst &Inst, unsigned N) const {
2343     assert(N == 2 && "Invalid number of operands!");
2344     Inst.addOperand(MCOperand::createImm(unsigned(getCondCode())));
2345     unsigned RegNum = getCondCode() == ARMCC::AL ? 0: ARM::CPSR;
2346     Inst.addOperand(MCOperand::createReg(RegNum));
2347   }
2348 
2349   void addVPTPredNOperands(MCInst &Inst, unsigned N) const {
2350     assert(N == 2 && "Invalid number of operands!");
2351     Inst.addOperand(MCOperand::createImm(unsigned(getVPTPred())));
2352     unsigned RegNum = getVPTPred() == ARMVCC::None ? 0: ARM::P0;
2353     Inst.addOperand(MCOperand::createReg(RegNum));
2354   }
2355 
2356   void addVPTPredROperands(MCInst &Inst, unsigned N) const {
2357     assert(N == 3 && "Invalid number of operands!");
2358     addVPTPredNOperands(Inst, N-1);
2359     unsigned RegNum;
2360     if (getVPTPred() == ARMVCC::None) {
2361       RegNum = 0;
2362     } else {
2363       unsigned NextOpIndex = Inst.getNumOperands();
2364       const MCInstrDesc &MCID = ARMInsts[Inst.getOpcode()];
2365       int TiedOp = MCID.getOperandConstraint(NextOpIndex, MCOI::TIED_TO);
2366       assert(TiedOp >= 0 &&
2367              "Inactive register in vpred_r is not tied to an output!");
2368       RegNum = Inst.getOperand(TiedOp).getReg();
2369     }
2370     Inst.addOperand(MCOperand::createReg(RegNum));
2371   }
2372 
2373   void addCoprocNumOperands(MCInst &Inst, unsigned N) const {
2374     assert(N == 1 && "Invalid number of operands!");
2375     Inst.addOperand(MCOperand::createImm(getCoproc()));
2376   }
2377 
2378   void addCoprocRegOperands(MCInst &Inst, unsigned N) const {
2379     assert(N == 1 && "Invalid number of operands!");
2380     Inst.addOperand(MCOperand::createImm(getCoproc()));
2381   }
2382 
2383   void addCoprocOptionOperands(MCInst &Inst, unsigned N) const {
2384     assert(N == 1 && "Invalid number of operands!");
2385     Inst.addOperand(MCOperand::createImm(CoprocOption.Val));
2386   }
2387 
2388   void addITMaskOperands(MCInst &Inst, unsigned N) const {
2389     assert(N == 1 && "Invalid number of operands!");
2390     Inst.addOperand(MCOperand::createImm(ITMask.Mask));
2391   }
2392 
2393   void addITCondCodeOperands(MCInst &Inst, unsigned N) const {
2394     assert(N == 1 && "Invalid number of operands!");
2395     Inst.addOperand(MCOperand::createImm(unsigned(getCondCode())));
2396   }
2397 
2398   void addITCondCodeInvOperands(MCInst &Inst, unsigned N) const {
2399     assert(N == 1 && "Invalid number of operands!");
2400     Inst.addOperand(MCOperand::createImm(unsigned(ARMCC::getOppositeCondition(getCondCode()))));
2401   }
2402 
2403   void addCCOutOperands(MCInst &Inst, unsigned N) const {
2404     assert(N == 1 && "Invalid number of operands!");
2405     Inst.addOperand(MCOperand::createReg(getReg()));
2406   }
2407 
2408   void addRegOperands(MCInst &Inst, unsigned N) const {
2409     assert(N == 1 && "Invalid number of operands!");
2410     Inst.addOperand(MCOperand::createReg(getReg()));
2411   }
2412 
2413   void addRegShiftedRegOperands(MCInst &Inst, unsigned N) const {
2414     assert(N == 3 && "Invalid number of operands!");
2415     assert(isRegShiftedReg() &&
2416            "addRegShiftedRegOperands() on non-RegShiftedReg!");
2417     Inst.addOperand(MCOperand::createReg(RegShiftedReg.SrcReg));
2418     Inst.addOperand(MCOperand::createReg(RegShiftedReg.ShiftReg));
2419     Inst.addOperand(MCOperand::createImm(
2420       ARM_AM::getSORegOpc(RegShiftedReg.ShiftTy, RegShiftedReg.ShiftImm)));
2421   }
2422 
2423   void addRegShiftedImmOperands(MCInst &Inst, unsigned N) const {
2424     assert(N == 2 && "Invalid number of operands!");
2425     assert(isRegShiftedImm() &&
2426            "addRegShiftedImmOperands() on non-RegShiftedImm!");
2427     Inst.addOperand(MCOperand::createReg(RegShiftedImm.SrcReg));
2428     // Shift of #32 is encoded as 0 where permitted
2429     unsigned Imm = (RegShiftedImm.ShiftImm == 32 ? 0 : RegShiftedImm.ShiftImm);
2430     Inst.addOperand(MCOperand::createImm(
2431       ARM_AM::getSORegOpc(RegShiftedImm.ShiftTy, Imm)));
2432   }
2433 
2434   void addShifterImmOperands(MCInst &Inst, unsigned N) const {
2435     assert(N == 1 && "Invalid number of operands!");
2436     Inst.addOperand(MCOperand::createImm((ShifterImm.isASR << 5) |
2437                                          ShifterImm.Imm));
2438   }
2439 
2440   void addRegListOperands(MCInst &Inst, unsigned N) const {
2441     assert(N == 1 && "Invalid number of operands!");
2442     const SmallVectorImpl<unsigned> &RegList = getRegList();
2443     for (SmallVectorImpl<unsigned>::const_iterator
2444            I = RegList.begin(), E = RegList.end(); I != E; ++I)
2445       Inst.addOperand(MCOperand::createReg(*I));
2446   }
2447 
2448   void addRegListWithAPSROperands(MCInst &Inst, unsigned N) const {
2449     assert(N == 1 && "Invalid number of operands!");
2450     const SmallVectorImpl<unsigned> &RegList = getRegList();
2451     for (SmallVectorImpl<unsigned>::const_iterator
2452            I = RegList.begin(), E = RegList.end(); I != E; ++I)
2453       Inst.addOperand(MCOperand::createReg(*I));
2454   }
2455 
2456   void addDPRRegListOperands(MCInst &Inst, unsigned N) const {
2457     addRegListOperands(Inst, N);
2458   }
2459 
2460   void addSPRRegListOperands(MCInst &Inst, unsigned N) const {
2461     addRegListOperands(Inst, N);
2462   }
2463 
2464   void addFPSRegListWithVPROperands(MCInst &Inst, unsigned N) const {
2465     addRegListOperands(Inst, N);
2466   }
2467 
2468   void addFPDRegListWithVPROperands(MCInst &Inst, unsigned N) const {
2469     addRegListOperands(Inst, N);
2470   }
2471 
2472   void addRotImmOperands(MCInst &Inst, unsigned N) const {
2473     assert(N == 1 && "Invalid number of operands!");
2474     // Encoded as val>>3. The printer handles display as 8, 16, 24.
2475     Inst.addOperand(MCOperand::createImm(RotImm.Imm >> 3));
2476   }
2477 
2478   void addModImmOperands(MCInst &Inst, unsigned N) const {
2479     assert(N == 1 && "Invalid number of operands!");
2480 
2481     // Support for fixups (MCFixup)
2482     if (isImm())
2483       return addImmOperands(Inst, N);
2484 
2485     Inst.addOperand(MCOperand::createImm(ModImm.Bits | (ModImm.Rot << 7)));
2486   }
2487 
2488   void addModImmNotOperands(MCInst &Inst, unsigned N) const {
2489     assert(N == 1 && "Invalid number of operands!");
2490     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2491     uint32_t Enc = ARM_AM::getSOImmVal(~CE->getValue());
2492     Inst.addOperand(MCOperand::createImm(Enc));
2493   }
2494 
2495   void addModImmNegOperands(MCInst &Inst, unsigned N) const {
2496     assert(N == 1 && "Invalid number of operands!");
2497     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2498     uint32_t Enc = ARM_AM::getSOImmVal(-CE->getValue());
2499     Inst.addOperand(MCOperand::createImm(Enc));
2500   }
2501 
2502   void addThumbModImmNeg8_255Operands(MCInst &Inst, unsigned N) const {
2503     assert(N == 1 && "Invalid number of operands!");
2504     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2505     uint32_t Val = -CE->getValue();
2506     Inst.addOperand(MCOperand::createImm(Val));
2507   }
2508 
2509   void addThumbModImmNeg1_7Operands(MCInst &Inst, unsigned N) const {
2510     assert(N == 1 && "Invalid number of operands!");
2511     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2512     uint32_t Val = -CE->getValue();
2513     Inst.addOperand(MCOperand::createImm(Val));
2514   }
2515 
2516   void addBitfieldOperands(MCInst &Inst, unsigned N) const {
2517     assert(N == 1 && "Invalid number of operands!");
2518     // Munge the lsb/width into a bitfield mask.
2519     unsigned lsb = Bitfield.LSB;
2520     unsigned width = Bitfield.Width;
2521     // Make a 32-bit mask w/ the referenced bits clear and all other bits set.
2522     uint32_t Mask = ~(((uint32_t)0xffffffff >> lsb) << (32 - width) >>
2523                       (32 - (lsb + width)));
2524     Inst.addOperand(MCOperand::createImm(Mask));
2525   }
2526 
2527   void addImmOperands(MCInst &Inst, unsigned N) const {
2528     assert(N == 1 && "Invalid number of operands!");
2529     addExpr(Inst, getImm());
2530   }
2531 
2532   void addFBits16Operands(MCInst &Inst, unsigned N) const {
2533     assert(N == 1 && "Invalid number of operands!");
2534     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2535     Inst.addOperand(MCOperand::createImm(16 - CE->getValue()));
2536   }
2537 
2538   void addFBits32Operands(MCInst &Inst, unsigned N) const {
2539     assert(N == 1 && "Invalid number of operands!");
2540     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2541     Inst.addOperand(MCOperand::createImm(32 - CE->getValue()));
2542   }
2543 
2544   void addFPImmOperands(MCInst &Inst, unsigned N) const {
2545     assert(N == 1 && "Invalid number of operands!");
2546     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2547     int Val = ARM_AM::getFP32Imm(APInt(32, CE->getValue()));
2548     Inst.addOperand(MCOperand::createImm(Val));
2549   }
2550 
2551   void addImm8s4Operands(MCInst &Inst, unsigned N) const {
2552     assert(N == 1 && "Invalid number of operands!");
2553     // FIXME: We really want to scale the value here, but the LDRD/STRD
2554     // instruction don't encode operands that way yet.
2555     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2556     Inst.addOperand(MCOperand::createImm(CE->getValue()));
2557   }
2558 
2559   void addImm7s4Operands(MCInst &Inst, unsigned N) const {
2560     assert(N == 1 && "Invalid number of operands!");
2561     // FIXME: We really want to scale the value here, but the VSTR/VLDR_VSYSR
2562     // instruction don't encode operands that way yet.
2563     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2564     Inst.addOperand(MCOperand::createImm(CE->getValue()));
2565   }
2566 
2567   void addImm7Shift0Operands(MCInst &Inst, unsigned N) const {
2568     assert(N == 1 && "Invalid number of operands!");
2569     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2570     assert(CE != nullptr && "Invalid operand type!");
2571     Inst.addOperand(MCOperand::createImm(CE->getValue()));
2572   }
2573 
2574   void addImm7Shift1Operands(MCInst &Inst, unsigned N) const {
2575     assert(N == 1 && "Invalid number of operands!");
2576     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2577     assert(CE != nullptr && "Invalid operand type!");
2578     Inst.addOperand(MCOperand::createImm(CE->getValue()));
2579   }
2580 
2581   void addImm7Shift2Operands(MCInst &Inst, unsigned N) const {
2582     assert(N == 1 && "Invalid number of operands!");
2583     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2584     assert(CE != nullptr && "Invalid operand type!");
2585     Inst.addOperand(MCOperand::createImm(CE->getValue()));
2586   }
2587 
2588   void addImm7Operands(MCInst &Inst, unsigned N) const {
2589     assert(N == 1 && "Invalid number of operands!");
2590     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2591     assert(CE != nullptr && "Invalid operand type!");
2592     Inst.addOperand(MCOperand::createImm(CE->getValue()));
2593   }
2594 
2595   void addImm0_1020s4Operands(MCInst &Inst, unsigned N) const {
2596     assert(N == 1 && "Invalid number of operands!");
2597     // The immediate is scaled by four in the encoding and is stored
2598     // in the MCInst as such. Lop off the low two bits here.
2599     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2600     Inst.addOperand(MCOperand::createImm(CE->getValue() / 4));
2601   }
2602 
2603   void addImm0_508s4NegOperands(MCInst &Inst, unsigned N) const {
2604     assert(N == 1 && "Invalid number of operands!");
2605     // The immediate is scaled by four in the encoding and is stored
2606     // in the MCInst as such. Lop off the low two bits here.
2607     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2608     Inst.addOperand(MCOperand::createImm(-(CE->getValue() / 4)));
2609   }
2610 
2611   void addImm0_508s4Operands(MCInst &Inst, unsigned N) const {
2612     assert(N == 1 && "Invalid number of operands!");
2613     // The immediate is scaled by four in the encoding and is stored
2614     // in the MCInst as such. Lop off the low two bits here.
2615     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2616     Inst.addOperand(MCOperand::createImm(CE->getValue() / 4));
2617   }
2618 
2619   void addImm1_16Operands(MCInst &Inst, unsigned N) const {
2620     assert(N == 1 && "Invalid number of operands!");
2621     // The constant encodes as the immediate-1, and we store in the instruction
2622     // the bits as encoded, so subtract off one here.
2623     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2624     Inst.addOperand(MCOperand::createImm(CE->getValue() - 1));
2625   }
2626 
2627   void addImm1_32Operands(MCInst &Inst, unsigned N) const {
2628     assert(N == 1 && "Invalid number of operands!");
2629     // The constant encodes as the immediate-1, and we store in the instruction
2630     // the bits as encoded, so subtract off one here.
2631     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2632     Inst.addOperand(MCOperand::createImm(CE->getValue() - 1));
2633   }
2634 
2635   void addImmThumbSROperands(MCInst &Inst, unsigned N) const {
2636     assert(N == 1 && "Invalid number of operands!");
2637     // The constant encodes as the immediate, except for 32, which encodes as
2638     // zero.
2639     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2640     unsigned Imm = CE->getValue();
2641     Inst.addOperand(MCOperand::createImm((Imm == 32 ? 0 : Imm)));
2642   }
2643 
2644   void addPKHASRImmOperands(MCInst &Inst, unsigned N) const {
2645     assert(N == 1 && "Invalid number of operands!");
2646     // An ASR value of 32 encodes as 0, so that's how we want to add it to
2647     // the instruction as well.
2648     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2649     int Val = CE->getValue();
2650     Inst.addOperand(MCOperand::createImm(Val == 32 ? 0 : Val));
2651   }
2652 
2653   void addT2SOImmNotOperands(MCInst &Inst, unsigned N) const {
2654     assert(N == 1 && "Invalid number of operands!");
2655     // The operand is actually a t2_so_imm, but we have its bitwise
2656     // negation in the assembly source, so twiddle it here.
2657     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2658     Inst.addOperand(MCOperand::createImm(~(uint32_t)CE->getValue()));
2659   }
2660 
2661   void addT2SOImmNegOperands(MCInst &Inst, unsigned N) const {
2662     assert(N == 1 && "Invalid number of operands!");
2663     // The operand is actually a t2_so_imm, but we have its
2664     // negation in the assembly source, so twiddle it here.
2665     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2666     Inst.addOperand(MCOperand::createImm(-(uint32_t)CE->getValue()));
2667   }
2668 
2669   void addImm0_4095NegOperands(MCInst &Inst, unsigned N) const {
2670     assert(N == 1 && "Invalid number of operands!");
2671     // The operand is actually an imm0_4095, but we have its
2672     // negation in the assembly source, so twiddle it here.
2673     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2674     Inst.addOperand(MCOperand::createImm(-(uint32_t)CE->getValue()));
2675   }
2676 
2677   void addUnsignedOffset_b8s2Operands(MCInst &Inst, unsigned N) const {
2678     if(const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm())) {
2679       Inst.addOperand(MCOperand::createImm(CE->getValue() >> 2));
2680       return;
2681     }
2682 
2683     const MCSymbolRefExpr *SR = dyn_cast<MCSymbolRefExpr>(Imm.Val);
2684     assert(SR && "Unknown value type!");
2685     Inst.addOperand(MCOperand::createExpr(SR));
2686   }
2687 
2688   void addThumbMemPCOperands(MCInst &Inst, unsigned N) const {
2689     assert(N == 1 && "Invalid number of operands!");
2690     if (isImm()) {
2691       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2692       if (CE) {
2693         Inst.addOperand(MCOperand::createImm(CE->getValue()));
2694         return;
2695       }
2696 
2697       const MCSymbolRefExpr *SR = dyn_cast<MCSymbolRefExpr>(Imm.Val);
2698 
2699       assert(SR && "Unknown value type!");
2700       Inst.addOperand(MCOperand::createExpr(SR));
2701       return;
2702     }
2703 
2704     assert(isGPRMem()  && "Unknown value type!");
2705     assert(isa<MCConstantExpr>(Memory.OffsetImm) && "Unknown value type!");
2706     Inst.addOperand(MCOperand::createImm(Memory.OffsetImm->getValue()));
2707   }
2708 
2709   void addMemBarrierOptOperands(MCInst &Inst, unsigned N) const {
2710     assert(N == 1 && "Invalid number of operands!");
2711     Inst.addOperand(MCOperand::createImm(unsigned(getMemBarrierOpt())));
2712   }
2713 
2714   void addInstSyncBarrierOptOperands(MCInst &Inst, unsigned N) const {
2715     assert(N == 1 && "Invalid number of operands!");
2716     Inst.addOperand(MCOperand::createImm(unsigned(getInstSyncBarrierOpt())));
2717   }
2718 
2719   void addTraceSyncBarrierOptOperands(MCInst &Inst, unsigned N) const {
2720     assert(N == 1 && "Invalid number of operands!");
2721     Inst.addOperand(MCOperand::createImm(unsigned(getTraceSyncBarrierOpt())));
2722   }
2723 
2724   void addMemNoOffsetOperands(MCInst &Inst, unsigned N) const {
2725     assert(N == 1 && "Invalid number of operands!");
2726     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2727   }
2728 
2729   void addMemNoOffsetT2Operands(MCInst &Inst, unsigned N) const {
2730     assert(N == 1 && "Invalid number of operands!");
2731     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2732   }
2733 
2734   void addMemNoOffsetT2NoSpOperands(MCInst &Inst, unsigned N) const {
2735     assert(N == 1 && "Invalid number of operands!");
2736     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2737   }
2738 
2739   void addMemNoOffsetTOperands(MCInst &Inst, unsigned N) const {
2740     assert(N == 1 && "Invalid number of operands!");
2741     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2742   }
2743 
2744   void addMemPCRelImm12Operands(MCInst &Inst, unsigned N) const {
2745     assert(N == 1 && "Invalid number of operands!");
2746     int32_t Imm = Memory.OffsetImm->getValue();
2747     Inst.addOperand(MCOperand::createImm(Imm));
2748   }
2749 
2750   void addAdrLabelOperands(MCInst &Inst, unsigned N) const {
2751     assert(N == 1 && "Invalid number of operands!");
2752     assert(isImm() && "Not an immediate!");
2753 
2754     // If we have an immediate that's not a constant, treat it as a label
2755     // reference needing a fixup.
2756     if (!isa<MCConstantExpr>(getImm())) {
2757       Inst.addOperand(MCOperand::createExpr(getImm()));
2758       return;
2759     }
2760 
2761     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2762     int Val = CE->getValue();
2763     Inst.addOperand(MCOperand::createImm(Val));
2764   }
2765 
2766   void addAlignedMemoryOperands(MCInst &Inst, unsigned N) const {
2767     assert(N == 2 && "Invalid number of operands!");
2768     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2769     Inst.addOperand(MCOperand::createImm(Memory.Alignment));
2770   }
2771 
2772   void addDupAlignedMemoryNoneOperands(MCInst &Inst, unsigned N) const {
2773     addAlignedMemoryOperands(Inst, N);
2774   }
2775 
2776   void addAlignedMemoryNoneOperands(MCInst &Inst, unsigned N) const {
2777     addAlignedMemoryOperands(Inst, N);
2778   }
2779 
2780   void addAlignedMemory16Operands(MCInst &Inst, unsigned N) const {
2781     addAlignedMemoryOperands(Inst, N);
2782   }
2783 
2784   void addDupAlignedMemory16Operands(MCInst &Inst, unsigned N) const {
2785     addAlignedMemoryOperands(Inst, N);
2786   }
2787 
2788   void addAlignedMemory32Operands(MCInst &Inst, unsigned N) const {
2789     addAlignedMemoryOperands(Inst, N);
2790   }
2791 
2792   void addDupAlignedMemory32Operands(MCInst &Inst, unsigned N) const {
2793     addAlignedMemoryOperands(Inst, N);
2794   }
2795 
2796   void addAlignedMemory64Operands(MCInst &Inst, unsigned N) const {
2797     addAlignedMemoryOperands(Inst, N);
2798   }
2799 
2800   void addDupAlignedMemory64Operands(MCInst &Inst, unsigned N) const {
2801     addAlignedMemoryOperands(Inst, N);
2802   }
2803 
2804   void addAlignedMemory64or128Operands(MCInst &Inst, unsigned N) const {
2805     addAlignedMemoryOperands(Inst, N);
2806   }
2807 
2808   void addDupAlignedMemory64or128Operands(MCInst &Inst, unsigned N) const {
2809     addAlignedMemoryOperands(Inst, N);
2810   }
2811 
2812   void addAlignedMemory64or128or256Operands(MCInst &Inst, unsigned N) const {
2813     addAlignedMemoryOperands(Inst, N);
2814   }
2815 
2816   void addAddrMode2Operands(MCInst &Inst, unsigned N) const {
2817     assert(N == 3 && "Invalid number of operands!");
2818     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2819     if (!Memory.OffsetRegNum) {
2820       ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2821       // Special case for #-0
2822       if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2823       if (Val < 0) Val = -Val;
2824       Val = ARM_AM::getAM2Opc(AddSub, Val, ARM_AM::no_shift);
2825     } else {
2826       // For register offset, we encode the shift type and negation flag
2827       // here.
2828       Val = ARM_AM::getAM2Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add,
2829                               Memory.ShiftImm, Memory.ShiftType);
2830     }
2831     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2832     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2833     Inst.addOperand(MCOperand::createImm(Val));
2834   }
2835 
2836   void addAM2OffsetImmOperands(MCInst &Inst, unsigned N) const {
2837     assert(N == 2 && "Invalid number of operands!");
2838     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2839     assert(CE && "non-constant AM2OffsetImm operand!");
2840     int32_t Val = CE->getValue();
2841     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2842     // Special case for #-0
2843     if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2844     if (Val < 0) Val = -Val;
2845     Val = ARM_AM::getAM2Opc(AddSub, Val, ARM_AM::no_shift);
2846     Inst.addOperand(MCOperand::createReg(0));
2847     Inst.addOperand(MCOperand::createImm(Val));
2848   }
2849 
2850   void addAddrMode3Operands(MCInst &Inst, unsigned N) const {
2851     assert(N == 3 && "Invalid number of operands!");
2852     // If we have an immediate that's not a constant, treat it as a label
2853     // reference needing a fixup. If it is a constant, it's something else
2854     // and we reject it.
2855     if (isImm()) {
2856       Inst.addOperand(MCOperand::createExpr(getImm()));
2857       Inst.addOperand(MCOperand::createReg(0));
2858       Inst.addOperand(MCOperand::createImm(0));
2859       return;
2860     }
2861 
2862     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2863     if (!Memory.OffsetRegNum) {
2864       ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2865       // Special case for #-0
2866       if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2867       if (Val < 0) Val = -Val;
2868       Val = ARM_AM::getAM3Opc(AddSub, Val);
2869     } else {
2870       // For register offset, we encode the shift type and negation flag
2871       // here.
2872       Val = ARM_AM::getAM3Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add, 0);
2873     }
2874     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2875     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2876     Inst.addOperand(MCOperand::createImm(Val));
2877   }
2878 
2879   void addAM3OffsetOperands(MCInst &Inst, unsigned N) const {
2880     assert(N == 2 && "Invalid number of operands!");
2881     if (Kind == k_PostIndexRegister) {
2882       int32_t Val =
2883         ARM_AM::getAM3Opc(PostIdxReg.isAdd ? ARM_AM::add : ARM_AM::sub, 0);
2884       Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
2885       Inst.addOperand(MCOperand::createImm(Val));
2886       return;
2887     }
2888 
2889     // Constant offset.
2890     const MCConstantExpr *CE = static_cast<const MCConstantExpr*>(getImm());
2891     int32_t Val = CE->getValue();
2892     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2893     // Special case for #-0
2894     if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2895     if (Val < 0) Val = -Val;
2896     Val = ARM_AM::getAM3Opc(AddSub, Val);
2897     Inst.addOperand(MCOperand::createReg(0));
2898     Inst.addOperand(MCOperand::createImm(Val));
2899   }
2900 
2901   void addAddrMode5Operands(MCInst &Inst, unsigned N) const {
2902     assert(N == 2 && "Invalid number of operands!");
2903     // If we have an immediate that's not a constant, treat it as a label
2904     // reference needing a fixup. If it is a constant, it's something else
2905     // and we reject it.
2906     if (isImm()) {
2907       Inst.addOperand(MCOperand::createExpr(getImm()));
2908       Inst.addOperand(MCOperand::createImm(0));
2909       return;
2910     }
2911 
2912     // The lower two bits are always zero and as such are not encoded.
2913     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 4 : 0;
2914     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2915     // Special case for #-0
2916     if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2917     if (Val < 0) Val = -Val;
2918     Val = ARM_AM::getAM5Opc(AddSub, Val);
2919     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2920     Inst.addOperand(MCOperand::createImm(Val));
2921   }
2922 
2923   void addAddrMode5FP16Operands(MCInst &Inst, unsigned N) const {
2924     assert(N == 2 && "Invalid number of operands!");
2925     // If we have an immediate that's not a constant, treat it as a label
2926     // reference needing a fixup. If it is a constant, it's something else
2927     // and we reject it.
2928     if (isImm()) {
2929       Inst.addOperand(MCOperand::createExpr(getImm()));
2930       Inst.addOperand(MCOperand::createImm(0));
2931       return;
2932     }
2933 
2934     // The lower bit is always zero and as such is not encoded.
2935     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 2 : 0;
2936     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2937     // Special case for #-0
2938     if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2939     if (Val < 0) Val = -Val;
2940     Val = ARM_AM::getAM5FP16Opc(AddSub, Val);
2941     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2942     Inst.addOperand(MCOperand::createImm(Val));
2943   }
2944 
2945   void addMemImm8s4OffsetOperands(MCInst &Inst, unsigned N) const {
2946     assert(N == 2 && "Invalid number of operands!");
2947     // If we have an immediate that's not a constant, treat it as a label
2948     // reference needing a fixup. If it is a constant, it's something else
2949     // and we reject it.
2950     if (isImm()) {
2951       Inst.addOperand(MCOperand::createExpr(getImm()));
2952       Inst.addOperand(MCOperand::createImm(0));
2953       return;
2954     }
2955 
2956     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2957     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2958     Inst.addOperand(MCOperand::createImm(Val));
2959   }
2960 
2961   void addMemImm7s4OffsetOperands(MCInst &Inst, unsigned N) const {
2962     assert(N == 2 && "Invalid number of operands!");
2963     // If we have an immediate that's not a constant, treat it as a label
2964     // reference needing a fixup. If it is a constant, it's something else
2965     // and we reject it.
2966     if (isImm()) {
2967       Inst.addOperand(MCOperand::createExpr(getImm()));
2968       Inst.addOperand(MCOperand::createImm(0));
2969       return;
2970     }
2971 
2972     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2973     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2974     Inst.addOperand(MCOperand::createImm(Val));
2975   }
2976 
2977   void addMemImm0_1020s4OffsetOperands(MCInst &Inst, unsigned N) const {
2978     assert(N == 2 && "Invalid number of operands!");
2979     // The lower two bits are always zero and as such are not encoded.
2980     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 4 : 0;
2981     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2982     Inst.addOperand(MCOperand::createImm(Val));
2983   }
2984 
2985   void addMemImmOffsetOperands(MCInst &Inst, unsigned N) const {
2986     assert(N == 2 && "Invalid number of operands!");
2987     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2988     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2989     Inst.addOperand(MCOperand::createImm(Val));
2990   }
2991 
2992   void addMemRegRQOffsetOperands(MCInst &Inst, unsigned N) const {
2993     assert(N == 2 && "Invalid number of operands!");
2994     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2995     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2996   }
2997 
2998   void addMemUImm12OffsetOperands(MCInst &Inst, unsigned N) const {
2999     assert(N == 2 && "Invalid number of operands!");
3000     // If this is an immediate, it's a label reference.
3001     if (isImm()) {
3002       addExpr(Inst, getImm());
3003       Inst.addOperand(MCOperand::createImm(0));
3004       return;
3005     }
3006 
3007     // Otherwise, it's a normal memory reg+offset.
3008     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
3009     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3010     Inst.addOperand(MCOperand::createImm(Val));
3011   }
3012 
3013   void addMemImm12OffsetOperands(MCInst &Inst, unsigned N) const {
3014     assert(N == 2 && "Invalid number of operands!");
3015     // If this is an immediate, it's a label reference.
3016     if (isImm()) {
3017       addExpr(Inst, getImm());
3018       Inst.addOperand(MCOperand::createImm(0));
3019       return;
3020     }
3021 
3022     // Otherwise, it's a normal memory reg+offset.
3023     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
3024     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3025     Inst.addOperand(MCOperand::createImm(Val));
3026   }
3027 
3028   void addConstPoolAsmImmOperands(MCInst &Inst, unsigned N) const {
3029     assert(N == 1 && "Invalid number of operands!");
3030     // This is container for the immediate that we will create the constant
3031     // pool from
3032     addExpr(Inst, getConstantPoolImm());
3033     return;
3034   }
3035 
3036   void addMemTBBOperands(MCInst &Inst, unsigned N) const {
3037     assert(N == 2 && "Invalid number of operands!");
3038     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3039     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
3040   }
3041 
3042   void addMemTBHOperands(MCInst &Inst, unsigned N) const {
3043     assert(N == 2 && "Invalid number of operands!");
3044     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3045     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
3046   }
3047 
3048   void addMemRegOffsetOperands(MCInst &Inst, unsigned N) const {
3049     assert(N == 3 && "Invalid number of operands!");
3050     unsigned Val =
3051       ARM_AM::getAM2Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add,
3052                         Memory.ShiftImm, Memory.ShiftType);
3053     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3054     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
3055     Inst.addOperand(MCOperand::createImm(Val));
3056   }
3057 
3058   void addT2MemRegOffsetOperands(MCInst &Inst, unsigned N) const {
3059     assert(N == 3 && "Invalid number of operands!");
3060     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3061     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
3062     Inst.addOperand(MCOperand::createImm(Memory.ShiftImm));
3063   }
3064 
3065   void addMemThumbRROperands(MCInst &Inst, unsigned N) const {
3066     assert(N == 2 && "Invalid number of operands!");
3067     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3068     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
3069   }
3070 
3071   void addMemThumbRIs4Operands(MCInst &Inst, unsigned N) const {
3072     assert(N == 2 && "Invalid number of operands!");
3073     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 4) : 0;
3074     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3075     Inst.addOperand(MCOperand::createImm(Val));
3076   }
3077 
3078   void addMemThumbRIs2Operands(MCInst &Inst, unsigned N) const {
3079     assert(N == 2 && "Invalid number of operands!");
3080     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 2) : 0;
3081     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3082     Inst.addOperand(MCOperand::createImm(Val));
3083   }
3084 
3085   void addMemThumbRIs1Operands(MCInst &Inst, unsigned N) const {
3086     assert(N == 2 && "Invalid number of operands!");
3087     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue()) : 0;
3088     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3089     Inst.addOperand(MCOperand::createImm(Val));
3090   }
3091 
3092   void addMemThumbSPIOperands(MCInst &Inst, unsigned N) const {
3093     assert(N == 2 && "Invalid number of operands!");
3094     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 4) : 0;
3095     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3096     Inst.addOperand(MCOperand::createImm(Val));
3097   }
3098 
3099   void addPostIdxImm8Operands(MCInst &Inst, unsigned N) const {
3100     assert(N == 1 && "Invalid number of operands!");
3101     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
3102     assert(CE && "non-constant post-idx-imm8 operand!");
3103     int Imm = CE->getValue();
3104     bool isAdd = Imm >= 0;
3105     if (Imm == std::numeric_limits<int32_t>::min()) Imm = 0;
3106     Imm = (Imm < 0 ? -Imm : Imm) | (int)isAdd << 8;
3107     Inst.addOperand(MCOperand::createImm(Imm));
3108   }
3109 
3110   void addPostIdxImm8s4Operands(MCInst &Inst, unsigned N) const {
3111     assert(N == 1 && "Invalid number of operands!");
3112     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
3113     assert(CE && "non-constant post-idx-imm8s4 operand!");
3114     int Imm = CE->getValue();
3115     bool isAdd = Imm >= 0;
3116     if (Imm == std::numeric_limits<int32_t>::min()) Imm = 0;
3117     // Immediate is scaled by 4.
3118     Imm = ((Imm < 0 ? -Imm : Imm) / 4) | (int)isAdd << 8;
3119     Inst.addOperand(MCOperand::createImm(Imm));
3120   }
3121 
3122   void addPostIdxRegOperands(MCInst &Inst, unsigned N) const {
3123     assert(N == 2 && "Invalid number of operands!");
3124     Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
3125     Inst.addOperand(MCOperand::createImm(PostIdxReg.isAdd));
3126   }
3127 
3128   void addPostIdxRegShiftedOperands(MCInst &Inst, unsigned N) const {
3129     assert(N == 2 && "Invalid number of operands!");
3130     Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
3131     // The sign, shift type, and shift amount are encoded in a single operand
3132     // using the AM2 encoding helpers.
3133     ARM_AM::AddrOpc opc = PostIdxReg.isAdd ? ARM_AM::add : ARM_AM::sub;
3134     unsigned Imm = ARM_AM::getAM2Opc(opc, PostIdxReg.ShiftImm,
3135                                      PostIdxReg.ShiftTy);
3136     Inst.addOperand(MCOperand::createImm(Imm));
3137   }
3138 
3139   void addPowerTwoOperands(MCInst &Inst, unsigned N) const {
3140     assert(N == 1 && "Invalid number of operands!");
3141     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
3142     Inst.addOperand(MCOperand::createImm(CE->getValue()));
3143   }
3144 
3145   void addMSRMaskOperands(MCInst &Inst, unsigned N) const {
3146     assert(N == 1 && "Invalid number of operands!");
3147     Inst.addOperand(MCOperand::createImm(unsigned(getMSRMask())));
3148   }
3149 
3150   void addBankedRegOperands(MCInst &Inst, unsigned N) const {
3151     assert(N == 1 && "Invalid number of operands!");
3152     Inst.addOperand(MCOperand::createImm(unsigned(getBankedReg())));
3153   }
3154 
3155   void addProcIFlagsOperands(MCInst &Inst, unsigned N) const {
3156     assert(N == 1 && "Invalid number of operands!");
3157     Inst.addOperand(MCOperand::createImm(unsigned(getProcIFlags())));
3158   }
3159 
3160   void addVecListOperands(MCInst &Inst, unsigned N) const {
3161     assert(N == 1 && "Invalid number of operands!");
3162     Inst.addOperand(MCOperand::createReg(VectorList.RegNum));
3163   }
3164 
3165   void addMVEVecListOperands(MCInst &Inst, unsigned N) const {
3166     assert(N == 1 && "Invalid number of operands!");
3167 
3168     // When we come here, the VectorList field will identify a range
3169     // of q-registers by its base register and length, and it will
3170     // have already been error-checked to be the expected length of
3171     // range and contain only q-regs in the range q0-q7. So we can
3172     // count on the base register being in the range q0-q6 (for 2
3173     // regs) or q0-q4 (for 4)
3174     //
3175     // The MVE instructions taking a register range of this kind will
3176     // need an operand in the QQPR or QQQQPR class, representing the
3177     // entire range as a unit. So we must translate into that class,
3178     // by finding the index of the base register in the MQPR reg
3179     // class, and returning the super-register at the corresponding
3180     // index in the target class.
3181 
3182     const MCRegisterClass *RC_in = &ARMMCRegisterClasses[ARM::MQPRRegClassID];
3183     const MCRegisterClass *RC_out = (VectorList.Count == 2) ?
3184       &ARMMCRegisterClasses[ARM::QQPRRegClassID] :
3185       &ARMMCRegisterClasses[ARM::QQQQPRRegClassID];
3186 
3187     unsigned I, E = RC_out->getNumRegs();
3188     for (I = 0; I < E; I++)
3189       if (RC_in->getRegister(I) == VectorList.RegNum)
3190         break;
3191     assert(I < E && "Invalid vector list start register!");
3192 
3193     Inst.addOperand(MCOperand::createReg(RC_out->getRegister(I)));
3194   }
3195 
3196   void addVecListIndexedOperands(MCInst &Inst, unsigned N) const {
3197     assert(N == 2 && "Invalid number of operands!");
3198     Inst.addOperand(MCOperand::createReg(VectorList.RegNum));
3199     Inst.addOperand(MCOperand::createImm(VectorList.LaneIndex));
3200   }
3201 
3202   void addVectorIndex8Operands(MCInst &Inst, unsigned N) const {
3203     assert(N == 1 && "Invalid number of operands!");
3204     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
3205   }
3206 
3207   void addVectorIndex16Operands(MCInst &Inst, unsigned N) const {
3208     assert(N == 1 && "Invalid number of operands!");
3209     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
3210   }
3211 
3212   void addVectorIndex32Operands(MCInst &Inst, unsigned N) const {
3213     assert(N == 1 && "Invalid number of operands!");
3214     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
3215   }
3216 
3217   void addVectorIndex64Operands(MCInst &Inst, unsigned N) const {
3218     assert(N == 1 && "Invalid number of operands!");
3219     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
3220   }
3221 
3222   void addMVEVectorIndexOperands(MCInst &Inst, unsigned N) const {
3223     assert(N == 1 && "Invalid number of operands!");
3224     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
3225   }
3226 
3227   void addMVEPairVectorIndexOperands(MCInst &Inst, unsigned N) const {
3228     assert(N == 1 && "Invalid number of operands!");
3229     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
3230   }
3231 
3232   void addNEONi8splatOperands(MCInst &Inst, unsigned N) const {
3233     assert(N == 1 && "Invalid number of operands!");
3234     // The immediate encodes the type of constant as well as the value.
3235     // Mask in that this is an i8 splat.
3236     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
3237     Inst.addOperand(MCOperand::createImm(CE->getValue() | 0xe00));
3238   }
3239 
3240   void addNEONi16splatOperands(MCInst &Inst, unsigned N) const {
3241     assert(N == 1 && "Invalid number of operands!");
3242     // The immediate encodes the type of constant as well as the value.
3243     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
3244     unsigned Value = CE->getValue();
3245     Value = ARM_AM::encodeNEONi16splat(Value);
3246     Inst.addOperand(MCOperand::createImm(Value));
3247   }
3248 
3249   void addNEONi16splatNotOperands(MCInst &Inst, unsigned N) const {
3250     assert(N == 1 && "Invalid number of operands!");
3251     // The immediate encodes the type of constant as well as the value.
3252     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
3253     unsigned Value = CE->getValue();
3254     Value = ARM_AM::encodeNEONi16splat(~Value & 0xffff);
3255     Inst.addOperand(MCOperand::createImm(Value));
3256   }
3257 
3258   void addNEONi32splatOperands(MCInst &Inst, unsigned N) const {
3259     assert(N == 1 && "Invalid number of operands!");
3260     // The immediate encodes the type of constant as well as the value.
3261     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
3262     unsigned Value = CE->getValue();
3263     Value = ARM_AM::encodeNEONi32splat(Value);
3264     Inst.addOperand(MCOperand::createImm(Value));
3265   }
3266 
3267   void addNEONi32splatNotOperands(MCInst &Inst, unsigned N) const {
3268     assert(N == 1 && "Invalid number of operands!");
3269     // The immediate encodes the type of constant as well as the value.
3270     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
3271     unsigned Value = CE->getValue();
3272     Value = ARM_AM::encodeNEONi32splat(~Value);
3273     Inst.addOperand(MCOperand::createImm(Value));
3274   }
3275 
3276   void addNEONi8ReplicateOperands(MCInst &Inst, bool Inv) const {
3277     // The immediate encodes the type of constant as well as the value.
3278     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
3279     assert((Inst.getOpcode() == ARM::VMOVv8i8 ||
3280             Inst.getOpcode() == ARM::VMOVv16i8) &&
3281           "All instructions that wants to replicate non-zero byte "
3282           "always must be replaced with VMOVv8i8 or VMOVv16i8.");
3283     unsigned Value = CE->getValue();
3284     if (Inv)
3285       Value = ~Value;
3286     unsigned B = Value & 0xff;
3287     B |= 0xe00; // cmode = 0b1110
3288     Inst.addOperand(MCOperand::createImm(B));
3289   }
3290 
3291   void addNEONinvi8ReplicateOperands(MCInst &Inst, unsigned N) const {
3292     assert(N == 1 && "Invalid number of operands!");
3293     addNEONi8ReplicateOperands(Inst, true);
3294   }
3295 
3296   static unsigned encodeNeonVMOVImmediate(unsigned Value) {
3297     if (Value >= 256 && Value <= 0xffff)
3298       Value = (Value >> 8) | ((Value & 0xff) ? 0xc00 : 0x200);
3299     else if (Value > 0xffff && Value <= 0xffffff)
3300       Value = (Value >> 16) | ((Value & 0xff) ? 0xd00 : 0x400);
3301     else if (Value > 0xffffff)
3302       Value = (Value >> 24) | 0x600;
3303     return Value;
3304   }
3305 
3306   void addNEONi32vmovOperands(MCInst &Inst, unsigned N) const {
3307     assert(N == 1 && "Invalid number of operands!");
3308     // The immediate encodes the type of constant as well as the value.
3309     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
3310     unsigned Value = encodeNeonVMOVImmediate(CE->getValue());
3311     Inst.addOperand(MCOperand::createImm(Value));
3312   }
3313 
3314   void addNEONvmovi8ReplicateOperands(MCInst &Inst, unsigned N) const {
3315     assert(N == 1 && "Invalid number of operands!");
3316     addNEONi8ReplicateOperands(Inst, false);
3317   }
3318 
3319   void addNEONvmovi16ReplicateOperands(MCInst &Inst, unsigned N) const {
3320     assert(N == 1 && "Invalid number of operands!");
3321     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
3322     assert((Inst.getOpcode() == ARM::VMOVv4i16 ||
3323             Inst.getOpcode() == ARM::VMOVv8i16 ||
3324             Inst.getOpcode() == ARM::VMVNv4i16 ||
3325             Inst.getOpcode() == ARM::VMVNv8i16) &&
3326           "All instructions that want to replicate non-zero half-word "
3327           "always must be replaced with V{MOV,MVN}v{4,8}i16.");
3328     uint64_t Value = CE->getValue();
3329     unsigned Elem = Value & 0xffff;
3330     if (Elem >= 256)
3331       Elem = (Elem >> 8) | 0x200;
3332     Inst.addOperand(MCOperand::createImm(Elem));
3333   }
3334 
3335   void addNEONi32vmovNegOperands(MCInst &Inst, unsigned N) const {
3336     assert(N == 1 && "Invalid number of operands!");
3337     // The immediate encodes the type of constant as well as the value.
3338     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
3339     unsigned Value = encodeNeonVMOVImmediate(~CE->getValue());
3340     Inst.addOperand(MCOperand::createImm(Value));
3341   }
3342 
3343   void addNEONvmovi32ReplicateOperands(MCInst &Inst, unsigned N) const {
3344     assert(N == 1 && "Invalid number of operands!");
3345     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
3346     assert((Inst.getOpcode() == ARM::VMOVv2i32 ||
3347             Inst.getOpcode() == ARM::VMOVv4i32 ||
3348             Inst.getOpcode() == ARM::VMVNv2i32 ||
3349             Inst.getOpcode() == ARM::VMVNv4i32) &&
3350           "All instructions that want to replicate non-zero word "
3351           "always must be replaced with V{MOV,MVN}v{2,4}i32.");
3352     uint64_t Value = CE->getValue();
3353     unsigned Elem = encodeNeonVMOVImmediate(Value & 0xffffffff);
3354     Inst.addOperand(MCOperand::createImm(Elem));
3355   }
3356 
3357   void addNEONi64splatOperands(MCInst &Inst, unsigned N) const {
3358     assert(N == 1 && "Invalid number of operands!");
3359     // The immediate encodes the type of constant as well as the value.
3360     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
3361     uint64_t Value = CE->getValue();
3362     unsigned Imm = 0;
3363     for (unsigned i = 0; i < 8; ++i, Value >>= 8) {
3364       Imm |= (Value & 1) << i;
3365     }
3366     Inst.addOperand(MCOperand::createImm(Imm | 0x1e00));
3367   }
3368 
3369   void addComplexRotationEvenOperands(MCInst &Inst, unsigned N) const {
3370     assert(N == 1 && "Invalid number of operands!");
3371     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
3372     Inst.addOperand(MCOperand::createImm(CE->getValue() / 90));
3373   }
3374 
3375   void addComplexRotationOddOperands(MCInst &Inst, unsigned N) const {
3376     assert(N == 1 && "Invalid number of operands!");
3377     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
3378     Inst.addOperand(MCOperand::createImm((CE->getValue() - 90) / 180));
3379   }
3380 
3381   void addMveSaturateOperands(MCInst &Inst, unsigned N) const {
3382     assert(N == 1 && "Invalid number of operands!");
3383     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
3384     unsigned Imm = CE->getValue();
3385     assert((Imm == 48 || Imm == 64) && "Invalid saturate operand");
3386     Inst.addOperand(MCOperand::createImm(Imm == 48 ? 1 : 0));
3387   }
3388 
3389   void print(raw_ostream &OS) const override;
3390 
3391   static std::unique_ptr<ARMOperand> CreateITMask(unsigned Mask, SMLoc S) {
3392     auto Op = make_unique<ARMOperand>(k_ITCondMask);
3393     Op->ITMask.Mask = Mask;
3394     Op->StartLoc = S;
3395     Op->EndLoc = S;
3396     return Op;
3397   }
3398 
3399   static std::unique_ptr<ARMOperand> CreateCondCode(ARMCC::CondCodes CC,
3400                                                     SMLoc S) {
3401     auto Op = make_unique<ARMOperand>(k_CondCode);
3402     Op->CC.Val = CC;
3403     Op->StartLoc = S;
3404     Op->EndLoc = S;
3405     return Op;
3406   }
3407 
3408   static std::unique_ptr<ARMOperand> CreateVPTPred(ARMVCC::VPTCodes CC,
3409                                                    SMLoc S) {
3410     auto Op = make_unique<ARMOperand>(k_VPTPred);
3411     Op->VCC.Val = CC;
3412     Op->StartLoc = S;
3413     Op->EndLoc = S;
3414     return Op;
3415   }
3416 
3417   static std::unique_ptr<ARMOperand> CreateCoprocNum(unsigned CopVal, SMLoc S) {
3418     auto Op = make_unique<ARMOperand>(k_CoprocNum);
3419     Op->Cop.Val = CopVal;
3420     Op->StartLoc = S;
3421     Op->EndLoc = S;
3422     return Op;
3423   }
3424 
3425   static std::unique_ptr<ARMOperand> CreateCoprocReg(unsigned CopVal, SMLoc S) {
3426     auto Op = make_unique<ARMOperand>(k_CoprocReg);
3427     Op->Cop.Val = CopVal;
3428     Op->StartLoc = S;
3429     Op->EndLoc = S;
3430     return Op;
3431   }
3432 
3433   static std::unique_ptr<ARMOperand> CreateCoprocOption(unsigned Val, SMLoc S,
3434                                                         SMLoc E) {
3435     auto Op = make_unique<ARMOperand>(k_CoprocOption);
3436     Op->Cop.Val = Val;
3437     Op->StartLoc = S;
3438     Op->EndLoc = E;
3439     return Op;
3440   }
3441 
3442   static std::unique_ptr<ARMOperand> CreateCCOut(unsigned RegNum, SMLoc S) {
3443     auto Op = make_unique<ARMOperand>(k_CCOut);
3444     Op->Reg.RegNum = RegNum;
3445     Op->StartLoc = S;
3446     Op->EndLoc = S;
3447     return Op;
3448   }
3449 
3450   static std::unique_ptr<ARMOperand> CreateToken(StringRef Str, SMLoc S) {
3451     auto Op = make_unique<ARMOperand>(k_Token);
3452     Op->Tok.Data = Str.data();
3453     Op->Tok.Length = Str.size();
3454     Op->StartLoc = S;
3455     Op->EndLoc = S;
3456     return Op;
3457   }
3458 
3459   static std::unique_ptr<ARMOperand> CreateReg(unsigned RegNum, SMLoc S,
3460                                                SMLoc E) {
3461     auto Op = make_unique<ARMOperand>(k_Register);
3462     Op->Reg.RegNum = RegNum;
3463     Op->StartLoc = S;
3464     Op->EndLoc = E;
3465     return Op;
3466   }
3467 
3468   static std::unique_ptr<ARMOperand>
3469   CreateShiftedRegister(ARM_AM::ShiftOpc ShTy, unsigned SrcReg,
3470                         unsigned ShiftReg, unsigned ShiftImm, SMLoc S,
3471                         SMLoc E) {
3472     auto Op = make_unique<ARMOperand>(k_ShiftedRegister);
3473     Op->RegShiftedReg.ShiftTy = ShTy;
3474     Op->RegShiftedReg.SrcReg = SrcReg;
3475     Op->RegShiftedReg.ShiftReg = ShiftReg;
3476     Op->RegShiftedReg.ShiftImm = ShiftImm;
3477     Op->StartLoc = S;
3478     Op->EndLoc = E;
3479     return Op;
3480   }
3481 
3482   static std::unique_ptr<ARMOperand>
3483   CreateShiftedImmediate(ARM_AM::ShiftOpc ShTy, unsigned SrcReg,
3484                          unsigned ShiftImm, SMLoc S, SMLoc E) {
3485     auto Op = make_unique<ARMOperand>(k_ShiftedImmediate);
3486     Op->RegShiftedImm.ShiftTy = ShTy;
3487     Op->RegShiftedImm.SrcReg = SrcReg;
3488     Op->RegShiftedImm.ShiftImm = ShiftImm;
3489     Op->StartLoc = S;
3490     Op->EndLoc = E;
3491     return Op;
3492   }
3493 
3494   static std::unique_ptr<ARMOperand> CreateShifterImm(bool isASR, unsigned Imm,
3495                                                       SMLoc S, SMLoc E) {
3496     auto Op = make_unique<ARMOperand>(k_ShifterImmediate);
3497     Op->ShifterImm.isASR = isASR;
3498     Op->ShifterImm.Imm = Imm;
3499     Op->StartLoc = S;
3500     Op->EndLoc = E;
3501     return Op;
3502   }
3503 
3504   static std::unique_ptr<ARMOperand> CreateRotImm(unsigned Imm, SMLoc S,
3505                                                   SMLoc E) {
3506     auto Op = make_unique<ARMOperand>(k_RotateImmediate);
3507     Op->RotImm.Imm = Imm;
3508     Op->StartLoc = S;
3509     Op->EndLoc = E;
3510     return Op;
3511   }
3512 
3513   static std::unique_ptr<ARMOperand> CreateModImm(unsigned Bits, unsigned Rot,
3514                                                   SMLoc S, SMLoc E) {
3515     auto Op = make_unique<ARMOperand>(k_ModifiedImmediate);
3516     Op->ModImm.Bits = Bits;
3517     Op->ModImm.Rot = Rot;
3518     Op->StartLoc = S;
3519     Op->EndLoc = E;
3520     return Op;
3521   }
3522 
3523   static std::unique_ptr<ARMOperand>
3524   CreateConstantPoolImm(const MCExpr *Val, SMLoc S, SMLoc E) {
3525     auto Op = make_unique<ARMOperand>(k_ConstantPoolImmediate);
3526     Op->Imm.Val = Val;
3527     Op->StartLoc = S;
3528     Op->EndLoc = E;
3529     return Op;
3530   }
3531 
3532   static std::unique_ptr<ARMOperand>
3533   CreateBitfield(unsigned LSB, unsigned Width, SMLoc S, SMLoc E) {
3534     auto Op = make_unique<ARMOperand>(k_BitfieldDescriptor);
3535     Op->Bitfield.LSB = LSB;
3536     Op->Bitfield.Width = Width;
3537     Op->StartLoc = S;
3538     Op->EndLoc = E;
3539     return Op;
3540   }
3541 
3542   static std::unique_ptr<ARMOperand>
3543   CreateRegList(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs,
3544                 SMLoc StartLoc, SMLoc EndLoc) {
3545     assert(Regs.size() > 0 && "RegList contains no registers?");
3546     KindTy Kind = k_RegisterList;
3547 
3548     if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(
3549             Regs.front().second)) {
3550       if (Regs.back().second == ARM::VPR)
3551         Kind = k_FPDRegisterListWithVPR;
3552       else
3553         Kind = k_DPRRegisterList;
3554     } else if (ARMMCRegisterClasses[ARM::SPRRegClassID].contains(
3555                    Regs.front().second)) {
3556       if (Regs.back().second == ARM::VPR)
3557         Kind = k_FPSRegisterListWithVPR;
3558       else
3559         Kind = k_SPRRegisterList;
3560     }
3561 
3562     // Sort based on the register encoding values.
3563     array_pod_sort(Regs.begin(), Regs.end());
3564 
3565     if (Kind == k_RegisterList && Regs.back().second == ARM::APSR)
3566       Kind = k_RegisterListWithAPSR;
3567 
3568     auto Op = make_unique<ARMOperand>(Kind);
3569     for (SmallVectorImpl<std::pair<unsigned, unsigned>>::const_iterator
3570            I = Regs.begin(), E = Regs.end(); I != E; ++I)
3571       Op->Registers.push_back(I->second);
3572 
3573     Op->StartLoc = StartLoc;
3574     Op->EndLoc = EndLoc;
3575     return Op;
3576   }
3577 
3578   static std::unique_ptr<ARMOperand> CreateVectorList(unsigned RegNum,
3579                                                       unsigned Count,
3580                                                       bool isDoubleSpaced,
3581                                                       SMLoc S, SMLoc E) {
3582     auto Op = make_unique<ARMOperand>(k_VectorList);
3583     Op->VectorList.RegNum = RegNum;
3584     Op->VectorList.Count = Count;
3585     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
3586     Op->StartLoc = S;
3587     Op->EndLoc = E;
3588     return Op;
3589   }
3590 
3591   static std::unique_ptr<ARMOperand>
3592   CreateVectorListAllLanes(unsigned RegNum, unsigned Count, bool isDoubleSpaced,
3593                            SMLoc S, SMLoc E) {
3594     auto Op = make_unique<ARMOperand>(k_VectorListAllLanes);
3595     Op->VectorList.RegNum = RegNum;
3596     Op->VectorList.Count = Count;
3597     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
3598     Op->StartLoc = S;
3599     Op->EndLoc = E;
3600     return Op;
3601   }
3602 
3603   static std::unique_ptr<ARMOperand>
3604   CreateVectorListIndexed(unsigned RegNum, unsigned Count, unsigned Index,
3605                           bool isDoubleSpaced, SMLoc S, SMLoc E) {
3606     auto Op = make_unique<ARMOperand>(k_VectorListIndexed);
3607     Op->VectorList.RegNum = RegNum;
3608     Op->VectorList.Count = Count;
3609     Op->VectorList.LaneIndex = Index;
3610     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
3611     Op->StartLoc = S;
3612     Op->EndLoc = E;
3613     return Op;
3614   }
3615 
3616   static std::unique_ptr<ARMOperand>
3617   CreateVectorIndex(unsigned Idx, SMLoc S, SMLoc E, MCContext &Ctx) {
3618     auto Op = make_unique<ARMOperand>(k_VectorIndex);
3619     Op->VectorIndex.Val = Idx;
3620     Op->StartLoc = S;
3621     Op->EndLoc = E;
3622     return Op;
3623   }
3624 
3625   static std::unique_ptr<ARMOperand> CreateImm(const MCExpr *Val, SMLoc S,
3626                                                SMLoc E) {
3627     auto Op = make_unique<ARMOperand>(k_Immediate);
3628     Op->Imm.Val = Val;
3629     Op->StartLoc = S;
3630     Op->EndLoc = E;
3631     return Op;
3632   }
3633 
3634   static std::unique_ptr<ARMOperand>
3635   CreateMem(unsigned BaseRegNum, const MCConstantExpr *OffsetImm,
3636             unsigned OffsetRegNum, ARM_AM::ShiftOpc ShiftType,
3637             unsigned ShiftImm, unsigned Alignment, bool isNegative, SMLoc S,
3638             SMLoc E, SMLoc AlignmentLoc = SMLoc()) {
3639     auto Op = make_unique<ARMOperand>(k_Memory);
3640     Op->Memory.BaseRegNum = BaseRegNum;
3641     Op->Memory.OffsetImm = OffsetImm;
3642     Op->Memory.OffsetRegNum = OffsetRegNum;
3643     Op->Memory.ShiftType = ShiftType;
3644     Op->Memory.ShiftImm = ShiftImm;
3645     Op->Memory.Alignment = Alignment;
3646     Op->Memory.isNegative = isNegative;
3647     Op->StartLoc = S;
3648     Op->EndLoc = E;
3649     Op->AlignmentLoc = AlignmentLoc;
3650     return Op;
3651   }
3652 
3653   static std::unique_ptr<ARMOperand>
3654   CreatePostIdxReg(unsigned RegNum, bool isAdd, ARM_AM::ShiftOpc ShiftTy,
3655                    unsigned ShiftImm, SMLoc S, SMLoc E) {
3656     auto Op = make_unique<ARMOperand>(k_PostIndexRegister);
3657     Op->PostIdxReg.RegNum = RegNum;
3658     Op->PostIdxReg.isAdd = isAdd;
3659     Op->PostIdxReg.ShiftTy = ShiftTy;
3660     Op->PostIdxReg.ShiftImm = ShiftImm;
3661     Op->StartLoc = S;
3662     Op->EndLoc = E;
3663     return Op;
3664   }
3665 
3666   static std::unique_ptr<ARMOperand> CreateMemBarrierOpt(ARM_MB::MemBOpt Opt,
3667                                                          SMLoc S) {
3668     auto Op = make_unique<ARMOperand>(k_MemBarrierOpt);
3669     Op->MBOpt.Val = Opt;
3670     Op->StartLoc = S;
3671     Op->EndLoc = S;
3672     return Op;
3673   }
3674 
3675   static std::unique_ptr<ARMOperand>
3676   CreateInstSyncBarrierOpt(ARM_ISB::InstSyncBOpt Opt, SMLoc S) {
3677     auto Op = make_unique<ARMOperand>(k_InstSyncBarrierOpt);
3678     Op->ISBOpt.Val = Opt;
3679     Op->StartLoc = S;
3680     Op->EndLoc = S;
3681     return Op;
3682   }
3683 
3684   static std::unique_ptr<ARMOperand>
3685   CreateTraceSyncBarrierOpt(ARM_TSB::TraceSyncBOpt Opt, SMLoc S) {
3686     auto Op = make_unique<ARMOperand>(k_TraceSyncBarrierOpt);
3687     Op->TSBOpt.Val = Opt;
3688     Op->StartLoc = S;
3689     Op->EndLoc = S;
3690     return Op;
3691   }
3692 
3693   static std::unique_ptr<ARMOperand> CreateProcIFlags(ARM_PROC::IFlags IFlags,
3694                                                       SMLoc S) {
3695     auto Op = make_unique<ARMOperand>(k_ProcIFlags);
3696     Op->IFlags.Val = IFlags;
3697     Op->StartLoc = S;
3698     Op->EndLoc = S;
3699     return Op;
3700   }
3701 
3702   static std::unique_ptr<ARMOperand> CreateMSRMask(unsigned MMask, SMLoc S) {
3703     auto Op = make_unique<ARMOperand>(k_MSRMask);
3704     Op->MMask.Val = MMask;
3705     Op->StartLoc = S;
3706     Op->EndLoc = S;
3707     return Op;
3708   }
3709 
3710   static std::unique_ptr<ARMOperand> CreateBankedReg(unsigned Reg, SMLoc S) {
3711     auto Op = make_unique<ARMOperand>(k_BankedReg);
3712     Op->BankedReg.Val = Reg;
3713     Op->StartLoc = S;
3714     Op->EndLoc = S;
3715     return Op;
3716   }
3717 };
3718 
3719 } // end anonymous namespace.
3720 
3721 void ARMOperand::print(raw_ostream &OS) const {
3722   auto RegName = [](unsigned Reg) {
3723     if (Reg)
3724       return ARMInstPrinter::getRegisterName(Reg);
3725     else
3726       return "noreg";
3727   };
3728 
3729   switch (Kind) {
3730   case k_CondCode:
3731     OS << "<ARMCC::" << ARMCondCodeToString(getCondCode()) << ">";
3732     break;
3733   case k_VPTPred:
3734     OS << "<ARMVCC::" << ARMVPTPredToString(getVPTPred()) << ">";
3735     break;
3736   case k_CCOut:
3737     OS << "<ccout " << RegName(getReg()) << ">";
3738     break;
3739   case k_ITCondMask: {
3740     static const char *const MaskStr[] = {
3741       "(invalid)", "(tttt)", "(ttt)", "(ttte)",
3742       "(tt)",      "(ttet)", "(tte)", "(ttee)",
3743       "(t)",       "(tett)", "(tet)", "(tete)",
3744       "(te)",      "(teet)", "(tee)", "(teee)",
3745     };
3746     assert((ITMask.Mask & 0xf) == ITMask.Mask);
3747     OS << "<it-mask " << MaskStr[ITMask.Mask] << ">";
3748     break;
3749   }
3750   case k_CoprocNum:
3751     OS << "<coprocessor number: " << getCoproc() << ">";
3752     break;
3753   case k_CoprocReg:
3754     OS << "<coprocessor register: " << getCoproc() << ">";
3755     break;
3756   case k_CoprocOption:
3757     OS << "<coprocessor option: " << CoprocOption.Val << ">";
3758     break;
3759   case k_MSRMask:
3760     OS << "<mask: " << getMSRMask() << ">";
3761     break;
3762   case k_BankedReg:
3763     OS << "<banked reg: " << getBankedReg() << ">";
3764     break;
3765   case k_Immediate:
3766     OS << *getImm();
3767     break;
3768   case k_MemBarrierOpt:
3769     OS << "<ARM_MB::" << MemBOptToString(getMemBarrierOpt(), false) << ">";
3770     break;
3771   case k_InstSyncBarrierOpt:
3772     OS << "<ARM_ISB::" << InstSyncBOptToString(getInstSyncBarrierOpt()) << ">";
3773     break;
3774   case k_TraceSyncBarrierOpt:
3775     OS << "<ARM_TSB::" << TraceSyncBOptToString(getTraceSyncBarrierOpt()) << ">";
3776     break;
3777   case k_Memory:
3778     OS << "<memory";
3779     if (Memory.BaseRegNum)
3780       OS << " base:" << RegName(Memory.BaseRegNum);
3781     if (Memory.OffsetImm)
3782       OS << " offset-imm:" << *Memory.OffsetImm;
3783     if (Memory.OffsetRegNum)
3784       OS << " offset-reg:" << (Memory.isNegative ? "-" : "")
3785          << RegName(Memory.OffsetRegNum);
3786     if (Memory.ShiftType != ARM_AM::no_shift) {
3787       OS << " shift-type:" << ARM_AM::getShiftOpcStr(Memory.ShiftType);
3788       OS << " shift-imm:" << Memory.ShiftImm;
3789     }
3790     if (Memory.Alignment)
3791       OS << " alignment:" << Memory.Alignment;
3792     OS << ">";
3793     break;
3794   case k_PostIndexRegister:
3795     OS << "post-idx register " << (PostIdxReg.isAdd ? "" : "-")
3796        << RegName(PostIdxReg.RegNum);
3797     if (PostIdxReg.ShiftTy != ARM_AM::no_shift)
3798       OS << ARM_AM::getShiftOpcStr(PostIdxReg.ShiftTy) << " "
3799          << PostIdxReg.ShiftImm;
3800     OS << ">";
3801     break;
3802   case k_ProcIFlags: {
3803     OS << "<ARM_PROC::";
3804     unsigned IFlags = getProcIFlags();
3805     for (int i=2; i >= 0; --i)
3806       if (IFlags & (1 << i))
3807         OS << ARM_PROC::IFlagsToString(1 << i);
3808     OS << ">";
3809     break;
3810   }
3811   case k_Register:
3812     OS << "<register " << RegName(getReg()) << ">";
3813     break;
3814   case k_ShifterImmediate:
3815     OS << "<shift " << (ShifterImm.isASR ? "asr" : "lsl")
3816        << " #" << ShifterImm.Imm << ">";
3817     break;
3818   case k_ShiftedRegister:
3819     OS << "<so_reg_reg " << RegName(RegShiftedReg.SrcReg) << " "
3820        << ARM_AM::getShiftOpcStr(RegShiftedReg.ShiftTy) << " "
3821        << RegName(RegShiftedReg.ShiftReg) << ">";
3822     break;
3823   case k_ShiftedImmediate:
3824     OS << "<so_reg_imm " << RegName(RegShiftedImm.SrcReg) << " "
3825        << ARM_AM::getShiftOpcStr(RegShiftedImm.ShiftTy) << " #"
3826        << RegShiftedImm.ShiftImm << ">";
3827     break;
3828   case k_RotateImmediate:
3829     OS << "<ror " << " #" << (RotImm.Imm * 8) << ">";
3830     break;
3831   case k_ModifiedImmediate:
3832     OS << "<mod_imm #" << ModImm.Bits << ", #"
3833        <<  ModImm.Rot << ")>";
3834     break;
3835   case k_ConstantPoolImmediate:
3836     OS << "<constant_pool_imm #" << *getConstantPoolImm();
3837     break;
3838   case k_BitfieldDescriptor:
3839     OS << "<bitfield " << "lsb: " << Bitfield.LSB
3840        << ", width: " << Bitfield.Width << ">";
3841     break;
3842   case k_RegisterList:
3843   case k_RegisterListWithAPSR:
3844   case k_DPRRegisterList:
3845   case k_SPRRegisterList:
3846   case k_FPSRegisterListWithVPR:
3847   case k_FPDRegisterListWithVPR: {
3848     OS << "<register_list ";
3849 
3850     const SmallVectorImpl<unsigned> &RegList = getRegList();
3851     for (SmallVectorImpl<unsigned>::const_iterator
3852            I = RegList.begin(), E = RegList.end(); I != E; ) {
3853       OS << RegName(*I);
3854       if (++I < E) OS << ", ";
3855     }
3856 
3857     OS << ">";
3858     break;
3859   }
3860   case k_VectorList:
3861     OS << "<vector_list " << VectorList.Count << " * "
3862        << RegName(VectorList.RegNum) << ">";
3863     break;
3864   case k_VectorListAllLanes:
3865     OS << "<vector_list(all lanes) " << VectorList.Count << " * "
3866        << RegName(VectorList.RegNum) << ">";
3867     break;
3868   case k_VectorListIndexed:
3869     OS << "<vector_list(lane " << VectorList.LaneIndex << ") "
3870        << VectorList.Count << " * " << RegName(VectorList.RegNum) << ">";
3871     break;
3872   case k_Token:
3873     OS << "'" << getToken() << "'";
3874     break;
3875   case k_VectorIndex:
3876     OS << "<vectorindex " << getVectorIndex() << ">";
3877     break;
3878   }
3879 }
3880 
3881 /// @name Auto-generated Match Functions
3882 /// {
3883 
3884 static unsigned MatchRegisterName(StringRef Name);
3885 
3886 /// }
3887 
3888 bool ARMAsmParser::ParseRegister(unsigned &RegNo,
3889                                  SMLoc &StartLoc, SMLoc &EndLoc) {
3890   const AsmToken &Tok = getParser().getTok();
3891   StartLoc = Tok.getLoc();
3892   EndLoc = Tok.getEndLoc();
3893   RegNo = tryParseRegister();
3894 
3895   return (RegNo == (unsigned)-1);
3896 }
3897 
3898 /// Try to parse a register name.  The token must be an Identifier when called,
3899 /// and if it is a register name the token is eaten and the register number is
3900 /// returned.  Otherwise return -1.
3901 int ARMAsmParser::tryParseRegister() {
3902   MCAsmParser &Parser = getParser();
3903   const AsmToken &Tok = Parser.getTok();
3904   if (Tok.isNot(AsmToken::Identifier)) return -1;
3905 
3906   std::string lowerCase = Tok.getString().lower();
3907   unsigned RegNum = MatchRegisterName(lowerCase);
3908   if (!RegNum) {
3909     RegNum = StringSwitch<unsigned>(lowerCase)
3910       .Case("r13", ARM::SP)
3911       .Case("r14", ARM::LR)
3912       .Case("r15", ARM::PC)
3913       .Case("ip", ARM::R12)
3914       // Additional register name aliases for 'gas' compatibility.
3915       .Case("a1", ARM::R0)
3916       .Case("a2", ARM::R1)
3917       .Case("a3", ARM::R2)
3918       .Case("a4", ARM::R3)
3919       .Case("v1", ARM::R4)
3920       .Case("v2", ARM::R5)
3921       .Case("v3", ARM::R6)
3922       .Case("v4", ARM::R7)
3923       .Case("v5", ARM::R8)
3924       .Case("v6", ARM::R9)
3925       .Case("v7", ARM::R10)
3926       .Case("v8", ARM::R11)
3927       .Case("sb", ARM::R9)
3928       .Case("sl", ARM::R10)
3929       .Case("fp", ARM::R11)
3930       .Default(0);
3931   }
3932   if (!RegNum) {
3933     // Check for aliases registered via .req. Canonicalize to lower case.
3934     // That's more consistent since register names are case insensitive, and
3935     // it's how the original entry was passed in from MC/MCParser/AsmParser.
3936     StringMap<unsigned>::const_iterator Entry = RegisterReqs.find(lowerCase);
3937     // If no match, return failure.
3938     if (Entry == RegisterReqs.end())
3939       return -1;
3940     Parser.Lex(); // Eat identifier token.
3941     return Entry->getValue();
3942   }
3943 
3944   // Some FPUs only have 16 D registers, so D16-D31 are invalid
3945   if (!hasD32() && RegNum >= ARM::D16 && RegNum <= ARM::D31)
3946     return -1;
3947 
3948   Parser.Lex(); // Eat identifier token.
3949 
3950   return RegNum;
3951 }
3952 
3953 // Try to parse a shifter  (e.g., "lsl <amt>"). On success, return 0.
3954 // If a recoverable error occurs, return 1. If an irrecoverable error
3955 // occurs, return -1. An irrecoverable error is one where tokens have been
3956 // consumed in the process of trying to parse the shifter (i.e., when it is
3957 // indeed a shifter operand, but malformed).
3958 int ARMAsmParser::tryParseShiftRegister(OperandVector &Operands) {
3959   MCAsmParser &Parser = getParser();
3960   SMLoc S = Parser.getTok().getLoc();
3961   const AsmToken &Tok = Parser.getTok();
3962   if (Tok.isNot(AsmToken::Identifier))
3963     return -1;
3964 
3965   std::string lowerCase = Tok.getString().lower();
3966   ARM_AM::ShiftOpc ShiftTy = StringSwitch<ARM_AM::ShiftOpc>(lowerCase)
3967       .Case("asl", ARM_AM::lsl)
3968       .Case("lsl", ARM_AM::lsl)
3969       .Case("lsr", ARM_AM::lsr)
3970       .Case("asr", ARM_AM::asr)
3971       .Case("ror", ARM_AM::ror)
3972       .Case("rrx", ARM_AM::rrx)
3973       .Default(ARM_AM::no_shift);
3974 
3975   if (ShiftTy == ARM_AM::no_shift)
3976     return 1;
3977 
3978   Parser.Lex(); // Eat the operator.
3979 
3980   // The source register for the shift has already been added to the
3981   // operand list, so we need to pop it off and combine it into the shifted
3982   // register operand instead.
3983   std::unique_ptr<ARMOperand> PrevOp(
3984       (ARMOperand *)Operands.pop_back_val().release());
3985   if (!PrevOp->isReg())
3986     return Error(PrevOp->getStartLoc(), "shift must be of a register");
3987   int SrcReg = PrevOp->getReg();
3988 
3989   SMLoc EndLoc;
3990   int64_t Imm = 0;
3991   int ShiftReg = 0;
3992   if (ShiftTy == ARM_AM::rrx) {
3993     // RRX Doesn't have an explicit shift amount. The encoder expects
3994     // the shift register to be the same as the source register. Seems odd,
3995     // but OK.
3996     ShiftReg = SrcReg;
3997   } else {
3998     // Figure out if this is shifted by a constant or a register (for non-RRX).
3999     if (Parser.getTok().is(AsmToken::Hash) ||
4000         Parser.getTok().is(AsmToken::Dollar)) {
4001       Parser.Lex(); // Eat hash.
4002       SMLoc ImmLoc = Parser.getTok().getLoc();
4003       const MCExpr *ShiftExpr = nullptr;
4004       if (getParser().parseExpression(ShiftExpr, EndLoc)) {
4005         Error(ImmLoc, "invalid immediate shift value");
4006         return -1;
4007       }
4008       // The expression must be evaluatable as an immediate.
4009       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftExpr);
4010       if (!CE) {
4011         Error(ImmLoc, "invalid immediate shift value");
4012         return -1;
4013       }
4014       // Range check the immediate.
4015       // lsl, ror: 0 <= imm <= 31
4016       // lsr, asr: 0 <= imm <= 32
4017       Imm = CE->getValue();
4018       if (Imm < 0 ||
4019           ((ShiftTy == ARM_AM::lsl || ShiftTy == ARM_AM::ror) && Imm > 31) ||
4020           ((ShiftTy == ARM_AM::lsr || ShiftTy == ARM_AM::asr) && Imm > 32)) {
4021         Error(ImmLoc, "immediate shift value out of range");
4022         return -1;
4023       }
4024       // shift by zero is a nop. Always send it through as lsl.
4025       // ('as' compatibility)
4026       if (Imm == 0)
4027         ShiftTy = ARM_AM::lsl;
4028     } else if (Parser.getTok().is(AsmToken::Identifier)) {
4029       SMLoc L = Parser.getTok().getLoc();
4030       EndLoc = Parser.getTok().getEndLoc();
4031       ShiftReg = tryParseRegister();
4032       if (ShiftReg == -1) {
4033         Error(L, "expected immediate or register in shift operand");
4034         return -1;
4035       }
4036     } else {
4037       Error(Parser.getTok().getLoc(),
4038             "expected immediate or register in shift operand");
4039       return -1;
4040     }
4041   }
4042 
4043   if (ShiftReg && ShiftTy != ARM_AM::rrx)
4044     Operands.push_back(ARMOperand::CreateShiftedRegister(ShiftTy, SrcReg,
4045                                                          ShiftReg, Imm,
4046                                                          S, EndLoc));
4047   else
4048     Operands.push_back(ARMOperand::CreateShiftedImmediate(ShiftTy, SrcReg, Imm,
4049                                                           S, EndLoc));
4050 
4051   return 0;
4052 }
4053 
4054 /// Try to parse a register name.  The token must be an Identifier when called.
4055 /// If it's a register, an AsmOperand is created. Another AsmOperand is created
4056 /// if there is a "writeback". 'true' if it's not a register.
4057 ///
4058 /// TODO this is likely to change to allow different register types and or to
4059 /// parse for a specific register type.
4060 bool ARMAsmParser::tryParseRegisterWithWriteBack(OperandVector &Operands) {
4061   MCAsmParser &Parser = getParser();
4062   SMLoc RegStartLoc = Parser.getTok().getLoc();
4063   SMLoc RegEndLoc = Parser.getTok().getEndLoc();
4064   int RegNo = tryParseRegister();
4065   if (RegNo == -1)
4066     return true;
4067 
4068   Operands.push_back(ARMOperand::CreateReg(RegNo, RegStartLoc, RegEndLoc));
4069 
4070   const AsmToken &ExclaimTok = Parser.getTok();
4071   if (ExclaimTok.is(AsmToken::Exclaim)) {
4072     Operands.push_back(ARMOperand::CreateToken(ExclaimTok.getString(),
4073                                                ExclaimTok.getLoc()));
4074     Parser.Lex(); // Eat exclaim token
4075     return false;
4076   }
4077 
4078   // Also check for an index operand. This is only legal for vector registers,
4079   // but that'll get caught OK in operand matching, so we don't need to
4080   // explicitly filter everything else out here.
4081   if (Parser.getTok().is(AsmToken::LBrac)) {
4082     SMLoc SIdx = Parser.getTok().getLoc();
4083     Parser.Lex(); // Eat left bracket token.
4084 
4085     const MCExpr *ImmVal;
4086     if (getParser().parseExpression(ImmVal))
4087       return true;
4088     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(ImmVal);
4089     if (!MCE)
4090       return TokError("immediate value expected for vector index");
4091 
4092     if (Parser.getTok().isNot(AsmToken::RBrac))
4093       return Error(Parser.getTok().getLoc(), "']' expected");
4094 
4095     SMLoc E = Parser.getTok().getEndLoc();
4096     Parser.Lex(); // Eat right bracket token.
4097 
4098     Operands.push_back(ARMOperand::CreateVectorIndex(MCE->getValue(),
4099                                                      SIdx, E,
4100                                                      getContext()));
4101   }
4102 
4103   return false;
4104 }
4105 
4106 /// MatchCoprocessorOperandName - Try to parse an coprocessor related
4107 /// instruction with a symbolic operand name.
4108 /// We accept "crN" syntax for GAS compatibility.
4109 /// <operand-name> ::= <prefix><number>
4110 /// If CoprocOp is 'c', then:
4111 ///   <prefix> ::= c | cr
4112 /// If CoprocOp is 'p', then :
4113 ///   <prefix> ::= p
4114 /// <number> ::= integer in range [0, 15]
4115 static int MatchCoprocessorOperandName(StringRef Name, char CoprocOp) {
4116   // Use the same layout as the tablegen'erated register name matcher. Ugly,
4117   // but efficient.
4118   if (Name.size() < 2 || Name[0] != CoprocOp)
4119     return -1;
4120   Name = (Name[1] == 'r') ? Name.drop_front(2) : Name.drop_front();
4121 
4122   switch (Name.size()) {
4123   default: return -1;
4124   case 1:
4125     switch (Name[0]) {
4126     default:  return -1;
4127     case '0': return 0;
4128     case '1': return 1;
4129     case '2': return 2;
4130     case '3': return 3;
4131     case '4': return 4;
4132     case '5': return 5;
4133     case '6': return 6;
4134     case '7': return 7;
4135     case '8': return 8;
4136     case '9': return 9;
4137     }
4138   case 2:
4139     if (Name[0] != '1')
4140       return -1;
4141     switch (Name[1]) {
4142     default:  return -1;
4143     // CP10 and CP11 are VFP/NEON and so vector instructions should be used.
4144     // However, old cores (v5/v6) did use them in that way.
4145     case '0': return 10;
4146     case '1': return 11;
4147     case '2': return 12;
4148     case '3': return 13;
4149     case '4': return 14;
4150     case '5': return 15;
4151     }
4152   }
4153 }
4154 
4155 /// parseITCondCode - Try to parse a condition code for an IT instruction.
4156 OperandMatchResultTy
4157 ARMAsmParser::parseITCondCode(OperandVector &Operands) {
4158   MCAsmParser &Parser = getParser();
4159   SMLoc S = Parser.getTok().getLoc();
4160   const AsmToken &Tok = Parser.getTok();
4161   if (!Tok.is(AsmToken::Identifier))
4162     return MatchOperand_NoMatch;
4163   unsigned CC = ARMCondCodeFromString(Tok.getString());
4164   if (CC == ~0U)
4165     return MatchOperand_NoMatch;
4166   Parser.Lex(); // Eat the token.
4167 
4168   Operands.push_back(ARMOperand::CreateCondCode(ARMCC::CondCodes(CC), S));
4169 
4170   return MatchOperand_Success;
4171 }
4172 
4173 /// parseCoprocNumOperand - Try to parse an coprocessor number operand. The
4174 /// token must be an Identifier when called, and if it is a coprocessor
4175 /// number, the token is eaten and the operand is added to the operand list.
4176 OperandMatchResultTy
4177 ARMAsmParser::parseCoprocNumOperand(OperandVector &Operands) {
4178   MCAsmParser &Parser = getParser();
4179   SMLoc S = Parser.getTok().getLoc();
4180   const AsmToken &Tok = Parser.getTok();
4181   if (Tok.isNot(AsmToken::Identifier))
4182     return MatchOperand_NoMatch;
4183 
4184   int Num = MatchCoprocessorOperandName(Tok.getString().lower(), 'p');
4185   if (Num == -1)
4186     return MatchOperand_NoMatch;
4187   if (!isValidCoprocessorNumber(Num, getSTI().getFeatureBits()))
4188     return MatchOperand_NoMatch;
4189 
4190   Parser.Lex(); // Eat identifier token.
4191   Operands.push_back(ARMOperand::CreateCoprocNum(Num, S));
4192   return MatchOperand_Success;
4193 }
4194 
4195 /// parseCoprocRegOperand - Try to parse an coprocessor register operand. The
4196 /// token must be an Identifier when called, and if it is a coprocessor
4197 /// number, the token is eaten and the operand is added to the operand list.
4198 OperandMatchResultTy
4199 ARMAsmParser::parseCoprocRegOperand(OperandVector &Operands) {
4200   MCAsmParser &Parser = getParser();
4201   SMLoc S = Parser.getTok().getLoc();
4202   const AsmToken &Tok = Parser.getTok();
4203   if (Tok.isNot(AsmToken::Identifier))
4204     return MatchOperand_NoMatch;
4205 
4206   int Reg = MatchCoprocessorOperandName(Tok.getString().lower(), 'c');
4207   if (Reg == -1)
4208     return MatchOperand_NoMatch;
4209 
4210   Parser.Lex(); // Eat identifier token.
4211   Operands.push_back(ARMOperand::CreateCoprocReg(Reg, S));
4212   return MatchOperand_Success;
4213 }
4214 
4215 /// parseCoprocOptionOperand - Try to parse an coprocessor option operand.
4216 /// coproc_option : '{' imm0_255 '}'
4217 OperandMatchResultTy
4218 ARMAsmParser::parseCoprocOptionOperand(OperandVector &Operands) {
4219   MCAsmParser &Parser = getParser();
4220   SMLoc S = Parser.getTok().getLoc();
4221 
4222   // If this isn't a '{', this isn't a coprocessor immediate operand.
4223   if (Parser.getTok().isNot(AsmToken::LCurly))
4224     return MatchOperand_NoMatch;
4225   Parser.Lex(); // Eat the '{'
4226 
4227   const MCExpr *Expr;
4228   SMLoc Loc = Parser.getTok().getLoc();
4229   if (getParser().parseExpression(Expr)) {
4230     Error(Loc, "illegal expression");
4231     return MatchOperand_ParseFail;
4232   }
4233   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
4234   if (!CE || CE->getValue() < 0 || CE->getValue() > 255) {
4235     Error(Loc, "coprocessor option must be an immediate in range [0, 255]");
4236     return MatchOperand_ParseFail;
4237   }
4238   int Val = CE->getValue();
4239 
4240   // Check for and consume the closing '}'
4241   if (Parser.getTok().isNot(AsmToken::RCurly))
4242     return MatchOperand_ParseFail;
4243   SMLoc E = Parser.getTok().getEndLoc();
4244   Parser.Lex(); // Eat the '}'
4245 
4246   Operands.push_back(ARMOperand::CreateCoprocOption(Val, S, E));
4247   return MatchOperand_Success;
4248 }
4249 
4250 // For register list parsing, we need to map from raw GPR register numbering
4251 // to the enumeration values. The enumeration values aren't sorted by
4252 // register number due to our using "sp", "lr" and "pc" as canonical names.
4253 static unsigned getNextRegister(unsigned Reg) {
4254   // If this is a GPR, we need to do it manually, otherwise we can rely
4255   // on the sort ordering of the enumeration since the other reg-classes
4256   // are sane.
4257   if (!ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
4258     return Reg + 1;
4259   switch(Reg) {
4260   default: llvm_unreachable("Invalid GPR number!");
4261   case ARM::R0:  return ARM::R1;  case ARM::R1:  return ARM::R2;
4262   case ARM::R2:  return ARM::R3;  case ARM::R3:  return ARM::R4;
4263   case ARM::R4:  return ARM::R5;  case ARM::R5:  return ARM::R6;
4264   case ARM::R6:  return ARM::R7;  case ARM::R7:  return ARM::R8;
4265   case ARM::R8:  return ARM::R9;  case ARM::R9:  return ARM::R10;
4266   case ARM::R10: return ARM::R11; case ARM::R11: return ARM::R12;
4267   case ARM::R12: return ARM::SP;  case ARM::SP:  return ARM::LR;
4268   case ARM::LR:  return ARM::PC;  case ARM::PC:  return ARM::R0;
4269   }
4270 }
4271 
4272 /// Parse a register list.
4273 bool ARMAsmParser::parseRegisterList(OperandVector &Operands,
4274                                      bool EnforceOrder) {
4275   MCAsmParser &Parser = getParser();
4276   if (Parser.getTok().isNot(AsmToken::LCurly))
4277     return TokError("Token is not a Left Curly Brace");
4278   SMLoc S = Parser.getTok().getLoc();
4279   Parser.Lex(); // Eat '{' token.
4280   SMLoc RegLoc = Parser.getTok().getLoc();
4281 
4282   // Check the first register in the list to see what register class
4283   // this is a list of.
4284   int Reg = tryParseRegister();
4285   if (Reg == -1)
4286     return Error(RegLoc, "register expected");
4287 
4288   // The reglist instructions have at most 16 registers, so reserve
4289   // space for that many.
4290   int EReg = 0;
4291   SmallVector<std::pair<unsigned, unsigned>, 16> Registers;
4292 
4293   // Allow Q regs and just interpret them as the two D sub-registers.
4294   if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
4295     Reg = getDRegFromQReg(Reg);
4296     EReg = MRI->getEncodingValue(Reg);
4297     Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
4298     ++Reg;
4299   }
4300   const MCRegisterClass *RC;
4301   if (ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
4302     RC = &ARMMCRegisterClasses[ARM::GPRRegClassID];
4303   else if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Reg))
4304     RC = &ARMMCRegisterClasses[ARM::DPRRegClassID];
4305   else if (ARMMCRegisterClasses[ARM::SPRRegClassID].contains(Reg))
4306     RC = &ARMMCRegisterClasses[ARM::SPRRegClassID];
4307   else if (ARMMCRegisterClasses[ARM::GPRwithAPSRnospRegClassID].contains(Reg))
4308     RC = &ARMMCRegisterClasses[ARM::GPRwithAPSRnospRegClassID];
4309   else
4310     return Error(RegLoc, "invalid register in register list");
4311 
4312   // Store the register.
4313   EReg = MRI->getEncodingValue(Reg);
4314   Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
4315 
4316   // This starts immediately after the first register token in the list,
4317   // so we can see either a comma or a minus (range separator) as a legal
4318   // next token.
4319   while (Parser.getTok().is(AsmToken::Comma) ||
4320          Parser.getTok().is(AsmToken::Minus)) {
4321     if (Parser.getTok().is(AsmToken::Minus)) {
4322       Parser.Lex(); // Eat the minus.
4323       SMLoc AfterMinusLoc = Parser.getTok().getLoc();
4324       int EndReg = tryParseRegister();
4325       if (EndReg == -1)
4326         return Error(AfterMinusLoc, "register expected");
4327       // Allow Q regs and just interpret them as the two D sub-registers.
4328       if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(EndReg))
4329         EndReg = getDRegFromQReg(EndReg) + 1;
4330       // If the register is the same as the start reg, there's nothing
4331       // more to do.
4332       if (Reg == EndReg)
4333         continue;
4334       // The register must be in the same register class as the first.
4335       if (!RC->contains(EndReg))
4336         return Error(AfterMinusLoc, "invalid register in register list");
4337       // Ranges must go from low to high.
4338       if (MRI->getEncodingValue(Reg) > MRI->getEncodingValue(EndReg))
4339         return Error(AfterMinusLoc, "bad range in register list");
4340 
4341       // Add all the registers in the range to the register list.
4342       while (Reg != EndReg) {
4343         Reg = getNextRegister(Reg);
4344         EReg = MRI->getEncodingValue(Reg);
4345         Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
4346       }
4347       continue;
4348     }
4349     Parser.Lex(); // Eat the comma.
4350     RegLoc = Parser.getTok().getLoc();
4351     int OldReg = Reg;
4352     const AsmToken RegTok = Parser.getTok();
4353     Reg = tryParseRegister();
4354     if (Reg == -1)
4355       return Error(RegLoc, "register expected");
4356     // Allow Q regs and just interpret them as the two D sub-registers.
4357     bool isQReg = false;
4358     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
4359       Reg = getDRegFromQReg(Reg);
4360       isQReg = true;
4361     }
4362     if (!RC->contains(Reg) &&
4363         RC->getID() == ARMMCRegisterClasses[ARM::GPRRegClassID].getID() &&
4364         ARMMCRegisterClasses[ARM::GPRwithAPSRnospRegClassID].contains(Reg)) {
4365       // switch the register classes, as GPRwithAPSRnospRegClassID is a partial
4366       // subset of GPRRegClassId except it contains APSR as well.
4367       RC = &ARMMCRegisterClasses[ARM::GPRwithAPSRnospRegClassID];
4368     }
4369     if (Reg == ARM::VPR && (RC == &ARMMCRegisterClasses[ARM::SPRRegClassID] ||
4370                             RC == &ARMMCRegisterClasses[ARM::DPRRegClassID])) {
4371       RC = &ARMMCRegisterClasses[ARM::FPWithVPRRegClassID];
4372       EReg = MRI->getEncodingValue(Reg);
4373       Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
4374       continue;
4375     }
4376     // The register must be in the same register class as the first.
4377     if (!RC->contains(Reg))
4378       return Error(RegLoc, "invalid register in register list");
4379     // In most cases, the list must be monotonically increasing. An
4380     // exception is CLRM, which is order-independent anyway, so
4381     // there's no potential for confusion if you write clrm {r2,r1}
4382     // instead of clrm {r1,r2}.
4383     if (EnforceOrder &&
4384         MRI->getEncodingValue(Reg) < MRI->getEncodingValue(OldReg)) {
4385       if (ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
4386         Warning(RegLoc, "register list not in ascending order");
4387       else if (!ARMMCRegisterClasses[ARM::GPRwithAPSRnospRegClassID].contains(Reg))
4388         return Error(RegLoc, "register list not in ascending order");
4389     }
4390     if (MRI->getEncodingValue(Reg) == MRI->getEncodingValue(OldReg)) {
4391       Warning(RegLoc, "duplicated register (" + RegTok.getString() +
4392               ") in register list");
4393       continue;
4394     }
4395     // VFP register lists must also be contiguous.
4396     if (RC != &ARMMCRegisterClasses[ARM::GPRRegClassID] &&
4397         RC != &ARMMCRegisterClasses[ARM::GPRwithAPSRnospRegClassID] &&
4398         Reg != OldReg + 1)
4399       return Error(RegLoc, "non-contiguous register range");
4400     EReg = MRI->getEncodingValue(Reg);
4401     Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
4402     if (isQReg) {
4403       EReg = MRI->getEncodingValue(++Reg);
4404       Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
4405     }
4406   }
4407 
4408   if (Parser.getTok().isNot(AsmToken::RCurly))
4409     return Error(Parser.getTok().getLoc(), "'}' expected");
4410   SMLoc E = Parser.getTok().getEndLoc();
4411   Parser.Lex(); // Eat '}' token.
4412 
4413   // Push the register list operand.
4414   Operands.push_back(ARMOperand::CreateRegList(Registers, S, E));
4415 
4416   // The ARM system instruction variants for LDM/STM have a '^' token here.
4417   if (Parser.getTok().is(AsmToken::Caret)) {
4418     Operands.push_back(ARMOperand::CreateToken("^",Parser.getTok().getLoc()));
4419     Parser.Lex(); // Eat '^' token.
4420   }
4421 
4422   return false;
4423 }
4424 
4425 // Helper function to parse the lane index for vector lists.
4426 OperandMatchResultTy ARMAsmParser::
4427 parseVectorLane(VectorLaneTy &LaneKind, unsigned &Index, SMLoc &EndLoc) {
4428   MCAsmParser &Parser = getParser();
4429   Index = 0; // Always return a defined index value.
4430   if (Parser.getTok().is(AsmToken::LBrac)) {
4431     Parser.Lex(); // Eat the '['.
4432     if (Parser.getTok().is(AsmToken::RBrac)) {
4433       // "Dn[]" is the 'all lanes' syntax.
4434       LaneKind = AllLanes;
4435       EndLoc = Parser.getTok().getEndLoc();
4436       Parser.Lex(); // Eat the ']'.
4437       return MatchOperand_Success;
4438     }
4439 
4440     // There's an optional '#' token here. Normally there wouldn't be, but
4441     // inline assemble puts one in, and it's friendly to accept that.
4442     if (Parser.getTok().is(AsmToken::Hash))
4443       Parser.Lex(); // Eat '#' or '$'.
4444 
4445     const MCExpr *LaneIndex;
4446     SMLoc Loc = Parser.getTok().getLoc();
4447     if (getParser().parseExpression(LaneIndex)) {
4448       Error(Loc, "illegal expression");
4449       return MatchOperand_ParseFail;
4450     }
4451     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(LaneIndex);
4452     if (!CE) {
4453       Error(Loc, "lane index must be empty or an integer");
4454       return MatchOperand_ParseFail;
4455     }
4456     if (Parser.getTok().isNot(AsmToken::RBrac)) {
4457       Error(Parser.getTok().getLoc(), "']' expected");
4458       return MatchOperand_ParseFail;
4459     }
4460     EndLoc = Parser.getTok().getEndLoc();
4461     Parser.Lex(); // Eat the ']'.
4462     int64_t Val = CE->getValue();
4463 
4464     // FIXME: Make this range check context sensitive for .8, .16, .32.
4465     if (Val < 0 || Val > 7) {
4466       Error(Parser.getTok().getLoc(), "lane index out of range");
4467       return MatchOperand_ParseFail;
4468     }
4469     Index = Val;
4470     LaneKind = IndexedLane;
4471     return MatchOperand_Success;
4472   }
4473   LaneKind = NoLanes;
4474   return MatchOperand_Success;
4475 }
4476 
4477 // parse a vector register list
4478 OperandMatchResultTy
4479 ARMAsmParser::parseVectorList(OperandVector &Operands) {
4480   MCAsmParser &Parser = getParser();
4481   VectorLaneTy LaneKind;
4482   unsigned LaneIndex;
4483   SMLoc S = Parser.getTok().getLoc();
4484   // As an extension (to match gas), support a plain D register or Q register
4485   // (without encosing curly braces) as a single or double entry list,
4486   // respectively.
4487   if (!hasMVE() && Parser.getTok().is(AsmToken::Identifier)) {
4488     SMLoc E = Parser.getTok().getEndLoc();
4489     int Reg = tryParseRegister();
4490     if (Reg == -1)
4491       return MatchOperand_NoMatch;
4492     if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Reg)) {
4493       OperandMatchResultTy Res = parseVectorLane(LaneKind, LaneIndex, E);
4494       if (Res != MatchOperand_Success)
4495         return Res;
4496       switch (LaneKind) {
4497       case NoLanes:
4498         Operands.push_back(ARMOperand::CreateVectorList(Reg, 1, false, S, E));
4499         break;
4500       case AllLanes:
4501         Operands.push_back(ARMOperand::CreateVectorListAllLanes(Reg, 1, false,
4502                                                                 S, E));
4503         break;
4504       case IndexedLane:
4505         Operands.push_back(ARMOperand::CreateVectorListIndexed(Reg, 1,
4506                                                                LaneIndex,
4507                                                                false, S, E));
4508         break;
4509       }
4510       return MatchOperand_Success;
4511     }
4512     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
4513       Reg = getDRegFromQReg(Reg);
4514       OperandMatchResultTy Res = parseVectorLane(LaneKind, LaneIndex, E);
4515       if (Res != MatchOperand_Success)
4516         return Res;
4517       switch (LaneKind) {
4518       case NoLanes:
4519         Reg = MRI->getMatchingSuperReg(Reg, ARM::dsub_0,
4520                                    &ARMMCRegisterClasses[ARM::DPairRegClassID]);
4521         Operands.push_back(ARMOperand::CreateVectorList(Reg, 2, false, S, E));
4522         break;
4523       case AllLanes:
4524         Reg = MRI->getMatchingSuperReg(Reg, ARM::dsub_0,
4525                                    &ARMMCRegisterClasses[ARM::DPairRegClassID]);
4526         Operands.push_back(ARMOperand::CreateVectorListAllLanes(Reg, 2, false,
4527                                                                 S, E));
4528         break;
4529       case IndexedLane:
4530         Operands.push_back(ARMOperand::CreateVectorListIndexed(Reg, 2,
4531                                                                LaneIndex,
4532                                                                false, S, E));
4533         break;
4534       }
4535       return MatchOperand_Success;
4536     }
4537     Error(S, "vector register expected");
4538     return MatchOperand_ParseFail;
4539   }
4540 
4541   if (Parser.getTok().isNot(AsmToken::LCurly))
4542     return MatchOperand_NoMatch;
4543 
4544   Parser.Lex(); // Eat '{' token.
4545   SMLoc RegLoc = Parser.getTok().getLoc();
4546 
4547   int Reg = tryParseRegister();
4548   if (Reg == -1) {
4549     Error(RegLoc, "register expected");
4550     return MatchOperand_ParseFail;
4551   }
4552   unsigned Count = 1;
4553   int Spacing = 0;
4554   unsigned FirstReg = Reg;
4555 
4556   if (hasMVE() && !ARMMCRegisterClasses[ARM::MQPRRegClassID].contains(Reg)) {
4557       Error(Parser.getTok().getLoc(), "vector register in range Q0-Q7 expected");
4558       return MatchOperand_ParseFail;
4559   }
4560   // The list is of D registers, but we also allow Q regs and just interpret
4561   // them as the two D sub-registers.
4562   else if (!hasMVE() && ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
4563     FirstReg = Reg = getDRegFromQReg(Reg);
4564     Spacing = 1; // double-spacing requires explicit D registers, otherwise
4565                  // it's ambiguous with four-register single spaced.
4566     ++Reg;
4567     ++Count;
4568   }
4569 
4570   SMLoc E;
4571   if (parseVectorLane(LaneKind, LaneIndex, E) != MatchOperand_Success)
4572     return MatchOperand_ParseFail;
4573 
4574   while (Parser.getTok().is(AsmToken::Comma) ||
4575          Parser.getTok().is(AsmToken::Minus)) {
4576     if (Parser.getTok().is(AsmToken::Minus)) {
4577       if (!Spacing)
4578         Spacing = 1; // Register range implies a single spaced list.
4579       else if (Spacing == 2) {
4580         Error(Parser.getTok().getLoc(),
4581               "sequential registers in double spaced list");
4582         return MatchOperand_ParseFail;
4583       }
4584       Parser.Lex(); // Eat the minus.
4585       SMLoc AfterMinusLoc = Parser.getTok().getLoc();
4586       int EndReg = tryParseRegister();
4587       if (EndReg == -1) {
4588         Error(AfterMinusLoc, "register expected");
4589         return MatchOperand_ParseFail;
4590       }
4591       // Allow Q regs and just interpret them as the two D sub-registers.
4592       if (!hasMVE() && ARMMCRegisterClasses[ARM::QPRRegClassID].contains(EndReg))
4593         EndReg = getDRegFromQReg(EndReg) + 1;
4594       // If the register is the same as the start reg, there's nothing
4595       // more to do.
4596       if (Reg == EndReg)
4597         continue;
4598       // The register must be in the same register class as the first.
4599       if ((hasMVE() &&
4600            !ARMMCRegisterClasses[ARM::MQPRRegClassID].contains(EndReg)) ||
4601           (!hasMVE() &&
4602            !ARMMCRegisterClasses[ARM::DPRRegClassID].contains(EndReg))) {
4603         Error(AfterMinusLoc, "invalid register in register list");
4604         return MatchOperand_ParseFail;
4605       }
4606       // Ranges must go from low to high.
4607       if (Reg > EndReg) {
4608         Error(AfterMinusLoc, "bad range in register list");
4609         return MatchOperand_ParseFail;
4610       }
4611       // Parse the lane specifier if present.
4612       VectorLaneTy NextLaneKind;
4613       unsigned NextLaneIndex;
4614       if (parseVectorLane(NextLaneKind, NextLaneIndex, E) !=
4615           MatchOperand_Success)
4616         return MatchOperand_ParseFail;
4617       if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
4618         Error(AfterMinusLoc, "mismatched lane index in register list");
4619         return MatchOperand_ParseFail;
4620       }
4621 
4622       // Add all the registers in the range to the register list.
4623       Count += EndReg - Reg;
4624       Reg = EndReg;
4625       continue;
4626     }
4627     Parser.Lex(); // Eat the comma.
4628     RegLoc = Parser.getTok().getLoc();
4629     int OldReg = Reg;
4630     Reg = tryParseRegister();
4631     if (Reg == -1) {
4632       Error(RegLoc, "register expected");
4633       return MatchOperand_ParseFail;
4634     }
4635 
4636     if (hasMVE()) {
4637       if (!ARMMCRegisterClasses[ARM::MQPRRegClassID].contains(Reg)) {
4638         Error(RegLoc, "vector register in range Q0-Q7 expected");
4639         return MatchOperand_ParseFail;
4640       }
4641       Spacing = 1;
4642     }
4643     // vector register lists must be contiguous.
4644     // It's OK to use the enumeration values directly here rather, as the
4645     // VFP register classes have the enum sorted properly.
4646     //
4647     // The list is of D registers, but we also allow Q regs and just interpret
4648     // them as the two D sub-registers.
4649     else if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
4650       if (!Spacing)
4651         Spacing = 1; // Register range implies a single spaced list.
4652       else if (Spacing == 2) {
4653         Error(RegLoc,
4654               "invalid register in double-spaced list (must be 'D' register')");
4655         return MatchOperand_ParseFail;
4656       }
4657       Reg = getDRegFromQReg(Reg);
4658       if (Reg != OldReg + 1) {
4659         Error(RegLoc, "non-contiguous register range");
4660         return MatchOperand_ParseFail;
4661       }
4662       ++Reg;
4663       Count += 2;
4664       // Parse the lane specifier if present.
4665       VectorLaneTy NextLaneKind;
4666       unsigned NextLaneIndex;
4667       SMLoc LaneLoc = Parser.getTok().getLoc();
4668       if (parseVectorLane(NextLaneKind, NextLaneIndex, E) !=
4669           MatchOperand_Success)
4670         return MatchOperand_ParseFail;
4671       if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
4672         Error(LaneLoc, "mismatched lane index in register list");
4673         return MatchOperand_ParseFail;
4674       }
4675       continue;
4676     }
4677     // Normal D register.
4678     // Figure out the register spacing (single or double) of the list if
4679     // we don't know it already.
4680     if (!Spacing)
4681       Spacing = 1 + (Reg == OldReg + 2);
4682 
4683     // Just check that it's contiguous and keep going.
4684     if (Reg != OldReg + Spacing) {
4685       Error(RegLoc, "non-contiguous register range");
4686       return MatchOperand_ParseFail;
4687     }
4688     ++Count;
4689     // Parse the lane specifier if present.
4690     VectorLaneTy NextLaneKind;
4691     unsigned NextLaneIndex;
4692     SMLoc EndLoc = Parser.getTok().getLoc();
4693     if (parseVectorLane(NextLaneKind, NextLaneIndex, E) != MatchOperand_Success)
4694       return MatchOperand_ParseFail;
4695     if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
4696       Error(EndLoc, "mismatched lane index in register list");
4697       return MatchOperand_ParseFail;
4698     }
4699   }
4700 
4701   if (Parser.getTok().isNot(AsmToken::RCurly)) {
4702     Error(Parser.getTok().getLoc(), "'}' expected");
4703     return MatchOperand_ParseFail;
4704   }
4705   E = Parser.getTok().getEndLoc();
4706   Parser.Lex(); // Eat '}' token.
4707 
4708   switch (LaneKind) {
4709   case NoLanes:
4710   case AllLanes: {
4711     // Two-register operands have been converted to the
4712     // composite register classes.
4713     if (Count == 2 && !hasMVE()) {
4714       const MCRegisterClass *RC = (Spacing == 1) ?
4715         &ARMMCRegisterClasses[ARM::DPairRegClassID] :
4716         &ARMMCRegisterClasses[ARM::DPairSpcRegClassID];
4717       FirstReg = MRI->getMatchingSuperReg(FirstReg, ARM::dsub_0, RC);
4718     }
4719     auto Create = (LaneKind == NoLanes ? ARMOperand::CreateVectorList :
4720                    ARMOperand::CreateVectorListAllLanes);
4721     Operands.push_back(Create(FirstReg, Count, (Spacing == 2), S, E));
4722     break;
4723   }
4724   case IndexedLane:
4725     Operands.push_back(ARMOperand::CreateVectorListIndexed(FirstReg, Count,
4726                                                            LaneIndex,
4727                                                            (Spacing == 2),
4728                                                            S, E));
4729     break;
4730   }
4731   return MatchOperand_Success;
4732 }
4733 
4734 /// parseMemBarrierOptOperand - Try to parse DSB/DMB data barrier options.
4735 OperandMatchResultTy
4736 ARMAsmParser::parseMemBarrierOptOperand(OperandVector &Operands) {
4737   MCAsmParser &Parser = getParser();
4738   SMLoc S = Parser.getTok().getLoc();
4739   const AsmToken &Tok = Parser.getTok();
4740   unsigned Opt;
4741 
4742   if (Tok.is(AsmToken::Identifier)) {
4743     StringRef OptStr = Tok.getString();
4744 
4745     Opt = StringSwitch<unsigned>(OptStr.slice(0, OptStr.size()).lower())
4746       .Case("sy",    ARM_MB::SY)
4747       .Case("st",    ARM_MB::ST)
4748       .Case("ld",    ARM_MB::LD)
4749       .Case("sh",    ARM_MB::ISH)
4750       .Case("ish",   ARM_MB::ISH)
4751       .Case("shst",  ARM_MB::ISHST)
4752       .Case("ishst", ARM_MB::ISHST)
4753       .Case("ishld", ARM_MB::ISHLD)
4754       .Case("nsh",   ARM_MB::NSH)
4755       .Case("un",    ARM_MB::NSH)
4756       .Case("nshst", ARM_MB::NSHST)
4757       .Case("nshld", ARM_MB::NSHLD)
4758       .Case("unst",  ARM_MB::NSHST)
4759       .Case("osh",   ARM_MB::OSH)
4760       .Case("oshst", ARM_MB::OSHST)
4761       .Case("oshld", ARM_MB::OSHLD)
4762       .Default(~0U);
4763 
4764     // ishld, oshld, nshld and ld are only available from ARMv8.
4765     if (!hasV8Ops() && (Opt == ARM_MB::ISHLD || Opt == ARM_MB::OSHLD ||
4766                         Opt == ARM_MB::NSHLD || Opt == ARM_MB::LD))
4767       Opt = ~0U;
4768 
4769     if (Opt == ~0U)
4770       return MatchOperand_NoMatch;
4771 
4772     Parser.Lex(); // Eat identifier token.
4773   } else if (Tok.is(AsmToken::Hash) ||
4774              Tok.is(AsmToken::Dollar) ||
4775              Tok.is(AsmToken::Integer)) {
4776     if (Parser.getTok().isNot(AsmToken::Integer))
4777       Parser.Lex(); // Eat '#' or '$'.
4778     SMLoc Loc = Parser.getTok().getLoc();
4779 
4780     const MCExpr *MemBarrierID;
4781     if (getParser().parseExpression(MemBarrierID)) {
4782       Error(Loc, "illegal expression");
4783       return MatchOperand_ParseFail;
4784     }
4785 
4786     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(MemBarrierID);
4787     if (!CE) {
4788       Error(Loc, "constant expression expected");
4789       return MatchOperand_ParseFail;
4790     }
4791 
4792     int Val = CE->getValue();
4793     if (Val & ~0xf) {
4794       Error(Loc, "immediate value out of range");
4795       return MatchOperand_ParseFail;
4796     }
4797 
4798     Opt = ARM_MB::RESERVED_0 + Val;
4799   } else
4800     return MatchOperand_ParseFail;
4801 
4802   Operands.push_back(ARMOperand::CreateMemBarrierOpt((ARM_MB::MemBOpt)Opt, S));
4803   return MatchOperand_Success;
4804 }
4805 
4806 OperandMatchResultTy
4807 ARMAsmParser::parseTraceSyncBarrierOptOperand(OperandVector &Operands) {
4808   MCAsmParser &Parser = getParser();
4809   SMLoc S = Parser.getTok().getLoc();
4810   const AsmToken &Tok = Parser.getTok();
4811 
4812   if (Tok.isNot(AsmToken::Identifier))
4813      return MatchOperand_NoMatch;
4814 
4815   if (!Tok.getString().equals_lower("csync"))
4816     return MatchOperand_NoMatch;
4817 
4818   Parser.Lex(); // Eat identifier token.
4819 
4820   Operands.push_back(ARMOperand::CreateTraceSyncBarrierOpt(ARM_TSB::CSYNC, S));
4821   return MatchOperand_Success;
4822 }
4823 
4824 /// parseInstSyncBarrierOptOperand - Try to parse ISB inst sync barrier options.
4825 OperandMatchResultTy
4826 ARMAsmParser::parseInstSyncBarrierOptOperand(OperandVector &Operands) {
4827   MCAsmParser &Parser = getParser();
4828   SMLoc S = Parser.getTok().getLoc();
4829   const AsmToken &Tok = Parser.getTok();
4830   unsigned Opt;
4831 
4832   if (Tok.is(AsmToken::Identifier)) {
4833     StringRef OptStr = Tok.getString();
4834 
4835     if (OptStr.equals_lower("sy"))
4836       Opt = ARM_ISB::SY;
4837     else
4838       return MatchOperand_NoMatch;
4839 
4840     Parser.Lex(); // Eat identifier token.
4841   } else if (Tok.is(AsmToken::Hash) ||
4842              Tok.is(AsmToken::Dollar) ||
4843              Tok.is(AsmToken::Integer)) {
4844     if (Parser.getTok().isNot(AsmToken::Integer))
4845       Parser.Lex(); // Eat '#' or '$'.
4846     SMLoc Loc = Parser.getTok().getLoc();
4847 
4848     const MCExpr *ISBarrierID;
4849     if (getParser().parseExpression(ISBarrierID)) {
4850       Error(Loc, "illegal expression");
4851       return MatchOperand_ParseFail;
4852     }
4853 
4854     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ISBarrierID);
4855     if (!CE) {
4856       Error(Loc, "constant expression expected");
4857       return MatchOperand_ParseFail;
4858     }
4859 
4860     int Val = CE->getValue();
4861     if (Val & ~0xf) {
4862       Error(Loc, "immediate value out of range");
4863       return MatchOperand_ParseFail;
4864     }
4865 
4866     Opt = ARM_ISB::RESERVED_0 + Val;
4867   } else
4868     return MatchOperand_ParseFail;
4869 
4870   Operands.push_back(ARMOperand::CreateInstSyncBarrierOpt(
4871           (ARM_ISB::InstSyncBOpt)Opt, S));
4872   return MatchOperand_Success;
4873 }
4874 
4875 
4876 /// parseProcIFlagsOperand - Try to parse iflags from CPS instruction.
4877 OperandMatchResultTy
4878 ARMAsmParser::parseProcIFlagsOperand(OperandVector &Operands) {
4879   MCAsmParser &Parser = getParser();
4880   SMLoc S = Parser.getTok().getLoc();
4881   const AsmToken &Tok = Parser.getTok();
4882   if (!Tok.is(AsmToken::Identifier))
4883     return MatchOperand_NoMatch;
4884   StringRef IFlagsStr = Tok.getString();
4885 
4886   // An iflags string of "none" is interpreted to mean that none of the AIF
4887   // bits are set.  Not a terribly useful instruction, but a valid encoding.
4888   unsigned IFlags = 0;
4889   if (IFlagsStr != "none") {
4890         for (int i = 0, e = IFlagsStr.size(); i != e; ++i) {
4891       unsigned Flag = StringSwitch<unsigned>(IFlagsStr.substr(i, 1).lower())
4892         .Case("a", ARM_PROC::A)
4893         .Case("i", ARM_PROC::I)
4894         .Case("f", ARM_PROC::F)
4895         .Default(~0U);
4896 
4897       // If some specific iflag is already set, it means that some letter is
4898       // present more than once, this is not acceptable.
4899       if (Flag == ~0U || (IFlags & Flag))
4900         return MatchOperand_NoMatch;
4901 
4902       IFlags |= Flag;
4903     }
4904   }
4905 
4906   Parser.Lex(); // Eat identifier token.
4907   Operands.push_back(ARMOperand::CreateProcIFlags((ARM_PROC::IFlags)IFlags, S));
4908   return MatchOperand_Success;
4909 }
4910 
4911 /// parseMSRMaskOperand - Try to parse mask flags from MSR instruction.
4912 OperandMatchResultTy
4913 ARMAsmParser::parseMSRMaskOperand(OperandVector &Operands) {
4914   MCAsmParser &Parser = getParser();
4915   SMLoc S = Parser.getTok().getLoc();
4916   const AsmToken &Tok = Parser.getTok();
4917 
4918   if (Tok.is(AsmToken::Integer)) {
4919     int64_t Val = Tok.getIntVal();
4920     if (Val > 255 || Val < 0) {
4921       return MatchOperand_NoMatch;
4922     }
4923     unsigned SYSmvalue = Val & 0xFF;
4924     Parser.Lex();
4925     Operands.push_back(ARMOperand::CreateMSRMask(SYSmvalue, S));
4926     return MatchOperand_Success;
4927   }
4928 
4929   if (!Tok.is(AsmToken::Identifier))
4930     return MatchOperand_NoMatch;
4931   StringRef Mask = Tok.getString();
4932 
4933   if (isMClass()) {
4934     auto TheReg = ARMSysReg::lookupMClassSysRegByName(Mask.lower());
4935     if (!TheReg || !TheReg->hasRequiredFeatures(getSTI().getFeatureBits()))
4936       return MatchOperand_NoMatch;
4937 
4938     unsigned SYSmvalue = TheReg->Encoding & 0xFFF;
4939 
4940     Parser.Lex(); // Eat identifier token.
4941     Operands.push_back(ARMOperand::CreateMSRMask(SYSmvalue, S));
4942     return MatchOperand_Success;
4943   }
4944 
4945   // Split spec_reg from flag, example: CPSR_sxf => "CPSR" and "sxf"
4946   size_t Start = 0, Next = Mask.find('_');
4947   StringRef Flags = "";
4948   std::string SpecReg = Mask.slice(Start, Next).lower();
4949   if (Next != StringRef::npos)
4950     Flags = Mask.slice(Next+1, Mask.size());
4951 
4952   // FlagsVal contains the complete mask:
4953   // 3-0: Mask
4954   // 4: Special Reg (cpsr, apsr => 0; spsr => 1)
4955   unsigned FlagsVal = 0;
4956 
4957   if (SpecReg == "apsr") {
4958     FlagsVal = StringSwitch<unsigned>(Flags)
4959     .Case("nzcvq",  0x8) // same as CPSR_f
4960     .Case("g",      0x4) // same as CPSR_s
4961     .Case("nzcvqg", 0xc) // same as CPSR_fs
4962     .Default(~0U);
4963 
4964     if (FlagsVal == ~0U) {
4965       if (!Flags.empty())
4966         return MatchOperand_NoMatch;
4967       else
4968         FlagsVal = 8; // No flag
4969     }
4970   } else if (SpecReg == "cpsr" || SpecReg == "spsr") {
4971     // cpsr_all is an alias for cpsr_fc, as is plain cpsr.
4972     if (Flags == "all" || Flags == "")
4973       Flags = "fc";
4974     for (int i = 0, e = Flags.size(); i != e; ++i) {
4975       unsigned Flag = StringSwitch<unsigned>(Flags.substr(i, 1))
4976       .Case("c", 1)
4977       .Case("x", 2)
4978       .Case("s", 4)
4979       .Case("f", 8)
4980       .Default(~0U);
4981 
4982       // If some specific flag is already set, it means that some letter is
4983       // present more than once, this is not acceptable.
4984       if (Flag == ~0U || (FlagsVal & Flag))
4985         return MatchOperand_NoMatch;
4986       FlagsVal |= Flag;
4987     }
4988   } else // No match for special register.
4989     return MatchOperand_NoMatch;
4990 
4991   // Special register without flags is NOT equivalent to "fc" flags.
4992   // NOTE: This is a divergence from gas' behavior.  Uncommenting the following
4993   // two lines would enable gas compatibility at the expense of breaking
4994   // round-tripping.
4995   //
4996   // if (!FlagsVal)
4997   //  FlagsVal = 0x9;
4998 
4999   // Bit 4: Special Reg (cpsr, apsr => 0; spsr => 1)
5000   if (SpecReg == "spsr")
5001     FlagsVal |= 16;
5002 
5003   Parser.Lex(); // Eat identifier token.
5004   Operands.push_back(ARMOperand::CreateMSRMask(FlagsVal, S));
5005   return MatchOperand_Success;
5006 }
5007 
5008 /// parseBankedRegOperand - Try to parse a banked register (e.g. "lr_irq") for
5009 /// use in the MRS/MSR instructions added to support virtualization.
5010 OperandMatchResultTy
5011 ARMAsmParser::parseBankedRegOperand(OperandVector &Operands) {
5012   MCAsmParser &Parser = getParser();
5013   SMLoc S = Parser.getTok().getLoc();
5014   const AsmToken &Tok = Parser.getTok();
5015   if (!Tok.is(AsmToken::Identifier))
5016     return MatchOperand_NoMatch;
5017   StringRef RegName = Tok.getString();
5018 
5019   auto TheReg = ARMBankedReg::lookupBankedRegByName(RegName.lower());
5020   if (!TheReg)
5021     return MatchOperand_NoMatch;
5022   unsigned Encoding = TheReg->Encoding;
5023 
5024   Parser.Lex(); // Eat identifier token.
5025   Operands.push_back(ARMOperand::CreateBankedReg(Encoding, S));
5026   return MatchOperand_Success;
5027 }
5028 
5029 OperandMatchResultTy
5030 ARMAsmParser::parsePKHImm(OperandVector &Operands, StringRef Op, int Low,
5031                           int High) {
5032   MCAsmParser &Parser = getParser();
5033   const AsmToken &Tok = Parser.getTok();
5034   if (Tok.isNot(AsmToken::Identifier)) {
5035     Error(Parser.getTok().getLoc(), Op + " operand expected.");
5036     return MatchOperand_ParseFail;
5037   }
5038   StringRef ShiftName = Tok.getString();
5039   std::string LowerOp = Op.lower();
5040   std::string UpperOp = Op.upper();
5041   if (ShiftName != LowerOp && ShiftName != UpperOp) {
5042     Error(Parser.getTok().getLoc(), Op + " operand expected.");
5043     return MatchOperand_ParseFail;
5044   }
5045   Parser.Lex(); // Eat shift type token.
5046 
5047   // There must be a '#' and a shift amount.
5048   if (Parser.getTok().isNot(AsmToken::Hash) &&
5049       Parser.getTok().isNot(AsmToken::Dollar)) {
5050     Error(Parser.getTok().getLoc(), "'#' expected");
5051     return MatchOperand_ParseFail;
5052   }
5053   Parser.Lex(); // Eat hash token.
5054 
5055   const MCExpr *ShiftAmount;
5056   SMLoc Loc = Parser.getTok().getLoc();
5057   SMLoc EndLoc;
5058   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
5059     Error(Loc, "illegal expression");
5060     return MatchOperand_ParseFail;
5061   }
5062   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
5063   if (!CE) {
5064     Error(Loc, "constant expression expected");
5065     return MatchOperand_ParseFail;
5066   }
5067   int Val = CE->getValue();
5068   if (Val < Low || Val > High) {
5069     Error(Loc, "immediate value out of range");
5070     return MatchOperand_ParseFail;
5071   }
5072 
5073   Operands.push_back(ARMOperand::CreateImm(CE, Loc, EndLoc));
5074 
5075   return MatchOperand_Success;
5076 }
5077 
5078 OperandMatchResultTy
5079 ARMAsmParser::parseSetEndImm(OperandVector &Operands) {
5080   MCAsmParser &Parser = getParser();
5081   const AsmToken &Tok = Parser.getTok();
5082   SMLoc S = Tok.getLoc();
5083   if (Tok.isNot(AsmToken::Identifier)) {
5084     Error(S, "'be' or 'le' operand expected");
5085     return MatchOperand_ParseFail;
5086   }
5087   int Val = StringSwitch<int>(Tok.getString().lower())
5088     .Case("be", 1)
5089     .Case("le", 0)
5090     .Default(-1);
5091   Parser.Lex(); // Eat the token.
5092 
5093   if (Val == -1) {
5094     Error(S, "'be' or 'le' operand expected");
5095     return MatchOperand_ParseFail;
5096   }
5097   Operands.push_back(ARMOperand::CreateImm(MCConstantExpr::create(Val,
5098                                                                   getContext()),
5099                                            S, Tok.getEndLoc()));
5100   return MatchOperand_Success;
5101 }
5102 
5103 /// parseShifterImm - Parse the shifter immediate operand for SSAT/USAT
5104 /// instructions. Legal values are:
5105 ///     lsl #n  'n' in [0,31]
5106 ///     asr #n  'n' in [1,32]
5107 ///             n == 32 encoded as n == 0.
5108 OperandMatchResultTy
5109 ARMAsmParser::parseShifterImm(OperandVector &Operands) {
5110   MCAsmParser &Parser = getParser();
5111   const AsmToken &Tok = Parser.getTok();
5112   SMLoc S = Tok.getLoc();
5113   if (Tok.isNot(AsmToken::Identifier)) {
5114     Error(S, "shift operator 'asr' or 'lsl' expected");
5115     return MatchOperand_ParseFail;
5116   }
5117   StringRef ShiftName = Tok.getString();
5118   bool isASR;
5119   if (ShiftName == "lsl" || ShiftName == "LSL")
5120     isASR = false;
5121   else if (ShiftName == "asr" || ShiftName == "ASR")
5122     isASR = true;
5123   else {
5124     Error(S, "shift operator 'asr' or 'lsl' expected");
5125     return MatchOperand_ParseFail;
5126   }
5127   Parser.Lex(); // Eat the operator.
5128 
5129   // A '#' and a shift amount.
5130   if (Parser.getTok().isNot(AsmToken::Hash) &&
5131       Parser.getTok().isNot(AsmToken::Dollar)) {
5132     Error(Parser.getTok().getLoc(), "'#' expected");
5133     return MatchOperand_ParseFail;
5134   }
5135   Parser.Lex(); // Eat hash token.
5136   SMLoc ExLoc = Parser.getTok().getLoc();
5137 
5138   const MCExpr *ShiftAmount;
5139   SMLoc EndLoc;
5140   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
5141     Error(ExLoc, "malformed shift expression");
5142     return MatchOperand_ParseFail;
5143   }
5144   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
5145   if (!CE) {
5146     Error(ExLoc, "shift amount must be an immediate");
5147     return MatchOperand_ParseFail;
5148   }
5149 
5150   int64_t Val = CE->getValue();
5151   if (isASR) {
5152     // Shift amount must be in [1,32]
5153     if (Val < 1 || Val > 32) {
5154       Error(ExLoc, "'asr' shift amount must be in range [1,32]");
5155       return MatchOperand_ParseFail;
5156     }
5157     // asr #32 encoded as asr #0, but is not allowed in Thumb2 mode.
5158     if (isThumb() && Val == 32) {
5159       Error(ExLoc, "'asr #32' shift amount not allowed in Thumb mode");
5160       return MatchOperand_ParseFail;
5161     }
5162     if (Val == 32) Val = 0;
5163   } else {
5164     // Shift amount must be in [1,32]
5165     if (Val < 0 || Val > 31) {
5166       Error(ExLoc, "'lsr' shift amount must be in range [0,31]");
5167       return MatchOperand_ParseFail;
5168     }
5169   }
5170 
5171   Operands.push_back(ARMOperand::CreateShifterImm(isASR, Val, S, EndLoc));
5172 
5173   return MatchOperand_Success;
5174 }
5175 
5176 /// parseRotImm - Parse the shifter immediate operand for SXTB/UXTB family
5177 /// of instructions. Legal values are:
5178 ///     ror #n  'n' in {0, 8, 16, 24}
5179 OperandMatchResultTy
5180 ARMAsmParser::parseRotImm(OperandVector &Operands) {
5181   MCAsmParser &Parser = getParser();
5182   const AsmToken &Tok = Parser.getTok();
5183   SMLoc S = Tok.getLoc();
5184   if (Tok.isNot(AsmToken::Identifier))
5185     return MatchOperand_NoMatch;
5186   StringRef ShiftName = Tok.getString();
5187   if (ShiftName != "ror" && ShiftName != "ROR")
5188     return MatchOperand_NoMatch;
5189   Parser.Lex(); // Eat the operator.
5190 
5191   // A '#' and a rotate amount.
5192   if (Parser.getTok().isNot(AsmToken::Hash) &&
5193       Parser.getTok().isNot(AsmToken::Dollar)) {
5194     Error(Parser.getTok().getLoc(), "'#' expected");
5195     return MatchOperand_ParseFail;
5196   }
5197   Parser.Lex(); // Eat hash token.
5198   SMLoc ExLoc = Parser.getTok().getLoc();
5199 
5200   const MCExpr *ShiftAmount;
5201   SMLoc EndLoc;
5202   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
5203     Error(ExLoc, "malformed rotate expression");
5204     return MatchOperand_ParseFail;
5205   }
5206   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
5207   if (!CE) {
5208     Error(ExLoc, "rotate amount must be an immediate");
5209     return MatchOperand_ParseFail;
5210   }
5211 
5212   int64_t Val = CE->getValue();
5213   // Shift amount must be in {0, 8, 16, 24} (0 is undocumented extension)
5214   // normally, zero is represented in asm by omitting the rotate operand
5215   // entirely.
5216   if (Val != 8 && Val != 16 && Val != 24 && Val != 0) {
5217     Error(ExLoc, "'ror' rotate amount must be 8, 16, or 24");
5218     return MatchOperand_ParseFail;
5219   }
5220 
5221   Operands.push_back(ARMOperand::CreateRotImm(Val, S, EndLoc));
5222 
5223   return MatchOperand_Success;
5224 }
5225 
5226 OperandMatchResultTy
5227 ARMAsmParser::parseModImm(OperandVector &Operands) {
5228   MCAsmParser &Parser = getParser();
5229   MCAsmLexer &Lexer = getLexer();
5230   int64_t Imm1, Imm2;
5231 
5232   SMLoc S = Parser.getTok().getLoc();
5233 
5234   // 1) A mod_imm operand can appear in the place of a register name:
5235   //   add r0, #mod_imm
5236   //   add r0, r0, #mod_imm
5237   // to correctly handle the latter, we bail out as soon as we see an
5238   // identifier.
5239   //
5240   // 2) Similarly, we do not want to parse into complex operands:
5241   //   mov r0, #mod_imm
5242   //   mov r0, :lower16:(_foo)
5243   if (Parser.getTok().is(AsmToken::Identifier) ||
5244       Parser.getTok().is(AsmToken::Colon))
5245     return MatchOperand_NoMatch;
5246 
5247   // Hash (dollar) is optional as per the ARMARM
5248   if (Parser.getTok().is(AsmToken::Hash) ||
5249       Parser.getTok().is(AsmToken::Dollar)) {
5250     // Avoid parsing into complex operands (#:)
5251     if (Lexer.peekTok().is(AsmToken::Colon))
5252       return MatchOperand_NoMatch;
5253 
5254     // Eat the hash (dollar)
5255     Parser.Lex();
5256   }
5257 
5258   SMLoc Sx1, Ex1;
5259   Sx1 = Parser.getTok().getLoc();
5260   const MCExpr *Imm1Exp;
5261   if (getParser().parseExpression(Imm1Exp, Ex1)) {
5262     Error(Sx1, "malformed expression");
5263     return MatchOperand_ParseFail;
5264   }
5265 
5266   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm1Exp);
5267 
5268   if (CE) {
5269     // Immediate must fit within 32-bits
5270     Imm1 = CE->getValue();
5271     int Enc = ARM_AM::getSOImmVal(Imm1);
5272     if (Enc != -1 && Parser.getTok().is(AsmToken::EndOfStatement)) {
5273       // We have a match!
5274       Operands.push_back(ARMOperand::CreateModImm((Enc & 0xFF),
5275                                                   (Enc & 0xF00) >> 7,
5276                                                   Sx1, Ex1));
5277       return MatchOperand_Success;
5278     }
5279 
5280     // We have parsed an immediate which is not for us, fallback to a plain
5281     // immediate. This can happen for instruction aliases. For an example,
5282     // ARMInstrInfo.td defines the alias [mov <-> mvn] which can transform
5283     // a mov (mvn) with a mod_imm_neg/mod_imm_not operand into the opposite
5284     // instruction with a mod_imm operand. The alias is defined such that the
5285     // parser method is shared, that's why we have to do this here.
5286     if (Parser.getTok().is(AsmToken::EndOfStatement)) {
5287       Operands.push_back(ARMOperand::CreateImm(Imm1Exp, Sx1, Ex1));
5288       return MatchOperand_Success;
5289     }
5290   } else {
5291     // Operands like #(l1 - l2) can only be evaluated at a later stage (via an
5292     // MCFixup). Fallback to a plain immediate.
5293     Operands.push_back(ARMOperand::CreateImm(Imm1Exp, Sx1, Ex1));
5294     return MatchOperand_Success;
5295   }
5296 
5297   // From this point onward, we expect the input to be a (#bits, #rot) pair
5298   if (Parser.getTok().isNot(AsmToken::Comma)) {
5299     Error(Sx1, "expected modified immediate operand: #[0, 255], #even[0-30]");
5300     return MatchOperand_ParseFail;
5301   }
5302 
5303   if (Imm1 & ~0xFF) {
5304     Error(Sx1, "immediate operand must a number in the range [0, 255]");
5305     return MatchOperand_ParseFail;
5306   }
5307 
5308   // Eat the comma
5309   Parser.Lex();
5310 
5311   // Repeat for #rot
5312   SMLoc Sx2, Ex2;
5313   Sx2 = Parser.getTok().getLoc();
5314 
5315   // Eat the optional hash (dollar)
5316   if (Parser.getTok().is(AsmToken::Hash) ||
5317       Parser.getTok().is(AsmToken::Dollar))
5318     Parser.Lex();
5319 
5320   const MCExpr *Imm2Exp;
5321   if (getParser().parseExpression(Imm2Exp, Ex2)) {
5322     Error(Sx2, "malformed expression");
5323     return MatchOperand_ParseFail;
5324   }
5325 
5326   CE = dyn_cast<MCConstantExpr>(Imm2Exp);
5327 
5328   if (CE) {
5329     Imm2 = CE->getValue();
5330     if (!(Imm2 & ~0x1E)) {
5331       // We have a match!
5332       Operands.push_back(ARMOperand::CreateModImm(Imm1, Imm2, S, Ex2));
5333       return MatchOperand_Success;
5334     }
5335     Error(Sx2, "immediate operand must an even number in the range [0, 30]");
5336     return MatchOperand_ParseFail;
5337   } else {
5338     Error(Sx2, "constant expression expected");
5339     return MatchOperand_ParseFail;
5340   }
5341 }
5342 
5343 OperandMatchResultTy
5344 ARMAsmParser::parseBitfield(OperandVector &Operands) {
5345   MCAsmParser &Parser = getParser();
5346   SMLoc S = Parser.getTok().getLoc();
5347   // The bitfield descriptor is really two operands, the LSB and the width.
5348   if (Parser.getTok().isNot(AsmToken::Hash) &&
5349       Parser.getTok().isNot(AsmToken::Dollar)) {
5350     Error(Parser.getTok().getLoc(), "'#' expected");
5351     return MatchOperand_ParseFail;
5352   }
5353   Parser.Lex(); // Eat hash token.
5354 
5355   const MCExpr *LSBExpr;
5356   SMLoc E = Parser.getTok().getLoc();
5357   if (getParser().parseExpression(LSBExpr)) {
5358     Error(E, "malformed immediate expression");
5359     return MatchOperand_ParseFail;
5360   }
5361   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(LSBExpr);
5362   if (!CE) {
5363     Error(E, "'lsb' operand must be an immediate");
5364     return MatchOperand_ParseFail;
5365   }
5366 
5367   int64_t LSB = CE->getValue();
5368   // The LSB must be in the range [0,31]
5369   if (LSB < 0 || LSB > 31) {
5370     Error(E, "'lsb' operand must be in the range [0,31]");
5371     return MatchOperand_ParseFail;
5372   }
5373   E = Parser.getTok().getLoc();
5374 
5375   // Expect another immediate operand.
5376   if (Parser.getTok().isNot(AsmToken::Comma)) {
5377     Error(Parser.getTok().getLoc(), "too few operands");
5378     return MatchOperand_ParseFail;
5379   }
5380   Parser.Lex(); // Eat hash token.
5381   if (Parser.getTok().isNot(AsmToken::Hash) &&
5382       Parser.getTok().isNot(AsmToken::Dollar)) {
5383     Error(Parser.getTok().getLoc(), "'#' expected");
5384     return MatchOperand_ParseFail;
5385   }
5386   Parser.Lex(); // Eat hash token.
5387 
5388   const MCExpr *WidthExpr;
5389   SMLoc EndLoc;
5390   if (getParser().parseExpression(WidthExpr, EndLoc)) {
5391     Error(E, "malformed immediate expression");
5392     return MatchOperand_ParseFail;
5393   }
5394   CE = dyn_cast<MCConstantExpr>(WidthExpr);
5395   if (!CE) {
5396     Error(E, "'width' operand must be an immediate");
5397     return MatchOperand_ParseFail;
5398   }
5399 
5400   int64_t Width = CE->getValue();
5401   // The LSB must be in the range [1,32-lsb]
5402   if (Width < 1 || Width > 32 - LSB) {
5403     Error(E, "'width' operand must be in the range [1,32-lsb]");
5404     return MatchOperand_ParseFail;
5405   }
5406 
5407   Operands.push_back(ARMOperand::CreateBitfield(LSB, Width, S, EndLoc));
5408 
5409   return MatchOperand_Success;
5410 }
5411 
5412 OperandMatchResultTy
5413 ARMAsmParser::parsePostIdxReg(OperandVector &Operands) {
5414   // Check for a post-index addressing register operand. Specifically:
5415   // postidx_reg := '+' register {, shift}
5416   //              | '-' register {, shift}
5417   //              | register {, shift}
5418 
5419   // This method must return MatchOperand_NoMatch without consuming any tokens
5420   // in the case where there is no match, as other alternatives take other
5421   // parse methods.
5422   MCAsmParser &Parser = getParser();
5423   AsmToken Tok = Parser.getTok();
5424   SMLoc S = Tok.getLoc();
5425   bool haveEaten = false;
5426   bool isAdd = true;
5427   if (Tok.is(AsmToken::Plus)) {
5428     Parser.Lex(); // Eat the '+' token.
5429     haveEaten = true;
5430   } else if (Tok.is(AsmToken::Minus)) {
5431     Parser.Lex(); // Eat the '-' token.
5432     isAdd = false;
5433     haveEaten = true;
5434   }
5435 
5436   SMLoc E = Parser.getTok().getEndLoc();
5437   int Reg = tryParseRegister();
5438   if (Reg == -1) {
5439     if (!haveEaten)
5440       return MatchOperand_NoMatch;
5441     Error(Parser.getTok().getLoc(), "register expected");
5442     return MatchOperand_ParseFail;
5443   }
5444 
5445   ARM_AM::ShiftOpc ShiftTy = ARM_AM::no_shift;
5446   unsigned ShiftImm = 0;
5447   if (Parser.getTok().is(AsmToken::Comma)) {
5448     Parser.Lex(); // Eat the ','.
5449     if (parseMemRegOffsetShift(ShiftTy, ShiftImm))
5450       return MatchOperand_ParseFail;
5451 
5452     // FIXME: Only approximates end...may include intervening whitespace.
5453     E = Parser.getTok().getLoc();
5454   }
5455 
5456   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ShiftTy,
5457                                                   ShiftImm, S, E));
5458 
5459   return MatchOperand_Success;
5460 }
5461 
5462 OperandMatchResultTy
5463 ARMAsmParser::parseAM3Offset(OperandVector &Operands) {
5464   // Check for a post-index addressing register operand. Specifically:
5465   // am3offset := '+' register
5466   //              | '-' register
5467   //              | register
5468   //              | # imm
5469   //              | # + imm
5470   //              | # - imm
5471 
5472   // This method must return MatchOperand_NoMatch without consuming any tokens
5473   // in the case where there is no match, as other alternatives take other
5474   // parse methods.
5475   MCAsmParser &Parser = getParser();
5476   AsmToken Tok = Parser.getTok();
5477   SMLoc S = Tok.getLoc();
5478 
5479   // Do immediates first, as we always parse those if we have a '#'.
5480   if (Parser.getTok().is(AsmToken::Hash) ||
5481       Parser.getTok().is(AsmToken::Dollar)) {
5482     Parser.Lex(); // Eat '#' or '$'.
5483     // Explicitly look for a '-', as we need to encode negative zero
5484     // differently.
5485     bool isNegative = Parser.getTok().is(AsmToken::Minus);
5486     const MCExpr *Offset;
5487     SMLoc E;
5488     if (getParser().parseExpression(Offset, E))
5489       return MatchOperand_ParseFail;
5490     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
5491     if (!CE) {
5492       Error(S, "constant expression expected");
5493       return MatchOperand_ParseFail;
5494     }
5495     // Negative zero is encoded as the flag value
5496     // std::numeric_limits<int32_t>::min().
5497     int32_t Val = CE->getValue();
5498     if (isNegative && Val == 0)
5499       Val = std::numeric_limits<int32_t>::min();
5500 
5501     Operands.push_back(
5502       ARMOperand::CreateImm(MCConstantExpr::create(Val, getContext()), S, E));
5503 
5504     return MatchOperand_Success;
5505   }
5506 
5507   bool haveEaten = false;
5508   bool isAdd = true;
5509   if (Tok.is(AsmToken::Plus)) {
5510     Parser.Lex(); // Eat the '+' token.
5511     haveEaten = true;
5512   } else if (Tok.is(AsmToken::Minus)) {
5513     Parser.Lex(); // Eat the '-' token.
5514     isAdd = false;
5515     haveEaten = true;
5516   }
5517 
5518   Tok = Parser.getTok();
5519   int Reg = tryParseRegister();
5520   if (Reg == -1) {
5521     if (!haveEaten)
5522       return MatchOperand_NoMatch;
5523     Error(Tok.getLoc(), "register expected");
5524     return MatchOperand_ParseFail;
5525   }
5526 
5527   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ARM_AM::no_shift,
5528                                                   0, S, Tok.getEndLoc()));
5529 
5530   return MatchOperand_Success;
5531 }
5532 
5533 /// Convert parsed operands to MCInst.  Needed here because this instruction
5534 /// only has two register operands, but multiplication is commutative so
5535 /// assemblers should accept both "mul rD, rN, rD" and "mul rD, rD, rN".
5536 void ARMAsmParser::cvtThumbMultiply(MCInst &Inst,
5537                                     const OperandVector &Operands) {
5538   ((ARMOperand &)*Operands[3]).addRegOperands(Inst, 1);
5539   ((ARMOperand &)*Operands[1]).addCCOutOperands(Inst, 1);
5540   // If we have a three-operand form, make sure to set Rn to be the operand
5541   // that isn't the same as Rd.
5542   unsigned RegOp = 4;
5543   if (Operands.size() == 6 &&
5544       ((ARMOperand &)*Operands[4]).getReg() ==
5545           ((ARMOperand &)*Operands[3]).getReg())
5546     RegOp = 5;
5547   ((ARMOperand &)*Operands[RegOp]).addRegOperands(Inst, 1);
5548   Inst.addOperand(Inst.getOperand(0));
5549   ((ARMOperand &)*Operands[2]).addCondCodeOperands(Inst, 2);
5550 }
5551 
5552 void ARMAsmParser::cvtThumbBranches(MCInst &Inst,
5553                                     const OperandVector &Operands) {
5554   int CondOp = -1, ImmOp = -1;
5555   switch(Inst.getOpcode()) {
5556     case ARM::tB:
5557     case ARM::tBcc:  CondOp = 1; ImmOp = 2; break;
5558 
5559     case ARM::t2B:
5560     case ARM::t2Bcc: CondOp = 1; ImmOp = 3; break;
5561 
5562     default: llvm_unreachable("Unexpected instruction in cvtThumbBranches");
5563   }
5564   // first decide whether or not the branch should be conditional
5565   // by looking at it's location relative to an IT block
5566   if(inITBlock()) {
5567     // inside an IT block we cannot have any conditional branches. any
5568     // such instructions needs to be converted to unconditional form
5569     switch(Inst.getOpcode()) {
5570       case ARM::tBcc: Inst.setOpcode(ARM::tB); break;
5571       case ARM::t2Bcc: Inst.setOpcode(ARM::t2B); break;
5572     }
5573   } else {
5574     // outside IT blocks we can only have unconditional branches with AL
5575     // condition code or conditional branches with non-AL condition code
5576     unsigned Cond = static_cast<ARMOperand &>(*Operands[CondOp]).getCondCode();
5577     switch(Inst.getOpcode()) {
5578       case ARM::tB:
5579       case ARM::tBcc:
5580         Inst.setOpcode(Cond == ARMCC::AL ? ARM::tB : ARM::tBcc);
5581         break;
5582       case ARM::t2B:
5583       case ARM::t2Bcc:
5584         Inst.setOpcode(Cond == ARMCC::AL ? ARM::t2B : ARM::t2Bcc);
5585         break;
5586     }
5587   }
5588 
5589   // now decide on encoding size based on branch target range
5590   switch(Inst.getOpcode()) {
5591     // classify tB as either t2B or t1B based on range of immediate operand
5592     case ARM::tB: {
5593       ARMOperand &op = static_cast<ARMOperand &>(*Operands[ImmOp]);
5594       if (!op.isSignedOffset<11, 1>() && isThumb() && hasV8MBaseline())
5595         Inst.setOpcode(ARM::t2B);
5596       break;
5597     }
5598     // classify tBcc as either t2Bcc or t1Bcc based on range of immediate operand
5599     case ARM::tBcc: {
5600       ARMOperand &op = static_cast<ARMOperand &>(*Operands[ImmOp]);
5601       if (!op.isSignedOffset<8, 1>() && isThumb() && hasV8MBaseline())
5602         Inst.setOpcode(ARM::t2Bcc);
5603       break;
5604     }
5605   }
5606   ((ARMOperand &)*Operands[ImmOp]).addImmOperands(Inst, 1);
5607   ((ARMOperand &)*Operands[CondOp]).addCondCodeOperands(Inst, 2);
5608 }
5609 
5610 void ARMAsmParser::cvtMVEVMOVQtoDReg(
5611   MCInst &Inst, const OperandVector &Operands) {
5612 
5613   // mnemonic, condition code, Rt, Rt2, Qd, idx, Qd again, idx2
5614   assert(Operands.size() == 8);
5615 
5616   ((ARMOperand &)*Operands[2]).addRegOperands(Inst, 1); // Rt
5617   ((ARMOperand &)*Operands[3]).addRegOperands(Inst, 1); // Rt2
5618   ((ARMOperand &)*Operands[4]).addRegOperands(Inst, 1); // Qd
5619   ((ARMOperand &)*Operands[5]).addMVEPairVectorIndexOperands(Inst, 1); // idx
5620   // skip second copy of Qd in Operands[6]
5621   ((ARMOperand &)*Operands[7]).addMVEPairVectorIndexOperands(Inst, 1); // idx2
5622   ((ARMOperand &)*Operands[1]).addCondCodeOperands(Inst, 2); // condition code
5623 }
5624 
5625 /// Parse an ARM memory expression, return false if successful else return true
5626 /// or an error.  The first token must be a '[' when called.
5627 bool ARMAsmParser::parseMemory(OperandVector &Operands) {
5628   MCAsmParser &Parser = getParser();
5629   SMLoc S, E;
5630   if (Parser.getTok().isNot(AsmToken::LBrac))
5631     return TokError("Token is not a Left Bracket");
5632   S = Parser.getTok().getLoc();
5633   Parser.Lex(); // Eat left bracket token.
5634 
5635   const AsmToken &BaseRegTok = Parser.getTok();
5636   int BaseRegNum = tryParseRegister();
5637   if (BaseRegNum == -1)
5638     return Error(BaseRegTok.getLoc(), "register expected");
5639 
5640   // The next token must either be a comma, a colon or a closing bracket.
5641   const AsmToken &Tok = Parser.getTok();
5642   if (!Tok.is(AsmToken::Colon) && !Tok.is(AsmToken::Comma) &&
5643       !Tok.is(AsmToken::RBrac))
5644     return Error(Tok.getLoc(), "malformed memory operand");
5645 
5646   if (Tok.is(AsmToken::RBrac)) {
5647     E = Tok.getEndLoc();
5648     Parser.Lex(); // Eat right bracket token.
5649 
5650     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, 0,
5651                                              ARM_AM::no_shift, 0, 0, false,
5652                                              S, E));
5653 
5654     // If there's a pre-indexing writeback marker, '!', just add it as a token
5655     // operand. It's rather odd, but syntactically valid.
5656     if (Parser.getTok().is(AsmToken::Exclaim)) {
5657       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
5658       Parser.Lex(); // Eat the '!'.
5659     }
5660 
5661     return false;
5662   }
5663 
5664   assert((Tok.is(AsmToken::Colon) || Tok.is(AsmToken::Comma)) &&
5665          "Lost colon or comma in memory operand?!");
5666   if (Tok.is(AsmToken::Comma)) {
5667     Parser.Lex(); // Eat the comma.
5668   }
5669 
5670   // If we have a ':', it's an alignment specifier.
5671   if (Parser.getTok().is(AsmToken::Colon)) {
5672     Parser.Lex(); // Eat the ':'.
5673     E = Parser.getTok().getLoc();
5674     SMLoc AlignmentLoc = Tok.getLoc();
5675 
5676     const MCExpr *Expr;
5677     if (getParser().parseExpression(Expr))
5678      return true;
5679 
5680     // The expression has to be a constant. Memory references with relocations
5681     // don't come through here, as they use the <label> forms of the relevant
5682     // instructions.
5683     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
5684     if (!CE)
5685       return Error (E, "constant expression expected");
5686 
5687     unsigned Align = 0;
5688     switch (CE->getValue()) {
5689     default:
5690       return Error(E,
5691                    "alignment specifier must be 16, 32, 64, 128, or 256 bits");
5692     case 16:  Align = 2; break;
5693     case 32:  Align = 4; break;
5694     case 64:  Align = 8; break;
5695     case 128: Align = 16; break;
5696     case 256: Align = 32; break;
5697     }
5698 
5699     // Now we should have the closing ']'
5700     if (Parser.getTok().isNot(AsmToken::RBrac))
5701       return Error(Parser.getTok().getLoc(), "']' expected");
5702     E = Parser.getTok().getEndLoc();
5703     Parser.Lex(); // Eat right bracket token.
5704 
5705     // Don't worry about range checking the value here. That's handled by
5706     // the is*() predicates.
5707     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, 0,
5708                                              ARM_AM::no_shift, 0, Align,
5709                                              false, S, E, AlignmentLoc));
5710 
5711     // If there's a pre-indexing writeback marker, '!', just add it as a token
5712     // operand.
5713     if (Parser.getTok().is(AsmToken::Exclaim)) {
5714       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
5715       Parser.Lex(); // Eat the '!'.
5716     }
5717 
5718     return false;
5719   }
5720 
5721   // If we have a '#', it's an immediate offset, else assume it's a register
5722   // offset. Be friendly and also accept a plain integer (without a leading
5723   // hash) for gas compatibility.
5724   if (Parser.getTok().is(AsmToken::Hash) ||
5725       Parser.getTok().is(AsmToken::Dollar) ||
5726       Parser.getTok().is(AsmToken::Integer)) {
5727     if (Parser.getTok().isNot(AsmToken::Integer))
5728       Parser.Lex(); // Eat '#' or '$'.
5729     E = Parser.getTok().getLoc();
5730 
5731     bool isNegative = getParser().getTok().is(AsmToken::Minus);
5732     const MCExpr *Offset;
5733     if (getParser().parseExpression(Offset))
5734      return true;
5735 
5736     // The expression has to be a constant. Memory references with relocations
5737     // don't come through here, as they use the <label> forms of the relevant
5738     // instructions.
5739     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
5740     if (!CE)
5741       return Error (E, "constant expression expected");
5742 
5743     // If the constant was #-0, represent it as
5744     // std::numeric_limits<int32_t>::min().
5745     int32_t Val = CE->getValue();
5746     if (isNegative && Val == 0)
5747       CE = MCConstantExpr::create(std::numeric_limits<int32_t>::min(),
5748                                   getContext());
5749 
5750     // Now we should have the closing ']'
5751     if (Parser.getTok().isNot(AsmToken::RBrac))
5752       return Error(Parser.getTok().getLoc(), "']' expected");
5753     E = Parser.getTok().getEndLoc();
5754     Parser.Lex(); // Eat right bracket token.
5755 
5756     // Don't worry about range checking the value here. That's handled by
5757     // the is*() predicates.
5758     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, CE, 0,
5759                                              ARM_AM::no_shift, 0, 0,
5760                                              false, S, E));
5761 
5762     // If there's a pre-indexing writeback marker, '!', just add it as a token
5763     // operand.
5764     if (Parser.getTok().is(AsmToken::Exclaim)) {
5765       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
5766       Parser.Lex(); // Eat the '!'.
5767     }
5768 
5769     return false;
5770   }
5771 
5772   // The register offset is optionally preceded by a '+' or '-'
5773   bool isNegative = false;
5774   if (Parser.getTok().is(AsmToken::Minus)) {
5775     isNegative = true;
5776     Parser.Lex(); // Eat the '-'.
5777   } else if (Parser.getTok().is(AsmToken::Plus)) {
5778     // Nothing to do.
5779     Parser.Lex(); // Eat the '+'.
5780   }
5781 
5782   E = Parser.getTok().getLoc();
5783   int OffsetRegNum = tryParseRegister();
5784   if (OffsetRegNum == -1)
5785     return Error(E, "register expected");
5786 
5787   // If there's a shift operator, handle it.
5788   ARM_AM::ShiftOpc ShiftType = ARM_AM::no_shift;
5789   unsigned ShiftImm = 0;
5790   if (Parser.getTok().is(AsmToken::Comma)) {
5791     Parser.Lex(); // Eat the ','.
5792     if (parseMemRegOffsetShift(ShiftType, ShiftImm))
5793       return true;
5794   }
5795 
5796   // Now we should have the closing ']'
5797   if (Parser.getTok().isNot(AsmToken::RBrac))
5798     return Error(Parser.getTok().getLoc(), "']' expected");
5799   E = Parser.getTok().getEndLoc();
5800   Parser.Lex(); // Eat right bracket token.
5801 
5802   Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, OffsetRegNum,
5803                                            ShiftType, ShiftImm, 0, isNegative,
5804                                            S, E));
5805 
5806   // If there's a pre-indexing writeback marker, '!', just add it as a token
5807   // operand.
5808   if (Parser.getTok().is(AsmToken::Exclaim)) {
5809     Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
5810     Parser.Lex(); // Eat the '!'.
5811   }
5812 
5813   return false;
5814 }
5815 
5816 /// parseMemRegOffsetShift - one of these two:
5817 ///   ( lsl | lsr | asr | ror ) , # shift_amount
5818 ///   rrx
5819 /// return true if it parses a shift otherwise it returns false.
5820 bool ARMAsmParser::parseMemRegOffsetShift(ARM_AM::ShiftOpc &St,
5821                                           unsigned &Amount) {
5822   MCAsmParser &Parser = getParser();
5823   SMLoc Loc = Parser.getTok().getLoc();
5824   const AsmToken &Tok = Parser.getTok();
5825   if (Tok.isNot(AsmToken::Identifier))
5826     return Error(Loc, "illegal shift operator");
5827   StringRef ShiftName = Tok.getString();
5828   if (ShiftName == "lsl" || ShiftName == "LSL" ||
5829       ShiftName == "asl" || ShiftName == "ASL")
5830     St = ARM_AM::lsl;
5831   else if (ShiftName == "lsr" || ShiftName == "LSR")
5832     St = ARM_AM::lsr;
5833   else if (ShiftName == "asr" || ShiftName == "ASR")
5834     St = ARM_AM::asr;
5835   else if (ShiftName == "ror" || ShiftName == "ROR")
5836     St = ARM_AM::ror;
5837   else if (ShiftName == "rrx" || ShiftName == "RRX")
5838     St = ARM_AM::rrx;
5839   else if (ShiftName == "uxtw" || ShiftName == "UXTW")
5840     St = ARM_AM::uxtw;
5841   else
5842     return Error(Loc, "illegal shift operator");
5843   Parser.Lex(); // Eat shift type token.
5844 
5845   // rrx stands alone.
5846   Amount = 0;
5847   if (St != ARM_AM::rrx) {
5848     Loc = Parser.getTok().getLoc();
5849     // A '#' and a shift amount.
5850     const AsmToken &HashTok = Parser.getTok();
5851     if (HashTok.isNot(AsmToken::Hash) &&
5852         HashTok.isNot(AsmToken::Dollar))
5853       return Error(HashTok.getLoc(), "'#' expected");
5854     Parser.Lex(); // Eat hash token.
5855 
5856     const MCExpr *Expr;
5857     if (getParser().parseExpression(Expr))
5858       return true;
5859     // Range check the immediate.
5860     // lsl, ror: 0 <= imm <= 31
5861     // lsr, asr: 0 <= imm <= 32
5862     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
5863     if (!CE)
5864       return Error(Loc, "shift amount must be an immediate");
5865     int64_t Imm = CE->getValue();
5866     if (Imm < 0 ||
5867         ((St == ARM_AM::lsl || St == ARM_AM::ror) && Imm > 31) ||
5868         ((St == ARM_AM::lsr || St == ARM_AM::asr) && Imm > 32))
5869       return Error(Loc, "immediate shift value out of range");
5870     // If <ShiftTy> #0, turn it into a no_shift.
5871     if (Imm == 0)
5872       St = ARM_AM::lsl;
5873     // For consistency, treat lsr #32 and asr #32 as having immediate value 0.
5874     if (Imm == 32)
5875       Imm = 0;
5876     Amount = Imm;
5877   }
5878 
5879   return false;
5880 }
5881 
5882 /// parseFPImm - A floating point immediate expression operand.
5883 OperandMatchResultTy
5884 ARMAsmParser::parseFPImm(OperandVector &Operands) {
5885   MCAsmParser &Parser = getParser();
5886   // Anything that can accept a floating point constant as an operand
5887   // needs to go through here, as the regular parseExpression is
5888   // integer only.
5889   //
5890   // This routine still creates a generic Immediate operand, containing
5891   // a bitcast of the 64-bit floating point value. The various operands
5892   // that accept floats can check whether the value is valid for them
5893   // via the standard is*() predicates.
5894 
5895   SMLoc S = Parser.getTok().getLoc();
5896 
5897   if (Parser.getTok().isNot(AsmToken::Hash) &&
5898       Parser.getTok().isNot(AsmToken::Dollar))
5899     return MatchOperand_NoMatch;
5900 
5901   // Disambiguate the VMOV forms that can accept an FP immediate.
5902   // vmov.f32 <sreg>, #imm
5903   // vmov.f64 <dreg>, #imm
5904   // vmov.f32 <dreg>, #imm  @ vector f32x2
5905   // vmov.f32 <qreg>, #imm  @ vector f32x4
5906   //
5907   // There are also the NEON VMOV instructions which expect an
5908   // integer constant. Make sure we don't try to parse an FPImm
5909   // for these:
5910   // vmov.i{8|16|32|64} <dreg|qreg>, #imm
5911   ARMOperand &TyOp = static_cast<ARMOperand &>(*Operands[2]);
5912   bool isVmovf = TyOp.isToken() &&
5913                  (TyOp.getToken() == ".f32" || TyOp.getToken() == ".f64" ||
5914                   TyOp.getToken() == ".f16");
5915   ARMOperand &Mnemonic = static_cast<ARMOperand &>(*Operands[0]);
5916   bool isFconst = Mnemonic.isToken() && (Mnemonic.getToken() == "fconstd" ||
5917                                          Mnemonic.getToken() == "fconsts");
5918   if (!(isVmovf || isFconst))
5919     return MatchOperand_NoMatch;
5920 
5921   Parser.Lex(); // Eat '#' or '$'.
5922 
5923   // Handle negation, as that still comes through as a separate token.
5924   bool isNegative = false;
5925   if (Parser.getTok().is(AsmToken::Minus)) {
5926     isNegative = true;
5927     Parser.Lex();
5928   }
5929   const AsmToken &Tok = Parser.getTok();
5930   SMLoc Loc = Tok.getLoc();
5931   if (Tok.is(AsmToken::Real) && isVmovf) {
5932     APFloat RealVal(APFloat::IEEEsingle(), Tok.getString());
5933     uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
5934     // If we had a '-' in front, toggle the sign bit.
5935     IntVal ^= (uint64_t)isNegative << 31;
5936     Parser.Lex(); // Eat the token.
5937     Operands.push_back(ARMOperand::CreateImm(
5938           MCConstantExpr::create(IntVal, getContext()),
5939           S, Parser.getTok().getLoc()));
5940     return MatchOperand_Success;
5941   }
5942   // Also handle plain integers. Instructions which allow floating point
5943   // immediates also allow a raw encoded 8-bit value.
5944   if (Tok.is(AsmToken::Integer) && isFconst) {
5945     int64_t Val = Tok.getIntVal();
5946     Parser.Lex(); // Eat the token.
5947     if (Val > 255 || Val < 0) {
5948       Error(Loc, "encoded floating point value out of range");
5949       return MatchOperand_ParseFail;
5950     }
5951     float RealVal = ARM_AM::getFPImmFloat(Val);
5952     Val = APFloat(RealVal).bitcastToAPInt().getZExtValue();
5953 
5954     Operands.push_back(ARMOperand::CreateImm(
5955         MCConstantExpr::create(Val, getContext()), S,
5956         Parser.getTok().getLoc()));
5957     return MatchOperand_Success;
5958   }
5959 
5960   Error(Loc, "invalid floating point immediate");
5961   return MatchOperand_ParseFail;
5962 }
5963 
5964 /// Parse a arm instruction operand.  For now this parses the operand regardless
5965 /// of the mnemonic.
5966 bool ARMAsmParser::parseOperand(OperandVector &Operands, StringRef Mnemonic) {
5967   MCAsmParser &Parser = getParser();
5968   SMLoc S, E;
5969 
5970   // Check if the current operand has a custom associated parser, if so, try to
5971   // custom parse the operand, or fallback to the general approach.
5972   OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
5973   if (ResTy == MatchOperand_Success)
5974     return false;
5975   // If there wasn't a custom match, try the generic matcher below. Otherwise,
5976   // there was a match, but an error occurred, in which case, just return that
5977   // the operand parsing failed.
5978   if (ResTy == MatchOperand_ParseFail)
5979     return true;
5980 
5981   switch (getLexer().getKind()) {
5982   default:
5983     Error(Parser.getTok().getLoc(), "unexpected token in operand");
5984     return true;
5985   case AsmToken::Identifier: {
5986     // If we've seen a branch mnemonic, the next operand must be a label.  This
5987     // is true even if the label is a register name.  So "br r1" means branch to
5988     // label "r1".
5989     bool ExpectLabel = Mnemonic == "b" || Mnemonic == "bl";
5990     if (!ExpectLabel) {
5991       if (!tryParseRegisterWithWriteBack(Operands))
5992         return false;
5993       int Res = tryParseShiftRegister(Operands);
5994       if (Res == 0) // success
5995         return false;
5996       else if (Res == -1) // irrecoverable error
5997         return true;
5998       // If this is VMRS, check for the apsr_nzcv operand.
5999       if (Mnemonic == "vmrs" &&
6000           Parser.getTok().getString().equals_lower("apsr_nzcv")) {
6001         S = Parser.getTok().getLoc();
6002         Parser.Lex();
6003         Operands.push_back(ARMOperand::CreateToken("APSR_nzcv", S));
6004         return false;
6005       }
6006     }
6007 
6008     // Fall though for the Identifier case that is not a register or a
6009     // special name.
6010     LLVM_FALLTHROUGH;
6011   }
6012   case AsmToken::LParen:  // parenthesized expressions like (_strcmp-4)
6013   case AsmToken::Integer: // things like 1f and 2b as a branch targets
6014   case AsmToken::String:  // quoted label names.
6015   case AsmToken::Dot: {   // . as a branch target
6016     // This was not a register so parse other operands that start with an
6017     // identifier (like labels) as expressions and create them as immediates.
6018     const MCExpr *IdVal;
6019     S = Parser.getTok().getLoc();
6020     if (getParser().parseExpression(IdVal))
6021       return true;
6022     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
6023     Operands.push_back(ARMOperand::CreateImm(IdVal, S, E));
6024     return false;
6025   }
6026   case AsmToken::LBrac:
6027     return parseMemory(Operands);
6028   case AsmToken::LCurly:
6029     return parseRegisterList(Operands, !Mnemonic.startswith("clr"));
6030   case AsmToken::Dollar:
6031   case AsmToken::Hash:
6032     // #42 -> immediate.
6033     S = Parser.getTok().getLoc();
6034     Parser.Lex();
6035 
6036     if (Parser.getTok().isNot(AsmToken::Colon)) {
6037       bool isNegative = Parser.getTok().is(AsmToken::Minus);
6038       const MCExpr *ImmVal;
6039       if (getParser().parseExpression(ImmVal))
6040         return true;
6041       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ImmVal);
6042       if (CE) {
6043         int32_t Val = CE->getValue();
6044         if (isNegative && Val == 0)
6045           ImmVal = MCConstantExpr::create(std::numeric_limits<int32_t>::min(),
6046                                           getContext());
6047       }
6048       E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
6049       Operands.push_back(ARMOperand::CreateImm(ImmVal, S, E));
6050 
6051       // There can be a trailing '!' on operands that we want as a separate
6052       // '!' Token operand. Handle that here. For example, the compatibility
6053       // alias for 'srsdb sp!, #imm' is 'srsdb #imm!'.
6054       if (Parser.getTok().is(AsmToken::Exclaim)) {
6055         Operands.push_back(ARMOperand::CreateToken(Parser.getTok().getString(),
6056                                                    Parser.getTok().getLoc()));
6057         Parser.Lex(); // Eat exclaim token
6058       }
6059       return false;
6060     }
6061     // w/ a ':' after the '#', it's just like a plain ':'.
6062     LLVM_FALLTHROUGH;
6063 
6064   case AsmToken::Colon: {
6065     S = Parser.getTok().getLoc();
6066     // ":lower16:" and ":upper16:" expression prefixes
6067     // FIXME: Check it's an expression prefix,
6068     // e.g. (FOO - :lower16:BAR) isn't legal.
6069     ARMMCExpr::VariantKind RefKind;
6070     if (parsePrefix(RefKind))
6071       return true;
6072 
6073     const MCExpr *SubExprVal;
6074     if (getParser().parseExpression(SubExprVal))
6075       return true;
6076 
6077     const MCExpr *ExprVal = ARMMCExpr::create(RefKind, SubExprVal,
6078                                               getContext());
6079     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
6080     Operands.push_back(ARMOperand::CreateImm(ExprVal, S, E));
6081     return false;
6082   }
6083   case AsmToken::Equal: {
6084     S = Parser.getTok().getLoc();
6085     if (Mnemonic != "ldr") // only parse for ldr pseudo (e.g. ldr r0, =val)
6086       return Error(S, "unexpected token in operand");
6087     Parser.Lex(); // Eat '='
6088     const MCExpr *SubExprVal;
6089     if (getParser().parseExpression(SubExprVal))
6090       return true;
6091     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
6092 
6093     // execute-only: we assume that assembly programmers know what they are
6094     // doing and allow literal pool creation here
6095     Operands.push_back(ARMOperand::CreateConstantPoolImm(SubExprVal, S, E));
6096     return false;
6097   }
6098   }
6099 }
6100 
6101 // parsePrefix - Parse ARM 16-bit relocations expression prefix, i.e.
6102 //  :lower16: and :upper16:.
6103 bool ARMAsmParser::parsePrefix(ARMMCExpr::VariantKind &RefKind) {
6104   MCAsmParser &Parser = getParser();
6105   RefKind = ARMMCExpr::VK_ARM_None;
6106 
6107   // consume an optional '#' (GNU compatibility)
6108   if (getLexer().is(AsmToken::Hash))
6109     Parser.Lex();
6110 
6111   // :lower16: and :upper16: modifiers
6112   assert(getLexer().is(AsmToken::Colon) && "expected a :");
6113   Parser.Lex(); // Eat ':'
6114 
6115   if (getLexer().isNot(AsmToken::Identifier)) {
6116     Error(Parser.getTok().getLoc(), "expected prefix identifier in operand");
6117     return true;
6118   }
6119 
6120   enum {
6121     COFF = (1 << MCObjectFileInfo::IsCOFF),
6122     ELF = (1 << MCObjectFileInfo::IsELF),
6123     MACHO = (1 << MCObjectFileInfo::IsMachO),
6124     WASM = (1 << MCObjectFileInfo::IsWasm),
6125   };
6126   static const struct PrefixEntry {
6127     const char *Spelling;
6128     ARMMCExpr::VariantKind VariantKind;
6129     uint8_t SupportedFormats;
6130   } PrefixEntries[] = {
6131     { "lower16", ARMMCExpr::VK_ARM_LO16, COFF | ELF | MACHO },
6132     { "upper16", ARMMCExpr::VK_ARM_HI16, COFF | ELF | MACHO },
6133   };
6134 
6135   StringRef IDVal = Parser.getTok().getIdentifier();
6136 
6137   const auto &Prefix =
6138       std::find_if(std::begin(PrefixEntries), std::end(PrefixEntries),
6139                    [&IDVal](const PrefixEntry &PE) {
6140                       return PE.Spelling == IDVal;
6141                    });
6142   if (Prefix == std::end(PrefixEntries)) {
6143     Error(Parser.getTok().getLoc(), "unexpected prefix in operand");
6144     return true;
6145   }
6146 
6147   uint8_t CurrentFormat;
6148   switch (getContext().getObjectFileInfo()->getObjectFileType()) {
6149   case MCObjectFileInfo::IsMachO:
6150     CurrentFormat = MACHO;
6151     break;
6152   case MCObjectFileInfo::IsELF:
6153     CurrentFormat = ELF;
6154     break;
6155   case MCObjectFileInfo::IsCOFF:
6156     CurrentFormat = COFF;
6157     break;
6158   case MCObjectFileInfo::IsWasm:
6159     CurrentFormat = WASM;
6160     break;
6161   case MCObjectFileInfo::IsXCOFF:
6162     llvm_unreachable("unexpected object format");
6163     break;
6164   }
6165 
6166   if (~Prefix->SupportedFormats & CurrentFormat) {
6167     Error(Parser.getTok().getLoc(),
6168           "cannot represent relocation in the current file format");
6169     return true;
6170   }
6171 
6172   RefKind = Prefix->VariantKind;
6173   Parser.Lex();
6174 
6175   if (getLexer().isNot(AsmToken::Colon)) {
6176     Error(Parser.getTok().getLoc(), "unexpected token after prefix");
6177     return true;
6178   }
6179   Parser.Lex(); // Eat the last ':'
6180 
6181   return false;
6182 }
6183 
6184 /// Given a mnemonic, split out possible predication code and carry
6185 /// setting letters to form a canonical mnemonic and flags.
6186 //
6187 // FIXME: Would be nice to autogen this.
6188 // FIXME: This is a bit of a maze of special cases.
6189 StringRef ARMAsmParser::splitMnemonic(StringRef Mnemonic,
6190                                       StringRef ExtraToken,
6191                                       unsigned &PredicationCode,
6192                                       unsigned &VPTPredicationCode,
6193                                       bool &CarrySetting,
6194                                       unsigned &ProcessorIMod,
6195                                       StringRef &ITMask) {
6196   PredicationCode = ARMCC::AL;
6197   VPTPredicationCode = ARMVCC::None;
6198   CarrySetting = false;
6199   ProcessorIMod = 0;
6200 
6201   // Ignore some mnemonics we know aren't predicated forms.
6202   //
6203   // FIXME: Would be nice to autogen this.
6204   if ((Mnemonic == "movs" && isThumb()) ||
6205       Mnemonic == "teq"   || Mnemonic == "vceq"   || Mnemonic == "svc"   ||
6206       Mnemonic == "mls"   || Mnemonic == "smmls"  || Mnemonic == "vcls"  ||
6207       Mnemonic == "vmls"  || Mnemonic == "vnmls"  || Mnemonic == "vacge" ||
6208       Mnemonic == "vcge"  || Mnemonic == "vclt"   || Mnemonic == "vacgt" ||
6209       Mnemonic == "vaclt" || Mnemonic == "vacle"  || Mnemonic == "hlt" ||
6210       Mnemonic == "vcgt"  || Mnemonic == "vcle"   || Mnemonic == "smlal" ||
6211       Mnemonic == "umaal" || Mnemonic == "umlal"  || Mnemonic == "vabal" ||
6212       Mnemonic == "vmlal" || Mnemonic == "vpadal" || Mnemonic == "vqdmlal" ||
6213       Mnemonic == "fmuls" || Mnemonic == "vmaxnm" || Mnemonic == "vminnm" ||
6214       Mnemonic == "vcvta" || Mnemonic == "vcvtn"  || Mnemonic == "vcvtp" ||
6215       Mnemonic == "vcvtm" || Mnemonic == "vrinta" || Mnemonic == "vrintn" ||
6216       Mnemonic == "vrintp" || Mnemonic == "vrintm" || Mnemonic == "hvc" ||
6217       Mnemonic.startswith("vsel") || Mnemonic == "vins" || Mnemonic == "vmovx" ||
6218       Mnemonic == "bxns"  || Mnemonic == "blxns" ||
6219       Mnemonic == "vudot" || Mnemonic == "vsdot" ||
6220       Mnemonic == "vcmla" || Mnemonic == "vcadd" ||
6221       Mnemonic == "vfmal" || Mnemonic == "vfmsl" ||
6222       Mnemonic == "wls" || Mnemonic == "le" || Mnemonic == "dls" ||
6223       Mnemonic == "csel" || Mnemonic == "csinc" ||
6224       Mnemonic == "csinv" || Mnemonic == "csneg" || Mnemonic == "cinc" ||
6225       Mnemonic == "cinv" || Mnemonic == "cneg" || Mnemonic == "cset" ||
6226       Mnemonic == "csetm")
6227     return Mnemonic;
6228 
6229   // First, split out any predication code. Ignore mnemonics we know aren't
6230   // predicated but do have a carry-set and so weren't caught above.
6231   if (Mnemonic != "adcs" && Mnemonic != "bics" && Mnemonic != "movs" &&
6232       Mnemonic != "muls" && Mnemonic != "smlals" && Mnemonic != "smulls" &&
6233       Mnemonic != "umlals" && Mnemonic != "umulls" && Mnemonic != "lsls" &&
6234       Mnemonic != "sbcs" && Mnemonic != "rscs" &&
6235       !(hasMVE() &&
6236         (Mnemonic == "vmine" ||
6237          Mnemonic == "vshle" || Mnemonic == "vshlt" || Mnemonic == "vshllt" ||
6238          Mnemonic == "vrshle" || Mnemonic == "vrshlt" ||
6239          Mnemonic == "vmvne" || Mnemonic == "vorne" ||
6240          Mnemonic == "vnege" || Mnemonic == "vnegt" ||
6241          Mnemonic == "vmule" || Mnemonic == "vmult" ||
6242          Mnemonic == "vrintne" ||
6243          Mnemonic == "vcmult" || Mnemonic == "vcmule" ||
6244          Mnemonic == "vpsele" || Mnemonic == "vpselt" ||
6245          Mnemonic.startswith("vq")))) {
6246     unsigned CC = ARMCondCodeFromString(Mnemonic.substr(Mnemonic.size()-2));
6247     if (CC != ~0U) {
6248       Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 2);
6249       PredicationCode = CC;
6250     }
6251   }
6252 
6253   // Next, determine if we have a carry setting bit. We explicitly ignore all
6254   // the instructions we know end in 's'.
6255   if (Mnemonic.endswith("s") &&
6256       !(Mnemonic == "cps" || Mnemonic == "mls" ||
6257         Mnemonic == "mrs" || Mnemonic == "smmls" || Mnemonic == "vabs" ||
6258         Mnemonic == "vcls" || Mnemonic == "vmls" || Mnemonic == "vmrs" ||
6259         Mnemonic == "vnmls" || Mnemonic == "vqabs" || Mnemonic == "vrecps" ||
6260         Mnemonic == "vrsqrts" || Mnemonic == "srs" || Mnemonic == "flds" ||
6261         Mnemonic == "fmrs" || Mnemonic == "fsqrts" || Mnemonic == "fsubs" ||
6262         Mnemonic == "fsts" || Mnemonic == "fcpys" || Mnemonic == "fdivs" ||
6263         Mnemonic == "fmuls" || Mnemonic == "fcmps" || Mnemonic == "fcmpzs" ||
6264         Mnemonic == "vfms" || Mnemonic == "vfnms" || Mnemonic == "fconsts" ||
6265         Mnemonic == "bxns" || Mnemonic == "blxns" || Mnemonic == "vfmas" ||
6266         Mnemonic == "vmlas" ||
6267         (Mnemonic == "movs" && isThumb()))) {
6268     Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 1);
6269     CarrySetting = true;
6270   }
6271 
6272   // The "cps" instruction can have a interrupt mode operand which is glued into
6273   // the mnemonic. Check if this is the case, split it and parse the imod op
6274   if (Mnemonic.startswith("cps")) {
6275     // Split out any imod code.
6276     unsigned IMod =
6277       StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2, 2))
6278       .Case("ie", ARM_PROC::IE)
6279       .Case("id", ARM_PROC::ID)
6280       .Default(~0U);
6281     if (IMod != ~0U) {
6282       Mnemonic = Mnemonic.slice(0, Mnemonic.size()-2);
6283       ProcessorIMod = IMod;
6284     }
6285   }
6286 
6287   if (isMnemonicVPTPredicable(Mnemonic, ExtraToken) && Mnemonic != "vmovlt" &&
6288       Mnemonic != "vshllt" && Mnemonic != "vrshrnt" && Mnemonic != "vshrnt" &&
6289       Mnemonic != "vqrshrunt" && Mnemonic != "vqshrunt" &&
6290       Mnemonic != "vqrshrnt" && Mnemonic != "vqshrnt" && Mnemonic != "vmullt" &&
6291       Mnemonic != "vqmovnt" && Mnemonic != "vqmovunt" &&
6292       Mnemonic != "vqmovnt" && Mnemonic != "vmovnt" && Mnemonic != "vqdmullt" &&
6293       Mnemonic != "vpnot" && Mnemonic != "vcvtt" && Mnemonic != "vcvt") {
6294     unsigned CC = ARMVectorCondCodeFromString(Mnemonic.substr(Mnemonic.size()-1));
6295     if (CC != ~0U) {
6296       Mnemonic = Mnemonic.slice(0, Mnemonic.size()-1);
6297       VPTPredicationCode = CC;
6298     }
6299     return Mnemonic;
6300   }
6301 
6302   // The "it" instruction has the condition mask on the end of the mnemonic.
6303   if (Mnemonic.startswith("it")) {
6304     ITMask = Mnemonic.slice(2, Mnemonic.size());
6305     Mnemonic = Mnemonic.slice(0, 2);
6306   }
6307 
6308   if (Mnemonic.startswith("vpst")) {
6309     ITMask = Mnemonic.slice(4, Mnemonic.size());
6310     Mnemonic = Mnemonic.slice(0, 4);
6311   }
6312   else if (Mnemonic.startswith("vpt")) {
6313     ITMask = Mnemonic.slice(3, Mnemonic.size());
6314     Mnemonic = Mnemonic.slice(0, 3);
6315   }
6316 
6317   return Mnemonic;
6318 }
6319 
6320 /// Given a canonical mnemonic, determine if the instruction ever allows
6321 /// inclusion of carry set or predication code operands.
6322 //
6323 // FIXME: It would be nice to autogen this.
6324 void ARMAsmParser::getMnemonicAcceptInfo(StringRef Mnemonic,
6325                                          StringRef ExtraToken,
6326                                          StringRef FullInst,
6327                                          bool &CanAcceptCarrySet,
6328                                          bool &CanAcceptPredicationCode,
6329                                          bool &CanAcceptVPTPredicationCode) {
6330   CanAcceptVPTPredicationCode = isMnemonicVPTPredicable(Mnemonic, ExtraToken);
6331 
6332   CanAcceptCarrySet =
6333       Mnemonic == "and" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
6334       Mnemonic == "rrx" || Mnemonic == "ror" || Mnemonic == "sub" ||
6335       Mnemonic == "add" || Mnemonic == "adc" || Mnemonic == "mul" ||
6336       Mnemonic == "bic" || Mnemonic == "asr" || Mnemonic == "orr" ||
6337       Mnemonic == "mvn" || Mnemonic == "rsb" || Mnemonic == "rsc" ||
6338       Mnemonic == "orn" || Mnemonic == "sbc" || Mnemonic == "eor" ||
6339       Mnemonic == "neg" || Mnemonic == "vfm" || Mnemonic == "vfnm" ||
6340       (!isThumb() &&
6341        (Mnemonic == "smull" || Mnemonic == "mov" || Mnemonic == "mla" ||
6342         Mnemonic == "smlal" || Mnemonic == "umlal" || Mnemonic == "umull"));
6343 
6344   if (Mnemonic == "bkpt" || Mnemonic == "cbnz" || Mnemonic == "setend" ||
6345       Mnemonic == "cps" || Mnemonic == "it" || Mnemonic == "cbz" ||
6346       Mnemonic == "trap" || Mnemonic == "hlt" || Mnemonic == "udf" ||
6347       Mnemonic.startswith("crc32") || Mnemonic.startswith("cps") ||
6348       Mnemonic.startswith("vsel") || Mnemonic == "vmaxnm" ||
6349       Mnemonic == "vminnm" || Mnemonic == "vcvta" || Mnemonic == "vcvtn" ||
6350       Mnemonic == "vcvtp" || Mnemonic == "vcvtm" || Mnemonic == "vrinta" ||
6351       Mnemonic == "vrintn" || Mnemonic == "vrintp" || Mnemonic == "vrintm" ||
6352       Mnemonic.startswith("aes") || Mnemonic == "hvc" || Mnemonic == "setpan" ||
6353       Mnemonic.startswith("sha1") || Mnemonic.startswith("sha256") ||
6354       (FullInst.startswith("vmull") && FullInst.endswith(".p64")) ||
6355       Mnemonic == "vmovx" || Mnemonic == "vins" ||
6356       Mnemonic == "vudot" || Mnemonic == "vsdot" ||
6357       Mnemonic == "vcmla" || Mnemonic == "vcadd" ||
6358       Mnemonic == "vfmal" || Mnemonic == "vfmsl" ||
6359       Mnemonic == "sb"    || Mnemonic == "ssbb"  ||
6360       Mnemonic == "pssbb" ||
6361       Mnemonic == "bfcsel" || Mnemonic == "wls" ||
6362       Mnemonic == "dls" || Mnemonic == "le" || Mnemonic == "csel" ||
6363       Mnemonic == "csinc" || Mnemonic == "csinv" || Mnemonic == "csneg" ||
6364       Mnemonic == "cinc" || Mnemonic == "cinv" || Mnemonic == "cneg" ||
6365       Mnemonic == "cset" || Mnemonic == "csetm" ||
6366       Mnemonic.startswith("vpt") || Mnemonic.startswith("vpst") ||
6367       (hasMVE() &&
6368        (Mnemonic.startswith("vst2") || Mnemonic.startswith("vld2") ||
6369         Mnemonic.startswith("vst4") || Mnemonic.startswith("vld4") ||
6370         Mnemonic.startswith("wlstp") || Mnemonic.startswith("dlstp") ||
6371         Mnemonic.startswith("letp")))) {
6372     // These mnemonics are never predicable
6373     CanAcceptPredicationCode = false;
6374   } else if (!isThumb()) {
6375     // Some instructions are only predicable in Thumb mode
6376     CanAcceptPredicationCode =
6377         Mnemonic != "cdp2" && Mnemonic != "clrex" && Mnemonic != "mcr2" &&
6378         Mnemonic != "mcrr2" && Mnemonic != "mrc2" && Mnemonic != "mrrc2" &&
6379         Mnemonic != "dmb" && Mnemonic != "dfb" && Mnemonic != "dsb" &&
6380         Mnemonic != "isb" && Mnemonic != "pld" && Mnemonic != "pli" &&
6381         Mnemonic != "pldw" && Mnemonic != "ldc2" && Mnemonic != "ldc2l" &&
6382         Mnemonic != "stc2" && Mnemonic != "stc2l" &&
6383         Mnemonic != "tsb" &&
6384         !Mnemonic.startswith("rfe") && !Mnemonic.startswith("srs");
6385   } else if (isThumbOne()) {
6386     if (hasV6MOps())
6387       CanAcceptPredicationCode = Mnemonic != "movs";
6388     else
6389       CanAcceptPredicationCode = Mnemonic != "nop" && Mnemonic != "movs";
6390   } else
6391     CanAcceptPredicationCode = true;
6392 }
6393 
6394 // Some Thumb instructions have two operand forms that are not
6395 // available as three operand, convert to two operand form if possible.
6396 //
6397 // FIXME: We would really like to be able to tablegen'erate this.
6398 void ARMAsmParser::tryConvertingToTwoOperandForm(StringRef Mnemonic,
6399                                                  bool CarrySetting,
6400                                                  OperandVector &Operands) {
6401   if (Operands.size() != 6)
6402     return;
6403 
6404   const auto &Op3 = static_cast<ARMOperand &>(*Operands[3]);
6405         auto &Op4 = static_cast<ARMOperand &>(*Operands[4]);
6406   if (!Op3.isReg() || !Op4.isReg())
6407     return;
6408 
6409   auto Op3Reg = Op3.getReg();
6410   auto Op4Reg = Op4.getReg();
6411 
6412   // For most Thumb2 cases we just generate the 3 operand form and reduce
6413   // it in processInstruction(), but the 3 operand form of ADD (t2ADDrr)
6414   // won't accept SP or PC so we do the transformation here taking care
6415   // with immediate range in the 'add sp, sp #imm' case.
6416   auto &Op5 = static_cast<ARMOperand &>(*Operands[5]);
6417   if (isThumbTwo()) {
6418     if (Mnemonic != "add")
6419       return;
6420     bool TryTransform = Op3Reg == ARM::PC || Op4Reg == ARM::PC ||
6421                         (Op5.isReg() && Op5.getReg() == ARM::PC);
6422     if (!TryTransform) {
6423       TryTransform = (Op3Reg == ARM::SP || Op4Reg == ARM::SP ||
6424                       (Op5.isReg() && Op5.getReg() == ARM::SP)) &&
6425                      !(Op3Reg == ARM::SP && Op4Reg == ARM::SP &&
6426                        Op5.isImm() && !Op5.isImm0_508s4());
6427     }
6428     if (!TryTransform)
6429       return;
6430   } else if (!isThumbOne())
6431     return;
6432 
6433   if (!(Mnemonic == "add" || Mnemonic == "sub" || Mnemonic == "and" ||
6434         Mnemonic == "eor" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
6435         Mnemonic == "asr" || Mnemonic == "adc" || Mnemonic == "sbc" ||
6436         Mnemonic == "ror" || Mnemonic == "orr" || Mnemonic == "bic"))
6437     return;
6438 
6439   // If first 2 operands of a 3 operand instruction are the same
6440   // then transform to 2 operand version of the same instruction
6441   // e.g. 'adds r0, r0, #1' transforms to 'adds r0, #1'
6442   bool Transform = Op3Reg == Op4Reg;
6443 
6444   // For communtative operations, we might be able to transform if we swap
6445   // Op4 and Op5.  The 'ADD Rdm, SP, Rdm' form is already handled specially
6446   // as tADDrsp.
6447   const ARMOperand *LastOp = &Op5;
6448   bool Swap = false;
6449   if (!Transform && Op5.isReg() && Op3Reg == Op5.getReg() &&
6450       ((Mnemonic == "add" && Op4Reg != ARM::SP) ||
6451        Mnemonic == "and" || Mnemonic == "eor" ||
6452        Mnemonic == "adc" || Mnemonic == "orr")) {
6453     Swap = true;
6454     LastOp = &Op4;
6455     Transform = true;
6456   }
6457 
6458   // If both registers are the same then remove one of them from
6459   // the operand list, with certain exceptions.
6460   if (Transform) {
6461     // Don't transform 'adds Rd, Rd, Rm' or 'sub{s} Rd, Rd, Rm' because the
6462     // 2 operand forms don't exist.
6463     if (((Mnemonic == "add" && CarrySetting) || Mnemonic == "sub") &&
6464         LastOp->isReg())
6465       Transform = false;
6466 
6467     // Don't transform 'add/sub{s} Rd, Rd, #imm' if the immediate fits into
6468     // 3-bits because the ARMARM says not to.
6469     if ((Mnemonic == "add" || Mnemonic == "sub") && LastOp->isImm0_7())
6470       Transform = false;
6471   }
6472 
6473   if (Transform) {
6474     if (Swap)
6475       std::swap(Op4, Op5);
6476     Operands.erase(Operands.begin() + 3);
6477   }
6478 }
6479 
6480 bool ARMAsmParser::shouldOmitCCOutOperand(StringRef Mnemonic,
6481                                           OperandVector &Operands) {
6482   // FIXME: This is all horribly hacky. We really need a better way to deal
6483   // with optional operands like this in the matcher table.
6484 
6485   // The 'mov' mnemonic is special. One variant has a cc_out operand, while
6486   // another does not. Specifically, the MOVW instruction does not. So we
6487   // special case it here and remove the defaulted (non-setting) cc_out
6488   // operand if that's the instruction we're trying to match.
6489   //
6490   // We do this as post-processing of the explicit operands rather than just
6491   // conditionally adding the cc_out in the first place because we need
6492   // to check the type of the parsed immediate operand.
6493   if (Mnemonic == "mov" && Operands.size() > 4 && !isThumb() &&
6494       !static_cast<ARMOperand &>(*Operands[4]).isModImm() &&
6495       static_cast<ARMOperand &>(*Operands[4]).isImm0_65535Expr() &&
6496       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0)
6497     return true;
6498 
6499   // Register-register 'add' for thumb does not have a cc_out operand
6500   // when there are only two register operands.
6501   if (isThumb() && Mnemonic == "add" && Operands.size() == 5 &&
6502       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6503       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
6504       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0)
6505     return true;
6506   // Register-register 'add' for thumb does not have a cc_out operand
6507   // when it's an ADD Rdm, SP, {Rdm|#imm0_255} instruction. We do
6508   // have to check the immediate range here since Thumb2 has a variant
6509   // that can handle a different range and has a cc_out operand.
6510   if (((isThumb() && Mnemonic == "add") ||
6511        (isThumbTwo() && Mnemonic == "sub")) &&
6512       Operands.size() == 6 && static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6513       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
6514       static_cast<ARMOperand &>(*Operands[4]).getReg() == ARM::SP &&
6515       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
6516       ((Mnemonic == "add" && static_cast<ARMOperand &>(*Operands[5]).isReg()) ||
6517        static_cast<ARMOperand &>(*Operands[5]).isImm0_1020s4()))
6518     return true;
6519   // For Thumb2, add/sub immediate does not have a cc_out operand for the
6520   // imm0_4095 variant. That's the least-preferred variant when
6521   // selecting via the generic "add" mnemonic, so to know that we
6522   // should remove the cc_out operand, we have to explicitly check that
6523   // it's not one of the other variants. Ugh.
6524   if (isThumbTwo() && (Mnemonic == "add" || Mnemonic == "sub") &&
6525       Operands.size() == 6 && static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6526       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
6527       static_cast<ARMOperand &>(*Operands[5]).isImm()) {
6528     // Nest conditions rather than one big 'if' statement for readability.
6529     //
6530     // If both registers are low, we're in an IT block, and the immediate is
6531     // in range, we should use encoding T1 instead, which has a cc_out.
6532     if (inITBlock() &&
6533         isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) &&
6534         isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) &&
6535         static_cast<ARMOperand &>(*Operands[5]).isImm0_7())
6536       return false;
6537     // Check against T3. If the second register is the PC, this is an
6538     // alternate form of ADR, which uses encoding T4, so check for that too.
6539     if (static_cast<ARMOperand &>(*Operands[4]).getReg() != ARM::PC &&
6540         static_cast<ARMOperand &>(*Operands[5]).isT2SOImm())
6541       return false;
6542 
6543     // Otherwise, we use encoding T4, which does not have a cc_out
6544     // operand.
6545     return true;
6546   }
6547 
6548   // The thumb2 multiply instruction doesn't have a CCOut register, so
6549   // if we have a "mul" mnemonic in Thumb mode, check if we'll be able to
6550   // use the 16-bit encoding or not.
6551   if (isThumbTwo() && Mnemonic == "mul" && Operands.size() == 6 &&
6552       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
6553       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6554       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
6555       static_cast<ARMOperand &>(*Operands[5]).isReg() &&
6556       // If the registers aren't low regs, the destination reg isn't the
6557       // same as one of the source regs, or the cc_out operand is zero
6558       // outside of an IT block, we have to use the 32-bit encoding, so
6559       // remove the cc_out operand.
6560       (!isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) ||
6561        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) ||
6562        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[5]).getReg()) ||
6563        !inITBlock() || (static_cast<ARMOperand &>(*Operands[3]).getReg() !=
6564                             static_cast<ARMOperand &>(*Operands[5]).getReg() &&
6565                         static_cast<ARMOperand &>(*Operands[3]).getReg() !=
6566                             static_cast<ARMOperand &>(*Operands[4]).getReg())))
6567     return true;
6568 
6569   // Also check the 'mul' syntax variant that doesn't specify an explicit
6570   // destination register.
6571   if (isThumbTwo() && Mnemonic == "mul" && Operands.size() == 5 &&
6572       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
6573       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6574       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
6575       // If the registers aren't low regs  or the cc_out operand is zero
6576       // outside of an IT block, we have to use the 32-bit encoding, so
6577       // remove the cc_out operand.
6578       (!isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) ||
6579        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) ||
6580        !inITBlock()))
6581     return true;
6582 
6583   // Register-register 'add/sub' for thumb does not have a cc_out operand
6584   // when it's an ADD/SUB SP, #imm. Be lenient on count since there's also
6585   // the "add/sub SP, SP, #imm" version. If the follow-up operands aren't
6586   // right, this will result in better diagnostics (which operand is off)
6587   // anyway.
6588   if (isThumb() && (Mnemonic == "add" || Mnemonic == "sub") &&
6589       (Operands.size() == 5 || Operands.size() == 6) &&
6590       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6591       static_cast<ARMOperand &>(*Operands[3]).getReg() == ARM::SP &&
6592       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
6593       (static_cast<ARMOperand &>(*Operands[4]).isImm() ||
6594        (Operands.size() == 6 &&
6595         static_cast<ARMOperand &>(*Operands[5]).isImm())))
6596     return true;
6597 
6598   return false;
6599 }
6600 
6601 bool ARMAsmParser::shouldOmitPredicateOperand(StringRef Mnemonic,
6602                                               OperandVector &Operands) {
6603   // VRINT{Z, X} have a predicate operand in VFP, but not in NEON
6604   unsigned RegIdx = 3;
6605   if ((((Mnemonic == "vrintz" || Mnemonic == "vrintx") && !hasMVE()) ||
6606       Mnemonic == "vrintr") &&
6607       (static_cast<ARMOperand &>(*Operands[2]).getToken() == ".f32" ||
6608        static_cast<ARMOperand &>(*Operands[2]).getToken() == ".f16")) {
6609     if (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
6610         (static_cast<ARMOperand &>(*Operands[3]).getToken() == ".f32" ||
6611          static_cast<ARMOperand &>(*Operands[3]).getToken() == ".f16"))
6612       RegIdx = 4;
6613 
6614     if (static_cast<ARMOperand &>(*Operands[RegIdx]).isReg() &&
6615         (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(
6616              static_cast<ARMOperand &>(*Operands[RegIdx]).getReg()) ||
6617          ARMMCRegisterClasses[ARM::QPRRegClassID].contains(
6618              static_cast<ARMOperand &>(*Operands[RegIdx]).getReg())))
6619       return true;
6620   }
6621   return false;
6622 }
6623 
6624 bool ARMAsmParser::shouldOmitVectorPredicateOperand(StringRef Mnemonic,
6625                                                     OperandVector &Operands) {
6626   if (!hasMVE() || Operands.size() < 3)
6627     return true;
6628 
6629   if (Mnemonic.startswith("vld2") || Mnemonic.startswith("vld4") ||
6630       Mnemonic.startswith("vst2") || Mnemonic.startswith("vst4"))
6631     return true;
6632 
6633   if (Mnemonic.startswith("vctp") || Mnemonic.startswith("vpnot"))
6634     return false;
6635 
6636   if (Mnemonic.startswith("vmov") &&
6637       !(Mnemonic.startswith("vmovl") || Mnemonic.startswith("vmovn") ||
6638         Mnemonic.startswith("vmovx"))) {
6639     for (auto &Operand : Operands) {
6640       if (static_cast<ARMOperand &>(*Operand).isVectorIndex() ||
6641           ((*Operand).isReg() &&
6642            (ARMMCRegisterClasses[ARM::SPRRegClassID].contains(
6643              (*Operand).getReg()) ||
6644             ARMMCRegisterClasses[ARM::DPRRegClassID].contains(
6645               (*Operand).getReg())))) {
6646         return true;
6647       }
6648     }
6649     return false;
6650   } else {
6651     for (auto &Operand : Operands) {
6652       // We check the larger class QPR instead of just the legal class
6653       // MQPR, to more accurately report errors when using Q registers
6654       // outside of the allowed range.
6655       if (static_cast<ARMOperand &>(*Operand).isVectorIndex() ||
6656           (Operand->isReg() &&
6657            (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(
6658              Operand->getReg()))))
6659         return false;
6660     }
6661     return true;
6662   }
6663 }
6664 
6665 static bool isDataTypeToken(StringRef Tok) {
6666   return Tok == ".8" || Tok == ".16" || Tok == ".32" || Tok == ".64" ||
6667     Tok == ".i8" || Tok == ".i16" || Tok == ".i32" || Tok == ".i64" ||
6668     Tok == ".u8" || Tok == ".u16" || Tok == ".u32" || Tok == ".u64" ||
6669     Tok == ".s8" || Tok == ".s16" || Tok == ".s32" || Tok == ".s64" ||
6670     Tok == ".p8" || Tok == ".p16" || Tok == ".f32" || Tok == ".f64" ||
6671     Tok == ".f" || Tok == ".d";
6672 }
6673 
6674 // FIXME: This bit should probably be handled via an explicit match class
6675 // in the .td files that matches the suffix instead of having it be
6676 // a literal string token the way it is now.
6677 static bool doesIgnoreDataTypeSuffix(StringRef Mnemonic, StringRef DT) {
6678   return Mnemonic.startswith("vldm") || Mnemonic.startswith("vstm");
6679 }
6680 
6681 static void applyMnemonicAliases(StringRef &Mnemonic,
6682                                  const FeatureBitset &Features,
6683                                  unsigned VariantID);
6684 
6685 // The GNU assembler has aliases of ldrd and strd with the second register
6686 // omitted. We don't have a way to do that in tablegen, so fix it up here.
6687 //
6688 // We have to be careful to not emit an invalid Rt2 here, because the rest of
6689 // the assmebly parser could then generate confusing diagnostics refering to
6690 // it. If we do find anything that prevents us from doing the transformation we
6691 // bail out, and let the assembly parser report an error on the instruction as
6692 // it is written.
6693 void ARMAsmParser::fixupGNULDRDAlias(StringRef Mnemonic,
6694                                      OperandVector &Operands) {
6695   if (Mnemonic != "ldrd" && Mnemonic != "strd")
6696     return;
6697   if (Operands.size() < 4)
6698     return;
6699 
6700   ARMOperand &Op2 = static_cast<ARMOperand &>(*Operands[2]);
6701   ARMOperand &Op3 = static_cast<ARMOperand &>(*Operands[3]);
6702 
6703   if (!Op2.isReg())
6704     return;
6705   if (!Op3.isGPRMem())
6706     return;
6707 
6708   const MCRegisterClass &GPR = MRI->getRegClass(ARM::GPRRegClassID);
6709   if (!GPR.contains(Op2.getReg()))
6710     return;
6711 
6712   unsigned RtEncoding = MRI->getEncodingValue(Op2.getReg());
6713   if (!isThumb() && (RtEncoding & 1)) {
6714     // In ARM mode, the registers must be from an aligned pair, this
6715     // restriction does not apply in Thumb mode.
6716     return;
6717   }
6718   if (Op2.getReg() == ARM::PC)
6719     return;
6720   unsigned PairedReg = GPR.getRegister(RtEncoding + 1);
6721   if (!PairedReg || PairedReg == ARM::PC ||
6722       (PairedReg == ARM::SP && !hasV8Ops()))
6723     return;
6724 
6725   Operands.insert(
6726       Operands.begin() + 3,
6727       ARMOperand::CreateReg(PairedReg, Op2.getStartLoc(), Op2.getEndLoc()));
6728 }
6729 
6730 /// Parse an arm instruction mnemonic followed by its operands.
6731 bool ARMAsmParser::ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
6732                                     SMLoc NameLoc, OperandVector &Operands) {
6733   MCAsmParser &Parser = getParser();
6734 
6735   // Apply mnemonic aliases before doing anything else, as the destination
6736   // mnemonic may include suffices and we want to handle them normally.
6737   // The generic tblgen'erated code does this later, at the start of
6738   // MatchInstructionImpl(), but that's too late for aliases that include
6739   // any sort of suffix.
6740   const FeatureBitset &AvailableFeatures = getAvailableFeatures();
6741   unsigned AssemblerDialect = getParser().getAssemblerDialect();
6742   applyMnemonicAliases(Name, AvailableFeatures, AssemblerDialect);
6743 
6744   // First check for the ARM-specific .req directive.
6745   if (Parser.getTok().is(AsmToken::Identifier) &&
6746       Parser.getTok().getIdentifier() == ".req") {
6747     parseDirectiveReq(Name, NameLoc);
6748     // We always return 'error' for this, as we're done with this
6749     // statement and don't need to match the 'instruction."
6750     return true;
6751   }
6752 
6753   // Create the leading tokens for the mnemonic, split by '.' characters.
6754   size_t Start = 0, Next = Name.find('.');
6755   StringRef Mnemonic = Name.slice(Start, Next);
6756   StringRef ExtraToken = Name.slice(Next, Name.find(' ', Next + 1));
6757 
6758   // Split out the predication code and carry setting flag from the mnemonic.
6759   unsigned PredicationCode;
6760   unsigned VPTPredicationCode;
6761   unsigned ProcessorIMod;
6762   bool CarrySetting;
6763   StringRef ITMask;
6764   Mnemonic = splitMnemonic(Mnemonic, ExtraToken, PredicationCode, VPTPredicationCode,
6765                            CarrySetting, ProcessorIMod, ITMask);
6766 
6767   // In Thumb1, only the branch (B) instruction can be predicated.
6768   if (isThumbOne() && PredicationCode != ARMCC::AL && Mnemonic != "b") {
6769     return Error(NameLoc, "conditional execution not supported in Thumb1");
6770   }
6771 
6772   Operands.push_back(ARMOperand::CreateToken(Mnemonic, NameLoc));
6773 
6774   // Handle the mask for IT and VPT instructions. In ARMOperand and
6775   // MCOperand, this is stored in a format independent of the
6776   // condition code: the lowest set bit indicates the end of the
6777   // encoding, and above that, a 1 bit indicates 'else', and an 0
6778   // indicates 'then'. E.g.
6779   //    IT    -> 1000
6780   //    ITx   -> x100    (ITT -> 0100, ITE -> 1100)
6781   //    ITxy  -> xy10    (e.g. ITET -> 1010)
6782   //    ITxyz -> xyz1    (e.g. ITEET -> 1101)
6783   if (Mnemonic == "it" || Mnemonic.startswith("vpt") ||
6784       Mnemonic.startswith("vpst")) {
6785     SMLoc Loc = Mnemonic == "it"  ? SMLoc::getFromPointer(NameLoc.getPointer() + 2) :
6786                 Mnemonic == "vpt" ? SMLoc::getFromPointer(NameLoc.getPointer() + 3) :
6787                                     SMLoc::getFromPointer(NameLoc.getPointer() + 4);
6788     if (ITMask.size() > 3) {
6789       if (Mnemonic == "it")
6790         return Error(Loc, "too many conditions on IT instruction");
6791       return Error(Loc, "too many conditions on VPT instruction");
6792     }
6793     unsigned Mask = 8;
6794     for (unsigned i = ITMask.size(); i != 0; --i) {
6795       char pos = ITMask[i - 1];
6796       if (pos != 't' && pos != 'e') {
6797         return Error(Loc, "illegal IT block condition mask '" + ITMask + "'");
6798       }
6799       Mask >>= 1;
6800       if (ITMask[i - 1] == 'e')
6801         Mask |= 8;
6802     }
6803     Operands.push_back(ARMOperand::CreateITMask(Mask, Loc));
6804   }
6805 
6806   // FIXME: This is all a pretty gross hack. We should automatically handle
6807   // optional operands like this via tblgen.
6808 
6809   // Next, add the CCOut and ConditionCode operands, if needed.
6810   //
6811   // For mnemonics which can ever incorporate a carry setting bit or predication
6812   // code, our matching model involves us always generating CCOut and
6813   // ConditionCode operands to match the mnemonic "as written" and then we let
6814   // the matcher deal with finding the right instruction or generating an
6815   // appropriate error.
6816   bool CanAcceptCarrySet, CanAcceptPredicationCode, CanAcceptVPTPredicationCode;
6817   getMnemonicAcceptInfo(Mnemonic, ExtraToken, Name, CanAcceptCarrySet,
6818                         CanAcceptPredicationCode, CanAcceptVPTPredicationCode);
6819 
6820   // If we had a carry-set on an instruction that can't do that, issue an
6821   // error.
6822   if (!CanAcceptCarrySet && CarrySetting) {
6823     return Error(NameLoc, "instruction '" + Mnemonic +
6824                  "' can not set flags, but 's' suffix specified");
6825   }
6826   // If we had a predication code on an instruction that can't do that, issue an
6827   // error.
6828   if (!CanAcceptPredicationCode && PredicationCode != ARMCC::AL) {
6829     return Error(NameLoc, "instruction '" + Mnemonic +
6830                  "' is not predicable, but condition code specified");
6831   }
6832 
6833   // If we had a VPT predication code on an instruction that can't do that, issue an
6834   // error.
6835   if (!CanAcceptVPTPredicationCode && VPTPredicationCode != ARMVCC::None) {
6836     return Error(NameLoc, "instruction '" + Mnemonic +
6837                  "' is not VPT predicable, but VPT code T/E is specified");
6838   }
6839 
6840   // Add the carry setting operand, if necessary.
6841   if (CanAcceptCarrySet) {
6842     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size());
6843     Operands.push_back(ARMOperand::CreateCCOut(CarrySetting ? ARM::CPSR : 0,
6844                                                Loc));
6845   }
6846 
6847   // Add the predication code operand, if necessary.
6848   if (CanAcceptPredicationCode) {
6849     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size() +
6850                                       CarrySetting);
6851     Operands.push_back(ARMOperand::CreateCondCode(
6852                        ARMCC::CondCodes(PredicationCode), Loc));
6853   }
6854 
6855   // Add the VPT predication code operand, if necessary.
6856   // FIXME: We don't add them for the instructions filtered below as these can
6857   // have custom operands which need special parsing.  This parsing requires
6858   // the operand to be in the same place in the OperandVector as their
6859   // definition in tblgen.  Since these instructions may also have the
6860   // scalar predication operand we do not add the vector one and leave until
6861   // now to fix it up.
6862   if (CanAcceptVPTPredicationCode && Mnemonic != "vmov" &&
6863       !Mnemonic.startswith("vcmp") &&
6864       !(Mnemonic.startswith("vcvt") && Mnemonic != "vcvta" &&
6865         Mnemonic != "vcvtn" && Mnemonic != "vcvtp" && Mnemonic != "vcvtm")) {
6866     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size() +
6867                                       CarrySetting);
6868     Operands.push_back(ARMOperand::CreateVPTPred(
6869                          ARMVCC::VPTCodes(VPTPredicationCode), Loc));
6870   }
6871 
6872   // Add the processor imod operand, if necessary.
6873   if (ProcessorIMod) {
6874     Operands.push_back(ARMOperand::CreateImm(
6875           MCConstantExpr::create(ProcessorIMod, getContext()),
6876                                  NameLoc, NameLoc));
6877   } else if (Mnemonic == "cps" && isMClass()) {
6878     return Error(NameLoc, "instruction 'cps' requires effect for M-class");
6879   }
6880 
6881   // Add the remaining tokens in the mnemonic.
6882   while (Next != StringRef::npos) {
6883     Start = Next;
6884     Next = Name.find('.', Start + 1);
6885     ExtraToken = Name.slice(Start, Next);
6886 
6887     // Some NEON instructions have an optional datatype suffix that is
6888     // completely ignored. Check for that.
6889     if (isDataTypeToken(ExtraToken) &&
6890         doesIgnoreDataTypeSuffix(Mnemonic, ExtraToken))
6891       continue;
6892 
6893     // For for ARM mode generate an error if the .n qualifier is used.
6894     if (ExtraToken == ".n" && !isThumb()) {
6895       SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Start);
6896       return Error(Loc, "instruction with .n (narrow) qualifier not allowed in "
6897                    "arm mode");
6898     }
6899 
6900     // The .n qualifier is always discarded as that is what the tables
6901     // and matcher expect.  In ARM mode the .w qualifier has no effect,
6902     // so discard it to avoid errors that can be caused by the matcher.
6903     if (ExtraToken != ".n" && (isThumb() || ExtraToken != ".w")) {
6904       SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Start);
6905       Operands.push_back(ARMOperand::CreateToken(ExtraToken, Loc));
6906     }
6907   }
6908 
6909   // Read the remaining operands.
6910   if (getLexer().isNot(AsmToken::EndOfStatement)) {
6911     // Read the first operand.
6912     if (parseOperand(Operands, Mnemonic)) {
6913       return true;
6914     }
6915 
6916     while (parseOptionalToken(AsmToken::Comma)) {
6917       // Parse and remember the operand.
6918       if (parseOperand(Operands, Mnemonic)) {
6919         return true;
6920       }
6921     }
6922   }
6923 
6924   if (parseToken(AsmToken::EndOfStatement, "unexpected token in argument list"))
6925     return true;
6926 
6927   tryConvertingToTwoOperandForm(Mnemonic, CarrySetting, Operands);
6928 
6929   // Some instructions, mostly Thumb, have forms for the same mnemonic that
6930   // do and don't have a cc_out optional-def operand. With some spot-checks
6931   // of the operand list, we can figure out which variant we're trying to
6932   // parse and adjust accordingly before actually matching. We shouldn't ever
6933   // try to remove a cc_out operand that was explicitly set on the
6934   // mnemonic, of course (CarrySetting == true). Reason number #317 the
6935   // table driven matcher doesn't fit well with the ARM instruction set.
6936   if (!CarrySetting && shouldOmitCCOutOperand(Mnemonic, Operands))
6937     Operands.erase(Operands.begin() + 1);
6938 
6939   // Some instructions have the same mnemonic, but don't always
6940   // have a predicate. Distinguish them here and delete the
6941   // appropriate predicate if needed.  This could be either the scalar
6942   // predication code or the vector predication code.
6943   if (PredicationCode == ARMCC::AL &&
6944       shouldOmitPredicateOperand(Mnemonic, Operands))
6945     Operands.erase(Operands.begin() + 1);
6946 
6947 
6948   if (hasMVE()) {
6949     if (!shouldOmitVectorPredicateOperand(Mnemonic, Operands) &&
6950         Mnemonic == "vmov" && PredicationCode == ARMCC::LT) {
6951       // Very nasty hack to deal with the vector predicated variant of vmovlt
6952       // the scalar predicated vmov with condition 'lt'.  We can not tell them
6953       // apart until we have parsed their operands.
6954       Operands.erase(Operands.begin() + 1);
6955       Operands.erase(Operands.begin());
6956       SMLoc MLoc = SMLoc::getFromPointer(NameLoc.getPointer());
6957       SMLoc PLoc = SMLoc::getFromPointer(NameLoc.getPointer() +
6958                                          Mnemonic.size() - 1 + CarrySetting);
6959       Operands.insert(Operands.begin(),
6960                       ARMOperand::CreateVPTPred(ARMVCC::None, PLoc));
6961       Operands.insert(Operands.begin(),
6962                       ARMOperand::CreateToken(StringRef("vmovlt"), MLoc));
6963     } else if (Mnemonic == "vcvt" && PredicationCode == ARMCC::NE &&
6964                !shouldOmitVectorPredicateOperand(Mnemonic, Operands)) {
6965       // Another nasty hack to deal with the ambiguity between vcvt with scalar
6966       // predication 'ne' and vcvtn with vector predication 'e'.  As above we
6967       // can only distinguish between the two after we have parsed their
6968       // operands.
6969       Operands.erase(Operands.begin() + 1);
6970       Operands.erase(Operands.begin());
6971       SMLoc MLoc = SMLoc::getFromPointer(NameLoc.getPointer());
6972       SMLoc PLoc = SMLoc::getFromPointer(NameLoc.getPointer() +
6973                                          Mnemonic.size() - 1 + CarrySetting);
6974       Operands.insert(Operands.begin(),
6975                       ARMOperand::CreateVPTPred(ARMVCC::Else, PLoc));
6976       Operands.insert(Operands.begin(),
6977                       ARMOperand::CreateToken(StringRef("vcvtn"), MLoc));
6978     } else if (Mnemonic == "vmul" && PredicationCode == ARMCC::LT &&
6979                !shouldOmitVectorPredicateOperand(Mnemonic, Operands)) {
6980       // Another hack, this time to distinguish between scalar predicated vmul
6981       // with 'lt' predication code and the vector instruction vmullt with
6982       // vector predication code "none"
6983       Operands.erase(Operands.begin() + 1);
6984       Operands.erase(Operands.begin());
6985       SMLoc MLoc = SMLoc::getFromPointer(NameLoc.getPointer());
6986       Operands.insert(Operands.begin(),
6987                       ARMOperand::CreateToken(StringRef("vmullt"), MLoc));
6988     }
6989     // For vmov and vcmp, as mentioned earlier, we did not add the vector
6990     // predication code, since these may contain operands that require
6991     // special parsing.  So now we have to see if they require vector
6992     // predication and replace the scalar one with the vector predication
6993     // operand if that is the case.
6994     else if (Mnemonic == "vmov" || Mnemonic.startswith("vcmp") ||
6995              (Mnemonic.startswith("vcvt") && !Mnemonic.startswith("vcvta") &&
6996               !Mnemonic.startswith("vcvtn") && !Mnemonic.startswith("vcvtp") &&
6997               !Mnemonic.startswith("vcvtm"))) {
6998       if (!shouldOmitVectorPredicateOperand(Mnemonic, Operands)) {
6999         // We could not split the vector predicate off vcvt because it might
7000         // have been the scalar vcvtt instruction.  Now we know its a vector
7001         // instruction, we still need to check whether its the vector
7002         // predicated vcvt with 'Then' predication or the vector vcvtt.  We can
7003         // distinguish the two based on the suffixes, if it is any of
7004         // ".f16.f32", ".f32.f16", ".f16.f64" or ".f64.f16" then it is the vcvtt.
7005         if (Mnemonic.startswith("vcvtt") && Operands.size() >= 4) {
7006           auto Sz1 = static_cast<ARMOperand &>(*Operands[2]);
7007           auto Sz2 = static_cast<ARMOperand &>(*Operands[3]);
7008           if (!(Sz1.isToken() && Sz1.getToken().startswith(".f") &&
7009               Sz2.isToken() && Sz2.getToken().startswith(".f"))) {
7010             Operands.erase(Operands.begin());
7011             SMLoc MLoc = SMLoc::getFromPointer(NameLoc.getPointer());
7012             VPTPredicationCode = ARMVCC::Then;
7013 
7014             Mnemonic = Mnemonic.substr(0, 4);
7015             Operands.insert(Operands.begin(),
7016                             ARMOperand::CreateToken(Mnemonic, MLoc));
7017           }
7018         }
7019         Operands.erase(Operands.begin() + 1);
7020         SMLoc PLoc = SMLoc::getFromPointer(NameLoc.getPointer() +
7021                                           Mnemonic.size() + CarrySetting);
7022         Operands.insert(Operands.begin() + 1,
7023                         ARMOperand::CreateVPTPred(
7024                             ARMVCC::VPTCodes(VPTPredicationCode), PLoc));
7025       }
7026     } else if (CanAcceptVPTPredicationCode) {
7027       // For all other instructions, make sure only one of the two
7028       // predication operands is left behind, depending on whether we should
7029       // use the vector predication.
7030       if (shouldOmitVectorPredicateOperand(Mnemonic, Operands)) {
7031         if (CanAcceptPredicationCode)
7032           Operands.erase(Operands.begin() + 2);
7033         else
7034           Operands.erase(Operands.begin() + 1);
7035       } else if (CanAcceptPredicationCode && PredicationCode == ARMCC::AL) {
7036         Operands.erase(Operands.begin() + 1);
7037       }
7038     }
7039   }
7040 
7041   if (VPTPredicationCode != ARMVCC::None) {
7042     bool usedVPTPredicationCode = false;
7043     for (unsigned I = 1; I < Operands.size(); ++I)
7044       if (static_cast<ARMOperand &>(*Operands[I]).isVPTPred())
7045         usedVPTPredicationCode = true;
7046     if (!usedVPTPredicationCode) {
7047       // If we have a VPT predication code and we haven't just turned it
7048       // into an operand, then it was a mistake for splitMnemonic to
7049       // separate it from the rest of the mnemonic in the first place,
7050       // and this may lead to wrong disassembly (e.g. scalar floating
7051       // point VCMPE is actually a different instruction from VCMP, so
7052       // we mustn't treat them the same). In that situation, glue it
7053       // back on.
7054       Mnemonic = Name.slice(0, Mnemonic.size() + 1);
7055       Operands.erase(Operands.begin());
7056       Operands.insert(Operands.begin(),
7057                       ARMOperand::CreateToken(Mnemonic, NameLoc));
7058     }
7059   }
7060 
7061     // ARM mode 'blx' need special handling, as the register operand version
7062     // is predicable, but the label operand version is not. So, we can't rely
7063     // on the Mnemonic based checking to correctly figure out when to put
7064     // a k_CondCode operand in the list. If we're trying to match the label
7065     // version, remove the k_CondCode operand here.
7066     if (!isThumb() && Mnemonic == "blx" && Operands.size() == 3 &&
7067         static_cast<ARMOperand &>(*Operands[2]).isImm())
7068       Operands.erase(Operands.begin() + 1);
7069 
7070     // Adjust operands of ldrexd/strexd to MCK_GPRPair.
7071     // ldrexd/strexd require even/odd GPR pair. To enforce this constraint,
7072     // a single GPRPair reg operand is used in the .td file to replace the two
7073     // GPRs. However, when parsing from asm, the two GRPs cannot be
7074     // automatically
7075     // expressed as a GPRPair, so we have to manually merge them.
7076     // FIXME: We would really like to be able to tablegen'erate this.
7077     if (!isThumb() && Operands.size() > 4 &&
7078         (Mnemonic == "ldrexd" || Mnemonic == "strexd" || Mnemonic == "ldaexd" ||
7079          Mnemonic == "stlexd")) {
7080       bool isLoad = (Mnemonic == "ldrexd" || Mnemonic == "ldaexd");
7081       unsigned Idx = isLoad ? 2 : 3;
7082       ARMOperand &Op1 = static_cast<ARMOperand &>(*Operands[Idx]);
7083       ARMOperand &Op2 = static_cast<ARMOperand &>(*Operands[Idx + 1]);
7084 
7085       const MCRegisterClass &MRC = MRI->getRegClass(ARM::GPRRegClassID);
7086       // Adjust only if Op1 and Op2 are GPRs.
7087       if (Op1.isReg() && Op2.isReg() && MRC.contains(Op1.getReg()) &&
7088           MRC.contains(Op2.getReg())) {
7089         unsigned Reg1 = Op1.getReg();
7090         unsigned Reg2 = Op2.getReg();
7091         unsigned Rt = MRI->getEncodingValue(Reg1);
7092         unsigned Rt2 = MRI->getEncodingValue(Reg2);
7093 
7094         // Rt2 must be Rt + 1 and Rt must be even.
7095         if (Rt + 1 != Rt2 || (Rt & 1)) {
7096           return Error(Op2.getStartLoc(),
7097                        isLoad ? "destination operands must be sequential"
7098                               : "source operands must be sequential");
7099         }
7100         unsigned NewReg = MRI->getMatchingSuperReg(
7101             Reg1, ARM::gsub_0, &(MRI->getRegClass(ARM::GPRPairRegClassID)));
7102         Operands[Idx] =
7103             ARMOperand::CreateReg(NewReg, Op1.getStartLoc(), Op2.getEndLoc());
7104         Operands.erase(Operands.begin() + Idx + 1);
7105       }
7106   }
7107 
7108   // GNU Assembler extension (compatibility).
7109   fixupGNULDRDAlias(Mnemonic, Operands);
7110 
7111   // FIXME: As said above, this is all a pretty gross hack.  This instruction
7112   // does not fit with other "subs" and tblgen.
7113   // Adjust operands of B9.3.19 SUBS PC, LR, #imm (Thumb2) system instruction
7114   // so the Mnemonic is the original name "subs" and delete the predicate
7115   // operand so it will match the table entry.
7116   if (isThumbTwo() && Mnemonic == "sub" && Operands.size() == 6 &&
7117       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
7118       static_cast<ARMOperand &>(*Operands[3]).getReg() == ARM::PC &&
7119       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
7120       static_cast<ARMOperand &>(*Operands[4]).getReg() == ARM::LR &&
7121       static_cast<ARMOperand &>(*Operands[5]).isImm()) {
7122     Operands.front() = ARMOperand::CreateToken(Name, NameLoc);
7123     Operands.erase(Operands.begin() + 1);
7124   }
7125   return false;
7126 }
7127 
7128 // Validate context-sensitive operand constraints.
7129 
7130 // return 'true' if register list contains non-low GPR registers,
7131 // 'false' otherwise. If Reg is in the register list or is HiReg, set
7132 // 'containsReg' to true.
7133 static bool checkLowRegisterList(const MCInst &Inst, unsigned OpNo,
7134                                  unsigned Reg, unsigned HiReg,
7135                                  bool &containsReg) {
7136   containsReg = false;
7137   for (unsigned i = OpNo; i < Inst.getNumOperands(); ++i) {
7138     unsigned OpReg = Inst.getOperand(i).getReg();
7139     if (OpReg == Reg)
7140       containsReg = true;
7141     // Anything other than a low register isn't legal here.
7142     if (!isARMLowRegister(OpReg) && (!HiReg || OpReg != HiReg))
7143       return true;
7144   }
7145   return false;
7146 }
7147 
7148 // Check if the specified regisgter is in the register list of the inst,
7149 // starting at the indicated operand number.
7150 static bool listContainsReg(const MCInst &Inst, unsigned OpNo, unsigned Reg) {
7151   for (unsigned i = OpNo, e = Inst.getNumOperands(); i < e; ++i) {
7152     unsigned OpReg = Inst.getOperand(i).getReg();
7153     if (OpReg == Reg)
7154       return true;
7155   }
7156   return false;
7157 }
7158 
7159 // Return true if instruction has the interesting property of being
7160 // allowed in IT blocks, but not being predicable.
7161 static bool instIsBreakpoint(const MCInst &Inst) {
7162     return Inst.getOpcode() == ARM::tBKPT ||
7163            Inst.getOpcode() == ARM::BKPT ||
7164            Inst.getOpcode() == ARM::tHLT ||
7165            Inst.getOpcode() == ARM::HLT;
7166 }
7167 
7168 bool ARMAsmParser::validatetLDMRegList(const MCInst &Inst,
7169                                        const OperandVector &Operands,
7170                                        unsigned ListNo, bool IsARPop) {
7171   const ARMOperand &Op = static_cast<const ARMOperand &>(*Operands[ListNo]);
7172   bool HasWritebackToken = Op.isToken() && Op.getToken() == "!";
7173 
7174   bool ListContainsSP = listContainsReg(Inst, ListNo, ARM::SP);
7175   bool ListContainsLR = listContainsReg(Inst, ListNo, ARM::LR);
7176   bool ListContainsPC = listContainsReg(Inst, ListNo, ARM::PC);
7177 
7178   if (!IsARPop && ListContainsSP)
7179     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
7180                  "SP may not be in the register list");
7181   else if (ListContainsPC && ListContainsLR)
7182     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
7183                  "PC and LR may not be in the register list simultaneously");
7184   return false;
7185 }
7186 
7187 bool ARMAsmParser::validatetSTMRegList(const MCInst &Inst,
7188                                        const OperandVector &Operands,
7189                                        unsigned ListNo) {
7190   const ARMOperand &Op = static_cast<const ARMOperand &>(*Operands[ListNo]);
7191   bool HasWritebackToken = Op.isToken() && Op.getToken() == "!";
7192 
7193   bool ListContainsSP = listContainsReg(Inst, ListNo, ARM::SP);
7194   bool ListContainsPC = listContainsReg(Inst, ListNo, ARM::PC);
7195 
7196   if (ListContainsSP && ListContainsPC)
7197     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
7198                  "SP and PC may not be in the register list");
7199   else if (ListContainsSP)
7200     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
7201                  "SP may not be in the register list");
7202   else if (ListContainsPC)
7203     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
7204                  "PC may not be in the register list");
7205   return false;
7206 }
7207 
7208 bool ARMAsmParser::validateLDRDSTRD(MCInst &Inst,
7209                                     const OperandVector &Operands,
7210                                     bool Load, bool ARMMode, bool Writeback) {
7211   unsigned RtIndex = Load || !Writeback ? 0 : 1;
7212   unsigned Rt = MRI->getEncodingValue(Inst.getOperand(RtIndex).getReg());
7213   unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(RtIndex + 1).getReg());
7214 
7215   if (ARMMode) {
7216     // Rt can't be R14.
7217     if (Rt == 14)
7218       return Error(Operands[3]->getStartLoc(),
7219                   "Rt can't be R14");
7220 
7221     // Rt must be even-numbered.
7222     if ((Rt & 1) == 1)
7223       return Error(Operands[3]->getStartLoc(),
7224                    "Rt must be even-numbered");
7225 
7226     // Rt2 must be Rt + 1.
7227     if (Rt2 != Rt + 1) {
7228       if (Load)
7229         return Error(Operands[3]->getStartLoc(),
7230                      "destination operands must be sequential");
7231       else
7232         return Error(Operands[3]->getStartLoc(),
7233                      "source operands must be sequential");
7234     }
7235 
7236     // FIXME: Diagnose m == 15
7237     // FIXME: Diagnose ldrd with m == t || m == t2.
7238   }
7239 
7240   if (!ARMMode && Load) {
7241     if (Rt2 == Rt)
7242       return Error(Operands[3]->getStartLoc(),
7243                    "destination operands can't be identical");
7244   }
7245 
7246   if (Writeback) {
7247     unsigned Rn = MRI->getEncodingValue(Inst.getOperand(3).getReg());
7248 
7249     if (Rn == Rt || Rn == Rt2) {
7250       if (Load)
7251         return Error(Operands[3]->getStartLoc(),
7252                      "base register needs to be different from destination "
7253                      "registers");
7254       else
7255         return Error(Operands[3]->getStartLoc(),
7256                      "source register and base register can't be identical");
7257     }
7258 
7259     // FIXME: Diagnose ldrd/strd with writeback and n == 15.
7260     // (Except the immediate form of ldrd?)
7261   }
7262 
7263   return false;
7264 }
7265 
7266 static int findFirstVectorPredOperandIdx(const MCInstrDesc &MCID) {
7267   for (unsigned i = 0; i < MCID.NumOperands; ++i) {
7268     if (ARM::isVpred(MCID.OpInfo[i].OperandType))
7269       return i;
7270   }
7271   return -1;
7272 }
7273 
7274 static bool isVectorPredicable(const MCInstrDesc &MCID) {
7275   return findFirstVectorPredOperandIdx(MCID) != -1;
7276 }
7277 
7278 // FIXME: We would really like to be able to tablegen'erate this.
7279 bool ARMAsmParser::validateInstruction(MCInst &Inst,
7280                                        const OperandVector &Operands) {
7281   const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
7282   SMLoc Loc = Operands[0]->getStartLoc();
7283 
7284   // Check the IT block state first.
7285   // NOTE: BKPT and HLT instructions have the interesting property of being
7286   // allowed in IT blocks, but not being predicable. They just always execute.
7287   if (inITBlock() && !instIsBreakpoint(Inst)) {
7288     // The instruction must be predicable.
7289     if (!MCID.isPredicable())
7290       return Error(Loc, "instructions in IT block must be predicable");
7291     ARMCC::CondCodes Cond = ARMCC::CondCodes(
7292         Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm());
7293     if (Cond != currentITCond()) {
7294       // Find the condition code Operand to get its SMLoc information.
7295       SMLoc CondLoc;
7296       for (unsigned I = 1; I < Operands.size(); ++I)
7297         if (static_cast<ARMOperand &>(*Operands[I]).isCondCode())
7298           CondLoc = Operands[I]->getStartLoc();
7299       return Error(CondLoc, "incorrect condition in IT block; got '" +
7300                                 StringRef(ARMCondCodeToString(Cond)) +
7301                                 "', but expected '" +
7302                                 ARMCondCodeToString(currentITCond()) + "'");
7303     }
7304   // Check for non-'al' condition codes outside of the IT block.
7305   } else if (isThumbTwo() && MCID.isPredicable() &&
7306              Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm() !=
7307              ARMCC::AL && Inst.getOpcode() != ARM::tBcc &&
7308              Inst.getOpcode() != ARM::t2Bcc &&
7309              Inst.getOpcode() != ARM::t2BFic) {
7310     return Error(Loc, "predicated instructions must be in IT block");
7311   } else if (!isThumb() && !useImplicitITARM() && MCID.isPredicable() &&
7312              Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm() !=
7313                  ARMCC::AL) {
7314     return Warning(Loc, "predicated instructions should be in IT block");
7315   } else if (!MCID.isPredicable()) {
7316     // Check the instruction doesn't have a predicate operand anyway
7317     // that it's not allowed to use. Sometimes this happens in order
7318     // to keep instructions the same shape even though one cannot
7319     // legally be predicated, e.g. vmul.f16 vs vmul.f32.
7320     for (unsigned i = 0, e = MCID.getNumOperands(); i != e; ++i) {
7321       if (MCID.OpInfo[i].isPredicate()) {
7322         if (Inst.getOperand(i).getImm() != ARMCC::AL)
7323           return Error(Loc, "instruction is not predicable");
7324         break;
7325       }
7326     }
7327   }
7328 
7329   // PC-setting instructions in an IT block, but not the last instruction of
7330   // the block, are UNPREDICTABLE.
7331   if (inExplicitITBlock() && !lastInITBlock() && isITBlockTerminator(Inst)) {
7332     return Error(Loc, "instruction must be outside of IT block or the last instruction in an IT block");
7333   }
7334 
7335   if (inVPTBlock() && !instIsBreakpoint(Inst)) {
7336     unsigned Bit = extractITMaskBit(VPTState.Mask, VPTState.CurPosition);
7337     if (!isVectorPredicable(MCID))
7338       return Error(Loc, "instruction in VPT block must be predicable");
7339     unsigned Pred = Inst.getOperand(findFirstVectorPredOperandIdx(MCID)).getImm();
7340     unsigned VPTPred = Bit ? ARMVCC::Else : ARMVCC::Then;
7341     if (Pred != VPTPred) {
7342       SMLoc PredLoc;
7343       for (unsigned I = 1; I < Operands.size(); ++I)
7344         if (static_cast<ARMOperand &>(*Operands[I]).isVPTPred())
7345           PredLoc = Operands[I]->getStartLoc();
7346       return Error(PredLoc, "incorrect predication in VPT block; got '" +
7347                    StringRef(ARMVPTPredToString(ARMVCC::VPTCodes(Pred))) +
7348                    "', but expected '" +
7349                    ARMVPTPredToString(ARMVCC::VPTCodes(VPTPred)) + "'");
7350     }
7351   }
7352   else if (isVectorPredicable(MCID) &&
7353            Inst.getOperand(findFirstVectorPredOperandIdx(MCID)).getImm() !=
7354            ARMVCC::None)
7355     return Error(Loc, "VPT predicated instructions must be in VPT block");
7356 
7357   const unsigned Opcode = Inst.getOpcode();
7358   switch (Opcode) {
7359   case ARM::t2IT: {
7360     // Encoding is unpredictable if it ever results in a notional 'NV'
7361     // predicate. Since we don't parse 'NV' directly this means an 'AL'
7362     // predicate with an "else" mask bit.
7363     unsigned Cond = Inst.getOperand(0).getImm();
7364     unsigned Mask = Inst.getOperand(1).getImm();
7365 
7366     // Conditions only allowing a 't' are those with no set bit except
7367     // the lowest-order one that indicates the end of the sequence. In
7368     // other words, powers of 2.
7369     if (Cond == ARMCC::AL && countPopulation(Mask) != 1)
7370       return Error(Loc, "unpredictable IT predicate sequence");
7371     break;
7372   }
7373   case ARM::LDRD:
7374     if (validateLDRDSTRD(Inst, Operands, /*Load*/true, /*ARMMode*/true,
7375                          /*Writeback*/false))
7376       return true;
7377     break;
7378   case ARM::LDRD_PRE:
7379   case ARM::LDRD_POST:
7380     if (validateLDRDSTRD(Inst, Operands, /*Load*/true, /*ARMMode*/true,
7381                          /*Writeback*/true))
7382       return true;
7383     break;
7384   case ARM::t2LDRDi8:
7385     if (validateLDRDSTRD(Inst, Operands, /*Load*/true, /*ARMMode*/false,
7386                          /*Writeback*/false))
7387       return true;
7388     break;
7389   case ARM::t2LDRD_PRE:
7390   case ARM::t2LDRD_POST:
7391     if (validateLDRDSTRD(Inst, Operands, /*Load*/true, /*ARMMode*/false,
7392                          /*Writeback*/true))
7393       return true;
7394     break;
7395   case ARM::t2BXJ: {
7396     const unsigned RmReg = Inst.getOperand(0).getReg();
7397     // Rm = SP is no longer unpredictable in v8-A
7398     if (RmReg == ARM::SP && !hasV8Ops())
7399       return Error(Operands[2]->getStartLoc(),
7400                    "r13 (SP) is an unpredictable operand to BXJ");
7401     return false;
7402   }
7403   case ARM::STRD:
7404     if (validateLDRDSTRD(Inst, Operands, /*Load*/false, /*ARMMode*/true,
7405                          /*Writeback*/false))
7406       return true;
7407     break;
7408   case ARM::STRD_PRE:
7409   case ARM::STRD_POST:
7410     if (validateLDRDSTRD(Inst, Operands, /*Load*/false, /*ARMMode*/true,
7411                          /*Writeback*/true))
7412       return true;
7413     break;
7414   case ARM::t2STRD_PRE:
7415   case ARM::t2STRD_POST:
7416     if (validateLDRDSTRD(Inst, Operands, /*Load*/false, /*ARMMode*/false,
7417                          /*Writeback*/true))
7418       return true;
7419     break;
7420   case ARM::STR_PRE_IMM:
7421   case ARM::STR_PRE_REG:
7422   case ARM::t2STR_PRE:
7423   case ARM::STR_POST_IMM:
7424   case ARM::STR_POST_REG:
7425   case ARM::t2STR_POST:
7426   case ARM::STRH_PRE:
7427   case ARM::t2STRH_PRE:
7428   case ARM::STRH_POST:
7429   case ARM::t2STRH_POST:
7430   case ARM::STRB_PRE_IMM:
7431   case ARM::STRB_PRE_REG:
7432   case ARM::t2STRB_PRE:
7433   case ARM::STRB_POST_IMM:
7434   case ARM::STRB_POST_REG:
7435   case ARM::t2STRB_POST: {
7436     // Rt must be different from Rn.
7437     const unsigned Rt = MRI->getEncodingValue(Inst.getOperand(1).getReg());
7438     const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(2).getReg());
7439 
7440     if (Rt == Rn)
7441       return Error(Operands[3]->getStartLoc(),
7442                    "source register and base register can't be identical");
7443     return false;
7444   }
7445   case ARM::LDR_PRE_IMM:
7446   case ARM::LDR_PRE_REG:
7447   case ARM::t2LDR_PRE:
7448   case ARM::LDR_POST_IMM:
7449   case ARM::LDR_POST_REG:
7450   case ARM::t2LDR_POST:
7451   case ARM::LDRH_PRE:
7452   case ARM::t2LDRH_PRE:
7453   case ARM::LDRH_POST:
7454   case ARM::t2LDRH_POST:
7455   case ARM::LDRSH_PRE:
7456   case ARM::t2LDRSH_PRE:
7457   case ARM::LDRSH_POST:
7458   case ARM::t2LDRSH_POST:
7459   case ARM::LDRB_PRE_IMM:
7460   case ARM::LDRB_PRE_REG:
7461   case ARM::t2LDRB_PRE:
7462   case ARM::LDRB_POST_IMM:
7463   case ARM::LDRB_POST_REG:
7464   case ARM::t2LDRB_POST:
7465   case ARM::LDRSB_PRE:
7466   case ARM::t2LDRSB_PRE:
7467   case ARM::LDRSB_POST:
7468   case ARM::t2LDRSB_POST: {
7469     // Rt must be different from Rn.
7470     const unsigned Rt = MRI->getEncodingValue(Inst.getOperand(0).getReg());
7471     const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(2).getReg());
7472 
7473     if (Rt == Rn)
7474       return Error(Operands[3]->getStartLoc(),
7475                    "destination register and base register can't be identical");
7476     return false;
7477   }
7478 
7479   case ARM::MVE_VLDRBU8_rq:
7480   case ARM::MVE_VLDRBU16_rq:
7481   case ARM::MVE_VLDRBS16_rq:
7482   case ARM::MVE_VLDRBU32_rq:
7483   case ARM::MVE_VLDRBS32_rq:
7484   case ARM::MVE_VLDRHU16_rq:
7485   case ARM::MVE_VLDRHU16_rq_u:
7486   case ARM::MVE_VLDRHU32_rq:
7487   case ARM::MVE_VLDRHU32_rq_u:
7488   case ARM::MVE_VLDRHS32_rq:
7489   case ARM::MVE_VLDRHS32_rq_u:
7490   case ARM::MVE_VLDRWU32_rq:
7491   case ARM::MVE_VLDRWU32_rq_u:
7492   case ARM::MVE_VLDRDU64_rq:
7493   case ARM::MVE_VLDRDU64_rq_u:
7494   case ARM::MVE_VLDRWU32_qi:
7495   case ARM::MVE_VLDRWU32_qi_pre:
7496   case ARM::MVE_VLDRDU64_qi:
7497   case ARM::MVE_VLDRDU64_qi_pre: {
7498     // Qd must be different from Qm.
7499     unsigned QdIdx = 0, QmIdx = 2;
7500     bool QmIsPointer = false;
7501     switch (Opcode) {
7502     case ARM::MVE_VLDRWU32_qi:
7503     case ARM::MVE_VLDRDU64_qi:
7504       QmIdx = 1;
7505       QmIsPointer = true;
7506       break;
7507     case ARM::MVE_VLDRWU32_qi_pre:
7508     case ARM::MVE_VLDRDU64_qi_pre:
7509       QdIdx = 1;
7510       QmIsPointer = true;
7511       break;
7512     }
7513 
7514     const unsigned Qd = MRI->getEncodingValue(Inst.getOperand(QdIdx).getReg());
7515     const unsigned Qm = MRI->getEncodingValue(Inst.getOperand(QmIdx).getReg());
7516 
7517     if (Qd == Qm) {
7518       return Error(Operands[3]->getStartLoc(),
7519                    Twine("destination vector register and vector ") +
7520                    (QmIsPointer ? "pointer" : "offset") +
7521                    " register can't be identical");
7522     }
7523     return false;
7524   }
7525 
7526   case ARM::SBFX:
7527   case ARM::t2SBFX:
7528   case ARM::UBFX:
7529   case ARM::t2UBFX: {
7530     // Width must be in range [1, 32-lsb].
7531     unsigned LSB = Inst.getOperand(2).getImm();
7532     unsigned Widthm1 = Inst.getOperand(3).getImm();
7533     if (Widthm1 >= 32 - LSB)
7534       return Error(Operands[5]->getStartLoc(),
7535                    "bitfield width must be in range [1,32-lsb]");
7536     return false;
7537   }
7538   // Notionally handles ARM::tLDMIA_UPD too.
7539   case ARM::tLDMIA: {
7540     // If we're parsing Thumb2, the .w variant is available and handles
7541     // most cases that are normally illegal for a Thumb1 LDM instruction.
7542     // We'll make the transformation in processInstruction() if necessary.
7543     //
7544     // Thumb LDM instructions are writeback iff the base register is not
7545     // in the register list.
7546     unsigned Rn = Inst.getOperand(0).getReg();
7547     bool HasWritebackToken =
7548         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
7549          static_cast<ARMOperand &>(*Operands[3]).getToken() == "!");
7550     bool ListContainsBase;
7551     if (checkLowRegisterList(Inst, 3, Rn, 0, ListContainsBase) && !isThumbTwo())
7552       return Error(Operands[3 + HasWritebackToken]->getStartLoc(),
7553                    "registers must be in range r0-r7");
7554     // If we should have writeback, then there should be a '!' token.
7555     if (!ListContainsBase && !HasWritebackToken && !isThumbTwo())
7556       return Error(Operands[2]->getStartLoc(),
7557                    "writeback operator '!' expected");
7558     // If we should not have writeback, there must not be a '!'. This is
7559     // true even for the 32-bit wide encodings.
7560     if (ListContainsBase && HasWritebackToken)
7561       return Error(Operands[3]->getStartLoc(),
7562                    "writeback operator '!' not allowed when base register "
7563                    "in register list");
7564 
7565     if (validatetLDMRegList(Inst, Operands, 3))
7566       return true;
7567     break;
7568   }
7569   case ARM::LDMIA_UPD:
7570   case ARM::LDMDB_UPD:
7571   case ARM::LDMIB_UPD:
7572   case ARM::LDMDA_UPD:
7573     // ARM variants loading and updating the same register are only officially
7574     // UNPREDICTABLE on v7 upwards. Goodness knows what they did before.
7575     if (!hasV7Ops())
7576       break;
7577     if (listContainsReg(Inst, 3, Inst.getOperand(0).getReg()))
7578       return Error(Operands.back()->getStartLoc(),
7579                    "writeback register not allowed in register list");
7580     break;
7581   case ARM::t2LDMIA:
7582   case ARM::t2LDMDB:
7583     if (validatetLDMRegList(Inst, Operands, 3))
7584       return true;
7585     break;
7586   case ARM::t2STMIA:
7587   case ARM::t2STMDB:
7588     if (validatetSTMRegList(Inst, Operands, 3))
7589       return true;
7590     break;
7591   case ARM::t2LDMIA_UPD:
7592   case ARM::t2LDMDB_UPD:
7593   case ARM::t2STMIA_UPD:
7594   case ARM::t2STMDB_UPD:
7595     if (listContainsReg(Inst, 3, Inst.getOperand(0).getReg()))
7596       return Error(Operands.back()->getStartLoc(),
7597                    "writeback register not allowed in register list");
7598 
7599     if (Opcode == ARM::t2LDMIA_UPD || Opcode == ARM::t2LDMDB_UPD) {
7600       if (validatetLDMRegList(Inst, Operands, 3))
7601         return true;
7602     } else {
7603       if (validatetSTMRegList(Inst, Operands, 3))
7604         return true;
7605     }
7606     break;
7607 
7608   case ARM::sysLDMIA_UPD:
7609   case ARM::sysLDMDA_UPD:
7610   case ARM::sysLDMDB_UPD:
7611   case ARM::sysLDMIB_UPD:
7612     if (!listContainsReg(Inst, 3, ARM::PC))
7613       return Error(Operands[4]->getStartLoc(),
7614                    "writeback register only allowed on system LDM "
7615                    "if PC in register-list");
7616     break;
7617   case ARM::sysSTMIA_UPD:
7618   case ARM::sysSTMDA_UPD:
7619   case ARM::sysSTMDB_UPD:
7620   case ARM::sysSTMIB_UPD:
7621     return Error(Operands[2]->getStartLoc(),
7622                  "system STM cannot have writeback register");
7623   case ARM::tMUL:
7624     // The second source operand must be the same register as the destination
7625     // operand.
7626     //
7627     // In this case, we must directly check the parsed operands because the
7628     // cvtThumbMultiply() function is written in such a way that it guarantees
7629     // this first statement is always true for the new Inst.  Essentially, the
7630     // destination is unconditionally copied into the second source operand
7631     // without checking to see if it matches what we actually parsed.
7632     if (Operands.size() == 6 && (((ARMOperand &)*Operands[3]).getReg() !=
7633                                  ((ARMOperand &)*Operands[5]).getReg()) &&
7634         (((ARMOperand &)*Operands[3]).getReg() !=
7635          ((ARMOperand &)*Operands[4]).getReg())) {
7636       return Error(Operands[3]->getStartLoc(),
7637                    "destination register must match source register");
7638     }
7639     break;
7640 
7641   // Like for ldm/stm, push and pop have hi-reg handling version in Thumb2,
7642   // so only issue a diagnostic for thumb1. The instructions will be
7643   // switched to the t2 encodings in processInstruction() if necessary.
7644   case ARM::tPOP: {
7645     bool ListContainsBase;
7646     if (checkLowRegisterList(Inst, 2, 0, ARM::PC, ListContainsBase) &&
7647         !isThumbTwo())
7648       return Error(Operands[2]->getStartLoc(),
7649                    "registers must be in range r0-r7 or pc");
7650     if (validatetLDMRegList(Inst, Operands, 2, !isMClass()))
7651       return true;
7652     break;
7653   }
7654   case ARM::tPUSH: {
7655     bool ListContainsBase;
7656     if (checkLowRegisterList(Inst, 2, 0, ARM::LR, ListContainsBase) &&
7657         !isThumbTwo())
7658       return Error(Operands[2]->getStartLoc(),
7659                    "registers must be in range r0-r7 or lr");
7660     if (validatetSTMRegList(Inst, Operands, 2))
7661       return true;
7662     break;
7663   }
7664   case ARM::tSTMIA_UPD: {
7665     bool ListContainsBase, InvalidLowList;
7666     InvalidLowList = checkLowRegisterList(Inst, 4, Inst.getOperand(0).getReg(),
7667                                           0, ListContainsBase);
7668     if (InvalidLowList && !isThumbTwo())
7669       return Error(Operands[4]->getStartLoc(),
7670                    "registers must be in range r0-r7");
7671 
7672     // This would be converted to a 32-bit stm, but that's not valid if the
7673     // writeback register is in the list.
7674     if (InvalidLowList && ListContainsBase)
7675       return Error(Operands[4]->getStartLoc(),
7676                    "writeback operator '!' not allowed when base register "
7677                    "in register list");
7678 
7679     if (validatetSTMRegList(Inst, Operands, 4))
7680       return true;
7681     break;
7682   }
7683   case ARM::tADDrSP:
7684     // If the non-SP source operand and the destination operand are not the
7685     // same, we need thumb2 (for the wide encoding), or we have an error.
7686     if (!isThumbTwo() &&
7687         Inst.getOperand(0).getReg() != Inst.getOperand(2).getReg()) {
7688       return Error(Operands[4]->getStartLoc(),
7689                    "source register must be the same as destination");
7690     }
7691     break;
7692 
7693   case ARM::t2ADDri:
7694   case ARM::t2ADDri12:
7695   case ARM::t2ADDrr:
7696   case ARM::t2ADDrs:
7697   case ARM::t2SUBri:
7698   case ARM::t2SUBri12:
7699   case ARM::t2SUBrr:
7700   case ARM::t2SUBrs:
7701     if (Inst.getOperand(0).getReg() == ARM::SP &&
7702         Inst.getOperand(1).getReg() != ARM::SP)
7703       return Error(Operands[4]->getStartLoc(),
7704                    "source register must be sp if destination is sp");
7705     break;
7706 
7707   // Final range checking for Thumb unconditional branch instructions.
7708   case ARM::tB:
7709     if (!(static_cast<ARMOperand &>(*Operands[2])).isSignedOffset<11, 1>())
7710       return Error(Operands[2]->getStartLoc(), "branch target out of range");
7711     break;
7712   case ARM::t2B: {
7713     int op = (Operands[2]->isImm()) ? 2 : 3;
7714     if (!static_cast<ARMOperand &>(*Operands[op]).isSignedOffset<24, 1>())
7715       return Error(Operands[op]->getStartLoc(), "branch target out of range");
7716     break;
7717   }
7718   // Final range checking for Thumb conditional branch instructions.
7719   case ARM::tBcc:
7720     if (!static_cast<ARMOperand &>(*Operands[2]).isSignedOffset<8, 1>())
7721       return Error(Operands[2]->getStartLoc(), "branch target out of range");
7722     break;
7723   case ARM::t2Bcc: {
7724     int Op = (Operands[2]->isImm()) ? 2 : 3;
7725     if (!static_cast<ARMOperand &>(*Operands[Op]).isSignedOffset<20, 1>())
7726       return Error(Operands[Op]->getStartLoc(), "branch target out of range");
7727     break;
7728   }
7729   case ARM::tCBZ:
7730   case ARM::tCBNZ: {
7731     if (!static_cast<ARMOperand &>(*Operands[2]).isUnsignedOffset<6, 1>())
7732       return Error(Operands[2]->getStartLoc(), "branch target out of range");
7733     break;
7734   }
7735   case ARM::MOVi16:
7736   case ARM::MOVTi16:
7737   case ARM::t2MOVi16:
7738   case ARM::t2MOVTi16:
7739     {
7740     // We want to avoid misleadingly allowing something like "mov r0, <symbol>"
7741     // especially when we turn it into a movw and the expression <symbol> does
7742     // not have a :lower16: or :upper16 as part of the expression.  We don't
7743     // want the behavior of silently truncating, which can be unexpected and
7744     // lead to bugs that are difficult to find since this is an easy mistake
7745     // to make.
7746     int i = (Operands[3]->isImm()) ? 3 : 4;
7747     ARMOperand &Op = static_cast<ARMOperand &>(*Operands[i]);
7748     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm());
7749     if (CE) break;
7750     const MCExpr *E = dyn_cast<MCExpr>(Op.getImm());
7751     if (!E) break;
7752     const ARMMCExpr *ARM16Expr = dyn_cast<ARMMCExpr>(E);
7753     if (!ARM16Expr || (ARM16Expr->getKind() != ARMMCExpr::VK_ARM_HI16 &&
7754                        ARM16Expr->getKind() != ARMMCExpr::VK_ARM_LO16))
7755       return Error(
7756           Op.getStartLoc(),
7757           "immediate expression for mov requires :lower16: or :upper16");
7758     break;
7759   }
7760   case ARM::HINT:
7761   case ARM::t2HINT: {
7762     unsigned Imm8 = Inst.getOperand(0).getImm();
7763     unsigned Pred = Inst.getOperand(1).getImm();
7764     // ESB is not predicable (pred must be AL). Without the RAS extension, this
7765     // behaves as any other unallocated hint.
7766     if (Imm8 == 0x10 && Pred != ARMCC::AL && hasRAS())
7767       return Error(Operands[1]->getStartLoc(), "instruction 'esb' is not "
7768                                                "predicable, but condition "
7769                                                "code specified");
7770     if (Imm8 == 0x14 && Pred != ARMCC::AL)
7771       return Error(Operands[1]->getStartLoc(), "instruction 'csdb' is not "
7772                                                "predicable, but condition "
7773                                                "code specified");
7774     break;
7775   }
7776   case ARM::t2BFi:
7777   case ARM::t2BFr:
7778   case ARM::t2BFLi:
7779   case ARM::t2BFLr: {
7780     if (!static_cast<ARMOperand &>(*Operands[2]).isUnsignedOffset<4, 1>() ||
7781         (Inst.getOperand(0).isImm() && Inst.getOperand(0).getImm() == 0))
7782       return Error(Operands[2]->getStartLoc(),
7783                    "branch location out of range or not a multiple of 2");
7784 
7785     if (Opcode == ARM::t2BFi) {
7786       if (!static_cast<ARMOperand &>(*Operands[3]).isSignedOffset<16, 1>())
7787         return Error(Operands[3]->getStartLoc(),
7788                      "branch target out of range or not a multiple of 2");
7789     } else if (Opcode == ARM::t2BFLi) {
7790       if (!static_cast<ARMOperand &>(*Operands[3]).isSignedOffset<18, 1>())
7791         return Error(Operands[3]->getStartLoc(),
7792                      "branch target out of range or not a multiple of 2");
7793     }
7794     break;
7795   }
7796   case ARM::t2BFic: {
7797     if (!static_cast<ARMOperand &>(*Operands[1]).isUnsignedOffset<4, 1>() ||
7798         (Inst.getOperand(0).isImm() && Inst.getOperand(0).getImm() == 0))
7799       return Error(Operands[1]->getStartLoc(),
7800                    "branch location out of range or not a multiple of 2");
7801 
7802     if (!static_cast<ARMOperand &>(*Operands[2]).isSignedOffset<16, 1>())
7803       return Error(Operands[2]->getStartLoc(),
7804                    "branch target out of range or not a multiple of 2");
7805 
7806     assert(Inst.getOperand(0).isImm() == Inst.getOperand(2).isImm() &&
7807            "branch location and else branch target should either both be "
7808            "immediates or both labels");
7809 
7810     if (Inst.getOperand(0).isImm() && Inst.getOperand(2).isImm()) {
7811       int Diff = Inst.getOperand(2).getImm() - Inst.getOperand(0).getImm();
7812       if (Diff != 4 && Diff != 2)
7813         return Error(
7814             Operands[3]->getStartLoc(),
7815             "else branch target must be 2 or 4 greater than the branch location");
7816     }
7817     break;
7818   }
7819   case ARM::t2CLRM: {
7820     for (unsigned i = 2; i < Inst.getNumOperands(); i++) {
7821       if (Inst.getOperand(i).isReg() &&
7822           !ARMMCRegisterClasses[ARM::GPRwithAPSRnospRegClassID].contains(
7823               Inst.getOperand(i).getReg())) {
7824         return Error(Operands[2]->getStartLoc(),
7825                      "invalid register in register list. Valid registers are "
7826                      "r0-r12, lr/r14 and APSR.");
7827       }
7828     }
7829     break;
7830   }
7831   case ARM::DSB:
7832   case ARM::t2DSB: {
7833 
7834     if (Inst.getNumOperands() < 2)
7835       break;
7836 
7837     unsigned Option = Inst.getOperand(0).getImm();
7838     unsigned Pred = Inst.getOperand(1).getImm();
7839 
7840     // SSBB and PSSBB (DSB #0|#4) are not predicable (pred must be AL).
7841     if (Option == 0 && Pred != ARMCC::AL)
7842       return Error(Operands[1]->getStartLoc(),
7843                    "instruction 'ssbb' is not predicable, but condition code "
7844                    "specified");
7845     if (Option == 4 && Pred != ARMCC::AL)
7846       return Error(Operands[1]->getStartLoc(),
7847                    "instruction 'pssbb' is not predicable, but condition code "
7848                    "specified");
7849     break;
7850   }
7851   case ARM::VMOVRRS: {
7852     // Source registers must be sequential.
7853     const unsigned Sm = MRI->getEncodingValue(Inst.getOperand(2).getReg());
7854     const unsigned Sm1 = MRI->getEncodingValue(Inst.getOperand(3).getReg());
7855     if (Sm1 != Sm + 1)
7856       return Error(Operands[5]->getStartLoc(),
7857                    "source operands must be sequential");
7858     break;
7859   }
7860   case ARM::VMOVSRR: {
7861     // Destination registers must be sequential.
7862     const unsigned Sm = MRI->getEncodingValue(Inst.getOperand(0).getReg());
7863     const unsigned Sm1 = MRI->getEncodingValue(Inst.getOperand(1).getReg());
7864     if (Sm1 != Sm + 1)
7865       return Error(Operands[3]->getStartLoc(),
7866                    "destination operands must be sequential");
7867     break;
7868   }
7869   case ARM::VLDMDIA:
7870   case ARM::VSTMDIA: {
7871     ARMOperand &Op = static_cast<ARMOperand&>(*Operands[3]);
7872     auto &RegList = Op.getRegList();
7873     if (RegList.size() < 1 || RegList.size() > 16)
7874       return Error(Operands[3]->getStartLoc(),
7875                    "list of registers must be at least 1 and at most 16");
7876     break;
7877   }
7878   case ARM::MVE_VQDMULLs32bh:
7879   case ARM::MVE_VQDMULLs32th:
7880   case ARM::MVE_VCMULf32:
7881   case ARM::MVE_VMULLs32bh:
7882   case ARM::MVE_VMULLs32th:
7883   case ARM::MVE_VMULLu32bh:
7884   case ARM::MVE_VMULLu32th: {
7885     if (Operands[3]->getReg() == Operands[4]->getReg()) {
7886       return Error (Operands[3]->getStartLoc(),
7887                     "Qd register and Qn register can't be identical");
7888     }
7889     if (Operands[3]->getReg() == Operands[5]->getReg()) {
7890       return Error (Operands[3]->getStartLoc(),
7891                     "Qd register and Qm register can't be identical");
7892     }
7893     break;
7894   }
7895   case ARM::MVE_VMOV_rr_q: {
7896     if (Operands[4]->getReg() != Operands[6]->getReg())
7897       return Error (Operands[4]->getStartLoc(), "Q-registers must be the same");
7898     if (static_cast<ARMOperand &>(*Operands[5]).getVectorIndex() !=
7899         static_cast<ARMOperand &>(*Operands[7]).getVectorIndex() + 2)
7900       return Error (Operands[5]->getStartLoc(), "Q-register indexes must be 2 and 0 or 3 and 1");
7901     break;
7902   }
7903   case ARM::MVE_VMOV_q_rr: {
7904     if (Operands[2]->getReg() != Operands[4]->getReg())
7905       return Error (Operands[2]->getStartLoc(), "Q-registers must be the same");
7906     if (static_cast<ARMOperand &>(*Operands[3]).getVectorIndex() !=
7907         static_cast<ARMOperand &>(*Operands[5]).getVectorIndex() + 2)
7908       return Error (Operands[3]->getStartLoc(), "Q-register indexes must be 2 and 0 or 3 and 1");
7909     break;
7910   }
7911   }
7912 
7913   return false;
7914 }
7915 
7916 static unsigned getRealVSTOpcode(unsigned Opc, unsigned &Spacing) {
7917   switch(Opc) {
7918   default: llvm_unreachable("unexpected opcode!");
7919   // VST1LN
7920   case ARM::VST1LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST1LNd8_UPD;
7921   case ARM::VST1LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST1LNd16_UPD;
7922   case ARM::VST1LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST1LNd32_UPD;
7923   case ARM::VST1LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST1LNd8_UPD;
7924   case ARM::VST1LNdWB_register_Asm_16: Spacing = 1; return ARM::VST1LNd16_UPD;
7925   case ARM::VST1LNdWB_register_Asm_32: Spacing = 1; return ARM::VST1LNd32_UPD;
7926   case ARM::VST1LNdAsm_8:  Spacing = 1; return ARM::VST1LNd8;
7927   case ARM::VST1LNdAsm_16: Spacing = 1; return ARM::VST1LNd16;
7928   case ARM::VST1LNdAsm_32: Spacing = 1; return ARM::VST1LNd32;
7929 
7930   // VST2LN
7931   case ARM::VST2LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST2LNd8_UPD;
7932   case ARM::VST2LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST2LNd16_UPD;
7933   case ARM::VST2LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST2LNd32_UPD;
7934   case ARM::VST2LNqWB_fixed_Asm_16: Spacing = 2; return ARM::VST2LNq16_UPD;
7935   case ARM::VST2LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST2LNq32_UPD;
7936 
7937   case ARM::VST2LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST2LNd8_UPD;
7938   case ARM::VST2LNdWB_register_Asm_16: Spacing = 1; return ARM::VST2LNd16_UPD;
7939   case ARM::VST2LNdWB_register_Asm_32: Spacing = 1; return ARM::VST2LNd32_UPD;
7940   case ARM::VST2LNqWB_register_Asm_16: Spacing = 2; return ARM::VST2LNq16_UPD;
7941   case ARM::VST2LNqWB_register_Asm_32: Spacing = 2; return ARM::VST2LNq32_UPD;
7942 
7943   case ARM::VST2LNdAsm_8:  Spacing = 1; return ARM::VST2LNd8;
7944   case ARM::VST2LNdAsm_16: Spacing = 1; return ARM::VST2LNd16;
7945   case ARM::VST2LNdAsm_32: Spacing = 1; return ARM::VST2LNd32;
7946   case ARM::VST2LNqAsm_16: Spacing = 2; return ARM::VST2LNq16;
7947   case ARM::VST2LNqAsm_32: Spacing = 2; return ARM::VST2LNq32;
7948 
7949   // VST3LN
7950   case ARM::VST3LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST3LNd8_UPD;
7951   case ARM::VST3LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST3LNd16_UPD;
7952   case ARM::VST3LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST3LNd32_UPD;
7953   case ARM::VST3LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VST3LNq16_UPD;
7954   case ARM::VST3LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST3LNq32_UPD;
7955   case ARM::VST3LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST3LNd8_UPD;
7956   case ARM::VST3LNdWB_register_Asm_16: Spacing = 1; return ARM::VST3LNd16_UPD;
7957   case ARM::VST3LNdWB_register_Asm_32: Spacing = 1; return ARM::VST3LNd32_UPD;
7958   case ARM::VST3LNqWB_register_Asm_16: Spacing = 2; return ARM::VST3LNq16_UPD;
7959   case ARM::VST3LNqWB_register_Asm_32: Spacing = 2; return ARM::VST3LNq32_UPD;
7960   case ARM::VST3LNdAsm_8:  Spacing = 1; return ARM::VST3LNd8;
7961   case ARM::VST3LNdAsm_16: Spacing = 1; return ARM::VST3LNd16;
7962   case ARM::VST3LNdAsm_32: Spacing = 1; return ARM::VST3LNd32;
7963   case ARM::VST3LNqAsm_16: Spacing = 2; return ARM::VST3LNq16;
7964   case ARM::VST3LNqAsm_32: Spacing = 2; return ARM::VST3LNq32;
7965 
7966   // VST3
7967   case ARM::VST3dWB_fixed_Asm_8:  Spacing = 1; return ARM::VST3d8_UPD;
7968   case ARM::VST3dWB_fixed_Asm_16: Spacing = 1; return ARM::VST3d16_UPD;
7969   case ARM::VST3dWB_fixed_Asm_32: Spacing = 1; return ARM::VST3d32_UPD;
7970   case ARM::VST3qWB_fixed_Asm_8:  Spacing = 2; return ARM::VST3q8_UPD;
7971   case ARM::VST3qWB_fixed_Asm_16: Spacing = 2; return ARM::VST3q16_UPD;
7972   case ARM::VST3qWB_fixed_Asm_32: Spacing = 2; return ARM::VST3q32_UPD;
7973   case ARM::VST3dWB_register_Asm_8:  Spacing = 1; return ARM::VST3d8_UPD;
7974   case ARM::VST3dWB_register_Asm_16: Spacing = 1; return ARM::VST3d16_UPD;
7975   case ARM::VST3dWB_register_Asm_32: Spacing = 1; return ARM::VST3d32_UPD;
7976   case ARM::VST3qWB_register_Asm_8:  Spacing = 2; return ARM::VST3q8_UPD;
7977   case ARM::VST3qWB_register_Asm_16: Spacing = 2; return ARM::VST3q16_UPD;
7978   case ARM::VST3qWB_register_Asm_32: Spacing = 2; return ARM::VST3q32_UPD;
7979   case ARM::VST3dAsm_8:  Spacing = 1; return ARM::VST3d8;
7980   case ARM::VST3dAsm_16: Spacing = 1; return ARM::VST3d16;
7981   case ARM::VST3dAsm_32: Spacing = 1; return ARM::VST3d32;
7982   case ARM::VST3qAsm_8:  Spacing = 2; return ARM::VST3q8;
7983   case ARM::VST3qAsm_16: Spacing = 2; return ARM::VST3q16;
7984   case ARM::VST3qAsm_32: Spacing = 2; return ARM::VST3q32;
7985 
7986   // VST4LN
7987   case ARM::VST4LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST4LNd8_UPD;
7988   case ARM::VST4LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST4LNd16_UPD;
7989   case ARM::VST4LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST4LNd32_UPD;
7990   case ARM::VST4LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VST4LNq16_UPD;
7991   case ARM::VST4LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST4LNq32_UPD;
7992   case ARM::VST4LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST4LNd8_UPD;
7993   case ARM::VST4LNdWB_register_Asm_16: Spacing = 1; return ARM::VST4LNd16_UPD;
7994   case ARM::VST4LNdWB_register_Asm_32: Spacing = 1; return ARM::VST4LNd32_UPD;
7995   case ARM::VST4LNqWB_register_Asm_16: Spacing = 2; return ARM::VST4LNq16_UPD;
7996   case ARM::VST4LNqWB_register_Asm_32: Spacing = 2; return ARM::VST4LNq32_UPD;
7997   case ARM::VST4LNdAsm_8:  Spacing = 1; return ARM::VST4LNd8;
7998   case ARM::VST4LNdAsm_16: Spacing = 1; return ARM::VST4LNd16;
7999   case ARM::VST4LNdAsm_32: Spacing = 1; return ARM::VST4LNd32;
8000   case ARM::VST4LNqAsm_16: Spacing = 2; return ARM::VST4LNq16;
8001   case ARM::VST4LNqAsm_32: Spacing = 2; return ARM::VST4LNq32;
8002 
8003   // VST4
8004   case ARM::VST4dWB_fixed_Asm_8:  Spacing = 1; return ARM::VST4d8_UPD;
8005   case ARM::VST4dWB_fixed_Asm_16: Spacing = 1; return ARM::VST4d16_UPD;
8006   case ARM::VST4dWB_fixed_Asm_32: Spacing = 1; return ARM::VST4d32_UPD;
8007   case ARM::VST4qWB_fixed_Asm_8:  Spacing = 2; return ARM::VST4q8_UPD;
8008   case ARM::VST4qWB_fixed_Asm_16: Spacing = 2; return ARM::VST4q16_UPD;
8009   case ARM::VST4qWB_fixed_Asm_32: Spacing = 2; return ARM::VST4q32_UPD;
8010   case ARM::VST4dWB_register_Asm_8:  Spacing = 1; return ARM::VST4d8_UPD;
8011   case ARM::VST4dWB_register_Asm_16: Spacing = 1; return ARM::VST4d16_UPD;
8012   case ARM::VST4dWB_register_Asm_32: Spacing = 1; return ARM::VST4d32_UPD;
8013   case ARM::VST4qWB_register_Asm_8:  Spacing = 2; return ARM::VST4q8_UPD;
8014   case ARM::VST4qWB_register_Asm_16: Spacing = 2; return ARM::VST4q16_UPD;
8015   case ARM::VST4qWB_register_Asm_32: Spacing = 2; return ARM::VST4q32_UPD;
8016   case ARM::VST4dAsm_8:  Spacing = 1; return ARM::VST4d8;
8017   case ARM::VST4dAsm_16: Spacing = 1; return ARM::VST4d16;
8018   case ARM::VST4dAsm_32: Spacing = 1; return ARM::VST4d32;
8019   case ARM::VST4qAsm_8:  Spacing = 2; return ARM::VST4q8;
8020   case ARM::VST4qAsm_16: Spacing = 2; return ARM::VST4q16;
8021   case ARM::VST4qAsm_32: Spacing = 2; return ARM::VST4q32;
8022   }
8023 }
8024 
8025 static unsigned getRealVLDOpcode(unsigned Opc, unsigned &Spacing) {
8026   switch(Opc) {
8027   default: llvm_unreachable("unexpected opcode!");
8028   // VLD1LN
8029   case ARM::VLD1LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD1LNd8_UPD;
8030   case ARM::VLD1LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD1LNd16_UPD;
8031   case ARM::VLD1LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD1LNd32_UPD;
8032   case ARM::VLD1LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD1LNd8_UPD;
8033   case ARM::VLD1LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD1LNd16_UPD;
8034   case ARM::VLD1LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD1LNd32_UPD;
8035   case ARM::VLD1LNdAsm_8:  Spacing = 1; return ARM::VLD1LNd8;
8036   case ARM::VLD1LNdAsm_16: Spacing = 1; return ARM::VLD1LNd16;
8037   case ARM::VLD1LNdAsm_32: Spacing = 1; return ARM::VLD1LNd32;
8038 
8039   // VLD2LN
8040   case ARM::VLD2LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD2LNd8_UPD;
8041   case ARM::VLD2LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD2LNd16_UPD;
8042   case ARM::VLD2LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD2LNd32_UPD;
8043   case ARM::VLD2LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD2LNq16_UPD;
8044   case ARM::VLD2LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD2LNq32_UPD;
8045   case ARM::VLD2LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD2LNd8_UPD;
8046   case ARM::VLD2LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD2LNd16_UPD;
8047   case ARM::VLD2LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD2LNd32_UPD;
8048   case ARM::VLD2LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD2LNq16_UPD;
8049   case ARM::VLD2LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD2LNq32_UPD;
8050   case ARM::VLD2LNdAsm_8:  Spacing = 1; return ARM::VLD2LNd8;
8051   case ARM::VLD2LNdAsm_16: Spacing = 1; return ARM::VLD2LNd16;
8052   case ARM::VLD2LNdAsm_32: Spacing = 1; return ARM::VLD2LNd32;
8053   case ARM::VLD2LNqAsm_16: Spacing = 2; return ARM::VLD2LNq16;
8054   case ARM::VLD2LNqAsm_32: Spacing = 2; return ARM::VLD2LNq32;
8055 
8056   // VLD3DUP
8057   case ARM::VLD3DUPdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3DUPd8_UPD;
8058   case ARM::VLD3DUPdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3DUPd16_UPD;
8059   case ARM::VLD3DUPdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3DUPd32_UPD;
8060   case ARM::VLD3DUPqWB_fixed_Asm_8: Spacing = 1; return ARM::VLD3DUPq8_UPD;
8061   case ARM::VLD3DUPqWB_fixed_Asm_16: Spacing = 2; return ARM::VLD3DUPq16_UPD;
8062   case ARM::VLD3DUPqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3DUPq32_UPD;
8063   case ARM::VLD3DUPdWB_register_Asm_8:  Spacing = 1; return ARM::VLD3DUPd8_UPD;
8064   case ARM::VLD3DUPdWB_register_Asm_16: Spacing = 1; return ARM::VLD3DUPd16_UPD;
8065   case ARM::VLD3DUPdWB_register_Asm_32: Spacing = 1; return ARM::VLD3DUPd32_UPD;
8066   case ARM::VLD3DUPqWB_register_Asm_8: Spacing = 2; return ARM::VLD3DUPq8_UPD;
8067   case ARM::VLD3DUPqWB_register_Asm_16: Spacing = 2; return ARM::VLD3DUPq16_UPD;
8068   case ARM::VLD3DUPqWB_register_Asm_32: Spacing = 2; return ARM::VLD3DUPq32_UPD;
8069   case ARM::VLD3DUPdAsm_8:  Spacing = 1; return ARM::VLD3DUPd8;
8070   case ARM::VLD3DUPdAsm_16: Spacing = 1; return ARM::VLD3DUPd16;
8071   case ARM::VLD3DUPdAsm_32: Spacing = 1; return ARM::VLD3DUPd32;
8072   case ARM::VLD3DUPqAsm_8: Spacing = 2; return ARM::VLD3DUPq8;
8073   case ARM::VLD3DUPqAsm_16: Spacing = 2; return ARM::VLD3DUPq16;
8074   case ARM::VLD3DUPqAsm_32: Spacing = 2; return ARM::VLD3DUPq32;
8075 
8076   // VLD3LN
8077   case ARM::VLD3LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3LNd8_UPD;
8078   case ARM::VLD3LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3LNd16_UPD;
8079   case ARM::VLD3LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3LNd32_UPD;
8080   case ARM::VLD3LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3LNq16_UPD;
8081   case ARM::VLD3LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3LNq32_UPD;
8082   case ARM::VLD3LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD3LNd8_UPD;
8083   case ARM::VLD3LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD3LNd16_UPD;
8084   case ARM::VLD3LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD3LNd32_UPD;
8085   case ARM::VLD3LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD3LNq16_UPD;
8086   case ARM::VLD3LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD3LNq32_UPD;
8087   case ARM::VLD3LNdAsm_8:  Spacing = 1; return ARM::VLD3LNd8;
8088   case ARM::VLD3LNdAsm_16: Spacing = 1; return ARM::VLD3LNd16;
8089   case ARM::VLD3LNdAsm_32: Spacing = 1; return ARM::VLD3LNd32;
8090   case ARM::VLD3LNqAsm_16: Spacing = 2; return ARM::VLD3LNq16;
8091   case ARM::VLD3LNqAsm_32: Spacing = 2; return ARM::VLD3LNq32;
8092 
8093   // VLD3
8094   case ARM::VLD3dWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3d8_UPD;
8095   case ARM::VLD3dWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3d16_UPD;
8096   case ARM::VLD3dWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3d32_UPD;
8097   case ARM::VLD3qWB_fixed_Asm_8:  Spacing = 2; return ARM::VLD3q8_UPD;
8098   case ARM::VLD3qWB_fixed_Asm_16: Spacing = 2; return ARM::VLD3q16_UPD;
8099   case ARM::VLD3qWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3q32_UPD;
8100   case ARM::VLD3dWB_register_Asm_8:  Spacing = 1; return ARM::VLD3d8_UPD;
8101   case ARM::VLD3dWB_register_Asm_16: Spacing = 1; return ARM::VLD3d16_UPD;
8102   case ARM::VLD3dWB_register_Asm_32: Spacing = 1; return ARM::VLD3d32_UPD;
8103   case ARM::VLD3qWB_register_Asm_8:  Spacing = 2; return ARM::VLD3q8_UPD;
8104   case ARM::VLD3qWB_register_Asm_16: Spacing = 2; return ARM::VLD3q16_UPD;
8105   case ARM::VLD3qWB_register_Asm_32: Spacing = 2; return ARM::VLD3q32_UPD;
8106   case ARM::VLD3dAsm_8:  Spacing = 1; return ARM::VLD3d8;
8107   case ARM::VLD3dAsm_16: Spacing = 1; return ARM::VLD3d16;
8108   case ARM::VLD3dAsm_32: Spacing = 1; return ARM::VLD3d32;
8109   case ARM::VLD3qAsm_8:  Spacing = 2; return ARM::VLD3q8;
8110   case ARM::VLD3qAsm_16: Spacing = 2; return ARM::VLD3q16;
8111   case ARM::VLD3qAsm_32: Spacing = 2; return ARM::VLD3q32;
8112 
8113   // VLD4LN
8114   case ARM::VLD4LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4LNd8_UPD;
8115   case ARM::VLD4LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4LNd16_UPD;
8116   case ARM::VLD4LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4LNd32_UPD;
8117   case ARM::VLD4LNqWB_fixed_Asm_16: Spacing = 2; return ARM::VLD4LNq16_UPD;
8118   case ARM::VLD4LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4LNq32_UPD;
8119   case ARM::VLD4LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD4LNd8_UPD;
8120   case ARM::VLD4LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD4LNd16_UPD;
8121   case ARM::VLD4LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD4LNd32_UPD;
8122   case ARM::VLD4LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD4LNq16_UPD;
8123   case ARM::VLD4LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD4LNq32_UPD;
8124   case ARM::VLD4LNdAsm_8:  Spacing = 1; return ARM::VLD4LNd8;
8125   case ARM::VLD4LNdAsm_16: Spacing = 1; return ARM::VLD4LNd16;
8126   case ARM::VLD4LNdAsm_32: Spacing = 1; return ARM::VLD4LNd32;
8127   case ARM::VLD4LNqAsm_16: Spacing = 2; return ARM::VLD4LNq16;
8128   case ARM::VLD4LNqAsm_32: Spacing = 2; return ARM::VLD4LNq32;
8129 
8130   // VLD4DUP
8131   case ARM::VLD4DUPdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4DUPd8_UPD;
8132   case ARM::VLD4DUPdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4DUPd16_UPD;
8133   case ARM::VLD4DUPdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4DUPd32_UPD;
8134   case ARM::VLD4DUPqWB_fixed_Asm_8: Spacing = 1; return ARM::VLD4DUPq8_UPD;
8135   case ARM::VLD4DUPqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4DUPq16_UPD;
8136   case ARM::VLD4DUPqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4DUPq32_UPD;
8137   case ARM::VLD4DUPdWB_register_Asm_8:  Spacing = 1; return ARM::VLD4DUPd8_UPD;
8138   case ARM::VLD4DUPdWB_register_Asm_16: Spacing = 1; return ARM::VLD4DUPd16_UPD;
8139   case ARM::VLD4DUPdWB_register_Asm_32: Spacing = 1; return ARM::VLD4DUPd32_UPD;
8140   case ARM::VLD4DUPqWB_register_Asm_8: Spacing = 2; return ARM::VLD4DUPq8_UPD;
8141   case ARM::VLD4DUPqWB_register_Asm_16: Spacing = 2; return ARM::VLD4DUPq16_UPD;
8142   case ARM::VLD4DUPqWB_register_Asm_32: Spacing = 2; return ARM::VLD4DUPq32_UPD;
8143   case ARM::VLD4DUPdAsm_8:  Spacing = 1; return ARM::VLD4DUPd8;
8144   case ARM::VLD4DUPdAsm_16: Spacing = 1; return ARM::VLD4DUPd16;
8145   case ARM::VLD4DUPdAsm_32: Spacing = 1; return ARM::VLD4DUPd32;
8146   case ARM::VLD4DUPqAsm_8: Spacing = 2; return ARM::VLD4DUPq8;
8147   case ARM::VLD4DUPqAsm_16: Spacing = 2; return ARM::VLD4DUPq16;
8148   case ARM::VLD4DUPqAsm_32: Spacing = 2; return ARM::VLD4DUPq32;
8149 
8150   // VLD4
8151   case ARM::VLD4dWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4d8_UPD;
8152   case ARM::VLD4dWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4d16_UPD;
8153   case ARM::VLD4dWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4d32_UPD;
8154   case ARM::VLD4qWB_fixed_Asm_8:  Spacing = 2; return ARM::VLD4q8_UPD;
8155   case ARM::VLD4qWB_fixed_Asm_16: Spacing = 2; return ARM::VLD4q16_UPD;
8156   case ARM::VLD4qWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4q32_UPD;
8157   case ARM::VLD4dWB_register_Asm_8:  Spacing = 1; return ARM::VLD4d8_UPD;
8158   case ARM::VLD4dWB_register_Asm_16: Spacing = 1; return ARM::VLD4d16_UPD;
8159   case ARM::VLD4dWB_register_Asm_32: Spacing = 1; return ARM::VLD4d32_UPD;
8160   case ARM::VLD4qWB_register_Asm_8:  Spacing = 2; return ARM::VLD4q8_UPD;
8161   case ARM::VLD4qWB_register_Asm_16: Spacing = 2; return ARM::VLD4q16_UPD;
8162   case ARM::VLD4qWB_register_Asm_32: Spacing = 2; return ARM::VLD4q32_UPD;
8163   case ARM::VLD4dAsm_8:  Spacing = 1; return ARM::VLD4d8;
8164   case ARM::VLD4dAsm_16: Spacing = 1; return ARM::VLD4d16;
8165   case ARM::VLD4dAsm_32: Spacing = 1; return ARM::VLD4d32;
8166   case ARM::VLD4qAsm_8:  Spacing = 2; return ARM::VLD4q8;
8167   case ARM::VLD4qAsm_16: Spacing = 2; return ARM::VLD4q16;
8168   case ARM::VLD4qAsm_32: Spacing = 2; return ARM::VLD4q32;
8169   }
8170 }
8171 
8172 bool ARMAsmParser::processInstruction(MCInst &Inst,
8173                                       const OperandVector &Operands,
8174                                       MCStreamer &Out) {
8175   // Check if we have the wide qualifier, because if it's present we
8176   // must avoid selecting a 16-bit thumb instruction.
8177   bool HasWideQualifier = false;
8178   for (auto &Op : Operands) {
8179     ARMOperand &ARMOp = static_cast<ARMOperand&>(*Op);
8180     if (ARMOp.isToken() && ARMOp.getToken() == ".w") {
8181       HasWideQualifier = true;
8182       break;
8183     }
8184   }
8185 
8186   switch (Inst.getOpcode()) {
8187   case ARM::MVE_VORNIZ0v4i32:
8188   case ARM::MVE_VORNIZ0v8i16:
8189   case ARM::MVE_VORNIZ8v4i32:
8190   case ARM::MVE_VORNIZ8v8i16:
8191   case ARM::MVE_VORNIZ16v4i32:
8192   case ARM::MVE_VORNIZ24v4i32:
8193   case ARM::MVE_VANDIZ0v4i32:
8194   case ARM::MVE_VANDIZ0v8i16:
8195   case ARM::MVE_VANDIZ8v4i32:
8196   case ARM::MVE_VANDIZ8v8i16:
8197   case ARM::MVE_VANDIZ16v4i32:
8198   case ARM::MVE_VANDIZ24v4i32: {
8199     unsigned Opcode;
8200     bool imm16 = false;
8201     switch(Inst.getOpcode()) {
8202     case ARM::MVE_VORNIZ0v4i32: Opcode = ARM::MVE_VORRIZ0v4i32; break;
8203     case ARM::MVE_VORNIZ0v8i16: Opcode = ARM::MVE_VORRIZ0v8i16; imm16 = true; break;
8204     case ARM::MVE_VORNIZ8v4i32: Opcode = ARM::MVE_VORRIZ8v4i32; break;
8205     case ARM::MVE_VORNIZ8v8i16: Opcode = ARM::MVE_VORRIZ8v8i16; imm16 = true; break;
8206     case ARM::MVE_VORNIZ16v4i32: Opcode = ARM::MVE_VORRIZ16v4i32; break;
8207     case ARM::MVE_VORNIZ24v4i32: Opcode = ARM::MVE_VORRIZ24v4i32; break;
8208     case ARM::MVE_VANDIZ0v4i32: Opcode = ARM::MVE_VBICIZ0v4i32; break;
8209     case ARM::MVE_VANDIZ0v8i16: Opcode = ARM::MVE_VBICIZ0v8i16; imm16 = true; break;
8210     case ARM::MVE_VANDIZ8v4i32: Opcode = ARM::MVE_VBICIZ8v4i32; break;
8211     case ARM::MVE_VANDIZ8v8i16: Opcode = ARM::MVE_VBICIZ8v8i16; imm16 = true; break;
8212     case ARM::MVE_VANDIZ16v4i32: Opcode = ARM::MVE_VBICIZ16v4i32; break;
8213     case ARM::MVE_VANDIZ24v4i32: Opcode = ARM::MVE_VBICIZ24v4i32; break;
8214     default: llvm_unreachable("unexpected opcode");
8215     }
8216 
8217     MCInst TmpInst;
8218     TmpInst.setOpcode(Opcode);
8219     TmpInst.addOperand(Inst.getOperand(0));
8220     TmpInst.addOperand(Inst.getOperand(1));
8221 
8222     // invert immediate
8223     unsigned imm = ~Inst.getOperand(2).getImm() & (imm16 ? 0xffff : 0xffffffff);
8224     TmpInst.addOperand(MCOperand::createImm(imm));
8225 
8226     TmpInst.addOperand(Inst.getOperand(3));
8227     TmpInst.addOperand(Inst.getOperand(4));
8228     Inst = TmpInst;
8229     return true;
8230   }
8231   // Alias for alternate form of 'ldr{,b}t Rt, [Rn], #imm' instruction.
8232   case ARM::LDRT_POST:
8233   case ARM::LDRBT_POST: {
8234     const unsigned Opcode =
8235       (Inst.getOpcode() == ARM::LDRT_POST) ? ARM::LDRT_POST_IMM
8236                                            : ARM::LDRBT_POST_IMM;
8237     MCInst TmpInst;
8238     TmpInst.setOpcode(Opcode);
8239     TmpInst.addOperand(Inst.getOperand(0));
8240     TmpInst.addOperand(Inst.getOperand(1));
8241     TmpInst.addOperand(Inst.getOperand(1));
8242     TmpInst.addOperand(MCOperand::createReg(0));
8243     TmpInst.addOperand(MCOperand::createImm(0));
8244     TmpInst.addOperand(Inst.getOperand(2));
8245     TmpInst.addOperand(Inst.getOperand(3));
8246     Inst = TmpInst;
8247     return true;
8248   }
8249   // Alias for alternate form of 'str{,b}t Rt, [Rn], #imm' instruction.
8250   case ARM::STRT_POST:
8251   case ARM::STRBT_POST: {
8252     const unsigned Opcode =
8253       (Inst.getOpcode() == ARM::STRT_POST) ? ARM::STRT_POST_IMM
8254                                            : ARM::STRBT_POST_IMM;
8255     MCInst TmpInst;
8256     TmpInst.setOpcode(Opcode);
8257     TmpInst.addOperand(Inst.getOperand(1));
8258     TmpInst.addOperand(Inst.getOperand(0));
8259     TmpInst.addOperand(Inst.getOperand(1));
8260     TmpInst.addOperand(MCOperand::createReg(0));
8261     TmpInst.addOperand(MCOperand::createImm(0));
8262     TmpInst.addOperand(Inst.getOperand(2));
8263     TmpInst.addOperand(Inst.getOperand(3));
8264     Inst = TmpInst;
8265     return true;
8266   }
8267   // Alias for alternate form of 'ADR Rd, #imm' instruction.
8268   case ARM::ADDri: {
8269     if (Inst.getOperand(1).getReg() != ARM::PC ||
8270         Inst.getOperand(5).getReg() != 0 ||
8271         !(Inst.getOperand(2).isExpr() || Inst.getOperand(2).isImm()))
8272       return false;
8273     MCInst TmpInst;
8274     TmpInst.setOpcode(ARM::ADR);
8275     TmpInst.addOperand(Inst.getOperand(0));
8276     if (Inst.getOperand(2).isImm()) {
8277       // Immediate (mod_imm) will be in its encoded form, we must unencode it
8278       // before passing it to the ADR instruction.
8279       unsigned Enc = Inst.getOperand(2).getImm();
8280       TmpInst.addOperand(MCOperand::createImm(
8281         ARM_AM::rotr32(Enc & 0xFF, (Enc & 0xF00) >> 7)));
8282     } else {
8283       // Turn PC-relative expression into absolute expression.
8284       // Reading PC provides the start of the current instruction + 8 and
8285       // the transform to adr is biased by that.
8286       MCSymbol *Dot = getContext().createTempSymbol();
8287       Out.EmitLabel(Dot);
8288       const MCExpr *OpExpr = Inst.getOperand(2).getExpr();
8289       const MCExpr *InstPC = MCSymbolRefExpr::create(Dot,
8290                                                      MCSymbolRefExpr::VK_None,
8291                                                      getContext());
8292       const MCExpr *Const8 = MCConstantExpr::create(8, getContext());
8293       const MCExpr *ReadPC = MCBinaryExpr::createAdd(InstPC, Const8,
8294                                                      getContext());
8295       const MCExpr *FixupAddr = MCBinaryExpr::createAdd(ReadPC, OpExpr,
8296                                                         getContext());
8297       TmpInst.addOperand(MCOperand::createExpr(FixupAddr));
8298     }
8299     TmpInst.addOperand(Inst.getOperand(3));
8300     TmpInst.addOperand(Inst.getOperand(4));
8301     Inst = TmpInst;
8302     return true;
8303   }
8304   // Aliases for alternate PC+imm syntax of LDR instructions.
8305   case ARM::t2LDRpcrel:
8306     // Select the narrow version if the immediate will fit.
8307     if (Inst.getOperand(1).getImm() > 0 &&
8308         Inst.getOperand(1).getImm() <= 0xff &&
8309         !HasWideQualifier)
8310       Inst.setOpcode(ARM::tLDRpci);
8311     else
8312       Inst.setOpcode(ARM::t2LDRpci);
8313     return true;
8314   case ARM::t2LDRBpcrel:
8315     Inst.setOpcode(ARM::t2LDRBpci);
8316     return true;
8317   case ARM::t2LDRHpcrel:
8318     Inst.setOpcode(ARM::t2LDRHpci);
8319     return true;
8320   case ARM::t2LDRSBpcrel:
8321     Inst.setOpcode(ARM::t2LDRSBpci);
8322     return true;
8323   case ARM::t2LDRSHpcrel:
8324     Inst.setOpcode(ARM::t2LDRSHpci);
8325     return true;
8326   case ARM::LDRConstPool:
8327   case ARM::tLDRConstPool:
8328   case ARM::t2LDRConstPool: {
8329     // Pseudo instruction ldr rt, =immediate is converted to a
8330     // MOV rt, immediate if immediate is known and representable
8331     // otherwise we create a constant pool entry that we load from.
8332     MCInst TmpInst;
8333     if (Inst.getOpcode() == ARM::LDRConstPool)
8334       TmpInst.setOpcode(ARM::LDRi12);
8335     else if (Inst.getOpcode() == ARM::tLDRConstPool)
8336       TmpInst.setOpcode(ARM::tLDRpci);
8337     else if (Inst.getOpcode() == ARM::t2LDRConstPool)
8338       TmpInst.setOpcode(ARM::t2LDRpci);
8339     const ARMOperand &PoolOperand =
8340       (HasWideQualifier ?
8341        static_cast<ARMOperand &>(*Operands[4]) :
8342        static_cast<ARMOperand &>(*Operands[3]));
8343     const MCExpr *SubExprVal = PoolOperand.getConstantPoolImm();
8344     // If SubExprVal is a constant we may be able to use a MOV
8345     if (isa<MCConstantExpr>(SubExprVal) &&
8346         Inst.getOperand(0).getReg() != ARM::PC &&
8347         Inst.getOperand(0).getReg() != ARM::SP) {
8348       int64_t Value =
8349         (int64_t) (cast<MCConstantExpr>(SubExprVal))->getValue();
8350       bool UseMov  = true;
8351       bool MovHasS = true;
8352       if (Inst.getOpcode() == ARM::LDRConstPool) {
8353         // ARM Constant
8354         if (ARM_AM::getSOImmVal(Value) != -1) {
8355           Value = ARM_AM::getSOImmVal(Value);
8356           TmpInst.setOpcode(ARM::MOVi);
8357         }
8358         else if (ARM_AM::getSOImmVal(~Value) != -1) {
8359           Value = ARM_AM::getSOImmVal(~Value);
8360           TmpInst.setOpcode(ARM::MVNi);
8361         }
8362         else if (hasV6T2Ops() &&
8363                  Value >=0 && Value < 65536) {
8364           TmpInst.setOpcode(ARM::MOVi16);
8365           MovHasS = false;
8366         }
8367         else
8368           UseMov = false;
8369       }
8370       else {
8371         // Thumb/Thumb2 Constant
8372         if (hasThumb2() &&
8373             ARM_AM::getT2SOImmVal(Value) != -1)
8374           TmpInst.setOpcode(ARM::t2MOVi);
8375         else if (hasThumb2() &&
8376                  ARM_AM::getT2SOImmVal(~Value) != -1) {
8377           TmpInst.setOpcode(ARM::t2MVNi);
8378           Value = ~Value;
8379         }
8380         else if (hasV8MBaseline() &&
8381                  Value >=0 && Value < 65536) {
8382           TmpInst.setOpcode(ARM::t2MOVi16);
8383           MovHasS = false;
8384         }
8385         else
8386           UseMov = false;
8387       }
8388       if (UseMov) {
8389         TmpInst.addOperand(Inst.getOperand(0));           // Rt
8390         TmpInst.addOperand(MCOperand::createImm(Value));  // Immediate
8391         TmpInst.addOperand(Inst.getOperand(2));           // CondCode
8392         TmpInst.addOperand(Inst.getOperand(3));           // CondCode
8393         if (MovHasS)
8394           TmpInst.addOperand(MCOperand::createReg(0));    // S
8395         Inst = TmpInst;
8396         return true;
8397       }
8398     }
8399     // No opportunity to use MOV/MVN create constant pool
8400     const MCExpr *CPLoc =
8401       getTargetStreamer().addConstantPoolEntry(SubExprVal,
8402                                                PoolOperand.getStartLoc());
8403     TmpInst.addOperand(Inst.getOperand(0));           // Rt
8404     TmpInst.addOperand(MCOperand::createExpr(CPLoc)); // offset to constpool
8405     if (TmpInst.getOpcode() == ARM::LDRi12)
8406       TmpInst.addOperand(MCOperand::createImm(0));    // unused offset
8407     TmpInst.addOperand(Inst.getOperand(2));           // CondCode
8408     TmpInst.addOperand(Inst.getOperand(3));           // CondCode
8409     Inst = TmpInst;
8410     return true;
8411   }
8412   // Handle NEON VST complex aliases.
8413   case ARM::VST1LNdWB_register_Asm_8:
8414   case ARM::VST1LNdWB_register_Asm_16:
8415   case ARM::VST1LNdWB_register_Asm_32: {
8416     MCInst TmpInst;
8417     // Shuffle the operands around so the lane index operand is in the
8418     // right place.
8419     unsigned Spacing;
8420     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8421     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8422     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8423     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8424     TmpInst.addOperand(Inst.getOperand(4)); // Rm
8425     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8426     TmpInst.addOperand(Inst.getOperand(1)); // lane
8427     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
8428     TmpInst.addOperand(Inst.getOperand(6));
8429     Inst = TmpInst;
8430     return true;
8431   }
8432 
8433   case ARM::VST2LNdWB_register_Asm_8:
8434   case ARM::VST2LNdWB_register_Asm_16:
8435   case ARM::VST2LNdWB_register_Asm_32:
8436   case ARM::VST2LNqWB_register_Asm_16:
8437   case ARM::VST2LNqWB_register_Asm_32: {
8438     MCInst TmpInst;
8439     // Shuffle the operands around so the lane index operand is in the
8440     // right place.
8441     unsigned Spacing;
8442     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8443     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8444     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8445     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8446     TmpInst.addOperand(Inst.getOperand(4)); // Rm
8447     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8448     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8449                                             Spacing));
8450     TmpInst.addOperand(Inst.getOperand(1)); // lane
8451     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
8452     TmpInst.addOperand(Inst.getOperand(6));
8453     Inst = TmpInst;
8454     return true;
8455   }
8456 
8457   case ARM::VST3LNdWB_register_Asm_8:
8458   case ARM::VST3LNdWB_register_Asm_16:
8459   case ARM::VST3LNdWB_register_Asm_32:
8460   case ARM::VST3LNqWB_register_Asm_16:
8461   case ARM::VST3LNqWB_register_Asm_32: {
8462     MCInst TmpInst;
8463     // Shuffle the operands around so the lane index operand is in the
8464     // right place.
8465     unsigned Spacing;
8466     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8467     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8468     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8469     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8470     TmpInst.addOperand(Inst.getOperand(4)); // Rm
8471     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8472     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8473                                             Spacing));
8474     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8475                                             Spacing * 2));
8476     TmpInst.addOperand(Inst.getOperand(1)); // lane
8477     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
8478     TmpInst.addOperand(Inst.getOperand(6));
8479     Inst = TmpInst;
8480     return true;
8481   }
8482 
8483   case ARM::VST4LNdWB_register_Asm_8:
8484   case ARM::VST4LNdWB_register_Asm_16:
8485   case ARM::VST4LNdWB_register_Asm_32:
8486   case ARM::VST4LNqWB_register_Asm_16:
8487   case ARM::VST4LNqWB_register_Asm_32: {
8488     MCInst TmpInst;
8489     // Shuffle the operands around so the lane index operand is in the
8490     // right place.
8491     unsigned Spacing;
8492     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8493     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8494     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8495     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8496     TmpInst.addOperand(Inst.getOperand(4)); // Rm
8497     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8498     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8499                                             Spacing));
8500     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8501                                             Spacing * 2));
8502     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8503                                             Spacing * 3));
8504     TmpInst.addOperand(Inst.getOperand(1)); // lane
8505     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
8506     TmpInst.addOperand(Inst.getOperand(6));
8507     Inst = TmpInst;
8508     return true;
8509   }
8510 
8511   case ARM::VST1LNdWB_fixed_Asm_8:
8512   case ARM::VST1LNdWB_fixed_Asm_16:
8513   case ARM::VST1LNdWB_fixed_Asm_32: {
8514     MCInst TmpInst;
8515     // Shuffle the operands around so the lane index operand is in the
8516     // right place.
8517     unsigned Spacing;
8518     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8519     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8520     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8521     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8522     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8523     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8524     TmpInst.addOperand(Inst.getOperand(1)); // lane
8525     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8526     TmpInst.addOperand(Inst.getOperand(5));
8527     Inst = TmpInst;
8528     return true;
8529   }
8530 
8531   case ARM::VST2LNdWB_fixed_Asm_8:
8532   case ARM::VST2LNdWB_fixed_Asm_16:
8533   case ARM::VST2LNdWB_fixed_Asm_32:
8534   case ARM::VST2LNqWB_fixed_Asm_16:
8535   case ARM::VST2LNqWB_fixed_Asm_32: {
8536     MCInst TmpInst;
8537     // Shuffle the operands around so the lane index operand is in the
8538     // right place.
8539     unsigned Spacing;
8540     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8541     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8542     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8543     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8544     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8545     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8546     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8547                                             Spacing));
8548     TmpInst.addOperand(Inst.getOperand(1)); // lane
8549     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8550     TmpInst.addOperand(Inst.getOperand(5));
8551     Inst = TmpInst;
8552     return true;
8553   }
8554 
8555   case ARM::VST3LNdWB_fixed_Asm_8:
8556   case ARM::VST3LNdWB_fixed_Asm_16:
8557   case ARM::VST3LNdWB_fixed_Asm_32:
8558   case ARM::VST3LNqWB_fixed_Asm_16:
8559   case ARM::VST3LNqWB_fixed_Asm_32: {
8560     MCInst TmpInst;
8561     // Shuffle the operands around so the lane index operand is in the
8562     // right place.
8563     unsigned Spacing;
8564     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8565     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8566     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8567     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8568     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8569     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8570     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8571                                             Spacing));
8572     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8573                                             Spacing * 2));
8574     TmpInst.addOperand(Inst.getOperand(1)); // lane
8575     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8576     TmpInst.addOperand(Inst.getOperand(5));
8577     Inst = TmpInst;
8578     return true;
8579   }
8580 
8581   case ARM::VST4LNdWB_fixed_Asm_8:
8582   case ARM::VST4LNdWB_fixed_Asm_16:
8583   case ARM::VST4LNdWB_fixed_Asm_32:
8584   case ARM::VST4LNqWB_fixed_Asm_16:
8585   case ARM::VST4LNqWB_fixed_Asm_32: {
8586     MCInst TmpInst;
8587     // Shuffle the operands around so the lane index operand is in the
8588     // right place.
8589     unsigned Spacing;
8590     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8591     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8592     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8593     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8594     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8595     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8596     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8597                                             Spacing));
8598     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8599                                             Spacing * 2));
8600     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8601                                             Spacing * 3));
8602     TmpInst.addOperand(Inst.getOperand(1)); // lane
8603     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8604     TmpInst.addOperand(Inst.getOperand(5));
8605     Inst = TmpInst;
8606     return true;
8607   }
8608 
8609   case ARM::VST1LNdAsm_8:
8610   case ARM::VST1LNdAsm_16:
8611   case ARM::VST1LNdAsm_32: {
8612     MCInst TmpInst;
8613     // Shuffle the operands around so the lane index operand is in the
8614     // right place.
8615     unsigned Spacing;
8616     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8617     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8618     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8619     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8620     TmpInst.addOperand(Inst.getOperand(1)); // lane
8621     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8622     TmpInst.addOperand(Inst.getOperand(5));
8623     Inst = TmpInst;
8624     return true;
8625   }
8626 
8627   case ARM::VST2LNdAsm_8:
8628   case ARM::VST2LNdAsm_16:
8629   case ARM::VST2LNdAsm_32:
8630   case ARM::VST2LNqAsm_16:
8631   case ARM::VST2LNqAsm_32: {
8632     MCInst TmpInst;
8633     // Shuffle the operands around so the lane index operand is in the
8634     // right place.
8635     unsigned Spacing;
8636     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8637     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8638     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8639     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8640     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8641                                             Spacing));
8642     TmpInst.addOperand(Inst.getOperand(1)); // lane
8643     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8644     TmpInst.addOperand(Inst.getOperand(5));
8645     Inst = TmpInst;
8646     return true;
8647   }
8648 
8649   case ARM::VST3LNdAsm_8:
8650   case ARM::VST3LNdAsm_16:
8651   case ARM::VST3LNdAsm_32:
8652   case ARM::VST3LNqAsm_16:
8653   case ARM::VST3LNqAsm_32: {
8654     MCInst TmpInst;
8655     // Shuffle the operands around so the lane index operand is in the
8656     // right place.
8657     unsigned Spacing;
8658     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8659     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8660     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8661     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8662     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8663                                             Spacing));
8664     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8665                                             Spacing * 2));
8666     TmpInst.addOperand(Inst.getOperand(1)); // lane
8667     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8668     TmpInst.addOperand(Inst.getOperand(5));
8669     Inst = TmpInst;
8670     return true;
8671   }
8672 
8673   case ARM::VST4LNdAsm_8:
8674   case ARM::VST4LNdAsm_16:
8675   case ARM::VST4LNdAsm_32:
8676   case ARM::VST4LNqAsm_16:
8677   case ARM::VST4LNqAsm_32: {
8678     MCInst TmpInst;
8679     // Shuffle the operands around so the lane index operand is in the
8680     // right place.
8681     unsigned Spacing;
8682     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8683     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8684     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8685     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8686     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8687                                             Spacing));
8688     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8689                                             Spacing * 2));
8690     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8691                                             Spacing * 3));
8692     TmpInst.addOperand(Inst.getOperand(1)); // lane
8693     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8694     TmpInst.addOperand(Inst.getOperand(5));
8695     Inst = TmpInst;
8696     return true;
8697   }
8698 
8699   // Handle NEON VLD complex aliases.
8700   case ARM::VLD1LNdWB_register_Asm_8:
8701   case ARM::VLD1LNdWB_register_Asm_16:
8702   case ARM::VLD1LNdWB_register_Asm_32: {
8703     MCInst TmpInst;
8704     // Shuffle the operands around so the lane index operand is in the
8705     // right place.
8706     unsigned Spacing;
8707     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8708     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8709     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8710     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8711     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8712     TmpInst.addOperand(Inst.getOperand(4)); // Rm
8713     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
8714     TmpInst.addOperand(Inst.getOperand(1)); // lane
8715     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
8716     TmpInst.addOperand(Inst.getOperand(6));
8717     Inst = TmpInst;
8718     return true;
8719   }
8720 
8721   case ARM::VLD2LNdWB_register_Asm_8:
8722   case ARM::VLD2LNdWB_register_Asm_16:
8723   case ARM::VLD2LNdWB_register_Asm_32:
8724   case ARM::VLD2LNqWB_register_Asm_16:
8725   case ARM::VLD2LNqWB_register_Asm_32: {
8726     MCInst TmpInst;
8727     // Shuffle the operands around so the lane index operand is in the
8728     // right place.
8729     unsigned Spacing;
8730     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8731     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8732     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8733                                             Spacing));
8734     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8735     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8736     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8737     TmpInst.addOperand(Inst.getOperand(4)); // Rm
8738     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
8739     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8740                                             Spacing));
8741     TmpInst.addOperand(Inst.getOperand(1)); // lane
8742     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
8743     TmpInst.addOperand(Inst.getOperand(6));
8744     Inst = TmpInst;
8745     return true;
8746   }
8747 
8748   case ARM::VLD3LNdWB_register_Asm_8:
8749   case ARM::VLD3LNdWB_register_Asm_16:
8750   case ARM::VLD3LNdWB_register_Asm_32:
8751   case ARM::VLD3LNqWB_register_Asm_16:
8752   case ARM::VLD3LNqWB_register_Asm_32: {
8753     MCInst TmpInst;
8754     // Shuffle the operands around so the lane index operand is in the
8755     // right place.
8756     unsigned Spacing;
8757     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8758     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8759     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8760                                             Spacing));
8761     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8762                                             Spacing * 2));
8763     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8764     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8765     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8766     TmpInst.addOperand(Inst.getOperand(4)); // Rm
8767     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
8768     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8769                                             Spacing));
8770     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8771                                             Spacing * 2));
8772     TmpInst.addOperand(Inst.getOperand(1)); // lane
8773     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
8774     TmpInst.addOperand(Inst.getOperand(6));
8775     Inst = TmpInst;
8776     return true;
8777   }
8778 
8779   case ARM::VLD4LNdWB_register_Asm_8:
8780   case ARM::VLD4LNdWB_register_Asm_16:
8781   case ARM::VLD4LNdWB_register_Asm_32:
8782   case ARM::VLD4LNqWB_register_Asm_16:
8783   case ARM::VLD4LNqWB_register_Asm_32: {
8784     MCInst TmpInst;
8785     // Shuffle the operands around so the lane index operand is in the
8786     // right place.
8787     unsigned Spacing;
8788     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8789     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8790     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8791                                             Spacing));
8792     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8793                                             Spacing * 2));
8794     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8795                                             Spacing * 3));
8796     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8797     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8798     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8799     TmpInst.addOperand(Inst.getOperand(4)); // Rm
8800     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
8801     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8802                                             Spacing));
8803     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8804                                             Spacing * 2));
8805     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8806                                             Spacing * 3));
8807     TmpInst.addOperand(Inst.getOperand(1)); // lane
8808     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
8809     TmpInst.addOperand(Inst.getOperand(6));
8810     Inst = TmpInst;
8811     return true;
8812   }
8813 
8814   case ARM::VLD1LNdWB_fixed_Asm_8:
8815   case ARM::VLD1LNdWB_fixed_Asm_16:
8816   case ARM::VLD1LNdWB_fixed_Asm_32: {
8817     MCInst TmpInst;
8818     // Shuffle the operands around so the lane index operand is in the
8819     // right place.
8820     unsigned Spacing;
8821     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8822     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8823     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8824     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8825     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8826     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8827     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
8828     TmpInst.addOperand(Inst.getOperand(1)); // lane
8829     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8830     TmpInst.addOperand(Inst.getOperand(5));
8831     Inst = TmpInst;
8832     return true;
8833   }
8834 
8835   case ARM::VLD2LNdWB_fixed_Asm_8:
8836   case ARM::VLD2LNdWB_fixed_Asm_16:
8837   case ARM::VLD2LNdWB_fixed_Asm_32:
8838   case ARM::VLD2LNqWB_fixed_Asm_16:
8839   case ARM::VLD2LNqWB_fixed_Asm_32: {
8840     MCInst TmpInst;
8841     // Shuffle the operands around so the lane index operand is in the
8842     // right place.
8843     unsigned Spacing;
8844     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8845     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8846     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8847                                             Spacing));
8848     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8849     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8850     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8851     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8852     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
8853     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8854                                             Spacing));
8855     TmpInst.addOperand(Inst.getOperand(1)); // lane
8856     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8857     TmpInst.addOperand(Inst.getOperand(5));
8858     Inst = TmpInst;
8859     return true;
8860   }
8861 
8862   case ARM::VLD3LNdWB_fixed_Asm_8:
8863   case ARM::VLD3LNdWB_fixed_Asm_16:
8864   case ARM::VLD3LNdWB_fixed_Asm_32:
8865   case ARM::VLD3LNqWB_fixed_Asm_16:
8866   case ARM::VLD3LNqWB_fixed_Asm_32: {
8867     MCInst TmpInst;
8868     // Shuffle the operands around so the lane index operand is in the
8869     // right place.
8870     unsigned Spacing;
8871     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8872     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8873     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8874                                             Spacing));
8875     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8876                                             Spacing * 2));
8877     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8878     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8879     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8880     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8881     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
8882     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8883                                             Spacing));
8884     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8885                                             Spacing * 2));
8886     TmpInst.addOperand(Inst.getOperand(1)); // lane
8887     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8888     TmpInst.addOperand(Inst.getOperand(5));
8889     Inst = TmpInst;
8890     return true;
8891   }
8892 
8893   case ARM::VLD4LNdWB_fixed_Asm_8:
8894   case ARM::VLD4LNdWB_fixed_Asm_16:
8895   case ARM::VLD4LNdWB_fixed_Asm_32:
8896   case ARM::VLD4LNqWB_fixed_Asm_16:
8897   case ARM::VLD4LNqWB_fixed_Asm_32: {
8898     MCInst TmpInst;
8899     // Shuffle the operands around so the lane index operand is in the
8900     // right place.
8901     unsigned Spacing;
8902     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8903     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8904     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8905                                             Spacing));
8906     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8907                                             Spacing * 2));
8908     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8909                                             Spacing * 3));
8910     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8911     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8912     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8913     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8914     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
8915     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8916                                             Spacing));
8917     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8918                                             Spacing * 2));
8919     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8920                                             Spacing * 3));
8921     TmpInst.addOperand(Inst.getOperand(1)); // lane
8922     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8923     TmpInst.addOperand(Inst.getOperand(5));
8924     Inst = TmpInst;
8925     return true;
8926   }
8927 
8928   case ARM::VLD1LNdAsm_8:
8929   case ARM::VLD1LNdAsm_16:
8930   case ARM::VLD1LNdAsm_32: {
8931     MCInst TmpInst;
8932     // Shuffle the operands around so the lane index operand is in the
8933     // right place.
8934     unsigned Spacing;
8935     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8936     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8937     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8938     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8939     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
8940     TmpInst.addOperand(Inst.getOperand(1)); // lane
8941     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8942     TmpInst.addOperand(Inst.getOperand(5));
8943     Inst = TmpInst;
8944     return true;
8945   }
8946 
8947   case ARM::VLD2LNdAsm_8:
8948   case ARM::VLD2LNdAsm_16:
8949   case ARM::VLD2LNdAsm_32:
8950   case ARM::VLD2LNqAsm_16:
8951   case ARM::VLD2LNqAsm_32: {
8952     MCInst TmpInst;
8953     // Shuffle the operands around so the lane index operand is in the
8954     // right place.
8955     unsigned Spacing;
8956     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8957     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8958     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8959                                             Spacing));
8960     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8961     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8962     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
8963     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8964                                             Spacing));
8965     TmpInst.addOperand(Inst.getOperand(1)); // lane
8966     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8967     TmpInst.addOperand(Inst.getOperand(5));
8968     Inst = TmpInst;
8969     return true;
8970   }
8971 
8972   case ARM::VLD3LNdAsm_8:
8973   case ARM::VLD3LNdAsm_16:
8974   case ARM::VLD3LNdAsm_32:
8975   case ARM::VLD3LNqAsm_16:
8976   case ARM::VLD3LNqAsm_32: {
8977     MCInst TmpInst;
8978     // Shuffle the operands around so the lane index operand is in the
8979     // right place.
8980     unsigned Spacing;
8981     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8982     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8983     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8984                                             Spacing));
8985     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8986                                             Spacing * 2));
8987     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8988     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8989     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
8990     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8991                                             Spacing));
8992     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8993                                             Spacing * 2));
8994     TmpInst.addOperand(Inst.getOperand(1)); // lane
8995     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8996     TmpInst.addOperand(Inst.getOperand(5));
8997     Inst = TmpInst;
8998     return true;
8999   }
9000 
9001   case ARM::VLD4LNdAsm_8:
9002   case ARM::VLD4LNdAsm_16:
9003   case ARM::VLD4LNdAsm_32:
9004   case ARM::VLD4LNqAsm_16:
9005   case ARM::VLD4LNqAsm_32: {
9006     MCInst TmpInst;
9007     // Shuffle the operands around so the lane index operand is in the
9008     // right place.
9009     unsigned Spacing;
9010     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9011     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9012     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9013                                             Spacing));
9014     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9015                                             Spacing * 2));
9016     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9017                                             Spacing * 3));
9018     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9019     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9020     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
9021     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9022                                             Spacing));
9023     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9024                                             Spacing * 2));
9025     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9026                                             Spacing * 3));
9027     TmpInst.addOperand(Inst.getOperand(1)); // lane
9028     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9029     TmpInst.addOperand(Inst.getOperand(5));
9030     Inst = TmpInst;
9031     return true;
9032   }
9033 
9034   // VLD3DUP single 3-element structure to all lanes instructions.
9035   case ARM::VLD3DUPdAsm_8:
9036   case ARM::VLD3DUPdAsm_16:
9037   case ARM::VLD3DUPdAsm_32:
9038   case ARM::VLD3DUPqAsm_8:
9039   case ARM::VLD3DUPqAsm_16:
9040   case ARM::VLD3DUPqAsm_32: {
9041     MCInst TmpInst;
9042     unsigned Spacing;
9043     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9044     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9045     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9046                                             Spacing));
9047     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9048                                             Spacing * 2));
9049     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9050     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9051     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9052     TmpInst.addOperand(Inst.getOperand(4));
9053     Inst = TmpInst;
9054     return true;
9055   }
9056 
9057   case ARM::VLD3DUPdWB_fixed_Asm_8:
9058   case ARM::VLD3DUPdWB_fixed_Asm_16:
9059   case ARM::VLD3DUPdWB_fixed_Asm_32:
9060   case ARM::VLD3DUPqWB_fixed_Asm_8:
9061   case ARM::VLD3DUPqWB_fixed_Asm_16:
9062   case ARM::VLD3DUPqWB_fixed_Asm_32: {
9063     MCInst TmpInst;
9064     unsigned Spacing;
9065     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9066     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9067     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9068                                             Spacing));
9069     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9070                                             Spacing * 2));
9071     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9072     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9073     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9074     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9075     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9076     TmpInst.addOperand(Inst.getOperand(4));
9077     Inst = TmpInst;
9078     return true;
9079   }
9080 
9081   case ARM::VLD3DUPdWB_register_Asm_8:
9082   case ARM::VLD3DUPdWB_register_Asm_16:
9083   case ARM::VLD3DUPdWB_register_Asm_32:
9084   case ARM::VLD3DUPqWB_register_Asm_8:
9085   case ARM::VLD3DUPqWB_register_Asm_16:
9086   case ARM::VLD3DUPqWB_register_Asm_32: {
9087     MCInst TmpInst;
9088     unsigned Spacing;
9089     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9090     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9091     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9092                                             Spacing));
9093     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9094                                             Spacing * 2));
9095     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9096     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9097     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9098     TmpInst.addOperand(Inst.getOperand(3)); // Rm
9099     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9100     TmpInst.addOperand(Inst.getOperand(5));
9101     Inst = TmpInst;
9102     return true;
9103   }
9104 
9105   // VLD3 multiple 3-element structure instructions.
9106   case ARM::VLD3dAsm_8:
9107   case ARM::VLD3dAsm_16:
9108   case ARM::VLD3dAsm_32:
9109   case ARM::VLD3qAsm_8:
9110   case ARM::VLD3qAsm_16:
9111   case ARM::VLD3qAsm_32: {
9112     MCInst TmpInst;
9113     unsigned Spacing;
9114     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9115     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9116     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9117                                             Spacing));
9118     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9119                                             Spacing * 2));
9120     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9121     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9122     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9123     TmpInst.addOperand(Inst.getOperand(4));
9124     Inst = TmpInst;
9125     return true;
9126   }
9127 
9128   case ARM::VLD3dWB_fixed_Asm_8:
9129   case ARM::VLD3dWB_fixed_Asm_16:
9130   case ARM::VLD3dWB_fixed_Asm_32:
9131   case ARM::VLD3qWB_fixed_Asm_8:
9132   case ARM::VLD3qWB_fixed_Asm_16:
9133   case ARM::VLD3qWB_fixed_Asm_32: {
9134     MCInst TmpInst;
9135     unsigned Spacing;
9136     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9137     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9138     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9139                                             Spacing));
9140     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9141                                             Spacing * 2));
9142     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9143     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9144     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9145     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9146     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9147     TmpInst.addOperand(Inst.getOperand(4));
9148     Inst = TmpInst;
9149     return true;
9150   }
9151 
9152   case ARM::VLD3dWB_register_Asm_8:
9153   case ARM::VLD3dWB_register_Asm_16:
9154   case ARM::VLD3dWB_register_Asm_32:
9155   case ARM::VLD3qWB_register_Asm_8:
9156   case ARM::VLD3qWB_register_Asm_16:
9157   case ARM::VLD3qWB_register_Asm_32: {
9158     MCInst TmpInst;
9159     unsigned Spacing;
9160     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9161     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9162     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9163                                             Spacing));
9164     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9165                                             Spacing * 2));
9166     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9167     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9168     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9169     TmpInst.addOperand(Inst.getOperand(3)); // Rm
9170     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9171     TmpInst.addOperand(Inst.getOperand(5));
9172     Inst = TmpInst;
9173     return true;
9174   }
9175 
9176   // VLD4DUP single 3-element structure to all lanes instructions.
9177   case ARM::VLD4DUPdAsm_8:
9178   case ARM::VLD4DUPdAsm_16:
9179   case ARM::VLD4DUPdAsm_32:
9180   case ARM::VLD4DUPqAsm_8:
9181   case ARM::VLD4DUPqAsm_16:
9182   case ARM::VLD4DUPqAsm_32: {
9183     MCInst TmpInst;
9184     unsigned Spacing;
9185     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9186     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9187     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9188                                             Spacing));
9189     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9190                                             Spacing * 2));
9191     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9192                                             Spacing * 3));
9193     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9194     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9195     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9196     TmpInst.addOperand(Inst.getOperand(4));
9197     Inst = TmpInst;
9198     return true;
9199   }
9200 
9201   case ARM::VLD4DUPdWB_fixed_Asm_8:
9202   case ARM::VLD4DUPdWB_fixed_Asm_16:
9203   case ARM::VLD4DUPdWB_fixed_Asm_32:
9204   case ARM::VLD4DUPqWB_fixed_Asm_8:
9205   case ARM::VLD4DUPqWB_fixed_Asm_16:
9206   case ARM::VLD4DUPqWB_fixed_Asm_32: {
9207     MCInst TmpInst;
9208     unsigned Spacing;
9209     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9210     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9211     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9212                                             Spacing));
9213     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9214                                             Spacing * 2));
9215     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9216                                             Spacing * 3));
9217     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9218     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9219     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9220     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9221     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9222     TmpInst.addOperand(Inst.getOperand(4));
9223     Inst = TmpInst;
9224     return true;
9225   }
9226 
9227   case ARM::VLD4DUPdWB_register_Asm_8:
9228   case ARM::VLD4DUPdWB_register_Asm_16:
9229   case ARM::VLD4DUPdWB_register_Asm_32:
9230   case ARM::VLD4DUPqWB_register_Asm_8:
9231   case ARM::VLD4DUPqWB_register_Asm_16:
9232   case ARM::VLD4DUPqWB_register_Asm_32: {
9233     MCInst TmpInst;
9234     unsigned Spacing;
9235     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9236     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9237     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9238                                             Spacing));
9239     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9240                                             Spacing * 2));
9241     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9242                                             Spacing * 3));
9243     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9244     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9245     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9246     TmpInst.addOperand(Inst.getOperand(3)); // Rm
9247     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9248     TmpInst.addOperand(Inst.getOperand(5));
9249     Inst = TmpInst;
9250     return true;
9251   }
9252 
9253   // VLD4 multiple 4-element structure instructions.
9254   case ARM::VLD4dAsm_8:
9255   case ARM::VLD4dAsm_16:
9256   case ARM::VLD4dAsm_32:
9257   case ARM::VLD4qAsm_8:
9258   case ARM::VLD4qAsm_16:
9259   case ARM::VLD4qAsm_32: {
9260     MCInst TmpInst;
9261     unsigned Spacing;
9262     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9263     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9264     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9265                                             Spacing));
9266     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9267                                             Spacing * 2));
9268     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9269                                             Spacing * 3));
9270     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9271     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9272     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9273     TmpInst.addOperand(Inst.getOperand(4));
9274     Inst = TmpInst;
9275     return true;
9276   }
9277 
9278   case ARM::VLD4dWB_fixed_Asm_8:
9279   case ARM::VLD4dWB_fixed_Asm_16:
9280   case ARM::VLD4dWB_fixed_Asm_32:
9281   case ARM::VLD4qWB_fixed_Asm_8:
9282   case ARM::VLD4qWB_fixed_Asm_16:
9283   case ARM::VLD4qWB_fixed_Asm_32: {
9284     MCInst TmpInst;
9285     unsigned Spacing;
9286     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9287     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9288     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9289                                             Spacing));
9290     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9291                                             Spacing * 2));
9292     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9293                                             Spacing * 3));
9294     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9295     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9296     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9297     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9298     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9299     TmpInst.addOperand(Inst.getOperand(4));
9300     Inst = TmpInst;
9301     return true;
9302   }
9303 
9304   case ARM::VLD4dWB_register_Asm_8:
9305   case ARM::VLD4dWB_register_Asm_16:
9306   case ARM::VLD4dWB_register_Asm_32:
9307   case ARM::VLD4qWB_register_Asm_8:
9308   case ARM::VLD4qWB_register_Asm_16:
9309   case ARM::VLD4qWB_register_Asm_32: {
9310     MCInst TmpInst;
9311     unsigned Spacing;
9312     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9313     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9314     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9315                                             Spacing));
9316     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9317                                             Spacing * 2));
9318     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9319                                             Spacing * 3));
9320     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9321     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9322     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9323     TmpInst.addOperand(Inst.getOperand(3)); // Rm
9324     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9325     TmpInst.addOperand(Inst.getOperand(5));
9326     Inst = TmpInst;
9327     return true;
9328   }
9329 
9330   // VST3 multiple 3-element structure instructions.
9331   case ARM::VST3dAsm_8:
9332   case ARM::VST3dAsm_16:
9333   case ARM::VST3dAsm_32:
9334   case ARM::VST3qAsm_8:
9335   case ARM::VST3qAsm_16:
9336   case ARM::VST3qAsm_32: {
9337     MCInst TmpInst;
9338     unsigned Spacing;
9339     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9340     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9341     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9342     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9343     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9344                                             Spacing));
9345     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9346                                             Spacing * 2));
9347     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9348     TmpInst.addOperand(Inst.getOperand(4));
9349     Inst = TmpInst;
9350     return true;
9351   }
9352 
9353   case ARM::VST3dWB_fixed_Asm_8:
9354   case ARM::VST3dWB_fixed_Asm_16:
9355   case ARM::VST3dWB_fixed_Asm_32:
9356   case ARM::VST3qWB_fixed_Asm_8:
9357   case ARM::VST3qWB_fixed_Asm_16:
9358   case ARM::VST3qWB_fixed_Asm_32: {
9359     MCInst TmpInst;
9360     unsigned Spacing;
9361     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9362     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9363     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9364     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9365     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9366     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9367     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9368                                             Spacing));
9369     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9370                                             Spacing * 2));
9371     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9372     TmpInst.addOperand(Inst.getOperand(4));
9373     Inst = TmpInst;
9374     return true;
9375   }
9376 
9377   case ARM::VST3dWB_register_Asm_8:
9378   case ARM::VST3dWB_register_Asm_16:
9379   case ARM::VST3dWB_register_Asm_32:
9380   case ARM::VST3qWB_register_Asm_8:
9381   case ARM::VST3qWB_register_Asm_16:
9382   case ARM::VST3qWB_register_Asm_32: {
9383     MCInst TmpInst;
9384     unsigned Spacing;
9385     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9386     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9387     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9388     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9389     TmpInst.addOperand(Inst.getOperand(3)); // Rm
9390     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9391     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9392                                             Spacing));
9393     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9394                                             Spacing * 2));
9395     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9396     TmpInst.addOperand(Inst.getOperand(5));
9397     Inst = TmpInst;
9398     return true;
9399   }
9400 
9401   // VST4 multiple 3-element structure instructions.
9402   case ARM::VST4dAsm_8:
9403   case ARM::VST4dAsm_16:
9404   case ARM::VST4dAsm_32:
9405   case ARM::VST4qAsm_8:
9406   case ARM::VST4qAsm_16:
9407   case ARM::VST4qAsm_32: {
9408     MCInst TmpInst;
9409     unsigned Spacing;
9410     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9411     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9412     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9413     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9414     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9415                                             Spacing));
9416     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9417                                             Spacing * 2));
9418     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9419                                             Spacing * 3));
9420     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9421     TmpInst.addOperand(Inst.getOperand(4));
9422     Inst = TmpInst;
9423     return true;
9424   }
9425 
9426   case ARM::VST4dWB_fixed_Asm_8:
9427   case ARM::VST4dWB_fixed_Asm_16:
9428   case ARM::VST4dWB_fixed_Asm_32:
9429   case ARM::VST4qWB_fixed_Asm_8:
9430   case ARM::VST4qWB_fixed_Asm_16:
9431   case ARM::VST4qWB_fixed_Asm_32: {
9432     MCInst TmpInst;
9433     unsigned Spacing;
9434     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9435     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9436     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9437     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9438     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9439     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9440     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9441                                             Spacing));
9442     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9443                                             Spacing * 2));
9444     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9445                                             Spacing * 3));
9446     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9447     TmpInst.addOperand(Inst.getOperand(4));
9448     Inst = TmpInst;
9449     return true;
9450   }
9451 
9452   case ARM::VST4dWB_register_Asm_8:
9453   case ARM::VST4dWB_register_Asm_16:
9454   case ARM::VST4dWB_register_Asm_32:
9455   case ARM::VST4qWB_register_Asm_8:
9456   case ARM::VST4qWB_register_Asm_16:
9457   case ARM::VST4qWB_register_Asm_32: {
9458     MCInst TmpInst;
9459     unsigned Spacing;
9460     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9461     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9462     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9463     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9464     TmpInst.addOperand(Inst.getOperand(3)); // Rm
9465     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9466     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9467                                             Spacing));
9468     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9469                                             Spacing * 2));
9470     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9471                                             Spacing * 3));
9472     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9473     TmpInst.addOperand(Inst.getOperand(5));
9474     Inst = TmpInst;
9475     return true;
9476   }
9477 
9478   // Handle encoding choice for the shift-immediate instructions.
9479   case ARM::t2LSLri:
9480   case ARM::t2LSRri:
9481   case ARM::t2ASRri:
9482     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
9483         isARMLowRegister(Inst.getOperand(1).getReg()) &&
9484         Inst.getOperand(5).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
9485         !HasWideQualifier) {
9486       unsigned NewOpc;
9487       switch (Inst.getOpcode()) {
9488       default: llvm_unreachable("unexpected opcode");
9489       case ARM::t2LSLri: NewOpc = ARM::tLSLri; break;
9490       case ARM::t2LSRri: NewOpc = ARM::tLSRri; break;
9491       case ARM::t2ASRri: NewOpc = ARM::tASRri; break;
9492       }
9493       // The Thumb1 operands aren't in the same order. Awesome, eh?
9494       MCInst TmpInst;
9495       TmpInst.setOpcode(NewOpc);
9496       TmpInst.addOperand(Inst.getOperand(0));
9497       TmpInst.addOperand(Inst.getOperand(5));
9498       TmpInst.addOperand(Inst.getOperand(1));
9499       TmpInst.addOperand(Inst.getOperand(2));
9500       TmpInst.addOperand(Inst.getOperand(3));
9501       TmpInst.addOperand(Inst.getOperand(4));
9502       Inst = TmpInst;
9503       return true;
9504     }
9505     return false;
9506 
9507   // Handle the Thumb2 mode MOV complex aliases.
9508   case ARM::t2MOVsr:
9509   case ARM::t2MOVSsr: {
9510     // Which instruction to expand to depends on the CCOut operand and
9511     // whether we're in an IT block if the register operands are low
9512     // registers.
9513     bool isNarrow = false;
9514     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
9515         isARMLowRegister(Inst.getOperand(1).getReg()) &&
9516         isARMLowRegister(Inst.getOperand(2).getReg()) &&
9517         Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() &&
9518         inITBlock() == (Inst.getOpcode() == ARM::t2MOVsr) &&
9519         !HasWideQualifier)
9520       isNarrow = true;
9521     MCInst TmpInst;
9522     unsigned newOpc;
9523     switch(ARM_AM::getSORegShOp(Inst.getOperand(3).getImm())) {
9524     default: llvm_unreachable("unexpected opcode!");
9525     case ARM_AM::asr: newOpc = isNarrow ? ARM::tASRrr : ARM::t2ASRrr; break;
9526     case ARM_AM::lsr: newOpc = isNarrow ? ARM::tLSRrr : ARM::t2LSRrr; break;
9527     case ARM_AM::lsl: newOpc = isNarrow ? ARM::tLSLrr : ARM::t2LSLrr; break;
9528     case ARM_AM::ror: newOpc = isNarrow ? ARM::tROR   : ARM::t2RORrr; break;
9529     }
9530     TmpInst.setOpcode(newOpc);
9531     TmpInst.addOperand(Inst.getOperand(0)); // Rd
9532     if (isNarrow)
9533       TmpInst.addOperand(MCOperand::createReg(
9534           Inst.getOpcode() == ARM::t2MOVSsr ? ARM::CPSR : 0));
9535     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9536     TmpInst.addOperand(Inst.getOperand(2)); // Rm
9537     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9538     TmpInst.addOperand(Inst.getOperand(5));
9539     if (!isNarrow)
9540       TmpInst.addOperand(MCOperand::createReg(
9541           Inst.getOpcode() == ARM::t2MOVSsr ? ARM::CPSR : 0));
9542     Inst = TmpInst;
9543     return true;
9544   }
9545   case ARM::t2MOVsi:
9546   case ARM::t2MOVSsi: {
9547     // Which instruction to expand to depends on the CCOut operand and
9548     // whether we're in an IT block if the register operands are low
9549     // registers.
9550     bool isNarrow = false;
9551     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
9552         isARMLowRegister(Inst.getOperand(1).getReg()) &&
9553         inITBlock() == (Inst.getOpcode() == ARM::t2MOVsi) &&
9554         !HasWideQualifier)
9555       isNarrow = true;
9556     MCInst TmpInst;
9557     unsigned newOpc;
9558     unsigned Shift = ARM_AM::getSORegShOp(Inst.getOperand(2).getImm());
9559     unsigned Amount = ARM_AM::getSORegOffset(Inst.getOperand(2).getImm());
9560     bool isMov = false;
9561     // MOV rd, rm, LSL #0 is actually a MOV instruction
9562     if (Shift == ARM_AM::lsl && Amount == 0) {
9563       isMov = true;
9564       // The 16-bit encoding of MOV rd, rm, LSL #N is explicitly encoding T2 of
9565       // MOV (register) in the ARMv8-A and ARMv8-M manuals, and immediate 0 is
9566       // unpredictable in an IT block so the 32-bit encoding T3 has to be used
9567       // instead.
9568       if (inITBlock()) {
9569         isNarrow = false;
9570       }
9571       newOpc = isNarrow ? ARM::tMOVSr : ARM::t2MOVr;
9572     } else {
9573       switch(Shift) {
9574       default: llvm_unreachable("unexpected opcode!");
9575       case ARM_AM::asr: newOpc = isNarrow ? ARM::tASRri : ARM::t2ASRri; break;
9576       case ARM_AM::lsr: newOpc = isNarrow ? ARM::tLSRri : ARM::t2LSRri; break;
9577       case ARM_AM::lsl: newOpc = isNarrow ? ARM::tLSLri : ARM::t2LSLri; break;
9578       case ARM_AM::ror: newOpc = ARM::t2RORri; isNarrow = false; break;
9579       case ARM_AM::rrx: isNarrow = false; newOpc = ARM::t2RRX; break;
9580       }
9581     }
9582     if (Amount == 32) Amount = 0;
9583     TmpInst.setOpcode(newOpc);
9584     TmpInst.addOperand(Inst.getOperand(0)); // Rd
9585     if (isNarrow && !isMov)
9586       TmpInst.addOperand(MCOperand::createReg(
9587           Inst.getOpcode() == ARM::t2MOVSsi ? ARM::CPSR : 0));
9588     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9589     if (newOpc != ARM::t2RRX && !isMov)
9590       TmpInst.addOperand(MCOperand::createImm(Amount));
9591     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9592     TmpInst.addOperand(Inst.getOperand(4));
9593     if (!isNarrow)
9594       TmpInst.addOperand(MCOperand::createReg(
9595           Inst.getOpcode() == ARM::t2MOVSsi ? ARM::CPSR : 0));
9596     Inst = TmpInst;
9597     return true;
9598   }
9599   // Handle the ARM mode MOV complex aliases.
9600   case ARM::ASRr:
9601   case ARM::LSRr:
9602   case ARM::LSLr:
9603   case ARM::RORr: {
9604     ARM_AM::ShiftOpc ShiftTy;
9605     switch(Inst.getOpcode()) {
9606     default: llvm_unreachable("unexpected opcode!");
9607     case ARM::ASRr: ShiftTy = ARM_AM::asr; break;
9608     case ARM::LSRr: ShiftTy = ARM_AM::lsr; break;
9609     case ARM::LSLr: ShiftTy = ARM_AM::lsl; break;
9610     case ARM::RORr: ShiftTy = ARM_AM::ror; break;
9611     }
9612     unsigned Shifter = ARM_AM::getSORegOpc(ShiftTy, 0);
9613     MCInst TmpInst;
9614     TmpInst.setOpcode(ARM::MOVsr);
9615     TmpInst.addOperand(Inst.getOperand(0)); // Rd
9616     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9617     TmpInst.addOperand(Inst.getOperand(2)); // Rm
9618     TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
9619     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9620     TmpInst.addOperand(Inst.getOperand(4));
9621     TmpInst.addOperand(Inst.getOperand(5)); // cc_out
9622     Inst = TmpInst;
9623     return true;
9624   }
9625   case ARM::ASRi:
9626   case ARM::LSRi:
9627   case ARM::LSLi:
9628   case ARM::RORi: {
9629     ARM_AM::ShiftOpc ShiftTy;
9630     switch(Inst.getOpcode()) {
9631     default: llvm_unreachable("unexpected opcode!");
9632     case ARM::ASRi: ShiftTy = ARM_AM::asr; break;
9633     case ARM::LSRi: ShiftTy = ARM_AM::lsr; break;
9634     case ARM::LSLi: ShiftTy = ARM_AM::lsl; break;
9635     case ARM::RORi: ShiftTy = ARM_AM::ror; break;
9636     }
9637     // A shift by zero is a plain MOVr, not a MOVsi.
9638     unsigned Amt = Inst.getOperand(2).getImm();
9639     unsigned Opc = Amt == 0 ? ARM::MOVr : ARM::MOVsi;
9640     // A shift by 32 should be encoded as 0 when permitted
9641     if (Amt == 32 && (ShiftTy == ARM_AM::lsr || ShiftTy == ARM_AM::asr))
9642       Amt = 0;
9643     unsigned Shifter = ARM_AM::getSORegOpc(ShiftTy, Amt);
9644     MCInst TmpInst;
9645     TmpInst.setOpcode(Opc);
9646     TmpInst.addOperand(Inst.getOperand(0)); // Rd
9647     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9648     if (Opc == ARM::MOVsi)
9649       TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
9650     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9651     TmpInst.addOperand(Inst.getOperand(4));
9652     TmpInst.addOperand(Inst.getOperand(5)); // cc_out
9653     Inst = TmpInst;
9654     return true;
9655   }
9656   case ARM::RRXi: {
9657     unsigned Shifter = ARM_AM::getSORegOpc(ARM_AM::rrx, 0);
9658     MCInst TmpInst;
9659     TmpInst.setOpcode(ARM::MOVsi);
9660     TmpInst.addOperand(Inst.getOperand(0)); // Rd
9661     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9662     TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
9663     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
9664     TmpInst.addOperand(Inst.getOperand(3));
9665     TmpInst.addOperand(Inst.getOperand(4)); // cc_out
9666     Inst = TmpInst;
9667     return true;
9668   }
9669   case ARM::t2LDMIA_UPD: {
9670     // If this is a load of a single register, then we should use
9671     // a post-indexed LDR instruction instead, per the ARM ARM.
9672     if (Inst.getNumOperands() != 5)
9673       return false;
9674     MCInst TmpInst;
9675     TmpInst.setOpcode(ARM::t2LDR_POST);
9676     TmpInst.addOperand(Inst.getOperand(4)); // Rt
9677     TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
9678     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9679     TmpInst.addOperand(MCOperand::createImm(4));
9680     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
9681     TmpInst.addOperand(Inst.getOperand(3));
9682     Inst = TmpInst;
9683     return true;
9684   }
9685   case ARM::t2STMDB_UPD: {
9686     // If this is a store of a single register, then we should use
9687     // a pre-indexed STR instruction instead, per the ARM ARM.
9688     if (Inst.getNumOperands() != 5)
9689       return false;
9690     MCInst TmpInst;
9691     TmpInst.setOpcode(ARM::t2STR_PRE);
9692     TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
9693     TmpInst.addOperand(Inst.getOperand(4)); // Rt
9694     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9695     TmpInst.addOperand(MCOperand::createImm(-4));
9696     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
9697     TmpInst.addOperand(Inst.getOperand(3));
9698     Inst = TmpInst;
9699     return true;
9700   }
9701   case ARM::LDMIA_UPD:
9702     // If this is a load of a single register via a 'pop', then we should use
9703     // a post-indexed LDR instruction instead, per the ARM ARM.
9704     if (static_cast<ARMOperand &>(*Operands[0]).getToken() == "pop" &&
9705         Inst.getNumOperands() == 5) {
9706       MCInst TmpInst;
9707       TmpInst.setOpcode(ARM::LDR_POST_IMM);
9708       TmpInst.addOperand(Inst.getOperand(4)); // Rt
9709       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
9710       TmpInst.addOperand(Inst.getOperand(1)); // Rn
9711       TmpInst.addOperand(MCOperand::createReg(0));  // am2offset
9712       TmpInst.addOperand(MCOperand::createImm(4));
9713       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
9714       TmpInst.addOperand(Inst.getOperand(3));
9715       Inst = TmpInst;
9716       return true;
9717     }
9718     break;
9719   case ARM::STMDB_UPD:
9720     // If this is a store of a single register via a 'push', then we should use
9721     // a pre-indexed STR instruction instead, per the ARM ARM.
9722     if (static_cast<ARMOperand &>(*Operands[0]).getToken() == "push" &&
9723         Inst.getNumOperands() == 5) {
9724       MCInst TmpInst;
9725       TmpInst.setOpcode(ARM::STR_PRE_IMM);
9726       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
9727       TmpInst.addOperand(Inst.getOperand(4)); // Rt
9728       TmpInst.addOperand(Inst.getOperand(1)); // addrmode_imm12
9729       TmpInst.addOperand(MCOperand::createImm(-4));
9730       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
9731       TmpInst.addOperand(Inst.getOperand(3));
9732       Inst = TmpInst;
9733     }
9734     break;
9735   case ARM::t2ADDri12:
9736     // If the immediate fits for encoding T3 (t2ADDri) and the generic "add"
9737     // mnemonic was used (not "addw"), encoding T3 is preferred.
9738     if (static_cast<ARMOperand &>(*Operands[0]).getToken() != "add" ||
9739         ARM_AM::getT2SOImmVal(Inst.getOperand(2).getImm()) == -1)
9740       break;
9741     Inst.setOpcode(ARM::t2ADDri);
9742     Inst.addOperand(MCOperand::createReg(0)); // cc_out
9743     break;
9744   case ARM::t2SUBri12:
9745     // If the immediate fits for encoding T3 (t2SUBri) and the generic "sub"
9746     // mnemonic was used (not "subw"), encoding T3 is preferred.
9747     if (static_cast<ARMOperand &>(*Operands[0]).getToken() != "sub" ||
9748         ARM_AM::getT2SOImmVal(Inst.getOperand(2).getImm()) == -1)
9749       break;
9750     Inst.setOpcode(ARM::t2SUBri);
9751     Inst.addOperand(MCOperand::createReg(0)); // cc_out
9752     break;
9753   case ARM::tADDi8:
9754     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
9755     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
9756     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
9757     // to encoding T1 if <Rd> is omitted."
9758     if ((unsigned)Inst.getOperand(3).getImm() < 8 && Operands.size() == 6) {
9759       Inst.setOpcode(ARM::tADDi3);
9760       return true;
9761     }
9762     break;
9763   case ARM::tSUBi8:
9764     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
9765     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
9766     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
9767     // to encoding T1 if <Rd> is omitted."
9768     if ((unsigned)Inst.getOperand(3).getImm() < 8 && Operands.size() == 6) {
9769       Inst.setOpcode(ARM::tSUBi3);
9770       return true;
9771     }
9772     break;
9773   case ARM::t2ADDri:
9774   case ARM::t2SUBri: {
9775     // If the destination and first source operand are the same, and
9776     // the flags are compatible with the current IT status, use encoding T2
9777     // instead of T3. For compatibility with the system 'as'. Make sure the
9778     // wide encoding wasn't explicit.
9779     if (Inst.getOperand(0).getReg() != Inst.getOperand(1).getReg() ||
9780         !isARMLowRegister(Inst.getOperand(0).getReg()) ||
9781         (Inst.getOperand(2).isImm() &&
9782          (unsigned)Inst.getOperand(2).getImm() > 255) ||
9783         Inst.getOperand(5).getReg() != (inITBlock() ? 0 : ARM::CPSR) ||
9784         HasWideQualifier)
9785       break;
9786     MCInst TmpInst;
9787     TmpInst.setOpcode(Inst.getOpcode() == ARM::t2ADDri ?
9788                       ARM::tADDi8 : ARM::tSUBi8);
9789     TmpInst.addOperand(Inst.getOperand(0));
9790     TmpInst.addOperand(Inst.getOperand(5));
9791     TmpInst.addOperand(Inst.getOperand(0));
9792     TmpInst.addOperand(Inst.getOperand(2));
9793     TmpInst.addOperand(Inst.getOperand(3));
9794     TmpInst.addOperand(Inst.getOperand(4));
9795     Inst = TmpInst;
9796     return true;
9797   }
9798   case ARM::t2ADDrr: {
9799     // If the destination and first source operand are the same, and
9800     // there's no setting of the flags, use encoding T2 instead of T3.
9801     // Note that this is only for ADD, not SUB. This mirrors the system
9802     // 'as' behaviour.  Also take advantage of ADD being commutative.
9803     // Make sure the wide encoding wasn't explicit.
9804     bool Swap = false;
9805     auto DestReg = Inst.getOperand(0).getReg();
9806     bool Transform = DestReg == Inst.getOperand(1).getReg();
9807     if (!Transform && DestReg == Inst.getOperand(2).getReg()) {
9808       Transform = true;
9809       Swap = true;
9810     }
9811     if (!Transform ||
9812         Inst.getOperand(5).getReg() != 0 ||
9813         HasWideQualifier)
9814       break;
9815     MCInst TmpInst;
9816     TmpInst.setOpcode(ARM::tADDhirr);
9817     TmpInst.addOperand(Inst.getOperand(0));
9818     TmpInst.addOperand(Inst.getOperand(0));
9819     TmpInst.addOperand(Inst.getOperand(Swap ? 1 : 2));
9820     TmpInst.addOperand(Inst.getOperand(3));
9821     TmpInst.addOperand(Inst.getOperand(4));
9822     Inst = TmpInst;
9823     return true;
9824   }
9825   case ARM::tADDrSP:
9826     // If the non-SP source operand and the destination operand are not the
9827     // same, we need to use the 32-bit encoding if it's available.
9828     if (Inst.getOperand(0).getReg() != Inst.getOperand(2).getReg()) {
9829       Inst.setOpcode(ARM::t2ADDrr);
9830       Inst.addOperand(MCOperand::createReg(0)); // cc_out
9831       return true;
9832     }
9833     break;
9834   case ARM::tB:
9835     // A Thumb conditional branch outside of an IT block is a tBcc.
9836     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock()) {
9837       Inst.setOpcode(ARM::tBcc);
9838       return true;
9839     }
9840     break;
9841   case ARM::t2B:
9842     // A Thumb2 conditional branch outside of an IT block is a t2Bcc.
9843     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock()){
9844       Inst.setOpcode(ARM::t2Bcc);
9845       return true;
9846     }
9847     break;
9848   case ARM::t2Bcc:
9849     // If the conditional is AL or we're in an IT block, we really want t2B.
9850     if (Inst.getOperand(1).getImm() == ARMCC::AL || inITBlock()) {
9851       Inst.setOpcode(ARM::t2B);
9852       return true;
9853     }
9854     break;
9855   case ARM::tBcc:
9856     // If the conditional is AL, we really want tB.
9857     if (Inst.getOperand(1).getImm() == ARMCC::AL) {
9858       Inst.setOpcode(ARM::tB);
9859       return true;
9860     }
9861     break;
9862   case ARM::tLDMIA: {
9863     // If the register list contains any high registers, or if the writeback
9864     // doesn't match what tLDMIA can do, we need to use the 32-bit encoding
9865     // instead if we're in Thumb2. Otherwise, this should have generated
9866     // an error in validateInstruction().
9867     unsigned Rn = Inst.getOperand(0).getReg();
9868     bool hasWritebackToken =
9869         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
9870          static_cast<ARMOperand &>(*Operands[3]).getToken() == "!");
9871     bool listContainsBase;
9872     if (checkLowRegisterList(Inst, 3, Rn, 0, listContainsBase) ||
9873         (!listContainsBase && !hasWritebackToken) ||
9874         (listContainsBase && hasWritebackToken)) {
9875       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
9876       assert(isThumbTwo());
9877       Inst.setOpcode(hasWritebackToken ? ARM::t2LDMIA_UPD : ARM::t2LDMIA);
9878       // If we're switching to the updating version, we need to insert
9879       // the writeback tied operand.
9880       if (hasWritebackToken)
9881         Inst.insert(Inst.begin(),
9882                     MCOperand::createReg(Inst.getOperand(0).getReg()));
9883       return true;
9884     }
9885     break;
9886   }
9887   case ARM::tSTMIA_UPD: {
9888     // If the register list contains any high registers, we need to use
9889     // the 32-bit encoding instead if we're in Thumb2. Otherwise, this
9890     // should have generated an error in validateInstruction().
9891     unsigned Rn = Inst.getOperand(0).getReg();
9892     bool listContainsBase;
9893     if (checkLowRegisterList(Inst, 4, Rn, 0, listContainsBase)) {
9894       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
9895       assert(isThumbTwo());
9896       Inst.setOpcode(ARM::t2STMIA_UPD);
9897       return true;
9898     }
9899     break;
9900   }
9901   case ARM::tPOP: {
9902     bool listContainsBase;
9903     // If the register list contains any high registers, we need to use
9904     // the 32-bit encoding instead if we're in Thumb2. Otherwise, this
9905     // should have generated an error in validateInstruction().
9906     if (!checkLowRegisterList(Inst, 2, 0, ARM::PC, listContainsBase))
9907       return false;
9908     assert(isThumbTwo());
9909     Inst.setOpcode(ARM::t2LDMIA_UPD);
9910     // Add the base register and writeback operands.
9911     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
9912     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
9913     return true;
9914   }
9915   case ARM::tPUSH: {
9916     bool listContainsBase;
9917     if (!checkLowRegisterList(Inst, 2, 0, ARM::LR, listContainsBase))
9918       return false;
9919     assert(isThumbTwo());
9920     Inst.setOpcode(ARM::t2STMDB_UPD);
9921     // Add the base register and writeback operands.
9922     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
9923     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
9924     return true;
9925   }
9926   case ARM::t2MOVi:
9927     // If we can use the 16-bit encoding and the user didn't explicitly
9928     // request the 32-bit variant, transform it here.
9929     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
9930         (Inst.getOperand(1).isImm() &&
9931          (unsigned)Inst.getOperand(1).getImm() <= 255) &&
9932         Inst.getOperand(4).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
9933         !HasWideQualifier) {
9934       // The operands aren't in the same order for tMOVi8...
9935       MCInst TmpInst;
9936       TmpInst.setOpcode(ARM::tMOVi8);
9937       TmpInst.addOperand(Inst.getOperand(0));
9938       TmpInst.addOperand(Inst.getOperand(4));
9939       TmpInst.addOperand(Inst.getOperand(1));
9940       TmpInst.addOperand(Inst.getOperand(2));
9941       TmpInst.addOperand(Inst.getOperand(3));
9942       Inst = TmpInst;
9943       return true;
9944     }
9945     break;
9946 
9947   case ARM::t2MOVr:
9948     // If we can use the 16-bit encoding and the user didn't explicitly
9949     // request the 32-bit variant, transform it here.
9950     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
9951         isARMLowRegister(Inst.getOperand(1).getReg()) &&
9952         Inst.getOperand(2).getImm() == ARMCC::AL &&
9953         Inst.getOperand(4).getReg() == ARM::CPSR &&
9954         !HasWideQualifier) {
9955       // The operands aren't the same for tMOV[S]r... (no cc_out)
9956       MCInst TmpInst;
9957       TmpInst.setOpcode(Inst.getOperand(4).getReg() ? ARM::tMOVSr : ARM::tMOVr);
9958       TmpInst.addOperand(Inst.getOperand(0));
9959       TmpInst.addOperand(Inst.getOperand(1));
9960       TmpInst.addOperand(Inst.getOperand(2));
9961       TmpInst.addOperand(Inst.getOperand(3));
9962       Inst = TmpInst;
9963       return true;
9964     }
9965     break;
9966 
9967   case ARM::t2SXTH:
9968   case ARM::t2SXTB:
9969   case ARM::t2UXTH:
9970   case ARM::t2UXTB:
9971     // If we can use the 16-bit encoding and the user didn't explicitly
9972     // request the 32-bit variant, transform it here.
9973     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
9974         isARMLowRegister(Inst.getOperand(1).getReg()) &&
9975         Inst.getOperand(2).getImm() == 0 &&
9976         !HasWideQualifier) {
9977       unsigned NewOpc;
9978       switch (Inst.getOpcode()) {
9979       default: llvm_unreachable("Illegal opcode!");
9980       case ARM::t2SXTH: NewOpc = ARM::tSXTH; break;
9981       case ARM::t2SXTB: NewOpc = ARM::tSXTB; break;
9982       case ARM::t2UXTH: NewOpc = ARM::tUXTH; break;
9983       case ARM::t2UXTB: NewOpc = ARM::tUXTB; break;
9984       }
9985       // The operands aren't the same for thumb1 (no rotate operand).
9986       MCInst TmpInst;
9987       TmpInst.setOpcode(NewOpc);
9988       TmpInst.addOperand(Inst.getOperand(0));
9989       TmpInst.addOperand(Inst.getOperand(1));
9990       TmpInst.addOperand(Inst.getOperand(3));
9991       TmpInst.addOperand(Inst.getOperand(4));
9992       Inst = TmpInst;
9993       return true;
9994     }
9995     break;
9996 
9997   case ARM::MOVsi: {
9998     ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(Inst.getOperand(2).getImm());
9999     // rrx shifts and asr/lsr of #32 is encoded as 0
10000     if (SOpc == ARM_AM::rrx || SOpc == ARM_AM::asr || SOpc == ARM_AM::lsr)
10001       return false;
10002     if (ARM_AM::getSORegOffset(Inst.getOperand(2).getImm()) == 0) {
10003       // Shifting by zero is accepted as a vanilla 'MOVr'
10004       MCInst TmpInst;
10005       TmpInst.setOpcode(ARM::MOVr);
10006       TmpInst.addOperand(Inst.getOperand(0));
10007       TmpInst.addOperand(Inst.getOperand(1));
10008       TmpInst.addOperand(Inst.getOperand(3));
10009       TmpInst.addOperand(Inst.getOperand(4));
10010       TmpInst.addOperand(Inst.getOperand(5));
10011       Inst = TmpInst;
10012       return true;
10013     }
10014     return false;
10015   }
10016   case ARM::ANDrsi:
10017   case ARM::ORRrsi:
10018   case ARM::EORrsi:
10019   case ARM::BICrsi:
10020   case ARM::SUBrsi:
10021   case ARM::ADDrsi: {
10022     unsigned newOpc;
10023     ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(Inst.getOperand(3).getImm());
10024     if (SOpc == ARM_AM::rrx) return false;
10025     switch (Inst.getOpcode()) {
10026     default: llvm_unreachable("unexpected opcode!");
10027     case ARM::ANDrsi: newOpc = ARM::ANDrr; break;
10028     case ARM::ORRrsi: newOpc = ARM::ORRrr; break;
10029     case ARM::EORrsi: newOpc = ARM::EORrr; break;
10030     case ARM::BICrsi: newOpc = ARM::BICrr; break;
10031     case ARM::SUBrsi: newOpc = ARM::SUBrr; break;
10032     case ARM::ADDrsi: newOpc = ARM::ADDrr; break;
10033     }
10034     // If the shift is by zero, use the non-shifted instruction definition.
10035     // The exception is for right shifts, where 0 == 32
10036     if (ARM_AM::getSORegOffset(Inst.getOperand(3).getImm()) == 0 &&
10037         !(SOpc == ARM_AM::lsr || SOpc == ARM_AM::asr)) {
10038       MCInst TmpInst;
10039       TmpInst.setOpcode(newOpc);
10040       TmpInst.addOperand(Inst.getOperand(0));
10041       TmpInst.addOperand(Inst.getOperand(1));
10042       TmpInst.addOperand(Inst.getOperand(2));
10043       TmpInst.addOperand(Inst.getOperand(4));
10044       TmpInst.addOperand(Inst.getOperand(5));
10045       TmpInst.addOperand(Inst.getOperand(6));
10046       Inst = TmpInst;
10047       return true;
10048     }
10049     return false;
10050   }
10051   case ARM::ITasm:
10052   case ARM::t2IT: {
10053     // Set up the IT block state according to the IT instruction we just
10054     // matched.
10055     assert(!inITBlock() && "nested IT blocks?!");
10056     startExplicitITBlock(ARMCC::CondCodes(Inst.getOperand(0).getImm()),
10057                          Inst.getOperand(1).getImm());
10058     break;
10059   }
10060   case ARM::t2LSLrr:
10061   case ARM::t2LSRrr:
10062   case ARM::t2ASRrr:
10063   case ARM::t2SBCrr:
10064   case ARM::t2RORrr:
10065   case ARM::t2BICrr:
10066     // Assemblers should use the narrow encodings of these instructions when permissible.
10067     if ((isARMLowRegister(Inst.getOperand(1).getReg()) &&
10068          isARMLowRegister(Inst.getOperand(2).getReg())) &&
10069         Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() &&
10070         Inst.getOperand(5).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
10071         !HasWideQualifier) {
10072       unsigned NewOpc;
10073       switch (Inst.getOpcode()) {
10074         default: llvm_unreachable("unexpected opcode");
10075         case ARM::t2LSLrr: NewOpc = ARM::tLSLrr; break;
10076         case ARM::t2LSRrr: NewOpc = ARM::tLSRrr; break;
10077         case ARM::t2ASRrr: NewOpc = ARM::tASRrr; break;
10078         case ARM::t2SBCrr: NewOpc = ARM::tSBC; break;
10079         case ARM::t2RORrr: NewOpc = ARM::tROR; break;
10080         case ARM::t2BICrr: NewOpc = ARM::tBIC; break;
10081       }
10082       MCInst TmpInst;
10083       TmpInst.setOpcode(NewOpc);
10084       TmpInst.addOperand(Inst.getOperand(0));
10085       TmpInst.addOperand(Inst.getOperand(5));
10086       TmpInst.addOperand(Inst.getOperand(1));
10087       TmpInst.addOperand(Inst.getOperand(2));
10088       TmpInst.addOperand(Inst.getOperand(3));
10089       TmpInst.addOperand(Inst.getOperand(4));
10090       Inst = TmpInst;
10091       return true;
10092     }
10093     return false;
10094 
10095   case ARM::t2ANDrr:
10096   case ARM::t2EORrr:
10097   case ARM::t2ADCrr:
10098   case ARM::t2ORRrr:
10099     // Assemblers should use the narrow encodings of these instructions when permissible.
10100     // These instructions are special in that they are commutable, so shorter encodings
10101     // are available more often.
10102     if ((isARMLowRegister(Inst.getOperand(1).getReg()) &&
10103          isARMLowRegister(Inst.getOperand(2).getReg())) &&
10104         (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() ||
10105          Inst.getOperand(0).getReg() == Inst.getOperand(2).getReg()) &&
10106         Inst.getOperand(5).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
10107         !HasWideQualifier) {
10108       unsigned NewOpc;
10109       switch (Inst.getOpcode()) {
10110         default: llvm_unreachable("unexpected opcode");
10111         case ARM::t2ADCrr: NewOpc = ARM::tADC; break;
10112         case ARM::t2ANDrr: NewOpc = ARM::tAND; break;
10113         case ARM::t2EORrr: NewOpc = ARM::tEOR; break;
10114         case ARM::t2ORRrr: NewOpc = ARM::tORR; break;
10115       }
10116       MCInst TmpInst;
10117       TmpInst.setOpcode(NewOpc);
10118       TmpInst.addOperand(Inst.getOperand(0));
10119       TmpInst.addOperand(Inst.getOperand(5));
10120       if (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg()) {
10121         TmpInst.addOperand(Inst.getOperand(1));
10122         TmpInst.addOperand(Inst.getOperand(2));
10123       } else {
10124         TmpInst.addOperand(Inst.getOperand(2));
10125         TmpInst.addOperand(Inst.getOperand(1));
10126       }
10127       TmpInst.addOperand(Inst.getOperand(3));
10128       TmpInst.addOperand(Inst.getOperand(4));
10129       Inst = TmpInst;
10130       return true;
10131     }
10132     return false;
10133   case ARM::MVE_VPST:
10134   case ARM::MVE_VPTv16i8:
10135   case ARM::MVE_VPTv8i16:
10136   case ARM::MVE_VPTv4i32:
10137   case ARM::MVE_VPTv16u8:
10138   case ARM::MVE_VPTv8u16:
10139   case ARM::MVE_VPTv4u32:
10140   case ARM::MVE_VPTv16s8:
10141   case ARM::MVE_VPTv8s16:
10142   case ARM::MVE_VPTv4s32:
10143   case ARM::MVE_VPTv4f32:
10144   case ARM::MVE_VPTv8f16:
10145   case ARM::MVE_VPTv16i8r:
10146   case ARM::MVE_VPTv8i16r:
10147   case ARM::MVE_VPTv4i32r:
10148   case ARM::MVE_VPTv16u8r:
10149   case ARM::MVE_VPTv8u16r:
10150   case ARM::MVE_VPTv4u32r:
10151   case ARM::MVE_VPTv16s8r:
10152   case ARM::MVE_VPTv8s16r:
10153   case ARM::MVE_VPTv4s32r:
10154   case ARM::MVE_VPTv4f32r:
10155   case ARM::MVE_VPTv8f16r: {
10156     assert(!inVPTBlock() && "Nested VPT blocks are not allowed");
10157     MCOperand &MO = Inst.getOperand(0);
10158     VPTState.Mask = MO.getImm();
10159     VPTState.CurPosition = 0;
10160     break;
10161   }
10162   }
10163   return false;
10164 }
10165 
10166 unsigned ARMAsmParser::checkTargetMatchPredicate(MCInst &Inst) {
10167   // 16-bit thumb arithmetic instructions either require or preclude the 'S'
10168   // suffix depending on whether they're in an IT block or not.
10169   unsigned Opc = Inst.getOpcode();
10170   const MCInstrDesc &MCID = MII.get(Opc);
10171   if (MCID.TSFlags & ARMII::ThumbArithFlagSetting) {
10172     assert(MCID.hasOptionalDef() &&
10173            "optionally flag setting instruction missing optional def operand");
10174     assert(MCID.NumOperands == Inst.getNumOperands() &&
10175            "operand count mismatch!");
10176     // Find the optional-def operand (cc_out).
10177     unsigned OpNo;
10178     for (OpNo = 0;
10179          !MCID.OpInfo[OpNo].isOptionalDef() && OpNo < MCID.NumOperands;
10180          ++OpNo)
10181       ;
10182     // If we're parsing Thumb1, reject it completely.
10183     if (isThumbOne() && Inst.getOperand(OpNo).getReg() != ARM::CPSR)
10184       return Match_RequiresFlagSetting;
10185     // If we're parsing Thumb2, which form is legal depends on whether we're
10186     // in an IT block.
10187     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() != ARM::CPSR &&
10188         !inITBlock())
10189       return Match_RequiresITBlock;
10190     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() == ARM::CPSR &&
10191         inITBlock())
10192       return Match_RequiresNotITBlock;
10193     // LSL with zero immediate is not allowed in an IT block
10194     if (Opc == ARM::tLSLri && Inst.getOperand(3).getImm() == 0 && inITBlock())
10195       return Match_RequiresNotITBlock;
10196   } else if (isThumbOne()) {
10197     // Some high-register supporting Thumb1 encodings only allow both registers
10198     // to be from r0-r7 when in Thumb2.
10199     if (Opc == ARM::tADDhirr && !hasV6MOps() &&
10200         isARMLowRegister(Inst.getOperand(1).getReg()) &&
10201         isARMLowRegister(Inst.getOperand(2).getReg()))
10202       return Match_RequiresThumb2;
10203     // Others only require ARMv6 or later.
10204     else if (Opc == ARM::tMOVr && !hasV6Ops() &&
10205              isARMLowRegister(Inst.getOperand(0).getReg()) &&
10206              isARMLowRegister(Inst.getOperand(1).getReg()))
10207       return Match_RequiresV6;
10208   }
10209 
10210   // Before ARMv8 the rules for when SP is allowed in t2MOVr are more complex
10211   // than the loop below can handle, so it uses the GPRnopc register class and
10212   // we do SP handling here.
10213   if (Opc == ARM::t2MOVr && !hasV8Ops())
10214   {
10215     // SP as both source and destination is not allowed
10216     if (Inst.getOperand(0).getReg() == ARM::SP &&
10217         Inst.getOperand(1).getReg() == ARM::SP)
10218       return Match_RequiresV8;
10219     // When flags-setting SP as either source or destination is not allowed
10220     if (Inst.getOperand(4).getReg() == ARM::CPSR &&
10221         (Inst.getOperand(0).getReg() == ARM::SP ||
10222          Inst.getOperand(1).getReg() == ARM::SP))
10223       return Match_RequiresV8;
10224   }
10225 
10226   switch (Inst.getOpcode()) {
10227   case ARM::VMRS:
10228   case ARM::VMSR:
10229   case ARM::VMRS_FPCXTS:
10230   case ARM::VMRS_FPCXTNS:
10231   case ARM::VMSR_FPCXTS:
10232   case ARM::VMSR_FPCXTNS:
10233   case ARM::VMRS_FPSCR_NZCVQC:
10234   case ARM::VMSR_FPSCR_NZCVQC:
10235   case ARM::FMSTAT:
10236   case ARM::VMRS_VPR:
10237   case ARM::VMRS_P0:
10238   case ARM::VMSR_VPR:
10239   case ARM::VMSR_P0:
10240     // Use of SP for VMRS/VMSR is only allowed in ARM mode with the exception of
10241     // ARMv8-A.
10242     if (Inst.getOperand(0).isReg() && Inst.getOperand(0).getReg() == ARM::SP &&
10243         (isThumb() && !hasV8Ops()))
10244       return Match_InvalidOperand;
10245     break;
10246   default:
10247     break;
10248   }
10249 
10250   for (unsigned I = 0; I < MCID.NumOperands; ++I)
10251     if (MCID.OpInfo[I].RegClass == ARM::rGPRRegClassID) {
10252       // rGPRRegClass excludes PC, and also excluded SP before ARMv8
10253       const auto &Op = Inst.getOperand(I);
10254       if (!Op.isReg()) {
10255         // This can happen in awkward cases with tied operands, e.g. a
10256         // writeback load/store with a complex addressing mode in
10257         // which there's an output operand corresponding to the
10258         // updated written-back base register: the Tablegen-generated
10259         // AsmMatcher will have written a placeholder operand to that
10260         // slot in the form of an immediate 0, because it can't
10261         // generate the register part of the complex addressing-mode
10262         // operand ahead of time.
10263         continue;
10264       }
10265 
10266       unsigned Reg = Op.getReg();
10267       if ((Reg == ARM::SP) && !hasV8Ops())
10268         return Match_RequiresV8;
10269       else if (Reg == ARM::PC)
10270         return Match_InvalidOperand;
10271     }
10272 
10273   return Match_Success;
10274 }
10275 
10276 namespace llvm {
10277 
10278 template <> inline bool IsCPSRDead<MCInst>(const MCInst *Instr) {
10279   return true; // In an assembly source, no need to second-guess
10280 }
10281 
10282 } // end namespace llvm
10283 
10284 // Returns true if Inst is unpredictable if it is in and IT block, but is not
10285 // the last instruction in the block.
10286 bool ARMAsmParser::isITBlockTerminator(MCInst &Inst) const {
10287   const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
10288 
10289   // All branch & call instructions terminate IT blocks with the exception of
10290   // SVC.
10291   if (MCID.isTerminator() || (MCID.isCall() && Inst.getOpcode() != ARM::tSVC) ||
10292       MCID.isReturn() || MCID.isBranch() || MCID.isIndirectBranch())
10293     return true;
10294 
10295   // Any arithmetic instruction which writes to the PC also terminates the IT
10296   // block.
10297   if (MCID.hasDefOfPhysReg(Inst, ARM::PC, *MRI))
10298     return true;
10299 
10300   return false;
10301 }
10302 
10303 unsigned ARMAsmParser::MatchInstruction(OperandVector &Operands, MCInst &Inst,
10304                                           SmallVectorImpl<NearMissInfo> &NearMisses,
10305                                           bool MatchingInlineAsm,
10306                                           bool &EmitInITBlock,
10307                                           MCStreamer &Out) {
10308   // If we can't use an implicit IT block here, just match as normal.
10309   if (inExplicitITBlock() || !isThumbTwo() || !useImplicitITThumb())
10310     return MatchInstructionImpl(Operands, Inst, &NearMisses, MatchingInlineAsm);
10311 
10312   // Try to match the instruction in an extension of the current IT block (if
10313   // there is one).
10314   if (inImplicitITBlock()) {
10315     extendImplicitITBlock(ITState.Cond);
10316     if (MatchInstructionImpl(Operands, Inst, nullptr, MatchingInlineAsm) ==
10317             Match_Success) {
10318       // The match succeded, but we still have to check that the instruction is
10319       // valid in this implicit IT block.
10320       const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
10321       if (MCID.isPredicable()) {
10322         ARMCC::CondCodes InstCond =
10323             (ARMCC::CondCodes)Inst.getOperand(MCID.findFirstPredOperandIdx())
10324                 .getImm();
10325         ARMCC::CondCodes ITCond = currentITCond();
10326         if (InstCond == ITCond) {
10327           EmitInITBlock = true;
10328           return Match_Success;
10329         } else if (InstCond == ARMCC::getOppositeCondition(ITCond)) {
10330           invertCurrentITCondition();
10331           EmitInITBlock = true;
10332           return Match_Success;
10333         }
10334       }
10335     }
10336     rewindImplicitITPosition();
10337   }
10338 
10339   // Finish the current IT block, and try to match outside any IT block.
10340   flushPendingInstructions(Out);
10341   unsigned PlainMatchResult =
10342       MatchInstructionImpl(Operands, Inst, &NearMisses, MatchingInlineAsm);
10343   if (PlainMatchResult == Match_Success) {
10344     const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
10345     if (MCID.isPredicable()) {
10346       ARMCC::CondCodes InstCond =
10347           (ARMCC::CondCodes)Inst.getOperand(MCID.findFirstPredOperandIdx())
10348               .getImm();
10349       // Some forms of the branch instruction have their own condition code
10350       // fields, so can be conditionally executed without an IT block.
10351       if (Inst.getOpcode() == ARM::tBcc || Inst.getOpcode() == ARM::t2Bcc) {
10352         EmitInITBlock = false;
10353         return Match_Success;
10354       }
10355       if (InstCond == ARMCC::AL) {
10356         EmitInITBlock = false;
10357         return Match_Success;
10358       }
10359     } else {
10360       EmitInITBlock = false;
10361       return Match_Success;
10362     }
10363   }
10364 
10365   // Try to match in a new IT block. The matcher doesn't check the actual
10366   // condition, so we create an IT block with a dummy condition, and fix it up
10367   // once we know the actual condition.
10368   startImplicitITBlock();
10369   if (MatchInstructionImpl(Operands, Inst, nullptr, MatchingInlineAsm) ==
10370       Match_Success) {
10371     const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
10372     if (MCID.isPredicable()) {
10373       ITState.Cond =
10374           (ARMCC::CondCodes)Inst.getOperand(MCID.findFirstPredOperandIdx())
10375               .getImm();
10376       EmitInITBlock = true;
10377       return Match_Success;
10378     }
10379   }
10380   discardImplicitITBlock();
10381 
10382   // If none of these succeed, return the error we got when trying to match
10383   // outside any IT blocks.
10384   EmitInITBlock = false;
10385   return PlainMatchResult;
10386 }
10387 
10388 static std::string ARMMnemonicSpellCheck(StringRef S, const FeatureBitset &FBS,
10389                                          unsigned VariantID = 0);
10390 
10391 static const char *getSubtargetFeatureName(uint64_t Val);
10392 bool ARMAsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
10393                                            OperandVector &Operands,
10394                                            MCStreamer &Out, uint64_t &ErrorInfo,
10395                                            bool MatchingInlineAsm) {
10396   MCInst Inst;
10397   unsigned MatchResult;
10398   bool PendConditionalInstruction = false;
10399 
10400   SmallVector<NearMissInfo, 4> NearMisses;
10401   MatchResult = MatchInstruction(Operands, Inst, NearMisses, MatchingInlineAsm,
10402                                  PendConditionalInstruction, Out);
10403 
10404   switch (MatchResult) {
10405   case Match_Success:
10406     LLVM_DEBUG(dbgs() << "Parsed as: ";
10407                Inst.dump_pretty(dbgs(), MII.getName(Inst.getOpcode()));
10408                dbgs() << "\n");
10409 
10410     // Context sensitive operand constraints aren't handled by the matcher,
10411     // so check them here.
10412     if (validateInstruction(Inst, Operands)) {
10413       // Still progress the IT block, otherwise one wrong condition causes
10414       // nasty cascading errors.
10415       forwardITPosition();
10416       forwardVPTPosition();
10417       return true;
10418     }
10419 
10420     { // processInstruction() updates inITBlock state, we need to save it away
10421       bool wasInITBlock = inITBlock();
10422 
10423       // Some instructions need post-processing to, for example, tweak which
10424       // encoding is selected. Loop on it while changes happen so the
10425       // individual transformations can chain off each other. E.g.,
10426       // tPOP(r8)->t2LDMIA_UPD(sp,r8)->t2STR_POST(sp,r8)
10427       while (processInstruction(Inst, Operands, Out))
10428         LLVM_DEBUG(dbgs() << "Changed to: ";
10429                    Inst.dump_pretty(dbgs(), MII.getName(Inst.getOpcode()));
10430                    dbgs() << "\n");
10431 
10432       // Only after the instruction is fully processed, we can validate it
10433       if (wasInITBlock && hasV8Ops() && isThumb() &&
10434           !isV8EligibleForIT(&Inst)) {
10435         Warning(IDLoc, "deprecated instruction in IT block");
10436       }
10437     }
10438 
10439     // Only move forward at the very end so that everything in validate
10440     // and process gets a consistent answer about whether we're in an IT
10441     // block.
10442     forwardITPosition();
10443     forwardVPTPosition();
10444 
10445     // ITasm is an ARM mode pseudo-instruction that just sets the ITblock and
10446     // doesn't actually encode.
10447     if (Inst.getOpcode() == ARM::ITasm)
10448       return false;
10449 
10450     Inst.setLoc(IDLoc);
10451     if (PendConditionalInstruction) {
10452       PendingConditionalInsts.push_back(Inst);
10453       if (isITBlockFull() || isITBlockTerminator(Inst))
10454         flushPendingInstructions(Out);
10455     } else {
10456       Out.EmitInstruction(Inst, getSTI());
10457     }
10458     return false;
10459   case Match_NearMisses:
10460     ReportNearMisses(NearMisses, IDLoc, Operands);
10461     return true;
10462   case Match_MnemonicFail: {
10463     FeatureBitset FBS = ComputeAvailableFeatures(getSTI().getFeatureBits());
10464     std::string Suggestion = ARMMnemonicSpellCheck(
10465       ((ARMOperand &)*Operands[0]).getToken(), FBS);
10466     return Error(IDLoc, "invalid instruction" + Suggestion,
10467                  ((ARMOperand &)*Operands[0]).getLocRange());
10468   }
10469   }
10470 
10471   llvm_unreachable("Implement any new match types added!");
10472 }
10473 
10474 /// parseDirective parses the arm specific directives
10475 bool ARMAsmParser::ParseDirective(AsmToken DirectiveID) {
10476   const MCObjectFileInfo::Environment Format =
10477     getContext().getObjectFileInfo()->getObjectFileType();
10478   bool IsMachO = Format == MCObjectFileInfo::IsMachO;
10479   bool IsCOFF = Format == MCObjectFileInfo::IsCOFF;
10480 
10481   StringRef IDVal = DirectiveID.getIdentifier();
10482   if (IDVal == ".word")
10483     parseLiteralValues(4, DirectiveID.getLoc());
10484   else if (IDVal == ".short" || IDVal == ".hword")
10485     parseLiteralValues(2, DirectiveID.getLoc());
10486   else if (IDVal == ".thumb")
10487     parseDirectiveThumb(DirectiveID.getLoc());
10488   else if (IDVal == ".arm")
10489     parseDirectiveARM(DirectiveID.getLoc());
10490   else if (IDVal == ".thumb_func")
10491     parseDirectiveThumbFunc(DirectiveID.getLoc());
10492   else if (IDVal == ".code")
10493     parseDirectiveCode(DirectiveID.getLoc());
10494   else if (IDVal == ".syntax")
10495     parseDirectiveSyntax(DirectiveID.getLoc());
10496   else if (IDVal == ".unreq")
10497     parseDirectiveUnreq(DirectiveID.getLoc());
10498   else if (IDVal == ".fnend")
10499     parseDirectiveFnEnd(DirectiveID.getLoc());
10500   else if (IDVal == ".cantunwind")
10501     parseDirectiveCantUnwind(DirectiveID.getLoc());
10502   else if (IDVal == ".personality")
10503     parseDirectivePersonality(DirectiveID.getLoc());
10504   else if (IDVal == ".handlerdata")
10505     parseDirectiveHandlerData(DirectiveID.getLoc());
10506   else if (IDVal == ".setfp")
10507     parseDirectiveSetFP(DirectiveID.getLoc());
10508   else if (IDVal == ".pad")
10509     parseDirectivePad(DirectiveID.getLoc());
10510   else if (IDVal == ".save")
10511     parseDirectiveRegSave(DirectiveID.getLoc(), false);
10512   else if (IDVal == ".vsave")
10513     parseDirectiveRegSave(DirectiveID.getLoc(), true);
10514   else if (IDVal == ".ltorg" || IDVal == ".pool")
10515     parseDirectiveLtorg(DirectiveID.getLoc());
10516   else if (IDVal == ".even")
10517     parseDirectiveEven(DirectiveID.getLoc());
10518   else if (IDVal == ".personalityindex")
10519     parseDirectivePersonalityIndex(DirectiveID.getLoc());
10520   else if (IDVal == ".unwind_raw")
10521     parseDirectiveUnwindRaw(DirectiveID.getLoc());
10522   else if (IDVal == ".movsp")
10523     parseDirectiveMovSP(DirectiveID.getLoc());
10524   else if (IDVal == ".arch_extension")
10525     parseDirectiveArchExtension(DirectiveID.getLoc());
10526   else if (IDVal == ".align")
10527     return parseDirectiveAlign(DirectiveID.getLoc()); // Use Generic on failure.
10528   else if (IDVal == ".thumb_set")
10529     parseDirectiveThumbSet(DirectiveID.getLoc());
10530   else if (IDVal == ".inst")
10531     parseDirectiveInst(DirectiveID.getLoc());
10532   else if (IDVal == ".inst.n")
10533     parseDirectiveInst(DirectiveID.getLoc(), 'n');
10534   else if (IDVal == ".inst.w")
10535     parseDirectiveInst(DirectiveID.getLoc(), 'w');
10536   else if (!IsMachO && !IsCOFF) {
10537     if (IDVal == ".arch")
10538       parseDirectiveArch(DirectiveID.getLoc());
10539     else if (IDVal == ".cpu")
10540       parseDirectiveCPU(DirectiveID.getLoc());
10541     else if (IDVal == ".eabi_attribute")
10542       parseDirectiveEabiAttr(DirectiveID.getLoc());
10543     else if (IDVal == ".fpu")
10544       parseDirectiveFPU(DirectiveID.getLoc());
10545     else if (IDVal == ".fnstart")
10546       parseDirectiveFnStart(DirectiveID.getLoc());
10547     else if (IDVal == ".object_arch")
10548       parseDirectiveObjectArch(DirectiveID.getLoc());
10549     else if (IDVal == ".tlsdescseq")
10550       parseDirectiveTLSDescSeq(DirectiveID.getLoc());
10551     else
10552       return true;
10553   } else
10554     return true;
10555   return false;
10556 }
10557 
10558 /// parseLiteralValues
10559 ///  ::= .hword expression [, expression]*
10560 ///  ::= .short expression [, expression]*
10561 ///  ::= .word expression [, expression]*
10562 bool ARMAsmParser::parseLiteralValues(unsigned Size, SMLoc L) {
10563   auto parseOne = [&]() -> bool {
10564     const MCExpr *Value;
10565     if (getParser().parseExpression(Value))
10566       return true;
10567     getParser().getStreamer().EmitValue(Value, Size, L);
10568     return false;
10569   };
10570   return (parseMany(parseOne));
10571 }
10572 
10573 /// parseDirectiveThumb
10574 ///  ::= .thumb
10575 bool ARMAsmParser::parseDirectiveThumb(SMLoc L) {
10576   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive") ||
10577       check(!hasThumb(), L, "target does not support Thumb mode"))
10578     return true;
10579 
10580   if (!isThumb())
10581     SwitchMode();
10582 
10583   getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
10584   return false;
10585 }
10586 
10587 /// parseDirectiveARM
10588 ///  ::= .arm
10589 bool ARMAsmParser::parseDirectiveARM(SMLoc L) {
10590   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive") ||
10591       check(!hasARM(), L, "target does not support ARM mode"))
10592     return true;
10593 
10594   if (isThumb())
10595     SwitchMode();
10596   getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
10597   return false;
10598 }
10599 
10600 void ARMAsmParser::doBeforeLabelEmit(MCSymbol *Symbol) {
10601   // We need to flush the current implicit IT block on a label, because it is
10602   // not legal to branch into an IT block.
10603   flushPendingInstructions(getStreamer());
10604 }
10605 
10606 void ARMAsmParser::onLabelParsed(MCSymbol *Symbol) {
10607   if (NextSymbolIsThumb) {
10608     getParser().getStreamer().EmitThumbFunc(Symbol);
10609     NextSymbolIsThumb = false;
10610   }
10611 }
10612 
10613 /// parseDirectiveThumbFunc
10614 ///  ::= .thumbfunc symbol_name
10615 bool ARMAsmParser::parseDirectiveThumbFunc(SMLoc L) {
10616   MCAsmParser &Parser = getParser();
10617   const auto Format = getContext().getObjectFileInfo()->getObjectFileType();
10618   bool IsMachO = Format == MCObjectFileInfo::IsMachO;
10619 
10620   // Darwin asm has (optionally) function name after .thumb_func direction
10621   // ELF doesn't
10622 
10623   if (IsMachO) {
10624     if (Parser.getTok().is(AsmToken::Identifier) ||
10625         Parser.getTok().is(AsmToken::String)) {
10626       MCSymbol *Func = getParser().getContext().getOrCreateSymbol(
10627           Parser.getTok().getIdentifier());
10628       getParser().getStreamer().EmitThumbFunc(Func);
10629       Parser.Lex();
10630       if (parseToken(AsmToken::EndOfStatement,
10631                      "unexpected token in '.thumb_func' directive"))
10632         return true;
10633       return false;
10634     }
10635   }
10636 
10637   if (parseToken(AsmToken::EndOfStatement,
10638                  "unexpected token in '.thumb_func' directive"))
10639     return true;
10640 
10641   NextSymbolIsThumb = true;
10642   return false;
10643 }
10644 
10645 /// parseDirectiveSyntax
10646 ///  ::= .syntax unified | divided
10647 bool ARMAsmParser::parseDirectiveSyntax(SMLoc L) {
10648   MCAsmParser &Parser = getParser();
10649   const AsmToken &Tok = Parser.getTok();
10650   if (Tok.isNot(AsmToken::Identifier)) {
10651     Error(L, "unexpected token in .syntax directive");
10652     return false;
10653   }
10654 
10655   StringRef Mode = Tok.getString();
10656   Parser.Lex();
10657   if (check(Mode == "divided" || Mode == "DIVIDED", L,
10658             "'.syntax divided' arm assembly not supported") ||
10659       check(Mode != "unified" && Mode != "UNIFIED", L,
10660             "unrecognized syntax mode in .syntax directive") ||
10661       parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
10662     return true;
10663 
10664   // TODO tell the MC streamer the mode
10665   // getParser().getStreamer().Emit???();
10666   return false;
10667 }
10668 
10669 /// parseDirectiveCode
10670 ///  ::= .code 16 | 32
10671 bool ARMAsmParser::parseDirectiveCode(SMLoc L) {
10672   MCAsmParser &Parser = getParser();
10673   const AsmToken &Tok = Parser.getTok();
10674   if (Tok.isNot(AsmToken::Integer))
10675     return Error(L, "unexpected token in .code directive");
10676   int64_t Val = Parser.getTok().getIntVal();
10677   if (Val != 16 && Val != 32) {
10678     Error(L, "invalid operand to .code directive");
10679     return false;
10680   }
10681   Parser.Lex();
10682 
10683   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
10684     return true;
10685 
10686   if (Val == 16) {
10687     if (!hasThumb())
10688       return Error(L, "target does not support Thumb mode");
10689 
10690     if (!isThumb())
10691       SwitchMode();
10692     getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
10693   } else {
10694     if (!hasARM())
10695       return Error(L, "target does not support ARM mode");
10696 
10697     if (isThumb())
10698       SwitchMode();
10699     getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
10700   }
10701 
10702   return false;
10703 }
10704 
10705 /// parseDirectiveReq
10706 ///  ::= name .req registername
10707 bool ARMAsmParser::parseDirectiveReq(StringRef Name, SMLoc L) {
10708   MCAsmParser &Parser = getParser();
10709   Parser.Lex(); // Eat the '.req' token.
10710   unsigned Reg;
10711   SMLoc SRegLoc, ERegLoc;
10712   if (check(ParseRegister(Reg, SRegLoc, ERegLoc), SRegLoc,
10713             "register name expected") ||
10714       parseToken(AsmToken::EndOfStatement,
10715                  "unexpected input in .req directive."))
10716     return true;
10717 
10718   if (RegisterReqs.insert(std::make_pair(Name, Reg)).first->second != Reg)
10719     return Error(SRegLoc,
10720                  "redefinition of '" + Name + "' does not match original.");
10721 
10722   return false;
10723 }
10724 
10725 /// parseDirectiveUneq
10726 ///  ::= .unreq registername
10727 bool ARMAsmParser::parseDirectiveUnreq(SMLoc L) {
10728   MCAsmParser &Parser = getParser();
10729   if (Parser.getTok().isNot(AsmToken::Identifier))
10730     return Error(L, "unexpected input in .unreq directive.");
10731   RegisterReqs.erase(Parser.getTok().getIdentifier().lower());
10732   Parser.Lex(); // Eat the identifier.
10733   if (parseToken(AsmToken::EndOfStatement,
10734                  "unexpected input in '.unreq' directive"))
10735     return true;
10736   return false;
10737 }
10738 
10739 // After changing arch/CPU, try to put the ARM/Thumb mode back to what it was
10740 // before, if supported by the new target, or emit mapping symbols for the mode
10741 // switch.
10742 void ARMAsmParser::FixModeAfterArchChange(bool WasThumb, SMLoc Loc) {
10743   if (WasThumb != isThumb()) {
10744     if (WasThumb && hasThumb()) {
10745       // Stay in Thumb mode
10746       SwitchMode();
10747     } else if (!WasThumb && hasARM()) {
10748       // Stay in ARM mode
10749       SwitchMode();
10750     } else {
10751       // Mode switch forced, because the new arch doesn't support the old mode.
10752       getParser().getStreamer().EmitAssemblerFlag(isThumb() ? MCAF_Code16
10753                                                             : MCAF_Code32);
10754       // Warn about the implcit mode switch. GAS does not switch modes here,
10755       // but instead stays in the old mode, reporting an error on any following
10756       // instructions as the mode does not exist on the target.
10757       Warning(Loc, Twine("new target does not support ") +
10758                        (WasThumb ? "thumb" : "arm") + " mode, switching to " +
10759                        (!WasThumb ? "thumb" : "arm") + " mode");
10760     }
10761   }
10762 }
10763 
10764 /// parseDirectiveArch
10765 ///  ::= .arch token
10766 bool ARMAsmParser::parseDirectiveArch(SMLoc L) {
10767   StringRef Arch = getParser().parseStringToEndOfStatement().trim();
10768   ARM::ArchKind ID = ARM::parseArch(Arch);
10769 
10770   if (ID == ARM::ArchKind::INVALID)
10771     return Error(L, "Unknown arch name");
10772 
10773   bool WasThumb = isThumb();
10774   Triple T;
10775   MCSubtargetInfo &STI = copySTI();
10776   STI.setDefaultFeatures("", ("+" + ARM::getArchName(ID)).str());
10777   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
10778   FixModeAfterArchChange(WasThumb, L);
10779 
10780   getTargetStreamer().emitArch(ID);
10781   return false;
10782 }
10783 
10784 /// parseDirectiveEabiAttr
10785 ///  ::= .eabi_attribute int, int [, "str"]
10786 ///  ::= .eabi_attribute Tag_name, int [, "str"]
10787 bool ARMAsmParser::parseDirectiveEabiAttr(SMLoc L) {
10788   MCAsmParser &Parser = getParser();
10789   int64_t Tag;
10790   SMLoc TagLoc;
10791   TagLoc = Parser.getTok().getLoc();
10792   if (Parser.getTok().is(AsmToken::Identifier)) {
10793     StringRef Name = Parser.getTok().getIdentifier();
10794     Tag = ARMBuildAttrs::AttrTypeFromString(Name);
10795     if (Tag == -1) {
10796       Error(TagLoc, "attribute name not recognised: " + Name);
10797       return false;
10798     }
10799     Parser.Lex();
10800   } else {
10801     const MCExpr *AttrExpr;
10802 
10803     TagLoc = Parser.getTok().getLoc();
10804     if (Parser.parseExpression(AttrExpr))
10805       return true;
10806 
10807     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(AttrExpr);
10808     if (check(!CE, TagLoc, "expected numeric constant"))
10809       return true;
10810 
10811     Tag = CE->getValue();
10812   }
10813 
10814   if (Parser.parseToken(AsmToken::Comma, "comma expected"))
10815     return true;
10816 
10817   StringRef StringValue = "";
10818   bool IsStringValue = false;
10819 
10820   int64_t IntegerValue = 0;
10821   bool IsIntegerValue = false;
10822 
10823   if (Tag == ARMBuildAttrs::CPU_raw_name || Tag == ARMBuildAttrs::CPU_name)
10824     IsStringValue = true;
10825   else if (Tag == ARMBuildAttrs::compatibility) {
10826     IsStringValue = true;
10827     IsIntegerValue = true;
10828   } else if (Tag < 32 || Tag % 2 == 0)
10829     IsIntegerValue = true;
10830   else if (Tag % 2 == 1)
10831     IsStringValue = true;
10832   else
10833     llvm_unreachable("invalid tag type");
10834 
10835   if (IsIntegerValue) {
10836     const MCExpr *ValueExpr;
10837     SMLoc ValueExprLoc = Parser.getTok().getLoc();
10838     if (Parser.parseExpression(ValueExpr))
10839       return true;
10840 
10841     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ValueExpr);
10842     if (!CE)
10843       return Error(ValueExprLoc, "expected numeric constant");
10844     IntegerValue = CE->getValue();
10845   }
10846 
10847   if (Tag == ARMBuildAttrs::compatibility) {
10848     if (Parser.parseToken(AsmToken::Comma, "comma expected"))
10849       return true;
10850   }
10851 
10852   if (IsStringValue) {
10853     if (Parser.getTok().isNot(AsmToken::String))
10854       return Error(Parser.getTok().getLoc(), "bad string constant");
10855 
10856     StringValue = Parser.getTok().getStringContents();
10857     Parser.Lex();
10858   }
10859 
10860   if (Parser.parseToken(AsmToken::EndOfStatement,
10861                         "unexpected token in '.eabi_attribute' directive"))
10862     return true;
10863 
10864   if (IsIntegerValue && IsStringValue) {
10865     assert(Tag == ARMBuildAttrs::compatibility);
10866     getTargetStreamer().emitIntTextAttribute(Tag, IntegerValue, StringValue);
10867   } else if (IsIntegerValue)
10868     getTargetStreamer().emitAttribute(Tag, IntegerValue);
10869   else if (IsStringValue)
10870     getTargetStreamer().emitTextAttribute(Tag, StringValue);
10871   return false;
10872 }
10873 
10874 /// parseDirectiveCPU
10875 ///  ::= .cpu str
10876 bool ARMAsmParser::parseDirectiveCPU(SMLoc L) {
10877   StringRef CPU = getParser().parseStringToEndOfStatement().trim();
10878   getTargetStreamer().emitTextAttribute(ARMBuildAttrs::CPU_name, CPU);
10879 
10880   // FIXME: This is using table-gen data, but should be moved to
10881   // ARMTargetParser once that is table-gen'd.
10882   if (!getSTI().isCPUStringValid(CPU))
10883     return Error(L, "Unknown CPU name");
10884 
10885   bool WasThumb = isThumb();
10886   MCSubtargetInfo &STI = copySTI();
10887   STI.setDefaultFeatures(CPU, "");
10888   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
10889   FixModeAfterArchChange(WasThumb, L);
10890 
10891   return false;
10892 }
10893 
10894 /// parseDirectiveFPU
10895 ///  ::= .fpu str
10896 bool ARMAsmParser::parseDirectiveFPU(SMLoc L) {
10897   SMLoc FPUNameLoc = getTok().getLoc();
10898   StringRef FPU = getParser().parseStringToEndOfStatement().trim();
10899 
10900   unsigned ID = ARM::parseFPU(FPU);
10901   std::vector<StringRef> Features;
10902   if (!ARM::getFPUFeatures(ID, Features))
10903     return Error(FPUNameLoc, "Unknown FPU name");
10904 
10905   MCSubtargetInfo &STI = copySTI();
10906   for (auto Feature : Features)
10907     STI.ApplyFeatureFlag(Feature);
10908   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
10909 
10910   getTargetStreamer().emitFPU(ID);
10911   return false;
10912 }
10913 
10914 /// parseDirectiveFnStart
10915 ///  ::= .fnstart
10916 bool ARMAsmParser::parseDirectiveFnStart(SMLoc L) {
10917   if (parseToken(AsmToken::EndOfStatement,
10918                  "unexpected token in '.fnstart' directive"))
10919     return true;
10920 
10921   if (UC.hasFnStart()) {
10922     Error(L, ".fnstart starts before the end of previous one");
10923     UC.emitFnStartLocNotes();
10924     return true;
10925   }
10926 
10927   // Reset the unwind directives parser state
10928   UC.reset();
10929 
10930   getTargetStreamer().emitFnStart();
10931 
10932   UC.recordFnStart(L);
10933   return false;
10934 }
10935 
10936 /// parseDirectiveFnEnd
10937 ///  ::= .fnend
10938 bool ARMAsmParser::parseDirectiveFnEnd(SMLoc L) {
10939   if (parseToken(AsmToken::EndOfStatement,
10940                  "unexpected token in '.fnend' directive"))
10941     return true;
10942   // Check the ordering of unwind directives
10943   if (!UC.hasFnStart())
10944     return Error(L, ".fnstart must precede .fnend directive");
10945 
10946   // Reset the unwind directives parser state
10947   getTargetStreamer().emitFnEnd();
10948 
10949   UC.reset();
10950   return false;
10951 }
10952 
10953 /// parseDirectiveCantUnwind
10954 ///  ::= .cantunwind
10955 bool ARMAsmParser::parseDirectiveCantUnwind(SMLoc L) {
10956   if (parseToken(AsmToken::EndOfStatement,
10957                  "unexpected token in '.cantunwind' directive"))
10958     return true;
10959 
10960   UC.recordCantUnwind(L);
10961   // Check the ordering of unwind directives
10962   if (check(!UC.hasFnStart(), L, ".fnstart must precede .cantunwind directive"))
10963     return true;
10964 
10965   if (UC.hasHandlerData()) {
10966     Error(L, ".cantunwind can't be used with .handlerdata directive");
10967     UC.emitHandlerDataLocNotes();
10968     return true;
10969   }
10970   if (UC.hasPersonality()) {
10971     Error(L, ".cantunwind can't be used with .personality directive");
10972     UC.emitPersonalityLocNotes();
10973     return true;
10974   }
10975 
10976   getTargetStreamer().emitCantUnwind();
10977   return false;
10978 }
10979 
10980 /// parseDirectivePersonality
10981 ///  ::= .personality name
10982 bool ARMAsmParser::parseDirectivePersonality(SMLoc L) {
10983   MCAsmParser &Parser = getParser();
10984   bool HasExistingPersonality = UC.hasPersonality();
10985 
10986   // Parse the name of the personality routine
10987   if (Parser.getTok().isNot(AsmToken::Identifier))
10988     return Error(L, "unexpected input in .personality directive.");
10989   StringRef Name(Parser.getTok().getIdentifier());
10990   Parser.Lex();
10991 
10992   if (parseToken(AsmToken::EndOfStatement,
10993                  "unexpected token in '.personality' directive"))
10994     return true;
10995 
10996   UC.recordPersonality(L);
10997 
10998   // Check the ordering of unwind directives
10999   if (!UC.hasFnStart())
11000     return Error(L, ".fnstart must precede .personality directive");
11001   if (UC.cantUnwind()) {
11002     Error(L, ".personality can't be used with .cantunwind directive");
11003     UC.emitCantUnwindLocNotes();
11004     return true;
11005   }
11006   if (UC.hasHandlerData()) {
11007     Error(L, ".personality must precede .handlerdata directive");
11008     UC.emitHandlerDataLocNotes();
11009     return true;
11010   }
11011   if (HasExistingPersonality) {
11012     Error(L, "multiple personality directives");
11013     UC.emitPersonalityLocNotes();
11014     return true;
11015   }
11016 
11017   MCSymbol *PR = getParser().getContext().getOrCreateSymbol(Name);
11018   getTargetStreamer().emitPersonality(PR);
11019   return false;
11020 }
11021 
11022 /// parseDirectiveHandlerData
11023 ///  ::= .handlerdata
11024 bool ARMAsmParser::parseDirectiveHandlerData(SMLoc L) {
11025   if (parseToken(AsmToken::EndOfStatement,
11026                  "unexpected token in '.handlerdata' directive"))
11027     return true;
11028 
11029   UC.recordHandlerData(L);
11030   // Check the ordering of unwind directives
11031   if (!UC.hasFnStart())
11032     return Error(L, ".fnstart must precede .personality directive");
11033   if (UC.cantUnwind()) {
11034     Error(L, ".handlerdata can't be used with .cantunwind directive");
11035     UC.emitCantUnwindLocNotes();
11036     return true;
11037   }
11038 
11039   getTargetStreamer().emitHandlerData();
11040   return false;
11041 }
11042 
11043 /// parseDirectiveSetFP
11044 ///  ::= .setfp fpreg, spreg [, offset]
11045 bool ARMAsmParser::parseDirectiveSetFP(SMLoc L) {
11046   MCAsmParser &Parser = getParser();
11047   // Check the ordering of unwind directives
11048   if (check(!UC.hasFnStart(), L, ".fnstart must precede .setfp directive") ||
11049       check(UC.hasHandlerData(), L,
11050             ".setfp must precede .handlerdata directive"))
11051     return true;
11052 
11053   // Parse fpreg
11054   SMLoc FPRegLoc = Parser.getTok().getLoc();
11055   int FPReg = tryParseRegister();
11056 
11057   if (check(FPReg == -1, FPRegLoc, "frame pointer register expected") ||
11058       Parser.parseToken(AsmToken::Comma, "comma expected"))
11059     return true;
11060 
11061   // Parse spreg
11062   SMLoc SPRegLoc = Parser.getTok().getLoc();
11063   int SPReg = tryParseRegister();
11064   if (check(SPReg == -1, SPRegLoc, "stack pointer register expected") ||
11065       check(SPReg != ARM::SP && SPReg != UC.getFPReg(), SPRegLoc,
11066             "register should be either $sp or the latest fp register"))
11067     return true;
11068 
11069   // Update the frame pointer register
11070   UC.saveFPReg(FPReg);
11071 
11072   // Parse offset
11073   int64_t Offset = 0;
11074   if (Parser.parseOptionalToken(AsmToken::Comma)) {
11075     if (Parser.getTok().isNot(AsmToken::Hash) &&
11076         Parser.getTok().isNot(AsmToken::Dollar))
11077       return Error(Parser.getTok().getLoc(), "'#' expected");
11078     Parser.Lex(); // skip hash token.
11079 
11080     const MCExpr *OffsetExpr;
11081     SMLoc ExLoc = Parser.getTok().getLoc();
11082     SMLoc EndLoc;
11083     if (getParser().parseExpression(OffsetExpr, EndLoc))
11084       return Error(ExLoc, "malformed setfp offset");
11085     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
11086     if (check(!CE, ExLoc, "setfp offset must be an immediate"))
11087       return true;
11088     Offset = CE->getValue();
11089   }
11090 
11091   if (Parser.parseToken(AsmToken::EndOfStatement))
11092     return true;
11093 
11094   getTargetStreamer().emitSetFP(static_cast<unsigned>(FPReg),
11095                                 static_cast<unsigned>(SPReg), Offset);
11096   return false;
11097 }
11098 
11099 /// parseDirective
11100 ///  ::= .pad offset
11101 bool ARMAsmParser::parseDirectivePad(SMLoc L) {
11102   MCAsmParser &Parser = getParser();
11103   // Check the ordering of unwind directives
11104   if (!UC.hasFnStart())
11105     return Error(L, ".fnstart must precede .pad directive");
11106   if (UC.hasHandlerData())
11107     return Error(L, ".pad must precede .handlerdata directive");
11108 
11109   // Parse the offset
11110   if (Parser.getTok().isNot(AsmToken::Hash) &&
11111       Parser.getTok().isNot(AsmToken::Dollar))
11112     return Error(Parser.getTok().getLoc(), "'#' expected");
11113   Parser.Lex(); // skip hash token.
11114 
11115   const MCExpr *OffsetExpr;
11116   SMLoc ExLoc = Parser.getTok().getLoc();
11117   SMLoc EndLoc;
11118   if (getParser().parseExpression(OffsetExpr, EndLoc))
11119     return Error(ExLoc, "malformed pad offset");
11120   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
11121   if (!CE)
11122     return Error(ExLoc, "pad offset must be an immediate");
11123 
11124   if (parseToken(AsmToken::EndOfStatement,
11125                  "unexpected token in '.pad' directive"))
11126     return true;
11127 
11128   getTargetStreamer().emitPad(CE->getValue());
11129   return false;
11130 }
11131 
11132 /// parseDirectiveRegSave
11133 ///  ::= .save  { registers }
11134 ///  ::= .vsave { registers }
11135 bool ARMAsmParser::parseDirectiveRegSave(SMLoc L, bool IsVector) {
11136   // Check the ordering of unwind directives
11137   if (!UC.hasFnStart())
11138     return Error(L, ".fnstart must precede .save or .vsave directives");
11139   if (UC.hasHandlerData())
11140     return Error(L, ".save or .vsave must precede .handlerdata directive");
11141 
11142   // RAII object to make sure parsed operands are deleted.
11143   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> Operands;
11144 
11145   // Parse the register list
11146   if (parseRegisterList(Operands) ||
11147       parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
11148     return true;
11149   ARMOperand &Op = (ARMOperand &)*Operands[0];
11150   if (!IsVector && !Op.isRegList())
11151     return Error(L, ".save expects GPR registers");
11152   if (IsVector && !Op.isDPRRegList())
11153     return Error(L, ".vsave expects DPR registers");
11154 
11155   getTargetStreamer().emitRegSave(Op.getRegList(), IsVector);
11156   return false;
11157 }
11158 
11159 /// parseDirectiveInst
11160 ///  ::= .inst opcode [, ...]
11161 ///  ::= .inst.n opcode [, ...]
11162 ///  ::= .inst.w opcode [, ...]
11163 bool ARMAsmParser::parseDirectiveInst(SMLoc Loc, char Suffix) {
11164   int Width = 4;
11165 
11166   if (isThumb()) {
11167     switch (Suffix) {
11168     case 'n':
11169       Width = 2;
11170       break;
11171     case 'w':
11172       break;
11173     default:
11174       Width = 0;
11175       break;
11176     }
11177   } else {
11178     if (Suffix)
11179       return Error(Loc, "width suffixes are invalid in ARM mode");
11180   }
11181 
11182   auto parseOne = [&]() -> bool {
11183     const MCExpr *Expr;
11184     if (getParser().parseExpression(Expr))
11185       return true;
11186     const MCConstantExpr *Value = dyn_cast_or_null<MCConstantExpr>(Expr);
11187     if (!Value) {
11188       return Error(Loc, "expected constant expression");
11189     }
11190 
11191     char CurSuffix = Suffix;
11192     switch (Width) {
11193     case 2:
11194       if (Value->getValue() > 0xffff)
11195         return Error(Loc, "inst.n operand is too big, use inst.w instead");
11196       break;
11197     case 4:
11198       if (Value->getValue() > 0xffffffff)
11199         return Error(Loc, StringRef(Suffix ? "inst.w" : "inst") +
11200                               " operand is too big");
11201       break;
11202     case 0:
11203       // Thumb mode, no width indicated. Guess from the opcode, if possible.
11204       if (Value->getValue() < 0xe800)
11205         CurSuffix = 'n';
11206       else if (Value->getValue() >= 0xe8000000)
11207         CurSuffix = 'w';
11208       else
11209         return Error(Loc, "cannot determine Thumb instruction size, "
11210                           "use inst.n/inst.w instead");
11211       break;
11212     default:
11213       llvm_unreachable("only supported widths are 2 and 4");
11214     }
11215 
11216     getTargetStreamer().emitInst(Value->getValue(), CurSuffix);
11217     return false;
11218   };
11219 
11220   if (parseOptionalToken(AsmToken::EndOfStatement))
11221     return Error(Loc, "expected expression following directive");
11222   if (parseMany(parseOne))
11223     return true;
11224   return false;
11225 }
11226 
11227 /// parseDirectiveLtorg
11228 ///  ::= .ltorg | .pool
11229 bool ARMAsmParser::parseDirectiveLtorg(SMLoc L) {
11230   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
11231     return true;
11232   getTargetStreamer().emitCurrentConstantPool();
11233   return false;
11234 }
11235 
11236 bool ARMAsmParser::parseDirectiveEven(SMLoc L) {
11237   const MCSection *Section = getStreamer().getCurrentSectionOnly();
11238 
11239   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
11240     return true;
11241 
11242   if (!Section) {
11243     getStreamer().InitSections(false);
11244     Section = getStreamer().getCurrentSectionOnly();
11245   }
11246 
11247   assert(Section && "must have section to emit alignment");
11248   if (Section->UseCodeAlign())
11249     getStreamer().EmitCodeAlignment(2);
11250   else
11251     getStreamer().EmitValueToAlignment(2);
11252 
11253   return false;
11254 }
11255 
11256 /// parseDirectivePersonalityIndex
11257 ///   ::= .personalityindex index
11258 bool ARMAsmParser::parseDirectivePersonalityIndex(SMLoc L) {
11259   MCAsmParser &Parser = getParser();
11260   bool HasExistingPersonality = UC.hasPersonality();
11261 
11262   const MCExpr *IndexExpression;
11263   SMLoc IndexLoc = Parser.getTok().getLoc();
11264   if (Parser.parseExpression(IndexExpression) ||
11265       parseToken(AsmToken::EndOfStatement,
11266                  "unexpected token in '.personalityindex' directive")) {
11267     return true;
11268   }
11269 
11270   UC.recordPersonalityIndex(L);
11271 
11272   if (!UC.hasFnStart()) {
11273     return Error(L, ".fnstart must precede .personalityindex directive");
11274   }
11275   if (UC.cantUnwind()) {
11276     Error(L, ".personalityindex cannot be used with .cantunwind");
11277     UC.emitCantUnwindLocNotes();
11278     return true;
11279   }
11280   if (UC.hasHandlerData()) {
11281     Error(L, ".personalityindex must precede .handlerdata directive");
11282     UC.emitHandlerDataLocNotes();
11283     return true;
11284   }
11285   if (HasExistingPersonality) {
11286     Error(L, "multiple personality directives");
11287     UC.emitPersonalityLocNotes();
11288     return true;
11289   }
11290 
11291   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(IndexExpression);
11292   if (!CE)
11293     return Error(IndexLoc, "index must be a constant number");
11294   if (CE->getValue() < 0 || CE->getValue() >= ARM::EHABI::NUM_PERSONALITY_INDEX)
11295     return Error(IndexLoc,
11296                  "personality routine index should be in range [0-3]");
11297 
11298   getTargetStreamer().emitPersonalityIndex(CE->getValue());
11299   return false;
11300 }
11301 
11302 /// parseDirectiveUnwindRaw
11303 ///   ::= .unwind_raw offset, opcode [, opcode...]
11304 bool ARMAsmParser::parseDirectiveUnwindRaw(SMLoc L) {
11305   MCAsmParser &Parser = getParser();
11306   int64_t StackOffset;
11307   const MCExpr *OffsetExpr;
11308   SMLoc OffsetLoc = getLexer().getLoc();
11309 
11310   if (!UC.hasFnStart())
11311     return Error(L, ".fnstart must precede .unwind_raw directives");
11312   if (getParser().parseExpression(OffsetExpr))
11313     return Error(OffsetLoc, "expected expression");
11314 
11315   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
11316   if (!CE)
11317     return Error(OffsetLoc, "offset must be a constant");
11318 
11319   StackOffset = CE->getValue();
11320 
11321   if (Parser.parseToken(AsmToken::Comma, "expected comma"))
11322     return true;
11323 
11324   SmallVector<uint8_t, 16> Opcodes;
11325 
11326   auto parseOne = [&]() -> bool {
11327     const MCExpr *OE;
11328     SMLoc OpcodeLoc = getLexer().getLoc();
11329     if (check(getLexer().is(AsmToken::EndOfStatement) ||
11330                   Parser.parseExpression(OE),
11331               OpcodeLoc, "expected opcode expression"))
11332       return true;
11333     const MCConstantExpr *OC = dyn_cast<MCConstantExpr>(OE);
11334     if (!OC)
11335       return Error(OpcodeLoc, "opcode value must be a constant");
11336     const int64_t Opcode = OC->getValue();
11337     if (Opcode & ~0xff)
11338       return Error(OpcodeLoc, "invalid opcode");
11339     Opcodes.push_back(uint8_t(Opcode));
11340     return false;
11341   };
11342 
11343   // Must have at least 1 element
11344   SMLoc OpcodeLoc = getLexer().getLoc();
11345   if (parseOptionalToken(AsmToken::EndOfStatement))
11346     return Error(OpcodeLoc, "expected opcode expression");
11347   if (parseMany(parseOne))
11348     return true;
11349 
11350   getTargetStreamer().emitUnwindRaw(StackOffset, Opcodes);
11351   return false;
11352 }
11353 
11354 /// parseDirectiveTLSDescSeq
11355 ///   ::= .tlsdescseq tls-variable
11356 bool ARMAsmParser::parseDirectiveTLSDescSeq(SMLoc L) {
11357   MCAsmParser &Parser = getParser();
11358 
11359   if (getLexer().isNot(AsmToken::Identifier))
11360     return TokError("expected variable after '.tlsdescseq' directive");
11361 
11362   const MCSymbolRefExpr *SRE =
11363     MCSymbolRefExpr::create(Parser.getTok().getIdentifier(),
11364                             MCSymbolRefExpr::VK_ARM_TLSDESCSEQ, getContext());
11365   Lex();
11366 
11367   if (parseToken(AsmToken::EndOfStatement,
11368                  "unexpected token in '.tlsdescseq' directive"))
11369     return true;
11370 
11371   getTargetStreamer().AnnotateTLSDescriptorSequence(SRE);
11372   return false;
11373 }
11374 
11375 /// parseDirectiveMovSP
11376 ///  ::= .movsp reg [, #offset]
11377 bool ARMAsmParser::parseDirectiveMovSP(SMLoc L) {
11378   MCAsmParser &Parser = getParser();
11379   if (!UC.hasFnStart())
11380     return Error(L, ".fnstart must precede .movsp directives");
11381   if (UC.getFPReg() != ARM::SP)
11382     return Error(L, "unexpected .movsp directive");
11383 
11384   SMLoc SPRegLoc = Parser.getTok().getLoc();
11385   int SPReg = tryParseRegister();
11386   if (SPReg == -1)
11387     return Error(SPRegLoc, "register expected");
11388   if (SPReg == ARM::SP || SPReg == ARM::PC)
11389     return Error(SPRegLoc, "sp and pc are not permitted in .movsp directive");
11390 
11391   int64_t Offset = 0;
11392   if (Parser.parseOptionalToken(AsmToken::Comma)) {
11393     if (Parser.parseToken(AsmToken::Hash, "expected #constant"))
11394       return true;
11395 
11396     const MCExpr *OffsetExpr;
11397     SMLoc OffsetLoc = Parser.getTok().getLoc();
11398 
11399     if (Parser.parseExpression(OffsetExpr))
11400       return Error(OffsetLoc, "malformed offset expression");
11401 
11402     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
11403     if (!CE)
11404       return Error(OffsetLoc, "offset must be an immediate constant");
11405 
11406     Offset = CE->getValue();
11407   }
11408 
11409   if (parseToken(AsmToken::EndOfStatement,
11410                  "unexpected token in '.movsp' directive"))
11411     return true;
11412 
11413   getTargetStreamer().emitMovSP(SPReg, Offset);
11414   UC.saveFPReg(SPReg);
11415 
11416   return false;
11417 }
11418 
11419 /// parseDirectiveObjectArch
11420 ///   ::= .object_arch name
11421 bool ARMAsmParser::parseDirectiveObjectArch(SMLoc L) {
11422   MCAsmParser &Parser = getParser();
11423   if (getLexer().isNot(AsmToken::Identifier))
11424     return Error(getLexer().getLoc(), "unexpected token");
11425 
11426   StringRef Arch = Parser.getTok().getString();
11427   SMLoc ArchLoc = Parser.getTok().getLoc();
11428   Lex();
11429 
11430   ARM::ArchKind ID = ARM::parseArch(Arch);
11431 
11432   if (ID == ARM::ArchKind::INVALID)
11433     return Error(ArchLoc, "unknown architecture '" + Arch + "'");
11434   if (parseToken(AsmToken::EndOfStatement))
11435     return true;
11436 
11437   getTargetStreamer().emitObjectArch(ID);
11438   return false;
11439 }
11440 
11441 /// parseDirectiveAlign
11442 ///   ::= .align
11443 bool ARMAsmParser::parseDirectiveAlign(SMLoc L) {
11444   // NOTE: if this is not the end of the statement, fall back to the target
11445   // agnostic handling for this directive which will correctly handle this.
11446   if (parseOptionalToken(AsmToken::EndOfStatement)) {
11447     // '.align' is target specifically handled to mean 2**2 byte alignment.
11448     const MCSection *Section = getStreamer().getCurrentSectionOnly();
11449     assert(Section && "must have section to emit alignment");
11450     if (Section->UseCodeAlign())
11451       getStreamer().EmitCodeAlignment(4, 0);
11452     else
11453       getStreamer().EmitValueToAlignment(4, 0, 1, 0);
11454     return false;
11455   }
11456   return true;
11457 }
11458 
11459 /// parseDirectiveThumbSet
11460 ///  ::= .thumb_set name, value
11461 bool ARMAsmParser::parseDirectiveThumbSet(SMLoc L) {
11462   MCAsmParser &Parser = getParser();
11463 
11464   StringRef Name;
11465   if (check(Parser.parseIdentifier(Name),
11466             "expected identifier after '.thumb_set'") ||
11467       parseToken(AsmToken::Comma, "expected comma after name '" + Name + "'"))
11468     return true;
11469 
11470   MCSymbol *Sym;
11471   const MCExpr *Value;
11472   if (MCParserUtils::parseAssignmentExpression(Name, /* allow_redef */ true,
11473                                                Parser, Sym, Value))
11474     return true;
11475 
11476   getTargetStreamer().emitThumbSet(Sym, Value);
11477   return false;
11478 }
11479 
11480 /// Force static initialization.
11481 extern "C" void LLVMInitializeARMAsmParser() {
11482   RegisterMCAsmParser<ARMAsmParser> X(getTheARMLETarget());
11483   RegisterMCAsmParser<ARMAsmParser> Y(getTheARMBETarget());
11484   RegisterMCAsmParser<ARMAsmParser> A(getTheThumbLETarget());
11485   RegisterMCAsmParser<ARMAsmParser> B(getTheThumbBETarget());
11486 }
11487 
11488 #define GET_REGISTER_MATCHER
11489 #define GET_SUBTARGET_FEATURE_NAME
11490 #define GET_MATCHER_IMPLEMENTATION
11491 #define GET_MNEMONIC_SPELL_CHECKER
11492 #include "ARMGenAsmMatcher.inc"
11493 
11494 // Some diagnostics need to vary with subtarget features, so they are handled
11495 // here. For example, the DPR class has either 16 or 32 registers, depending
11496 // on the FPU available.
11497 const char *
11498 ARMAsmParser::getCustomOperandDiag(ARMMatchResultTy MatchError) {
11499   switch (MatchError) {
11500   // rGPR contains sp starting with ARMv8.
11501   case Match_rGPR:
11502     return hasV8Ops() ? "operand must be a register in range [r0, r14]"
11503                       : "operand must be a register in range [r0, r12] or r14";
11504   // DPR contains 16 registers for some FPUs, and 32 for others.
11505   case Match_DPR:
11506     return hasD32() ? "operand must be a register in range [d0, d31]"
11507                     : "operand must be a register in range [d0, d15]";
11508   case Match_DPR_RegList:
11509     return hasD32() ? "operand must be a list of registers in range [d0, d31]"
11510                     : "operand must be a list of registers in range [d0, d15]";
11511 
11512   // For all other diags, use the static string from tablegen.
11513   default:
11514     return getMatchKindDiag(MatchError);
11515   }
11516 }
11517 
11518 // Process the list of near-misses, throwing away ones we don't want to report
11519 // to the user, and converting the rest to a source location and string that
11520 // should be reported.
11521 void
11522 ARMAsmParser::FilterNearMisses(SmallVectorImpl<NearMissInfo> &NearMissesIn,
11523                                SmallVectorImpl<NearMissMessage> &NearMissesOut,
11524                                SMLoc IDLoc, OperandVector &Operands) {
11525   // TODO: If operand didn't match, sub in a dummy one and run target
11526   // predicate, so that we can avoid reporting near-misses that are invalid?
11527   // TODO: Many operand types dont have SuperClasses set, so we report
11528   // redundant ones.
11529   // TODO: Some operands are superclasses of registers (e.g.
11530   // MCK_RegShiftedImm), we don't have any way to represent that currently.
11531   // TODO: This is not all ARM-specific, can some of it be factored out?
11532 
11533   // Record some information about near-misses that we have already seen, so
11534   // that we can avoid reporting redundant ones. For example, if there are
11535   // variants of an instruction that take 8- and 16-bit immediates, we want
11536   // to only report the widest one.
11537   std::multimap<unsigned, unsigned> OperandMissesSeen;
11538   SmallSet<FeatureBitset, 4> FeatureMissesSeen;
11539   bool ReportedTooFewOperands = false;
11540 
11541   // Process the near-misses in reverse order, so that we see more general ones
11542   // first, and so can avoid emitting more specific ones.
11543   for (NearMissInfo &I : reverse(NearMissesIn)) {
11544     switch (I.getKind()) {
11545     case NearMissInfo::NearMissOperand: {
11546       SMLoc OperandLoc =
11547           ((ARMOperand &)*Operands[I.getOperandIndex()]).getStartLoc();
11548       const char *OperandDiag =
11549           getCustomOperandDiag((ARMMatchResultTy)I.getOperandError());
11550 
11551       // If we have already emitted a message for a superclass, don't also report
11552       // the sub-class. We consider all operand classes that we don't have a
11553       // specialised diagnostic for to be equal for the propose of this check,
11554       // so that we don't report the generic error multiple times on the same
11555       // operand.
11556       unsigned DupCheckMatchClass = OperandDiag ? I.getOperandClass() : ~0U;
11557       auto PrevReports = OperandMissesSeen.equal_range(I.getOperandIndex());
11558       if (std::any_of(PrevReports.first, PrevReports.second,
11559                       [DupCheckMatchClass](
11560                           const std::pair<unsigned, unsigned> Pair) {
11561             if (DupCheckMatchClass == ~0U || Pair.second == ~0U)
11562               return Pair.second == DupCheckMatchClass;
11563             else
11564               return isSubclass((MatchClassKind)DupCheckMatchClass,
11565                                 (MatchClassKind)Pair.second);
11566           }))
11567         break;
11568       OperandMissesSeen.insert(
11569           std::make_pair(I.getOperandIndex(), DupCheckMatchClass));
11570 
11571       NearMissMessage Message;
11572       Message.Loc = OperandLoc;
11573       if (OperandDiag) {
11574         Message.Message = OperandDiag;
11575       } else if (I.getOperandClass() == InvalidMatchClass) {
11576         Message.Message = "too many operands for instruction";
11577       } else {
11578         Message.Message = "invalid operand for instruction";
11579         LLVM_DEBUG(
11580             dbgs() << "Missing diagnostic string for operand class "
11581                    << getMatchClassName((MatchClassKind)I.getOperandClass())
11582                    << I.getOperandClass() << ", error " << I.getOperandError()
11583                    << ", opcode " << MII.getName(I.getOpcode()) << "\n");
11584       }
11585       NearMissesOut.emplace_back(Message);
11586       break;
11587     }
11588     case NearMissInfo::NearMissFeature: {
11589       const FeatureBitset &MissingFeatures = I.getFeatures();
11590       // Don't report the same set of features twice.
11591       if (FeatureMissesSeen.count(MissingFeatures))
11592         break;
11593       FeatureMissesSeen.insert(MissingFeatures);
11594 
11595       // Special case: don't report a feature set which includes arm-mode for
11596       // targets that don't have ARM mode.
11597       if (MissingFeatures.test(Feature_IsARMBit) && !hasARM())
11598         break;
11599       // Don't report any near-misses that both require switching instruction
11600       // set, and adding other subtarget features.
11601       if (isThumb() && MissingFeatures.test(Feature_IsARMBit) &&
11602           MissingFeatures.count() > 1)
11603         break;
11604       if (!isThumb() && MissingFeatures.test(Feature_IsThumbBit) &&
11605           MissingFeatures.count() > 1)
11606         break;
11607       if (!isThumb() && MissingFeatures.test(Feature_IsThumb2Bit) &&
11608           (MissingFeatures & ~FeatureBitset({Feature_IsThumb2Bit,
11609                                              Feature_IsThumbBit})).any())
11610         break;
11611       if (isMClass() && MissingFeatures.test(Feature_HasNEONBit))
11612         break;
11613 
11614       NearMissMessage Message;
11615       Message.Loc = IDLoc;
11616       raw_svector_ostream OS(Message.Message);
11617 
11618       OS << "instruction requires:";
11619       for (unsigned i = 0, e = MissingFeatures.size(); i != e; ++i)
11620         if (MissingFeatures.test(i))
11621           OS << ' ' << getSubtargetFeatureName(i);
11622 
11623       NearMissesOut.emplace_back(Message);
11624 
11625       break;
11626     }
11627     case NearMissInfo::NearMissPredicate: {
11628       NearMissMessage Message;
11629       Message.Loc = IDLoc;
11630       switch (I.getPredicateError()) {
11631       case Match_RequiresNotITBlock:
11632         Message.Message = "flag setting instruction only valid outside IT block";
11633         break;
11634       case Match_RequiresITBlock:
11635         Message.Message = "instruction only valid inside IT block";
11636         break;
11637       case Match_RequiresV6:
11638         Message.Message = "instruction variant requires ARMv6 or later";
11639         break;
11640       case Match_RequiresThumb2:
11641         Message.Message = "instruction variant requires Thumb2";
11642         break;
11643       case Match_RequiresV8:
11644         Message.Message = "instruction variant requires ARMv8 or later";
11645         break;
11646       case Match_RequiresFlagSetting:
11647         Message.Message = "no flag-preserving variant of this instruction available";
11648         break;
11649       case Match_InvalidOperand:
11650         Message.Message = "invalid operand for instruction";
11651         break;
11652       default:
11653         llvm_unreachable("Unhandled target predicate error");
11654         break;
11655       }
11656       NearMissesOut.emplace_back(Message);
11657       break;
11658     }
11659     case NearMissInfo::NearMissTooFewOperands: {
11660       if (!ReportedTooFewOperands) {
11661         SMLoc EndLoc = ((ARMOperand &)*Operands.back()).getEndLoc();
11662         NearMissesOut.emplace_back(NearMissMessage{
11663             EndLoc, StringRef("too few operands for instruction")});
11664         ReportedTooFewOperands = true;
11665       }
11666       break;
11667     }
11668     case NearMissInfo::NoNearMiss:
11669       // This should never leave the matcher.
11670       llvm_unreachable("not a near-miss");
11671       break;
11672     }
11673   }
11674 }
11675 
11676 void ARMAsmParser::ReportNearMisses(SmallVectorImpl<NearMissInfo> &NearMisses,
11677                                     SMLoc IDLoc, OperandVector &Operands) {
11678   SmallVector<NearMissMessage, 4> Messages;
11679   FilterNearMisses(NearMisses, Messages, IDLoc, Operands);
11680 
11681   if (Messages.size() == 0) {
11682     // No near-misses were found, so the best we can do is "invalid
11683     // instruction".
11684     Error(IDLoc, "invalid instruction");
11685   } else if (Messages.size() == 1) {
11686     // One near miss was found, report it as the sole error.
11687     Error(Messages[0].Loc, Messages[0].Message);
11688   } else {
11689     // More than one near miss, so report a generic "invalid instruction"
11690     // error, followed by notes for each of the near-misses.
11691     Error(IDLoc, "invalid instruction, any one of the following would fix this:");
11692     for (auto &M : Messages) {
11693       Note(M.Loc, M.Message);
11694     }
11695   }
11696 }
11697 
11698 /// parseDirectiveArchExtension
11699 ///   ::= .arch_extension [no]feature
11700 bool ARMAsmParser::parseDirectiveArchExtension(SMLoc L) {
11701   // FIXME: This structure should be moved inside ARMTargetParser
11702   // when we start to table-generate them, and we can use the ARM
11703   // flags below, that were generated by table-gen.
11704   static const struct {
11705     const unsigned Kind;
11706     const FeatureBitset ArchCheck;
11707     const FeatureBitset Features;
11708   } Extensions[] = {
11709     { ARM::AEK_CRC, {Feature_HasV8Bit}, {ARM::FeatureCRC} },
11710     { ARM::AEK_CRYPTO,  {Feature_HasV8Bit},
11711       {ARM::FeatureCrypto, ARM::FeatureNEON, ARM::FeatureFPARMv8} },
11712     { ARM::AEK_FP, {Feature_HasV8Bit},
11713       {ARM::FeatureVFP2_D16_SP, ARM::FeatureFPARMv8} },
11714     { (ARM::AEK_HWDIVTHUMB | ARM::AEK_HWDIVARM),
11715       {Feature_HasV7Bit, Feature_IsNotMClassBit},
11716       {ARM::FeatureHWDivThumb, ARM::FeatureHWDivARM} },
11717     { ARM::AEK_MP, {Feature_HasV7Bit, Feature_IsNotMClassBit},
11718       {ARM::FeatureMP} },
11719     { ARM::AEK_SIMD, {Feature_HasV8Bit},
11720       {ARM::FeatureNEON, ARM::FeatureVFP2_D16_SP, ARM::FeatureFPARMv8} },
11721     { ARM::AEK_SEC, {Feature_HasV6KBit}, {ARM::FeatureTrustZone} },
11722     // FIXME: Only available in A-class, isel not predicated
11723     { ARM::AEK_VIRT, {Feature_HasV7Bit}, {ARM::FeatureVirtualization} },
11724     { ARM::AEK_FP16, {Feature_HasV8_2aBit},
11725       {ARM::FeatureFPARMv8, ARM::FeatureFullFP16} },
11726     { ARM::AEK_RAS, {Feature_HasV8Bit}, {ARM::FeatureRAS} },
11727     { ARM::AEK_LOB, {Feature_HasV8_1MMainlineBit}, {ARM::FeatureLOB} },
11728     // FIXME: Unsupported extensions.
11729     { ARM::AEK_OS, {}, {} },
11730     { ARM::AEK_IWMMXT, {}, {} },
11731     { ARM::AEK_IWMMXT2, {}, {} },
11732     { ARM::AEK_MAVERICK, {}, {} },
11733     { ARM::AEK_XSCALE, {}, {} },
11734   };
11735 
11736   MCAsmParser &Parser = getParser();
11737 
11738   if (getLexer().isNot(AsmToken::Identifier))
11739     return Error(getLexer().getLoc(), "expected architecture extension name");
11740 
11741   StringRef Name = Parser.getTok().getString();
11742   SMLoc ExtLoc = Parser.getTok().getLoc();
11743   Lex();
11744 
11745   if (parseToken(AsmToken::EndOfStatement,
11746                  "unexpected token in '.arch_extension' directive"))
11747     return true;
11748 
11749   bool EnableFeature = true;
11750   if (Name.startswith_lower("no")) {
11751     EnableFeature = false;
11752     Name = Name.substr(2);
11753   }
11754   unsigned FeatureKind = ARM::parseArchExt(Name);
11755   if (FeatureKind == ARM::AEK_INVALID)
11756     return Error(ExtLoc, "unknown architectural extension: " + Name);
11757 
11758   for (const auto &Extension : Extensions) {
11759     if (Extension.Kind != FeatureKind)
11760       continue;
11761 
11762     if (Extension.Features.none())
11763       return Error(ExtLoc, "unsupported architectural extension: " + Name);
11764 
11765     if ((getAvailableFeatures() & Extension.ArchCheck) != Extension.ArchCheck)
11766       return Error(ExtLoc, "architectural extension '" + Name +
11767                                "' is not "
11768                                "allowed for the current base architecture");
11769 
11770     MCSubtargetInfo &STI = copySTI();
11771     if (EnableFeature) {
11772       STI.SetFeatureBitsTransitively(Extension.Features);
11773     } else {
11774       STI.ClearFeatureBitsTransitively(Extension.Features);
11775     }
11776     FeatureBitset Features = ComputeAvailableFeatures(STI.getFeatureBits());
11777     setAvailableFeatures(Features);
11778     return false;
11779   }
11780 
11781   return Error(ExtLoc, "unknown architectural extension: " + Name);
11782 }
11783 
11784 // Define this matcher function after the auto-generated include so we
11785 // have the match class enum definitions.
11786 unsigned ARMAsmParser::validateTargetOperandClass(MCParsedAsmOperand &AsmOp,
11787                                                   unsigned Kind) {
11788   ARMOperand &Op = static_cast<ARMOperand &>(AsmOp);
11789   // If the kind is a token for a literal immediate, check if our asm
11790   // operand matches. This is for InstAliases which have a fixed-value
11791   // immediate in the syntax.
11792   switch (Kind) {
11793   default: break;
11794   case MCK__35_0:
11795     if (Op.isImm())
11796       if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm()))
11797         if (CE->getValue() == 0)
11798           return Match_Success;
11799     break;
11800   case MCK__35_8:
11801     if (Op.isImm())
11802       if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm()))
11803         if (CE->getValue() == 8)
11804           return Match_Success;
11805     break;
11806   case MCK__35_16:
11807     if (Op.isImm())
11808       if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm()))
11809         if (CE->getValue() == 16)
11810           return Match_Success;
11811     break;
11812   case MCK_ModImm:
11813     if (Op.isImm()) {
11814       const MCExpr *SOExpr = Op.getImm();
11815       int64_t Value;
11816       if (!SOExpr->evaluateAsAbsolute(Value))
11817         return Match_Success;
11818       assert((Value >= std::numeric_limits<int32_t>::min() &&
11819               Value <= std::numeric_limits<uint32_t>::max()) &&
11820              "expression value must be representable in 32 bits");
11821     }
11822     break;
11823   case MCK_rGPR:
11824     if (hasV8Ops() && Op.isReg() && Op.getReg() == ARM::SP)
11825       return Match_Success;
11826     return Match_rGPR;
11827   case MCK_GPRPair:
11828     if (Op.isReg() &&
11829         MRI->getRegClass(ARM::GPRRegClassID).contains(Op.getReg()))
11830       return Match_Success;
11831     break;
11832   }
11833   return Match_InvalidOperand;
11834 }
11835 
11836 bool ARMAsmParser::isMnemonicVPTPredicable(StringRef Mnemonic,
11837                                            StringRef ExtraToken) {
11838   if (!hasMVE())
11839     return false;
11840 
11841   return Mnemonic.startswith("vabav") || Mnemonic.startswith("vaddv") ||
11842          Mnemonic.startswith("vaddlv") || Mnemonic.startswith("vminnmv") ||
11843          Mnemonic.startswith("vminnmav") || Mnemonic.startswith("vminv") ||
11844          Mnemonic.startswith("vminav") || Mnemonic.startswith("vmaxnmv") ||
11845          Mnemonic.startswith("vmaxnmav") || Mnemonic.startswith("vmaxv") ||
11846          Mnemonic.startswith("vmaxav") || Mnemonic.startswith("vmladav") ||
11847          Mnemonic.startswith("vrmlaldavh") || Mnemonic.startswith("vrmlalvh") ||
11848          Mnemonic.startswith("vmlsdav") || Mnemonic.startswith("vmlav") ||
11849          Mnemonic.startswith("vmlaldav") || Mnemonic.startswith("vmlalv") ||
11850          Mnemonic.startswith("vmaxnm") || Mnemonic.startswith("vminnm") ||
11851          Mnemonic.startswith("vmax") || Mnemonic.startswith("vmin") ||
11852          Mnemonic.startswith("vshlc") || Mnemonic.startswith("vmovlt") ||
11853          Mnemonic.startswith("vmovlb") || Mnemonic.startswith("vshll") ||
11854          Mnemonic.startswith("vrshrn") || Mnemonic.startswith("vshrn") ||
11855          Mnemonic.startswith("vqrshrun") || Mnemonic.startswith("vqshrun") ||
11856          Mnemonic.startswith("vqrshrn") || Mnemonic.startswith("vqshrn") ||
11857          Mnemonic.startswith("vbic") || Mnemonic.startswith("vrev64") ||
11858          Mnemonic.startswith("vrev32") || Mnemonic.startswith("vrev16") ||
11859          Mnemonic.startswith("vmvn") || Mnemonic.startswith("veor") ||
11860          Mnemonic.startswith("vorn") || Mnemonic.startswith("vorr") ||
11861          Mnemonic.startswith("vand") || Mnemonic.startswith("vmul") ||
11862          Mnemonic.startswith("vqrdmulh") || Mnemonic.startswith("vqdmulh") ||
11863          Mnemonic.startswith("vsub") || Mnemonic.startswith("vadd") ||
11864          Mnemonic.startswith("vqsub") || Mnemonic.startswith("vqadd") ||
11865          Mnemonic.startswith("vabd") || Mnemonic.startswith("vrhadd") ||
11866          Mnemonic.startswith("vhsub") || Mnemonic.startswith("vhadd") ||
11867          Mnemonic.startswith("vdup") || Mnemonic.startswith("vcls") ||
11868          Mnemonic.startswith("vclz") || Mnemonic.startswith("vneg") ||
11869          Mnemonic.startswith("vabs") || Mnemonic.startswith("vqneg") ||
11870          Mnemonic.startswith("vqabs") ||
11871          (Mnemonic.startswith("vrint") && Mnemonic != "vrintr") ||
11872          Mnemonic.startswith("vcmla") || Mnemonic.startswith("vfma") ||
11873          Mnemonic.startswith("vfms") || Mnemonic.startswith("vcadd") ||
11874          Mnemonic.startswith("vadd") || Mnemonic.startswith("vsub") ||
11875          Mnemonic.startswith("vshl") || Mnemonic.startswith("vqshl") ||
11876          Mnemonic.startswith("vqrshl") || Mnemonic.startswith("vrshl") ||
11877          Mnemonic.startswith("vsri") || Mnemonic.startswith("vsli") ||
11878          Mnemonic.startswith("vrshr") || Mnemonic.startswith("vshr") ||
11879          Mnemonic.startswith("vpsel") || Mnemonic.startswith("vcmp") ||
11880          Mnemonic.startswith("vqdmladh") || Mnemonic.startswith("vqrdmladh") ||
11881          Mnemonic.startswith("vqdmlsdh") || Mnemonic.startswith("vqrdmlsdh") ||
11882          Mnemonic.startswith("vcmul") || Mnemonic.startswith("vrmulh") ||
11883          Mnemonic.startswith("vqmovn") || Mnemonic.startswith("vqmovun") ||
11884          Mnemonic.startswith("vmovnt") || Mnemonic.startswith("vmovnb") ||
11885          Mnemonic.startswith("vmaxa") || Mnemonic.startswith("vmaxnma") ||
11886          Mnemonic.startswith("vhcadd") || Mnemonic.startswith("vadc") ||
11887          Mnemonic.startswith("vsbc") || Mnemonic.startswith("vrshr") ||
11888          Mnemonic.startswith("vshr") || Mnemonic.startswith("vstrb") ||
11889          Mnemonic.startswith("vldrb") ||
11890          (Mnemonic.startswith("vstrh") && Mnemonic != "vstrhi") ||
11891          (Mnemonic.startswith("vldrh") && Mnemonic != "vldrhi") ||
11892          Mnemonic.startswith("vstrw") || Mnemonic.startswith("vldrw") ||
11893          Mnemonic.startswith("vldrd") || Mnemonic.startswith("vstrd") ||
11894          Mnemonic.startswith("vqdmull") || Mnemonic.startswith("vbrsr") ||
11895          Mnemonic.startswith("vfmas") || Mnemonic.startswith("vmlas") ||
11896          Mnemonic.startswith("vmla") || Mnemonic.startswith("vqdmlash") ||
11897          Mnemonic.startswith("vqdmlah") || Mnemonic.startswith("vqrdmlash") ||
11898          Mnemonic.startswith("vqrdmlah") || Mnemonic.startswith("viwdup") ||
11899          Mnemonic.startswith("vdwdup") || Mnemonic.startswith("vidup") ||
11900          Mnemonic.startswith("vddup") || Mnemonic.startswith("vctp") ||
11901          Mnemonic.startswith("vpnot") || Mnemonic.startswith("vbic") ||
11902          Mnemonic.startswith("vrmlsldavh") || Mnemonic.startswith("vmlsldav") ||
11903          Mnemonic.startswith("vcvt") ||
11904          (Mnemonic.startswith("vmov") &&
11905           !(ExtraToken == ".f16" || ExtraToken == ".32" ||
11906             ExtraToken == ".16" || ExtraToken == ".8"));
11907 }
11908