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/StringSet.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/ADT/StringSwitch.h"
28 #include "llvm/ADT/Triple.h"
29 #include "llvm/ADT/Twine.h"
30 #include "llvm/MC/MCContext.h"
31 #include "llvm/MC/MCExpr.h"
32 #include "llvm/MC/MCInst.h"
33 #include "llvm/MC/MCInstrDesc.h"
34 #include "llvm/MC/MCInstrInfo.h"
35 #include "llvm/MC/MCObjectFileInfo.h"
36 #include "llvm/MC/MCParser/MCAsmLexer.h"
37 #include "llvm/MC/MCParser/MCAsmParser.h"
38 #include "llvm/MC/MCParser/MCAsmParserExtension.h"
39 #include "llvm/MC/MCParser/MCAsmParserUtils.h"
40 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
41 #include "llvm/MC/MCParser/MCTargetAsmParser.h"
42 #include "llvm/MC/MCRegisterInfo.h"
43 #include "llvm/MC/MCSection.h"
44 #include "llvm/MC/MCStreamer.h"
45 #include "llvm/MC/MCSubtargetInfo.h"
46 #include "llvm/MC/MCSymbol.h"
47 #include "llvm/MC/SubtargetFeature.h"
48 #include "llvm/Support/ARMBuildAttributes.h"
49 #include "llvm/Support/ARMEHABI.h"
50 #include "llvm/Support/Casting.h"
51 #include "llvm/Support/CommandLine.h"
52 #include "llvm/Support/Compiler.h"
53 #include "llvm/Support/ErrorHandling.h"
54 #include "llvm/Support/MathExtras.h"
55 #include "llvm/Support/SMLoc.h"
56 #include "llvm/Support/TargetParser.h"
57 #include "llvm/Support/TargetRegistry.h"
58 #include "llvm/Support/raw_ostream.h"
59 #include <algorithm>
60 #include <cassert>
61 #include <cstddef>
62 #include <cstdint>
63 #include <iterator>
64 #include <limits>
65 #include <memory>
66 #include <string>
67 #include <utility>
68 #include <vector>
69 
70 #define DEBUG_TYPE "asm-parser"
71 
72 using namespace llvm;
73 
74 namespace llvm {
75 extern const MCInstrDesc ARMInsts[];
76 } // end namespace llvm
77 
78 namespace {
79 
80 enum class ImplicitItModeTy { Always, Never, ARMOnly, ThumbOnly };
81 
82 static cl::opt<ImplicitItModeTy> ImplicitItMode(
83     "arm-implicit-it", cl::init(ImplicitItModeTy::ARMOnly),
84     cl::desc("Allow conditional instructions outdside of an IT block"),
85     cl::values(clEnumValN(ImplicitItModeTy::Always, "always",
86                           "Accept in both ISAs, emit implicit ITs in Thumb"),
87                clEnumValN(ImplicitItModeTy::Never, "never",
88                           "Warn in ARM, reject in Thumb"),
89                clEnumValN(ImplicitItModeTy::ARMOnly, "arm",
90                           "Accept in ARM, reject in Thumb"),
91                clEnumValN(ImplicitItModeTy::ThumbOnly, "thumb",
92                           "Warn in ARM, emit implicit ITs in Thumb")));
93 
94 static cl::opt<bool> AddBuildAttributes("arm-add-build-attributes",
95                                         cl::init(false));
96 
97 enum VectorLaneTy { NoLanes, AllLanes, IndexedLane };
98 
99 static inline unsigned extractITMaskBit(unsigned Mask, unsigned Position) {
100   // Position==0 means we're not in an IT block at all. Position==1
101   // means we want the first state bit, which is always 0 (Then).
102   // Position==2 means we want the second state bit, stored at bit 3
103   // of Mask, and so on downwards. So (5 - Position) will shift the
104   // right bit down to bit 0, including the always-0 bit at bit 4 for
105   // the mandatory initial Then.
106   return (Mask >> (5 - Position) & 1);
107 }
108 
109 class UnwindContext {
110   using Locs = SmallVector<SMLoc, 4>;
111 
112   MCAsmParser &Parser;
113   Locs FnStartLocs;
114   Locs CantUnwindLocs;
115   Locs PersonalityLocs;
116   Locs PersonalityIndexLocs;
117   Locs HandlerDataLocs;
118   int FPReg;
119 
120 public:
121   UnwindContext(MCAsmParser &P) : Parser(P), FPReg(ARM::SP) {}
122 
123   bool hasFnStart() const { return !FnStartLocs.empty(); }
124   bool cantUnwind() const { return !CantUnwindLocs.empty(); }
125   bool hasHandlerData() const { return !HandlerDataLocs.empty(); }
126 
127   bool hasPersonality() const {
128     return !(PersonalityLocs.empty() && PersonalityIndexLocs.empty());
129   }
130 
131   void recordFnStart(SMLoc L) { FnStartLocs.push_back(L); }
132   void recordCantUnwind(SMLoc L) { CantUnwindLocs.push_back(L); }
133   void recordPersonality(SMLoc L) { PersonalityLocs.push_back(L); }
134   void recordHandlerData(SMLoc L) { HandlerDataLocs.push_back(L); }
135   void recordPersonalityIndex(SMLoc L) { PersonalityIndexLocs.push_back(L); }
136 
137   void saveFPReg(int Reg) { FPReg = Reg; }
138   int getFPReg() const { return FPReg; }
139 
140   void emitFnStartLocNotes() const {
141     for (Locs::const_iterator FI = FnStartLocs.begin(), FE = FnStartLocs.end();
142          FI != FE; ++FI)
143       Parser.Note(*FI, ".fnstart was specified here");
144   }
145 
146   void emitCantUnwindLocNotes() const {
147     for (Locs::const_iterator UI = CantUnwindLocs.begin(),
148                               UE = CantUnwindLocs.end(); UI != UE; ++UI)
149       Parser.Note(*UI, ".cantunwind was specified here");
150   }
151 
152   void emitHandlerDataLocNotes() const {
153     for (Locs::const_iterator HI = HandlerDataLocs.begin(),
154                               HE = HandlerDataLocs.end(); HI != HE; ++HI)
155       Parser.Note(*HI, ".handlerdata was specified here");
156   }
157 
158   void emitPersonalityLocNotes() const {
159     for (Locs::const_iterator PI = PersonalityLocs.begin(),
160                               PE = PersonalityLocs.end(),
161                               PII = PersonalityIndexLocs.begin(),
162                               PIE = PersonalityIndexLocs.end();
163          PI != PE || PII != PIE;) {
164       if (PI != PE && (PII == PIE || PI->getPointer() < PII->getPointer()))
165         Parser.Note(*PI++, ".personality was specified here");
166       else if (PII != PIE && (PI == PE || PII->getPointer() < PI->getPointer()))
167         Parser.Note(*PII++, ".personalityindex was specified here");
168       else
169         llvm_unreachable(".personality and .personalityindex cannot be "
170                          "at the same location");
171     }
172   }
173 
174   void reset() {
175     FnStartLocs = Locs();
176     CantUnwindLocs = Locs();
177     PersonalityLocs = Locs();
178     HandlerDataLocs = Locs();
179     PersonalityIndexLocs = Locs();
180     FPReg = ARM::SP;
181   }
182 };
183 
184 // Various sets of ARM instruction mnemonics which are used by the asm parser
185 class ARMMnemonicSets {
186   StringSet<> CDE;
187   StringSet<> CDEWithVPTSuffix;
188 public:
189   ARMMnemonicSets(const MCSubtargetInfo &STI);
190 
191   /// Returns true iff a given mnemonic is a CDE instruction
192   bool isCDEInstr(StringRef Mnemonic) {
193     // Quick check before searching the set
194     if (!Mnemonic.startswith("cx") && !Mnemonic.startswith("vcx"))
195       return false;
196     return CDE.count(Mnemonic);
197   }
198 
199   /// Returns true iff a given mnemonic is a VPT-predicable CDE instruction
200   /// (possibly with a predication suffix "e" or "t")
201   bool isVPTPredicableCDEInstr(StringRef Mnemonic) {
202     if (!Mnemonic.startswith("vcx"))
203       return false;
204     return CDEWithVPTSuffix.count(Mnemonic);
205   }
206 
207   /// Returns true iff a given mnemonic is an IT-predicable CDE instruction
208   /// (possibly with a condition suffix)
209   bool isITPredicableCDEInstr(StringRef Mnemonic) {
210     if (!Mnemonic.startswith("cx"))
211       return false;
212     return Mnemonic.startswith("cx1a") || Mnemonic.startswith("cx1da") ||
213            Mnemonic.startswith("cx2a") || Mnemonic.startswith("cx2da") ||
214            Mnemonic.startswith("cx3a") || Mnemonic.startswith("cx3da");
215   }
216 
217   /// Return true iff a given mnemonic is an integer CDE instruction with
218   /// dual-register destination
219   bool isCDEDualRegInstr(StringRef Mnemonic) {
220     if (!Mnemonic.startswith("cx"))
221       return false;
222     return Mnemonic == "cx1d" || Mnemonic == "cx1da" ||
223            Mnemonic == "cx2d" || Mnemonic == "cx2da" ||
224            Mnemonic == "cx3d" || Mnemonic == "cx3da";
225   }
226 };
227 
228 ARMMnemonicSets::ARMMnemonicSets(const MCSubtargetInfo &STI) {
229   for (StringRef Mnemonic: { "cx1", "cx1a", "cx1d", "cx1da",
230                              "cx2", "cx2a", "cx2d", "cx2da",
231                              "cx3", "cx3a", "cx3d", "cx3da", })
232     CDE.insert(Mnemonic);
233   for (StringRef Mnemonic :
234        {"vcx1", "vcx1a", "vcx2", "vcx2a", "vcx3", "vcx3a"}) {
235     CDE.insert(Mnemonic);
236     CDEWithVPTSuffix.insert(Mnemonic);
237     CDEWithVPTSuffix.insert(std::string(Mnemonic) + "t");
238     CDEWithVPTSuffix.insert(std::string(Mnemonic) + "e");
239   }
240 }
241 
242 class ARMAsmParser : public MCTargetAsmParser {
243   const MCRegisterInfo *MRI;
244   UnwindContext UC;
245   ARMMnemonicSets MS;
246 
247   ARMTargetStreamer &getTargetStreamer() {
248     assert(getParser().getStreamer().getTargetStreamer() &&
249            "do not have a target streamer");
250     MCTargetStreamer &TS = *getParser().getStreamer().getTargetStreamer();
251     return static_cast<ARMTargetStreamer &>(TS);
252   }
253 
254   // Map of register aliases registers via the .req directive.
255   StringMap<unsigned> RegisterReqs;
256 
257   bool NextSymbolIsThumb;
258 
259   bool useImplicitITThumb() const {
260     return ImplicitItMode == ImplicitItModeTy::Always ||
261            ImplicitItMode == ImplicitItModeTy::ThumbOnly;
262   }
263 
264   bool useImplicitITARM() const {
265     return ImplicitItMode == ImplicitItModeTy::Always ||
266            ImplicitItMode == ImplicitItModeTy::ARMOnly;
267   }
268 
269   struct {
270     ARMCC::CondCodes Cond;    // Condition for IT block.
271     unsigned Mask:4;          // Condition mask for instructions.
272                               // Starting at first 1 (from lsb).
273                               //   '1'  condition as indicated in IT.
274                               //   '0'  inverse of condition (else).
275                               // Count of instructions in IT block is
276                               // 4 - trailingzeroes(mask)
277                               // Note that this does not have the same encoding
278                               // as in the IT instruction, which also depends
279                               // on the low bit of the condition code.
280 
281     unsigned CurPosition;     // Current position in parsing of IT
282                               // block. In range [0,4], with 0 being the IT
283                               // instruction itself. Initialized according to
284                               // count of instructions in block.  ~0U if no
285                               // active IT block.
286 
287     bool IsExplicit;          // true  - The IT instruction was present in the
288                               //         input, we should not modify it.
289                               // false - The IT instruction was added
290                               //         implicitly, we can extend it if that
291                               //         would be legal.
292   } ITState;
293 
294   SmallVector<MCInst, 4> PendingConditionalInsts;
295 
296   void flushPendingInstructions(MCStreamer &Out) override {
297     if (!inImplicitITBlock()) {
298       assert(PendingConditionalInsts.size() == 0);
299       return;
300     }
301 
302     // Emit the IT instruction
303     MCInst ITInst;
304     ITInst.setOpcode(ARM::t2IT);
305     ITInst.addOperand(MCOperand::createImm(ITState.Cond));
306     ITInst.addOperand(MCOperand::createImm(ITState.Mask));
307     Out.emitInstruction(ITInst, getSTI());
308 
309     // Emit the conditonal instructions
310     assert(PendingConditionalInsts.size() <= 4);
311     for (const MCInst &Inst : PendingConditionalInsts) {
312       Out.emitInstruction(Inst, getSTI());
313     }
314     PendingConditionalInsts.clear();
315 
316     // Clear the IT state
317     ITState.Mask = 0;
318     ITState.CurPosition = ~0U;
319   }
320 
321   bool inITBlock() { return ITState.CurPosition != ~0U; }
322   bool inExplicitITBlock() { return inITBlock() && ITState.IsExplicit; }
323   bool inImplicitITBlock() { return inITBlock() && !ITState.IsExplicit; }
324 
325   bool lastInITBlock() {
326     return ITState.CurPosition == 4 - countTrailingZeros(ITState.Mask);
327   }
328 
329   void forwardITPosition() {
330     if (!inITBlock()) return;
331     // Move to the next instruction in the IT block, if there is one. If not,
332     // mark the block as done, except for implicit IT blocks, which we leave
333     // open until we find an instruction that can't be added to it.
334     unsigned TZ = countTrailingZeros(ITState.Mask);
335     if (++ITState.CurPosition == 5 - TZ && ITState.IsExplicit)
336       ITState.CurPosition = ~0U; // Done with the IT block after this.
337   }
338 
339   // Rewind the state of the current IT block, removing the last slot from it.
340   void rewindImplicitITPosition() {
341     assert(inImplicitITBlock());
342     assert(ITState.CurPosition > 1);
343     ITState.CurPosition--;
344     unsigned TZ = countTrailingZeros(ITState.Mask);
345     unsigned NewMask = 0;
346     NewMask |= ITState.Mask & (0xC << TZ);
347     NewMask |= 0x2 << TZ;
348     ITState.Mask = NewMask;
349   }
350 
351   // Rewind the state of the current IT block, removing the last slot from it.
352   // If we were at the first slot, this closes the IT block.
353   void discardImplicitITBlock() {
354     assert(inImplicitITBlock());
355     assert(ITState.CurPosition == 1);
356     ITState.CurPosition = ~0U;
357   }
358 
359   // Return the low-subreg of a given Q register.
360   unsigned getDRegFromQReg(unsigned QReg) const {
361     return MRI->getSubReg(QReg, ARM::dsub_0);
362   }
363 
364   // Get the condition code corresponding to the current IT block slot.
365   ARMCC::CondCodes currentITCond() {
366     unsigned MaskBit = extractITMaskBit(ITState.Mask, ITState.CurPosition);
367     return MaskBit ? ARMCC::getOppositeCondition(ITState.Cond) : ITState.Cond;
368   }
369 
370   // Invert the condition of the current IT block slot without changing any
371   // other slots in the same block.
372   void invertCurrentITCondition() {
373     if (ITState.CurPosition == 1) {
374       ITState.Cond = ARMCC::getOppositeCondition(ITState.Cond);
375     } else {
376       ITState.Mask ^= 1 << (5 - ITState.CurPosition);
377     }
378   }
379 
380   // Returns true if the current IT block is full (all 4 slots used).
381   bool isITBlockFull() {
382     return inITBlock() && (ITState.Mask & 1);
383   }
384 
385   // Extend the current implicit IT block to have one more slot with the given
386   // condition code.
387   void extendImplicitITBlock(ARMCC::CondCodes Cond) {
388     assert(inImplicitITBlock());
389     assert(!isITBlockFull());
390     assert(Cond == ITState.Cond ||
391            Cond == ARMCC::getOppositeCondition(ITState.Cond));
392     unsigned TZ = countTrailingZeros(ITState.Mask);
393     unsigned NewMask = 0;
394     // Keep any existing condition bits.
395     NewMask |= ITState.Mask & (0xE << TZ);
396     // Insert the new condition bit.
397     NewMask |= (Cond != ITState.Cond) << TZ;
398     // Move the trailing 1 down one bit.
399     NewMask |= 1 << (TZ - 1);
400     ITState.Mask = NewMask;
401   }
402 
403   // Create a new implicit IT block with a dummy condition code.
404   void startImplicitITBlock() {
405     assert(!inITBlock());
406     ITState.Cond = ARMCC::AL;
407     ITState.Mask = 8;
408     ITState.CurPosition = 1;
409     ITState.IsExplicit = false;
410   }
411 
412   // Create a new explicit IT block with the given condition and mask.
413   // The mask should be in the format used in ARMOperand and
414   // MCOperand, with a 1 implying 'e', regardless of the low bit of
415   // the condition.
416   void startExplicitITBlock(ARMCC::CondCodes Cond, unsigned Mask) {
417     assert(!inITBlock());
418     ITState.Cond = Cond;
419     ITState.Mask = Mask;
420     ITState.CurPosition = 0;
421     ITState.IsExplicit = true;
422   }
423 
424   struct {
425     unsigned Mask : 4;
426     unsigned CurPosition;
427   } VPTState;
428   bool inVPTBlock() { return VPTState.CurPosition != ~0U; }
429   void forwardVPTPosition() {
430     if (!inVPTBlock()) return;
431     unsigned TZ = countTrailingZeros(VPTState.Mask);
432     if (++VPTState.CurPosition == 5 - TZ)
433       VPTState.CurPosition = ~0U;
434   }
435 
436   void Note(SMLoc L, const Twine &Msg, SMRange Range = None) {
437     return getParser().Note(L, Msg, Range);
438   }
439 
440   bool Warning(SMLoc L, const Twine &Msg, SMRange Range = None) {
441     return getParser().Warning(L, Msg, Range);
442   }
443 
444   bool Error(SMLoc L, const Twine &Msg, SMRange Range = None) {
445     return getParser().Error(L, Msg, Range);
446   }
447 
448   bool validatetLDMRegList(const MCInst &Inst, const OperandVector &Operands,
449                            unsigned ListNo, bool IsARPop = false);
450   bool validatetSTMRegList(const MCInst &Inst, const OperandVector &Operands,
451                            unsigned ListNo);
452 
453   int tryParseRegister();
454   bool tryParseRegisterWithWriteBack(OperandVector &);
455   int tryParseShiftRegister(OperandVector &);
456   bool parseRegisterList(OperandVector &, bool EnforceOrder = true);
457   bool parseMemory(OperandVector &);
458   bool parseOperand(OperandVector &, StringRef Mnemonic);
459   bool parsePrefix(ARMMCExpr::VariantKind &RefKind);
460   bool parseMemRegOffsetShift(ARM_AM::ShiftOpc &ShiftType,
461                               unsigned &ShiftAmount);
462   bool parseLiteralValues(unsigned Size, SMLoc L);
463   bool parseDirectiveThumb(SMLoc L);
464   bool parseDirectiveARM(SMLoc L);
465   bool parseDirectiveThumbFunc(SMLoc L);
466   bool parseDirectiveCode(SMLoc L);
467   bool parseDirectiveSyntax(SMLoc L);
468   bool parseDirectiveReq(StringRef Name, SMLoc L);
469   bool parseDirectiveUnreq(SMLoc L);
470   bool parseDirectiveArch(SMLoc L);
471   bool parseDirectiveEabiAttr(SMLoc L);
472   bool parseDirectiveCPU(SMLoc L);
473   bool parseDirectiveFPU(SMLoc L);
474   bool parseDirectiveFnStart(SMLoc L);
475   bool parseDirectiveFnEnd(SMLoc L);
476   bool parseDirectiveCantUnwind(SMLoc L);
477   bool parseDirectivePersonality(SMLoc L);
478   bool parseDirectiveHandlerData(SMLoc L);
479   bool parseDirectiveSetFP(SMLoc L);
480   bool parseDirectivePad(SMLoc L);
481   bool parseDirectiveRegSave(SMLoc L, bool IsVector);
482   bool parseDirectiveInst(SMLoc L, char Suffix = '\0');
483   bool parseDirectiveLtorg(SMLoc L);
484   bool parseDirectiveEven(SMLoc L);
485   bool parseDirectivePersonalityIndex(SMLoc L);
486   bool parseDirectiveUnwindRaw(SMLoc L);
487   bool parseDirectiveTLSDescSeq(SMLoc L);
488   bool parseDirectiveMovSP(SMLoc L);
489   bool parseDirectiveObjectArch(SMLoc L);
490   bool parseDirectiveArchExtension(SMLoc L);
491   bool parseDirectiveAlign(SMLoc L);
492   bool parseDirectiveThumbSet(SMLoc L);
493 
494   bool isMnemonicVPTPredicable(StringRef Mnemonic, StringRef ExtraToken);
495   StringRef splitMnemonic(StringRef Mnemonic, StringRef ExtraToken,
496                           unsigned &PredicationCode,
497                           unsigned &VPTPredicationCode, bool &CarrySetting,
498                           unsigned &ProcessorIMod, StringRef &ITMask);
499   void getMnemonicAcceptInfo(StringRef Mnemonic, StringRef ExtraToken,
500                              StringRef FullInst, bool &CanAcceptCarrySet,
501                              bool &CanAcceptPredicationCode,
502                              bool &CanAcceptVPTPredicationCode);
503   bool enableArchExtFeature(StringRef Name, SMLoc &ExtLoc);
504 
505   void tryConvertingToTwoOperandForm(StringRef Mnemonic, bool CarrySetting,
506                                      OperandVector &Operands);
507   bool CDEConvertDualRegOperand(StringRef Mnemonic, OperandVector &Operands);
508 
509   bool isThumb() const {
510     // FIXME: Can tablegen auto-generate this?
511     return getSTI().getFeatureBits()[ARM::ModeThumb];
512   }
513 
514   bool isThumbOne() const {
515     return isThumb() && !getSTI().getFeatureBits()[ARM::FeatureThumb2];
516   }
517 
518   bool isThumbTwo() const {
519     return isThumb() && getSTI().getFeatureBits()[ARM::FeatureThumb2];
520   }
521 
522   bool hasThumb() const {
523     return getSTI().getFeatureBits()[ARM::HasV4TOps];
524   }
525 
526   bool hasThumb2() const {
527     return getSTI().getFeatureBits()[ARM::FeatureThumb2];
528   }
529 
530   bool hasV6Ops() const {
531     return getSTI().getFeatureBits()[ARM::HasV6Ops];
532   }
533 
534   bool hasV6T2Ops() const {
535     return getSTI().getFeatureBits()[ARM::HasV6T2Ops];
536   }
537 
538   bool hasV6MOps() const {
539     return getSTI().getFeatureBits()[ARM::HasV6MOps];
540   }
541 
542   bool hasV7Ops() const {
543     return getSTI().getFeatureBits()[ARM::HasV7Ops];
544   }
545 
546   bool hasV8Ops() const {
547     return getSTI().getFeatureBits()[ARM::HasV8Ops];
548   }
549 
550   bool hasV8MBaseline() const {
551     return getSTI().getFeatureBits()[ARM::HasV8MBaselineOps];
552   }
553 
554   bool hasV8MMainline() const {
555     return getSTI().getFeatureBits()[ARM::HasV8MMainlineOps];
556   }
557   bool hasV8_1MMainline() const {
558     return getSTI().getFeatureBits()[ARM::HasV8_1MMainlineOps];
559   }
560   bool hasMVE() const {
561     return getSTI().getFeatureBits()[ARM::HasMVEIntegerOps];
562   }
563   bool hasMVEFloat() const {
564     return getSTI().getFeatureBits()[ARM::HasMVEFloatOps];
565   }
566   bool hasCDE() const {
567     return getSTI().getFeatureBits()[ARM::HasCDEOps];
568   }
569   bool has8MSecExt() const {
570     return getSTI().getFeatureBits()[ARM::Feature8MSecExt];
571   }
572 
573   bool hasARM() const {
574     return !getSTI().getFeatureBits()[ARM::FeatureNoARM];
575   }
576 
577   bool hasDSP() const {
578     return getSTI().getFeatureBits()[ARM::FeatureDSP];
579   }
580 
581   bool hasD32() const {
582     return getSTI().getFeatureBits()[ARM::FeatureD32];
583   }
584 
585   bool hasV8_1aOps() const {
586     return getSTI().getFeatureBits()[ARM::HasV8_1aOps];
587   }
588 
589   bool hasRAS() const {
590     return getSTI().getFeatureBits()[ARM::FeatureRAS];
591   }
592 
593   void SwitchMode() {
594     MCSubtargetInfo &STI = copySTI();
595     auto FB = ComputeAvailableFeatures(STI.ToggleFeature(ARM::ModeThumb));
596     setAvailableFeatures(FB);
597   }
598 
599   void FixModeAfterArchChange(bool WasThumb, SMLoc Loc);
600 
601   bool isMClass() const {
602     return getSTI().getFeatureBits()[ARM::FeatureMClass];
603   }
604 
605   /// @name Auto-generated Match Functions
606   /// {
607 
608 #define GET_ASSEMBLER_HEADER
609 #include "ARMGenAsmMatcher.inc"
610 
611   /// }
612 
613   OperandMatchResultTy parseITCondCode(OperandVector &);
614   OperandMatchResultTy parseCoprocNumOperand(OperandVector &);
615   OperandMatchResultTy parseCoprocRegOperand(OperandVector &);
616   OperandMatchResultTy parseCoprocOptionOperand(OperandVector &);
617   OperandMatchResultTy parseMemBarrierOptOperand(OperandVector &);
618   OperandMatchResultTy parseTraceSyncBarrierOptOperand(OperandVector &);
619   OperandMatchResultTy parseInstSyncBarrierOptOperand(OperandVector &);
620   OperandMatchResultTy parseProcIFlagsOperand(OperandVector &);
621   OperandMatchResultTy parseMSRMaskOperand(OperandVector &);
622   OperandMatchResultTy parseBankedRegOperand(OperandVector &);
623   OperandMatchResultTy parsePKHImm(OperandVector &O, StringRef Op, int Low,
624                                    int High);
625   OperandMatchResultTy parsePKHLSLImm(OperandVector &O) {
626     return parsePKHImm(O, "lsl", 0, 31);
627   }
628   OperandMatchResultTy parsePKHASRImm(OperandVector &O) {
629     return parsePKHImm(O, "asr", 1, 32);
630   }
631   OperandMatchResultTy parseSetEndImm(OperandVector &);
632   OperandMatchResultTy parseShifterImm(OperandVector &);
633   OperandMatchResultTy parseRotImm(OperandVector &);
634   OperandMatchResultTy parseModImm(OperandVector &);
635   OperandMatchResultTy parseBitfield(OperandVector &);
636   OperandMatchResultTy parsePostIdxReg(OperandVector &);
637   OperandMatchResultTy parseAM3Offset(OperandVector &);
638   OperandMatchResultTy parseFPImm(OperandVector &);
639   OperandMatchResultTy parseVectorList(OperandVector &);
640   OperandMatchResultTy parseVectorLane(VectorLaneTy &LaneKind, unsigned &Index,
641                                        SMLoc &EndLoc);
642 
643   // Asm Match Converter Methods
644   void cvtThumbMultiply(MCInst &Inst, const OperandVector &);
645   void cvtThumbBranches(MCInst &Inst, const OperandVector &);
646   void cvtMVEVMOVQtoDReg(MCInst &Inst, const OperandVector &);
647 
648   bool validateInstruction(MCInst &Inst, const OperandVector &Ops);
649   bool processInstruction(MCInst &Inst, const OperandVector &Ops, MCStreamer &Out);
650   bool shouldOmitCCOutOperand(StringRef Mnemonic, OperandVector &Operands);
651   bool shouldOmitPredicateOperand(StringRef Mnemonic, OperandVector &Operands);
652   bool shouldOmitVectorPredicateOperand(StringRef Mnemonic, OperandVector &Operands);
653   bool isITBlockTerminator(MCInst &Inst) const;
654   void fixupGNULDRDAlias(StringRef Mnemonic, OperandVector &Operands);
655   bool validateLDRDSTRD(MCInst &Inst, const OperandVector &Operands,
656                         bool Load, bool ARMMode, bool Writeback);
657 
658 public:
659   enum ARMMatchResultTy {
660     Match_RequiresITBlock = FIRST_TARGET_MATCH_RESULT_TY,
661     Match_RequiresNotITBlock,
662     Match_RequiresV6,
663     Match_RequiresThumb2,
664     Match_RequiresV8,
665     Match_RequiresFlagSetting,
666 #define GET_OPERAND_DIAGNOSTIC_TYPES
667 #include "ARMGenAsmMatcher.inc"
668 
669   };
670 
671   ARMAsmParser(const MCSubtargetInfo &STI, MCAsmParser &Parser,
672                const MCInstrInfo &MII, const MCTargetOptions &Options)
673     : MCTargetAsmParser(Options, STI, MII), UC(Parser), MS(STI) {
674     MCAsmParserExtension::Initialize(Parser);
675 
676     // Cache the MCRegisterInfo.
677     MRI = getContext().getRegisterInfo();
678 
679     // Initialize the set of available features.
680     setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
681 
682     // Add build attributes based on the selected target.
683     if (AddBuildAttributes)
684       getTargetStreamer().emitTargetAttributes(STI);
685 
686     // Not in an ITBlock to start with.
687     ITState.CurPosition = ~0U;
688 
689     VPTState.CurPosition = ~0U;
690 
691     NextSymbolIsThumb = false;
692   }
693 
694   // Implementation of the MCTargetAsmParser interface:
695   bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc) override;
696   OperandMatchResultTy tryParseRegister(unsigned &RegNo, SMLoc &StartLoc,
697                                         SMLoc &EndLoc) override;
698   bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
699                         SMLoc NameLoc, OperandVector &Operands) override;
700   bool ParseDirective(AsmToken DirectiveID) override;
701 
702   unsigned validateTargetOperandClass(MCParsedAsmOperand &Op,
703                                       unsigned Kind) override;
704   unsigned checkTargetMatchPredicate(MCInst &Inst) override;
705 
706   bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
707                                OperandVector &Operands, MCStreamer &Out,
708                                uint64_t &ErrorInfo,
709                                bool MatchingInlineAsm) override;
710   unsigned MatchInstruction(OperandVector &Operands, MCInst &Inst,
711                             SmallVectorImpl<NearMissInfo> &NearMisses,
712                             bool MatchingInlineAsm, bool &EmitInITBlock,
713                             MCStreamer &Out);
714 
715   struct NearMissMessage {
716     SMLoc Loc;
717     SmallString<128> Message;
718   };
719 
720   const char *getCustomOperandDiag(ARMMatchResultTy MatchError);
721 
722   void FilterNearMisses(SmallVectorImpl<NearMissInfo> &NearMissesIn,
723                         SmallVectorImpl<NearMissMessage> &NearMissesOut,
724                         SMLoc IDLoc, OperandVector &Operands);
725   void ReportNearMisses(SmallVectorImpl<NearMissInfo> &NearMisses, SMLoc IDLoc,
726                         OperandVector &Operands);
727 
728   void doBeforeLabelEmit(MCSymbol *Symbol) override;
729 
730   void onLabelParsed(MCSymbol *Symbol) override;
731 };
732 
733 /// ARMOperand - Instances of this class represent a parsed ARM machine
734 /// operand.
735 class ARMOperand : public MCParsedAsmOperand {
736   enum KindTy {
737     k_CondCode,
738     k_VPTPred,
739     k_CCOut,
740     k_ITCondMask,
741     k_CoprocNum,
742     k_CoprocReg,
743     k_CoprocOption,
744     k_Immediate,
745     k_MemBarrierOpt,
746     k_InstSyncBarrierOpt,
747     k_TraceSyncBarrierOpt,
748     k_Memory,
749     k_PostIndexRegister,
750     k_MSRMask,
751     k_BankedReg,
752     k_ProcIFlags,
753     k_VectorIndex,
754     k_Register,
755     k_RegisterList,
756     k_RegisterListWithAPSR,
757     k_DPRRegisterList,
758     k_SPRRegisterList,
759     k_FPSRegisterListWithVPR,
760     k_FPDRegisterListWithVPR,
761     k_VectorList,
762     k_VectorListAllLanes,
763     k_VectorListIndexed,
764     k_ShiftedRegister,
765     k_ShiftedImmediate,
766     k_ShifterImmediate,
767     k_RotateImmediate,
768     k_ModifiedImmediate,
769     k_ConstantPoolImmediate,
770     k_BitfieldDescriptor,
771     k_Token,
772   } Kind;
773 
774   SMLoc StartLoc, EndLoc, AlignmentLoc;
775   SmallVector<unsigned, 8> Registers;
776 
777   struct CCOp {
778     ARMCC::CondCodes Val;
779   };
780 
781   struct VCCOp {
782     ARMVCC::VPTCodes Val;
783   };
784 
785   struct CopOp {
786     unsigned Val;
787   };
788 
789   struct CoprocOptionOp {
790     unsigned Val;
791   };
792 
793   struct ITMaskOp {
794     unsigned Mask:4;
795   };
796 
797   struct MBOptOp {
798     ARM_MB::MemBOpt Val;
799   };
800 
801   struct ISBOptOp {
802     ARM_ISB::InstSyncBOpt Val;
803   };
804 
805   struct TSBOptOp {
806     ARM_TSB::TraceSyncBOpt Val;
807   };
808 
809   struct IFlagsOp {
810     ARM_PROC::IFlags Val;
811   };
812 
813   struct MMaskOp {
814     unsigned Val;
815   };
816 
817   struct BankedRegOp {
818     unsigned Val;
819   };
820 
821   struct TokOp {
822     const char *Data;
823     unsigned Length;
824   };
825 
826   struct RegOp {
827     unsigned RegNum;
828   };
829 
830   // A vector register list is a sequential list of 1 to 4 registers.
831   struct VectorListOp {
832     unsigned RegNum;
833     unsigned Count;
834     unsigned LaneIndex;
835     bool isDoubleSpaced;
836   };
837 
838   struct VectorIndexOp {
839     unsigned Val;
840   };
841 
842   struct ImmOp {
843     const MCExpr *Val;
844   };
845 
846   /// Combined record for all forms of ARM address expressions.
847   struct MemoryOp {
848     unsigned BaseRegNum;
849     // Offset is in OffsetReg or OffsetImm. If both are zero, no offset
850     // was specified.
851     const MCExpr *OffsetImm;  // Offset immediate value
852     unsigned OffsetRegNum;    // Offset register num, when OffsetImm == NULL
853     ARM_AM::ShiftOpc ShiftType; // Shift type for OffsetReg
854     unsigned ShiftImm;        // shift for OffsetReg.
855     unsigned Alignment;       // 0 = no alignment specified
856     // n = alignment in bytes (2, 4, 8, 16, or 32)
857     unsigned isNegative : 1;  // Negated OffsetReg? (~'U' bit)
858   };
859 
860   struct PostIdxRegOp {
861     unsigned RegNum;
862     bool isAdd;
863     ARM_AM::ShiftOpc ShiftTy;
864     unsigned ShiftImm;
865   };
866 
867   struct ShifterImmOp {
868     bool isASR;
869     unsigned Imm;
870   };
871 
872   struct RegShiftedRegOp {
873     ARM_AM::ShiftOpc ShiftTy;
874     unsigned SrcReg;
875     unsigned ShiftReg;
876     unsigned ShiftImm;
877   };
878 
879   struct RegShiftedImmOp {
880     ARM_AM::ShiftOpc ShiftTy;
881     unsigned SrcReg;
882     unsigned ShiftImm;
883   };
884 
885   struct RotImmOp {
886     unsigned Imm;
887   };
888 
889   struct ModImmOp {
890     unsigned Bits;
891     unsigned Rot;
892   };
893 
894   struct BitfieldOp {
895     unsigned LSB;
896     unsigned Width;
897   };
898 
899   union {
900     struct CCOp CC;
901     struct VCCOp VCC;
902     struct CopOp Cop;
903     struct CoprocOptionOp CoprocOption;
904     struct MBOptOp MBOpt;
905     struct ISBOptOp ISBOpt;
906     struct TSBOptOp TSBOpt;
907     struct ITMaskOp ITMask;
908     struct IFlagsOp IFlags;
909     struct MMaskOp MMask;
910     struct BankedRegOp BankedReg;
911     struct TokOp Tok;
912     struct RegOp Reg;
913     struct VectorListOp VectorList;
914     struct VectorIndexOp VectorIndex;
915     struct ImmOp Imm;
916     struct MemoryOp Memory;
917     struct PostIdxRegOp PostIdxReg;
918     struct ShifterImmOp ShifterImm;
919     struct RegShiftedRegOp RegShiftedReg;
920     struct RegShiftedImmOp RegShiftedImm;
921     struct RotImmOp RotImm;
922     struct ModImmOp ModImm;
923     struct BitfieldOp Bitfield;
924   };
925 
926 public:
927   ARMOperand(KindTy K) : MCParsedAsmOperand(), Kind(K) {}
928 
929   /// getStartLoc - Get the location of the first token of this operand.
930   SMLoc getStartLoc() const override { return StartLoc; }
931 
932   /// getEndLoc - Get the location of the last token of this operand.
933   SMLoc getEndLoc() const override { return EndLoc; }
934 
935   /// getLocRange - Get the range between the first and last token of this
936   /// operand.
937   SMRange getLocRange() const { return SMRange(StartLoc, EndLoc); }
938 
939   /// getAlignmentLoc - Get the location of the Alignment token of this operand.
940   SMLoc getAlignmentLoc() const {
941     assert(Kind == k_Memory && "Invalid access!");
942     return AlignmentLoc;
943   }
944 
945   ARMCC::CondCodes getCondCode() const {
946     assert(Kind == k_CondCode && "Invalid access!");
947     return CC.Val;
948   }
949 
950   ARMVCC::VPTCodes getVPTPred() const {
951     assert(isVPTPred() && "Invalid access!");
952     return VCC.Val;
953   }
954 
955   unsigned getCoproc() const {
956     assert((Kind == k_CoprocNum || Kind == k_CoprocReg) && "Invalid access!");
957     return Cop.Val;
958   }
959 
960   StringRef getToken() const {
961     assert(Kind == k_Token && "Invalid access!");
962     return StringRef(Tok.Data, Tok.Length);
963   }
964 
965   unsigned getReg() const override {
966     assert((Kind == k_Register || Kind == k_CCOut) && "Invalid access!");
967     return Reg.RegNum;
968   }
969 
970   const SmallVectorImpl<unsigned> &getRegList() const {
971     assert((Kind == k_RegisterList || Kind == k_RegisterListWithAPSR ||
972             Kind == k_DPRRegisterList || Kind == k_SPRRegisterList ||
973             Kind == k_FPSRegisterListWithVPR ||
974             Kind == k_FPDRegisterListWithVPR) &&
975            "Invalid access!");
976     return Registers;
977   }
978 
979   const MCExpr *getImm() const {
980     assert(isImm() && "Invalid access!");
981     return Imm.Val;
982   }
983 
984   const MCExpr *getConstantPoolImm() const {
985     assert(isConstantPoolImm() && "Invalid access!");
986     return Imm.Val;
987   }
988 
989   unsigned getVectorIndex() const {
990     assert(Kind == k_VectorIndex && "Invalid access!");
991     return VectorIndex.Val;
992   }
993 
994   ARM_MB::MemBOpt getMemBarrierOpt() const {
995     assert(Kind == k_MemBarrierOpt && "Invalid access!");
996     return MBOpt.Val;
997   }
998 
999   ARM_ISB::InstSyncBOpt getInstSyncBarrierOpt() const {
1000     assert(Kind == k_InstSyncBarrierOpt && "Invalid access!");
1001     return ISBOpt.Val;
1002   }
1003 
1004   ARM_TSB::TraceSyncBOpt getTraceSyncBarrierOpt() const {
1005     assert(Kind == k_TraceSyncBarrierOpt && "Invalid access!");
1006     return TSBOpt.Val;
1007   }
1008 
1009   ARM_PROC::IFlags getProcIFlags() const {
1010     assert(Kind == k_ProcIFlags && "Invalid access!");
1011     return IFlags.Val;
1012   }
1013 
1014   unsigned getMSRMask() const {
1015     assert(Kind == k_MSRMask && "Invalid access!");
1016     return MMask.Val;
1017   }
1018 
1019   unsigned getBankedReg() const {
1020     assert(Kind == k_BankedReg && "Invalid access!");
1021     return BankedReg.Val;
1022   }
1023 
1024   bool isCoprocNum() const { return Kind == k_CoprocNum; }
1025   bool isCoprocReg() const { return Kind == k_CoprocReg; }
1026   bool isCoprocOption() const { return Kind == k_CoprocOption; }
1027   bool isCondCode() const { return Kind == k_CondCode; }
1028   bool isVPTPred() const { return Kind == k_VPTPred; }
1029   bool isCCOut() const { return Kind == k_CCOut; }
1030   bool isITMask() const { return Kind == k_ITCondMask; }
1031   bool isITCondCode() const { return Kind == k_CondCode; }
1032   bool isImm() const override {
1033     return Kind == k_Immediate;
1034   }
1035 
1036   bool isARMBranchTarget() const {
1037     if (!isImm()) return false;
1038 
1039     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm()))
1040       return CE->getValue() % 4 == 0;
1041     return true;
1042   }
1043 
1044 
1045   bool isThumbBranchTarget() const {
1046     if (!isImm()) return false;
1047 
1048     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm()))
1049       return CE->getValue() % 2 == 0;
1050     return true;
1051   }
1052 
1053   // checks whether this operand is an unsigned offset which fits is a field
1054   // of specified width and scaled by a specific number of bits
1055   template<unsigned width, unsigned scale>
1056   bool isUnsignedOffset() const {
1057     if (!isImm()) return false;
1058     if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
1059     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val)) {
1060       int64_t Val = CE->getValue();
1061       int64_t Align = 1LL << scale;
1062       int64_t Max = Align * ((1LL << width) - 1);
1063       return ((Val % Align) == 0) && (Val >= 0) && (Val <= Max);
1064     }
1065     return false;
1066   }
1067 
1068   // checks whether this operand is an signed offset which fits is a field
1069   // of specified width and scaled by a specific number of bits
1070   template<unsigned width, unsigned scale>
1071   bool isSignedOffset() const {
1072     if (!isImm()) return false;
1073     if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
1074     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val)) {
1075       int64_t Val = CE->getValue();
1076       int64_t Align = 1LL << scale;
1077       int64_t Max = Align * ((1LL << (width-1)) - 1);
1078       int64_t Min = -Align * (1LL << (width-1));
1079       return ((Val % Align) == 0) && (Val >= Min) && (Val <= Max);
1080     }
1081     return false;
1082   }
1083 
1084   // checks whether this operand is an offset suitable for the LE /
1085   // LETP instructions in Arm v8.1M
1086   bool isLEOffset() const {
1087     if (!isImm()) return false;
1088     if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
1089     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val)) {
1090       int64_t Val = CE->getValue();
1091       return Val < 0 && Val >= -4094 && (Val & 1) == 0;
1092     }
1093     return false;
1094   }
1095 
1096   // checks whether this operand is a memory operand computed as an offset
1097   // applied to PC. the offset may have 8 bits of magnitude and is represented
1098   // with two bits of shift. textually it may be either [pc, #imm], #imm or
1099   // relocable expression...
1100   bool isThumbMemPC() const {
1101     int64_t Val = 0;
1102     if (isImm()) {
1103       if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
1104       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val);
1105       if (!CE) return false;
1106       Val = CE->getValue();
1107     }
1108     else if (isGPRMem()) {
1109       if(!Memory.OffsetImm || Memory.OffsetRegNum) return false;
1110       if(Memory.BaseRegNum != ARM::PC) return false;
1111       if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm))
1112         Val = CE->getValue();
1113       else
1114         return false;
1115     }
1116     else return false;
1117     return ((Val % 4) == 0) && (Val >= 0) && (Val <= 1020);
1118   }
1119 
1120   bool isFPImm() const {
1121     if (!isImm()) return false;
1122     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1123     if (!CE) return false;
1124     int Val = ARM_AM::getFP32Imm(APInt(32, CE->getValue()));
1125     return Val != -1;
1126   }
1127 
1128   template<int64_t N, int64_t M>
1129   bool isImmediate() const {
1130     if (!isImm()) return false;
1131     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1132     if (!CE) return false;
1133     int64_t Value = CE->getValue();
1134     return Value >= N && Value <= M;
1135   }
1136 
1137   template<int64_t N, int64_t M>
1138   bool isImmediateS4() const {
1139     if (!isImm()) return false;
1140     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1141     if (!CE) return false;
1142     int64_t Value = CE->getValue();
1143     return ((Value & 3) == 0) && Value >= N && Value <= M;
1144   }
1145   template<int64_t N, int64_t M>
1146   bool isImmediateS2() const {
1147     if (!isImm()) return false;
1148     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1149     if (!CE) return false;
1150     int64_t Value = CE->getValue();
1151     return ((Value & 1) == 0) && Value >= N && Value <= M;
1152   }
1153   bool isFBits16() const {
1154     return isImmediate<0, 17>();
1155   }
1156   bool isFBits32() const {
1157     return isImmediate<1, 33>();
1158   }
1159   bool isImm8s4() const {
1160     return isImmediateS4<-1020, 1020>();
1161   }
1162   bool isImm7s4() const {
1163     return isImmediateS4<-508, 508>();
1164   }
1165   bool isImm7Shift0() const {
1166     return isImmediate<-127, 127>();
1167   }
1168   bool isImm7Shift1() const {
1169     return isImmediateS2<-255, 255>();
1170   }
1171   bool isImm7Shift2() const {
1172     return isImmediateS4<-511, 511>();
1173   }
1174   bool isImm7() const {
1175     return isImmediate<-127, 127>();
1176   }
1177   bool isImm0_1020s4() const {
1178     return isImmediateS4<0, 1020>();
1179   }
1180   bool isImm0_508s4() const {
1181     return isImmediateS4<0, 508>();
1182   }
1183   bool isImm0_508s4Neg() const {
1184     if (!isImm()) return false;
1185     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1186     if (!CE) return false;
1187     int64_t Value = -CE->getValue();
1188     // explicitly exclude zero. we want that to use the normal 0_508 version.
1189     return ((Value & 3) == 0) && Value > 0 && Value <= 508;
1190   }
1191 
1192   bool isImm0_4095Neg() const {
1193     if (!isImm()) return false;
1194     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1195     if (!CE) return false;
1196     // isImm0_4095Neg is used with 32-bit immediates only.
1197     // 32-bit immediates are zero extended to 64-bit when parsed,
1198     // thus simple -CE->getValue() results in a big negative number,
1199     // not a small positive number as intended
1200     if ((CE->getValue() >> 32) > 0) return false;
1201     uint32_t Value = -static_cast<uint32_t>(CE->getValue());
1202     return Value > 0 && Value < 4096;
1203   }
1204 
1205   bool isImm0_7() const {
1206     return isImmediate<0, 7>();
1207   }
1208 
1209   bool isImm1_16() const {
1210     return isImmediate<1, 16>();
1211   }
1212 
1213   bool isImm1_32() const {
1214     return isImmediate<1, 32>();
1215   }
1216 
1217   bool isImm8_255() const {
1218     return isImmediate<8, 255>();
1219   }
1220 
1221   bool isImm256_65535Expr() const {
1222     if (!isImm()) return false;
1223     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1224     // If it's not a constant expression, it'll generate a fixup and be
1225     // handled later.
1226     if (!CE) return true;
1227     int64_t Value = CE->getValue();
1228     return Value >= 256 && Value < 65536;
1229   }
1230 
1231   bool isImm0_65535Expr() const {
1232     if (!isImm()) return false;
1233     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1234     // If it's not a constant expression, it'll generate a fixup and be
1235     // handled later.
1236     if (!CE) return true;
1237     int64_t Value = CE->getValue();
1238     return Value >= 0 && Value < 65536;
1239   }
1240 
1241   bool isImm24bit() const {
1242     return isImmediate<0, 0xffffff + 1>();
1243   }
1244 
1245   bool isImmThumbSR() const {
1246     return isImmediate<1, 33>();
1247   }
1248 
1249   template<int shift>
1250   bool isExpImmValue(uint64_t Value) const {
1251     uint64_t mask = (1 << shift) - 1;
1252     if ((Value & mask) != 0 || (Value >> shift) > 0xff)
1253       return false;
1254     return true;
1255   }
1256 
1257   template<int shift>
1258   bool isExpImm() const {
1259     if (!isImm()) return false;
1260     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1261     if (!CE) return false;
1262 
1263     return isExpImmValue<shift>(CE->getValue());
1264   }
1265 
1266   template<int shift, int size>
1267   bool isInvertedExpImm() const {
1268     if (!isImm()) return false;
1269     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1270     if (!CE) return false;
1271 
1272     uint64_t OriginalValue = CE->getValue();
1273     uint64_t InvertedValue = OriginalValue ^ (((uint64_t)1 << size) - 1);
1274     return isExpImmValue<shift>(InvertedValue);
1275   }
1276 
1277   bool isPKHLSLImm() const {
1278     return isImmediate<0, 32>();
1279   }
1280 
1281   bool isPKHASRImm() const {
1282     return isImmediate<0, 33>();
1283   }
1284 
1285   bool isAdrLabel() const {
1286     // If we have an immediate that's not a constant, treat it as a label
1287     // reference needing a fixup.
1288     if (isImm() && !isa<MCConstantExpr>(getImm()))
1289       return true;
1290 
1291     // If it is a constant, it must fit into a modified immediate encoding.
1292     if (!isImm()) return false;
1293     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1294     if (!CE) return false;
1295     int64_t Value = CE->getValue();
1296     return (ARM_AM::getSOImmVal(Value) != -1 ||
1297             ARM_AM::getSOImmVal(-Value) != -1);
1298   }
1299 
1300   bool isT2SOImm() const {
1301     // If we have an immediate that's not a constant, treat it as an expression
1302     // needing a fixup.
1303     if (isImm() && !isa<MCConstantExpr>(getImm())) {
1304       // We want to avoid matching :upper16: and :lower16: as we want these
1305       // expressions to match in isImm0_65535Expr()
1306       const ARMMCExpr *ARM16Expr = dyn_cast<ARMMCExpr>(getImm());
1307       return (!ARM16Expr || (ARM16Expr->getKind() != ARMMCExpr::VK_ARM_HI16 &&
1308                              ARM16Expr->getKind() != ARMMCExpr::VK_ARM_LO16));
1309     }
1310     if (!isImm()) return false;
1311     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1312     if (!CE) return false;
1313     int64_t Value = CE->getValue();
1314     return ARM_AM::getT2SOImmVal(Value) != -1;
1315   }
1316 
1317   bool isT2SOImmNot() const {
1318     if (!isImm()) return false;
1319     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1320     if (!CE) return false;
1321     int64_t Value = CE->getValue();
1322     return ARM_AM::getT2SOImmVal(Value) == -1 &&
1323       ARM_AM::getT2SOImmVal(~Value) != -1;
1324   }
1325 
1326   bool isT2SOImmNeg() const {
1327     if (!isImm()) return false;
1328     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1329     if (!CE) return false;
1330     int64_t Value = CE->getValue();
1331     // Only use this when not representable as a plain so_imm.
1332     return ARM_AM::getT2SOImmVal(Value) == -1 &&
1333       ARM_AM::getT2SOImmVal(-Value) != -1;
1334   }
1335 
1336   bool isSetEndImm() const {
1337     if (!isImm()) return false;
1338     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1339     if (!CE) return false;
1340     int64_t Value = CE->getValue();
1341     return Value == 1 || Value == 0;
1342   }
1343 
1344   bool isReg() const override { return Kind == k_Register; }
1345   bool isRegList() const { return Kind == k_RegisterList; }
1346   bool isRegListWithAPSR() const {
1347     return Kind == k_RegisterListWithAPSR || Kind == k_RegisterList;
1348   }
1349   bool isDPRRegList() const { return Kind == k_DPRRegisterList; }
1350   bool isSPRRegList() const { return Kind == k_SPRRegisterList; }
1351   bool isFPSRegListWithVPR() const { return Kind == k_FPSRegisterListWithVPR; }
1352   bool isFPDRegListWithVPR() const { return Kind == k_FPDRegisterListWithVPR; }
1353   bool isToken() const override { return Kind == k_Token; }
1354   bool isMemBarrierOpt() const { return Kind == k_MemBarrierOpt; }
1355   bool isInstSyncBarrierOpt() const { return Kind == k_InstSyncBarrierOpt; }
1356   bool isTraceSyncBarrierOpt() const { return Kind == k_TraceSyncBarrierOpt; }
1357   bool isMem() const override {
1358       return isGPRMem() || isMVEMem();
1359   }
1360   bool isMVEMem() const {
1361     if (Kind != k_Memory)
1362       return false;
1363     if (Memory.BaseRegNum &&
1364         !ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Memory.BaseRegNum) &&
1365         !ARMMCRegisterClasses[ARM::MQPRRegClassID].contains(Memory.BaseRegNum))
1366       return false;
1367     if (Memory.OffsetRegNum &&
1368         !ARMMCRegisterClasses[ARM::MQPRRegClassID].contains(
1369             Memory.OffsetRegNum))
1370       return false;
1371     return true;
1372   }
1373   bool isGPRMem() const {
1374     if (Kind != k_Memory)
1375       return false;
1376     if (Memory.BaseRegNum &&
1377         !ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Memory.BaseRegNum))
1378       return false;
1379     if (Memory.OffsetRegNum &&
1380         !ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Memory.OffsetRegNum))
1381       return false;
1382     return true;
1383   }
1384   bool isShifterImm() const { return Kind == k_ShifterImmediate; }
1385   bool isRegShiftedReg() const {
1386     return Kind == k_ShiftedRegister &&
1387            ARMMCRegisterClasses[ARM::GPRRegClassID].contains(
1388                RegShiftedReg.SrcReg) &&
1389            ARMMCRegisterClasses[ARM::GPRRegClassID].contains(
1390                RegShiftedReg.ShiftReg);
1391   }
1392   bool isRegShiftedImm() const {
1393     return Kind == k_ShiftedImmediate &&
1394            ARMMCRegisterClasses[ARM::GPRRegClassID].contains(
1395                RegShiftedImm.SrcReg);
1396   }
1397   bool isRotImm() const { return Kind == k_RotateImmediate; }
1398 
1399   template<unsigned Min, unsigned Max>
1400   bool isPowerTwoInRange() const {
1401     if (!isImm()) return false;
1402     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1403     if (!CE) return false;
1404     int64_t Value = CE->getValue();
1405     return Value > 0 && countPopulation((uint64_t)Value) == 1 &&
1406            Value >= Min && Value <= Max;
1407   }
1408   bool isModImm() const { return Kind == k_ModifiedImmediate; }
1409 
1410   bool isModImmNot() const {
1411     if (!isImm()) return false;
1412     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1413     if (!CE) return false;
1414     int64_t Value = CE->getValue();
1415     return ARM_AM::getSOImmVal(~Value) != -1;
1416   }
1417 
1418   bool isModImmNeg() const {
1419     if (!isImm()) return false;
1420     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1421     if (!CE) return false;
1422     int64_t Value = CE->getValue();
1423     return ARM_AM::getSOImmVal(Value) == -1 &&
1424       ARM_AM::getSOImmVal(-Value) != -1;
1425   }
1426 
1427   bool isThumbModImmNeg1_7() const {
1428     if (!isImm()) return false;
1429     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1430     if (!CE) return false;
1431     int32_t Value = -(int32_t)CE->getValue();
1432     return 0 < Value && Value < 8;
1433   }
1434 
1435   bool isThumbModImmNeg8_255() const {
1436     if (!isImm()) return false;
1437     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1438     if (!CE) return false;
1439     int32_t Value = -(int32_t)CE->getValue();
1440     return 7 < Value && Value < 256;
1441   }
1442 
1443   bool isConstantPoolImm() const { return Kind == k_ConstantPoolImmediate; }
1444   bool isBitfield() const { return Kind == k_BitfieldDescriptor; }
1445   bool isPostIdxRegShifted() const {
1446     return Kind == k_PostIndexRegister &&
1447            ARMMCRegisterClasses[ARM::GPRRegClassID].contains(PostIdxReg.RegNum);
1448   }
1449   bool isPostIdxReg() const {
1450     return isPostIdxRegShifted() && PostIdxReg.ShiftTy == ARM_AM::no_shift;
1451   }
1452   bool isMemNoOffset(bool alignOK = false, unsigned Alignment = 0) const {
1453     if (!isGPRMem())
1454       return false;
1455     // No offset of any kind.
1456     return Memory.OffsetRegNum == 0 && Memory.OffsetImm == nullptr &&
1457      (alignOK || Memory.Alignment == Alignment);
1458   }
1459   bool isMemNoOffsetT2(bool alignOK = false, unsigned Alignment = 0) const {
1460     if (!isGPRMem())
1461       return false;
1462 
1463     if (!ARMMCRegisterClasses[ARM::GPRnopcRegClassID].contains(
1464             Memory.BaseRegNum))
1465       return false;
1466 
1467     // No offset of any kind.
1468     return Memory.OffsetRegNum == 0 && Memory.OffsetImm == nullptr &&
1469      (alignOK || Memory.Alignment == Alignment);
1470   }
1471   bool isMemNoOffsetT2NoSp(bool alignOK = false, unsigned Alignment = 0) const {
1472     if (!isGPRMem())
1473       return false;
1474 
1475     if (!ARMMCRegisterClasses[ARM::rGPRRegClassID].contains(
1476             Memory.BaseRegNum))
1477       return false;
1478 
1479     // No offset of any kind.
1480     return Memory.OffsetRegNum == 0 && Memory.OffsetImm == nullptr &&
1481      (alignOK || Memory.Alignment == Alignment);
1482   }
1483   bool isMemNoOffsetT(bool alignOK = false, unsigned Alignment = 0) const {
1484     if (!isGPRMem())
1485       return false;
1486 
1487     if (!ARMMCRegisterClasses[ARM::tGPRRegClassID].contains(
1488             Memory.BaseRegNum))
1489       return false;
1490 
1491     // No offset of any kind.
1492     return Memory.OffsetRegNum == 0 && Memory.OffsetImm == nullptr &&
1493      (alignOK || Memory.Alignment == Alignment);
1494   }
1495   bool isMemPCRelImm12() const {
1496     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1497       return false;
1498     // Base register must be PC.
1499     if (Memory.BaseRegNum != ARM::PC)
1500       return false;
1501     // Immediate offset in range [-4095, 4095].
1502     if (!Memory.OffsetImm) return true;
1503     if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
1504       int64_t Val = CE->getValue();
1505       return (Val > -4096 && Val < 4096) ||
1506              (Val == std::numeric_limits<int32_t>::min());
1507     }
1508     return false;
1509   }
1510 
1511   bool isAlignedMemory() const {
1512     return isMemNoOffset(true);
1513   }
1514 
1515   bool isAlignedMemoryNone() const {
1516     return isMemNoOffset(false, 0);
1517   }
1518 
1519   bool isDupAlignedMemoryNone() const {
1520     return isMemNoOffset(false, 0);
1521   }
1522 
1523   bool isAlignedMemory16() const {
1524     if (isMemNoOffset(false, 2)) // alignment in bytes for 16-bits is 2.
1525       return true;
1526     return isMemNoOffset(false, 0);
1527   }
1528 
1529   bool isDupAlignedMemory16() const {
1530     if (isMemNoOffset(false, 2)) // alignment in bytes for 16-bits is 2.
1531       return true;
1532     return isMemNoOffset(false, 0);
1533   }
1534 
1535   bool isAlignedMemory32() const {
1536     if (isMemNoOffset(false, 4)) // alignment in bytes for 32-bits is 4.
1537       return true;
1538     return isMemNoOffset(false, 0);
1539   }
1540 
1541   bool isDupAlignedMemory32() const {
1542     if (isMemNoOffset(false, 4)) // alignment in bytes for 32-bits is 4.
1543       return true;
1544     return isMemNoOffset(false, 0);
1545   }
1546 
1547   bool isAlignedMemory64() const {
1548     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1549       return true;
1550     return isMemNoOffset(false, 0);
1551   }
1552 
1553   bool isDupAlignedMemory64() const {
1554     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1555       return true;
1556     return isMemNoOffset(false, 0);
1557   }
1558 
1559   bool isAlignedMemory64or128() const {
1560     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1561       return true;
1562     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1563       return true;
1564     return isMemNoOffset(false, 0);
1565   }
1566 
1567   bool isDupAlignedMemory64or128() const {
1568     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1569       return true;
1570     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1571       return true;
1572     return isMemNoOffset(false, 0);
1573   }
1574 
1575   bool isAlignedMemory64or128or256() const {
1576     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1577       return true;
1578     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1579       return true;
1580     if (isMemNoOffset(false, 32)) // alignment in bytes for 256-bits is 32.
1581       return true;
1582     return isMemNoOffset(false, 0);
1583   }
1584 
1585   bool isAddrMode2() const {
1586     if (!isGPRMem() || Memory.Alignment != 0) return false;
1587     // Check for register offset.
1588     if (Memory.OffsetRegNum) return true;
1589     // Immediate offset in range [-4095, 4095].
1590     if (!Memory.OffsetImm) return true;
1591     if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
1592       int64_t Val = CE->getValue();
1593       return Val > -4096 && Val < 4096;
1594     }
1595     return false;
1596   }
1597 
1598   bool isAM2OffsetImm() const {
1599     if (!isImm()) return false;
1600     // Immediate offset in range [-4095, 4095].
1601     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1602     if (!CE) return false;
1603     int64_t Val = CE->getValue();
1604     return (Val == std::numeric_limits<int32_t>::min()) ||
1605            (Val > -4096 && Val < 4096);
1606   }
1607 
1608   bool isAddrMode3() const {
1609     // If we have an immediate that's not a constant, treat it as a label
1610     // reference needing a fixup. If it is a constant, it's something else
1611     // and we reject it.
1612     if (isImm() && !isa<MCConstantExpr>(getImm()))
1613       return true;
1614     if (!isGPRMem() || Memory.Alignment != 0) return false;
1615     // No shifts are legal for AM3.
1616     if (Memory.ShiftType != ARM_AM::no_shift) return false;
1617     // Check for register offset.
1618     if (Memory.OffsetRegNum) return true;
1619     // Immediate offset in range [-255, 255].
1620     if (!Memory.OffsetImm) return true;
1621     if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
1622       int64_t Val = CE->getValue();
1623       // The #-0 offset is encoded as std::numeric_limits<int32_t>::min(), and
1624       // we have to check for this too.
1625       return (Val > -256 && Val < 256) ||
1626              Val == std::numeric_limits<int32_t>::min();
1627     }
1628     return false;
1629   }
1630 
1631   bool isAM3Offset() const {
1632     if (isPostIdxReg())
1633       return true;
1634     if (!isImm())
1635       return false;
1636     // Immediate offset in range [-255, 255].
1637     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1638     if (!CE) return false;
1639     int64_t Val = CE->getValue();
1640     // Special case, #-0 is std::numeric_limits<int32_t>::min().
1641     return (Val > -256 && Val < 256) ||
1642            Val == std::numeric_limits<int32_t>::min();
1643   }
1644 
1645   bool isAddrMode5() const {
1646     // If we have an immediate that's not a constant, treat it as a label
1647     // reference needing a fixup. If it is a constant, it's something else
1648     // and we reject it.
1649     if (isImm() && !isa<MCConstantExpr>(getImm()))
1650       return true;
1651     if (!isGPRMem() || Memory.Alignment != 0) return false;
1652     // Check for register offset.
1653     if (Memory.OffsetRegNum) return false;
1654     // Immediate offset in range [-1020, 1020] and a multiple of 4.
1655     if (!Memory.OffsetImm) return true;
1656     if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
1657       int64_t Val = CE->getValue();
1658       return (Val >= -1020 && Val <= 1020 && ((Val & 3) == 0)) ||
1659              Val == std::numeric_limits<int32_t>::min();
1660     }
1661     return false;
1662   }
1663 
1664   bool isAddrMode5FP16() const {
1665     // If we have an immediate that's not a constant, treat it as a label
1666     // reference needing a fixup. If it is a constant, it's something else
1667     // and we reject it.
1668     if (isImm() && !isa<MCConstantExpr>(getImm()))
1669       return true;
1670     if (!isGPRMem() || Memory.Alignment != 0) return false;
1671     // Check for register offset.
1672     if (Memory.OffsetRegNum) return false;
1673     // Immediate offset in range [-510, 510] and a multiple of 2.
1674     if (!Memory.OffsetImm) return true;
1675     if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
1676       int64_t Val = CE->getValue();
1677       return (Val >= -510 && Val <= 510 && ((Val & 1) == 0)) ||
1678              Val == std::numeric_limits<int32_t>::min();
1679     }
1680     return false;
1681   }
1682 
1683   bool isMemTBB() const {
1684     if (!isGPRMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1685         Memory.ShiftType != ARM_AM::no_shift || Memory.Alignment != 0)
1686       return false;
1687     return true;
1688   }
1689 
1690   bool isMemTBH() const {
1691     if (!isGPRMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1692         Memory.ShiftType != ARM_AM::lsl || Memory.ShiftImm != 1 ||
1693         Memory.Alignment != 0 )
1694       return false;
1695     return true;
1696   }
1697 
1698   bool isMemRegOffset() const {
1699     if (!isGPRMem() || !Memory.OffsetRegNum || Memory.Alignment != 0)
1700       return false;
1701     return true;
1702   }
1703 
1704   bool isT2MemRegOffset() const {
1705     if (!isGPRMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1706         Memory.Alignment != 0 || Memory.BaseRegNum == ARM::PC)
1707       return false;
1708     // Only lsl #{0, 1, 2, 3} allowed.
1709     if (Memory.ShiftType == ARM_AM::no_shift)
1710       return true;
1711     if (Memory.ShiftType != ARM_AM::lsl || Memory.ShiftImm > 3)
1712       return false;
1713     return true;
1714   }
1715 
1716   bool isMemThumbRR() const {
1717     // Thumb reg+reg addressing is simple. Just two registers, a base and
1718     // an offset. No shifts, negations or any other complicating factors.
1719     if (!isGPRMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1720         Memory.ShiftType != ARM_AM::no_shift || Memory.Alignment != 0)
1721       return false;
1722     return isARMLowRegister(Memory.BaseRegNum) &&
1723       (!Memory.OffsetRegNum || isARMLowRegister(Memory.OffsetRegNum));
1724   }
1725 
1726   bool isMemThumbRIs4() const {
1727     if (!isGPRMem() || Memory.OffsetRegNum != 0 ||
1728         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1729       return false;
1730     // Immediate offset, multiple of 4 in range [0, 124].
1731     if (!Memory.OffsetImm) return true;
1732     if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
1733       int64_t Val = CE->getValue();
1734       return Val >= 0 && Val <= 124 && (Val % 4) == 0;
1735     }
1736     return false;
1737   }
1738 
1739   bool isMemThumbRIs2() const {
1740     if (!isGPRMem() || Memory.OffsetRegNum != 0 ||
1741         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1742       return false;
1743     // Immediate offset, multiple of 4 in range [0, 62].
1744     if (!Memory.OffsetImm) return true;
1745     if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
1746       int64_t Val = CE->getValue();
1747       return Val >= 0 && Val <= 62 && (Val % 2) == 0;
1748     }
1749     return false;
1750   }
1751 
1752   bool isMemThumbRIs1() const {
1753     if (!isGPRMem() || Memory.OffsetRegNum != 0 ||
1754         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1755       return false;
1756     // Immediate offset in range [0, 31].
1757     if (!Memory.OffsetImm) return true;
1758     if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
1759       int64_t Val = CE->getValue();
1760       return Val >= 0 && Val <= 31;
1761     }
1762     return false;
1763   }
1764 
1765   bool isMemThumbSPI() const {
1766     if (!isGPRMem() || Memory.OffsetRegNum != 0 ||
1767         Memory.BaseRegNum != ARM::SP || Memory.Alignment != 0)
1768       return false;
1769     // Immediate offset, multiple of 4 in range [0, 1020].
1770     if (!Memory.OffsetImm) return true;
1771     if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
1772       int64_t Val = CE->getValue();
1773       return Val >= 0 && Val <= 1020 && (Val % 4) == 0;
1774     }
1775     return false;
1776   }
1777 
1778   bool isMemImm8s4Offset() const {
1779     // If we have an immediate that's not a constant, treat it as a label
1780     // reference needing a fixup. If it is a constant, it's something else
1781     // and we reject it.
1782     if (isImm() && !isa<MCConstantExpr>(getImm()))
1783       return true;
1784     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1785       return false;
1786     // Immediate offset a multiple of 4 in range [-1020, 1020].
1787     if (!Memory.OffsetImm) return true;
1788     if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
1789       int64_t Val = CE->getValue();
1790       // Special case, #-0 is std::numeric_limits<int32_t>::min().
1791       return (Val >= -1020 && Val <= 1020 && (Val & 3) == 0) ||
1792              Val == std::numeric_limits<int32_t>::min();
1793     }
1794     return false;
1795   }
1796 
1797   bool isMemImm7s4Offset() const {
1798     // If we have an immediate that's not a constant, treat it as a label
1799     // reference needing a fixup. If it is a constant, it's something else
1800     // and we reject it.
1801     if (isImm() && !isa<MCConstantExpr>(getImm()))
1802       return true;
1803     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0 ||
1804         !ARMMCRegisterClasses[ARM::GPRnopcRegClassID].contains(
1805             Memory.BaseRegNum))
1806       return false;
1807     // Immediate offset a multiple of 4 in range [-508, 508].
1808     if (!Memory.OffsetImm) return true;
1809     if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
1810       int64_t Val = CE->getValue();
1811       // Special case, #-0 is INT32_MIN.
1812       return (Val >= -508 && Val <= 508 && (Val & 3) == 0) || Val == INT32_MIN;
1813     }
1814     return false;
1815   }
1816 
1817   bool isMemImm0_1020s4Offset() const {
1818     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1819       return false;
1820     // Immediate offset a multiple of 4 in range [0, 1020].
1821     if (!Memory.OffsetImm) return true;
1822     if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
1823       int64_t Val = CE->getValue();
1824       return Val >= 0 && Val <= 1020 && (Val & 3) == 0;
1825     }
1826     return false;
1827   }
1828 
1829   bool isMemImm8Offset() const {
1830     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1831       return false;
1832     // Base reg of PC isn't allowed for these encodings.
1833     if (Memory.BaseRegNum == ARM::PC) return false;
1834     // Immediate offset in range [-255, 255].
1835     if (!Memory.OffsetImm) return true;
1836     if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
1837       int64_t Val = CE->getValue();
1838       return (Val == std::numeric_limits<int32_t>::min()) ||
1839              (Val > -256 && Val < 256);
1840     }
1841     return false;
1842   }
1843 
1844   template<unsigned Bits, unsigned RegClassID>
1845   bool isMemImm7ShiftedOffset() const {
1846     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0 ||
1847         !ARMMCRegisterClasses[RegClassID].contains(Memory.BaseRegNum))
1848       return false;
1849 
1850     // Expect an immediate offset equal to an element of the range
1851     // [-127, 127], shifted left by Bits.
1852 
1853     if (!Memory.OffsetImm) return true;
1854     if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
1855       int64_t Val = CE->getValue();
1856 
1857       // INT32_MIN is a special-case value (indicating the encoding with
1858       // zero offset and the subtract bit set)
1859       if (Val == INT32_MIN)
1860         return true;
1861 
1862       unsigned Divisor = 1U << Bits;
1863 
1864       // Check that the low bits are zero
1865       if (Val % Divisor != 0)
1866         return false;
1867 
1868       // Check that the remaining offset is within range.
1869       Val /= Divisor;
1870       return (Val >= -127 && Val <= 127);
1871     }
1872     return false;
1873   }
1874 
1875   template <int shift> bool isMemRegRQOffset() const {
1876     if (!isMVEMem() || Memory.OffsetImm != 0 || Memory.Alignment != 0)
1877       return false;
1878 
1879     if (!ARMMCRegisterClasses[ARM::GPRnopcRegClassID].contains(
1880             Memory.BaseRegNum))
1881       return false;
1882     if (!ARMMCRegisterClasses[ARM::MQPRRegClassID].contains(
1883             Memory.OffsetRegNum))
1884       return false;
1885 
1886     if (shift == 0 && Memory.ShiftType != ARM_AM::no_shift)
1887       return false;
1888 
1889     if (shift > 0 &&
1890         (Memory.ShiftType != ARM_AM::uxtw || Memory.ShiftImm != shift))
1891       return false;
1892 
1893     return true;
1894   }
1895 
1896   template <int shift> bool isMemRegQOffset() const {
1897     if (!isMVEMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1898       return false;
1899 
1900     if (!ARMMCRegisterClasses[ARM::MQPRRegClassID].contains(
1901             Memory.BaseRegNum))
1902       return false;
1903 
1904     if (!Memory.OffsetImm)
1905       return true;
1906     static_assert(shift < 56,
1907                   "Such that we dont shift by a value higher than 62");
1908     if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
1909       int64_t Val = CE->getValue();
1910 
1911       // The value must be a multiple of (1 << shift)
1912       if ((Val & ((1U << shift) - 1)) != 0)
1913         return false;
1914 
1915       // And be in the right range, depending on the amount that it is shifted
1916       // by.  Shift 0, is equal to 7 unsigned bits, the sign bit is set
1917       // separately.
1918       int64_t Range = (1U << (7 + shift)) - 1;
1919       return (Val == INT32_MIN) || (Val > -Range && Val < Range);
1920     }
1921     return false;
1922   }
1923 
1924   bool isMemPosImm8Offset() const {
1925     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1926       return false;
1927     // Immediate offset in range [0, 255].
1928     if (!Memory.OffsetImm) return true;
1929     if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
1930       int64_t Val = CE->getValue();
1931       return Val >= 0 && Val < 256;
1932     }
1933     return false;
1934   }
1935 
1936   bool isMemNegImm8Offset() const {
1937     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1938       return false;
1939     // Base reg of PC isn't allowed for these encodings.
1940     if (Memory.BaseRegNum == ARM::PC) return false;
1941     // Immediate offset in range [-255, -1].
1942     if (!Memory.OffsetImm) return false;
1943     if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
1944       int64_t Val = CE->getValue();
1945       return (Val == std::numeric_limits<int32_t>::min()) ||
1946              (Val > -256 && Val < 0);
1947     }
1948     return false;
1949   }
1950 
1951   bool isMemUImm12Offset() const {
1952     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1953       return false;
1954     // Immediate offset in range [0, 4095].
1955     if (!Memory.OffsetImm) return true;
1956     if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
1957       int64_t Val = CE->getValue();
1958       return (Val >= 0 && Val < 4096);
1959     }
1960     return false;
1961   }
1962 
1963   bool isMemImm12Offset() const {
1964     // If we have an immediate that's not a constant, treat it as a label
1965     // reference needing a fixup. If it is a constant, it's something else
1966     // and we reject it.
1967 
1968     if (isImm() && !isa<MCConstantExpr>(getImm()))
1969       return true;
1970 
1971     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1972       return false;
1973     // Immediate offset in range [-4095, 4095].
1974     if (!Memory.OffsetImm) return true;
1975     if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
1976       int64_t Val = CE->getValue();
1977       return (Val > -4096 && Val < 4096) ||
1978              (Val == std::numeric_limits<int32_t>::min());
1979     }
1980     // If we have an immediate that's not a constant, treat it as a
1981     // symbolic expression needing a fixup.
1982     return true;
1983   }
1984 
1985   bool isConstPoolAsmImm() const {
1986     // Delay processing of Constant Pool Immediate, this will turn into
1987     // a constant. Match no other operand
1988     return (isConstantPoolImm());
1989   }
1990 
1991   bool isPostIdxImm8() const {
1992     if (!isImm()) return false;
1993     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1994     if (!CE) return false;
1995     int64_t Val = CE->getValue();
1996     return (Val > -256 && Val < 256) ||
1997            (Val == std::numeric_limits<int32_t>::min());
1998   }
1999 
2000   bool isPostIdxImm8s4() const {
2001     if (!isImm()) return false;
2002     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2003     if (!CE) return false;
2004     int64_t Val = CE->getValue();
2005     return ((Val & 3) == 0 && Val >= -1020 && Val <= 1020) ||
2006            (Val == std::numeric_limits<int32_t>::min());
2007   }
2008 
2009   bool isMSRMask() const { return Kind == k_MSRMask; }
2010   bool isBankedReg() const { return Kind == k_BankedReg; }
2011   bool isProcIFlags() const { return Kind == k_ProcIFlags; }
2012 
2013   // NEON operands.
2014   bool isSingleSpacedVectorList() const {
2015     return Kind == k_VectorList && !VectorList.isDoubleSpaced;
2016   }
2017 
2018   bool isDoubleSpacedVectorList() const {
2019     return Kind == k_VectorList && VectorList.isDoubleSpaced;
2020   }
2021 
2022   bool isVecListOneD() const {
2023     if (!isSingleSpacedVectorList()) return false;
2024     return VectorList.Count == 1;
2025   }
2026 
2027   bool isVecListTwoMQ() const {
2028     return isSingleSpacedVectorList() && VectorList.Count == 2 &&
2029            ARMMCRegisterClasses[ARM::MQPRRegClassID].contains(
2030                VectorList.RegNum);
2031   }
2032 
2033   bool isVecListDPair() const {
2034     if (!isSingleSpacedVectorList()) return false;
2035     return (ARMMCRegisterClasses[ARM::DPairRegClassID]
2036               .contains(VectorList.RegNum));
2037   }
2038 
2039   bool isVecListThreeD() const {
2040     if (!isSingleSpacedVectorList()) return false;
2041     return VectorList.Count == 3;
2042   }
2043 
2044   bool isVecListFourD() const {
2045     if (!isSingleSpacedVectorList()) return false;
2046     return VectorList.Count == 4;
2047   }
2048 
2049   bool isVecListDPairSpaced() const {
2050     if (Kind != k_VectorList) return false;
2051     if (isSingleSpacedVectorList()) return false;
2052     return (ARMMCRegisterClasses[ARM::DPairSpcRegClassID]
2053               .contains(VectorList.RegNum));
2054   }
2055 
2056   bool isVecListThreeQ() const {
2057     if (!isDoubleSpacedVectorList()) return false;
2058     return VectorList.Count == 3;
2059   }
2060 
2061   bool isVecListFourQ() const {
2062     if (!isDoubleSpacedVectorList()) return false;
2063     return VectorList.Count == 4;
2064   }
2065 
2066   bool isVecListFourMQ() const {
2067     return isSingleSpacedVectorList() && VectorList.Count == 4 &&
2068            ARMMCRegisterClasses[ARM::MQPRRegClassID].contains(
2069                VectorList.RegNum);
2070   }
2071 
2072   bool isSingleSpacedVectorAllLanes() const {
2073     return Kind == k_VectorListAllLanes && !VectorList.isDoubleSpaced;
2074   }
2075 
2076   bool isDoubleSpacedVectorAllLanes() const {
2077     return Kind == k_VectorListAllLanes && VectorList.isDoubleSpaced;
2078   }
2079 
2080   bool isVecListOneDAllLanes() const {
2081     if (!isSingleSpacedVectorAllLanes()) return false;
2082     return VectorList.Count == 1;
2083   }
2084 
2085   bool isVecListDPairAllLanes() const {
2086     if (!isSingleSpacedVectorAllLanes()) return false;
2087     return (ARMMCRegisterClasses[ARM::DPairRegClassID]
2088               .contains(VectorList.RegNum));
2089   }
2090 
2091   bool isVecListDPairSpacedAllLanes() const {
2092     if (!isDoubleSpacedVectorAllLanes()) return false;
2093     return VectorList.Count == 2;
2094   }
2095 
2096   bool isVecListThreeDAllLanes() const {
2097     if (!isSingleSpacedVectorAllLanes()) return false;
2098     return VectorList.Count == 3;
2099   }
2100 
2101   bool isVecListThreeQAllLanes() const {
2102     if (!isDoubleSpacedVectorAllLanes()) return false;
2103     return VectorList.Count == 3;
2104   }
2105 
2106   bool isVecListFourDAllLanes() const {
2107     if (!isSingleSpacedVectorAllLanes()) return false;
2108     return VectorList.Count == 4;
2109   }
2110 
2111   bool isVecListFourQAllLanes() const {
2112     if (!isDoubleSpacedVectorAllLanes()) return false;
2113     return VectorList.Count == 4;
2114   }
2115 
2116   bool isSingleSpacedVectorIndexed() const {
2117     return Kind == k_VectorListIndexed && !VectorList.isDoubleSpaced;
2118   }
2119 
2120   bool isDoubleSpacedVectorIndexed() const {
2121     return Kind == k_VectorListIndexed && VectorList.isDoubleSpaced;
2122   }
2123 
2124   bool isVecListOneDByteIndexed() const {
2125     if (!isSingleSpacedVectorIndexed()) return false;
2126     return VectorList.Count == 1 && VectorList.LaneIndex <= 7;
2127   }
2128 
2129   bool isVecListOneDHWordIndexed() const {
2130     if (!isSingleSpacedVectorIndexed()) return false;
2131     return VectorList.Count == 1 && VectorList.LaneIndex <= 3;
2132   }
2133 
2134   bool isVecListOneDWordIndexed() const {
2135     if (!isSingleSpacedVectorIndexed()) return false;
2136     return VectorList.Count == 1 && VectorList.LaneIndex <= 1;
2137   }
2138 
2139   bool isVecListTwoDByteIndexed() const {
2140     if (!isSingleSpacedVectorIndexed()) return false;
2141     return VectorList.Count == 2 && VectorList.LaneIndex <= 7;
2142   }
2143 
2144   bool isVecListTwoDHWordIndexed() const {
2145     if (!isSingleSpacedVectorIndexed()) return false;
2146     return VectorList.Count == 2 && VectorList.LaneIndex <= 3;
2147   }
2148 
2149   bool isVecListTwoQWordIndexed() const {
2150     if (!isDoubleSpacedVectorIndexed()) return false;
2151     return VectorList.Count == 2 && VectorList.LaneIndex <= 1;
2152   }
2153 
2154   bool isVecListTwoQHWordIndexed() const {
2155     if (!isDoubleSpacedVectorIndexed()) return false;
2156     return VectorList.Count == 2 && VectorList.LaneIndex <= 3;
2157   }
2158 
2159   bool isVecListTwoDWordIndexed() const {
2160     if (!isSingleSpacedVectorIndexed()) return false;
2161     return VectorList.Count == 2 && VectorList.LaneIndex <= 1;
2162   }
2163 
2164   bool isVecListThreeDByteIndexed() const {
2165     if (!isSingleSpacedVectorIndexed()) return false;
2166     return VectorList.Count == 3 && VectorList.LaneIndex <= 7;
2167   }
2168 
2169   bool isVecListThreeDHWordIndexed() const {
2170     if (!isSingleSpacedVectorIndexed()) return false;
2171     return VectorList.Count == 3 && VectorList.LaneIndex <= 3;
2172   }
2173 
2174   bool isVecListThreeQWordIndexed() const {
2175     if (!isDoubleSpacedVectorIndexed()) return false;
2176     return VectorList.Count == 3 && VectorList.LaneIndex <= 1;
2177   }
2178 
2179   bool isVecListThreeQHWordIndexed() const {
2180     if (!isDoubleSpacedVectorIndexed()) return false;
2181     return VectorList.Count == 3 && VectorList.LaneIndex <= 3;
2182   }
2183 
2184   bool isVecListThreeDWordIndexed() const {
2185     if (!isSingleSpacedVectorIndexed()) return false;
2186     return VectorList.Count == 3 && VectorList.LaneIndex <= 1;
2187   }
2188 
2189   bool isVecListFourDByteIndexed() const {
2190     if (!isSingleSpacedVectorIndexed()) return false;
2191     return VectorList.Count == 4 && VectorList.LaneIndex <= 7;
2192   }
2193 
2194   bool isVecListFourDHWordIndexed() const {
2195     if (!isSingleSpacedVectorIndexed()) return false;
2196     return VectorList.Count == 4 && VectorList.LaneIndex <= 3;
2197   }
2198 
2199   bool isVecListFourQWordIndexed() const {
2200     if (!isDoubleSpacedVectorIndexed()) return false;
2201     return VectorList.Count == 4 && VectorList.LaneIndex <= 1;
2202   }
2203 
2204   bool isVecListFourQHWordIndexed() const {
2205     if (!isDoubleSpacedVectorIndexed()) return false;
2206     return VectorList.Count == 4 && VectorList.LaneIndex <= 3;
2207   }
2208 
2209   bool isVecListFourDWordIndexed() const {
2210     if (!isSingleSpacedVectorIndexed()) return false;
2211     return VectorList.Count == 4 && VectorList.LaneIndex <= 1;
2212   }
2213 
2214   bool isVectorIndex() const { return Kind == k_VectorIndex; }
2215 
2216   template <unsigned NumLanes>
2217   bool isVectorIndexInRange() const {
2218     if (Kind != k_VectorIndex) return false;
2219     return VectorIndex.Val < NumLanes;
2220   }
2221 
2222   bool isVectorIndex8()  const { return isVectorIndexInRange<8>(); }
2223   bool isVectorIndex16() const { return isVectorIndexInRange<4>(); }
2224   bool isVectorIndex32() const { return isVectorIndexInRange<2>(); }
2225   bool isVectorIndex64() const { return isVectorIndexInRange<1>(); }
2226 
2227   template<int PermittedValue, int OtherPermittedValue>
2228   bool isMVEPairVectorIndex() const {
2229     if (Kind != k_VectorIndex) return false;
2230     return VectorIndex.Val == PermittedValue ||
2231            VectorIndex.Val == OtherPermittedValue;
2232   }
2233 
2234   bool isNEONi8splat() const {
2235     if (!isImm()) return false;
2236     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2237     // Must be a constant.
2238     if (!CE) return false;
2239     int64_t Value = CE->getValue();
2240     // i8 value splatted across 8 bytes. The immediate is just the 8 byte
2241     // value.
2242     return Value >= 0 && Value < 256;
2243   }
2244 
2245   bool isNEONi16splat() const {
2246     if (isNEONByteReplicate(2))
2247       return false; // Leave that for bytes replication and forbid by default.
2248     if (!isImm())
2249       return false;
2250     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2251     // Must be a constant.
2252     if (!CE) return false;
2253     unsigned Value = CE->getValue();
2254     return ARM_AM::isNEONi16splat(Value);
2255   }
2256 
2257   bool isNEONi16splatNot() const {
2258     if (!isImm())
2259       return false;
2260     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2261     // Must be a constant.
2262     if (!CE) return false;
2263     unsigned Value = CE->getValue();
2264     return ARM_AM::isNEONi16splat(~Value & 0xffff);
2265   }
2266 
2267   bool isNEONi32splat() const {
2268     if (isNEONByteReplicate(4))
2269       return false; // Leave that for bytes replication and forbid by default.
2270     if (!isImm())
2271       return false;
2272     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2273     // Must be a constant.
2274     if (!CE) return false;
2275     unsigned Value = CE->getValue();
2276     return ARM_AM::isNEONi32splat(Value);
2277   }
2278 
2279   bool isNEONi32splatNot() const {
2280     if (!isImm())
2281       return false;
2282     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2283     // Must be a constant.
2284     if (!CE) return false;
2285     unsigned Value = CE->getValue();
2286     return ARM_AM::isNEONi32splat(~Value);
2287   }
2288 
2289   static bool isValidNEONi32vmovImm(int64_t Value) {
2290     // i32 value with set bits only in one byte X000, 0X00, 00X0, or 000X,
2291     // for VMOV/VMVN only, 00Xf or 0Xff are also accepted.
2292     return ((Value & 0xffffffffffffff00) == 0) ||
2293            ((Value & 0xffffffffffff00ff) == 0) ||
2294            ((Value & 0xffffffffff00ffff) == 0) ||
2295            ((Value & 0xffffffff00ffffff) == 0) ||
2296            ((Value & 0xffffffffffff00ff) == 0xff) ||
2297            ((Value & 0xffffffffff00ffff) == 0xffff);
2298   }
2299 
2300   bool isNEONReplicate(unsigned Width, unsigned NumElems, bool Inv) const {
2301     assert((Width == 8 || Width == 16 || Width == 32) &&
2302            "Invalid element width");
2303     assert(NumElems * Width <= 64 && "Invalid result width");
2304 
2305     if (!isImm())
2306       return false;
2307     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2308     // Must be a constant.
2309     if (!CE)
2310       return false;
2311     int64_t Value = CE->getValue();
2312     if (!Value)
2313       return false; // Don't bother with zero.
2314     if (Inv)
2315       Value = ~Value;
2316 
2317     uint64_t Mask = (1ull << Width) - 1;
2318     uint64_t Elem = Value & Mask;
2319     if (Width == 16 && (Elem & 0x00ff) != 0 && (Elem & 0xff00) != 0)
2320       return false;
2321     if (Width == 32 && !isValidNEONi32vmovImm(Elem))
2322       return false;
2323 
2324     for (unsigned i = 1; i < NumElems; ++i) {
2325       Value >>= Width;
2326       if ((Value & Mask) != Elem)
2327         return false;
2328     }
2329     return true;
2330   }
2331 
2332   bool isNEONByteReplicate(unsigned NumBytes) const {
2333     return isNEONReplicate(8, NumBytes, false);
2334   }
2335 
2336   static void checkNeonReplicateArgs(unsigned FromW, unsigned ToW) {
2337     assert((FromW == 8 || FromW == 16 || FromW == 32) &&
2338            "Invalid source width");
2339     assert((ToW == 16 || ToW == 32 || ToW == 64) &&
2340            "Invalid destination width");
2341     assert(FromW < ToW && "ToW is not less than FromW");
2342   }
2343 
2344   template<unsigned FromW, unsigned ToW>
2345   bool isNEONmovReplicate() const {
2346     checkNeonReplicateArgs(FromW, ToW);
2347     if (ToW == 64 && isNEONi64splat())
2348       return false;
2349     return isNEONReplicate(FromW, ToW / FromW, false);
2350   }
2351 
2352   template<unsigned FromW, unsigned ToW>
2353   bool isNEONinvReplicate() const {
2354     checkNeonReplicateArgs(FromW, ToW);
2355     return isNEONReplicate(FromW, ToW / FromW, true);
2356   }
2357 
2358   bool isNEONi32vmov() const {
2359     if (isNEONByteReplicate(4))
2360       return false; // Let it to be classified as byte-replicate case.
2361     if (!isImm())
2362       return false;
2363     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2364     // Must be a constant.
2365     if (!CE)
2366       return false;
2367     return isValidNEONi32vmovImm(CE->getValue());
2368   }
2369 
2370   bool isNEONi32vmovNeg() const {
2371     if (!isImm()) return false;
2372     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2373     // Must be a constant.
2374     if (!CE) return false;
2375     return isValidNEONi32vmovImm(~CE->getValue());
2376   }
2377 
2378   bool isNEONi64splat() const {
2379     if (!isImm()) return false;
2380     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2381     // Must be a constant.
2382     if (!CE) return false;
2383     uint64_t Value = CE->getValue();
2384     // i64 value with each byte being either 0 or 0xff.
2385     for (unsigned i = 0; i < 8; ++i, Value >>= 8)
2386       if ((Value & 0xff) != 0 && (Value & 0xff) != 0xff) return false;
2387     return true;
2388   }
2389 
2390   template<int64_t Angle, int64_t Remainder>
2391   bool isComplexRotation() const {
2392     if (!isImm()) return false;
2393 
2394     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2395     if (!CE) return false;
2396     uint64_t Value = CE->getValue();
2397 
2398     return (Value % Angle == Remainder && Value <= 270);
2399   }
2400 
2401   bool isMVELongShift() const {
2402     if (!isImm()) return false;
2403     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2404     // Must be a constant.
2405     if (!CE) return false;
2406     uint64_t Value = CE->getValue();
2407     return Value >= 1 && Value <= 32;
2408   }
2409 
2410   bool isMveSaturateOp() const {
2411     if (!isImm()) return false;
2412     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2413     if (!CE) return false;
2414     uint64_t Value = CE->getValue();
2415     return Value == 48 || Value == 64;
2416   }
2417 
2418   bool isITCondCodeNoAL() const {
2419     if (!isITCondCode()) return false;
2420     ARMCC::CondCodes CC = getCondCode();
2421     return CC != ARMCC::AL;
2422   }
2423 
2424   bool isITCondCodeRestrictedI() const {
2425     if (!isITCondCode())
2426       return false;
2427     ARMCC::CondCodes CC = getCondCode();
2428     return CC == ARMCC::EQ || CC == ARMCC::NE;
2429   }
2430 
2431   bool isITCondCodeRestrictedS() const {
2432     if (!isITCondCode())
2433       return false;
2434     ARMCC::CondCodes CC = getCondCode();
2435     return CC == ARMCC::LT || CC == ARMCC::GT || CC == ARMCC::LE ||
2436            CC == ARMCC::GE;
2437   }
2438 
2439   bool isITCondCodeRestrictedU() const {
2440     if (!isITCondCode())
2441       return false;
2442     ARMCC::CondCodes CC = getCondCode();
2443     return CC == ARMCC::HS || CC == ARMCC::HI;
2444   }
2445 
2446   bool isITCondCodeRestrictedFP() const {
2447     if (!isITCondCode())
2448       return false;
2449     ARMCC::CondCodes CC = getCondCode();
2450     return CC == ARMCC::EQ || CC == ARMCC::NE || CC == ARMCC::LT ||
2451            CC == ARMCC::GT || CC == ARMCC::LE || CC == ARMCC::GE;
2452   }
2453 
2454   void addExpr(MCInst &Inst, const MCExpr *Expr) const {
2455     // Add as immediates when possible.  Null MCExpr = 0.
2456     if (!Expr)
2457       Inst.addOperand(MCOperand::createImm(0));
2458     else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
2459       Inst.addOperand(MCOperand::createImm(CE->getValue()));
2460     else
2461       Inst.addOperand(MCOperand::createExpr(Expr));
2462   }
2463 
2464   void addARMBranchTargetOperands(MCInst &Inst, unsigned N) const {
2465     assert(N == 1 && "Invalid number of operands!");
2466     addExpr(Inst, getImm());
2467   }
2468 
2469   void addThumbBranchTargetOperands(MCInst &Inst, unsigned N) const {
2470     assert(N == 1 && "Invalid number of operands!");
2471     addExpr(Inst, getImm());
2472   }
2473 
2474   void addCondCodeOperands(MCInst &Inst, unsigned N) const {
2475     assert(N == 2 && "Invalid number of operands!");
2476     Inst.addOperand(MCOperand::createImm(unsigned(getCondCode())));
2477     unsigned RegNum = getCondCode() == ARMCC::AL ? 0: ARM::CPSR;
2478     Inst.addOperand(MCOperand::createReg(RegNum));
2479   }
2480 
2481   void addVPTPredNOperands(MCInst &Inst, unsigned N) const {
2482     assert(N == 2 && "Invalid number of operands!");
2483     Inst.addOperand(MCOperand::createImm(unsigned(getVPTPred())));
2484     unsigned RegNum = getVPTPred() == ARMVCC::None ? 0: ARM::P0;
2485     Inst.addOperand(MCOperand::createReg(RegNum));
2486   }
2487 
2488   void addVPTPredROperands(MCInst &Inst, unsigned N) const {
2489     assert(N == 3 && "Invalid number of operands!");
2490     addVPTPredNOperands(Inst, N-1);
2491     unsigned RegNum;
2492     if (getVPTPred() == ARMVCC::None) {
2493       RegNum = 0;
2494     } else {
2495       unsigned NextOpIndex = Inst.getNumOperands();
2496       const MCInstrDesc &MCID = ARMInsts[Inst.getOpcode()];
2497       int TiedOp = MCID.getOperandConstraint(NextOpIndex, MCOI::TIED_TO);
2498       assert(TiedOp >= 0 &&
2499              "Inactive register in vpred_r is not tied to an output!");
2500       RegNum = Inst.getOperand(TiedOp).getReg();
2501     }
2502     Inst.addOperand(MCOperand::createReg(RegNum));
2503   }
2504 
2505   void addCoprocNumOperands(MCInst &Inst, unsigned N) const {
2506     assert(N == 1 && "Invalid number of operands!");
2507     Inst.addOperand(MCOperand::createImm(getCoproc()));
2508   }
2509 
2510   void addCoprocRegOperands(MCInst &Inst, unsigned N) const {
2511     assert(N == 1 && "Invalid number of operands!");
2512     Inst.addOperand(MCOperand::createImm(getCoproc()));
2513   }
2514 
2515   void addCoprocOptionOperands(MCInst &Inst, unsigned N) const {
2516     assert(N == 1 && "Invalid number of operands!");
2517     Inst.addOperand(MCOperand::createImm(CoprocOption.Val));
2518   }
2519 
2520   void addITMaskOperands(MCInst &Inst, unsigned N) const {
2521     assert(N == 1 && "Invalid number of operands!");
2522     Inst.addOperand(MCOperand::createImm(ITMask.Mask));
2523   }
2524 
2525   void addITCondCodeOperands(MCInst &Inst, unsigned N) const {
2526     assert(N == 1 && "Invalid number of operands!");
2527     Inst.addOperand(MCOperand::createImm(unsigned(getCondCode())));
2528   }
2529 
2530   void addITCondCodeInvOperands(MCInst &Inst, unsigned N) const {
2531     assert(N == 1 && "Invalid number of operands!");
2532     Inst.addOperand(MCOperand::createImm(unsigned(ARMCC::getOppositeCondition(getCondCode()))));
2533   }
2534 
2535   void addCCOutOperands(MCInst &Inst, unsigned N) const {
2536     assert(N == 1 && "Invalid number of operands!");
2537     Inst.addOperand(MCOperand::createReg(getReg()));
2538   }
2539 
2540   void addRegOperands(MCInst &Inst, unsigned N) const {
2541     assert(N == 1 && "Invalid number of operands!");
2542     Inst.addOperand(MCOperand::createReg(getReg()));
2543   }
2544 
2545   void addRegShiftedRegOperands(MCInst &Inst, unsigned N) const {
2546     assert(N == 3 && "Invalid number of operands!");
2547     assert(isRegShiftedReg() &&
2548            "addRegShiftedRegOperands() on non-RegShiftedReg!");
2549     Inst.addOperand(MCOperand::createReg(RegShiftedReg.SrcReg));
2550     Inst.addOperand(MCOperand::createReg(RegShiftedReg.ShiftReg));
2551     Inst.addOperand(MCOperand::createImm(
2552       ARM_AM::getSORegOpc(RegShiftedReg.ShiftTy, RegShiftedReg.ShiftImm)));
2553   }
2554 
2555   void addRegShiftedImmOperands(MCInst &Inst, unsigned N) const {
2556     assert(N == 2 && "Invalid number of operands!");
2557     assert(isRegShiftedImm() &&
2558            "addRegShiftedImmOperands() on non-RegShiftedImm!");
2559     Inst.addOperand(MCOperand::createReg(RegShiftedImm.SrcReg));
2560     // Shift of #32 is encoded as 0 where permitted
2561     unsigned Imm = (RegShiftedImm.ShiftImm == 32 ? 0 : RegShiftedImm.ShiftImm);
2562     Inst.addOperand(MCOperand::createImm(
2563       ARM_AM::getSORegOpc(RegShiftedImm.ShiftTy, Imm)));
2564   }
2565 
2566   void addShifterImmOperands(MCInst &Inst, unsigned N) const {
2567     assert(N == 1 && "Invalid number of operands!");
2568     Inst.addOperand(MCOperand::createImm((ShifterImm.isASR << 5) |
2569                                          ShifterImm.Imm));
2570   }
2571 
2572   void addRegListOperands(MCInst &Inst, unsigned N) const {
2573     assert(N == 1 && "Invalid number of operands!");
2574     const SmallVectorImpl<unsigned> &RegList = getRegList();
2575     for (SmallVectorImpl<unsigned>::const_iterator
2576            I = RegList.begin(), E = RegList.end(); I != E; ++I)
2577       Inst.addOperand(MCOperand::createReg(*I));
2578   }
2579 
2580   void addRegListWithAPSROperands(MCInst &Inst, unsigned N) const {
2581     assert(N == 1 && "Invalid number of operands!");
2582     const SmallVectorImpl<unsigned> &RegList = getRegList();
2583     for (SmallVectorImpl<unsigned>::const_iterator
2584            I = RegList.begin(), E = RegList.end(); I != E; ++I)
2585       Inst.addOperand(MCOperand::createReg(*I));
2586   }
2587 
2588   void addDPRRegListOperands(MCInst &Inst, unsigned N) const {
2589     addRegListOperands(Inst, N);
2590   }
2591 
2592   void addSPRRegListOperands(MCInst &Inst, unsigned N) const {
2593     addRegListOperands(Inst, N);
2594   }
2595 
2596   void addFPSRegListWithVPROperands(MCInst &Inst, unsigned N) const {
2597     addRegListOperands(Inst, N);
2598   }
2599 
2600   void addFPDRegListWithVPROperands(MCInst &Inst, unsigned N) const {
2601     addRegListOperands(Inst, N);
2602   }
2603 
2604   void addRotImmOperands(MCInst &Inst, unsigned N) const {
2605     assert(N == 1 && "Invalid number of operands!");
2606     // Encoded as val>>3. The printer handles display as 8, 16, 24.
2607     Inst.addOperand(MCOperand::createImm(RotImm.Imm >> 3));
2608   }
2609 
2610   void addModImmOperands(MCInst &Inst, unsigned N) const {
2611     assert(N == 1 && "Invalid number of operands!");
2612 
2613     // Support for fixups (MCFixup)
2614     if (isImm())
2615       return addImmOperands(Inst, N);
2616 
2617     Inst.addOperand(MCOperand::createImm(ModImm.Bits | (ModImm.Rot << 7)));
2618   }
2619 
2620   void addModImmNotOperands(MCInst &Inst, unsigned N) const {
2621     assert(N == 1 && "Invalid number of operands!");
2622     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2623     uint32_t Enc = ARM_AM::getSOImmVal(~CE->getValue());
2624     Inst.addOperand(MCOperand::createImm(Enc));
2625   }
2626 
2627   void addModImmNegOperands(MCInst &Inst, unsigned N) const {
2628     assert(N == 1 && "Invalid number of operands!");
2629     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2630     uint32_t Enc = ARM_AM::getSOImmVal(-CE->getValue());
2631     Inst.addOperand(MCOperand::createImm(Enc));
2632   }
2633 
2634   void addThumbModImmNeg8_255Operands(MCInst &Inst, unsigned N) const {
2635     assert(N == 1 && "Invalid number of operands!");
2636     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2637     uint32_t Val = -CE->getValue();
2638     Inst.addOperand(MCOperand::createImm(Val));
2639   }
2640 
2641   void addThumbModImmNeg1_7Operands(MCInst &Inst, unsigned N) const {
2642     assert(N == 1 && "Invalid number of operands!");
2643     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2644     uint32_t Val = -CE->getValue();
2645     Inst.addOperand(MCOperand::createImm(Val));
2646   }
2647 
2648   void addBitfieldOperands(MCInst &Inst, unsigned N) const {
2649     assert(N == 1 && "Invalid number of operands!");
2650     // Munge the lsb/width into a bitfield mask.
2651     unsigned lsb = Bitfield.LSB;
2652     unsigned width = Bitfield.Width;
2653     // Make a 32-bit mask w/ the referenced bits clear and all other bits set.
2654     uint32_t Mask = ~(((uint32_t)0xffffffff >> lsb) << (32 - width) >>
2655                       (32 - (lsb + width)));
2656     Inst.addOperand(MCOperand::createImm(Mask));
2657   }
2658 
2659   void addImmOperands(MCInst &Inst, unsigned N) const {
2660     assert(N == 1 && "Invalid number of operands!");
2661     addExpr(Inst, getImm());
2662   }
2663 
2664   void addFBits16Operands(MCInst &Inst, unsigned N) const {
2665     assert(N == 1 && "Invalid number of operands!");
2666     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2667     Inst.addOperand(MCOperand::createImm(16 - CE->getValue()));
2668   }
2669 
2670   void addFBits32Operands(MCInst &Inst, unsigned N) const {
2671     assert(N == 1 && "Invalid number of operands!");
2672     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2673     Inst.addOperand(MCOperand::createImm(32 - CE->getValue()));
2674   }
2675 
2676   void addFPImmOperands(MCInst &Inst, unsigned N) const {
2677     assert(N == 1 && "Invalid number of operands!");
2678     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2679     int Val = ARM_AM::getFP32Imm(APInt(32, CE->getValue()));
2680     Inst.addOperand(MCOperand::createImm(Val));
2681   }
2682 
2683   void addImm8s4Operands(MCInst &Inst, unsigned N) const {
2684     assert(N == 1 && "Invalid number of operands!");
2685     // FIXME: We really want to scale the value here, but the LDRD/STRD
2686     // instruction don't encode operands that way yet.
2687     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2688     Inst.addOperand(MCOperand::createImm(CE->getValue()));
2689   }
2690 
2691   void addImm7s4Operands(MCInst &Inst, unsigned N) const {
2692     assert(N == 1 && "Invalid number of operands!");
2693     // FIXME: We really want to scale the value here, but the VSTR/VLDR_VSYSR
2694     // instruction don't encode operands that way yet.
2695     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2696     Inst.addOperand(MCOperand::createImm(CE->getValue()));
2697   }
2698 
2699   void addImm7Shift0Operands(MCInst &Inst, unsigned N) const {
2700     assert(N == 1 && "Invalid number of operands!");
2701     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2702     Inst.addOperand(MCOperand::createImm(CE->getValue()));
2703   }
2704 
2705   void addImm7Shift1Operands(MCInst &Inst, unsigned N) const {
2706     assert(N == 1 && "Invalid number of operands!");
2707     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2708     Inst.addOperand(MCOperand::createImm(CE->getValue()));
2709   }
2710 
2711   void addImm7Shift2Operands(MCInst &Inst, unsigned N) const {
2712     assert(N == 1 && "Invalid number of operands!");
2713     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2714     Inst.addOperand(MCOperand::createImm(CE->getValue()));
2715   }
2716 
2717   void addImm7Operands(MCInst &Inst, unsigned N) const {
2718     assert(N == 1 && "Invalid number of operands!");
2719     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2720     Inst.addOperand(MCOperand::createImm(CE->getValue()));
2721   }
2722 
2723   void addImm0_1020s4Operands(MCInst &Inst, unsigned N) const {
2724     assert(N == 1 && "Invalid number of operands!");
2725     // The immediate is scaled by four in the encoding and is stored
2726     // in the MCInst as such. Lop off the low two bits here.
2727     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2728     Inst.addOperand(MCOperand::createImm(CE->getValue() / 4));
2729   }
2730 
2731   void addImm0_508s4NegOperands(MCInst &Inst, unsigned N) const {
2732     assert(N == 1 && "Invalid number of operands!");
2733     // The immediate is scaled by four in the encoding and is stored
2734     // in the MCInst as such. Lop off the low two bits here.
2735     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2736     Inst.addOperand(MCOperand::createImm(-(CE->getValue() / 4)));
2737   }
2738 
2739   void addImm0_508s4Operands(MCInst &Inst, unsigned N) const {
2740     assert(N == 1 && "Invalid number of operands!");
2741     // The immediate is scaled by four in the encoding and is stored
2742     // in the MCInst as such. Lop off the low two bits here.
2743     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2744     Inst.addOperand(MCOperand::createImm(CE->getValue() / 4));
2745   }
2746 
2747   void addImm1_16Operands(MCInst &Inst, unsigned N) const {
2748     assert(N == 1 && "Invalid number of operands!");
2749     // The constant encodes as the immediate-1, and we store in the instruction
2750     // the bits as encoded, so subtract off one here.
2751     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2752     Inst.addOperand(MCOperand::createImm(CE->getValue() - 1));
2753   }
2754 
2755   void addImm1_32Operands(MCInst &Inst, unsigned N) const {
2756     assert(N == 1 && "Invalid number of operands!");
2757     // The constant encodes as the immediate-1, and we store in the instruction
2758     // the bits as encoded, so subtract off one here.
2759     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2760     Inst.addOperand(MCOperand::createImm(CE->getValue() - 1));
2761   }
2762 
2763   void addImmThumbSROperands(MCInst &Inst, unsigned N) const {
2764     assert(N == 1 && "Invalid number of operands!");
2765     // The constant encodes as the immediate, except for 32, which encodes as
2766     // zero.
2767     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2768     unsigned Imm = CE->getValue();
2769     Inst.addOperand(MCOperand::createImm((Imm == 32 ? 0 : Imm)));
2770   }
2771 
2772   void addPKHASRImmOperands(MCInst &Inst, unsigned N) const {
2773     assert(N == 1 && "Invalid number of operands!");
2774     // An ASR value of 32 encodes as 0, so that's how we want to add it to
2775     // the instruction as well.
2776     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2777     int Val = CE->getValue();
2778     Inst.addOperand(MCOperand::createImm(Val == 32 ? 0 : Val));
2779   }
2780 
2781   void addT2SOImmNotOperands(MCInst &Inst, unsigned N) const {
2782     assert(N == 1 && "Invalid number of operands!");
2783     // The operand is actually a t2_so_imm, but we have its bitwise
2784     // negation in the assembly source, so twiddle it here.
2785     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2786     Inst.addOperand(MCOperand::createImm(~(uint32_t)CE->getValue()));
2787   }
2788 
2789   void addT2SOImmNegOperands(MCInst &Inst, unsigned N) const {
2790     assert(N == 1 && "Invalid number of operands!");
2791     // The operand is actually a t2_so_imm, but we have its
2792     // negation in the assembly source, so twiddle it here.
2793     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2794     Inst.addOperand(MCOperand::createImm(-(uint32_t)CE->getValue()));
2795   }
2796 
2797   void addImm0_4095NegOperands(MCInst &Inst, unsigned N) const {
2798     assert(N == 1 && "Invalid number of operands!");
2799     // The operand is actually an imm0_4095, but we have its
2800     // negation in the assembly source, so twiddle it here.
2801     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2802     Inst.addOperand(MCOperand::createImm(-(uint32_t)CE->getValue()));
2803   }
2804 
2805   void addUnsignedOffset_b8s2Operands(MCInst &Inst, unsigned N) const {
2806     if(const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm())) {
2807       Inst.addOperand(MCOperand::createImm(CE->getValue() >> 2));
2808       return;
2809     }
2810     const MCSymbolRefExpr *SR = cast<MCSymbolRefExpr>(Imm.Val);
2811     Inst.addOperand(MCOperand::createExpr(SR));
2812   }
2813 
2814   void addThumbMemPCOperands(MCInst &Inst, unsigned N) const {
2815     assert(N == 1 && "Invalid number of operands!");
2816     if (isImm()) {
2817       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2818       if (CE) {
2819         Inst.addOperand(MCOperand::createImm(CE->getValue()));
2820         return;
2821       }
2822       const MCSymbolRefExpr *SR = cast<MCSymbolRefExpr>(Imm.Val);
2823       Inst.addOperand(MCOperand::createExpr(SR));
2824       return;
2825     }
2826 
2827     assert(isGPRMem()  && "Unknown value type!");
2828     assert(isa<MCConstantExpr>(Memory.OffsetImm) && "Unknown value type!");
2829     if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm))
2830       Inst.addOperand(MCOperand::createImm(CE->getValue()));
2831     else
2832       Inst.addOperand(MCOperand::createExpr(Memory.OffsetImm));
2833   }
2834 
2835   void addMemBarrierOptOperands(MCInst &Inst, unsigned N) const {
2836     assert(N == 1 && "Invalid number of operands!");
2837     Inst.addOperand(MCOperand::createImm(unsigned(getMemBarrierOpt())));
2838   }
2839 
2840   void addInstSyncBarrierOptOperands(MCInst &Inst, unsigned N) const {
2841     assert(N == 1 && "Invalid number of operands!");
2842     Inst.addOperand(MCOperand::createImm(unsigned(getInstSyncBarrierOpt())));
2843   }
2844 
2845   void addTraceSyncBarrierOptOperands(MCInst &Inst, unsigned N) const {
2846     assert(N == 1 && "Invalid number of operands!");
2847     Inst.addOperand(MCOperand::createImm(unsigned(getTraceSyncBarrierOpt())));
2848   }
2849 
2850   void addMemNoOffsetOperands(MCInst &Inst, unsigned N) const {
2851     assert(N == 1 && "Invalid number of operands!");
2852     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2853   }
2854 
2855   void addMemNoOffsetT2Operands(MCInst &Inst, unsigned N) const {
2856     assert(N == 1 && "Invalid number of operands!");
2857     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2858   }
2859 
2860   void addMemNoOffsetT2NoSpOperands(MCInst &Inst, unsigned N) const {
2861     assert(N == 1 && "Invalid number of operands!");
2862     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2863   }
2864 
2865   void addMemNoOffsetTOperands(MCInst &Inst, unsigned N) const {
2866     assert(N == 1 && "Invalid number of operands!");
2867     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2868   }
2869 
2870   void addMemPCRelImm12Operands(MCInst &Inst, unsigned N) const {
2871     assert(N == 1 && "Invalid number of operands!");
2872     if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm))
2873       Inst.addOperand(MCOperand::createImm(CE->getValue()));
2874     else
2875       Inst.addOperand(MCOperand::createExpr(Memory.OffsetImm));
2876   }
2877 
2878   void addAdrLabelOperands(MCInst &Inst, unsigned N) const {
2879     assert(N == 1 && "Invalid number of operands!");
2880     assert(isImm() && "Not an immediate!");
2881 
2882     // If we have an immediate that's not a constant, treat it as a label
2883     // reference needing a fixup.
2884     if (!isa<MCConstantExpr>(getImm())) {
2885       Inst.addOperand(MCOperand::createExpr(getImm()));
2886       return;
2887     }
2888 
2889     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2890     int Val = CE->getValue();
2891     Inst.addOperand(MCOperand::createImm(Val));
2892   }
2893 
2894   void addAlignedMemoryOperands(MCInst &Inst, unsigned N) const {
2895     assert(N == 2 && "Invalid number of operands!");
2896     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2897     Inst.addOperand(MCOperand::createImm(Memory.Alignment));
2898   }
2899 
2900   void addDupAlignedMemoryNoneOperands(MCInst &Inst, unsigned N) const {
2901     addAlignedMemoryOperands(Inst, N);
2902   }
2903 
2904   void addAlignedMemoryNoneOperands(MCInst &Inst, unsigned N) const {
2905     addAlignedMemoryOperands(Inst, N);
2906   }
2907 
2908   void addAlignedMemory16Operands(MCInst &Inst, unsigned N) const {
2909     addAlignedMemoryOperands(Inst, N);
2910   }
2911 
2912   void addDupAlignedMemory16Operands(MCInst &Inst, unsigned N) const {
2913     addAlignedMemoryOperands(Inst, N);
2914   }
2915 
2916   void addAlignedMemory32Operands(MCInst &Inst, unsigned N) const {
2917     addAlignedMemoryOperands(Inst, N);
2918   }
2919 
2920   void addDupAlignedMemory32Operands(MCInst &Inst, unsigned N) const {
2921     addAlignedMemoryOperands(Inst, N);
2922   }
2923 
2924   void addAlignedMemory64Operands(MCInst &Inst, unsigned N) const {
2925     addAlignedMemoryOperands(Inst, N);
2926   }
2927 
2928   void addDupAlignedMemory64Operands(MCInst &Inst, unsigned N) const {
2929     addAlignedMemoryOperands(Inst, N);
2930   }
2931 
2932   void addAlignedMemory64or128Operands(MCInst &Inst, unsigned N) const {
2933     addAlignedMemoryOperands(Inst, N);
2934   }
2935 
2936   void addDupAlignedMemory64or128Operands(MCInst &Inst, unsigned N) const {
2937     addAlignedMemoryOperands(Inst, N);
2938   }
2939 
2940   void addAlignedMemory64or128or256Operands(MCInst &Inst, unsigned N) const {
2941     addAlignedMemoryOperands(Inst, N);
2942   }
2943 
2944   void addAddrMode2Operands(MCInst &Inst, unsigned N) const {
2945     assert(N == 3 && "Invalid number of operands!");
2946     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2947     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2948     if (!Memory.OffsetRegNum) {
2949       if (!Memory.OffsetImm)
2950         Inst.addOperand(MCOperand::createImm(0));
2951       else if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
2952         int32_t Val = CE->getValue();
2953         ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2954         // Special case for #-0
2955         if (Val == std::numeric_limits<int32_t>::min())
2956           Val = 0;
2957         if (Val < 0)
2958           Val = -Val;
2959         Val = ARM_AM::getAM2Opc(AddSub, Val, ARM_AM::no_shift);
2960         Inst.addOperand(MCOperand::createImm(Val));
2961       } else
2962         Inst.addOperand(MCOperand::createExpr(Memory.OffsetImm));
2963     } else {
2964       // For register offset, we encode the shift type and negation flag
2965       // here.
2966       int32_t Val =
2967           ARM_AM::getAM2Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add,
2968                             Memory.ShiftImm, Memory.ShiftType);
2969       Inst.addOperand(MCOperand::createImm(Val));
2970     }
2971   }
2972 
2973   void addAM2OffsetImmOperands(MCInst &Inst, unsigned N) const {
2974     assert(N == 2 && "Invalid number of operands!");
2975     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2976     assert(CE && "non-constant AM2OffsetImm operand!");
2977     int32_t Val = CE->getValue();
2978     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2979     // Special case for #-0
2980     if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2981     if (Val < 0) Val = -Val;
2982     Val = ARM_AM::getAM2Opc(AddSub, Val, ARM_AM::no_shift);
2983     Inst.addOperand(MCOperand::createReg(0));
2984     Inst.addOperand(MCOperand::createImm(Val));
2985   }
2986 
2987   void addAddrMode3Operands(MCInst &Inst, unsigned N) const {
2988     assert(N == 3 && "Invalid number of operands!");
2989     // If we have an immediate that's not a constant, treat it as a label
2990     // reference needing a fixup. If it is a constant, it's something else
2991     // and we reject it.
2992     if (isImm()) {
2993       Inst.addOperand(MCOperand::createExpr(getImm()));
2994       Inst.addOperand(MCOperand::createReg(0));
2995       Inst.addOperand(MCOperand::createImm(0));
2996       return;
2997     }
2998 
2999     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3000     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
3001     if (!Memory.OffsetRegNum) {
3002       if (!Memory.OffsetImm)
3003         Inst.addOperand(MCOperand::createImm(0));
3004       else if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
3005         int32_t Val = CE->getValue();
3006         ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
3007         // Special case for #-0
3008         if (Val == std::numeric_limits<int32_t>::min())
3009           Val = 0;
3010         if (Val < 0)
3011           Val = -Val;
3012         Val = ARM_AM::getAM3Opc(AddSub, Val);
3013         Inst.addOperand(MCOperand::createImm(Val));
3014       } else
3015         Inst.addOperand(MCOperand::createExpr(Memory.OffsetImm));
3016     } else {
3017       // For register offset, we encode the shift type and negation flag
3018       // here.
3019       int32_t Val =
3020           ARM_AM::getAM3Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add, 0);
3021       Inst.addOperand(MCOperand::createImm(Val));
3022     }
3023   }
3024 
3025   void addAM3OffsetOperands(MCInst &Inst, unsigned N) const {
3026     assert(N == 2 && "Invalid number of operands!");
3027     if (Kind == k_PostIndexRegister) {
3028       int32_t Val =
3029         ARM_AM::getAM3Opc(PostIdxReg.isAdd ? ARM_AM::add : ARM_AM::sub, 0);
3030       Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
3031       Inst.addOperand(MCOperand::createImm(Val));
3032       return;
3033     }
3034 
3035     // Constant offset.
3036     const MCConstantExpr *CE = static_cast<const MCConstantExpr*>(getImm());
3037     int32_t Val = CE->getValue();
3038     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
3039     // Special case for #-0
3040     if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
3041     if (Val < 0) Val = -Val;
3042     Val = ARM_AM::getAM3Opc(AddSub, Val);
3043     Inst.addOperand(MCOperand::createReg(0));
3044     Inst.addOperand(MCOperand::createImm(Val));
3045   }
3046 
3047   void addAddrMode5Operands(MCInst &Inst, unsigned N) const {
3048     assert(N == 2 && "Invalid number of operands!");
3049     // If we have an immediate that's not a constant, treat it as a label
3050     // reference needing a fixup. If it is a constant, it's something else
3051     // and we reject it.
3052     if (isImm()) {
3053       Inst.addOperand(MCOperand::createExpr(getImm()));
3054       Inst.addOperand(MCOperand::createImm(0));
3055       return;
3056     }
3057 
3058     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3059     if (!Memory.OffsetImm)
3060       Inst.addOperand(MCOperand::createImm(0));
3061     else if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
3062       // The lower two bits are always zero and as such are not encoded.
3063       int32_t Val = CE->getValue() / 4;
3064       ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
3065       // Special case for #-0
3066       if (Val == std::numeric_limits<int32_t>::min())
3067         Val = 0;
3068       if (Val < 0)
3069         Val = -Val;
3070       Val = ARM_AM::getAM5Opc(AddSub, Val);
3071       Inst.addOperand(MCOperand::createImm(Val));
3072     } else
3073       Inst.addOperand(MCOperand::createExpr(Memory.OffsetImm));
3074   }
3075 
3076   void addAddrMode5FP16Operands(MCInst &Inst, unsigned N) const {
3077     assert(N == 2 && "Invalid number of operands!");
3078     // If we have an immediate that's not a constant, treat it as a label
3079     // reference needing a fixup. If it is a constant, it's something else
3080     // and we reject it.
3081     if (isImm()) {
3082       Inst.addOperand(MCOperand::createExpr(getImm()));
3083       Inst.addOperand(MCOperand::createImm(0));
3084       return;
3085     }
3086 
3087     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3088     // The lower bit is always zero and as such is not encoded.
3089     if (!Memory.OffsetImm)
3090       Inst.addOperand(MCOperand::createImm(0));
3091     else if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm)) {
3092       int32_t Val = CE->getValue() / 2;
3093       ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
3094       // Special case for #-0
3095       if (Val == std::numeric_limits<int32_t>::min())
3096         Val = 0;
3097       if (Val < 0)
3098         Val = -Val;
3099       Val = ARM_AM::getAM5FP16Opc(AddSub, Val);
3100       Inst.addOperand(MCOperand::createImm(Val));
3101     } else
3102       Inst.addOperand(MCOperand::createExpr(Memory.OffsetImm));
3103   }
3104 
3105   void addMemImm8s4OffsetOperands(MCInst &Inst, unsigned N) const {
3106     assert(N == 2 && "Invalid number of operands!");
3107     // If we have an immediate that's not a constant, treat it as a label
3108     // reference needing a fixup. If it is a constant, it's something else
3109     // and we reject it.
3110     if (isImm()) {
3111       Inst.addOperand(MCOperand::createExpr(getImm()));
3112       Inst.addOperand(MCOperand::createImm(0));
3113       return;
3114     }
3115 
3116     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3117     addExpr(Inst, Memory.OffsetImm);
3118   }
3119 
3120   void addMemImm7s4OffsetOperands(MCInst &Inst, unsigned N) const {
3121     assert(N == 2 && "Invalid number of operands!");
3122     // If we have an immediate that's not a constant, treat it as a label
3123     // reference needing a fixup. If it is a constant, it's something else
3124     // and we reject it.
3125     if (isImm()) {
3126       Inst.addOperand(MCOperand::createExpr(getImm()));
3127       Inst.addOperand(MCOperand::createImm(0));
3128       return;
3129     }
3130 
3131     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3132     addExpr(Inst, Memory.OffsetImm);
3133   }
3134 
3135   void addMemImm0_1020s4OffsetOperands(MCInst &Inst, unsigned N) const {
3136     assert(N == 2 && "Invalid number of operands!");
3137     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3138     if (!Memory.OffsetImm)
3139       Inst.addOperand(MCOperand::createImm(0));
3140     else if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm))
3141       // The lower two bits are always zero and as such are not encoded.
3142       Inst.addOperand(MCOperand::createImm(CE->getValue() / 4));
3143     else
3144       Inst.addOperand(MCOperand::createExpr(Memory.OffsetImm));
3145   }
3146 
3147   void addMemImmOffsetOperands(MCInst &Inst, unsigned N) const {
3148     assert(N == 2 && "Invalid number of operands!");
3149     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3150     addExpr(Inst, Memory.OffsetImm);
3151   }
3152 
3153   void addMemRegRQOffsetOperands(MCInst &Inst, unsigned N) const {
3154     assert(N == 2 && "Invalid number of operands!");
3155     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3156     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
3157   }
3158 
3159   void addMemUImm12OffsetOperands(MCInst &Inst, unsigned N) const {
3160     assert(N == 2 && "Invalid number of operands!");
3161     // If this is an immediate, it's a label reference.
3162     if (isImm()) {
3163       addExpr(Inst, getImm());
3164       Inst.addOperand(MCOperand::createImm(0));
3165       return;
3166     }
3167 
3168     // Otherwise, it's a normal memory reg+offset.
3169     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3170     addExpr(Inst, Memory.OffsetImm);
3171   }
3172 
3173   void addMemImm12OffsetOperands(MCInst &Inst, unsigned N) const {
3174     assert(N == 2 && "Invalid number of operands!");
3175     // If this is an immediate, it's a label reference.
3176     if (isImm()) {
3177       addExpr(Inst, getImm());
3178       Inst.addOperand(MCOperand::createImm(0));
3179       return;
3180     }
3181 
3182     // Otherwise, it's a normal memory reg+offset.
3183     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3184     addExpr(Inst, Memory.OffsetImm);
3185   }
3186 
3187   void addConstPoolAsmImmOperands(MCInst &Inst, unsigned N) const {
3188     assert(N == 1 && "Invalid number of operands!");
3189     // This is container for the immediate that we will create the constant
3190     // pool from
3191     addExpr(Inst, getConstantPoolImm());
3192   }
3193 
3194   void addMemTBBOperands(MCInst &Inst, unsigned N) const {
3195     assert(N == 2 && "Invalid number of operands!");
3196     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3197     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
3198   }
3199 
3200   void addMemTBHOperands(MCInst &Inst, unsigned N) const {
3201     assert(N == 2 && "Invalid number of operands!");
3202     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3203     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
3204   }
3205 
3206   void addMemRegOffsetOperands(MCInst &Inst, unsigned N) const {
3207     assert(N == 3 && "Invalid number of operands!");
3208     unsigned Val =
3209       ARM_AM::getAM2Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add,
3210                         Memory.ShiftImm, Memory.ShiftType);
3211     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3212     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
3213     Inst.addOperand(MCOperand::createImm(Val));
3214   }
3215 
3216   void addT2MemRegOffsetOperands(MCInst &Inst, unsigned N) const {
3217     assert(N == 3 && "Invalid number of operands!");
3218     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3219     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
3220     Inst.addOperand(MCOperand::createImm(Memory.ShiftImm));
3221   }
3222 
3223   void addMemThumbRROperands(MCInst &Inst, unsigned N) const {
3224     assert(N == 2 && "Invalid number of operands!");
3225     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3226     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
3227   }
3228 
3229   void addMemThumbRIs4Operands(MCInst &Inst, unsigned N) const {
3230     assert(N == 2 && "Invalid number of operands!");
3231     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3232     if (!Memory.OffsetImm)
3233       Inst.addOperand(MCOperand::createImm(0));
3234     else if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm))
3235       // The lower two bits are always zero and as such are not encoded.
3236       Inst.addOperand(MCOperand::createImm(CE->getValue() / 4));
3237     else
3238       Inst.addOperand(MCOperand::createExpr(Memory.OffsetImm));
3239   }
3240 
3241   void addMemThumbRIs2Operands(MCInst &Inst, unsigned N) const {
3242     assert(N == 2 && "Invalid number of operands!");
3243     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3244     if (!Memory.OffsetImm)
3245       Inst.addOperand(MCOperand::createImm(0));
3246     else if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm))
3247       Inst.addOperand(MCOperand::createImm(CE->getValue() / 2));
3248     else
3249       Inst.addOperand(MCOperand::createExpr(Memory.OffsetImm));
3250   }
3251 
3252   void addMemThumbRIs1Operands(MCInst &Inst, unsigned N) const {
3253     assert(N == 2 && "Invalid number of operands!");
3254     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3255     addExpr(Inst, Memory.OffsetImm);
3256   }
3257 
3258   void addMemThumbSPIOperands(MCInst &Inst, unsigned N) const {
3259     assert(N == 2 && "Invalid number of operands!");
3260     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3261     if (!Memory.OffsetImm)
3262       Inst.addOperand(MCOperand::createImm(0));
3263     else if (const auto *CE = dyn_cast<MCConstantExpr>(Memory.OffsetImm))
3264       // The lower two bits are always zero and as such are not encoded.
3265       Inst.addOperand(MCOperand::createImm(CE->getValue() / 4));
3266     else
3267       Inst.addOperand(MCOperand::createExpr(Memory.OffsetImm));
3268   }
3269 
3270   void addPostIdxImm8Operands(MCInst &Inst, unsigned N) const {
3271     assert(N == 1 && "Invalid number of operands!");
3272     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
3273     assert(CE && "non-constant post-idx-imm8 operand!");
3274     int Imm = CE->getValue();
3275     bool isAdd = Imm >= 0;
3276     if (Imm == std::numeric_limits<int32_t>::min()) Imm = 0;
3277     Imm = (Imm < 0 ? -Imm : Imm) | (int)isAdd << 8;
3278     Inst.addOperand(MCOperand::createImm(Imm));
3279   }
3280 
3281   void addPostIdxImm8s4Operands(MCInst &Inst, unsigned N) const {
3282     assert(N == 1 && "Invalid number of operands!");
3283     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
3284     assert(CE && "non-constant post-idx-imm8s4 operand!");
3285     int Imm = CE->getValue();
3286     bool isAdd = Imm >= 0;
3287     if (Imm == std::numeric_limits<int32_t>::min()) Imm = 0;
3288     // Immediate is scaled by 4.
3289     Imm = ((Imm < 0 ? -Imm : Imm) / 4) | (int)isAdd << 8;
3290     Inst.addOperand(MCOperand::createImm(Imm));
3291   }
3292 
3293   void addPostIdxRegOperands(MCInst &Inst, unsigned N) const {
3294     assert(N == 2 && "Invalid number of operands!");
3295     Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
3296     Inst.addOperand(MCOperand::createImm(PostIdxReg.isAdd));
3297   }
3298 
3299   void addPostIdxRegShiftedOperands(MCInst &Inst, unsigned N) const {
3300     assert(N == 2 && "Invalid number of operands!");
3301     Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
3302     // The sign, shift type, and shift amount are encoded in a single operand
3303     // using the AM2 encoding helpers.
3304     ARM_AM::AddrOpc opc = PostIdxReg.isAdd ? ARM_AM::add : ARM_AM::sub;
3305     unsigned Imm = ARM_AM::getAM2Opc(opc, PostIdxReg.ShiftImm,
3306                                      PostIdxReg.ShiftTy);
3307     Inst.addOperand(MCOperand::createImm(Imm));
3308   }
3309 
3310   void addPowerTwoOperands(MCInst &Inst, unsigned N) const {
3311     assert(N == 1 && "Invalid number of operands!");
3312     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3313     Inst.addOperand(MCOperand::createImm(CE->getValue()));
3314   }
3315 
3316   void addMSRMaskOperands(MCInst &Inst, unsigned N) const {
3317     assert(N == 1 && "Invalid number of operands!");
3318     Inst.addOperand(MCOperand::createImm(unsigned(getMSRMask())));
3319   }
3320 
3321   void addBankedRegOperands(MCInst &Inst, unsigned N) const {
3322     assert(N == 1 && "Invalid number of operands!");
3323     Inst.addOperand(MCOperand::createImm(unsigned(getBankedReg())));
3324   }
3325 
3326   void addProcIFlagsOperands(MCInst &Inst, unsigned N) const {
3327     assert(N == 1 && "Invalid number of operands!");
3328     Inst.addOperand(MCOperand::createImm(unsigned(getProcIFlags())));
3329   }
3330 
3331   void addVecListOperands(MCInst &Inst, unsigned N) const {
3332     assert(N == 1 && "Invalid number of operands!");
3333     Inst.addOperand(MCOperand::createReg(VectorList.RegNum));
3334   }
3335 
3336   void addMVEVecListOperands(MCInst &Inst, unsigned N) const {
3337     assert(N == 1 && "Invalid number of operands!");
3338 
3339     // When we come here, the VectorList field will identify a range
3340     // of q-registers by its base register and length, and it will
3341     // have already been error-checked to be the expected length of
3342     // range and contain only q-regs in the range q0-q7. So we can
3343     // count on the base register being in the range q0-q6 (for 2
3344     // regs) or q0-q4 (for 4)
3345     //
3346     // The MVE instructions taking a register range of this kind will
3347     // need an operand in the QQPR or QQQQPR class, representing the
3348     // entire range as a unit. So we must translate into that class,
3349     // by finding the index of the base register in the MQPR reg
3350     // class, and returning the super-register at the corresponding
3351     // index in the target class.
3352 
3353     const MCRegisterClass *RC_in = &ARMMCRegisterClasses[ARM::MQPRRegClassID];
3354     const MCRegisterClass *RC_out = (VectorList.Count == 2) ?
3355       &ARMMCRegisterClasses[ARM::QQPRRegClassID] :
3356       &ARMMCRegisterClasses[ARM::QQQQPRRegClassID];
3357 
3358     unsigned I, E = RC_out->getNumRegs();
3359     for (I = 0; I < E; I++)
3360       if (RC_in->getRegister(I) == VectorList.RegNum)
3361         break;
3362     assert(I < E && "Invalid vector list start register!");
3363 
3364     Inst.addOperand(MCOperand::createReg(RC_out->getRegister(I)));
3365   }
3366 
3367   void addVecListIndexedOperands(MCInst &Inst, unsigned N) const {
3368     assert(N == 2 && "Invalid number of operands!");
3369     Inst.addOperand(MCOperand::createReg(VectorList.RegNum));
3370     Inst.addOperand(MCOperand::createImm(VectorList.LaneIndex));
3371   }
3372 
3373   void addVectorIndex8Operands(MCInst &Inst, unsigned N) const {
3374     assert(N == 1 && "Invalid number of operands!");
3375     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
3376   }
3377 
3378   void addVectorIndex16Operands(MCInst &Inst, unsigned N) const {
3379     assert(N == 1 && "Invalid number of operands!");
3380     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
3381   }
3382 
3383   void addVectorIndex32Operands(MCInst &Inst, unsigned N) const {
3384     assert(N == 1 && "Invalid number of operands!");
3385     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
3386   }
3387 
3388   void addVectorIndex64Operands(MCInst &Inst, unsigned N) const {
3389     assert(N == 1 && "Invalid number of operands!");
3390     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
3391   }
3392 
3393   void addMVEVectorIndexOperands(MCInst &Inst, unsigned N) const {
3394     assert(N == 1 && "Invalid number of operands!");
3395     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
3396   }
3397 
3398   void addMVEPairVectorIndexOperands(MCInst &Inst, unsigned N) const {
3399     assert(N == 1 && "Invalid number of operands!");
3400     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
3401   }
3402 
3403   void addNEONi8splatOperands(MCInst &Inst, unsigned N) const {
3404     assert(N == 1 && "Invalid number of operands!");
3405     // The immediate encodes the type of constant as well as the value.
3406     // Mask in that this is an i8 splat.
3407     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3408     Inst.addOperand(MCOperand::createImm(CE->getValue() | 0xe00));
3409   }
3410 
3411   void addNEONi16splatOperands(MCInst &Inst, unsigned N) const {
3412     assert(N == 1 && "Invalid number of operands!");
3413     // The immediate encodes the type of constant as well as the value.
3414     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3415     unsigned Value = CE->getValue();
3416     Value = ARM_AM::encodeNEONi16splat(Value);
3417     Inst.addOperand(MCOperand::createImm(Value));
3418   }
3419 
3420   void addNEONi16splatNotOperands(MCInst &Inst, unsigned N) const {
3421     assert(N == 1 && "Invalid number of operands!");
3422     // The immediate encodes the type of constant as well as the value.
3423     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3424     unsigned Value = CE->getValue();
3425     Value = ARM_AM::encodeNEONi16splat(~Value & 0xffff);
3426     Inst.addOperand(MCOperand::createImm(Value));
3427   }
3428 
3429   void addNEONi32splatOperands(MCInst &Inst, unsigned N) const {
3430     assert(N == 1 && "Invalid number of operands!");
3431     // The immediate encodes the type of constant as well as the value.
3432     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3433     unsigned Value = CE->getValue();
3434     Value = ARM_AM::encodeNEONi32splat(Value);
3435     Inst.addOperand(MCOperand::createImm(Value));
3436   }
3437 
3438   void addNEONi32splatNotOperands(MCInst &Inst, unsigned N) const {
3439     assert(N == 1 && "Invalid number of operands!");
3440     // The immediate encodes the type of constant as well as the value.
3441     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3442     unsigned Value = CE->getValue();
3443     Value = ARM_AM::encodeNEONi32splat(~Value);
3444     Inst.addOperand(MCOperand::createImm(Value));
3445   }
3446 
3447   void addNEONi8ReplicateOperands(MCInst &Inst, bool Inv) const {
3448     // The immediate encodes the type of constant as well as the value.
3449     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3450     assert((Inst.getOpcode() == ARM::VMOVv8i8 ||
3451             Inst.getOpcode() == ARM::VMOVv16i8) &&
3452           "All instructions that wants to replicate non-zero byte "
3453           "always must be replaced with VMOVv8i8 or VMOVv16i8.");
3454     unsigned Value = CE->getValue();
3455     if (Inv)
3456       Value = ~Value;
3457     unsigned B = Value & 0xff;
3458     B |= 0xe00; // cmode = 0b1110
3459     Inst.addOperand(MCOperand::createImm(B));
3460   }
3461 
3462   void addNEONinvi8ReplicateOperands(MCInst &Inst, unsigned N) const {
3463     assert(N == 1 && "Invalid number of operands!");
3464     addNEONi8ReplicateOperands(Inst, true);
3465   }
3466 
3467   static unsigned encodeNeonVMOVImmediate(unsigned Value) {
3468     if (Value >= 256 && Value <= 0xffff)
3469       Value = (Value >> 8) | ((Value & 0xff) ? 0xc00 : 0x200);
3470     else if (Value > 0xffff && Value <= 0xffffff)
3471       Value = (Value >> 16) | ((Value & 0xff) ? 0xd00 : 0x400);
3472     else if (Value > 0xffffff)
3473       Value = (Value >> 24) | 0x600;
3474     return Value;
3475   }
3476 
3477   void addNEONi32vmovOperands(MCInst &Inst, unsigned N) const {
3478     assert(N == 1 && "Invalid number of operands!");
3479     // The immediate encodes the type of constant as well as the value.
3480     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3481     unsigned Value = encodeNeonVMOVImmediate(CE->getValue());
3482     Inst.addOperand(MCOperand::createImm(Value));
3483   }
3484 
3485   void addNEONvmovi8ReplicateOperands(MCInst &Inst, unsigned N) const {
3486     assert(N == 1 && "Invalid number of operands!");
3487     addNEONi8ReplicateOperands(Inst, false);
3488   }
3489 
3490   void addNEONvmovi16ReplicateOperands(MCInst &Inst, unsigned N) const {
3491     assert(N == 1 && "Invalid number of operands!");
3492     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3493     assert((Inst.getOpcode() == ARM::VMOVv4i16 ||
3494             Inst.getOpcode() == ARM::VMOVv8i16 ||
3495             Inst.getOpcode() == ARM::VMVNv4i16 ||
3496             Inst.getOpcode() == ARM::VMVNv8i16) &&
3497           "All instructions that want to replicate non-zero half-word "
3498           "always must be replaced with V{MOV,MVN}v{4,8}i16.");
3499     uint64_t Value = CE->getValue();
3500     unsigned Elem = Value & 0xffff;
3501     if (Elem >= 256)
3502       Elem = (Elem >> 8) | 0x200;
3503     Inst.addOperand(MCOperand::createImm(Elem));
3504   }
3505 
3506   void addNEONi32vmovNegOperands(MCInst &Inst, unsigned N) const {
3507     assert(N == 1 && "Invalid number of operands!");
3508     // The immediate encodes the type of constant as well as the value.
3509     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3510     unsigned Value = encodeNeonVMOVImmediate(~CE->getValue());
3511     Inst.addOperand(MCOperand::createImm(Value));
3512   }
3513 
3514   void addNEONvmovi32ReplicateOperands(MCInst &Inst, unsigned N) const {
3515     assert(N == 1 && "Invalid number of operands!");
3516     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3517     assert((Inst.getOpcode() == ARM::VMOVv2i32 ||
3518             Inst.getOpcode() == ARM::VMOVv4i32 ||
3519             Inst.getOpcode() == ARM::VMVNv2i32 ||
3520             Inst.getOpcode() == ARM::VMVNv4i32) &&
3521           "All instructions that want to replicate non-zero word "
3522           "always must be replaced with V{MOV,MVN}v{2,4}i32.");
3523     uint64_t Value = CE->getValue();
3524     unsigned Elem = encodeNeonVMOVImmediate(Value & 0xffffffff);
3525     Inst.addOperand(MCOperand::createImm(Elem));
3526   }
3527 
3528   void addNEONi64splatOperands(MCInst &Inst, unsigned N) const {
3529     assert(N == 1 && "Invalid number of operands!");
3530     // The immediate encodes the type of constant as well as the value.
3531     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3532     uint64_t Value = CE->getValue();
3533     unsigned Imm = 0;
3534     for (unsigned i = 0; i < 8; ++i, Value >>= 8) {
3535       Imm |= (Value & 1) << i;
3536     }
3537     Inst.addOperand(MCOperand::createImm(Imm | 0x1e00));
3538   }
3539 
3540   void addComplexRotationEvenOperands(MCInst &Inst, unsigned N) const {
3541     assert(N == 1 && "Invalid number of operands!");
3542     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3543     Inst.addOperand(MCOperand::createImm(CE->getValue() / 90));
3544   }
3545 
3546   void addComplexRotationOddOperands(MCInst &Inst, unsigned N) const {
3547     assert(N == 1 && "Invalid number of operands!");
3548     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3549     Inst.addOperand(MCOperand::createImm((CE->getValue() - 90) / 180));
3550   }
3551 
3552   void addMveSaturateOperands(MCInst &Inst, unsigned N) const {
3553     assert(N == 1 && "Invalid number of operands!");
3554     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3555     unsigned Imm = CE->getValue();
3556     assert((Imm == 48 || Imm == 64) && "Invalid saturate operand");
3557     Inst.addOperand(MCOperand::createImm(Imm == 48 ? 1 : 0));
3558   }
3559 
3560   void print(raw_ostream &OS) const override;
3561 
3562   static std::unique_ptr<ARMOperand> CreateITMask(unsigned Mask, SMLoc S) {
3563     auto Op = std::make_unique<ARMOperand>(k_ITCondMask);
3564     Op->ITMask.Mask = Mask;
3565     Op->StartLoc = S;
3566     Op->EndLoc = S;
3567     return Op;
3568   }
3569 
3570   static std::unique_ptr<ARMOperand> CreateCondCode(ARMCC::CondCodes CC,
3571                                                     SMLoc S) {
3572     auto Op = std::make_unique<ARMOperand>(k_CondCode);
3573     Op->CC.Val = CC;
3574     Op->StartLoc = S;
3575     Op->EndLoc = S;
3576     return Op;
3577   }
3578 
3579   static std::unique_ptr<ARMOperand> CreateVPTPred(ARMVCC::VPTCodes CC,
3580                                                    SMLoc S) {
3581     auto Op = std::make_unique<ARMOperand>(k_VPTPred);
3582     Op->VCC.Val = CC;
3583     Op->StartLoc = S;
3584     Op->EndLoc = S;
3585     return Op;
3586   }
3587 
3588   static std::unique_ptr<ARMOperand> CreateCoprocNum(unsigned CopVal, SMLoc S) {
3589     auto Op = std::make_unique<ARMOperand>(k_CoprocNum);
3590     Op->Cop.Val = CopVal;
3591     Op->StartLoc = S;
3592     Op->EndLoc = S;
3593     return Op;
3594   }
3595 
3596   static std::unique_ptr<ARMOperand> CreateCoprocReg(unsigned CopVal, SMLoc S) {
3597     auto Op = std::make_unique<ARMOperand>(k_CoprocReg);
3598     Op->Cop.Val = CopVal;
3599     Op->StartLoc = S;
3600     Op->EndLoc = S;
3601     return Op;
3602   }
3603 
3604   static std::unique_ptr<ARMOperand> CreateCoprocOption(unsigned Val, SMLoc S,
3605                                                         SMLoc E) {
3606     auto Op = std::make_unique<ARMOperand>(k_CoprocOption);
3607     Op->Cop.Val = Val;
3608     Op->StartLoc = S;
3609     Op->EndLoc = E;
3610     return Op;
3611   }
3612 
3613   static std::unique_ptr<ARMOperand> CreateCCOut(unsigned RegNum, SMLoc S) {
3614     auto Op = std::make_unique<ARMOperand>(k_CCOut);
3615     Op->Reg.RegNum = RegNum;
3616     Op->StartLoc = S;
3617     Op->EndLoc = S;
3618     return Op;
3619   }
3620 
3621   static std::unique_ptr<ARMOperand> CreateToken(StringRef Str, SMLoc S) {
3622     auto Op = std::make_unique<ARMOperand>(k_Token);
3623     Op->Tok.Data = Str.data();
3624     Op->Tok.Length = Str.size();
3625     Op->StartLoc = S;
3626     Op->EndLoc = S;
3627     return Op;
3628   }
3629 
3630   static std::unique_ptr<ARMOperand> CreateReg(unsigned RegNum, SMLoc S,
3631                                                SMLoc E) {
3632     auto Op = std::make_unique<ARMOperand>(k_Register);
3633     Op->Reg.RegNum = RegNum;
3634     Op->StartLoc = S;
3635     Op->EndLoc = E;
3636     return Op;
3637   }
3638 
3639   static std::unique_ptr<ARMOperand>
3640   CreateShiftedRegister(ARM_AM::ShiftOpc ShTy, unsigned SrcReg,
3641                         unsigned ShiftReg, unsigned ShiftImm, SMLoc S,
3642                         SMLoc E) {
3643     auto Op = std::make_unique<ARMOperand>(k_ShiftedRegister);
3644     Op->RegShiftedReg.ShiftTy = ShTy;
3645     Op->RegShiftedReg.SrcReg = SrcReg;
3646     Op->RegShiftedReg.ShiftReg = ShiftReg;
3647     Op->RegShiftedReg.ShiftImm = ShiftImm;
3648     Op->StartLoc = S;
3649     Op->EndLoc = E;
3650     return Op;
3651   }
3652 
3653   static std::unique_ptr<ARMOperand>
3654   CreateShiftedImmediate(ARM_AM::ShiftOpc ShTy, unsigned SrcReg,
3655                          unsigned ShiftImm, SMLoc S, SMLoc E) {
3656     auto Op = std::make_unique<ARMOperand>(k_ShiftedImmediate);
3657     Op->RegShiftedImm.ShiftTy = ShTy;
3658     Op->RegShiftedImm.SrcReg = SrcReg;
3659     Op->RegShiftedImm.ShiftImm = ShiftImm;
3660     Op->StartLoc = S;
3661     Op->EndLoc = E;
3662     return Op;
3663   }
3664 
3665   static std::unique_ptr<ARMOperand> CreateShifterImm(bool isASR, unsigned Imm,
3666                                                       SMLoc S, SMLoc E) {
3667     auto Op = std::make_unique<ARMOperand>(k_ShifterImmediate);
3668     Op->ShifterImm.isASR = isASR;
3669     Op->ShifterImm.Imm = Imm;
3670     Op->StartLoc = S;
3671     Op->EndLoc = E;
3672     return Op;
3673   }
3674 
3675   static std::unique_ptr<ARMOperand> CreateRotImm(unsigned Imm, SMLoc S,
3676                                                   SMLoc E) {
3677     auto Op = std::make_unique<ARMOperand>(k_RotateImmediate);
3678     Op->RotImm.Imm = Imm;
3679     Op->StartLoc = S;
3680     Op->EndLoc = E;
3681     return Op;
3682   }
3683 
3684   static std::unique_ptr<ARMOperand> CreateModImm(unsigned Bits, unsigned Rot,
3685                                                   SMLoc S, SMLoc E) {
3686     auto Op = std::make_unique<ARMOperand>(k_ModifiedImmediate);
3687     Op->ModImm.Bits = Bits;
3688     Op->ModImm.Rot = Rot;
3689     Op->StartLoc = S;
3690     Op->EndLoc = E;
3691     return Op;
3692   }
3693 
3694   static std::unique_ptr<ARMOperand>
3695   CreateConstantPoolImm(const MCExpr *Val, SMLoc S, SMLoc E) {
3696     auto Op = std::make_unique<ARMOperand>(k_ConstantPoolImmediate);
3697     Op->Imm.Val = Val;
3698     Op->StartLoc = S;
3699     Op->EndLoc = E;
3700     return Op;
3701   }
3702 
3703   static std::unique_ptr<ARMOperand>
3704   CreateBitfield(unsigned LSB, unsigned Width, SMLoc S, SMLoc E) {
3705     auto Op = std::make_unique<ARMOperand>(k_BitfieldDescriptor);
3706     Op->Bitfield.LSB = LSB;
3707     Op->Bitfield.Width = Width;
3708     Op->StartLoc = S;
3709     Op->EndLoc = E;
3710     return Op;
3711   }
3712 
3713   static std::unique_ptr<ARMOperand>
3714   CreateRegList(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs,
3715                 SMLoc StartLoc, SMLoc EndLoc) {
3716     assert(Regs.size() > 0 && "RegList contains no registers?");
3717     KindTy Kind = k_RegisterList;
3718 
3719     if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(
3720             Regs.front().second)) {
3721       if (Regs.back().second == ARM::VPR)
3722         Kind = k_FPDRegisterListWithVPR;
3723       else
3724         Kind = k_DPRRegisterList;
3725     } else if (ARMMCRegisterClasses[ARM::SPRRegClassID].contains(
3726                    Regs.front().second)) {
3727       if (Regs.back().second == ARM::VPR)
3728         Kind = k_FPSRegisterListWithVPR;
3729       else
3730         Kind = k_SPRRegisterList;
3731     }
3732 
3733     if (Kind == k_RegisterList && Regs.back().second == ARM::APSR)
3734       Kind = k_RegisterListWithAPSR;
3735 
3736     assert(llvm::is_sorted(Regs) && "Register list must be sorted by encoding");
3737 
3738     auto Op = std::make_unique<ARMOperand>(Kind);
3739     for (const auto &P : Regs)
3740       Op->Registers.push_back(P.second);
3741 
3742     Op->StartLoc = StartLoc;
3743     Op->EndLoc = EndLoc;
3744     return Op;
3745   }
3746 
3747   static std::unique_ptr<ARMOperand> CreateVectorList(unsigned RegNum,
3748                                                       unsigned Count,
3749                                                       bool isDoubleSpaced,
3750                                                       SMLoc S, SMLoc E) {
3751     auto Op = std::make_unique<ARMOperand>(k_VectorList);
3752     Op->VectorList.RegNum = RegNum;
3753     Op->VectorList.Count = Count;
3754     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
3755     Op->StartLoc = S;
3756     Op->EndLoc = E;
3757     return Op;
3758   }
3759 
3760   static std::unique_ptr<ARMOperand>
3761   CreateVectorListAllLanes(unsigned RegNum, unsigned Count, bool isDoubleSpaced,
3762                            SMLoc S, SMLoc E) {
3763     auto Op = std::make_unique<ARMOperand>(k_VectorListAllLanes);
3764     Op->VectorList.RegNum = RegNum;
3765     Op->VectorList.Count = Count;
3766     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
3767     Op->StartLoc = S;
3768     Op->EndLoc = E;
3769     return Op;
3770   }
3771 
3772   static std::unique_ptr<ARMOperand>
3773   CreateVectorListIndexed(unsigned RegNum, unsigned Count, unsigned Index,
3774                           bool isDoubleSpaced, SMLoc S, SMLoc E) {
3775     auto Op = std::make_unique<ARMOperand>(k_VectorListIndexed);
3776     Op->VectorList.RegNum = RegNum;
3777     Op->VectorList.Count = Count;
3778     Op->VectorList.LaneIndex = Index;
3779     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
3780     Op->StartLoc = S;
3781     Op->EndLoc = E;
3782     return Op;
3783   }
3784 
3785   static std::unique_ptr<ARMOperand>
3786   CreateVectorIndex(unsigned Idx, SMLoc S, SMLoc E, MCContext &Ctx) {
3787     auto Op = std::make_unique<ARMOperand>(k_VectorIndex);
3788     Op->VectorIndex.Val = Idx;
3789     Op->StartLoc = S;
3790     Op->EndLoc = E;
3791     return Op;
3792   }
3793 
3794   static std::unique_ptr<ARMOperand> CreateImm(const MCExpr *Val, SMLoc S,
3795                                                SMLoc E) {
3796     auto Op = std::make_unique<ARMOperand>(k_Immediate);
3797     Op->Imm.Val = Val;
3798     Op->StartLoc = S;
3799     Op->EndLoc = E;
3800     return Op;
3801   }
3802 
3803   static std::unique_ptr<ARMOperand>
3804   CreateMem(unsigned BaseRegNum, const MCExpr *OffsetImm, unsigned OffsetRegNum,
3805             ARM_AM::ShiftOpc ShiftType, unsigned ShiftImm, unsigned Alignment,
3806             bool isNegative, SMLoc S, SMLoc E, SMLoc AlignmentLoc = SMLoc()) {
3807     auto Op = std::make_unique<ARMOperand>(k_Memory);
3808     Op->Memory.BaseRegNum = BaseRegNum;
3809     Op->Memory.OffsetImm = OffsetImm;
3810     Op->Memory.OffsetRegNum = OffsetRegNum;
3811     Op->Memory.ShiftType = ShiftType;
3812     Op->Memory.ShiftImm = ShiftImm;
3813     Op->Memory.Alignment = Alignment;
3814     Op->Memory.isNegative = isNegative;
3815     Op->StartLoc = S;
3816     Op->EndLoc = E;
3817     Op->AlignmentLoc = AlignmentLoc;
3818     return Op;
3819   }
3820 
3821   static std::unique_ptr<ARMOperand>
3822   CreatePostIdxReg(unsigned RegNum, bool isAdd, ARM_AM::ShiftOpc ShiftTy,
3823                    unsigned ShiftImm, SMLoc S, SMLoc E) {
3824     auto Op = std::make_unique<ARMOperand>(k_PostIndexRegister);
3825     Op->PostIdxReg.RegNum = RegNum;
3826     Op->PostIdxReg.isAdd = isAdd;
3827     Op->PostIdxReg.ShiftTy = ShiftTy;
3828     Op->PostIdxReg.ShiftImm = ShiftImm;
3829     Op->StartLoc = S;
3830     Op->EndLoc = E;
3831     return Op;
3832   }
3833 
3834   static std::unique_ptr<ARMOperand> CreateMemBarrierOpt(ARM_MB::MemBOpt Opt,
3835                                                          SMLoc S) {
3836     auto Op = std::make_unique<ARMOperand>(k_MemBarrierOpt);
3837     Op->MBOpt.Val = Opt;
3838     Op->StartLoc = S;
3839     Op->EndLoc = S;
3840     return Op;
3841   }
3842 
3843   static std::unique_ptr<ARMOperand>
3844   CreateInstSyncBarrierOpt(ARM_ISB::InstSyncBOpt Opt, SMLoc S) {
3845     auto Op = std::make_unique<ARMOperand>(k_InstSyncBarrierOpt);
3846     Op->ISBOpt.Val = Opt;
3847     Op->StartLoc = S;
3848     Op->EndLoc = S;
3849     return Op;
3850   }
3851 
3852   static std::unique_ptr<ARMOperand>
3853   CreateTraceSyncBarrierOpt(ARM_TSB::TraceSyncBOpt Opt, SMLoc S) {
3854     auto Op = std::make_unique<ARMOperand>(k_TraceSyncBarrierOpt);
3855     Op->TSBOpt.Val = Opt;
3856     Op->StartLoc = S;
3857     Op->EndLoc = S;
3858     return Op;
3859   }
3860 
3861   static std::unique_ptr<ARMOperand> CreateProcIFlags(ARM_PROC::IFlags IFlags,
3862                                                       SMLoc S) {
3863     auto Op = std::make_unique<ARMOperand>(k_ProcIFlags);
3864     Op->IFlags.Val = IFlags;
3865     Op->StartLoc = S;
3866     Op->EndLoc = S;
3867     return Op;
3868   }
3869 
3870   static std::unique_ptr<ARMOperand> CreateMSRMask(unsigned MMask, SMLoc S) {
3871     auto Op = std::make_unique<ARMOperand>(k_MSRMask);
3872     Op->MMask.Val = MMask;
3873     Op->StartLoc = S;
3874     Op->EndLoc = S;
3875     return Op;
3876   }
3877 
3878   static std::unique_ptr<ARMOperand> CreateBankedReg(unsigned Reg, SMLoc S) {
3879     auto Op = std::make_unique<ARMOperand>(k_BankedReg);
3880     Op->BankedReg.Val = Reg;
3881     Op->StartLoc = S;
3882     Op->EndLoc = S;
3883     return Op;
3884   }
3885 };
3886 
3887 } // end anonymous namespace.
3888 
3889 void ARMOperand::print(raw_ostream &OS) const {
3890   auto RegName = [](unsigned Reg) {
3891     if (Reg)
3892       return ARMInstPrinter::getRegisterName(Reg);
3893     else
3894       return "noreg";
3895   };
3896 
3897   switch (Kind) {
3898   case k_CondCode:
3899     OS << "<ARMCC::" << ARMCondCodeToString(getCondCode()) << ">";
3900     break;
3901   case k_VPTPred:
3902     OS << "<ARMVCC::" << ARMVPTPredToString(getVPTPred()) << ">";
3903     break;
3904   case k_CCOut:
3905     OS << "<ccout " << RegName(getReg()) << ">";
3906     break;
3907   case k_ITCondMask: {
3908     static const char *const MaskStr[] = {
3909       "(invalid)", "(tttt)", "(ttt)", "(ttte)",
3910       "(tt)",      "(ttet)", "(tte)", "(ttee)",
3911       "(t)",       "(tett)", "(tet)", "(tete)",
3912       "(te)",      "(teet)", "(tee)", "(teee)",
3913     };
3914     assert((ITMask.Mask & 0xf) == ITMask.Mask);
3915     OS << "<it-mask " << MaskStr[ITMask.Mask] << ">";
3916     break;
3917   }
3918   case k_CoprocNum:
3919     OS << "<coprocessor number: " << getCoproc() << ">";
3920     break;
3921   case k_CoprocReg:
3922     OS << "<coprocessor register: " << getCoproc() << ">";
3923     break;
3924   case k_CoprocOption:
3925     OS << "<coprocessor option: " << CoprocOption.Val << ">";
3926     break;
3927   case k_MSRMask:
3928     OS << "<mask: " << getMSRMask() << ">";
3929     break;
3930   case k_BankedReg:
3931     OS << "<banked reg: " << getBankedReg() << ">";
3932     break;
3933   case k_Immediate:
3934     OS << *getImm();
3935     break;
3936   case k_MemBarrierOpt:
3937     OS << "<ARM_MB::" << MemBOptToString(getMemBarrierOpt(), false) << ">";
3938     break;
3939   case k_InstSyncBarrierOpt:
3940     OS << "<ARM_ISB::" << InstSyncBOptToString(getInstSyncBarrierOpt()) << ">";
3941     break;
3942   case k_TraceSyncBarrierOpt:
3943     OS << "<ARM_TSB::" << TraceSyncBOptToString(getTraceSyncBarrierOpt()) << ">";
3944     break;
3945   case k_Memory:
3946     OS << "<memory";
3947     if (Memory.BaseRegNum)
3948       OS << " base:" << RegName(Memory.BaseRegNum);
3949     if (Memory.OffsetImm)
3950       OS << " offset-imm:" << *Memory.OffsetImm;
3951     if (Memory.OffsetRegNum)
3952       OS << " offset-reg:" << (Memory.isNegative ? "-" : "")
3953          << RegName(Memory.OffsetRegNum);
3954     if (Memory.ShiftType != ARM_AM::no_shift) {
3955       OS << " shift-type:" << ARM_AM::getShiftOpcStr(Memory.ShiftType);
3956       OS << " shift-imm:" << Memory.ShiftImm;
3957     }
3958     if (Memory.Alignment)
3959       OS << " alignment:" << Memory.Alignment;
3960     OS << ">";
3961     break;
3962   case k_PostIndexRegister:
3963     OS << "post-idx register " << (PostIdxReg.isAdd ? "" : "-")
3964        << RegName(PostIdxReg.RegNum);
3965     if (PostIdxReg.ShiftTy != ARM_AM::no_shift)
3966       OS << ARM_AM::getShiftOpcStr(PostIdxReg.ShiftTy) << " "
3967          << PostIdxReg.ShiftImm;
3968     OS << ">";
3969     break;
3970   case k_ProcIFlags: {
3971     OS << "<ARM_PROC::";
3972     unsigned IFlags = getProcIFlags();
3973     for (int i=2; i >= 0; --i)
3974       if (IFlags & (1 << i))
3975         OS << ARM_PROC::IFlagsToString(1 << i);
3976     OS << ">";
3977     break;
3978   }
3979   case k_Register:
3980     OS << "<register " << RegName(getReg()) << ">";
3981     break;
3982   case k_ShifterImmediate:
3983     OS << "<shift " << (ShifterImm.isASR ? "asr" : "lsl")
3984        << " #" << ShifterImm.Imm << ">";
3985     break;
3986   case k_ShiftedRegister:
3987     OS << "<so_reg_reg " << RegName(RegShiftedReg.SrcReg) << " "
3988        << ARM_AM::getShiftOpcStr(RegShiftedReg.ShiftTy) << " "
3989        << RegName(RegShiftedReg.ShiftReg) << ">";
3990     break;
3991   case k_ShiftedImmediate:
3992     OS << "<so_reg_imm " << RegName(RegShiftedImm.SrcReg) << " "
3993        << ARM_AM::getShiftOpcStr(RegShiftedImm.ShiftTy) << " #"
3994        << RegShiftedImm.ShiftImm << ">";
3995     break;
3996   case k_RotateImmediate:
3997     OS << "<ror " << " #" << (RotImm.Imm * 8) << ">";
3998     break;
3999   case k_ModifiedImmediate:
4000     OS << "<mod_imm #" << ModImm.Bits << ", #"
4001        <<  ModImm.Rot << ")>";
4002     break;
4003   case k_ConstantPoolImmediate:
4004     OS << "<constant_pool_imm #" << *getConstantPoolImm();
4005     break;
4006   case k_BitfieldDescriptor:
4007     OS << "<bitfield " << "lsb: " << Bitfield.LSB
4008        << ", width: " << Bitfield.Width << ">";
4009     break;
4010   case k_RegisterList:
4011   case k_RegisterListWithAPSR:
4012   case k_DPRRegisterList:
4013   case k_SPRRegisterList:
4014   case k_FPSRegisterListWithVPR:
4015   case k_FPDRegisterListWithVPR: {
4016     OS << "<register_list ";
4017 
4018     const SmallVectorImpl<unsigned> &RegList = getRegList();
4019     for (SmallVectorImpl<unsigned>::const_iterator
4020            I = RegList.begin(), E = RegList.end(); I != E; ) {
4021       OS << RegName(*I);
4022       if (++I < E) OS << ", ";
4023     }
4024 
4025     OS << ">";
4026     break;
4027   }
4028   case k_VectorList:
4029     OS << "<vector_list " << VectorList.Count << " * "
4030        << RegName(VectorList.RegNum) << ">";
4031     break;
4032   case k_VectorListAllLanes:
4033     OS << "<vector_list(all lanes) " << VectorList.Count << " * "
4034        << RegName(VectorList.RegNum) << ">";
4035     break;
4036   case k_VectorListIndexed:
4037     OS << "<vector_list(lane " << VectorList.LaneIndex << ") "
4038        << VectorList.Count << " * " << RegName(VectorList.RegNum) << ">";
4039     break;
4040   case k_Token:
4041     OS << "'" << getToken() << "'";
4042     break;
4043   case k_VectorIndex:
4044     OS << "<vectorindex " << getVectorIndex() << ">";
4045     break;
4046   }
4047 }
4048 
4049 /// @name Auto-generated Match Functions
4050 /// {
4051 
4052 static unsigned MatchRegisterName(StringRef Name);
4053 
4054 /// }
4055 
4056 bool ARMAsmParser::ParseRegister(unsigned &RegNo,
4057                                  SMLoc &StartLoc, SMLoc &EndLoc) {
4058   const AsmToken &Tok = getParser().getTok();
4059   StartLoc = Tok.getLoc();
4060   EndLoc = Tok.getEndLoc();
4061   RegNo = tryParseRegister();
4062 
4063   return (RegNo == (unsigned)-1);
4064 }
4065 
4066 OperandMatchResultTy ARMAsmParser::tryParseRegister(unsigned &RegNo,
4067                                                     SMLoc &StartLoc,
4068                                                     SMLoc &EndLoc) {
4069   if (ParseRegister(RegNo, StartLoc, EndLoc))
4070     return MatchOperand_NoMatch;
4071   return MatchOperand_Success;
4072 }
4073 
4074 /// Try to parse a register name.  The token must be an Identifier when called,
4075 /// and if it is a register name the token is eaten and the register number is
4076 /// returned.  Otherwise return -1.
4077 int ARMAsmParser::tryParseRegister() {
4078   MCAsmParser &Parser = getParser();
4079   const AsmToken &Tok = Parser.getTok();
4080   if (Tok.isNot(AsmToken::Identifier)) return -1;
4081 
4082   std::string lowerCase = Tok.getString().lower();
4083   unsigned RegNum = MatchRegisterName(lowerCase);
4084   if (!RegNum) {
4085     RegNum = StringSwitch<unsigned>(lowerCase)
4086       .Case("r13", ARM::SP)
4087       .Case("r14", ARM::LR)
4088       .Case("r15", ARM::PC)
4089       .Case("ip", ARM::R12)
4090       // Additional register name aliases for 'gas' compatibility.
4091       .Case("a1", ARM::R0)
4092       .Case("a2", ARM::R1)
4093       .Case("a3", ARM::R2)
4094       .Case("a4", ARM::R3)
4095       .Case("v1", ARM::R4)
4096       .Case("v2", ARM::R5)
4097       .Case("v3", ARM::R6)
4098       .Case("v4", ARM::R7)
4099       .Case("v5", ARM::R8)
4100       .Case("v6", ARM::R9)
4101       .Case("v7", ARM::R10)
4102       .Case("v8", ARM::R11)
4103       .Case("sb", ARM::R9)
4104       .Case("sl", ARM::R10)
4105       .Case("fp", ARM::R11)
4106       .Default(0);
4107   }
4108   if (!RegNum) {
4109     // Check for aliases registered via .req. Canonicalize to lower case.
4110     // That's more consistent since register names are case insensitive, and
4111     // it's how the original entry was passed in from MC/MCParser/AsmParser.
4112     StringMap<unsigned>::const_iterator Entry = RegisterReqs.find(lowerCase);
4113     // If no match, return failure.
4114     if (Entry == RegisterReqs.end())
4115       return -1;
4116     Parser.Lex(); // Eat identifier token.
4117     return Entry->getValue();
4118   }
4119 
4120   // Some FPUs only have 16 D registers, so D16-D31 are invalid
4121   if (!hasD32() && RegNum >= ARM::D16 && RegNum <= ARM::D31)
4122     return -1;
4123 
4124   Parser.Lex(); // Eat identifier token.
4125 
4126   return RegNum;
4127 }
4128 
4129 // Try to parse a shifter  (e.g., "lsl <amt>"). On success, return 0.
4130 // If a recoverable error occurs, return 1. If an irrecoverable error
4131 // occurs, return -1. An irrecoverable error is one where tokens have been
4132 // consumed in the process of trying to parse the shifter (i.e., when it is
4133 // indeed a shifter operand, but malformed).
4134 int ARMAsmParser::tryParseShiftRegister(OperandVector &Operands) {
4135   MCAsmParser &Parser = getParser();
4136   SMLoc S = Parser.getTok().getLoc();
4137   const AsmToken &Tok = Parser.getTok();
4138   if (Tok.isNot(AsmToken::Identifier))
4139     return -1;
4140 
4141   std::string lowerCase = Tok.getString().lower();
4142   ARM_AM::ShiftOpc ShiftTy = StringSwitch<ARM_AM::ShiftOpc>(lowerCase)
4143       .Case("asl", ARM_AM::lsl)
4144       .Case("lsl", ARM_AM::lsl)
4145       .Case("lsr", ARM_AM::lsr)
4146       .Case("asr", ARM_AM::asr)
4147       .Case("ror", ARM_AM::ror)
4148       .Case("rrx", ARM_AM::rrx)
4149       .Default(ARM_AM::no_shift);
4150 
4151   if (ShiftTy == ARM_AM::no_shift)
4152     return 1;
4153 
4154   Parser.Lex(); // Eat the operator.
4155 
4156   // The source register for the shift has already been added to the
4157   // operand list, so we need to pop it off and combine it into the shifted
4158   // register operand instead.
4159   std::unique_ptr<ARMOperand> PrevOp(
4160       (ARMOperand *)Operands.pop_back_val().release());
4161   if (!PrevOp->isReg())
4162     return Error(PrevOp->getStartLoc(), "shift must be of a register");
4163   int SrcReg = PrevOp->getReg();
4164 
4165   SMLoc EndLoc;
4166   int64_t Imm = 0;
4167   int ShiftReg = 0;
4168   if (ShiftTy == ARM_AM::rrx) {
4169     // RRX Doesn't have an explicit shift amount. The encoder expects
4170     // the shift register to be the same as the source register. Seems odd,
4171     // but OK.
4172     ShiftReg = SrcReg;
4173   } else {
4174     // Figure out if this is shifted by a constant or a register (for non-RRX).
4175     if (Parser.getTok().is(AsmToken::Hash) ||
4176         Parser.getTok().is(AsmToken::Dollar)) {
4177       Parser.Lex(); // Eat hash.
4178       SMLoc ImmLoc = Parser.getTok().getLoc();
4179       const MCExpr *ShiftExpr = nullptr;
4180       if (getParser().parseExpression(ShiftExpr, EndLoc)) {
4181         Error(ImmLoc, "invalid immediate shift value");
4182         return -1;
4183       }
4184       // The expression must be evaluatable as an immediate.
4185       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftExpr);
4186       if (!CE) {
4187         Error(ImmLoc, "invalid immediate shift value");
4188         return -1;
4189       }
4190       // Range check the immediate.
4191       // lsl, ror: 0 <= imm <= 31
4192       // lsr, asr: 0 <= imm <= 32
4193       Imm = CE->getValue();
4194       if (Imm < 0 ||
4195           ((ShiftTy == ARM_AM::lsl || ShiftTy == ARM_AM::ror) && Imm > 31) ||
4196           ((ShiftTy == ARM_AM::lsr || ShiftTy == ARM_AM::asr) && Imm > 32)) {
4197         Error(ImmLoc, "immediate shift value out of range");
4198         return -1;
4199       }
4200       // shift by zero is a nop. Always send it through as lsl.
4201       // ('as' compatibility)
4202       if (Imm == 0)
4203         ShiftTy = ARM_AM::lsl;
4204     } else if (Parser.getTok().is(AsmToken::Identifier)) {
4205       SMLoc L = Parser.getTok().getLoc();
4206       EndLoc = Parser.getTok().getEndLoc();
4207       ShiftReg = tryParseRegister();
4208       if (ShiftReg == -1) {
4209         Error(L, "expected immediate or register in shift operand");
4210         return -1;
4211       }
4212     } else {
4213       Error(Parser.getTok().getLoc(),
4214             "expected immediate or register in shift operand");
4215       return -1;
4216     }
4217   }
4218 
4219   if (ShiftReg && ShiftTy != ARM_AM::rrx)
4220     Operands.push_back(ARMOperand::CreateShiftedRegister(ShiftTy, SrcReg,
4221                                                          ShiftReg, Imm,
4222                                                          S, EndLoc));
4223   else
4224     Operands.push_back(ARMOperand::CreateShiftedImmediate(ShiftTy, SrcReg, Imm,
4225                                                           S, EndLoc));
4226 
4227   return 0;
4228 }
4229 
4230 /// Try to parse a register name.  The token must be an Identifier when called.
4231 /// If it's a register, an AsmOperand is created. Another AsmOperand is created
4232 /// if there is a "writeback". 'true' if it's not a register.
4233 ///
4234 /// TODO this is likely to change to allow different register types and or to
4235 /// parse for a specific register type.
4236 bool ARMAsmParser::tryParseRegisterWithWriteBack(OperandVector &Operands) {
4237   MCAsmParser &Parser = getParser();
4238   SMLoc RegStartLoc = Parser.getTok().getLoc();
4239   SMLoc RegEndLoc = Parser.getTok().getEndLoc();
4240   int RegNo = tryParseRegister();
4241   if (RegNo == -1)
4242     return true;
4243 
4244   Operands.push_back(ARMOperand::CreateReg(RegNo, RegStartLoc, RegEndLoc));
4245 
4246   const AsmToken &ExclaimTok = Parser.getTok();
4247   if (ExclaimTok.is(AsmToken::Exclaim)) {
4248     Operands.push_back(ARMOperand::CreateToken(ExclaimTok.getString(),
4249                                                ExclaimTok.getLoc()));
4250     Parser.Lex(); // Eat exclaim token
4251     return false;
4252   }
4253 
4254   // Also check for an index operand. This is only legal for vector registers,
4255   // but that'll get caught OK in operand matching, so we don't need to
4256   // explicitly filter everything else out here.
4257   if (Parser.getTok().is(AsmToken::LBrac)) {
4258     SMLoc SIdx = Parser.getTok().getLoc();
4259     Parser.Lex(); // Eat left bracket token.
4260 
4261     const MCExpr *ImmVal;
4262     if (getParser().parseExpression(ImmVal))
4263       return true;
4264     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(ImmVal);
4265     if (!MCE)
4266       return TokError("immediate value expected for vector index");
4267 
4268     if (Parser.getTok().isNot(AsmToken::RBrac))
4269       return Error(Parser.getTok().getLoc(), "']' expected");
4270 
4271     SMLoc E = Parser.getTok().getEndLoc();
4272     Parser.Lex(); // Eat right bracket token.
4273 
4274     Operands.push_back(ARMOperand::CreateVectorIndex(MCE->getValue(),
4275                                                      SIdx, E,
4276                                                      getContext()));
4277   }
4278 
4279   return false;
4280 }
4281 
4282 /// MatchCoprocessorOperandName - Try to parse an coprocessor related
4283 /// instruction with a symbolic operand name.
4284 /// We accept "crN" syntax for GAS compatibility.
4285 /// <operand-name> ::= <prefix><number>
4286 /// If CoprocOp is 'c', then:
4287 ///   <prefix> ::= c | cr
4288 /// If CoprocOp is 'p', then :
4289 ///   <prefix> ::= p
4290 /// <number> ::= integer in range [0, 15]
4291 static int MatchCoprocessorOperandName(StringRef Name, char CoprocOp) {
4292   // Use the same layout as the tablegen'erated register name matcher. Ugly,
4293   // but efficient.
4294   if (Name.size() < 2 || Name[0] != CoprocOp)
4295     return -1;
4296   Name = (Name[1] == 'r') ? Name.drop_front(2) : Name.drop_front();
4297 
4298   switch (Name.size()) {
4299   default: return -1;
4300   case 1:
4301     switch (Name[0]) {
4302     default:  return -1;
4303     case '0': return 0;
4304     case '1': return 1;
4305     case '2': return 2;
4306     case '3': return 3;
4307     case '4': return 4;
4308     case '5': return 5;
4309     case '6': return 6;
4310     case '7': return 7;
4311     case '8': return 8;
4312     case '9': return 9;
4313     }
4314   case 2:
4315     if (Name[0] != '1')
4316       return -1;
4317     switch (Name[1]) {
4318     default:  return -1;
4319     // CP10 and CP11 are VFP/NEON and so vector instructions should be used.
4320     // However, old cores (v5/v6) did use them in that way.
4321     case '0': return 10;
4322     case '1': return 11;
4323     case '2': return 12;
4324     case '3': return 13;
4325     case '4': return 14;
4326     case '5': return 15;
4327     }
4328   }
4329 }
4330 
4331 /// parseITCondCode - Try to parse a condition code for an IT instruction.
4332 OperandMatchResultTy
4333 ARMAsmParser::parseITCondCode(OperandVector &Operands) {
4334   MCAsmParser &Parser = getParser();
4335   SMLoc S = Parser.getTok().getLoc();
4336   const AsmToken &Tok = Parser.getTok();
4337   if (!Tok.is(AsmToken::Identifier))
4338     return MatchOperand_NoMatch;
4339   unsigned CC = ARMCondCodeFromString(Tok.getString());
4340   if (CC == ~0U)
4341     return MatchOperand_NoMatch;
4342   Parser.Lex(); // Eat the token.
4343 
4344   Operands.push_back(ARMOperand::CreateCondCode(ARMCC::CondCodes(CC), S));
4345 
4346   return MatchOperand_Success;
4347 }
4348 
4349 /// parseCoprocNumOperand - Try to parse an coprocessor number operand. The
4350 /// token must be an Identifier when called, and if it is a coprocessor
4351 /// number, the token is eaten and the operand is added to the operand list.
4352 OperandMatchResultTy
4353 ARMAsmParser::parseCoprocNumOperand(OperandVector &Operands) {
4354   MCAsmParser &Parser = getParser();
4355   SMLoc S = Parser.getTok().getLoc();
4356   const AsmToken &Tok = Parser.getTok();
4357   if (Tok.isNot(AsmToken::Identifier))
4358     return MatchOperand_NoMatch;
4359 
4360   int Num = MatchCoprocessorOperandName(Tok.getString().lower(), 'p');
4361   if (Num == -1)
4362     return MatchOperand_NoMatch;
4363   if (!isValidCoprocessorNumber(Num, getSTI().getFeatureBits()))
4364     return MatchOperand_NoMatch;
4365 
4366   Parser.Lex(); // Eat identifier token.
4367   Operands.push_back(ARMOperand::CreateCoprocNum(Num, S));
4368   return MatchOperand_Success;
4369 }
4370 
4371 /// parseCoprocRegOperand - Try to parse an coprocessor register operand. The
4372 /// token must be an Identifier when called, and if it is a coprocessor
4373 /// number, the token is eaten and the operand is added to the operand list.
4374 OperandMatchResultTy
4375 ARMAsmParser::parseCoprocRegOperand(OperandVector &Operands) {
4376   MCAsmParser &Parser = getParser();
4377   SMLoc S = Parser.getTok().getLoc();
4378   const AsmToken &Tok = Parser.getTok();
4379   if (Tok.isNot(AsmToken::Identifier))
4380     return MatchOperand_NoMatch;
4381 
4382   int Reg = MatchCoprocessorOperandName(Tok.getString().lower(), 'c');
4383   if (Reg == -1)
4384     return MatchOperand_NoMatch;
4385 
4386   Parser.Lex(); // Eat identifier token.
4387   Operands.push_back(ARMOperand::CreateCoprocReg(Reg, S));
4388   return MatchOperand_Success;
4389 }
4390 
4391 /// parseCoprocOptionOperand - Try to parse an coprocessor option operand.
4392 /// coproc_option : '{' imm0_255 '}'
4393 OperandMatchResultTy
4394 ARMAsmParser::parseCoprocOptionOperand(OperandVector &Operands) {
4395   MCAsmParser &Parser = getParser();
4396   SMLoc S = Parser.getTok().getLoc();
4397 
4398   // If this isn't a '{', this isn't a coprocessor immediate operand.
4399   if (Parser.getTok().isNot(AsmToken::LCurly))
4400     return MatchOperand_NoMatch;
4401   Parser.Lex(); // Eat the '{'
4402 
4403   const MCExpr *Expr;
4404   SMLoc Loc = Parser.getTok().getLoc();
4405   if (getParser().parseExpression(Expr)) {
4406     Error(Loc, "illegal expression");
4407     return MatchOperand_ParseFail;
4408   }
4409   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
4410   if (!CE || CE->getValue() < 0 || CE->getValue() > 255) {
4411     Error(Loc, "coprocessor option must be an immediate in range [0, 255]");
4412     return MatchOperand_ParseFail;
4413   }
4414   int Val = CE->getValue();
4415 
4416   // Check for and consume the closing '}'
4417   if (Parser.getTok().isNot(AsmToken::RCurly))
4418     return MatchOperand_ParseFail;
4419   SMLoc E = Parser.getTok().getEndLoc();
4420   Parser.Lex(); // Eat the '}'
4421 
4422   Operands.push_back(ARMOperand::CreateCoprocOption(Val, S, E));
4423   return MatchOperand_Success;
4424 }
4425 
4426 // For register list parsing, we need to map from raw GPR register numbering
4427 // to the enumeration values. The enumeration values aren't sorted by
4428 // register number due to our using "sp", "lr" and "pc" as canonical names.
4429 static unsigned getNextRegister(unsigned Reg) {
4430   // If this is a GPR, we need to do it manually, otherwise we can rely
4431   // on the sort ordering of the enumeration since the other reg-classes
4432   // are sane.
4433   if (!ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
4434     return Reg + 1;
4435   switch(Reg) {
4436   default: llvm_unreachable("Invalid GPR number!");
4437   case ARM::R0:  return ARM::R1;  case ARM::R1:  return ARM::R2;
4438   case ARM::R2:  return ARM::R3;  case ARM::R3:  return ARM::R4;
4439   case ARM::R4:  return ARM::R5;  case ARM::R5:  return ARM::R6;
4440   case ARM::R6:  return ARM::R7;  case ARM::R7:  return ARM::R8;
4441   case ARM::R8:  return ARM::R9;  case ARM::R9:  return ARM::R10;
4442   case ARM::R10: return ARM::R11; case ARM::R11: return ARM::R12;
4443   case ARM::R12: return ARM::SP;  case ARM::SP:  return ARM::LR;
4444   case ARM::LR:  return ARM::PC;  case ARM::PC:  return ARM::R0;
4445   }
4446 }
4447 
4448 // Insert an <Encoding, Register> pair in an ordered vector. Return true on
4449 // success, or false, if duplicate encoding found.
4450 static bool
4451 insertNoDuplicates(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs,
4452                    unsigned Enc, unsigned Reg) {
4453   Regs.emplace_back(Enc, Reg);
4454   for (auto I = Regs.rbegin(), J = I + 1, E = Regs.rend(); J != E; ++I, ++J) {
4455     if (J->first == Enc) {
4456       Regs.erase(J.base());
4457       return false;
4458     }
4459     if (J->first < Enc)
4460       break;
4461     std::swap(*I, *J);
4462   }
4463   return true;
4464 }
4465 
4466 /// Parse a register list.
4467 bool ARMAsmParser::parseRegisterList(OperandVector &Operands,
4468                                      bool EnforceOrder) {
4469   MCAsmParser &Parser = getParser();
4470   if (Parser.getTok().isNot(AsmToken::LCurly))
4471     return TokError("Token is not a Left Curly Brace");
4472   SMLoc S = Parser.getTok().getLoc();
4473   Parser.Lex(); // Eat '{' token.
4474   SMLoc RegLoc = Parser.getTok().getLoc();
4475 
4476   // Check the first register in the list to see what register class
4477   // this is a list of.
4478   int Reg = tryParseRegister();
4479   if (Reg == -1)
4480     return Error(RegLoc, "register expected");
4481 
4482   // The reglist instructions have at most 16 registers, so reserve
4483   // space for that many.
4484   int EReg = 0;
4485   SmallVector<std::pair<unsigned, unsigned>, 16> Registers;
4486 
4487   // Allow Q regs and just interpret them as the two D sub-registers.
4488   if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
4489     Reg = getDRegFromQReg(Reg);
4490     EReg = MRI->getEncodingValue(Reg);
4491     Registers.emplace_back(EReg, Reg);
4492     ++Reg;
4493   }
4494   const MCRegisterClass *RC;
4495   if (ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
4496     RC = &ARMMCRegisterClasses[ARM::GPRRegClassID];
4497   else if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Reg))
4498     RC = &ARMMCRegisterClasses[ARM::DPRRegClassID];
4499   else if (ARMMCRegisterClasses[ARM::SPRRegClassID].contains(Reg))
4500     RC = &ARMMCRegisterClasses[ARM::SPRRegClassID];
4501   else if (ARMMCRegisterClasses[ARM::GPRwithAPSRnospRegClassID].contains(Reg))
4502     RC = &ARMMCRegisterClasses[ARM::GPRwithAPSRnospRegClassID];
4503   else
4504     return Error(RegLoc, "invalid register in register list");
4505 
4506   // Store the register.
4507   EReg = MRI->getEncodingValue(Reg);
4508   Registers.emplace_back(EReg, Reg);
4509 
4510   // This starts immediately after the first register token in the list,
4511   // so we can see either a comma or a minus (range separator) as a legal
4512   // next token.
4513   while (Parser.getTok().is(AsmToken::Comma) ||
4514          Parser.getTok().is(AsmToken::Minus)) {
4515     if (Parser.getTok().is(AsmToken::Minus)) {
4516       Parser.Lex(); // Eat the minus.
4517       SMLoc AfterMinusLoc = Parser.getTok().getLoc();
4518       int EndReg = tryParseRegister();
4519       if (EndReg == -1)
4520         return Error(AfterMinusLoc, "register expected");
4521       // Allow Q regs and just interpret them as the two D sub-registers.
4522       if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(EndReg))
4523         EndReg = getDRegFromQReg(EndReg) + 1;
4524       // If the register is the same as the start reg, there's nothing
4525       // more to do.
4526       if (Reg == EndReg)
4527         continue;
4528       // The register must be in the same register class as the first.
4529       if (!RC->contains(EndReg))
4530         return Error(AfterMinusLoc, "invalid register in register list");
4531       // Ranges must go from low to high.
4532       if (MRI->getEncodingValue(Reg) > MRI->getEncodingValue(EndReg))
4533         return Error(AfterMinusLoc, "bad range in register list");
4534 
4535       // Add all the registers in the range to the register list.
4536       while (Reg != EndReg) {
4537         Reg = getNextRegister(Reg);
4538         EReg = MRI->getEncodingValue(Reg);
4539         if (!insertNoDuplicates(Registers, EReg, Reg)) {
4540           Warning(AfterMinusLoc, StringRef("duplicated register (") +
4541                                      ARMInstPrinter::getRegisterName(Reg) +
4542                                      ") in register list");
4543         }
4544       }
4545       continue;
4546     }
4547     Parser.Lex(); // Eat the comma.
4548     RegLoc = Parser.getTok().getLoc();
4549     int OldReg = Reg;
4550     const AsmToken RegTok = Parser.getTok();
4551     Reg = tryParseRegister();
4552     if (Reg == -1)
4553       return Error(RegLoc, "register expected");
4554     // Allow Q regs and just interpret them as the two D sub-registers.
4555     bool isQReg = false;
4556     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
4557       Reg = getDRegFromQReg(Reg);
4558       isQReg = true;
4559     }
4560     if (!RC->contains(Reg) &&
4561         RC->getID() == ARMMCRegisterClasses[ARM::GPRRegClassID].getID() &&
4562         ARMMCRegisterClasses[ARM::GPRwithAPSRnospRegClassID].contains(Reg)) {
4563       // switch the register classes, as GPRwithAPSRnospRegClassID is a partial
4564       // subset of GPRRegClassId except it contains APSR as well.
4565       RC = &ARMMCRegisterClasses[ARM::GPRwithAPSRnospRegClassID];
4566     }
4567     if (Reg == ARM::VPR &&
4568         (RC == &ARMMCRegisterClasses[ARM::SPRRegClassID] ||
4569          RC == &ARMMCRegisterClasses[ARM::DPRRegClassID] ||
4570          RC == &ARMMCRegisterClasses[ARM::FPWithVPRRegClassID])) {
4571       RC = &ARMMCRegisterClasses[ARM::FPWithVPRRegClassID];
4572       EReg = MRI->getEncodingValue(Reg);
4573       if (!insertNoDuplicates(Registers, EReg, Reg)) {
4574         Warning(RegLoc, "duplicated register (" + RegTok.getString() +
4575                             ") in register list");
4576       }
4577       continue;
4578     }
4579     // The register must be in the same register class as the first.
4580     if (!RC->contains(Reg))
4581       return Error(RegLoc, "invalid register in register list");
4582     // In most cases, the list must be monotonically increasing. An
4583     // exception is CLRM, which is order-independent anyway, so
4584     // there's no potential for confusion if you write clrm {r2,r1}
4585     // instead of clrm {r1,r2}.
4586     if (EnforceOrder &&
4587         MRI->getEncodingValue(Reg) < MRI->getEncodingValue(OldReg)) {
4588       if (ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
4589         Warning(RegLoc, "register list not in ascending order");
4590       else if (!ARMMCRegisterClasses[ARM::GPRwithAPSRnospRegClassID].contains(Reg))
4591         return Error(RegLoc, "register list not in ascending order");
4592     }
4593     // VFP register lists must also be contiguous.
4594     if (RC != &ARMMCRegisterClasses[ARM::GPRRegClassID] &&
4595         RC != &ARMMCRegisterClasses[ARM::GPRwithAPSRnospRegClassID] &&
4596         Reg != OldReg + 1)
4597       return Error(RegLoc, "non-contiguous register range");
4598     EReg = MRI->getEncodingValue(Reg);
4599     if (!insertNoDuplicates(Registers, EReg, Reg)) {
4600       Warning(RegLoc, "duplicated register (" + RegTok.getString() +
4601                           ") in register list");
4602     }
4603     if (isQReg) {
4604       EReg = MRI->getEncodingValue(++Reg);
4605       Registers.emplace_back(EReg, Reg);
4606     }
4607   }
4608 
4609   if (Parser.getTok().isNot(AsmToken::RCurly))
4610     return Error(Parser.getTok().getLoc(), "'}' expected");
4611   SMLoc E = Parser.getTok().getEndLoc();
4612   Parser.Lex(); // Eat '}' token.
4613 
4614   // Push the register list operand.
4615   Operands.push_back(ARMOperand::CreateRegList(Registers, S, E));
4616 
4617   // The ARM system instruction variants for LDM/STM have a '^' token here.
4618   if (Parser.getTok().is(AsmToken::Caret)) {
4619     Operands.push_back(ARMOperand::CreateToken("^",Parser.getTok().getLoc()));
4620     Parser.Lex(); // Eat '^' token.
4621   }
4622 
4623   return false;
4624 }
4625 
4626 // Helper function to parse the lane index for vector lists.
4627 OperandMatchResultTy ARMAsmParser::
4628 parseVectorLane(VectorLaneTy &LaneKind, unsigned &Index, SMLoc &EndLoc) {
4629   MCAsmParser &Parser = getParser();
4630   Index = 0; // Always return a defined index value.
4631   if (Parser.getTok().is(AsmToken::LBrac)) {
4632     Parser.Lex(); // Eat the '['.
4633     if (Parser.getTok().is(AsmToken::RBrac)) {
4634       // "Dn[]" is the 'all lanes' syntax.
4635       LaneKind = AllLanes;
4636       EndLoc = Parser.getTok().getEndLoc();
4637       Parser.Lex(); // Eat the ']'.
4638       return MatchOperand_Success;
4639     }
4640 
4641     // There's an optional '#' token here. Normally there wouldn't be, but
4642     // inline assemble puts one in, and it's friendly to accept that.
4643     if (Parser.getTok().is(AsmToken::Hash))
4644       Parser.Lex(); // Eat '#' or '$'.
4645 
4646     const MCExpr *LaneIndex;
4647     SMLoc Loc = Parser.getTok().getLoc();
4648     if (getParser().parseExpression(LaneIndex)) {
4649       Error(Loc, "illegal expression");
4650       return MatchOperand_ParseFail;
4651     }
4652     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(LaneIndex);
4653     if (!CE) {
4654       Error(Loc, "lane index must be empty or an integer");
4655       return MatchOperand_ParseFail;
4656     }
4657     if (Parser.getTok().isNot(AsmToken::RBrac)) {
4658       Error(Parser.getTok().getLoc(), "']' expected");
4659       return MatchOperand_ParseFail;
4660     }
4661     EndLoc = Parser.getTok().getEndLoc();
4662     Parser.Lex(); // Eat the ']'.
4663     int64_t Val = CE->getValue();
4664 
4665     // FIXME: Make this range check context sensitive for .8, .16, .32.
4666     if (Val < 0 || Val > 7) {
4667       Error(Parser.getTok().getLoc(), "lane index out of range");
4668       return MatchOperand_ParseFail;
4669     }
4670     Index = Val;
4671     LaneKind = IndexedLane;
4672     return MatchOperand_Success;
4673   }
4674   LaneKind = NoLanes;
4675   return MatchOperand_Success;
4676 }
4677 
4678 // parse a vector register list
4679 OperandMatchResultTy
4680 ARMAsmParser::parseVectorList(OperandVector &Operands) {
4681   MCAsmParser &Parser = getParser();
4682   VectorLaneTy LaneKind;
4683   unsigned LaneIndex;
4684   SMLoc S = Parser.getTok().getLoc();
4685   // As an extension (to match gas), support a plain D register or Q register
4686   // (without encosing curly braces) as a single or double entry list,
4687   // respectively.
4688   if (!hasMVE() && Parser.getTok().is(AsmToken::Identifier)) {
4689     SMLoc E = Parser.getTok().getEndLoc();
4690     int Reg = tryParseRegister();
4691     if (Reg == -1)
4692       return MatchOperand_NoMatch;
4693     if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Reg)) {
4694       OperandMatchResultTy Res = parseVectorLane(LaneKind, LaneIndex, E);
4695       if (Res != MatchOperand_Success)
4696         return Res;
4697       switch (LaneKind) {
4698       case NoLanes:
4699         Operands.push_back(ARMOperand::CreateVectorList(Reg, 1, false, S, E));
4700         break;
4701       case AllLanes:
4702         Operands.push_back(ARMOperand::CreateVectorListAllLanes(Reg, 1, false,
4703                                                                 S, E));
4704         break;
4705       case IndexedLane:
4706         Operands.push_back(ARMOperand::CreateVectorListIndexed(Reg, 1,
4707                                                                LaneIndex,
4708                                                                false, S, E));
4709         break;
4710       }
4711       return MatchOperand_Success;
4712     }
4713     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
4714       Reg = getDRegFromQReg(Reg);
4715       OperandMatchResultTy Res = parseVectorLane(LaneKind, LaneIndex, E);
4716       if (Res != MatchOperand_Success)
4717         return Res;
4718       switch (LaneKind) {
4719       case NoLanes:
4720         Reg = MRI->getMatchingSuperReg(Reg, ARM::dsub_0,
4721                                    &ARMMCRegisterClasses[ARM::DPairRegClassID]);
4722         Operands.push_back(ARMOperand::CreateVectorList(Reg, 2, false, S, E));
4723         break;
4724       case AllLanes:
4725         Reg = MRI->getMatchingSuperReg(Reg, ARM::dsub_0,
4726                                    &ARMMCRegisterClasses[ARM::DPairRegClassID]);
4727         Operands.push_back(ARMOperand::CreateVectorListAllLanes(Reg, 2, false,
4728                                                                 S, E));
4729         break;
4730       case IndexedLane:
4731         Operands.push_back(ARMOperand::CreateVectorListIndexed(Reg, 2,
4732                                                                LaneIndex,
4733                                                                false, S, E));
4734         break;
4735       }
4736       return MatchOperand_Success;
4737     }
4738     Error(S, "vector register expected");
4739     return MatchOperand_ParseFail;
4740   }
4741 
4742   if (Parser.getTok().isNot(AsmToken::LCurly))
4743     return MatchOperand_NoMatch;
4744 
4745   Parser.Lex(); // Eat '{' token.
4746   SMLoc RegLoc = Parser.getTok().getLoc();
4747 
4748   int Reg = tryParseRegister();
4749   if (Reg == -1) {
4750     Error(RegLoc, "register expected");
4751     return MatchOperand_ParseFail;
4752   }
4753   unsigned Count = 1;
4754   int Spacing = 0;
4755   unsigned FirstReg = Reg;
4756 
4757   if (hasMVE() && !ARMMCRegisterClasses[ARM::MQPRRegClassID].contains(Reg)) {
4758       Error(Parser.getTok().getLoc(), "vector register in range Q0-Q7 expected");
4759       return MatchOperand_ParseFail;
4760   }
4761   // The list is of D registers, but we also allow Q regs and just interpret
4762   // them as the two D sub-registers.
4763   else if (!hasMVE() && ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
4764     FirstReg = Reg = getDRegFromQReg(Reg);
4765     Spacing = 1; // double-spacing requires explicit D registers, otherwise
4766                  // it's ambiguous with four-register single spaced.
4767     ++Reg;
4768     ++Count;
4769   }
4770 
4771   SMLoc E;
4772   if (parseVectorLane(LaneKind, LaneIndex, E) != MatchOperand_Success)
4773     return MatchOperand_ParseFail;
4774 
4775   while (Parser.getTok().is(AsmToken::Comma) ||
4776          Parser.getTok().is(AsmToken::Minus)) {
4777     if (Parser.getTok().is(AsmToken::Minus)) {
4778       if (!Spacing)
4779         Spacing = 1; // Register range implies a single spaced list.
4780       else if (Spacing == 2) {
4781         Error(Parser.getTok().getLoc(),
4782               "sequential registers in double spaced list");
4783         return MatchOperand_ParseFail;
4784       }
4785       Parser.Lex(); // Eat the minus.
4786       SMLoc AfterMinusLoc = Parser.getTok().getLoc();
4787       int EndReg = tryParseRegister();
4788       if (EndReg == -1) {
4789         Error(AfterMinusLoc, "register expected");
4790         return MatchOperand_ParseFail;
4791       }
4792       // Allow Q regs and just interpret them as the two D sub-registers.
4793       if (!hasMVE() && ARMMCRegisterClasses[ARM::QPRRegClassID].contains(EndReg))
4794         EndReg = getDRegFromQReg(EndReg) + 1;
4795       // If the register is the same as the start reg, there's nothing
4796       // more to do.
4797       if (Reg == EndReg)
4798         continue;
4799       // The register must be in the same register class as the first.
4800       if ((hasMVE() &&
4801            !ARMMCRegisterClasses[ARM::MQPRRegClassID].contains(EndReg)) ||
4802           (!hasMVE() &&
4803            !ARMMCRegisterClasses[ARM::DPRRegClassID].contains(EndReg))) {
4804         Error(AfterMinusLoc, "invalid register in register list");
4805         return MatchOperand_ParseFail;
4806       }
4807       // Ranges must go from low to high.
4808       if (Reg > EndReg) {
4809         Error(AfterMinusLoc, "bad range in register list");
4810         return MatchOperand_ParseFail;
4811       }
4812       // Parse the lane specifier if present.
4813       VectorLaneTy NextLaneKind;
4814       unsigned NextLaneIndex;
4815       if (parseVectorLane(NextLaneKind, NextLaneIndex, E) !=
4816           MatchOperand_Success)
4817         return MatchOperand_ParseFail;
4818       if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
4819         Error(AfterMinusLoc, "mismatched lane index in register list");
4820         return MatchOperand_ParseFail;
4821       }
4822 
4823       // Add all the registers in the range to the register list.
4824       Count += EndReg - Reg;
4825       Reg = EndReg;
4826       continue;
4827     }
4828     Parser.Lex(); // Eat the comma.
4829     RegLoc = Parser.getTok().getLoc();
4830     int OldReg = Reg;
4831     Reg = tryParseRegister();
4832     if (Reg == -1) {
4833       Error(RegLoc, "register expected");
4834       return MatchOperand_ParseFail;
4835     }
4836 
4837     if (hasMVE()) {
4838       if (!ARMMCRegisterClasses[ARM::MQPRRegClassID].contains(Reg)) {
4839         Error(RegLoc, "vector register in range Q0-Q7 expected");
4840         return MatchOperand_ParseFail;
4841       }
4842       Spacing = 1;
4843     }
4844     // vector register lists must be contiguous.
4845     // It's OK to use the enumeration values directly here rather, as the
4846     // VFP register classes have the enum sorted properly.
4847     //
4848     // The list is of D registers, but we also allow Q regs and just interpret
4849     // them as the two D sub-registers.
4850     else if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
4851       if (!Spacing)
4852         Spacing = 1; // Register range implies a single spaced list.
4853       else if (Spacing == 2) {
4854         Error(RegLoc,
4855               "invalid register in double-spaced list (must be 'D' register')");
4856         return MatchOperand_ParseFail;
4857       }
4858       Reg = getDRegFromQReg(Reg);
4859       if (Reg != OldReg + 1) {
4860         Error(RegLoc, "non-contiguous register range");
4861         return MatchOperand_ParseFail;
4862       }
4863       ++Reg;
4864       Count += 2;
4865       // Parse the lane specifier if present.
4866       VectorLaneTy NextLaneKind;
4867       unsigned NextLaneIndex;
4868       SMLoc LaneLoc = Parser.getTok().getLoc();
4869       if (parseVectorLane(NextLaneKind, NextLaneIndex, E) !=
4870           MatchOperand_Success)
4871         return MatchOperand_ParseFail;
4872       if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
4873         Error(LaneLoc, "mismatched lane index in register list");
4874         return MatchOperand_ParseFail;
4875       }
4876       continue;
4877     }
4878     // Normal D register.
4879     // Figure out the register spacing (single or double) of the list if
4880     // we don't know it already.
4881     if (!Spacing)
4882       Spacing = 1 + (Reg == OldReg + 2);
4883 
4884     // Just check that it's contiguous and keep going.
4885     if (Reg != OldReg + Spacing) {
4886       Error(RegLoc, "non-contiguous register range");
4887       return MatchOperand_ParseFail;
4888     }
4889     ++Count;
4890     // Parse the lane specifier if present.
4891     VectorLaneTy NextLaneKind;
4892     unsigned NextLaneIndex;
4893     SMLoc EndLoc = Parser.getTok().getLoc();
4894     if (parseVectorLane(NextLaneKind, NextLaneIndex, E) != MatchOperand_Success)
4895       return MatchOperand_ParseFail;
4896     if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
4897       Error(EndLoc, "mismatched lane index in register list");
4898       return MatchOperand_ParseFail;
4899     }
4900   }
4901 
4902   if (Parser.getTok().isNot(AsmToken::RCurly)) {
4903     Error(Parser.getTok().getLoc(), "'}' expected");
4904     return MatchOperand_ParseFail;
4905   }
4906   E = Parser.getTok().getEndLoc();
4907   Parser.Lex(); // Eat '}' token.
4908 
4909   switch (LaneKind) {
4910   case NoLanes:
4911   case AllLanes: {
4912     // Two-register operands have been converted to the
4913     // composite register classes.
4914     if (Count == 2 && !hasMVE()) {
4915       const MCRegisterClass *RC = (Spacing == 1) ?
4916         &ARMMCRegisterClasses[ARM::DPairRegClassID] :
4917         &ARMMCRegisterClasses[ARM::DPairSpcRegClassID];
4918       FirstReg = MRI->getMatchingSuperReg(FirstReg, ARM::dsub_0, RC);
4919     }
4920     auto Create = (LaneKind == NoLanes ? ARMOperand::CreateVectorList :
4921                    ARMOperand::CreateVectorListAllLanes);
4922     Operands.push_back(Create(FirstReg, Count, (Spacing == 2), S, E));
4923     break;
4924   }
4925   case IndexedLane:
4926     Operands.push_back(ARMOperand::CreateVectorListIndexed(FirstReg, Count,
4927                                                            LaneIndex,
4928                                                            (Spacing == 2),
4929                                                            S, E));
4930     break;
4931   }
4932   return MatchOperand_Success;
4933 }
4934 
4935 /// parseMemBarrierOptOperand - Try to parse DSB/DMB data barrier options.
4936 OperandMatchResultTy
4937 ARMAsmParser::parseMemBarrierOptOperand(OperandVector &Operands) {
4938   MCAsmParser &Parser = getParser();
4939   SMLoc S = Parser.getTok().getLoc();
4940   const AsmToken &Tok = Parser.getTok();
4941   unsigned Opt;
4942 
4943   if (Tok.is(AsmToken::Identifier)) {
4944     StringRef OptStr = Tok.getString();
4945 
4946     Opt = StringSwitch<unsigned>(OptStr.slice(0, OptStr.size()).lower())
4947       .Case("sy",    ARM_MB::SY)
4948       .Case("st",    ARM_MB::ST)
4949       .Case("ld",    ARM_MB::LD)
4950       .Case("sh",    ARM_MB::ISH)
4951       .Case("ish",   ARM_MB::ISH)
4952       .Case("shst",  ARM_MB::ISHST)
4953       .Case("ishst", ARM_MB::ISHST)
4954       .Case("ishld", ARM_MB::ISHLD)
4955       .Case("nsh",   ARM_MB::NSH)
4956       .Case("un",    ARM_MB::NSH)
4957       .Case("nshst", ARM_MB::NSHST)
4958       .Case("nshld", ARM_MB::NSHLD)
4959       .Case("unst",  ARM_MB::NSHST)
4960       .Case("osh",   ARM_MB::OSH)
4961       .Case("oshst", ARM_MB::OSHST)
4962       .Case("oshld", ARM_MB::OSHLD)
4963       .Default(~0U);
4964 
4965     // ishld, oshld, nshld and ld are only available from ARMv8.
4966     if (!hasV8Ops() && (Opt == ARM_MB::ISHLD || Opt == ARM_MB::OSHLD ||
4967                         Opt == ARM_MB::NSHLD || Opt == ARM_MB::LD))
4968       Opt = ~0U;
4969 
4970     if (Opt == ~0U)
4971       return MatchOperand_NoMatch;
4972 
4973     Parser.Lex(); // Eat identifier token.
4974   } else if (Tok.is(AsmToken::Hash) ||
4975              Tok.is(AsmToken::Dollar) ||
4976              Tok.is(AsmToken::Integer)) {
4977     if (Parser.getTok().isNot(AsmToken::Integer))
4978       Parser.Lex(); // Eat '#' or '$'.
4979     SMLoc Loc = Parser.getTok().getLoc();
4980 
4981     const MCExpr *MemBarrierID;
4982     if (getParser().parseExpression(MemBarrierID)) {
4983       Error(Loc, "illegal expression");
4984       return MatchOperand_ParseFail;
4985     }
4986 
4987     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(MemBarrierID);
4988     if (!CE) {
4989       Error(Loc, "constant expression expected");
4990       return MatchOperand_ParseFail;
4991     }
4992 
4993     int Val = CE->getValue();
4994     if (Val & ~0xf) {
4995       Error(Loc, "immediate value out of range");
4996       return MatchOperand_ParseFail;
4997     }
4998 
4999     Opt = ARM_MB::RESERVED_0 + Val;
5000   } else
5001     return MatchOperand_ParseFail;
5002 
5003   Operands.push_back(ARMOperand::CreateMemBarrierOpt((ARM_MB::MemBOpt)Opt, S));
5004   return MatchOperand_Success;
5005 }
5006 
5007 OperandMatchResultTy
5008 ARMAsmParser::parseTraceSyncBarrierOptOperand(OperandVector &Operands) {
5009   MCAsmParser &Parser = getParser();
5010   SMLoc S = Parser.getTok().getLoc();
5011   const AsmToken &Tok = Parser.getTok();
5012 
5013   if (Tok.isNot(AsmToken::Identifier))
5014      return MatchOperand_NoMatch;
5015 
5016   if (!Tok.getString().equals_lower("csync"))
5017     return MatchOperand_NoMatch;
5018 
5019   Parser.Lex(); // Eat identifier token.
5020 
5021   Operands.push_back(ARMOperand::CreateTraceSyncBarrierOpt(ARM_TSB::CSYNC, S));
5022   return MatchOperand_Success;
5023 }
5024 
5025 /// parseInstSyncBarrierOptOperand - Try to parse ISB inst sync barrier options.
5026 OperandMatchResultTy
5027 ARMAsmParser::parseInstSyncBarrierOptOperand(OperandVector &Operands) {
5028   MCAsmParser &Parser = getParser();
5029   SMLoc S = Parser.getTok().getLoc();
5030   const AsmToken &Tok = Parser.getTok();
5031   unsigned Opt;
5032 
5033   if (Tok.is(AsmToken::Identifier)) {
5034     StringRef OptStr = Tok.getString();
5035 
5036     if (OptStr.equals_lower("sy"))
5037       Opt = ARM_ISB::SY;
5038     else
5039       return MatchOperand_NoMatch;
5040 
5041     Parser.Lex(); // Eat identifier token.
5042   } else if (Tok.is(AsmToken::Hash) ||
5043              Tok.is(AsmToken::Dollar) ||
5044              Tok.is(AsmToken::Integer)) {
5045     if (Parser.getTok().isNot(AsmToken::Integer))
5046       Parser.Lex(); // Eat '#' or '$'.
5047     SMLoc Loc = Parser.getTok().getLoc();
5048 
5049     const MCExpr *ISBarrierID;
5050     if (getParser().parseExpression(ISBarrierID)) {
5051       Error(Loc, "illegal expression");
5052       return MatchOperand_ParseFail;
5053     }
5054 
5055     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ISBarrierID);
5056     if (!CE) {
5057       Error(Loc, "constant expression expected");
5058       return MatchOperand_ParseFail;
5059     }
5060 
5061     int Val = CE->getValue();
5062     if (Val & ~0xf) {
5063       Error(Loc, "immediate value out of range");
5064       return MatchOperand_ParseFail;
5065     }
5066 
5067     Opt = ARM_ISB::RESERVED_0 + Val;
5068   } else
5069     return MatchOperand_ParseFail;
5070 
5071   Operands.push_back(ARMOperand::CreateInstSyncBarrierOpt(
5072           (ARM_ISB::InstSyncBOpt)Opt, S));
5073   return MatchOperand_Success;
5074 }
5075 
5076 
5077 /// parseProcIFlagsOperand - Try to parse iflags from CPS instruction.
5078 OperandMatchResultTy
5079 ARMAsmParser::parseProcIFlagsOperand(OperandVector &Operands) {
5080   MCAsmParser &Parser = getParser();
5081   SMLoc S = Parser.getTok().getLoc();
5082   const AsmToken &Tok = Parser.getTok();
5083   if (!Tok.is(AsmToken::Identifier))
5084     return MatchOperand_NoMatch;
5085   StringRef IFlagsStr = Tok.getString();
5086 
5087   // An iflags string of "none" is interpreted to mean that none of the AIF
5088   // bits are set.  Not a terribly useful instruction, but a valid encoding.
5089   unsigned IFlags = 0;
5090   if (IFlagsStr != "none") {
5091         for (int i = 0, e = IFlagsStr.size(); i != e; ++i) {
5092       unsigned Flag = StringSwitch<unsigned>(IFlagsStr.substr(i, 1).lower())
5093         .Case("a", ARM_PROC::A)
5094         .Case("i", ARM_PROC::I)
5095         .Case("f", ARM_PROC::F)
5096         .Default(~0U);
5097 
5098       // If some specific iflag is already set, it means that some letter is
5099       // present more than once, this is not acceptable.
5100       if (Flag == ~0U || (IFlags & Flag))
5101         return MatchOperand_NoMatch;
5102 
5103       IFlags |= Flag;
5104     }
5105   }
5106 
5107   Parser.Lex(); // Eat identifier token.
5108   Operands.push_back(ARMOperand::CreateProcIFlags((ARM_PROC::IFlags)IFlags, S));
5109   return MatchOperand_Success;
5110 }
5111 
5112 /// parseMSRMaskOperand - Try to parse mask flags from MSR instruction.
5113 OperandMatchResultTy
5114 ARMAsmParser::parseMSRMaskOperand(OperandVector &Operands) {
5115   MCAsmParser &Parser = getParser();
5116   SMLoc S = Parser.getTok().getLoc();
5117   const AsmToken &Tok = Parser.getTok();
5118 
5119   if (Tok.is(AsmToken::Integer)) {
5120     int64_t Val = Tok.getIntVal();
5121     if (Val > 255 || Val < 0) {
5122       return MatchOperand_NoMatch;
5123     }
5124     unsigned SYSmvalue = Val & 0xFF;
5125     Parser.Lex();
5126     Operands.push_back(ARMOperand::CreateMSRMask(SYSmvalue, S));
5127     return MatchOperand_Success;
5128   }
5129 
5130   if (!Tok.is(AsmToken::Identifier))
5131     return MatchOperand_NoMatch;
5132   StringRef Mask = Tok.getString();
5133 
5134   if (isMClass()) {
5135     auto TheReg = ARMSysReg::lookupMClassSysRegByName(Mask.lower());
5136     if (!TheReg || !TheReg->hasRequiredFeatures(getSTI().getFeatureBits()))
5137       return MatchOperand_NoMatch;
5138 
5139     unsigned SYSmvalue = TheReg->Encoding & 0xFFF;
5140 
5141     Parser.Lex(); // Eat identifier token.
5142     Operands.push_back(ARMOperand::CreateMSRMask(SYSmvalue, S));
5143     return MatchOperand_Success;
5144   }
5145 
5146   // Split spec_reg from flag, example: CPSR_sxf => "CPSR" and "sxf"
5147   size_t Start = 0, Next = Mask.find('_');
5148   StringRef Flags = "";
5149   std::string SpecReg = Mask.slice(Start, Next).lower();
5150   if (Next != StringRef::npos)
5151     Flags = Mask.slice(Next+1, Mask.size());
5152 
5153   // FlagsVal contains the complete mask:
5154   // 3-0: Mask
5155   // 4: Special Reg (cpsr, apsr => 0; spsr => 1)
5156   unsigned FlagsVal = 0;
5157 
5158   if (SpecReg == "apsr") {
5159     FlagsVal = StringSwitch<unsigned>(Flags)
5160     .Case("nzcvq",  0x8) // same as CPSR_f
5161     .Case("g",      0x4) // same as CPSR_s
5162     .Case("nzcvqg", 0xc) // same as CPSR_fs
5163     .Default(~0U);
5164 
5165     if (FlagsVal == ~0U) {
5166       if (!Flags.empty())
5167         return MatchOperand_NoMatch;
5168       else
5169         FlagsVal = 8; // No flag
5170     }
5171   } else if (SpecReg == "cpsr" || SpecReg == "spsr") {
5172     // cpsr_all is an alias for cpsr_fc, as is plain cpsr.
5173     if (Flags == "all" || Flags == "")
5174       Flags = "fc";
5175     for (int i = 0, e = Flags.size(); i != e; ++i) {
5176       unsigned Flag = StringSwitch<unsigned>(Flags.substr(i, 1))
5177       .Case("c", 1)
5178       .Case("x", 2)
5179       .Case("s", 4)
5180       .Case("f", 8)
5181       .Default(~0U);
5182 
5183       // If some specific flag is already set, it means that some letter is
5184       // present more than once, this is not acceptable.
5185       if (Flag == ~0U || (FlagsVal & Flag))
5186         return MatchOperand_NoMatch;
5187       FlagsVal |= Flag;
5188     }
5189   } else // No match for special register.
5190     return MatchOperand_NoMatch;
5191 
5192   // Special register without flags is NOT equivalent to "fc" flags.
5193   // NOTE: This is a divergence from gas' behavior.  Uncommenting the following
5194   // two lines would enable gas compatibility at the expense of breaking
5195   // round-tripping.
5196   //
5197   // if (!FlagsVal)
5198   //  FlagsVal = 0x9;
5199 
5200   // Bit 4: Special Reg (cpsr, apsr => 0; spsr => 1)
5201   if (SpecReg == "spsr")
5202     FlagsVal |= 16;
5203 
5204   Parser.Lex(); // Eat identifier token.
5205   Operands.push_back(ARMOperand::CreateMSRMask(FlagsVal, S));
5206   return MatchOperand_Success;
5207 }
5208 
5209 /// parseBankedRegOperand - Try to parse a banked register (e.g. "lr_irq") for
5210 /// use in the MRS/MSR instructions added to support virtualization.
5211 OperandMatchResultTy
5212 ARMAsmParser::parseBankedRegOperand(OperandVector &Operands) {
5213   MCAsmParser &Parser = getParser();
5214   SMLoc S = Parser.getTok().getLoc();
5215   const AsmToken &Tok = Parser.getTok();
5216   if (!Tok.is(AsmToken::Identifier))
5217     return MatchOperand_NoMatch;
5218   StringRef RegName = Tok.getString();
5219 
5220   auto TheReg = ARMBankedReg::lookupBankedRegByName(RegName.lower());
5221   if (!TheReg)
5222     return MatchOperand_NoMatch;
5223   unsigned Encoding = TheReg->Encoding;
5224 
5225   Parser.Lex(); // Eat identifier token.
5226   Operands.push_back(ARMOperand::CreateBankedReg(Encoding, S));
5227   return MatchOperand_Success;
5228 }
5229 
5230 OperandMatchResultTy
5231 ARMAsmParser::parsePKHImm(OperandVector &Operands, StringRef Op, int Low,
5232                           int High) {
5233   MCAsmParser &Parser = getParser();
5234   const AsmToken &Tok = Parser.getTok();
5235   if (Tok.isNot(AsmToken::Identifier)) {
5236     Error(Parser.getTok().getLoc(), Op + " operand expected.");
5237     return MatchOperand_ParseFail;
5238   }
5239   StringRef ShiftName = Tok.getString();
5240   std::string LowerOp = Op.lower();
5241   std::string UpperOp = Op.upper();
5242   if (ShiftName != LowerOp && ShiftName != UpperOp) {
5243     Error(Parser.getTok().getLoc(), Op + " operand expected.");
5244     return MatchOperand_ParseFail;
5245   }
5246   Parser.Lex(); // Eat shift type token.
5247 
5248   // There must be a '#' and a shift amount.
5249   if (Parser.getTok().isNot(AsmToken::Hash) &&
5250       Parser.getTok().isNot(AsmToken::Dollar)) {
5251     Error(Parser.getTok().getLoc(), "'#' expected");
5252     return MatchOperand_ParseFail;
5253   }
5254   Parser.Lex(); // Eat hash token.
5255 
5256   const MCExpr *ShiftAmount;
5257   SMLoc Loc = Parser.getTok().getLoc();
5258   SMLoc EndLoc;
5259   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
5260     Error(Loc, "illegal expression");
5261     return MatchOperand_ParseFail;
5262   }
5263   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
5264   if (!CE) {
5265     Error(Loc, "constant expression expected");
5266     return MatchOperand_ParseFail;
5267   }
5268   int Val = CE->getValue();
5269   if (Val < Low || Val > High) {
5270     Error(Loc, "immediate value out of range");
5271     return MatchOperand_ParseFail;
5272   }
5273 
5274   Operands.push_back(ARMOperand::CreateImm(CE, Loc, EndLoc));
5275 
5276   return MatchOperand_Success;
5277 }
5278 
5279 OperandMatchResultTy
5280 ARMAsmParser::parseSetEndImm(OperandVector &Operands) {
5281   MCAsmParser &Parser = getParser();
5282   const AsmToken &Tok = Parser.getTok();
5283   SMLoc S = Tok.getLoc();
5284   if (Tok.isNot(AsmToken::Identifier)) {
5285     Error(S, "'be' or 'le' operand expected");
5286     return MatchOperand_ParseFail;
5287   }
5288   int Val = StringSwitch<int>(Tok.getString().lower())
5289     .Case("be", 1)
5290     .Case("le", 0)
5291     .Default(-1);
5292   Parser.Lex(); // Eat the token.
5293 
5294   if (Val == -1) {
5295     Error(S, "'be' or 'le' operand expected");
5296     return MatchOperand_ParseFail;
5297   }
5298   Operands.push_back(ARMOperand::CreateImm(MCConstantExpr::create(Val,
5299                                                                   getContext()),
5300                                            S, Tok.getEndLoc()));
5301   return MatchOperand_Success;
5302 }
5303 
5304 /// parseShifterImm - Parse the shifter immediate operand for SSAT/USAT
5305 /// instructions. Legal values are:
5306 ///     lsl #n  'n' in [0,31]
5307 ///     asr #n  'n' in [1,32]
5308 ///             n == 32 encoded as n == 0.
5309 OperandMatchResultTy
5310 ARMAsmParser::parseShifterImm(OperandVector &Operands) {
5311   MCAsmParser &Parser = getParser();
5312   const AsmToken &Tok = Parser.getTok();
5313   SMLoc S = Tok.getLoc();
5314   if (Tok.isNot(AsmToken::Identifier)) {
5315     Error(S, "shift operator 'asr' or 'lsl' expected");
5316     return MatchOperand_ParseFail;
5317   }
5318   StringRef ShiftName = Tok.getString();
5319   bool isASR;
5320   if (ShiftName == "lsl" || ShiftName == "LSL")
5321     isASR = false;
5322   else if (ShiftName == "asr" || ShiftName == "ASR")
5323     isASR = true;
5324   else {
5325     Error(S, "shift operator 'asr' or 'lsl' expected");
5326     return MatchOperand_ParseFail;
5327   }
5328   Parser.Lex(); // Eat the operator.
5329 
5330   // A '#' and a shift amount.
5331   if (Parser.getTok().isNot(AsmToken::Hash) &&
5332       Parser.getTok().isNot(AsmToken::Dollar)) {
5333     Error(Parser.getTok().getLoc(), "'#' expected");
5334     return MatchOperand_ParseFail;
5335   }
5336   Parser.Lex(); // Eat hash token.
5337   SMLoc ExLoc = Parser.getTok().getLoc();
5338 
5339   const MCExpr *ShiftAmount;
5340   SMLoc EndLoc;
5341   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
5342     Error(ExLoc, "malformed shift expression");
5343     return MatchOperand_ParseFail;
5344   }
5345   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
5346   if (!CE) {
5347     Error(ExLoc, "shift amount must be an immediate");
5348     return MatchOperand_ParseFail;
5349   }
5350 
5351   int64_t Val = CE->getValue();
5352   if (isASR) {
5353     // Shift amount must be in [1,32]
5354     if (Val < 1 || Val > 32) {
5355       Error(ExLoc, "'asr' shift amount must be in range [1,32]");
5356       return MatchOperand_ParseFail;
5357     }
5358     // asr #32 encoded as asr #0, but is not allowed in Thumb2 mode.
5359     if (isThumb() && Val == 32) {
5360       Error(ExLoc, "'asr #32' shift amount not allowed in Thumb mode");
5361       return MatchOperand_ParseFail;
5362     }
5363     if (Val == 32) Val = 0;
5364   } else {
5365     // Shift amount must be in [1,32]
5366     if (Val < 0 || Val > 31) {
5367       Error(ExLoc, "'lsr' shift amount must be in range [0,31]");
5368       return MatchOperand_ParseFail;
5369     }
5370   }
5371 
5372   Operands.push_back(ARMOperand::CreateShifterImm(isASR, Val, S, EndLoc));
5373 
5374   return MatchOperand_Success;
5375 }
5376 
5377 /// parseRotImm - Parse the shifter immediate operand for SXTB/UXTB family
5378 /// of instructions. Legal values are:
5379 ///     ror #n  'n' in {0, 8, 16, 24}
5380 OperandMatchResultTy
5381 ARMAsmParser::parseRotImm(OperandVector &Operands) {
5382   MCAsmParser &Parser = getParser();
5383   const AsmToken &Tok = Parser.getTok();
5384   SMLoc S = Tok.getLoc();
5385   if (Tok.isNot(AsmToken::Identifier))
5386     return MatchOperand_NoMatch;
5387   StringRef ShiftName = Tok.getString();
5388   if (ShiftName != "ror" && ShiftName != "ROR")
5389     return MatchOperand_NoMatch;
5390   Parser.Lex(); // Eat the operator.
5391 
5392   // A '#' and a rotate amount.
5393   if (Parser.getTok().isNot(AsmToken::Hash) &&
5394       Parser.getTok().isNot(AsmToken::Dollar)) {
5395     Error(Parser.getTok().getLoc(), "'#' expected");
5396     return MatchOperand_ParseFail;
5397   }
5398   Parser.Lex(); // Eat hash token.
5399   SMLoc ExLoc = Parser.getTok().getLoc();
5400 
5401   const MCExpr *ShiftAmount;
5402   SMLoc EndLoc;
5403   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
5404     Error(ExLoc, "malformed rotate expression");
5405     return MatchOperand_ParseFail;
5406   }
5407   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
5408   if (!CE) {
5409     Error(ExLoc, "rotate amount must be an immediate");
5410     return MatchOperand_ParseFail;
5411   }
5412 
5413   int64_t Val = CE->getValue();
5414   // Shift amount must be in {0, 8, 16, 24} (0 is undocumented extension)
5415   // normally, zero is represented in asm by omitting the rotate operand
5416   // entirely.
5417   if (Val != 8 && Val != 16 && Val != 24 && Val != 0) {
5418     Error(ExLoc, "'ror' rotate amount must be 8, 16, or 24");
5419     return MatchOperand_ParseFail;
5420   }
5421 
5422   Operands.push_back(ARMOperand::CreateRotImm(Val, S, EndLoc));
5423 
5424   return MatchOperand_Success;
5425 }
5426 
5427 OperandMatchResultTy
5428 ARMAsmParser::parseModImm(OperandVector &Operands) {
5429   MCAsmParser &Parser = getParser();
5430   MCAsmLexer &Lexer = getLexer();
5431   int64_t Imm1, Imm2;
5432 
5433   SMLoc S = Parser.getTok().getLoc();
5434 
5435   // 1) A mod_imm operand can appear in the place of a register name:
5436   //   add r0, #mod_imm
5437   //   add r0, r0, #mod_imm
5438   // to correctly handle the latter, we bail out as soon as we see an
5439   // identifier.
5440   //
5441   // 2) Similarly, we do not want to parse into complex operands:
5442   //   mov r0, #mod_imm
5443   //   mov r0, :lower16:(_foo)
5444   if (Parser.getTok().is(AsmToken::Identifier) ||
5445       Parser.getTok().is(AsmToken::Colon))
5446     return MatchOperand_NoMatch;
5447 
5448   // Hash (dollar) is optional as per the ARMARM
5449   if (Parser.getTok().is(AsmToken::Hash) ||
5450       Parser.getTok().is(AsmToken::Dollar)) {
5451     // Avoid parsing into complex operands (#:)
5452     if (Lexer.peekTok().is(AsmToken::Colon))
5453       return MatchOperand_NoMatch;
5454 
5455     // Eat the hash (dollar)
5456     Parser.Lex();
5457   }
5458 
5459   SMLoc Sx1, Ex1;
5460   Sx1 = Parser.getTok().getLoc();
5461   const MCExpr *Imm1Exp;
5462   if (getParser().parseExpression(Imm1Exp, Ex1)) {
5463     Error(Sx1, "malformed expression");
5464     return MatchOperand_ParseFail;
5465   }
5466 
5467   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm1Exp);
5468 
5469   if (CE) {
5470     // Immediate must fit within 32-bits
5471     Imm1 = CE->getValue();
5472     int Enc = ARM_AM::getSOImmVal(Imm1);
5473     if (Enc != -1 && Parser.getTok().is(AsmToken::EndOfStatement)) {
5474       // We have a match!
5475       Operands.push_back(ARMOperand::CreateModImm((Enc & 0xFF),
5476                                                   (Enc & 0xF00) >> 7,
5477                                                   Sx1, Ex1));
5478       return MatchOperand_Success;
5479     }
5480 
5481     // We have parsed an immediate which is not for us, fallback to a plain
5482     // immediate. This can happen for instruction aliases. For an example,
5483     // ARMInstrInfo.td defines the alias [mov <-> mvn] which can transform
5484     // a mov (mvn) with a mod_imm_neg/mod_imm_not operand into the opposite
5485     // instruction with a mod_imm operand. The alias is defined such that the
5486     // parser method is shared, that's why we have to do this here.
5487     if (Parser.getTok().is(AsmToken::EndOfStatement)) {
5488       Operands.push_back(ARMOperand::CreateImm(Imm1Exp, Sx1, Ex1));
5489       return MatchOperand_Success;
5490     }
5491   } else {
5492     // Operands like #(l1 - l2) can only be evaluated at a later stage (via an
5493     // MCFixup). Fallback to a plain immediate.
5494     Operands.push_back(ARMOperand::CreateImm(Imm1Exp, Sx1, Ex1));
5495     return MatchOperand_Success;
5496   }
5497 
5498   // From this point onward, we expect the input to be a (#bits, #rot) pair
5499   if (Parser.getTok().isNot(AsmToken::Comma)) {
5500     Error(Sx1, "expected modified immediate operand: #[0, 255], #even[0-30]");
5501     return MatchOperand_ParseFail;
5502   }
5503 
5504   if (Imm1 & ~0xFF) {
5505     Error(Sx1, "immediate operand must a number in the range [0, 255]");
5506     return MatchOperand_ParseFail;
5507   }
5508 
5509   // Eat the comma
5510   Parser.Lex();
5511 
5512   // Repeat for #rot
5513   SMLoc Sx2, Ex2;
5514   Sx2 = Parser.getTok().getLoc();
5515 
5516   // Eat the optional hash (dollar)
5517   if (Parser.getTok().is(AsmToken::Hash) ||
5518       Parser.getTok().is(AsmToken::Dollar))
5519     Parser.Lex();
5520 
5521   const MCExpr *Imm2Exp;
5522   if (getParser().parseExpression(Imm2Exp, Ex2)) {
5523     Error(Sx2, "malformed expression");
5524     return MatchOperand_ParseFail;
5525   }
5526 
5527   CE = dyn_cast<MCConstantExpr>(Imm2Exp);
5528 
5529   if (CE) {
5530     Imm2 = CE->getValue();
5531     if (!(Imm2 & ~0x1E)) {
5532       // We have a match!
5533       Operands.push_back(ARMOperand::CreateModImm(Imm1, Imm2, S, Ex2));
5534       return MatchOperand_Success;
5535     }
5536     Error(Sx2, "immediate operand must an even number in the range [0, 30]");
5537     return MatchOperand_ParseFail;
5538   } else {
5539     Error(Sx2, "constant expression expected");
5540     return MatchOperand_ParseFail;
5541   }
5542 }
5543 
5544 OperandMatchResultTy
5545 ARMAsmParser::parseBitfield(OperandVector &Operands) {
5546   MCAsmParser &Parser = getParser();
5547   SMLoc S = Parser.getTok().getLoc();
5548   // The bitfield descriptor is really two operands, the LSB and the width.
5549   if (Parser.getTok().isNot(AsmToken::Hash) &&
5550       Parser.getTok().isNot(AsmToken::Dollar)) {
5551     Error(Parser.getTok().getLoc(), "'#' expected");
5552     return MatchOperand_ParseFail;
5553   }
5554   Parser.Lex(); // Eat hash token.
5555 
5556   const MCExpr *LSBExpr;
5557   SMLoc E = Parser.getTok().getLoc();
5558   if (getParser().parseExpression(LSBExpr)) {
5559     Error(E, "malformed immediate expression");
5560     return MatchOperand_ParseFail;
5561   }
5562   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(LSBExpr);
5563   if (!CE) {
5564     Error(E, "'lsb' operand must be an immediate");
5565     return MatchOperand_ParseFail;
5566   }
5567 
5568   int64_t LSB = CE->getValue();
5569   // The LSB must be in the range [0,31]
5570   if (LSB < 0 || LSB > 31) {
5571     Error(E, "'lsb' operand must be in the range [0,31]");
5572     return MatchOperand_ParseFail;
5573   }
5574   E = Parser.getTok().getLoc();
5575 
5576   // Expect another immediate operand.
5577   if (Parser.getTok().isNot(AsmToken::Comma)) {
5578     Error(Parser.getTok().getLoc(), "too few operands");
5579     return MatchOperand_ParseFail;
5580   }
5581   Parser.Lex(); // Eat hash token.
5582   if (Parser.getTok().isNot(AsmToken::Hash) &&
5583       Parser.getTok().isNot(AsmToken::Dollar)) {
5584     Error(Parser.getTok().getLoc(), "'#' expected");
5585     return MatchOperand_ParseFail;
5586   }
5587   Parser.Lex(); // Eat hash token.
5588 
5589   const MCExpr *WidthExpr;
5590   SMLoc EndLoc;
5591   if (getParser().parseExpression(WidthExpr, EndLoc)) {
5592     Error(E, "malformed immediate expression");
5593     return MatchOperand_ParseFail;
5594   }
5595   CE = dyn_cast<MCConstantExpr>(WidthExpr);
5596   if (!CE) {
5597     Error(E, "'width' operand must be an immediate");
5598     return MatchOperand_ParseFail;
5599   }
5600 
5601   int64_t Width = CE->getValue();
5602   // The LSB must be in the range [1,32-lsb]
5603   if (Width < 1 || Width > 32 - LSB) {
5604     Error(E, "'width' operand must be in the range [1,32-lsb]");
5605     return MatchOperand_ParseFail;
5606   }
5607 
5608   Operands.push_back(ARMOperand::CreateBitfield(LSB, Width, S, EndLoc));
5609 
5610   return MatchOperand_Success;
5611 }
5612 
5613 OperandMatchResultTy
5614 ARMAsmParser::parsePostIdxReg(OperandVector &Operands) {
5615   // Check for a post-index addressing register operand. Specifically:
5616   // postidx_reg := '+' register {, shift}
5617   //              | '-' register {, shift}
5618   //              | register {, shift}
5619 
5620   // This method must return MatchOperand_NoMatch without consuming any tokens
5621   // in the case where there is no match, as other alternatives take other
5622   // parse methods.
5623   MCAsmParser &Parser = getParser();
5624   AsmToken Tok = Parser.getTok();
5625   SMLoc S = Tok.getLoc();
5626   bool haveEaten = false;
5627   bool isAdd = true;
5628   if (Tok.is(AsmToken::Plus)) {
5629     Parser.Lex(); // Eat the '+' token.
5630     haveEaten = true;
5631   } else if (Tok.is(AsmToken::Minus)) {
5632     Parser.Lex(); // Eat the '-' token.
5633     isAdd = false;
5634     haveEaten = true;
5635   }
5636 
5637   SMLoc E = Parser.getTok().getEndLoc();
5638   int Reg = tryParseRegister();
5639   if (Reg == -1) {
5640     if (!haveEaten)
5641       return MatchOperand_NoMatch;
5642     Error(Parser.getTok().getLoc(), "register expected");
5643     return MatchOperand_ParseFail;
5644   }
5645 
5646   ARM_AM::ShiftOpc ShiftTy = ARM_AM::no_shift;
5647   unsigned ShiftImm = 0;
5648   if (Parser.getTok().is(AsmToken::Comma)) {
5649     Parser.Lex(); // Eat the ','.
5650     if (parseMemRegOffsetShift(ShiftTy, ShiftImm))
5651       return MatchOperand_ParseFail;
5652 
5653     // FIXME: Only approximates end...may include intervening whitespace.
5654     E = Parser.getTok().getLoc();
5655   }
5656 
5657   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ShiftTy,
5658                                                   ShiftImm, S, E));
5659 
5660   return MatchOperand_Success;
5661 }
5662 
5663 OperandMatchResultTy
5664 ARMAsmParser::parseAM3Offset(OperandVector &Operands) {
5665   // Check for a post-index addressing register operand. Specifically:
5666   // am3offset := '+' register
5667   //              | '-' register
5668   //              | register
5669   //              | # imm
5670   //              | # + imm
5671   //              | # - imm
5672 
5673   // This method must return MatchOperand_NoMatch without consuming any tokens
5674   // in the case where there is no match, as other alternatives take other
5675   // parse methods.
5676   MCAsmParser &Parser = getParser();
5677   AsmToken Tok = Parser.getTok();
5678   SMLoc S = Tok.getLoc();
5679 
5680   // Do immediates first, as we always parse those if we have a '#'.
5681   if (Parser.getTok().is(AsmToken::Hash) ||
5682       Parser.getTok().is(AsmToken::Dollar)) {
5683     Parser.Lex(); // Eat '#' or '$'.
5684     // Explicitly look for a '-', as we need to encode negative zero
5685     // differently.
5686     bool isNegative = Parser.getTok().is(AsmToken::Minus);
5687     const MCExpr *Offset;
5688     SMLoc E;
5689     if (getParser().parseExpression(Offset, E))
5690       return MatchOperand_ParseFail;
5691     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
5692     if (!CE) {
5693       Error(S, "constant expression expected");
5694       return MatchOperand_ParseFail;
5695     }
5696     // Negative zero is encoded as the flag value
5697     // std::numeric_limits<int32_t>::min().
5698     int32_t Val = CE->getValue();
5699     if (isNegative && Val == 0)
5700       Val = std::numeric_limits<int32_t>::min();
5701 
5702     Operands.push_back(
5703       ARMOperand::CreateImm(MCConstantExpr::create(Val, getContext()), S, E));
5704 
5705     return MatchOperand_Success;
5706   }
5707 
5708   bool haveEaten = false;
5709   bool isAdd = true;
5710   if (Tok.is(AsmToken::Plus)) {
5711     Parser.Lex(); // Eat the '+' token.
5712     haveEaten = true;
5713   } else if (Tok.is(AsmToken::Minus)) {
5714     Parser.Lex(); // Eat the '-' token.
5715     isAdd = false;
5716     haveEaten = true;
5717   }
5718 
5719   Tok = Parser.getTok();
5720   int Reg = tryParseRegister();
5721   if (Reg == -1) {
5722     if (!haveEaten)
5723       return MatchOperand_NoMatch;
5724     Error(Tok.getLoc(), "register expected");
5725     return MatchOperand_ParseFail;
5726   }
5727 
5728   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ARM_AM::no_shift,
5729                                                   0, S, Tok.getEndLoc()));
5730 
5731   return MatchOperand_Success;
5732 }
5733 
5734 /// Convert parsed operands to MCInst.  Needed here because this instruction
5735 /// only has two register operands, but multiplication is commutative so
5736 /// assemblers should accept both "mul rD, rN, rD" and "mul rD, rD, rN".
5737 void ARMAsmParser::cvtThumbMultiply(MCInst &Inst,
5738                                     const OperandVector &Operands) {
5739   ((ARMOperand &)*Operands[3]).addRegOperands(Inst, 1);
5740   ((ARMOperand &)*Operands[1]).addCCOutOperands(Inst, 1);
5741   // If we have a three-operand form, make sure to set Rn to be the operand
5742   // that isn't the same as Rd.
5743   unsigned RegOp = 4;
5744   if (Operands.size() == 6 &&
5745       ((ARMOperand &)*Operands[4]).getReg() ==
5746           ((ARMOperand &)*Operands[3]).getReg())
5747     RegOp = 5;
5748   ((ARMOperand &)*Operands[RegOp]).addRegOperands(Inst, 1);
5749   Inst.addOperand(Inst.getOperand(0));
5750   ((ARMOperand &)*Operands[2]).addCondCodeOperands(Inst, 2);
5751 }
5752 
5753 void ARMAsmParser::cvtThumbBranches(MCInst &Inst,
5754                                     const OperandVector &Operands) {
5755   int CondOp = -1, ImmOp = -1;
5756   switch(Inst.getOpcode()) {
5757     case ARM::tB:
5758     case ARM::tBcc:  CondOp = 1; ImmOp = 2; break;
5759 
5760     case ARM::t2B:
5761     case ARM::t2Bcc: CondOp = 1; ImmOp = 3; break;
5762 
5763     default: llvm_unreachable("Unexpected instruction in cvtThumbBranches");
5764   }
5765   // first decide whether or not the branch should be conditional
5766   // by looking at it's location relative to an IT block
5767   if(inITBlock()) {
5768     // inside an IT block we cannot have any conditional branches. any
5769     // such instructions needs to be converted to unconditional form
5770     switch(Inst.getOpcode()) {
5771       case ARM::tBcc: Inst.setOpcode(ARM::tB); break;
5772       case ARM::t2Bcc: Inst.setOpcode(ARM::t2B); break;
5773     }
5774   } else {
5775     // outside IT blocks we can only have unconditional branches with AL
5776     // condition code or conditional branches with non-AL condition code
5777     unsigned Cond = static_cast<ARMOperand &>(*Operands[CondOp]).getCondCode();
5778     switch(Inst.getOpcode()) {
5779       case ARM::tB:
5780       case ARM::tBcc:
5781         Inst.setOpcode(Cond == ARMCC::AL ? ARM::tB : ARM::tBcc);
5782         break;
5783       case ARM::t2B:
5784       case ARM::t2Bcc:
5785         Inst.setOpcode(Cond == ARMCC::AL ? ARM::t2B : ARM::t2Bcc);
5786         break;
5787     }
5788   }
5789 
5790   // now decide on encoding size based on branch target range
5791   switch(Inst.getOpcode()) {
5792     // classify tB as either t2B or t1B based on range of immediate operand
5793     case ARM::tB: {
5794       ARMOperand &op = static_cast<ARMOperand &>(*Operands[ImmOp]);
5795       if (!op.isSignedOffset<11, 1>() && isThumb() && hasV8MBaseline())
5796         Inst.setOpcode(ARM::t2B);
5797       break;
5798     }
5799     // classify tBcc as either t2Bcc or t1Bcc based on range of immediate operand
5800     case ARM::tBcc: {
5801       ARMOperand &op = static_cast<ARMOperand &>(*Operands[ImmOp]);
5802       if (!op.isSignedOffset<8, 1>() && isThumb() && hasV8MBaseline())
5803         Inst.setOpcode(ARM::t2Bcc);
5804       break;
5805     }
5806   }
5807   ((ARMOperand &)*Operands[ImmOp]).addImmOperands(Inst, 1);
5808   ((ARMOperand &)*Operands[CondOp]).addCondCodeOperands(Inst, 2);
5809 }
5810 
5811 void ARMAsmParser::cvtMVEVMOVQtoDReg(
5812   MCInst &Inst, const OperandVector &Operands) {
5813 
5814   // mnemonic, condition code, Rt, Rt2, Qd, idx, Qd again, idx2
5815   assert(Operands.size() == 8);
5816 
5817   ((ARMOperand &)*Operands[2]).addRegOperands(Inst, 1); // Rt
5818   ((ARMOperand &)*Operands[3]).addRegOperands(Inst, 1); // Rt2
5819   ((ARMOperand &)*Operands[4]).addRegOperands(Inst, 1); // Qd
5820   ((ARMOperand &)*Operands[5]).addMVEPairVectorIndexOperands(Inst, 1); // idx
5821   // skip second copy of Qd in Operands[6]
5822   ((ARMOperand &)*Operands[7]).addMVEPairVectorIndexOperands(Inst, 1); // idx2
5823   ((ARMOperand &)*Operands[1]).addCondCodeOperands(Inst, 2); // condition code
5824 }
5825 
5826 /// Parse an ARM memory expression, return false if successful else return true
5827 /// or an error.  The first token must be a '[' when called.
5828 bool ARMAsmParser::parseMemory(OperandVector &Operands) {
5829   MCAsmParser &Parser = getParser();
5830   SMLoc S, E;
5831   if (Parser.getTok().isNot(AsmToken::LBrac))
5832     return TokError("Token is not a Left Bracket");
5833   S = Parser.getTok().getLoc();
5834   Parser.Lex(); // Eat left bracket token.
5835 
5836   const AsmToken &BaseRegTok = Parser.getTok();
5837   int BaseRegNum = tryParseRegister();
5838   if (BaseRegNum == -1)
5839     return Error(BaseRegTok.getLoc(), "register expected");
5840 
5841   // The next token must either be a comma, a colon or a closing bracket.
5842   const AsmToken &Tok = Parser.getTok();
5843   if (!Tok.is(AsmToken::Colon) && !Tok.is(AsmToken::Comma) &&
5844       !Tok.is(AsmToken::RBrac))
5845     return Error(Tok.getLoc(), "malformed memory operand");
5846 
5847   if (Tok.is(AsmToken::RBrac)) {
5848     E = Tok.getEndLoc();
5849     Parser.Lex(); // Eat right bracket token.
5850 
5851     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, 0,
5852                                              ARM_AM::no_shift, 0, 0, false,
5853                                              S, E));
5854 
5855     // If there's a pre-indexing writeback marker, '!', just add it as a token
5856     // operand. It's rather odd, but syntactically valid.
5857     if (Parser.getTok().is(AsmToken::Exclaim)) {
5858       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
5859       Parser.Lex(); // Eat the '!'.
5860     }
5861 
5862     return false;
5863   }
5864 
5865   assert((Tok.is(AsmToken::Colon) || Tok.is(AsmToken::Comma)) &&
5866          "Lost colon or comma in memory operand?!");
5867   if (Tok.is(AsmToken::Comma)) {
5868     Parser.Lex(); // Eat the comma.
5869   }
5870 
5871   // If we have a ':', it's an alignment specifier.
5872   if (Parser.getTok().is(AsmToken::Colon)) {
5873     Parser.Lex(); // Eat the ':'.
5874     E = Parser.getTok().getLoc();
5875     SMLoc AlignmentLoc = Tok.getLoc();
5876 
5877     const MCExpr *Expr;
5878     if (getParser().parseExpression(Expr))
5879      return true;
5880 
5881     // The expression has to be a constant. Memory references with relocations
5882     // don't come through here, as they use the <label> forms of the relevant
5883     // instructions.
5884     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
5885     if (!CE)
5886       return Error (E, "constant expression expected");
5887 
5888     unsigned Align = 0;
5889     switch (CE->getValue()) {
5890     default:
5891       return Error(E,
5892                    "alignment specifier must be 16, 32, 64, 128, or 256 bits");
5893     case 16:  Align = 2; break;
5894     case 32:  Align = 4; break;
5895     case 64:  Align = 8; break;
5896     case 128: Align = 16; break;
5897     case 256: Align = 32; break;
5898     }
5899 
5900     // Now we should have the closing ']'
5901     if (Parser.getTok().isNot(AsmToken::RBrac))
5902       return Error(Parser.getTok().getLoc(), "']' expected");
5903     E = Parser.getTok().getEndLoc();
5904     Parser.Lex(); // Eat right bracket token.
5905 
5906     // Don't worry about range checking the value here. That's handled by
5907     // the is*() predicates.
5908     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, 0,
5909                                              ARM_AM::no_shift, 0, Align,
5910                                              false, S, E, AlignmentLoc));
5911 
5912     // If there's a pre-indexing writeback marker, '!', just add it as a token
5913     // operand.
5914     if (Parser.getTok().is(AsmToken::Exclaim)) {
5915       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
5916       Parser.Lex(); // Eat the '!'.
5917     }
5918 
5919     return false;
5920   }
5921 
5922   // If we have a '#' or '$', it's an immediate offset, else assume it's a
5923   // register offset. Be friendly and also accept a plain integer or expression
5924   // (without a leading hash) for gas compatibility.
5925   if (Parser.getTok().is(AsmToken::Hash) ||
5926       Parser.getTok().is(AsmToken::Dollar) ||
5927       Parser.getTok().is(AsmToken::LParen) ||
5928       Parser.getTok().is(AsmToken::Integer)) {
5929     if (Parser.getTok().is(AsmToken::Hash) ||
5930         Parser.getTok().is(AsmToken::Dollar))
5931       Parser.Lex(); // Eat '#' or '$'
5932     E = Parser.getTok().getLoc();
5933 
5934     bool isNegative = getParser().getTok().is(AsmToken::Minus);
5935     const MCExpr *Offset, *AdjustedOffset;
5936     if (getParser().parseExpression(Offset))
5937      return true;
5938 
5939     if (const auto *CE = dyn_cast<MCConstantExpr>(Offset)) {
5940       // If the constant was #-0, represent it as
5941       // std::numeric_limits<int32_t>::min().
5942       int32_t Val = CE->getValue();
5943       if (isNegative && Val == 0)
5944         CE = MCConstantExpr::create(std::numeric_limits<int32_t>::min(),
5945                                     getContext());
5946       // Don't worry about range checking the value here. That's handled by
5947       // the is*() predicates.
5948       AdjustedOffset = CE;
5949     } else
5950       AdjustedOffset = Offset;
5951     Operands.push_back(ARMOperand::CreateMem(
5952         BaseRegNum, AdjustedOffset, 0, ARM_AM::no_shift, 0, 0, false, S, E));
5953 
5954     // Now we should have the closing ']'
5955     if (Parser.getTok().isNot(AsmToken::RBrac))
5956       return Error(Parser.getTok().getLoc(), "']' expected");
5957     E = Parser.getTok().getEndLoc();
5958     Parser.Lex(); // Eat right bracket token.
5959 
5960     // If there's a pre-indexing writeback marker, '!', just add it as a token
5961     // operand.
5962     if (Parser.getTok().is(AsmToken::Exclaim)) {
5963       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
5964       Parser.Lex(); // Eat the '!'.
5965     }
5966 
5967     return false;
5968   }
5969 
5970   // The register offset is optionally preceded by a '+' or '-'
5971   bool isNegative = false;
5972   if (Parser.getTok().is(AsmToken::Minus)) {
5973     isNegative = true;
5974     Parser.Lex(); // Eat the '-'.
5975   } else if (Parser.getTok().is(AsmToken::Plus)) {
5976     // Nothing to do.
5977     Parser.Lex(); // Eat the '+'.
5978   }
5979 
5980   E = Parser.getTok().getLoc();
5981   int OffsetRegNum = tryParseRegister();
5982   if (OffsetRegNum == -1)
5983     return Error(E, "register expected");
5984 
5985   // If there's a shift operator, handle it.
5986   ARM_AM::ShiftOpc ShiftType = ARM_AM::no_shift;
5987   unsigned ShiftImm = 0;
5988   if (Parser.getTok().is(AsmToken::Comma)) {
5989     Parser.Lex(); // Eat the ','.
5990     if (parseMemRegOffsetShift(ShiftType, ShiftImm))
5991       return true;
5992   }
5993 
5994   // Now we should have the closing ']'
5995   if (Parser.getTok().isNot(AsmToken::RBrac))
5996     return Error(Parser.getTok().getLoc(), "']' expected");
5997   E = Parser.getTok().getEndLoc();
5998   Parser.Lex(); // Eat right bracket token.
5999 
6000   Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, OffsetRegNum,
6001                                            ShiftType, ShiftImm, 0, isNegative,
6002                                            S, E));
6003 
6004   // If there's a pre-indexing writeback marker, '!', just add it as a token
6005   // operand.
6006   if (Parser.getTok().is(AsmToken::Exclaim)) {
6007     Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
6008     Parser.Lex(); // Eat the '!'.
6009   }
6010 
6011   return false;
6012 }
6013 
6014 /// parseMemRegOffsetShift - one of these two:
6015 ///   ( lsl | lsr | asr | ror ) , # shift_amount
6016 ///   rrx
6017 /// return true if it parses a shift otherwise it returns false.
6018 bool ARMAsmParser::parseMemRegOffsetShift(ARM_AM::ShiftOpc &St,
6019                                           unsigned &Amount) {
6020   MCAsmParser &Parser = getParser();
6021   SMLoc Loc = Parser.getTok().getLoc();
6022   const AsmToken &Tok = Parser.getTok();
6023   if (Tok.isNot(AsmToken::Identifier))
6024     return Error(Loc, "illegal shift operator");
6025   StringRef ShiftName = Tok.getString();
6026   if (ShiftName == "lsl" || ShiftName == "LSL" ||
6027       ShiftName == "asl" || ShiftName == "ASL")
6028     St = ARM_AM::lsl;
6029   else if (ShiftName == "lsr" || ShiftName == "LSR")
6030     St = ARM_AM::lsr;
6031   else if (ShiftName == "asr" || ShiftName == "ASR")
6032     St = ARM_AM::asr;
6033   else if (ShiftName == "ror" || ShiftName == "ROR")
6034     St = ARM_AM::ror;
6035   else if (ShiftName == "rrx" || ShiftName == "RRX")
6036     St = ARM_AM::rrx;
6037   else if (ShiftName == "uxtw" || ShiftName == "UXTW")
6038     St = ARM_AM::uxtw;
6039   else
6040     return Error(Loc, "illegal shift operator");
6041   Parser.Lex(); // Eat shift type token.
6042 
6043   // rrx stands alone.
6044   Amount = 0;
6045   if (St != ARM_AM::rrx) {
6046     Loc = Parser.getTok().getLoc();
6047     // A '#' and a shift amount.
6048     const AsmToken &HashTok = Parser.getTok();
6049     if (HashTok.isNot(AsmToken::Hash) &&
6050         HashTok.isNot(AsmToken::Dollar))
6051       return Error(HashTok.getLoc(), "'#' expected");
6052     Parser.Lex(); // Eat hash token.
6053 
6054     const MCExpr *Expr;
6055     if (getParser().parseExpression(Expr))
6056       return true;
6057     // Range check the immediate.
6058     // lsl, ror: 0 <= imm <= 31
6059     // lsr, asr: 0 <= imm <= 32
6060     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
6061     if (!CE)
6062       return Error(Loc, "shift amount must be an immediate");
6063     int64_t Imm = CE->getValue();
6064     if (Imm < 0 ||
6065         ((St == ARM_AM::lsl || St == ARM_AM::ror) && Imm > 31) ||
6066         ((St == ARM_AM::lsr || St == ARM_AM::asr) && Imm > 32))
6067       return Error(Loc, "immediate shift value out of range");
6068     // If <ShiftTy> #0, turn it into a no_shift.
6069     if (Imm == 0)
6070       St = ARM_AM::lsl;
6071     // For consistency, treat lsr #32 and asr #32 as having immediate value 0.
6072     if (Imm == 32)
6073       Imm = 0;
6074     Amount = Imm;
6075   }
6076 
6077   return false;
6078 }
6079 
6080 /// parseFPImm - A floating point immediate expression operand.
6081 OperandMatchResultTy
6082 ARMAsmParser::parseFPImm(OperandVector &Operands) {
6083   MCAsmParser &Parser = getParser();
6084   // Anything that can accept a floating point constant as an operand
6085   // needs to go through here, as the regular parseExpression is
6086   // integer only.
6087   //
6088   // This routine still creates a generic Immediate operand, containing
6089   // a bitcast of the 64-bit floating point value. The various operands
6090   // that accept floats can check whether the value is valid for them
6091   // via the standard is*() predicates.
6092 
6093   SMLoc S = Parser.getTok().getLoc();
6094 
6095   if (Parser.getTok().isNot(AsmToken::Hash) &&
6096       Parser.getTok().isNot(AsmToken::Dollar))
6097     return MatchOperand_NoMatch;
6098 
6099   // Disambiguate the VMOV forms that can accept an FP immediate.
6100   // vmov.f32 <sreg>, #imm
6101   // vmov.f64 <dreg>, #imm
6102   // vmov.f32 <dreg>, #imm  @ vector f32x2
6103   // vmov.f32 <qreg>, #imm  @ vector f32x4
6104   //
6105   // There are also the NEON VMOV instructions which expect an
6106   // integer constant. Make sure we don't try to parse an FPImm
6107   // for these:
6108   // vmov.i{8|16|32|64} <dreg|qreg>, #imm
6109   ARMOperand &TyOp = static_cast<ARMOperand &>(*Operands[2]);
6110   bool isVmovf = TyOp.isToken() &&
6111                  (TyOp.getToken() == ".f32" || TyOp.getToken() == ".f64" ||
6112                   TyOp.getToken() == ".f16");
6113   ARMOperand &Mnemonic = static_cast<ARMOperand &>(*Operands[0]);
6114   bool isFconst = Mnemonic.isToken() && (Mnemonic.getToken() == "fconstd" ||
6115                                          Mnemonic.getToken() == "fconsts");
6116   if (!(isVmovf || isFconst))
6117     return MatchOperand_NoMatch;
6118 
6119   Parser.Lex(); // Eat '#' or '$'.
6120 
6121   // Handle negation, as that still comes through as a separate token.
6122   bool isNegative = false;
6123   if (Parser.getTok().is(AsmToken::Minus)) {
6124     isNegative = true;
6125     Parser.Lex();
6126   }
6127   const AsmToken &Tok = Parser.getTok();
6128   SMLoc Loc = Tok.getLoc();
6129   if (Tok.is(AsmToken::Real) && isVmovf) {
6130     APFloat RealVal(APFloat::IEEEsingle(), Tok.getString());
6131     uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
6132     // If we had a '-' in front, toggle the sign bit.
6133     IntVal ^= (uint64_t)isNegative << 31;
6134     Parser.Lex(); // Eat the token.
6135     Operands.push_back(ARMOperand::CreateImm(
6136           MCConstantExpr::create(IntVal, getContext()),
6137           S, Parser.getTok().getLoc()));
6138     return MatchOperand_Success;
6139   }
6140   // Also handle plain integers. Instructions which allow floating point
6141   // immediates also allow a raw encoded 8-bit value.
6142   if (Tok.is(AsmToken::Integer) && isFconst) {
6143     int64_t Val = Tok.getIntVal();
6144     Parser.Lex(); // Eat the token.
6145     if (Val > 255 || Val < 0) {
6146       Error(Loc, "encoded floating point value out of range");
6147       return MatchOperand_ParseFail;
6148     }
6149     float RealVal = ARM_AM::getFPImmFloat(Val);
6150     Val = APFloat(RealVal).bitcastToAPInt().getZExtValue();
6151 
6152     Operands.push_back(ARMOperand::CreateImm(
6153         MCConstantExpr::create(Val, getContext()), S,
6154         Parser.getTok().getLoc()));
6155     return MatchOperand_Success;
6156   }
6157 
6158   Error(Loc, "invalid floating point immediate");
6159   return MatchOperand_ParseFail;
6160 }
6161 
6162 /// Parse a arm instruction operand.  For now this parses the operand regardless
6163 /// of the mnemonic.
6164 bool ARMAsmParser::parseOperand(OperandVector &Operands, StringRef Mnemonic) {
6165   MCAsmParser &Parser = getParser();
6166   SMLoc S, E;
6167 
6168   // Check if the current operand has a custom associated parser, if so, try to
6169   // custom parse the operand, or fallback to the general approach.
6170   OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
6171   if (ResTy == MatchOperand_Success)
6172     return false;
6173   // If there wasn't a custom match, try the generic matcher below. Otherwise,
6174   // there was a match, but an error occurred, in which case, just return that
6175   // the operand parsing failed.
6176   if (ResTy == MatchOperand_ParseFail)
6177     return true;
6178 
6179   switch (getLexer().getKind()) {
6180   default:
6181     Error(Parser.getTok().getLoc(), "unexpected token in operand");
6182     return true;
6183   case AsmToken::Identifier: {
6184     // If we've seen a branch mnemonic, the next operand must be a label.  This
6185     // is true even if the label is a register name.  So "br r1" means branch to
6186     // label "r1".
6187     bool ExpectLabel = Mnemonic == "b" || Mnemonic == "bl";
6188     if (!ExpectLabel) {
6189       if (!tryParseRegisterWithWriteBack(Operands))
6190         return false;
6191       int Res = tryParseShiftRegister(Operands);
6192       if (Res == 0) // success
6193         return false;
6194       else if (Res == -1) // irrecoverable error
6195         return true;
6196       // If this is VMRS, check for the apsr_nzcv operand.
6197       if (Mnemonic == "vmrs" &&
6198           Parser.getTok().getString().equals_lower("apsr_nzcv")) {
6199         S = Parser.getTok().getLoc();
6200         Parser.Lex();
6201         Operands.push_back(ARMOperand::CreateToken("APSR_nzcv", S));
6202         return false;
6203       }
6204     }
6205 
6206     // Fall though for the Identifier case that is not a register or a
6207     // special name.
6208     LLVM_FALLTHROUGH;
6209   }
6210   case AsmToken::LParen:  // parenthesized expressions like (_strcmp-4)
6211   case AsmToken::Integer: // things like 1f and 2b as a branch targets
6212   case AsmToken::String:  // quoted label names.
6213   case AsmToken::Dot: {   // . as a branch target
6214     // This was not a register so parse other operands that start with an
6215     // identifier (like labels) as expressions and create them as immediates.
6216     const MCExpr *IdVal;
6217     S = Parser.getTok().getLoc();
6218     if (getParser().parseExpression(IdVal))
6219       return true;
6220     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
6221     Operands.push_back(ARMOperand::CreateImm(IdVal, S, E));
6222     return false;
6223   }
6224   case AsmToken::LBrac:
6225     return parseMemory(Operands);
6226   case AsmToken::LCurly:
6227     return parseRegisterList(Operands, !Mnemonic.startswith("clr"));
6228   case AsmToken::Dollar:
6229   case AsmToken::Hash: {
6230     // #42 -> immediate
6231     // $ 42 -> immediate
6232     // $foo -> symbol name
6233     // $42 -> symbol name
6234     S = Parser.getTok().getLoc();
6235 
6236     // Favor the interpretation of $-prefixed operands as symbol names.
6237     // Cases where immediates are explicitly expected are handled by their
6238     // specific ParseMethod implementations.
6239     auto AdjacentToken = getLexer().peekTok(/*ShouldSkipSpace=*/false);
6240     bool ExpectIdentifier = Parser.getTok().is(AsmToken::Dollar) &&
6241                             (AdjacentToken.is(AsmToken::Identifier) ||
6242                              AdjacentToken.is(AsmToken::Integer));
6243     if (!ExpectIdentifier) {
6244       // Token is not part of identifier. Drop leading $ or # before parsing
6245       // expression.
6246       Parser.Lex();
6247     }
6248 
6249     if (Parser.getTok().isNot(AsmToken::Colon)) {
6250       bool IsNegative = Parser.getTok().is(AsmToken::Minus);
6251       const MCExpr *ImmVal;
6252       if (getParser().parseExpression(ImmVal))
6253         return true;
6254       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ImmVal);
6255       if (CE) {
6256         int32_t Val = CE->getValue();
6257         if (IsNegative && Val == 0)
6258           ImmVal = MCConstantExpr::create(std::numeric_limits<int32_t>::min(),
6259                                           getContext());
6260       }
6261       E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
6262       Operands.push_back(ARMOperand::CreateImm(ImmVal, S, E));
6263 
6264       // There can be a trailing '!' on operands that we want as a separate
6265       // '!' Token operand. Handle that here. For example, the compatibility
6266       // alias for 'srsdb sp!, #imm' is 'srsdb #imm!'.
6267       if (Parser.getTok().is(AsmToken::Exclaim)) {
6268         Operands.push_back(ARMOperand::CreateToken(Parser.getTok().getString(),
6269                                                    Parser.getTok().getLoc()));
6270         Parser.Lex(); // Eat exclaim token
6271       }
6272       return false;
6273     }
6274     // w/ a ':' after the '#', it's just like a plain ':'.
6275     LLVM_FALLTHROUGH;
6276   }
6277   case AsmToken::Colon: {
6278     S = Parser.getTok().getLoc();
6279     // ":lower16:" and ":upper16:" expression prefixes
6280     // FIXME: Check it's an expression prefix,
6281     // e.g. (FOO - :lower16:BAR) isn't legal.
6282     ARMMCExpr::VariantKind RefKind;
6283     if (parsePrefix(RefKind))
6284       return true;
6285 
6286     const MCExpr *SubExprVal;
6287     if (getParser().parseExpression(SubExprVal))
6288       return true;
6289 
6290     const MCExpr *ExprVal = ARMMCExpr::create(RefKind, SubExprVal,
6291                                               getContext());
6292     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
6293     Operands.push_back(ARMOperand::CreateImm(ExprVal, S, E));
6294     return false;
6295   }
6296   case AsmToken::Equal: {
6297     S = Parser.getTok().getLoc();
6298     if (Mnemonic != "ldr") // only parse for ldr pseudo (e.g. ldr r0, =val)
6299       return Error(S, "unexpected token in operand");
6300     Parser.Lex(); // Eat '='
6301     const MCExpr *SubExprVal;
6302     if (getParser().parseExpression(SubExprVal))
6303       return true;
6304     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
6305 
6306     // execute-only: we assume that assembly programmers know what they are
6307     // doing and allow literal pool creation here
6308     Operands.push_back(ARMOperand::CreateConstantPoolImm(SubExprVal, S, E));
6309     return false;
6310   }
6311   }
6312 }
6313 
6314 // parsePrefix - Parse ARM 16-bit relocations expression prefix, i.e.
6315 //  :lower16: and :upper16:.
6316 bool ARMAsmParser::parsePrefix(ARMMCExpr::VariantKind &RefKind) {
6317   MCAsmParser &Parser = getParser();
6318   RefKind = ARMMCExpr::VK_ARM_None;
6319 
6320   // consume an optional '#' (GNU compatibility)
6321   if (getLexer().is(AsmToken::Hash))
6322     Parser.Lex();
6323 
6324   // :lower16: and :upper16: modifiers
6325   assert(getLexer().is(AsmToken::Colon) && "expected a :");
6326   Parser.Lex(); // Eat ':'
6327 
6328   if (getLexer().isNot(AsmToken::Identifier)) {
6329     Error(Parser.getTok().getLoc(), "expected prefix identifier in operand");
6330     return true;
6331   }
6332 
6333   enum {
6334     COFF = (1 << MCObjectFileInfo::IsCOFF),
6335     ELF = (1 << MCObjectFileInfo::IsELF),
6336     MACHO = (1 << MCObjectFileInfo::IsMachO),
6337     WASM = (1 << MCObjectFileInfo::IsWasm),
6338   };
6339   static const struct PrefixEntry {
6340     const char *Spelling;
6341     ARMMCExpr::VariantKind VariantKind;
6342     uint8_t SupportedFormats;
6343   } PrefixEntries[] = {
6344     { "lower16", ARMMCExpr::VK_ARM_LO16, COFF | ELF | MACHO },
6345     { "upper16", ARMMCExpr::VK_ARM_HI16, COFF | ELF | MACHO },
6346   };
6347 
6348   StringRef IDVal = Parser.getTok().getIdentifier();
6349 
6350   const auto &Prefix =
6351       llvm::find_if(PrefixEntries, [&IDVal](const PrefixEntry &PE) {
6352         return PE.Spelling == IDVal;
6353       });
6354   if (Prefix == std::end(PrefixEntries)) {
6355     Error(Parser.getTok().getLoc(), "unexpected prefix in operand");
6356     return true;
6357   }
6358 
6359   uint8_t CurrentFormat;
6360   switch (getContext().getObjectFileInfo()->getObjectFileType()) {
6361   case MCObjectFileInfo::IsMachO:
6362     CurrentFormat = MACHO;
6363     break;
6364   case MCObjectFileInfo::IsELF:
6365     CurrentFormat = ELF;
6366     break;
6367   case MCObjectFileInfo::IsCOFF:
6368     CurrentFormat = COFF;
6369     break;
6370   case MCObjectFileInfo::IsWasm:
6371     CurrentFormat = WASM;
6372     break;
6373   case MCObjectFileInfo::IsXCOFF:
6374     llvm_unreachable("unexpected object format");
6375     break;
6376   }
6377 
6378   if (~Prefix->SupportedFormats & CurrentFormat) {
6379     Error(Parser.getTok().getLoc(),
6380           "cannot represent relocation in the current file format");
6381     return true;
6382   }
6383 
6384   RefKind = Prefix->VariantKind;
6385   Parser.Lex();
6386 
6387   if (getLexer().isNot(AsmToken::Colon)) {
6388     Error(Parser.getTok().getLoc(), "unexpected token after prefix");
6389     return true;
6390   }
6391   Parser.Lex(); // Eat the last ':'
6392 
6393   return false;
6394 }
6395 
6396 /// Given a mnemonic, split out possible predication code and carry
6397 /// setting letters to form a canonical mnemonic and flags.
6398 //
6399 // FIXME: Would be nice to autogen this.
6400 // FIXME: This is a bit of a maze of special cases.
6401 StringRef ARMAsmParser::splitMnemonic(StringRef Mnemonic,
6402                                       StringRef ExtraToken,
6403                                       unsigned &PredicationCode,
6404                                       unsigned &VPTPredicationCode,
6405                                       bool &CarrySetting,
6406                                       unsigned &ProcessorIMod,
6407                                       StringRef &ITMask) {
6408   PredicationCode = ARMCC::AL;
6409   VPTPredicationCode = ARMVCC::None;
6410   CarrySetting = false;
6411   ProcessorIMod = 0;
6412 
6413   // Ignore some mnemonics we know aren't predicated forms.
6414   //
6415   // FIXME: Would be nice to autogen this.
6416   if ((Mnemonic == "movs" && isThumb()) ||
6417       Mnemonic == "teq"   || Mnemonic == "vceq"   || Mnemonic == "svc"   ||
6418       Mnemonic == "mls"   || Mnemonic == "smmls"  || Mnemonic == "vcls"  ||
6419       Mnemonic == "vmls"  || Mnemonic == "vnmls"  || Mnemonic == "vacge" ||
6420       Mnemonic == "vcge"  || Mnemonic == "vclt"   || Mnemonic == "vacgt" ||
6421       Mnemonic == "vaclt" || Mnemonic == "vacle"  || Mnemonic == "hlt" ||
6422       Mnemonic == "vcgt"  || Mnemonic == "vcle"   || Mnemonic == "smlal" ||
6423       Mnemonic == "umaal" || Mnemonic == "umlal"  || Mnemonic == "vabal" ||
6424       Mnemonic == "vmlal" || Mnemonic == "vpadal" || Mnemonic == "vqdmlal" ||
6425       Mnemonic == "fmuls" || Mnemonic == "vmaxnm" || Mnemonic == "vminnm" ||
6426       Mnemonic == "vcvta" || Mnemonic == "vcvtn"  || Mnemonic == "vcvtp" ||
6427       Mnemonic == "vcvtm" || Mnemonic == "vrinta" || Mnemonic == "vrintn" ||
6428       Mnemonic == "vrintp" || Mnemonic == "vrintm" || Mnemonic == "hvc" ||
6429       Mnemonic.startswith("vsel") || Mnemonic == "vins" || Mnemonic == "vmovx" ||
6430       Mnemonic == "bxns"  || Mnemonic == "blxns" ||
6431       Mnemonic == "vdot"  || Mnemonic == "vmmla"  ||
6432       Mnemonic == "vudot" || Mnemonic == "vsdot" ||
6433       Mnemonic == "vcmla" || Mnemonic == "vcadd" ||
6434       Mnemonic == "vfmal" || Mnemonic == "vfmsl" ||
6435       Mnemonic == "wls" || Mnemonic == "le" || Mnemonic == "dls" ||
6436       Mnemonic == "csel" || Mnemonic == "csinc" ||
6437       Mnemonic == "csinv" || Mnemonic == "csneg" || Mnemonic == "cinc" ||
6438       Mnemonic == "cinv" || Mnemonic == "cneg" || Mnemonic == "cset" ||
6439       Mnemonic == "csetm")
6440     return Mnemonic;
6441 
6442   // First, split out any predication code. Ignore mnemonics we know aren't
6443   // predicated but do have a carry-set and so weren't caught above.
6444   if (Mnemonic != "adcs" && Mnemonic != "bics" && Mnemonic != "movs" &&
6445       Mnemonic != "muls" && Mnemonic != "smlals" && Mnemonic != "smulls" &&
6446       Mnemonic != "umlals" && Mnemonic != "umulls" && Mnemonic != "lsls" &&
6447       Mnemonic != "sbcs" && Mnemonic != "rscs" &&
6448       !(hasMVE() &&
6449         (Mnemonic == "vmine" ||
6450          Mnemonic == "vshle" || Mnemonic == "vshlt" || Mnemonic == "vshllt" ||
6451          Mnemonic == "vrshle" || Mnemonic == "vrshlt" ||
6452          Mnemonic == "vmvne" || Mnemonic == "vorne" ||
6453          Mnemonic == "vnege" || Mnemonic == "vnegt" ||
6454          Mnemonic == "vmule" || Mnemonic == "vmult" ||
6455          Mnemonic == "vrintne" ||
6456          Mnemonic == "vcmult" || Mnemonic == "vcmule" ||
6457          Mnemonic == "vpsele" || Mnemonic == "vpselt" ||
6458          Mnemonic.startswith("vq")))) {
6459     unsigned CC = ARMCondCodeFromString(Mnemonic.substr(Mnemonic.size()-2));
6460     if (CC != ~0U) {
6461       Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 2);
6462       PredicationCode = CC;
6463     }
6464   }
6465 
6466   // Next, determine if we have a carry setting bit. We explicitly ignore all
6467   // the instructions we know end in 's'.
6468   if (Mnemonic.endswith("s") &&
6469       !(Mnemonic == "cps" || Mnemonic == "mls" ||
6470         Mnemonic == "mrs" || Mnemonic == "smmls" || Mnemonic == "vabs" ||
6471         Mnemonic == "vcls" || Mnemonic == "vmls" || Mnemonic == "vmrs" ||
6472         Mnemonic == "vnmls" || Mnemonic == "vqabs" || Mnemonic == "vrecps" ||
6473         Mnemonic == "vrsqrts" || Mnemonic == "srs" || Mnemonic == "flds" ||
6474         Mnemonic == "fmrs" || Mnemonic == "fsqrts" || Mnemonic == "fsubs" ||
6475         Mnemonic == "fsts" || Mnemonic == "fcpys" || Mnemonic == "fdivs" ||
6476         Mnemonic == "fmuls" || Mnemonic == "fcmps" || Mnemonic == "fcmpzs" ||
6477         Mnemonic == "vfms" || Mnemonic == "vfnms" || Mnemonic == "fconsts" ||
6478         Mnemonic == "bxns" || Mnemonic == "blxns" || Mnemonic == "vfmas" ||
6479         Mnemonic == "vmlas" ||
6480         (Mnemonic == "movs" && isThumb()))) {
6481     Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 1);
6482     CarrySetting = true;
6483   }
6484 
6485   // The "cps" instruction can have a interrupt mode operand which is glued into
6486   // the mnemonic. Check if this is the case, split it and parse the imod op
6487   if (Mnemonic.startswith("cps")) {
6488     // Split out any imod code.
6489     unsigned IMod =
6490       StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2, 2))
6491       .Case("ie", ARM_PROC::IE)
6492       .Case("id", ARM_PROC::ID)
6493       .Default(~0U);
6494     if (IMod != ~0U) {
6495       Mnemonic = Mnemonic.slice(0, Mnemonic.size()-2);
6496       ProcessorIMod = IMod;
6497     }
6498   }
6499 
6500   if (isMnemonicVPTPredicable(Mnemonic, ExtraToken) && Mnemonic != "vmovlt" &&
6501       Mnemonic != "vshllt" && Mnemonic != "vrshrnt" && Mnemonic != "vshrnt" &&
6502       Mnemonic != "vqrshrunt" && Mnemonic != "vqshrunt" &&
6503       Mnemonic != "vqrshrnt" && Mnemonic != "vqshrnt" && Mnemonic != "vmullt" &&
6504       Mnemonic != "vqmovnt" && Mnemonic != "vqmovunt" &&
6505       Mnemonic != "vqmovnt" && Mnemonic != "vmovnt" && Mnemonic != "vqdmullt" &&
6506       Mnemonic != "vpnot" && Mnemonic != "vcvtt" && Mnemonic != "vcvt") {
6507     unsigned CC = ARMVectorCondCodeFromString(Mnemonic.substr(Mnemonic.size()-1));
6508     if (CC != ~0U) {
6509       Mnemonic = Mnemonic.slice(0, Mnemonic.size()-1);
6510       VPTPredicationCode = CC;
6511     }
6512     return Mnemonic;
6513   }
6514 
6515   // The "it" instruction has the condition mask on the end of the mnemonic.
6516   if (Mnemonic.startswith("it")) {
6517     ITMask = Mnemonic.slice(2, Mnemonic.size());
6518     Mnemonic = Mnemonic.slice(0, 2);
6519   }
6520 
6521   if (Mnemonic.startswith("vpst")) {
6522     ITMask = Mnemonic.slice(4, Mnemonic.size());
6523     Mnemonic = Mnemonic.slice(0, 4);
6524   }
6525   else if (Mnemonic.startswith("vpt")) {
6526     ITMask = Mnemonic.slice(3, Mnemonic.size());
6527     Mnemonic = Mnemonic.slice(0, 3);
6528   }
6529 
6530   return Mnemonic;
6531 }
6532 
6533 /// Given a canonical mnemonic, determine if the instruction ever allows
6534 /// inclusion of carry set or predication code operands.
6535 //
6536 // FIXME: It would be nice to autogen this.
6537 void ARMAsmParser::getMnemonicAcceptInfo(StringRef Mnemonic,
6538                                          StringRef ExtraToken,
6539                                          StringRef FullInst,
6540                                          bool &CanAcceptCarrySet,
6541                                          bool &CanAcceptPredicationCode,
6542                                          bool &CanAcceptVPTPredicationCode) {
6543   CanAcceptVPTPredicationCode = isMnemonicVPTPredicable(Mnemonic, ExtraToken);
6544 
6545   CanAcceptCarrySet =
6546       Mnemonic == "and" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
6547       Mnemonic == "rrx" || Mnemonic == "ror" || Mnemonic == "sub" ||
6548       Mnemonic == "add" || Mnemonic == "adc" || Mnemonic == "mul" ||
6549       Mnemonic == "bic" || Mnemonic == "asr" || Mnemonic == "orr" ||
6550       Mnemonic == "mvn" || Mnemonic == "rsb" || Mnemonic == "rsc" ||
6551       Mnemonic == "orn" || Mnemonic == "sbc" || Mnemonic == "eor" ||
6552       Mnemonic == "neg" || Mnemonic == "vfm" || Mnemonic == "vfnm" ||
6553       (!isThumb() &&
6554        (Mnemonic == "smull" || Mnemonic == "mov" || Mnemonic == "mla" ||
6555         Mnemonic == "smlal" || Mnemonic == "umlal" || Mnemonic == "umull"));
6556 
6557   if (Mnemonic == "bkpt" || Mnemonic == "cbnz" || Mnemonic == "setend" ||
6558       Mnemonic == "cps" || Mnemonic == "it" || Mnemonic == "cbz" ||
6559       Mnemonic == "trap" || Mnemonic == "hlt" || Mnemonic == "udf" ||
6560       Mnemonic.startswith("crc32") || Mnemonic.startswith("cps") ||
6561       Mnemonic.startswith("vsel") || Mnemonic == "vmaxnm" ||
6562       Mnemonic == "vminnm" || Mnemonic == "vcvta" || Mnemonic == "vcvtn" ||
6563       Mnemonic == "vcvtp" || Mnemonic == "vcvtm" || Mnemonic == "vrinta" ||
6564       Mnemonic == "vrintn" || Mnemonic == "vrintp" || Mnemonic == "vrintm" ||
6565       Mnemonic.startswith("aes") || Mnemonic == "hvc" || Mnemonic == "setpan" ||
6566       Mnemonic.startswith("sha1") || Mnemonic.startswith("sha256") ||
6567       (FullInst.startswith("vmull") && FullInst.endswith(".p64")) ||
6568       Mnemonic == "vmovx" || Mnemonic == "vins" ||
6569       Mnemonic == "vudot" || Mnemonic == "vsdot" ||
6570       Mnemonic == "vcmla" || Mnemonic == "vcadd" ||
6571       Mnemonic == "vfmal" || Mnemonic == "vfmsl" ||
6572       Mnemonic == "vfmat" || Mnemonic == "vfmab" ||
6573       Mnemonic == "vdot"  || Mnemonic == "vmmla" ||
6574       Mnemonic == "sb"    || Mnemonic == "ssbb"  ||
6575       Mnemonic == "pssbb" || Mnemonic == "vsmmla" ||
6576       Mnemonic == "vummla" || Mnemonic == "vusmmla" ||
6577       Mnemonic == "vusdot" || Mnemonic == "vsudot" ||
6578       Mnemonic == "bfcsel" || Mnemonic == "wls" ||
6579       Mnemonic == "dls" || Mnemonic == "le" || Mnemonic == "csel" ||
6580       Mnemonic == "csinc" || Mnemonic == "csinv" || Mnemonic == "csneg" ||
6581       Mnemonic == "cinc" || Mnemonic == "cinv" || Mnemonic == "cneg" ||
6582       Mnemonic == "cset" || Mnemonic == "csetm" ||
6583       Mnemonic.startswith("vpt") || Mnemonic.startswith("vpst") ||
6584       (hasCDE() && MS.isCDEInstr(Mnemonic) &&
6585        !MS.isITPredicableCDEInstr(Mnemonic)) ||
6586       (hasMVE() &&
6587        (Mnemonic.startswith("vst2") || Mnemonic.startswith("vld2") ||
6588         Mnemonic.startswith("vst4") || Mnemonic.startswith("vld4") ||
6589         Mnemonic.startswith("wlstp") || Mnemonic.startswith("dlstp") ||
6590         Mnemonic.startswith("letp")))) {
6591     // These mnemonics are never predicable
6592     CanAcceptPredicationCode = false;
6593   } else if (!isThumb()) {
6594     // Some instructions are only predicable in Thumb mode
6595     CanAcceptPredicationCode =
6596         Mnemonic != "cdp2" && Mnemonic != "clrex" && Mnemonic != "mcr2" &&
6597         Mnemonic != "mcrr2" && Mnemonic != "mrc2" && Mnemonic != "mrrc2" &&
6598         Mnemonic != "dmb" && Mnemonic != "dfb" && Mnemonic != "dsb" &&
6599         Mnemonic != "isb" && Mnemonic != "pld" && Mnemonic != "pli" &&
6600         Mnemonic != "pldw" && Mnemonic != "ldc2" && Mnemonic != "ldc2l" &&
6601         Mnemonic != "stc2" && Mnemonic != "stc2l" &&
6602         Mnemonic != "tsb" &&
6603         !Mnemonic.startswith("rfe") && !Mnemonic.startswith("srs");
6604   } else if (isThumbOne()) {
6605     if (hasV6MOps())
6606       CanAcceptPredicationCode = Mnemonic != "movs";
6607     else
6608       CanAcceptPredicationCode = Mnemonic != "nop" && Mnemonic != "movs";
6609   } else
6610     CanAcceptPredicationCode = true;
6611 }
6612 
6613 // Some Thumb instructions have two operand forms that are not
6614 // available as three operand, convert to two operand form if possible.
6615 //
6616 // FIXME: We would really like to be able to tablegen'erate this.
6617 void ARMAsmParser::tryConvertingToTwoOperandForm(StringRef Mnemonic,
6618                                                  bool CarrySetting,
6619                                                  OperandVector &Operands) {
6620   if (Operands.size() != 6)
6621     return;
6622 
6623   const auto &Op3 = static_cast<ARMOperand &>(*Operands[3]);
6624         auto &Op4 = static_cast<ARMOperand &>(*Operands[4]);
6625   if (!Op3.isReg() || !Op4.isReg())
6626     return;
6627 
6628   auto Op3Reg = Op3.getReg();
6629   auto Op4Reg = Op4.getReg();
6630 
6631   // For most Thumb2 cases we just generate the 3 operand form and reduce
6632   // it in processInstruction(), but the 3 operand form of ADD (t2ADDrr)
6633   // won't accept SP or PC so we do the transformation here taking care
6634   // with immediate range in the 'add sp, sp #imm' case.
6635   auto &Op5 = static_cast<ARMOperand &>(*Operands[5]);
6636   if (isThumbTwo()) {
6637     if (Mnemonic != "add")
6638       return;
6639     bool TryTransform = Op3Reg == ARM::PC || Op4Reg == ARM::PC ||
6640                         (Op5.isReg() && Op5.getReg() == ARM::PC);
6641     if (!TryTransform) {
6642       TryTransform = (Op3Reg == ARM::SP || Op4Reg == ARM::SP ||
6643                       (Op5.isReg() && Op5.getReg() == ARM::SP)) &&
6644                      !(Op3Reg == ARM::SP && Op4Reg == ARM::SP &&
6645                        Op5.isImm() && !Op5.isImm0_508s4());
6646     }
6647     if (!TryTransform)
6648       return;
6649   } else if (!isThumbOne())
6650     return;
6651 
6652   if (!(Mnemonic == "add" || Mnemonic == "sub" || Mnemonic == "and" ||
6653         Mnemonic == "eor" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
6654         Mnemonic == "asr" || Mnemonic == "adc" || Mnemonic == "sbc" ||
6655         Mnemonic == "ror" || Mnemonic == "orr" || Mnemonic == "bic"))
6656     return;
6657 
6658   // If first 2 operands of a 3 operand instruction are the same
6659   // then transform to 2 operand version of the same instruction
6660   // e.g. 'adds r0, r0, #1' transforms to 'adds r0, #1'
6661   bool Transform = Op3Reg == Op4Reg;
6662 
6663   // For communtative operations, we might be able to transform if we swap
6664   // Op4 and Op5.  The 'ADD Rdm, SP, Rdm' form is already handled specially
6665   // as tADDrsp.
6666   const ARMOperand *LastOp = &Op5;
6667   bool Swap = false;
6668   if (!Transform && Op5.isReg() && Op3Reg == Op5.getReg() &&
6669       ((Mnemonic == "add" && Op4Reg != ARM::SP) ||
6670        Mnemonic == "and" || Mnemonic == "eor" ||
6671        Mnemonic == "adc" || Mnemonic == "orr")) {
6672     Swap = true;
6673     LastOp = &Op4;
6674     Transform = true;
6675   }
6676 
6677   // If both registers are the same then remove one of them from
6678   // the operand list, with certain exceptions.
6679   if (Transform) {
6680     // Don't transform 'adds Rd, Rd, Rm' or 'sub{s} Rd, Rd, Rm' because the
6681     // 2 operand forms don't exist.
6682     if (((Mnemonic == "add" && CarrySetting) || Mnemonic == "sub") &&
6683         LastOp->isReg())
6684       Transform = false;
6685 
6686     // Don't transform 'add/sub{s} Rd, Rd, #imm' if the immediate fits into
6687     // 3-bits because the ARMARM says not to.
6688     if ((Mnemonic == "add" || Mnemonic == "sub") && LastOp->isImm0_7())
6689       Transform = false;
6690   }
6691 
6692   if (Transform) {
6693     if (Swap)
6694       std::swap(Op4, Op5);
6695     Operands.erase(Operands.begin() + 3);
6696   }
6697 }
6698 
6699 bool ARMAsmParser::shouldOmitCCOutOperand(StringRef Mnemonic,
6700                                           OperandVector &Operands) {
6701   // FIXME: This is all horribly hacky. We really need a better way to deal
6702   // with optional operands like this in the matcher table.
6703 
6704   // The 'mov' mnemonic is special. One variant has a cc_out operand, while
6705   // another does not. Specifically, the MOVW instruction does not. So we
6706   // special case it here and remove the defaulted (non-setting) cc_out
6707   // operand if that's the instruction we're trying to match.
6708   //
6709   // We do this as post-processing of the explicit operands rather than just
6710   // conditionally adding the cc_out in the first place because we need
6711   // to check the type of the parsed immediate operand.
6712   if (Mnemonic == "mov" && Operands.size() > 4 && !isThumb() &&
6713       !static_cast<ARMOperand &>(*Operands[4]).isModImm() &&
6714       static_cast<ARMOperand &>(*Operands[4]).isImm0_65535Expr() &&
6715       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0)
6716     return true;
6717 
6718   // Register-register 'add' for thumb does not have a cc_out operand
6719   // when there are only two register operands.
6720   if (isThumb() && Mnemonic == "add" && Operands.size() == 5 &&
6721       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6722       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
6723       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0)
6724     return true;
6725   // Register-register 'add' for thumb does not have a cc_out operand
6726   // when it's an ADD Rdm, SP, {Rdm|#imm0_255} instruction. We do
6727   // have to check the immediate range here since Thumb2 has a variant
6728   // that can handle a different range and has a cc_out operand.
6729   if (((isThumb() && Mnemonic == "add") ||
6730        (isThumbTwo() && Mnemonic == "sub")) &&
6731       Operands.size() == 6 && static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6732       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
6733       static_cast<ARMOperand &>(*Operands[4]).getReg() == ARM::SP &&
6734       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
6735       ((Mnemonic == "add" && static_cast<ARMOperand &>(*Operands[5]).isReg()) ||
6736        static_cast<ARMOperand &>(*Operands[5]).isImm0_1020s4()))
6737     return true;
6738   // For Thumb2, add/sub immediate does not have a cc_out operand for the
6739   // imm0_4095 variant. That's the least-preferred variant when
6740   // selecting via the generic "add" mnemonic, so to know that we
6741   // should remove the cc_out operand, we have to explicitly check that
6742   // it's not one of the other variants. Ugh.
6743   if (isThumbTwo() && (Mnemonic == "add" || Mnemonic == "sub") &&
6744       Operands.size() == 6 && static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6745       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
6746       static_cast<ARMOperand &>(*Operands[5]).isImm()) {
6747     // Nest conditions rather than one big 'if' statement for readability.
6748     //
6749     // If both registers are low, we're in an IT block, and the immediate is
6750     // in range, we should use encoding T1 instead, which has a cc_out.
6751     if (inITBlock() &&
6752         isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) &&
6753         isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) &&
6754         static_cast<ARMOperand &>(*Operands[5]).isImm0_7())
6755       return false;
6756     // Check against T3. If the second register is the PC, this is an
6757     // alternate form of ADR, which uses encoding T4, so check for that too.
6758     if (static_cast<ARMOperand &>(*Operands[4]).getReg() != ARM::PC &&
6759         (static_cast<ARMOperand &>(*Operands[5]).isT2SOImm() ||
6760          static_cast<ARMOperand &>(*Operands[5]).isT2SOImmNeg()))
6761       return false;
6762 
6763     // Otherwise, we use encoding T4, which does not have a cc_out
6764     // operand.
6765     return true;
6766   }
6767 
6768   // The thumb2 multiply instruction doesn't have a CCOut register, so
6769   // if we have a "mul" mnemonic in Thumb mode, check if we'll be able to
6770   // use the 16-bit encoding or not.
6771   if (isThumbTwo() && Mnemonic == "mul" && Operands.size() == 6 &&
6772       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
6773       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6774       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
6775       static_cast<ARMOperand &>(*Operands[5]).isReg() &&
6776       // If the registers aren't low regs, the destination reg isn't the
6777       // same as one of the source regs, or the cc_out operand is zero
6778       // outside of an IT block, we have to use the 32-bit encoding, so
6779       // remove the cc_out operand.
6780       (!isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) ||
6781        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) ||
6782        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[5]).getReg()) ||
6783        !inITBlock() || (static_cast<ARMOperand &>(*Operands[3]).getReg() !=
6784                             static_cast<ARMOperand &>(*Operands[5]).getReg() &&
6785                         static_cast<ARMOperand &>(*Operands[3]).getReg() !=
6786                             static_cast<ARMOperand &>(*Operands[4]).getReg())))
6787     return true;
6788 
6789   // Also check the 'mul' syntax variant that doesn't specify an explicit
6790   // destination register.
6791   if (isThumbTwo() && Mnemonic == "mul" && Operands.size() == 5 &&
6792       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
6793       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6794       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
6795       // If the registers aren't low regs  or the cc_out operand is zero
6796       // outside of an IT block, we have to use the 32-bit encoding, so
6797       // remove the cc_out operand.
6798       (!isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) ||
6799        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) ||
6800        !inITBlock()))
6801     return true;
6802 
6803   // Register-register 'add/sub' for thumb does not have a cc_out operand
6804   // when it's an ADD/SUB SP, #imm. Be lenient on count since there's also
6805   // the "add/sub SP, SP, #imm" version. If the follow-up operands aren't
6806   // right, this will result in better diagnostics (which operand is off)
6807   // anyway.
6808   if (isThumb() && (Mnemonic == "add" || Mnemonic == "sub") &&
6809       (Operands.size() == 5 || Operands.size() == 6) &&
6810       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6811       static_cast<ARMOperand &>(*Operands[3]).getReg() == ARM::SP &&
6812       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
6813       (static_cast<ARMOperand &>(*Operands[4]).isImm() ||
6814        (Operands.size() == 6 &&
6815         static_cast<ARMOperand &>(*Operands[5]).isImm()))) {
6816     // Thumb2 (add|sub){s}{p}.w GPRnopc, sp, #{T2SOImm} has cc_out
6817     return (!(isThumbTwo() &&
6818               (static_cast<ARMOperand &>(*Operands[4]).isT2SOImm() ||
6819                static_cast<ARMOperand &>(*Operands[4]).isT2SOImmNeg())));
6820   }
6821   // Fixme: Should join all the thumb+thumb2 (add|sub) in a single if case
6822   // Thumb2 ADD r0, #4095 -> ADDW r0, r0, #4095 (T4)
6823   // Thumb2 SUB r0, #4095 -> SUBW r0, r0, #4095
6824   if (isThumbTwo() && (Mnemonic == "add" || Mnemonic == "sub") &&
6825       (Operands.size() == 5) &&
6826       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6827       static_cast<ARMOperand &>(*Operands[3]).getReg() != ARM::SP &&
6828       static_cast<ARMOperand &>(*Operands[3]).getReg() != ARM::PC &&
6829       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
6830       static_cast<ARMOperand &>(*Operands[4]).isImm()) {
6831     const ARMOperand &IMM = static_cast<ARMOperand &>(*Operands[4]);
6832     if (IMM.isT2SOImm() || IMM.isT2SOImmNeg())
6833       return false; // add.w / sub.w
6834     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(IMM.getImm())) {
6835       const int64_t Value = CE->getValue();
6836       // Thumb1 imm8 sub / add
6837       if ((Value < ((1 << 7) - 1) << 2) && inITBlock() && (!(Value & 3)) &&
6838           isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()))
6839         return false;
6840       return true; // Thumb2 T4 addw / subw
6841     }
6842   }
6843   return false;
6844 }
6845 
6846 bool ARMAsmParser::shouldOmitPredicateOperand(StringRef Mnemonic,
6847                                               OperandVector &Operands) {
6848   // VRINT{Z, X} have a predicate operand in VFP, but not in NEON
6849   unsigned RegIdx = 3;
6850   if ((((Mnemonic == "vrintz" || Mnemonic == "vrintx") && !hasMVE()) ||
6851       Mnemonic == "vrintr") &&
6852       (static_cast<ARMOperand &>(*Operands[2]).getToken() == ".f32" ||
6853        static_cast<ARMOperand &>(*Operands[2]).getToken() == ".f16")) {
6854     if (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
6855         (static_cast<ARMOperand &>(*Operands[3]).getToken() == ".f32" ||
6856          static_cast<ARMOperand &>(*Operands[3]).getToken() == ".f16"))
6857       RegIdx = 4;
6858 
6859     if (static_cast<ARMOperand &>(*Operands[RegIdx]).isReg() &&
6860         (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(
6861              static_cast<ARMOperand &>(*Operands[RegIdx]).getReg()) ||
6862          ARMMCRegisterClasses[ARM::QPRRegClassID].contains(
6863              static_cast<ARMOperand &>(*Operands[RegIdx]).getReg())))
6864       return true;
6865   }
6866   return false;
6867 }
6868 
6869 bool ARMAsmParser::shouldOmitVectorPredicateOperand(StringRef Mnemonic,
6870                                                     OperandVector &Operands) {
6871   if (!hasMVE() || Operands.size() < 3)
6872     return true;
6873 
6874   if (Mnemonic.startswith("vld2") || Mnemonic.startswith("vld4") ||
6875       Mnemonic.startswith("vst2") || Mnemonic.startswith("vst4"))
6876     return true;
6877 
6878   if (Mnemonic.startswith("vctp") || Mnemonic.startswith("vpnot"))
6879     return false;
6880 
6881   if (Mnemonic.startswith("vmov") &&
6882       !(Mnemonic.startswith("vmovl") || Mnemonic.startswith("vmovn") ||
6883         Mnemonic.startswith("vmovx"))) {
6884     for (auto &Operand : Operands) {
6885       if (static_cast<ARMOperand &>(*Operand).isVectorIndex() ||
6886           ((*Operand).isReg() &&
6887            (ARMMCRegisterClasses[ARM::SPRRegClassID].contains(
6888              (*Operand).getReg()) ||
6889             ARMMCRegisterClasses[ARM::DPRRegClassID].contains(
6890               (*Operand).getReg())))) {
6891         return true;
6892       }
6893     }
6894     return false;
6895   } else {
6896     for (auto &Operand : Operands) {
6897       // We check the larger class QPR instead of just the legal class
6898       // MQPR, to more accurately report errors when using Q registers
6899       // outside of the allowed range.
6900       if (static_cast<ARMOperand &>(*Operand).isVectorIndex() ||
6901           (Operand->isReg() &&
6902            (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(
6903              Operand->getReg()))))
6904         return false;
6905     }
6906     return true;
6907   }
6908 }
6909 
6910 static bool isDataTypeToken(StringRef Tok) {
6911   return Tok == ".8" || Tok == ".16" || Tok == ".32" || Tok == ".64" ||
6912     Tok == ".i8" || Tok == ".i16" || Tok == ".i32" || Tok == ".i64" ||
6913     Tok == ".u8" || Tok == ".u16" || Tok == ".u32" || Tok == ".u64" ||
6914     Tok == ".s8" || Tok == ".s16" || Tok == ".s32" || Tok == ".s64" ||
6915     Tok == ".p8" || Tok == ".p16" || Tok == ".f32" || Tok == ".f64" ||
6916     Tok == ".f" || Tok == ".d";
6917 }
6918 
6919 // FIXME: This bit should probably be handled via an explicit match class
6920 // in the .td files that matches the suffix instead of having it be
6921 // a literal string token the way it is now.
6922 static bool doesIgnoreDataTypeSuffix(StringRef Mnemonic, StringRef DT) {
6923   return Mnemonic.startswith("vldm") || Mnemonic.startswith("vstm");
6924 }
6925 
6926 static void applyMnemonicAliases(StringRef &Mnemonic,
6927                                  const FeatureBitset &Features,
6928                                  unsigned VariantID);
6929 
6930 // The GNU assembler has aliases of ldrd and strd with the second register
6931 // omitted. We don't have a way to do that in tablegen, so fix it up here.
6932 //
6933 // We have to be careful to not emit an invalid Rt2 here, because the rest of
6934 // the assembly parser could then generate confusing diagnostics refering to
6935 // it. If we do find anything that prevents us from doing the transformation we
6936 // bail out, and let the assembly parser report an error on the instruction as
6937 // it is written.
6938 void ARMAsmParser::fixupGNULDRDAlias(StringRef Mnemonic,
6939                                      OperandVector &Operands) {
6940   if (Mnemonic != "ldrd" && Mnemonic != "strd")
6941     return;
6942   if (Operands.size() < 4)
6943     return;
6944 
6945   ARMOperand &Op2 = static_cast<ARMOperand &>(*Operands[2]);
6946   ARMOperand &Op3 = static_cast<ARMOperand &>(*Operands[3]);
6947 
6948   if (!Op2.isReg())
6949     return;
6950   if (!Op3.isGPRMem())
6951     return;
6952 
6953   const MCRegisterClass &GPR = MRI->getRegClass(ARM::GPRRegClassID);
6954   if (!GPR.contains(Op2.getReg()))
6955     return;
6956 
6957   unsigned RtEncoding = MRI->getEncodingValue(Op2.getReg());
6958   if (!isThumb() && (RtEncoding & 1)) {
6959     // In ARM mode, the registers must be from an aligned pair, this
6960     // restriction does not apply in Thumb mode.
6961     return;
6962   }
6963   if (Op2.getReg() == ARM::PC)
6964     return;
6965   unsigned PairedReg = GPR.getRegister(RtEncoding + 1);
6966   if (!PairedReg || PairedReg == ARM::PC ||
6967       (PairedReg == ARM::SP && !hasV8Ops()))
6968     return;
6969 
6970   Operands.insert(
6971       Operands.begin() + 3,
6972       ARMOperand::CreateReg(PairedReg, Op2.getStartLoc(), Op2.getEndLoc()));
6973 }
6974 
6975 // Dual-register instruction have the following syntax:
6976 // <mnemonic> <predicate>? <coproc>, <Rdest>, <Rdest+1>, <Rsrc>, ..., #imm
6977 // This function tries to remove <Rdest+1> and replace <Rdest> with a pair
6978 // operand. If the conversion fails an error is diagnosed, and the function
6979 // returns true.
6980 bool ARMAsmParser::CDEConvertDualRegOperand(StringRef Mnemonic,
6981                                             OperandVector &Operands) {
6982   assert(MS.isCDEDualRegInstr(Mnemonic));
6983   bool isPredicable =
6984       Mnemonic == "cx1da" || Mnemonic == "cx2da" || Mnemonic == "cx3da";
6985   size_t NumPredOps = isPredicable ? 1 : 0;
6986 
6987   if (Operands.size() <= 3 + NumPredOps)
6988     return false;
6989 
6990   StringRef Op2Diag(
6991       "operand must be an even-numbered register in the range [r0, r10]");
6992 
6993   const MCParsedAsmOperand &Op2 = *Operands[2 + NumPredOps];
6994   if (!Op2.isReg())
6995     return Error(Op2.getStartLoc(), Op2Diag);
6996 
6997   unsigned RNext;
6998   unsigned RPair;
6999   switch (Op2.getReg()) {
7000   default:
7001     return Error(Op2.getStartLoc(), Op2Diag);
7002   case ARM::R0:
7003     RNext = ARM::R1;
7004     RPair = ARM::R0_R1;
7005     break;
7006   case ARM::R2:
7007     RNext = ARM::R3;
7008     RPair = ARM::R2_R3;
7009     break;
7010   case ARM::R4:
7011     RNext = ARM::R5;
7012     RPair = ARM::R4_R5;
7013     break;
7014   case ARM::R6:
7015     RNext = ARM::R7;
7016     RPair = ARM::R6_R7;
7017     break;
7018   case ARM::R8:
7019     RNext = ARM::R9;
7020     RPair = ARM::R8_R9;
7021     break;
7022   case ARM::R10:
7023     RNext = ARM::R11;
7024     RPair = ARM::R10_R11;
7025     break;
7026   }
7027 
7028   const MCParsedAsmOperand &Op3 = *Operands[3 + NumPredOps];
7029   if (!Op3.isReg() || Op3.getReg() != RNext)
7030     return Error(Op3.getStartLoc(), "operand must be a consecutive register");
7031 
7032   Operands.erase(Operands.begin() + 3 + NumPredOps);
7033   Operands[2 + NumPredOps] =
7034       ARMOperand::CreateReg(RPair, Op2.getStartLoc(), Op2.getEndLoc());
7035   return false;
7036 }
7037 
7038 /// Parse an arm instruction mnemonic followed by its operands.
7039 bool ARMAsmParser::ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
7040                                     SMLoc NameLoc, OperandVector &Operands) {
7041   MCAsmParser &Parser = getParser();
7042 
7043   // Apply mnemonic aliases before doing anything else, as the destination
7044   // mnemonic may include suffices and we want to handle them normally.
7045   // The generic tblgen'erated code does this later, at the start of
7046   // MatchInstructionImpl(), but that's too late for aliases that include
7047   // any sort of suffix.
7048   const FeatureBitset &AvailableFeatures = getAvailableFeatures();
7049   unsigned AssemblerDialect = getParser().getAssemblerDialect();
7050   applyMnemonicAliases(Name, AvailableFeatures, AssemblerDialect);
7051 
7052   // First check for the ARM-specific .req directive.
7053   if (Parser.getTok().is(AsmToken::Identifier) &&
7054       Parser.getTok().getIdentifier().lower() == ".req") {
7055     parseDirectiveReq(Name, NameLoc);
7056     // We always return 'error' for this, as we're done with this
7057     // statement and don't need to match the 'instruction."
7058     return true;
7059   }
7060 
7061   // Create the leading tokens for the mnemonic, split by '.' characters.
7062   size_t Start = 0, Next = Name.find('.');
7063   StringRef Mnemonic = Name.slice(Start, Next);
7064   StringRef ExtraToken = Name.slice(Next, Name.find(' ', Next + 1));
7065 
7066   // Split out the predication code and carry setting flag from the mnemonic.
7067   unsigned PredicationCode;
7068   unsigned VPTPredicationCode;
7069   unsigned ProcessorIMod;
7070   bool CarrySetting;
7071   StringRef ITMask;
7072   Mnemonic = splitMnemonic(Mnemonic, ExtraToken, PredicationCode, VPTPredicationCode,
7073                            CarrySetting, ProcessorIMod, ITMask);
7074 
7075   // In Thumb1, only the branch (B) instruction can be predicated.
7076   if (isThumbOne() && PredicationCode != ARMCC::AL && Mnemonic != "b") {
7077     return Error(NameLoc, "conditional execution not supported in Thumb1");
7078   }
7079 
7080   Operands.push_back(ARMOperand::CreateToken(Mnemonic, NameLoc));
7081 
7082   // Handle the mask for IT and VPT instructions. In ARMOperand and
7083   // MCOperand, this is stored in a format independent of the
7084   // condition code: the lowest set bit indicates the end of the
7085   // encoding, and above that, a 1 bit indicates 'else', and an 0
7086   // indicates 'then'. E.g.
7087   //    IT    -> 1000
7088   //    ITx   -> x100    (ITT -> 0100, ITE -> 1100)
7089   //    ITxy  -> xy10    (e.g. ITET -> 1010)
7090   //    ITxyz -> xyz1    (e.g. ITEET -> 1101)
7091   // Note: See the ARM::PredBlockMask enum in
7092   //   /lib/Target/ARM/Utils/ARMBaseInfo.h
7093   if (Mnemonic == "it" || Mnemonic.startswith("vpt") ||
7094       Mnemonic.startswith("vpst")) {
7095     SMLoc Loc = Mnemonic == "it"  ? SMLoc::getFromPointer(NameLoc.getPointer() + 2) :
7096                 Mnemonic == "vpt" ? SMLoc::getFromPointer(NameLoc.getPointer() + 3) :
7097                                     SMLoc::getFromPointer(NameLoc.getPointer() + 4);
7098     if (ITMask.size() > 3) {
7099       if (Mnemonic == "it")
7100         return Error(Loc, "too many conditions on IT instruction");
7101       return Error(Loc, "too many conditions on VPT instruction");
7102     }
7103     unsigned Mask = 8;
7104     for (unsigned i = ITMask.size(); i != 0; --i) {
7105       char pos = ITMask[i - 1];
7106       if (pos != 't' && pos != 'e') {
7107         return Error(Loc, "illegal IT block condition mask '" + ITMask + "'");
7108       }
7109       Mask >>= 1;
7110       if (ITMask[i - 1] == 'e')
7111         Mask |= 8;
7112     }
7113     Operands.push_back(ARMOperand::CreateITMask(Mask, Loc));
7114   }
7115 
7116   // FIXME: This is all a pretty gross hack. We should automatically handle
7117   // optional operands like this via tblgen.
7118 
7119   // Next, add the CCOut and ConditionCode operands, if needed.
7120   //
7121   // For mnemonics which can ever incorporate a carry setting bit or predication
7122   // code, our matching model involves us always generating CCOut and
7123   // ConditionCode operands to match the mnemonic "as written" and then we let
7124   // the matcher deal with finding the right instruction or generating an
7125   // appropriate error.
7126   bool CanAcceptCarrySet, CanAcceptPredicationCode, CanAcceptVPTPredicationCode;
7127   getMnemonicAcceptInfo(Mnemonic, ExtraToken, Name, CanAcceptCarrySet,
7128                         CanAcceptPredicationCode, CanAcceptVPTPredicationCode);
7129 
7130   // If we had a carry-set on an instruction that can't do that, issue an
7131   // error.
7132   if (!CanAcceptCarrySet && CarrySetting) {
7133     return Error(NameLoc, "instruction '" + Mnemonic +
7134                  "' can not set flags, but 's' suffix specified");
7135   }
7136   // If we had a predication code on an instruction that can't do that, issue an
7137   // error.
7138   if (!CanAcceptPredicationCode && PredicationCode != ARMCC::AL) {
7139     return Error(NameLoc, "instruction '" + Mnemonic +
7140                  "' is not predicable, but condition code specified");
7141   }
7142 
7143   // If we had a VPT predication code on an instruction that can't do that, issue an
7144   // error.
7145   if (!CanAcceptVPTPredicationCode && VPTPredicationCode != ARMVCC::None) {
7146     return Error(NameLoc, "instruction '" + Mnemonic +
7147                  "' is not VPT predicable, but VPT code T/E is specified");
7148   }
7149 
7150   // Add the carry setting operand, if necessary.
7151   if (CanAcceptCarrySet) {
7152     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size());
7153     Operands.push_back(ARMOperand::CreateCCOut(CarrySetting ? ARM::CPSR : 0,
7154                                                Loc));
7155   }
7156 
7157   // Add the predication code operand, if necessary.
7158   if (CanAcceptPredicationCode) {
7159     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size() +
7160                                       CarrySetting);
7161     Operands.push_back(ARMOperand::CreateCondCode(
7162                        ARMCC::CondCodes(PredicationCode), Loc));
7163   }
7164 
7165   // Add the VPT predication code operand, if necessary.
7166   // FIXME: We don't add them for the instructions filtered below as these can
7167   // have custom operands which need special parsing.  This parsing requires
7168   // the operand to be in the same place in the OperandVector as their
7169   // definition in tblgen.  Since these instructions may also have the
7170   // scalar predication operand we do not add the vector one and leave until
7171   // now to fix it up.
7172   if (CanAcceptVPTPredicationCode && Mnemonic != "vmov" &&
7173       !Mnemonic.startswith("vcmp") &&
7174       !(Mnemonic.startswith("vcvt") && Mnemonic != "vcvta" &&
7175         Mnemonic != "vcvtn" && Mnemonic != "vcvtp" && Mnemonic != "vcvtm")) {
7176     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size() +
7177                                       CarrySetting);
7178     Operands.push_back(ARMOperand::CreateVPTPred(
7179                          ARMVCC::VPTCodes(VPTPredicationCode), Loc));
7180   }
7181 
7182   // Add the processor imod operand, if necessary.
7183   if (ProcessorIMod) {
7184     Operands.push_back(ARMOperand::CreateImm(
7185           MCConstantExpr::create(ProcessorIMod, getContext()),
7186                                  NameLoc, NameLoc));
7187   } else if (Mnemonic == "cps" && isMClass()) {
7188     return Error(NameLoc, "instruction 'cps' requires effect for M-class");
7189   }
7190 
7191   // Add the remaining tokens in the mnemonic.
7192   while (Next != StringRef::npos) {
7193     Start = Next;
7194     Next = Name.find('.', Start + 1);
7195     ExtraToken = Name.slice(Start, Next);
7196 
7197     // Some NEON instructions have an optional datatype suffix that is
7198     // completely ignored. Check for that.
7199     if (isDataTypeToken(ExtraToken) &&
7200         doesIgnoreDataTypeSuffix(Mnemonic, ExtraToken))
7201       continue;
7202 
7203     // For for ARM mode generate an error if the .n qualifier is used.
7204     if (ExtraToken == ".n" && !isThumb()) {
7205       SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Start);
7206       return Error(Loc, "instruction with .n (narrow) qualifier not allowed in "
7207                    "arm mode");
7208     }
7209 
7210     // The .n qualifier is always discarded as that is what the tables
7211     // and matcher expect.  In ARM mode the .w qualifier has no effect,
7212     // so discard it to avoid errors that can be caused by the matcher.
7213     if (ExtraToken != ".n" && (isThumb() || ExtraToken != ".w")) {
7214       SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Start);
7215       Operands.push_back(ARMOperand::CreateToken(ExtraToken, Loc));
7216     }
7217   }
7218 
7219   // Read the remaining operands.
7220   if (getLexer().isNot(AsmToken::EndOfStatement)) {
7221     // Read the first operand.
7222     if (parseOperand(Operands, Mnemonic)) {
7223       return true;
7224     }
7225 
7226     while (parseOptionalToken(AsmToken::Comma)) {
7227       // Parse and remember the operand.
7228       if (parseOperand(Operands, Mnemonic)) {
7229         return true;
7230       }
7231     }
7232   }
7233 
7234   if (parseToken(AsmToken::EndOfStatement, "unexpected token in argument list"))
7235     return true;
7236 
7237   tryConvertingToTwoOperandForm(Mnemonic, CarrySetting, Operands);
7238 
7239   if (hasCDE() && MS.isCDEInstr(Mnemonic)) {
7240     // Dual-register instructions use even-odd register pairs as their
7241     // destination operand, in assembly such pair is spelled as two
7242     // consecutive registers, without any special syntax. ConvertDualRegOperand
7243     // tries to convert such operand into register pair, e.g. r2, r3 -> r2_r3.
7244     // It returns true, if an error message has been emitted. If the function
7245     // returns false, the function either succeeded or an error (e.g. missing
7246     // operand) will be diagnosed elsewhere.
7247     if (MS.isCDEDualRegInstr(Mnemonic)) {
7248       bool GotError = CDEConvertDualRegOperand(Mnemonic, Operands);
7249       if (GotError)
7250         return GotError;
7251     }
7252   }
7253 
7254   // Some instructions, mostly Thumb, have forms for the same mnemonic that
7255   // do and don't have a cc_out optional-def operand. With some spot-checks
7256   // of the operand list, we can figure out which variant we're trying to
7257   // parse and adjust accordingly before actually matching. We shouldn't ever
7258   // try to remove a cc_out operand that was explicitly set on the
7259   // mnemonic, of course (CarrySetting == true). Reason number #317 the
7260   // table driven matcher doesn't fit well with the ARM instruction set.
7261   if (!CarrySetting && shouldOmitCCOutOperand(Mnemonic, Operands))
7262     Operands.erase(Operands.begin() + 1);
7263 
7264   // Some instructions have the same mnemonic, but don't always
7265   // have a predicate. Distinguish them here and delete the
7266   // appropriate predicate if needed.  This could be either the scalar
7267   // predication code or the vector predication code.
7268   if (PredicationCode == ARMCC::AL &&
7269       shouldOmitPredicateOperand(Mnemonic, Operands))
7270     Operands.erase(Operands.begin() + 1);
7271 
7272 
7273   if (hasMVE()) {
7274     if (!shouldOmitVectorPredicateOperand(Mnemonic, Operands) &&
7275         Mnemonic == "vmov" && PredicationCode == ARMCC::LT) {
7276       // Very nasty hack to deal with the vector predicated variant of vmovlt
7277       // the scalar predicated vmov with condition 'lt'.  We can not tell them
7278       // apart until we have parsed their operands.
7279       Operands.erase(Operands.begin() + 1);
7280       Operands.erase(Operands.begin());
7281       SMLoc MLoc = SMLoc::getFromPointer(NameLoc.getPointer());
7282       SMLoc PLoc = SMLoc::getFromPointer(NameLoc.getPointer() +
7283                                          Mnemonic.size() - 1 + CarrySetting);
7284       Operands.insert(Operands.begin(),
7285                       ARMOperand::CreateVPTPred(ARMVCC::None, PLoc));
7286       Operands.insert(Operands.begin(),
7287                       ARMOperand::CreateToken(StringRef("vmovlt"), MLoc));
7288     } else if (Mnemonic == "vcvt" && PredicationCode == ARMCC::NE &&
7289                !shouldOmitVectorPredicateOperand(Mnemonic, Operands)) {
7290       // Another nasty hack to deal with the ambiguity between vcvt with scalar
7291       // predication 'ne' and vcvtn with vector predication 'e'.  As above we
7292       // can only distinguish between the two after we have parsed their
7293       // operands.
7294       Operands.erase(Operands.begin() + 1);
7295       Operands.erase(Operands.begin());
7296       SMLoc MLoc = SMLoc::getFromPointer(NameLoc.getPointer());
7297       SMLoc PLoc = SMLoc::getFromPointer(NameLoc.getPointer() +
7298                                          Mnemonic.size() - 1 + CarrySetting);
7299       Operands.insert(Operands.begin(),
7300                       ARMOperand::CreateVPTPred(ARMVCC::Else, PLoc));
7301       Operands.insert(Operands.begin(),
7302                       ARMOperand::CreateToken(StringRef("vcvtn"), MLoc));
7303     } else if (Mnemonic == "vmul" && PredicationCode == ARMCC::LT &&
7304                !shouldOmitVectorPredicateOperand(Mnemonic, Operands)) {
7305       // Another hack, this time to distinguish between scalar predicated vmul
7306       // with 'lt' predication code and the vector instruction vmullt with
7307       // vector predication code "none"
7308       Operands.erase(Operands.begin() + 1);
7309       Operands.erase(Operands.begin());
7310       SMLoc MLoc = SMLoc::getFromPointer(NameLoc.getPointer());
7311       Operands.insert(Operands.begin(),
7312                       ARMOperand::CreateToken(StringRef("vmullt"), MLoc));
7313     }
7314     // For vmov and vcmp, as mentioned earlier, we did not add the vector
7315     // predication code, since these may contain operands that require
7316     // special parsing.  So now we have to see if they require vector
7317     // predication and replace the scalar one with the vector predication
7318     // operand if that is the case.
7319     else if (Mnemonic == "vmov" || Mnemonic.startswith("vcmp") ||
7320              (Mnemonic.startswith("vcvt") && !Mnemonic.startswith("vcvta") &&
7321               !Mnemonic.startswith("vcvtn") && !Mnemonic.startswith("vcvtp") &&
7322               !Mnemonic.startswith("vcvtm"))) {
7323       if (!shouldOmitVectorPredicateOperand(Mnemonic, Operands)) {
7324         // We could not split the vector predicate off vcvt because it might
7325         // have been the scalar vcvtt instruction.  Now we know its a vector
7326         // instruction, we still need to check whether its the vector
7327         // predicated vcvt with 'Then' predication or the vector vcvtt.  We can
7328         // distinguish the two based on the suffixes, if it is any of
7329         // ".f16.f32", ".f32.f16", ".f16.f64" or ".f64.f16" then it is the vcvtt.
7330         if (Mnemonic.startswith("vcvtt") && Operands.size() >= 4) {
7331           auto Sz1 = static_cast<ARMOperand &>(*Operands[2]);
7332           auto Sz2 = static_cast<ARMOperand &>(*Operands[3]);
7333           if (!(Sz1.isToken() && Sz1.getToken().startswith(".f") &&
7334               Sz2.isToken() && Sz2.getToken().startswith(".f"))) {
7335             Operands.erase(Operands.begin());
7336             SMLoc MLoc = SMLoc::getFromPointer(NameLoc.getPointer());
7337             VPTPredicationCode = ARMVCC::Then;
7338 
7339             Mnemonic = Mnemonic.substr(0, 4);
7340             Operands.insert(Operands.begin(),
7341                             ARMOperand::CreateToken(Mnemonic, MLoc));
7342           }
7343         }
7344         Operands.erase(Operands.begin() + 1);
7345         SMLoc PLoc = SMLoc::getFromPointer(NameLoc.getPointer() +
7346                                           Mnemonic.size() + CarrySetting);
7347         Operands.insert(Operands.begin() + 1,
7348                         ARMOperand::CreateVPTPred(
7349                             ARMVCC::VPTCodes(VPTPredicationCode), PLoc));
7350       }
7351     } else if (CanAcceptVPTPredicationCode) {
7352       // For all other instructions, make sure only one of the two
7353       // predication operands is left behind, depending on whether we should
7354       // use the vector predication.
7355       if (shouldOmitVectorPredicateOperand(Mnemonic, Operands)) {
7356         if (CanAcceptPredicationCode)
7357           Operands.erase(Operands.begin() + 2);
7358         else
7359           Operands.erase(Operands.begin() + 1);
7360       } else if (CanAcceptPredicationCode && PredicationCode == ARMCC::AL) {
7361         Operands.erase(Operands.begin() + 1);
7362       }
7363     }
7364   }
7365 
7366   if (VPTPredicationCode != ARMVCC::None) {
7367     bool usedVPTPredicationCode = false;
7368     for (unsigned I = 1; I < Operands.size(); ++I)
7369       if (static_cast<ARMOperand &>(*Operands[I]).isVPTPred())
7370         usedVPTPredicationCode = true;
7371     if (!usedVPTPredicationCode) {
7372       // If we have a VPT predication code and we haven't just turned it
7373       // into an operand, then it was a mistake for splitMnemonic to
7374       // separate it from the rest of the mnemonic in the first place,
7375       // and this may lead to wrong disassembly (e.g. scalar floating
7376       // point VCMPE is actually a different instruction from VCMP, so
7377       // we mustn't treat them the same). In that situation, glue it
7378       // back on.
7379       Mnemonic = Name.slice(0, Mnemonic.size() + 1);
7380       Operands.erase(Operands.begin());
7381       Operands.insert(Operands.begin(),
7382                       ARMOperand::CreateToken(Mnemonic, NameLoc));
7383     }
7384   }
7385 
7386     // ARM mode 'blx' need special handling, as the register operand version
7387     // is predicable, but the label operand version is not. So, we can't rely
7388     // on the Mnemonic based checking to correctly figure out when to put
7389     // a k_CondCode operand in the list. If we're trying to match the label
7390     // version, remove the k_CondCode operand here.
7391     if (!isThumb() && Mnemonic == "blx" && Operands.size() == 3 &&
7392         static_cast<ARMOperand &>(*Operands[2]).isImm())
7393       Operands.erase(Operands.begin() + 1);
7394 
7395     // Adjust operands of ldrexd/strexd to MCK_GPRPair.
7396     // ldrexd/strexd require even/odd GPR pair. To enforce this constraint,
7397     // a single GPRPair reg operand is used in the .td file to replace the two
7398     // GPRs. However, when parsing from asm, the two GRPs cannot be
7399     // automatically
7400     // expressed as a GPRPair, so we have to manually merge them.
7401     // FIXME: We would really like to be able to tablegen'erate this.
7402     if (!isThumb() && Operands.size() > 4 &&
7403         (Mnemonic == "ldrexd" || Mnemonic == "strexd" || Mnemonic == "ldaexd" ||
7404          Mnemonic == "stlexd")) {
7405       bool isLoad = (Mnemonic == "ldrexd" || Mnemonic == "ldaexd");
7406       unsigned Idx = isLoad ? 2 : 3;
7407       ARMOperand &Op1 = static_cast<ARMOperand &>(*Operands[Idx]);
7408       ARMOperand &Op2 = static_cast<ARMOperand &>(*Operands[Idx + 1]);
7409 
7410       const MCRegisterClass &MRC = MRI->getRegClass(ARM::GPRRegClassID);
7411       // Adjust only if Op1 and Op2 are GPRs.
7412       if (Op1.isReg() && Op2.isReg() && MRC.contains(Op1.getReg()) &&
7413           MRC.contains(Op2.getReg())) {
7414         unsigned Reg1 = Op1.getReg();
7415         unsigned Reg2 = Op2.getReg();
7416         unsigned Rt = MRI->getEncodingValue(Reg1);
7417         unsigned Rt2 = MRI->getEncodingValue(Reg2);
7418 
7419         // Rt2 must be Rt + 1 and Rt must be even.
7420         if (Rt + 1 != Rt2 || (Rt & 1)) {
7421           return Error(Op2.getStartLoc(),
7422                        isLoad ? "destination operands must be sequential"
7423                               : "source operands must be sequential");
7424         }
7425         unsigned NewReg = MRI->getMatchingSuperReg(
7426             Reg1, ARM::gsub_0, &(MRI->getRegClass(ARM::GPRPairRegClassID)));
7427         Operands[Idx] =
7428             ARMOperand::CreateReg(NewReg, Op1.getStartLoc(), Op2.getEndLoc());
7429         Operands.erase(Operands.begin() + Idx + 1);
7430       }
7431   }
7432 
7433   // GNU Assembler extension (compatibility).
7434   fixupGNULDRDAlias(Mnemonic, Operands);
7435 
7436   // FIXME: As said above, this is all a pretty gross hack.  This instruction
7437   // does not fit with other "subs" and tblgen.
7438   // Adjust operands of B9.3.19 SUBS PC, LR, #imm (Thumb2) system instruction
7439   // so the Mnemonic is the original name "subs" and delete the predicate
7440   // operand so it will match the table entry.
7441   if (isThumbTwo() && Mnemonic == "sub" && Operands.size() == 6 &&
7442       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
7443       static_cast<ARMOperand &>(*Operands[3]).getReg() == ARM::PC &&
7444       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
7445       static_cast<ARMOperand &>(*Operands[4]).getReg() == ARM::LR &&
7446       static_cast<ARMOperand &>(*Operands[5]).isImm()) {
7447     Operands.front() = ARMOperand::CreateToken(Name, NameLoc);
7448     Operands.erase(Operands.begin() + 1);
7449   }
7450   return false;
7451 }
7452 
7453 // Validate context-sensitive operand constraints.
7454 
7455 // return 'true' if register list contains non-low GPR registers,
7456 // 'false' otherwise. If Reg is in the register list or is HiReg, set
7457 // 'containsReg' to true.
7458 static bool checkLowRegisterList(const MCInst &Inst, unsigned OpNo,
7459                                  unsigned Reg, unsigned HiReg,
7460                                  bool &containsReg) {
7461   containsReg = false;
7462   for (unsigned i = OpNo; i < Inst.getNumOperands(); ++i) {
7463     unsigned OpReg = Inst.getOperand(i).getReg();
7464     if (OpReg == Reg)
7465       containsReg = true;
7466     // Anything other than a low register isn't legal here.
7467     if (!isARMLowRegister(OpReg) && (!HiReg || OpReg != HiReg))
7468       return true;
7469   }
7470   return false;
7471 }
7472 
7473 // Check if the specified regisgter is in the register list of the inst,
7474 // starting at the indicated operand number.
7475 static bool listContainsReg(const MCInst &Inst, unsigned OpNo, unsigned Reg) {
7476   for (unsigned i = OpNo, e = Inst.getNumOperands(); i < e; ++i) {
7477     unsigned OpReg = Inst.getOperand(i).getReg();
7478     if (OpReg == Reg)
7479       return true;
7480   }
7481   return false;
7482 }
7483 
7484 // Return true if instruction has the interesting property of being
7485 // allowed in IT blocks, but not being predicable.
7486 static bool instIsBreakpoint(const MCInst &Inst) {
7487     return Inst.getOpcode() == ARM::tBKPT ||
7488            Inst.getOpcode() == ARM::BKPT ||
7489            Inst.getOpcode() == ARM::tHLT ||
7490            Inst.getOpcode() == ARM::HLT;
7491 }
7492 
7493 bool ARMAsmParser::validatetLDMRegList(const MCInst &Inst,
7494                                        const OperandVector &Operands,
7495                                        unsigned ListNo, bool IsARPop) {
7496   const ARMOperand &Op = static_cast<const ARMOperand &>(*Operands[ListNo]);
7497   bool HasWritebackToken = Op.isToken() && Op.getToken() == "!";
7498 
7499   bool ListContainsSP = listContainsReg(Inst, ListNo, ARM::SP);
7500   bool ListContainsLR = listContainsReg(Inst, ListNo, ARM::LR);
7501   bool ListContainsPC = listContainsReg(Inst, ListNo, ARM::PC);
7502 
7503   if (!IsARPop && ListContainsSP)
7504     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
7505                  "SP may not be in the register list");
7506   else if (ListContainsPC && ListContainsLR)
7507     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
7508                  "PC and LR may not be in the register list simultaneously");
7509   return false;
7510 }
7511 
7512 bool ARMAsmParser::validatetSTMRegList(const MCInst &Inst,
7513                                        const OperandVector &Operands,
7514                                        unsigned ListNo) {
7515   const ARMOperand &Op = static_cast<const ARMOperand &>(*Operands[ListNo]);
7516   bool HasWritebackToken = Op.isToken() && Op.getToken() == "!";
7517 
7518   bool ListContainsSP = listContainsReg(Inst, ListNo, ARM::SP);
7519   bool ListContainsPC = listContainsReg(Inst, ListNo, ARM::PC);
7520 
7521   if (ListContainsSP && ListContainsPC)
7522     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
7523                  "SP and PC may not be in the register list");
7524   else if (ListContainsSP)
7525     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
7526                  "SP may not be in the register list");
7527   else if (ListContainsPC)
7528     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
7529                  "PC may not be in the register list");
7530   return false;
7531 }
7532 
7533 bool ARMAsmParser::validateLDRDSTRD(MCInst &Inst,
7534                                     const OperandVector &Operands,
7535                                     bool Load, bool ARMMode, bool Writeback) {
7536   unsigned RtIndex = Load || !Writeback ? 0 : 1;
7537   unsigned Rt = MRI->getEncodingValue(Inst.getOperand(RtIndex).getReg());
7538   unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(RtIndex + 1).getReg());
7539 
7540   if (ARMMode) {
7541     // Rt can't be R14.
7542     if (Rt == 14)
7543       return Error(Operands[3]->getStartLoc(),
7544                   "Rt can't be R14");
7545 
7546     // Rt must be even-numbered.
7547     if ((Rt & 1) == 1)
7548       return Error(Operands[3]->getStartLoc(),
7549                    "Rt must be even-numbered");
7550 
7551     // Rt2 must be Rt + 1.
7552     if (Rt2 != Rt + 1) {
7553       if (Load)
7554         return Error(Operands[3]->getStartLoc(),
7555                      "destination operands must be sequential");
7556       else
7557         return Error(Operands[3]->getStartLoc(),
7558                      "source operands must be sequential");
7559     }
7560 
7561     // FIXME: Diagnose m == 15
7562     // FIXME: Diagnose ldrd with m == t || m == t2.
7563   }
7564 
7565   if (!ARMMode && Load) {
7566     if (Rt2 == Rt)
7567       return Error(Operands[3]->getStartLoc(),
7568                    "destination operands can't be identical");
7569   }
7570 
7571   if (Writeback) {
7572     unsigned Rn = MRI->getEncodingValue(Inst.getOperand(3).getReg());
7573 
7574     if (Rn == Rt || Rn == Rt2) {
7575       if (Load)
7576         return Error(Operands[3]->getStartLoc(),
7577                      "base register needs to be different from destination "
7578                      "registers");
7579       else
7580         return Error(Operands[3]->getStartLoc(),
7581                      "source register and base register can't be identical");
7582     }
7583 
7584     // FIXME: Diagnose ldrd/strd with writeback and n == 15.
7585     // (Except the immediate form of ldrd?)
7586   }
7587 
7588   return false;
7589 }
7590 
7591 static int findFirstVectorPredOperandIdx(const MCInstrDesc &MCID) {
7592   for (unsigned i = 0; i < MCID.NumOperands; ++i) {
7593     if (ARM::isVpred(MCID.OpInfo[i].OperandType))
7594       return i;
7595   }
7596   return -1;
7597 }
7598 
7599 static bool isVectorPredicable(const MCInstrDesc &MCID) {
7600   return findFirstVectorPredOperandIdx(MCID) != -1;
7601 }
7602 
7603 // FIXME: We would really like to be able to tablegen'erate this.
7604 bool ARMAsmParser::validateInstruction(MCInst &Inst,
7605                                        const OperandVector &Operands) {
7606   const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
7607   SMLoc Loc = Operands[0]->getStartLoc();
7608 
7609   // Check the IT block state first.
7610   // NOTE: BKPT and HLT instructions have the interesting property of being
7611   // allowed in IT blocks, but not being predicable. They just always execute.
7612   if (inITBlock() && !instIsBreakpoint(Inst)) {
7613     // The instruction must be predicable.
7614     if (!MCID.isPredicable())
7615       return Error(Loc, "instructions in IT block must be predicable");
7616     ARMCC::CondCodes Cond = ARMCC::CondCodes(
7617         Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm());
7618     if (Cond != currentITCond()) {
7619       // Find the condition code Operand to get its SMLoc information.
7620       SMLoc CondLoc;
7621       for (unsigned I = 1; I < Operands.size(); ++I)
7622         if (static_cast<ARMOperand &>(*Operands[I]).isCondCode())
7623           CondLoc = Operands[I]->getStartLoc();
7624       return Error(CondLoc, "incorrect condition in IT block; got '" +
7625                                 StringRef(ARMCondCodeToString(Cond)) +
7626                                 "', but expected '" +
7627                                 ARMCondCodeToString(currentITCond()) + "'");
7628     }
7629   // Check for non-'al' condition codes outside of the IT block.
7630   } else if (isThumbTwo() && MCID.isPredicable() &&
7631              Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm() !=
7632              ARMCC::AL && Inst.getOpcode() != ARM::tBcc &&
7633              Inst.getOpcode() != ARM::t2Bcc &&
7634              Inst.getOpcode() != ARM::t2BFic) {
7635     return Error(Loc, "predicated instructions must be in IT block");
7636   } else if (!isThumb() && !useImplicitITARM() && MCID.isPredicable() &&
7637              Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm() !=
7638                  ARMCC::AL) {
7639     return Warning(Loc, "predicated instructions should be in IT block");
7640   } else if (!MCID.isPredicable()) {
7641     // Check the instruction doesn't have a predicate operand anyway
7642     // that it's not allowed to use. Sometimes this happens in order
7643     // to keep instructions the same shape even though one cannot
7644     // legally be predicated, e.g. vmul.f16 vs vmul.f32.
7645     for (unsigned i = 0, e = MCID.getNumOperands(); i != e; ++i) {
7646       if (MCID.OpInfo[i].isPredicate()) {
7647         if (Inst.getOperand(i).getImm() != ARMCC::AL)
7648           return Error(Loc, "instruction is not predicable");
7649         break;
7650       }
7651     }
7652   }
7653 
7654   // PC-setting instructions in an IT block, but not the last instruction of
7655   // the block, are UNPREDICTABLE.
7656   if (inExplicitITBlock() && !lastInITBlock() && isITBlockTerminator(Inst)) {
7657     return Error(Loc, "instruction must be outside of IT block or the last instruction in an IT block");
7658   }
7659 
7660   if (inVPTBlock() && !instIsBreakpoint(Inst)) {
7661     unsigned Bit = extractITMaskBit(VPTState.Mask, VPTState.CurPosition);
7662     if (!isVectorPredicable(MCID))
7663       return Error(Loc, "instruction in VPT block must be predicable");
7664     unsigned Pred = Inst.getOperand(findFirstVectorPredOperandIdx(MCID)).getImm();
7665     unsigned VPTPred = Bit ? ARMVCC::Else : ARMVCC::Then;
7666     if (Pred != VPTPred) {
7667       SMLoc PredLoc;
7668       for (unsigned I = 1; I < Operands.size(); ++I)
7669         if (static_cast<ARMOperand &>(*Operands[I]).isVPTPred())
7670           PredLoc = Operands[I]->getStartLoc();
7671       return Error(PredLoc, "incorrect predication in VPT block; got '" +
7672                    StringRef(ARMVPTPredToString(ARMVCC::VPTCodes(Pred))) +
7673                    "', but expected '" +
7674                    ARMVPTPredToString(ARMVCC::VPTCodes(VPTPred)) + "'");
7675     }
7676   }
7677   else if (isVectorPredicable(MCID) &&
7678            Inst.getOperand(findFirstVectorPredOperandIdx(MCID)).getImm() !=
7679            ARMVCC::None)
7680     return Error(Loc, "VPT predicated instructions must be in VPT block");
7681 
7682   const unsigned Opcode = Inst.getOpcode();
7683   switch (Opcode) {
7684   case ARM::t2IT: {
7685     // Encoding is unpredictable if it ever results in a notional 'NV'
7686     // predicate. Since we don't parse 'NV' directly this means an 'AL'
7687     // predicate with an "else" mask bit.
7688     unsigned Cond = Inst.getOperand(0).getImm();
7689     unsigned Mask = Inst.getOperand(1).getImm();
7690 
7691     // Conditions only allowing a 't' are those with no set bit except
7692     // the lowest-order one that indicates the end of the sequence. In
7693     // other words, powers of 2.
7694     if (Cond == ARMCC::AL && countPopulation(Mask) != 1)
7695       return Error(Loc, "unpredictable IT predicate sequence");
7696     break;
7697   }
7698   case ARM::LDRD:
7699     if (validateLDRDSTRD(Inst, Operands, /*Load*/true, /*ARMMode*/true,
7700                          /*Writeback*/false))
7701       return true;
7702     break;
7703   case ARM::LDRD_PRE:
7704   case ARM::LDRD_POST:
7705     if (validateLDRDSTRD(Inst, Operands, /*Load*/true, /*ARMMode*/true,
7706                          /*Writeback*/true))
7707       return true;
7708     break;
7709   case ARM::t2LDRDi8:
7710     if (validateLDRDSTRD(Inst, Operands, /*Load*/true, /*ARMMode*/false,
7711                          /*Writeback*/false))
7712       return true;
7713     break;
7714   case ARM::t2LDRD_PRE:
7715   case ARM::t2LDRD_POST:
7716     if (validateLDRDSTRD(Inst, Operands, /*Load*/true, /*ARMMode*/false,
7717                          /*Writeback*/true))
7718       return true;
7719     break;
7720   case ARM::t2BXJ: {
7721     const unsigned RmReg = Inst.getOperand(0).getReg();
7722     // Rm = SP is no longer unpredictable in v8-A
7723     if (RmReg == ARM::SP && !hasV8Ops())
7724       return Error(Operands[2]->getStartLoc(),
7725                    "r13 (SP) is an unpredictable operand to BXJ");
7726     return false;
7727   }
7728   case ARM::STRD:
7729     if (validateLDRDSTRD(Inst, Operands, /*Load*/false, /*ARMMode*/true,
7730                          /*Writeback*/false))
7731       return true;
7732     break;
7733   case ARM::STRD_PRE:
7734   case ARM::STRD_POST:
7735     if (validateLDRDSTRD(Inst, Operands, /*Load*/false, /*ARMMode*/true,
7736                          /*Writeback*/true))
7737       return true;
7738     break;
7739   case ARM::t2STRD_PRE:
7740   case ARM::t2STRD_POST:
7741     if (validateLDRDSTRD(Inst, Operands, /*Load*/false, /*ARMMode*/false,
7742                          /*Writeback*/true))
7743       return true;
7744     break;
7745   case ARM::STR_PRE_IMM:
7746   case ARM::STR_PRE_REG:
7747   case ARM::t2STR_PRE:
7748   case ARM::STR_POST_IMM:
7749   case ARM::STR_POST_REG:
7750   case ARM::t2STR_POST:
7751   case ARM::STRH_PRE:
7752   case ARM::t2STRH_PRE:
7753   case ARM::STRH_POST:
7754   case ARM::t2STRH_POST:
7755   case ARM::STRB_PRE_IMM:
7756   case ARM::STRB_PRE_REG:
7757   case ARM::t2STRB_PRE:
7758   case ARM::STRB_POST_IMM:
7759   case ARM::STRB_POST_REG:
7760   case ARM::t2STRB_POST: {
7761     // Rt must be different from Rn.
7762     const unsigned Rt = MRI->getEncodingValue(Inst.getOperand(1).getReg());
7763     const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(2).getReg());
7764 
7765     if (Rt == Rn)
7766       return Error(Operands[3]->getStartLoc(),
7767                    "source register and base register can't be identical");
7768     return false;
7769   }
7770   case ARM::t2LDR_PRE_imm:
7771   case ARM::t2LDR_POST_imm:
7772   case ARM::t2STR_PRE_imm:
7773   case ARM::t2STR_POST_imm: {
7774     // Rt must be different from Rn.
7775     const unsigned Rt = MRI->getEncodingValue(Inst.getOperand(0).getReg());
7776     const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(1).getReg());
7777 
7778     if (Rt == Rn)
7779       return Error(Operands[3]->getStartLoc(),
7780                    "destination register and base register can't be identical");
7781     if (Inst.getOpcode() == ARM::t2LDR_POST_imm ||
7782         Inst.getOpcode() == ARM::t2STR_POST_imm) {
7783       int Imm = Inst.getOperand(2).getImm();
7784       if (Imm > 255 || Imm < -255)
7785         return Error(Operands[5]->getStartLoc(),
7786                      "operand must be in range [-255, 255]");
7787     }
7788     if (Inst.getOpcode() == ARM::t2STR_PRE_imm ||
7789         Inst.getOpcode() == ARM::t2STR_POST_imm) {
7790       if (Inst.getOperand(0).getReg() == ARM::PC) {
7791         return Error(Operands[3]->getStartLoc(),
7792                      "operand must be a register in range [r0, r14]");
7793       }
7794     }
7795     return false;
7796   }
7797   case ARM::LDR_PRE_IMM:
7798   case ARM::LDR_PRE_REG:
7799   case ARM::t2LDR_PRE:
7800   case ARM::LDR_POST_IMM:
7801   case ARM::LDR_POST_REG:
7802   case ARM::t2LDR_POST:
7803   case ARM::LDRH_PRE:
7804   case ARM::t2LDRH_PRE:
7805   case ARM::LDRH_POST:
7806   case ARM::t2LDRH_POST:
7807   case ARM::LDRSH_PRE:
7808   case ARM::t2LDRSH_PRE:
7809   case ARM::LDRSH_POST:
7810   case ARM::t2LDRSH_POST:
7811   case ARM::LDRB_PRE_IMM:
7812   case ARM::LDRB_PRE_REG:
7813   case ARM::t2LDRB_PRE:
7814   case ARM::LDRB_POST_IMM:
7815   case ARM::LDRB_POST_REG:
7816   case ARM::t2LDRB_POST:
7817   case ARM::LDRSB_PRE:
7818   case ARM::t2LDRSB_PRE:
7819   case ARM::LDRSB_POST:
7820   case ARM::t2LDRSB_POST: {
7821     // Rt must be different from Rn.
7822     const unsigned Rt = MRI->getEncodingValue(Inst.getOperand(0).getReg());
7823     const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(2).getReg());
7824 
7825     if (Rt == Rn)
7826       return Error(Operands[3]->getStartLoc(),
7827                    "destination register and base register can't be identical");
7828     return false;
7829   }
7830 
7831   case ARM::MVE_VLDRBU8_rq:
7832   case ARM::MVE_VLDRBU16_rq:
7833   case ARM::MVE_VLDRBS16_rq:
7834   case ARM::MVE_VLDRBU32_rq:
7835   case ARM::MVE_VLDRBS32_rq:
7836   case ARM::MVE_VLDRHU16_rq:
7837   case ARM::MVE_VLDRHU16_rq_u:
7838   case ARM::MVE_VLDRHU32_rq:
7839   case ARM::MVE_VLDRHU32_rq_u:
7840   case ARM::MVE_VLDRHS32_rq:
7841   case ARM::MVE_VLDRHS32_rq_u:
7842   case ARM::MVE_VLDRWU32_rq:
7843   case ARM::MVE_VLDRWU32_rq_u:
7844   case ARM::MVE_VLDRDU64_rq:
7845   case ARM::MVE_VLDRDU64_rq_u:
7846   case ARM::MVE_VLDRWU32_qi:
7847   case ARM::MVE_VLDRWU32_qi_pre:
7848   case ARM::MVE_VLDRDU64_qi:
7849   case ARM::MVE_VLDRDU64_qi_pre: {
7850     // Qd must be different from Qm.
7851     unsigned QdIdx = 0, QmIdx = 2;
7852     bool QmIsPointer = false;
7853     switch (Opcode) {
7854     case ARM::MVE_VLDRWU32_qi:
7855     case ARM::MVE_VLDRDU64_qi:
7856       QmIdx = 1;
7857       QmIsPointer = true;
7858       break;
7859     case ARM::MVE_VLDRWU32_qi_pre:
7860     case ARM::MVE_VLDRDU64_qi_pre:
7861       QdIdx = 1;
7862       QmIsPointer = true;
7863       break;
7864     }
7865 
7866     const unsigned Qd = MRI->getEncodingValue(Inst.getOperand(QdIdx).getReg());
7867     const unsigned Qm = MRI->getEncodingValue(Inst.getOperand(QmIdx).getReg());
7868 
7869     if (Qd == Qm) {
7870       return Error(Operands[3]->getStartLoc(),
7871                    Twine("destination vector register and vector ") +
7872                    (QmIsPointer ? "pointer" : "offset") +
7873                    " register can't be identical");
7874     }
7875     return false;
7876   }
7877 
7878   case ARM::SBFX:
7879   case ARM::t2SBFX:
7880   case ARM::UBFX:
7881   case ARM::t2UBFX: {
7882     // Width must be in range [1, 32-lsb].
7883     unsigned LSB = Inst.getOperand(2).getImm();
7884     unsigned Widthm1 = Inst.getOperand(3).getImm();
7885     if (Widthm1 >= 32 - LSB)
7886       return Error(Operands[5]->getStartLoc(),
7887                    "bitfield width must be in range [1,32-lsb]");
7888     return false;
7889   }
7890   // Notionally handles ARM::tLDMIA_UPD too.
7891   case ARM::tLDMIA: {
7892     // If we're parsing Thumb2, the .w variant is available and handles
7893     // most cases that are normally illegal for a Thumb1 LDM instruction.
7894     // We'll make the transformation in processInstruction() if necessary.
7895     //
7896     // Thumb LDM instructions are writeback iff the base register is not
7897     // in the register list.
7898     unsigned Rn = Inst.getOperand(0).getReg();
7899     bool HasWritebackToken =
7900         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
7901          static_cast<ARMOperand &>(*Operands[3]).getToken() == "!");
7902     bool ListContainsBase;
7903     if (checkLowRegisterList(Inst, 3, Rn, 0, ListContainsBase) && !isThumbTwo())
7904       return Error(Operands[3 + HasWritebackToken]->getStartLoc(),
7905                    "registers must be in range r0-r7");
7906     // If we should have writeback, then there should be a '!' token.
7907     if (!ListContainsBase && !HasWritebackToken && !isThumbTwo())
7908       return Error(Operands[2]->getStartLoc(),
7909                    "writeback operator '!' expected");
7910     // If we should not have writeback, there must not be a '!'. This is
7911     // true even for the 32-bit wide encodings.
7912     if (ListContainsBase && HasWritebackToken)
7913       return Error(Operands[3]->getStartLoc(),
7914                    "writeback operator '!' not allowed when base register "
7915                    "in register list");
7916 
7917     if (validatetLDMRegList(Inst, Operands, 3))
7918       return true;
7919     break;
7920   }
7921   case ARM::LDMIA_UPD:
7922   case ARM::LDMDB_UPD:
7923   case ARM::LDMIB_UPD:
7924   case ARM::LDMDA_UPD:
7925     // ARM variants loading and updating the same register are only officially
7926     // UNPREDICTABLE on v7 upwards. Goodness knows what they did before.
7927     if (!hasV7Ops())
7928       break;
7929     if (listContainsReg(Inst, 3, Inst.getOperand(0).getReg()))
7930       return Error(Operands.back()->getStartLoc(),
7931                    "writeback register not allowed in register list");
7932     break;
7933   case ARM::t2LDMIA:
7934   case ARM::t2LDMDB:
7935     if (validatetLDMRegList(Inst, Operands, 3))
7936       return true;
7937     break;
7938   case ARM::t2STMIA:
7939   case ARM::t2STMDB:
7940     if (validatetSTMRegList(Inst, Operands, 3))
7941       return true;
7942     break;
7943   case ARM::t2LDMIA_UPD:
7944   case ARM::t2LDMDB_UPD:
7945   case ARM::t2STMIA_UPD:
7946   case ARM::t2STMDB_UPD:
7947     if (listContainsReg(Inst, 3, Inst.getOperand(0).getReg()))
7948       return Error(Operands.back()->getStartLoc(),
7949                    "writeback register not allowed in register list");
7950 
7951     if (Opcode == ARM::t2LDMIA_UPD || Opcode == ARM::t2LDMDB_UPD) {
7952       if (validatetLDMRegList(Inst, Operands, 3))
7953         return true;
7954     } else {
7955       if (validatetSTMRegList(Inst, Operands, 3))
7956         return true;
7957     }
7958     break;
7959 
7960   case ARM::sysLDMIA_UPD:
7961   case ARM::sysLDMDA_UPD:
7962   case ARM::sysLDMDB_UPD:
7963   case ARM::sysLDMIB_UPD:
7964     if (!listContainsReg(Inst, 3, ARM::PC))
7965       return Error(Operands[4]->getStartLoc(),
7966                    "writeback register only allowed on system LDM "
7967                    "if PC in register-list");
7968     break;
7969   case ARM::sysSTMIA_UPD:
7970   case ARM::sysSTMDA_UPD:
7971   case ARM::sysSTMDB_UPD:
7972   case ARM::sysSTMIB_UPD:
7973     return Error(Operands[2]->getStartLoc(),
7974                  "system STM cannot have writeback register");
7975   case ARM::tMUL:
7976     // The second source operand must be the same register as the destination
7977     // operand.
7978     //
7979     // In this case, we must directly check the parsed operands because the
7980     // cvtThumbMultiply() function is written in such a way that it guarantees
7981     // this first statement is always true for the new Inst.  Essentially, the
7982     // destination is unconditionally copied into the second source operand
7983     // without checking to see if it matches what we actually parsed.
7984     if (Operands.size() == 6 && (((ARMOperand &)*Operands[3]).getReg() !=
7985                                  ((ARMOperand &)*Operands[5]).getReg()) &&
7986         (((ARMOperand &)*Operands[3]).getReg() !=
7987          ((ARMOperand &)*Operands[4]).getReg())) {
7988       return Error(Operands[3]->getStartLoc(),
7989                    "destination register must match source register");
7990     }
7991     break;
7992 
7993   // Like for ldm/stm, push and pop have hi-reg handling version in Thumb2,
7994   // so only issue a diagnostic for thumb1. The instructions will be
7995   // switched to the t2 encodings in processInstruction() if necessary.
7996   case ARM::tPOP: {
7997     bool ListContainsBase;
7998     if (checkLowRegisterList(Inst, 2, 0, ARM::PC, ListContainsBase) &&
7999         !isThumbTwo())
8000       return Error(Operands[2]->getStartLoc(),
8001                    "registers must be in range r0-r7 or pc");
8002     if (validatetLDMRegList(Inst, Operands, 2, !isMClass()))
8003       return true;
8004     break;
8005   }
8006   case ARM::tPUSH: {
8007     bool ListContainsBase;
8008     if (checkLowRegisterList(Inst, 2, 0, ARM::LR, ListContainsBase) &&
8009         !isThumbTwo())
8010       return Error(Operands[2]->getStartLoc(),
8011                    "registers must be in range r0-r7 or lr");
8012     if (validatetSTMRegList(Inst, Operands, 2))
8013       return true;
8014     break;
8015   }
8016   case ARM::tSTMIA_UPD: {
8017     bool ListContainsBase, InvalidLowList;
8018     InvalidLowList = checkLowRegisterList(Inst, 4, Inst.getOperand(0).getReg(),
8019                                           0, ListContainsBase);
8020     if (InvalidLowList && !isThumbTwo())
8021       return Error(Operands[4]->getStartLoc(),
8022                    "registers must be in range r0-r7");
8023 
8024     // This would be converted to a 32-bit stm, but that's not valid if the
8025     // writeback register is in the list.
8026     if (InvalidLowList && ListContainsBase)
8027       return Error(Operands[4]->getStartLoc(),
8028                    "writeback operator '!' not allowed when base register "
8029                    "in register list");
8030 
8031     if (validatetSTMRegList(Inst, Operands, 4))
8032       return true;
8033     break;
8034   }
8035   case ARM::tADDrSP:
8036     // If the non-SP source operand and the destination operand are not the
8037     // same, we need thumb2 (for the wide encoding), or we have an error.
8038     if (!isThumbTwo() &&
8039         Inst.getOperand(0).getReg() != Inst.getOperand(2).getReg()) {
8040       return Error(Operands[4]->getStartLoc(),
8041                    "source register must be the same as destination");
8042     }
8043     break;
8044 
8045   case ARM::t2ADDrr:
8046   case ARM::t2ADDrs:
8047   case ARM::t2SUBrr:
8048   case ARM::t2SUBrs:
8049     if (Inst.getOperand(0).getReg() == ARM::SP &&
8050         Inst.getOperand(1).getReg() != ARM::SP)
8051       return Error(Operands[4]->getStartLoc(),
8052                    "source register must be sp if destination is sp");
8053     break;
8054 
8055   // Final range checking for Thumb unconditional branch instructions.
8056   case ARM::tB:
8057     if (!(static_cast<ARMOperand &>(*Operands[2])).isSignedOffset<11, 1>())
8058       return Error(Operands[2]->getStartLoc(), "branch target out of range");
8059     break;
8060   case ARM::t2B: {
8061     int op = (Operands[2]->isImm()) ? 2 : 3;
8062     ARMOperand &Operand = static_cast<ARMOperand &>(*Operands[op]);
8063     // Delay the checks of symbolic expressions until they are resolved.
8064     if (!isa<MCBinaryExpr>(Operand.getImm()) &&
8065         !Operand.isSignedOffset<24, 1>())
8066       return Error(Operands[op]->getStartLoc(), "branch target out of range");
8067     break;
8068   }
8069   // Final range checking for Thumb conditional branch instructions.
8070   case ARM::tBcc:
8071     if (!static_cast<ARMOperand &>(*Operands[2]).isSignedOffset<8, 1>())
8072       return Error(Operands[2]->getStartLoc(), "branch target out of range");
8073     break;
8074   case ARM::t2Bcc: {
8075     int Op = (Operands[2]->isImm()) ? 2 : 3;
8076     if (!static_cast<ARMOperand &>(*Operands[Op]).isSignedOffset<20, 1>())
8077       return Error(Operands[Op]->getStartLoc(), "branch target out of range");
8078     break;
8079   }
8080   case ARM::tCBZ:
8081   case ARM::tCBNZ: {
8082     if (!static_cast<ARMOperand &>(*Operands[2]).isUnsignedOffset<6, 1>())
8083       return Error(Operands[2]->getStartLoc(), "branch target out of range");
8084     break;
8085   }
8086   case ARM::MOVi16:
8087   case ARM::MOVTi16:
8088   case ARM::t2MOVi16:
8089   case ARM::t2MOVTi16:
8090     {
8091     // We want to avoid misleadingly allowing something like "mov r0, <symbol>"
8092     // especially when we turn it into a movw and the expression <symbol> does
8093     // not have a :lower16: or :upper16 as part of the expression.  We don't
8094     // want the behavior of silently truncating, which can be unexpected and
8095     // lead to bugs that are difficult to find since this is an easy mistake
8096     // to make.
8097     int i = (Operands[3]->isImm()) ? 3 : 4;
8098     ARMOperand &Op = static_cast<ARMOperand &>(*Operands[i]);
8099     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm());
8100     if (CE) break;
8101     const MCExpr *E = dyn_cast<MCExpr>(Op.getImm());
8102     if (!E) break;
8103     const ARMMCExpr *ARM16Expr = dyn_cast<ARMMCExpr>(E);
8104     if (!ARM16Expr || (ARM16Expr->getKind() != ARMMCExpr::VK_ARM_HI16 &&
8105                        ARM16Expr->getKind() != ARMMCExpr::VK_ARM_LO16))
8106       return Error(
8107           Op.getStartLoc(),
8108           "immediate expression for mov requires :lower16: or :upper16");
8109     break;
8110   }
8111   case ARM::HINT:
8112   case ARM::t2HINT: {
8113     unsigned Imm8 = Inst.getOperand(0).getImm();
8114     unsigned Pred = Inst.getOperand(1).getImm();
8115     // ESB is not predicable (pred must be AL). Without the RAS extension, this
8116     // behaves as any other unallocated hint.
8117     if (Imm8 == 0x10 && Pred != ARMCC::AL && hasRAS())
8118       return Error(Operands[1]->getStartLoc(), "instruction 'esb' is not "
8119                                                "predicable, but condition "
8120                                                "code specified");
8121     if (Imm8 == 0x14 && Pred != ARMCC::AL)
8122       return Error(Operands[1]->getStartLoc(), "instruction 'csdb' is not "
8123                                                "predicable, but condition "
8124                                                "code specified");
8125     break;
8126   }
8127   case ARM::t2BFi:
8128   case ARM::t2BFr:
8129   case ARM::t2BFLi:
8130   case ARM::t2BFLr: {
8131     if (!static_cast<ARMOperand &>(*Operands[2]).isUnsignedOffset<4, 1>() ||
8132         (Inst.getOperand(0).isImm() && Inst.getOperand(0).getImm() == 0))
8133       return Error(Operands[2]->getStartLoc(),
8134                    "branch location out of range or not a multiple of 2");
8135 
8136     if (Opcode == ARM::t2BFi) {
8137       if (!static_cast<ARMOperand &>(*Operands[3]).isSignedOffset<16, 1>())
8138         return Error(Operands[3]->getStartLoc(),
8139                      "branch target out of range or not a multiple of 2");
8140     } else if (Opcode == ARM::t2BFLi) {
8141       if (!static_cast<ARMOperand &>(*Operands[3]).isSignedOffset<18, 1>())
8142         return Error(Operands[3]->getStartLoc(),
8143                      "branch target out of range or not a multiple of 2");
8144     }
8145     break;
8146   }
8147   case ARM::t2BFic: {
8148     if (!static_cast<ARMOperand &>(*Operands[1]).isUnsignedOffset<4, 1>() ||
8149         (Inst.getOperand(0).isImm() && Inst.getOperand(0).getImm() == 0))
8150       return Error(Operands[1]->getStartLoc(),
8151                    "branch location out of range or not a multiple of 2");
8152 
8153     if (!static_cast<ARMOperand &>(*Operands[2]).isSignedOffset<16, 1>())
8154       return Error(Operands[2]->getStartLoc(),
8155                    "branch target out of range or not a multiple of 2");
8156 
8157     assert(Inst.getOperand(0).isImm() == Inst.getOperand(2).isImm() &&
8158            "branch location and else branch target should either both be "
8159            "immediates or both labels");
8160 
8161     if (Inst.getOperand(0).isImm() && Inst.getOperand(2).isImm()) {
8162       int Diff = Inst.getOperand(2).getImm() - Inst.getOperand(0).getImm();
8163       if (Diff != 4 && Diff != 2)
8164         return Error(
8165             Operands[3]->getStartLoc(),
8166             "else branch target must be 2 or 4 greater than the branch location");
8167     }
8168     break;
8169   }
8170   case ARM::t2CLRM: {
8171     for (unsigned i = 2; i < Inst.getNumOperands(); i++) {
8172       if (Inst.getOperand(i).isReg() &&
8173           !ARMMCRegisterClasses[ARM::GPRwithAPSRnospRegClassID].contains(
8174               Inst.getOperand(i).getReg())) {
8175         return Error(Operands[2]->getStartLoc(),
8176                      "invalid register in register list. Valid registers are "
8177                      "r0-r12, lr/r14 and APSR.");
8178       }
8179     }
8180     break;
8181   }
8182   case ARM::DSB:
8183   case ARM::t2DSB: {
8184 
8185     if (Inst.getNumOperands() < 2)
8186       break;
8187 
8188     unsigned Option = Inst.getOperand(0).getImm();
8189     unsigned Pred = Inst.getOperand(1).getImm();
8190 
8191     // SSBB and PSSBB (DSB #0|#4) are not predicable (pred must be AL).
8192     if (Option == 0 && Pred != ARMCC::AL)
8193       return Error(Operands[1]->getStartLoc(),
8194                    "instruction 'ssbb' is not predicable, but condition code "
8195                    "specified");
8196     if (Option == 4 && Pred != ARMCC::AL)
8197       return Error(Operands[1]->getStartLoc(),
8198                    "instruction 'pssbb' is not predicable, but condition code "
8199                    "specified");
8200     break;
8201   }
8202   case ARM::VMOVRRS: {
8203     // Source registers must be sequential.
8204     const unsigned Sm = MRI->getEncodingValue(Inst.getOperand(2).getReg());
8205     const unsigned Sm1 = MRI->getEncodingValue(Inst.getOperand(3).getReg());
8206     if (Sm1 != Sm + 1)
8207       return Error(Operands[5]->getStartLoc(),
8208                    "source operands must be sequential");
8209     break;
8210   }
8211   case ARM::VMOVSRR: {
8212     // Destination registers must be sequential.
8213     const unsigned Sm = MRI->getEncodingValue(Inst.getOperand(0).getReg());
8214     const unsigned Sm1 = MRI->getEncodingValue(Inst.getOperand(1).getReg());
8215     if (Sm1 != Sm + 1)
8216       return Error(Operands[3]->getStartLoc(),
8217                    "destination operands must be sequential");
8218     break;
8219   }
8220   case ARM::VLDMDIA:
8221   case ARM::VSTMDIA: {
8222     ARMOperand &Op = static_cast<ARMOperand&>(*Operands[3]);
8223     auto &RegList = Op.getRegList();
8224     if (RegList.size() < 1 || RegList.size() > 16)
8225       return Error(Operands[3]->getStartLoc(),
8226                    "list of registers must be at least 1 and at most 16");
8227     break;
8228   }
8229   case ARM::MVE_VQDMULLs32bh:
8230   case ARM::MVE_VQDMULLs32th:
8231   case ARM::MVE_VCMULf32:
8232   case ARM::MVE_VMULLBs32:
8233   case ARM::MVE_VMULLTs32:
8234   case ARM::MVE_VMULLBu32:
8235   case ARM::MVE_VMULLTu32: {
8236     if (Operands[3]->getReg() == Operands[4]->getReg()) {
8237       return Error (Operands[3]->getStartLoc(),
8238                     "Qd register and Qn register can't be identical");
8239     }
8240     if (Operands[3]->getReg() == Operands[5]->getReg()) {
8241       return Error (Operands[3]->getStartLoc(),
8242                     "Qd register and Qm register can't be identical");
8243     }
8244     break;
8245   }
8246   case ARM::MVE_VMOV_rr_q: {
8247     if (Operands[4]->getReg() != Operands[6]->getReg())
8248       return Error (Operands[4]->getStartLoc(), "Q-registers must be the same");
8249     if (static_cast<ARMOperand &>(*Operands[5]).getVectorIndex() !=
8250         static_cast<ARMOperand &>(*Operands[7]).getVectorIndex() + 2)
8251       return Error (Operands[5]->getStartLoc(), "Q-register indexes must be 2 and 0 or 3 and 1");
8252     break;
8253   }
8254   case ARM::MVE_VMOV_q_rr: {
8255     if (Operands[2]->getReg() != Operands[4]->getReg())
8256       return Error (Operands[2]->getStartLoc(), "Q-registers must be the same");
8257     if (static_cast<ARMOperand &>(*Operands[3]).getVectorIndex() !=
8258         static_cast<ARMOperand &>(*Operands[5]).getVectorIndex() + 2)
8259       return Error (Operands[3]->getStartLoc(), "Q-register indexes must be 2 and 0 or 3 and 1");
8260     break;
8261   }
8262   case ARM::UMAAL:
8263   case ARM::UMLAL:
8264   case ARM::UMULL:
8265   case ARM::t2UMAAL:
8266   case ARM::t2UMLAL:
8267   case ARM::t2UMULL:
8268   case ARM::SMLAL:
8269   case ARM::SMLALBB:
8270   case ARM::SMLALBT:
8271   case ARM::SMLALD:
8272   case ARM::SMLALDX:
8273   case ARM::SMLALTB:
8274   case ARM::SMLALTT:
8275   case ARM::SMLSLD:
8276   case ARM::SMLSLDX:
8277   case ARM::SMULL:
8278   case ARM::t2SMLAL:
8279   case ARM::t2SMLALBB:
8280   case ARM::t2SMLALBT:
8281   case ARM::t2SMLALD:
8282   case ARM::t2SMLALDX:
8283   case ARM::t2SMLALTB:
8284   case ARM::t2SMLALTT:
8285   case ARM::t2SMLSLD:
8286   case ARM::t2SMLSLDX:
8287   case ARM::t2SMULL: {
8288     unsigned RdHi = Inst.getOperand(0).getReg();
8289     unsigned RdLo = Inst.getOperand(1).getReg();
8290     if(RdHi == RdLo) {
8291       return Error(Loc,
8292                    "unpredictable instruction, RdHi and RdLo must be different");
8293     }
8294     break;
8295   }
8296 
8297   case ARM::CDE_CX1:
8298   case ARM::CDE_CX1A:
8299   case ARM::CDE_CX1D:
8300   case ARM::CDE_CX1DA:
8301   case ARM::CDE_CX2:
8302   case ARM::CDE_CX2A:
8303   case ARM::CDE_CX2D:
8304   case ARM::CDE_CX2DA:
8305   case ARM::CDE_CX3:
8306   case ARM::CDE_CX3A:
8307   case ARM::CDE_CX3D:
8308   case ARM::CDE_CX3DA:
8309   case ARM::CDE_VCX1_vec:
8310   case ARM::CDE_VCX1_fpsp:
8311   case ARM::CDE_VCX1_fpdp:
8312   case ARM::CDE_VCX1A_vec:
8313   case ARM::CDE_VCX1A_fpsp:
8314   case ARM::CDE_VCX1A_fpdp:
8315   case ARM::CDE_VCX2_vec:
8316   case ARM::CDE_VCX2_fpsp:
8317   case ARM::CDE_VCX2_fpdp:
8318   case ARM::CDE_VCX2A_vec:
8319   case ARM::CDE_VCX2A_fpsp:
8320   case ARM::CDE_VCX2A_fpdp:
8321   case ARM::CDE_VCX3_vec:
8322   case ARM::CDE_VCX3_fpsp:
8323   case ARM::CDE_VCX3_fpdp:
8324   case ARM::CDE_VCX3A_vec:
8325   case ARM::CDE_VCX3A_fpsp:
8326   case ARM::CDE_VCX3A_fpdp: {
8327     assert(Inst.getOperand(1).isImm() &&
8328            "CDE operand 1 must be a coprocessor ID");
8329     int64_t Coproc = Inst.getOperand(1).getImm();
8330     if (Coproc < 8 && !ARM::isCDECoproc(Coproc, *STI))
8331       return Error(Operands[1]->getStartLoc(),
8332                    "coprocessor must be configured as CDE");
8333     else if (Coproc >= 8)
8334       return Error(Operands[1]->getStartLoc(),
8335                    "coprocessor must be in the range [p0, p7]");
8336     break;
8337   }
8338 
8339   case ARM::t2CDP:
8340   case ARM::t2CDP2:
8341   case ARM::t2LDC2L_OFFSET:
8342   case ARM::t2LDC2L_OPTION:
8343   case ARM::t2LDC2L_POST:
8344   case ARM::t2LDC2L_PRE:
8345   case ARM::t2LDC2_OFFSET:
8346   case ARM::t2LDC2_OPTION:
8347   case ARM::t2LDC2_POST:
8348   case ARM::t2LDC2_PRE:
8349   case ARM::t2LDCL_OFFSET:
8350   case ARM::t2LDCL_OPTION:
8351   case ARM::t2LDCL_POST:
8352   case ARM::t2LDCL_PRE:
8353   case ARM::t2LDC_OFFSET:
8354   case ARM::t2LDC_OPTION:
8355   case ARM::t2LDC_POST:
8356   case ARM::t2LDC_PRE:
8357   case ARM::t2MCR:
8358   case ARM::t2MCR2:
8359   case ARM::t2MCRR:
8360   case ARM::t2MCRR2:
8361   case ARM::t2MRC:
8362   case ARM::t2MRC2:
8363   case ARM::t2MRRC:
8364   case ARM::t2MRRC2:
8365   case ARM::t2STC2L_OFFSET:
8366   case ARM::t2STC2L_OPTION:
8367   case ARM::t2STC2L_POST:
8368   case ARM::t2STC2L_PRE:
8369   case ARM::t2STC2_OFFSET:
8370   case ARM::t2STC2_OPTION:
8371   case ARM::t2STC2_POST:
8372   case ARM::t2STC2_PRE:
8373   case ARM::t2STCL_OFFSET:
8374   case ARM::t2STCL_OPTION:
8375   case ARM::t2STCL_POST:
8376   case ARM::t2STCL_PRE:
8377   case ARM::t2STC_OFFSET:
8378   case ARM::t2STC_OPTION:
8379   case ARM::t2STC_POST:
8380   case ARM::t2STC_PRE: {
8381     unsigned Opcode = Inst.getOpcode();
8382     // Inst.getOperand indexes operands in the (oops ...) and (iops ...) dags,
8383     // CopInd is the index of the coprocessor operand.
8384     size_t CopInd = 0;
8385     if (Opcode == ARM::t2MRRC || Opcode == ARM::t2MRRC2)
8386       CopInd = 2;
8387     else if (Opcode == ARM::t2MRC || Opcode == ARM::t2MRC2)
8388       CopInd = 1;
8389     assert(Inst.getOperand(CopInd).isImm() &&
8390            "Operand must be a coprocessor ID");
8391     int64_t Coproc = Inst.getOperand(CopInd).getImm();
8392     // Operands[2] is the coprocessor operand at syntactic level
8393     if (ARM::isCDECoproc(Coproc, *STI))
8394       return Error(Operands[2]->getStartLoc(),
8395                    "coprocessor must be configured as GCP");
8396     break;
8397   }
8398   }
8399 
8400   return false;
8401 }
8402 
8403 static unsigned getRealVSTOpcode(unsigned Opc, unsigned &Spacing) {
8404   switch(Opc) {
8405   default: llvm_unreachable("unexpected opcode!");
8406   // VST1LN
8407   case ARM::VST1LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST1LNd8_UPD;
8408   case ARM::VST1LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST1LNd16_UPD;
8409   case ARM::VST1LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST1LNd32_UPD;
8410   case ARM::VST1LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST1LNd8_UPD;
8411   case ARM::VST1LNdWB_register_Asm_16: Spacing = 1; return ARM::VST1LNd16_UPD;
8412   case ARM::VST1LNdWB_register_Asm_32: Spacing = 1; return ARM::VST1LNd32_UPD;
8413   case ARM::VST1LNdAsm_8:  Spacing = 1; return ARM::VST1LNd8;
8414   case ARM::VST1LNdAsm_16: Spacing = 1; return ARM::VST1LNd16;
8415   case ARM::VST1LNdAsm_32: Spacing = 1; return ARM::VST1LNd32;
8416 
8417   // VST2LN
8418   case ARM::VST2LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST2LNd8_UPD;
8419   case ARM::VST2LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST2LNd16_UPD;
8420   case ARM::VST2LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST2LNd32_UPD;
8421   case ARM::VST2LNqWB_fixed_Asm_16: Spacing = 2; return ARM::VST2LNq16_UPD;
8422   case ARM::VST2LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST2LNq32_UPD;
8423 
8424   case ARM::VST2LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST2LNd8_UPD;
8425   case ARM::VST2LNdWB_register_Asm_16: Spacing = 1; return ARM::VST2LNd16_UPD;
8426   case ARM::VST2LNdWB_register_Asm_32: Spacing = 1; return ARM::VST2LNd32_UPD;
8427   case ARM::VST2LNqWB_register_Asm_16: Spacing = 2; return ARM::VST2LNq16_UPD;
8428   case ARM::VST2LNqWB_register_Asm_32: Spacing = 2; return ARM::VST2LNq32_UPD;
8429 
8430   case ARM::VST2LNdAsm_8:  Spacing = 1; return ARM::VST2LNd8;
8431   case ARM::VST2LNdAsm_16: Spacing = 1; return ARM::VST2LNd16;
8432   case ARM::VST2LNdAsm_32: Spacing = 1; return ARM::VST2LNd32;
8433   case ARM::VST2LNqAsm_16: Spacing = 2; return ARM::VST2LNq16;
8434   case ARM::VST2LNqAsm_32: Spacing = 2; return ARM::VST2LNq32;
8435 
8436   // VST3LN
8437   case ARM::VST3LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST3LNd8_UPD;
8438   case ARM::VST3LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST3LNd16_UPD;
8439   case ARM::VST3LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST3LNd32_UPD;
8440   case ARM::VST3LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VST3LNq16_UPD;
8441   case ARM::VST3LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST3LNq32_UPD;
8442   case ARM::VST3LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST3LNd8_UPD;
8443   case ARM::VST3LNdWB_register_Asm_16: Spacing = 1; return ARM::VST3LNd16_UPD;
8444   case ARM::VST3LNdWB_register_Asm_32: Spacing = 1; return ARM::VST3LNd32_UPD;
8445   case ARM::VST3LNqWB_register_Asm_16: Spacing = 2; return ARM::VST3LNq16_UPD;
8446   case ARM::VST3LNqWB_register_Asm_32: Spacing = 2; return ARM::VST3LNq32_UPD;
8447   case ARM::VST3LNdAsm_8:  Spacing = 1; return ARM::VST3LNd8;
8448   case ARM::VST3LNdAsm_16: Spacing = 1; return ARM::VST3LNd16;
8449   case ARM::VST3LNdAsm_32: Spacing = 1; return ARM::VST3LNd32;
8450   case ARM::VST3LNqAsm_16: Spacing = 2; return ARM::VST3LNq16;
8451   case ARM::VST3LNqAsm_32: Spacing = 2; return ARM::VST3LNq32;
8452 
8453   // VST3
8454   case ARM::VST3dWB_fixed_Asm_8:  Spacing = 1; return ARM::VST3d8_UPD;
8455   case ARM::VST3dWB_fixed_Asm_16: Spacing = 1; return ARM::VST3d16_UPD;
8456   case ARM::VST3dWB_fixed_Asm_32: Spacing = 1; return ARM::VST3d32_UPD;
8457   case ARM::VST3qWB_fixed_Asm_8:  Spacing = 2; return ARM::VST3q8_UPD;
8458   case ARM::VST3qWB_fixed_Asm_16: Spacing = 2; return ARM::VST3q16_UPD;
8459   case ARM::VST3qWB_fixed_Asm_32: Spacing = 2; return ARM::VST3q32_UPD;
8460   case ARM::VST3dWB_register_Asm_8:  Spacing = 1; return ARM::VST3d8_UPD;
8461   case ARM::VST3dWB_register_Asm_16: Spacing = 1; return ARM::VST3d16_UPD;
8462   case ARM::VST3dWB_register_Asm_32: Spacing = 1; return ARM::VST3d32_UPD;
8463   case ARM::VST3qWB_register_Asm_8:  Spacing = 2; return ARM::VST3q8_UPD;
8464   case ARM::VST3qWB_register_Asm_16: Spacing = 2; return ARM::VST3q16_UPD;
8465   case ARM::VST3qWB_register_Asm_32: Spacing = 2; return ARM::VST3q32_UPD;
8466   case ARM::VST3dAsm_8:  Spacing = 1; return ARM::VST3d8;
8467   case ARM::VST3dAsm_16: Spacing = 1; return ARM::VST3d16;
8468   case ARM::VST3dAsm_32: Spacing = 1; return ARM::VST3d32;
8469   case ARM::VST3qAsm_8:  Spacing = 2; return ARM::VST3q8;
8470   case ARM::VST3qAsm_16: Spacing = 2; return ARM::VST3q16;
8471   case ARM::VST3qAsm_32: Spacing = 2; return ARM::VST3q32;
8472 
8473   // VST4LN
8474   case ARM::VST4LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST4LNd8_UPD;
8475   case ARM::VST4LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST4LNd16_UPD;
8476   case ARM::VST4LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST4LNd32_UPD;
8477   case ARM::VST4LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VST4LNq16_UPD;
8478   case ARM::VST4LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST4LNq32_UPD;
8479   case ARM::VST4LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST4LNd8_UPD;
8480   case ARM::VST4LNdWB_register_Asm_16: Spacing = 1; return ARM::VST4LNd16_UPD;
8481   case ARM::VST4LNdWB_register_Asm_32: Spacing = 1; return ARM::VST4LNd32_UPD;
8482   case ARM::VST4LNqWB_register_Asm_16: Spacing = 2; return ARM::VST4LNq16_UPD;
8483   case ARM::VST4LNqWB_register_Asm_32: Spacing = 2; return ARM::VST4LNq32_UPD;
8484   case ARM::VST4LNdAsm_8:  Spacing = 1; return ARM::VST4LNd8;
8485   case ARM::VST4LNdAsm_16: Spacing = 1; return ARM::VST4LNd16;
8486   case ARM::VST4LNdAsm_32: Spacing = 1; return ARM::VST4LNd32;
8487   case ARM::VST4LNqAsm_16: Spacing = 2; return ARM::VST4LNq16;
8488   case ARM::VST4LNqAsm_32: Spacing = 2; return ARM::VST4LNq32;
8489 
8490   // VST4
8491   case ARM::VST4dWB_fixed_Asm_8:  Spacing = 1; return ARM::VST4d8_UPD;
8492   case ARM::VST4dWB_fixed_Asm_16: Spacing = 1; return ARM::VST4d16_UPD;
8493   case ARM::VST4dWB_fixed_Asm_32: Spacing = 1; return ARM::VST4d32_UPD;
8494   case ARM::VST4qWB_fixed_Asm_8:  Spacing = 2; return ARM::VST4q8_UPD;
8495   case ARM::VST4qWB_fixed_Asm_16: Spacing = 2; return ARM::VST4q16_UPD;
8496   case ARM::VST4qWB_fixed_Asm_32: Spacing = 2; return ARM::VST4q32_UPD;
8497   case ARM::VST4dWB_register_Asm_8:  Spacing = 1; return ARM::VST4d8_UPD;
8498   case ARM::VST4dWB_register_Asm_16: Spacing = 1; return ARM::VST4d16_UPD;
8499   case ARM::VST4dWB_register_Asm_32: Spacing = 1; return ARM::VST4d32_UPD;
8500   case ARM::VST4qWB_register_Asm_8:  Spacing = 2; return ARM::VST4q8_UPD;
8501   case ARM::VST4qWB_register_Asm_16: Spacing = 2; return ARM::VST4q16_UPD;
8502   case ARM::VST4qWB_register_Asm_32: Spacing = 2; return ARM::VST4q32_UPD;
8503   case ARM::VST4dAsm_8:  Spacing = 1; return ARM::VST4d8;
8504   case ARM::VST4dAsm_16: Spacing = 1; return ARM::VST4d16;
8505   case ARM::VST4dAsm_32: Spacing = 1; return ARM::VST4d32;
8506   case ARM::VST4qAsm_8:  Spacing = 2; return ARM::VST4q8;
8507   case ARM::VST4qAsm_16: Spacing = 2; return ARM::VST4q16;
8508   case ARM::VST4qAsm_32: Spacing = 2; return ARM::VST4q32;
8509   }
8510 }
8511 
8512 static unsigned getRealVLDOpcode(unsigned Opc, unsigned &Spacing) {
8513   switch(Opc) {
8514   default: llvm_unreachable("unexpected opcode!");
8515   // VLD1LN
8516   case ARM::VLD1LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD1LNd8_UPD;
8517   case ARM::VLD1LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD1LNd16_UPD;
8518   case ARM::VLD1LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD1LNd32_UPD;
8519   case ARM::VLD1LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD1LNd8_UPD;
8520   case ARM::VLD1LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD1LNd16_UPD;
8521   case ARM::VLD1LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD1LNd32_UPD;
8522   case ARM::VLD1LNdAsm_8:  Spacing = 1; return ARM::VLD1LNd8;
8523   case ARM::VLD1LNdAsm_16: Spacing = 1; return ARM::VLD1LNd16;
8524   case ARM::VLD1LNdAsm_32: Spacing = 1; return ARM::VLD1LNd32;
8525 
8526   // VLD2LN
8527   case ARM::VLD2LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD2LNd8_UPD;
8528   case ARM::VLD2LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD2LNd16_UPD;
8529   case ARM::VLD2LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD2LNd32_UPD;
8530   case ARM::VLD2LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD2LNq16_UPD;
8531   case ARM::VLD2LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD2LNq32_UPD;
8532   case ARM::VLD2LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD2LNd8_UPD;
8533   case ARM::VLD2LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD2LNd16_UPD;
8534   case ARM::VLD2LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD2LNd32_UPD;
8535   case ARM::VLD2LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD2LNq16_UPD;
8536   case ARM::VLD2LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD2LNq32_UPD;
8537   case ARM::VLD2LNdAsm_8:  Spacing = 1; return ARM::VLD2LNd8;
8538   case ARM::VLD2LNdAsm_16: Spacing = 1; return ARM::VLD2LNd16;
8539   case ARM::VLD2LNdAsm_32: Spacing = 1; return ARM::VLD2LNd32;
8540   case ARM::VLD2LNqAsm_16: Spacing = 2; return ARM::VLD2LNq16;
8541   case ARM::VLD2LNqAsm_32: Spacing = 2; return ARM::VLD2LNq32;
8542 
8543   // VLD3DUP
8544   case ARM::VLD3DUPdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3DUPd8_UPD;
8545   case ARM::VLD3DUPdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3DUPd16_UPD;
8546   case ARM::VLD3DUPdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3DUPd32_UPD;
8547   case ARM::VLD3DUPqWB_fixed_Asm_8: Spacing = 1; return ARM::VLD3DUPq8_UPD;
8548   case ARM::VLD3DUPqWB_fixed_Asm_16: Spacing = 2; return ARM::VLD3DUPq16_UPD;
8549   case ARM::VLD3DUPqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3DUPq32_UPD;
8550   case ARM::VLD3DUPdWB_register_Asm_8:  Spacing = 1; return ARM::VLD3DUPd8_UPD;
8551   case ARM::VLD3DUPdWB_register_Asm_16: Spacing = 1; return ARM::VLD3DUPd16_UPD;
8552   case ARM::VLD3DUPdWB_register_Asm_32: Spacing = 1; return ARM::VLD3DUPd32_UPD;
8553   case ARM::VLD3DUPqWB_register_Asm_8: Spacing = 2; return ARM::VLD3DUPq8_UPD;
8554   case ARM::VLD3DUPqWB_register_Asm_16: Spacing = 2; return ARM::VLD3DUPq16_UPD;
8555   case ARM::VLD3DUPqWB_register_Asm_32: Spacing = 2; return ARM::VLD3DUPq32_UPD;
8556   case ARM::VLD3DUPdAsm_8:  Spacing = 1; return ARM::VLD3DUPd8;
8557   case ARM::VLD3DUPdAsm_16: Spacing = 1; return ARM::VLD3DUPd16;
8558   case ARM::VLD3DUPdAsm_32: Spacing = 1; return ARM::VLD3DUPd32;
8559   case ARM::VLD3DUPqAsm_8: Spacing = 2; return ARM::VLD3DUPq8;
8560   case ARM::VLD3DUPqAsm_16: Spacing = 2; return ARM::VLD3DUPq16;
8561   case ARM::VLD3DUPqAsm_32: Spacing = 2; return ARM::VLD3DUPq32;
8562 
8563   // VLD3LN
8564   case ARM::VLD3LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3LNd8_UPD;
8565   case ARM::VLD3LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3LNd16_UPD;
8566   case ARM::VLD3LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3LNd32_UPD;
8567   case ARM::VLD3LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3LNq16_UPD;
8568   case ARM::VLD3LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3LNq32_UPD;
8569   case ARM::VLD3LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD3LNd8_UPD;
8570   case ARM::VLD3LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD3LNd16_UPD;
8571   case ARM::VLD3LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD3LNd32_UPD;
8572   case ARM::VLD3LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD3LNq16_UPD;
8573   case ARM::VLD3LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD3LNq32_UPD;
8574   case ARM::VLD3LNdAsm_8:  Spacing = 1; return ARM::VLD3LNd8;
8575   case ARM::VLD3LNdAsm_16: Spacing = 1; return ARM::VLD3LNd16;
8576   case ARM::VLD3LNdAsm_32: Spacing = 1; return ARM::VLD3LNd32;
8577   case ARM::VLD3LNqAsm_16: Spacing = 2; return ARM::VLD3LNq16;
8578   case ARM::VLD3LNqAsm_32: Spacing = 2; return ARM::VLD3LNq32;
8579 
8580   // VLD3
8581   case ARM::VLD3dWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3d8_UPD;
8582   case ARM::VLD3dWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3d16_UPD;
8583   case ARM::VLD3dWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3d32_UPD;
8584   case ARM::VLD3qWB_fixed_Asm_8:  Spacing = 2; return ARM::VLD3q8_UPD;
8585   case ARM::VLD3qWB_fixed_Asm_16: Spacing = 2; return ARM::VLD3q16_UPD;
8586   case ARM::VLD3qWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3q32_UPD;
8587   case ARM::VLD3dWB_register_Asm_8:  Spacing = 1; return ARM::VLD3d8_UPD;
8588   case ARM::VLD3dWB_register_Asm_16: Spacing = 1; return ARM::VLD3d16_UPD;
8589   case ARM::VLD3dWB_register_Asm_32: Spacing = 1; return ARM::VLD3d32_UPD;
8590   case ARM::VLD3qWB_register_Asm_8:  Spacing = 2; return ARM::VLD3q8_UPD;
8591   case ARM::VLD3qWB_register_Asm_16: Spacing = 2; return ARM::VLD3q16_UPD;
8592   case ARM::VLD3qWB_register_Asm_32: Spacing = 2; return ARM::VLD3q32_UPD;
8593   case ARM::VLD3dAsm_8:  Spacing = 1; return ARM::VLD3d8;
8594   case ARM::VLD3dAsm_16: Spacing = 1; return ARM::VLD3d16;
8595   case ARM::VLD3dAsm_32: Spacing = 1; return ARM::VLD3d32;
8596   case ARM::VLD3qAsm_8:  Spacing = 2; return ARM::VLD3q8;
8597   case ARM::VLD3qAsm_16: Spacing = 2; return ARM::VLD3q16;
8598   case ARM::VLD3qAsm_32: Spacing = 2; return ARM::VLD3q32;
8599 
8600   // VLD4LN
8601   case ARM::VLD4LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4LNd8_UPD;
8602   case ARM::VLD4LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4LNd16_UPD;
8603   case ARM::VLD4LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4LNd32_UPD;
8604   case ARM::VLD4LNqWB_fixed_Asm_16: Spacing = 2; return ARM::VLD4LNq16_UPD;
8605   case ARM::VLD4LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4LNq32_UPD;
8606   case ARM::VLD4LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD4LNd8_UPD;
8607   case ARM::VLD4LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD4LNd16_UPD;
8608   case ARM::VLD4LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD4LNd32_UPD;
8609   case ARM::VLD4LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD4LNq16_UPD;
8610   case ARM::VLD4LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD4LNq32_UPD;
8611   case ARM::VLD4LNdAsm_8:  Spacing = 1; return ARM::VLD4LNd8;
8612   case ARM::VLD4LNdAsm_16: Spacing = 1; return ARM::VLD4LNd16;
8613   case ARM::VLD4LNdAsm_32: Spacing = 1; return ARM::VLD4LNd32;
8614   case ARM::VLD4LNqAsm_16: Spacing = 2; return ARM::VLD4LNq16;
8615   case ARM::VLD4LNqAsm_32: Spacing = 2; return ARM::VLD4LNq32;
8616 
8617   // VLD4DUP
8618   case ARM::VLD4DUPdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4DUPd8_UPD;
8619   case ARM::VLD4DUPdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4DUPd16_UPD;
8620   case ARM::VLD4DUPdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4DUPd32_UPD;
8621   case ARM::VLD4DUPqWB_fixed_Asm_8: Spacing = 1; return ARM::VLD4DUPq8_UPD;
8622   case ARM::VLD4DUPqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4DUPq16_UPD;
8623   case ARM::VLD4DUPqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4DUPq32_UPD;
8624   case ARM::VLD4DUPdWB_register_Asm_8:  Spacing = 1; return ARM::VLD4DUPd8_UPD;
8625   case ARM::VLD4DUPdWB_register_Asm_16: Spacing = 1; return ARM::VLD4DUPd16_UPD;
8626   case ARM::VLD4DUPdWB_register_Asm_32: Spacing = 1; return ARM::VLD4DUPd32_UPD;
8627   case ARM::VLD4DUPqWB_register_Asm_8: Spacing = 2; return ARM::VLD4DUPq8_UPD;
8628   case ARM::VLD4DUPqWB_register_Asm_16: Spacing = 2; return ARM::VLD4DUPq16_UPD;
8629   case ARM::VLD4DUPqWB_register_Asm_32: Spacing = 2; return ARM::VLD4DUPq32_UPD;
8630   case ARM::VLD4DUPdAsm_8:  Spacing = 1; return ARM::VLD4DUPd8;
8631   case ARM::VLD4DUPdAsm_16: Spacing = 1; return ARM::VLD4DUPd16;
8632   case ARM::VLD4DUPdAsm_32: Spacing = 1; return ARM::VLD4DUPd32;
8633   case ARM::VLD4DUPqAsm_8: Spacing = 2; return ARM::VLD4DUPq8;
8634   case ARM::VLD4DUPqAsm_16: Spacing = 2; return ARM::VLD4DUPq16;
8635   case ARM::VLD4DUPqAsm_32: Spacing = 2; return ARM::VLD4DUPq32;
8636 
8637   // VLD4
8638   case ARM::VLD4dWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4d8_UPD;
8639   case ARM::VLD4dWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4d16_UPD;
8640   case ARM::VLD4dWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4d32_UPD;
8641   case ARM::VLD4qWB_fixed_Asm_8:  Spacing = 2; return ARM::VLD4q8_UPD;
8642   case ARM::VLD4qWB_fixed_Asm_16: Spacing = 2; return ARM::VLD4q16_UPD;
8643   case ARM::VLD4qWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4q32_UPD;
8644   case ARM::VLD4dWB_register_Asm_8:  Spacing = 1; return ARM::VLD4d8_UPD;
8645   case ARM::VLD4dWB_register_Asm_16: Spacing = 1; return ARM::VLD4d16_UPD;
8646   case ARM::VLD4dWB_register_Asm_32: Spacing = 1; return ARM::VLD4d32_UPD;
8647   case ARM::VLD4qWB_register_Asm_8:  Spacing = 2; return ARM::VLD4q8_UPD;
8648   case ARM::VLD4qWB_register_Asm_16: Spacing = 2; return ARM::VLD4q16_UPD;
8649   case ARM::VLD4qWB_register_Asm_32: Spacing = 2; return ARM::VLD4q32_UPD;
8650   case ARM::VLD4dAsm_8:  Spacing = 1; return ARM::VLD4d8;
8651   case ARM::VLD4dAsm_16: Spacing = 1; return ARM::VLD4d16;
8652   case ARM::VLD4dAsm_32: Spacing = 1; return ARM::VLD4d32;
8653   case ARM::VLD4qAsm_8:  Spacing = 2; return ARM::VLD4q8;
8654   case ARM::VLD4qAsm_16: Spacing = 2; return ARM::VLD4q16;
8655   case ARM::VLD4qAsm_32: Spacing = 2; return ARM::VLD4q32;
8656   }
8657 }
8658 
8659 bool ARMAsmParser::processInstruction(MCInst &Inst,
8660                                       const OperandVector &Operands,
8661                                       MCStreamer &Out) {
8662   // Check if we have the wide qualifier, because if it's present we
8663   // must avoid selecting a 16-bit thumb instruction.
8664   bool HasWideQualifier = false;
8665   for (auto &Op : Operands) {
8666     ARMOperand &ARMOp = static_cast<ARMOperand&>(*Op);
8667     if (ARMOp.isToken() && ARMOp.getToken() == ".w") {
8668       HasWideQualifier = true;
8669       break;
8670     }
8671   }
8672 
8673   switch (Inst.getOpcode()) {
8674   // Alias for alternate form of 'ldr{,b}t Rt, [Rn], #imm' instruction.
8675   case ARM::LDRT_POST:
8676   case ARM::LDRBT_POST: {
8677     const unsigned Opcode =
8678       (Inst.getOpcode() == ARM::LDRT_POST) ? ARM::LDRT_POST_IMM
8679                                            : ARM::LDRBT_POST_IMM;
8680     MCInst TmpInst;
8681     TmpInst.setOpcode(Opcode);
8682     TmpInst.addOperand(Inst.getOperand(0));
8683     TmpInst.addOperand(Inst.getOperand(1));
8684     TmpInst.addOperand(Inst.getOperand(1));
8685     TmpInst.addOperand(MCOperand::createReg(0));
8686     TmpInst.addOperand(MCOperand::createImm(0));
8687     TmpInst.addOperand(Inst.getOperand(2));
8688     TmpInst.addOperand(Inst.getOperand(3));
8689     Inst = TmpInst;
8690     return true;
8691   }
8692   // Alias for 'ldr{sb,h,sh}t Rt, [Rn] {, #imm}' for ommitted immediate.
8693   case ARM::LDRSBTii:
8694   case ARM::LDRHTii:
8695   case ARM::LDRSHTii: {
8696     MCInst TmpInst;
8697 
8698     if (Inst.getOpcode() == ARM::LDRSBTii)
8699       TmpInst.setOpcode(ARM::LDRSBTi);
8700     else if (Inst.getOpcode() == ARM::LDRHTii)
8701       TmpInst.setOpcode(ARM::LDRHTi);
8702     else if (Inst.getOpcode() == ARM::LDRSHTii)
8703       TmpInst.setOpcode(ARM::LDRSHTi);
8704     TmpInst.addOperand(Inst.getOperand(0));
8705     TmpInst.addOperand(Inst.getOperand(1));
8706     TmpInst.addOperand(Inst.getOperand(1));
8707     TmpInst.addOperand(MCOperand::createImm(256));
8708     TmpInst.addOperand(Inst.getOperand(2));
8709     Inst = TmpInst;
8710     return true;
8711   }
8712   // Alias for alternate form of 'str{,b}t Rt, [Rn], #imm' instruction.
8713   case ARM::STRT_POST:
8714   case ARM::STRBT_POST: {
8715     const unsigned Opcode =
8716       (Inst.getOpcode() == ARM::STRT_POST) ? ARM::STRT_POST_IMM
8717                                            : ARM::STRBT_POST_IMM;
8718     MCInst TmpInst;
8719     TmpInst.setOpcode(Opcode);
8720     TmpInst.addOperand(Inst.getOperand(1));
8721     TmpInst.addOperand(Inst.getOperand(0));
8722     TmpInst.addOperand(Inst.getOperand(1));
8723     TmpInst.addOperand(MCOperand::createReg(0));
8724     TmpInst.addOperand(MCOperand::createImm(0));
8725     TmpInst.addOperand(Inst.getOperand(2));
8726     TmpInst.addOperand(Inst.getOperand(3));
8727     Inst = TmpInst;
8728     return true;
8729   }
8730   // Alias for alternate form of 'ADR Rd, #imm' instruction.
8731   case ARM::ADDri: {
8732     if (Inst.getOperand(1).getReg() != ARM::PC ||
8733         Inst.getOperand(5).getReg() != 0 ||
8734         !(Inst.getOperand(2).isExpr() || Inst.getOperand(2).isImm()))
8735       return false;
8736     MCInst TmpInst;
8737     TmpInst.setOpcode(ARM::ADR);
8738     TmpInst.addOperand(Inst.getOperand(0));
8739     if (Inst.getOperand(2).isImm()) {
8740       // Immediate (mod_imm) will be in its encoded form, we must unencode it
8741       // before passing it to the ADR instruction.
8742       unsigned Enc = Inst.getOperand(2).getImm();
8743       TmpInst.addOperand(MCOperand::createImm(
8744         ARM_AM::rotr32(Enc & 0xFF, (Enc & 0xF00) >> 7)));
8745     } else {
8746       // Turn PC-relative expression into absolute expression.
8747       // Reading PC provides the start of the current instruction + 8 and
8748       // the transform to adr is biased by that.
8749       MCSymbol *Dot = getContext().createTempSymbol();
8750       Out.emitLabel(Dot);
8751       const MCExpr *OpExpr = Inst.getOperand(2).getExpr();
8752       const MCExpr *InstPC = MCSymbolRefExpr::create(Dot,
8753                                                      MCSymbolRefExpr::VK_None,
8754                                                      getContext());
8755       const MCExpr *Const8 = MCConstantExpr::create(8, getContext());
8756       const MCExpr *ReadPC = MCBinaryExpr::createAdd(InstPC, Const8,
8757                                                      getContext());
8758       const MCExpr *FixupAddr = MCBinaryExpr::createAdd(ReadPC, OpExpr,
8759                                                         getContext());
8760       TmpInst.addOperand(MCOperand::createExpr(FixupAddr));
8761     }
8762     TmpInst.addOperand(Inst.getOperand(3));
8763     TmpInst.addOperand(Inst.getOperand(4));
8764     Inst = TmpInst;
8765     return true;
8766   }
8767   // Aliases for imm syntax of LDR instructions.
8768   case ARM::t2LDR_PRE_imm:
8769   case ARM::t2LDR_POST_imm: {
8770     MCInst TmpInst;
8771     TmpInst.setOpcode(Inst.getOpcode() == ARM::t2LDR_PRE_imm ? ARM::t2LDR_PRE
8772                                                              : ARM::t2LDR_POST);
8773     TmpInst.addOperand(Inst.getOperand(0)); // Rt
8774     TmpInst.addOperand(Inst.getOperand(4)); // Rt_wb
8775     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8776     TmpInst.addOperand(Inst.getOperand(2)); // imm
8777     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8778     Inst = TmpInst;
8779     return true;
8780   }
8781   // Aliases for imm syntax of STR instructions.
8782   case ARM::t2STR_PRE_imm:
8783   case ARM::t2STR_POST_imm: {
8784     MCInst TmpInst;
8785     TmpInst.setOpcode(Inst.getOpcode() == ARM::t2STR_PRE_imm ? ARM::t2STR_PRE
8786                                                              : ARM::t2STR_POST);
8787     TmpInst.addOperand(Inst.getOperand(4)); // Rt_wb
8788     TmpInst.addOperand(Inst.getOperand(0)); // Rt
8789     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8790     TmpInst.addOperand(Inst.getOperand(2)); // imm
8791     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8792     Inst = TmpInst;
8793     return true;
8794   }
8795   // Aliases for alternate PC+imm syntax of LDR instructions.
8796   case ARM::t2LDRpcrel:
8797     // Select the narrow version if the immediate will fit.
8798     if (Inst.getOperand(1).getImm() > 0 &&
8799         Inst.getOperand(1).getImm() <= 0xff &&
8800         !HasWideQualifier)
8801       Inst.setOpcode(ARM::tLDRpci);
8802     else
8803       Inst.setOpcode(ARM::t2LDRpci);
8804     return true;
8805   case ARM::t2LDRBpcrel:
8806     Inst.setOpcode(ARM::t2LDRBpci);
8807     return true;
8808   case ARM::t2LDRHpcrel:
8809     Inst.setOpcode(ARM::t2LDRHpci);
8810     return true;
8811   case ARM::t2LDRSBpcrel:
8812     Inst.setOpcode(ARM::t2LDRSBpci);
8813     return true;
8814   case ARM::t2LDRSHpcrel:
8815     Inst.setOpcode(ARM::t2LDRSHpci);
8816     return true;
8817   case ARM::LDRConstPool:
8818   case ARM::tLDRConstPool:
8819   case ARM::t2LDRConstPool: {
8820     // Pseudo instruction ldr rt, =immediate is converted to a
8821     // MOV rt, immediate if immediate is known and representable
8822     // otherwise we create a constant pool entry that we load from.
8823     MCInst TmpInst;
8824     if (Inst.getOpcode() == ARM::LDRConstPool)
8825       TmpInst.setOpcode(ARM::LDRi12);
8826     else if (Inst.getOpcode() == ARM::tLDRConstPool)
8827       TmpInst.setOpcode(ARM::tLDRpci);
8828     else if (Inst.getOpcode() == ARM::t2LDRConstPool)
8829       TmpInst.setOpcode(ARM::t2LDRpci);
8830     const ARMOperand &PoolOperand =
8831       (HasWideQualifier ?
8832        static_cast<ARMOperand &>(*Operands[4]) :
8833        static_cast<ARMOperand &>(*Operands[3]));
8834     const MCExpr *SubExprVal = PoolOperand.getConstantPoolImm();
8835     // If SubExprVal is a constant we may be able to use a MOV
8836     if (isa<MCConstantExpr>(SubExprVal) &&
8837         Inst.getOperand(0).getReg() != ARM::PC &&
8838         Inst.getOperand(0).getReg() != ARM::SP) {
8839       int64_t Value =
8840         (int64_t) (cast<MCConstantExpr>(SubExprVal))->getValue();
8841       bool UseMov  = true;
8842       bool MovHasS = true;
8843       if (Inst.getOpcode() == ARM::LDRConstPool) {
8844         // ARM Constant
8845         if (ARM_AM::getSOImmVal(Value) != -1) {
8846           Value = ARM_AM::getSOImmVal(Value);
8847           TmpInst.setOpcode(ARM::MOVi);
8848         }
8849         else if (ARM_AM::getSOImmVal(~Value) != -1) {
8850           Value = ARM_AM::getSOImmVal(~Value);
8851           TmpInst.setOpcode(ARM::MVNi);
8852         }
8853         else if (hasV6T2Ops() &&
8854                  Value >=0 && Value < 65536) {
8855           TmpInst.setOpcode(ARM::MOVi16);
8856           MovHasS = false;
8857         }
8858         else
8859           UseMov = false;
8860       }
8861       else {
8862         // Thumb/Thumb2 Constant
8863         if (hasThumb2() &&
8864             ARM_AM::getT2SOImmVal(Value) != -1)
8865           TmpInst.setOpcode(ARM::t2MOVi);
8866         else if (hasThumb2() &&
8867                  ARM_AM::getT2SOImmVal(~Value) != -1) {
8868           TmpInst.setOpcode(ARM::t2MVNi);
8869           Value = ~Value;
8870         }
8871         else if (hasV8MBaseline() &&
8872                  Value >=0 && Value < 65536) {
8873           TmpInst.setOpcode(ARM::t2MOVi16);
8874           MovHasS = false;
8875         }
8876         else
8877           UseMov = false;
8878       }
8879       if (UseMov) {
8880         TmpInst.addOperand(Inst.getOperand(0));           // Rt
8881         TmpInst.addOperand(MCOperand::createImm(Value));  // Immediate
8882         TmpInst.addOperand(Inst.getOperand(2));           // CondCode
8883         TmpInst.addOperand(Inst.getOperand(3));           // CondCode
8884         if (MovHasS)
8885           TmpInst.addOperand(MCOperand::createReg(0));    // S
8886         Inst = TmpInst;
8887         return true;
8888       }
8889     }
8890     // No opportunity to use MOV/MVN create constant pool
8891     const MCExpr *CPLoc =
8892       getTargetStreamer().addConstantPoolEntry(SubExprVal,
8893                                                PoolOperand.getStartLoc());
8894     TmpInst.addOperand(Inst.getOperand(0));           // Rt
8895     TmpInst.addOperand(MCOperand::createExpr(CPLoc)); // offset to constpool
8896     if (TmpInst.getOpcode() == ARM::LDRi12)
8897       TmpInst.addOperand(MCOperand::createImm(0));    // unused offset
8898     TmpInst.addOperand(Inst.getOperand(2));           // CondCode
8899     TmpInst.addOperand(Inst.getOperand(3));           // CondCode
8900     Inst = TmpInst;
8901     return true;
8902   }
8903   // Handle NEON VST complex aliases.
8904   case ARM::VST1LNdWB_register_Asm_8:
8905   case ARM::VST1LNdWB_register_Asm_16:
8906   case ARM::VST1LNdWB_register_Asm_32: {
8907     MCInst TmpInst;
8908     // Shuffle the operands around so the lane index operand is in the
8909     // right place.
8910     unsigned Spacing;
8911     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8912     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8913     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8914     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8915     TmpInst.addOperand(Inst.getOperand(4)); // Rm
8916     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8917     TmpInst.addOperand(Inst.getOperand(1)); // lane
8918     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
8919     TmpInst.addOperand(Inst.getOperand(6));
8920     Inst = TmpInst;
8921     return true;
8922   }
8923 
8924   case ARM::VST2LNdWB_register_Asm_8:
8925   case ARM::VST2LNdWB_register_Asm_16:
8926   case ARM::VST2LNdWB_register_Asm_32:
8927   case ARM::VST2LNqWB_register_Asm_16:
8928   case ARM::VST2LNqWB_register_Asm_32: {
8929     MCInst TmpInst;
8930     // Shuffle the operands around so the lane index operand is in the
8931     // right place.
8932     unsigned Spacing;
8933     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8934     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8935     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8936     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8937     TmpInst.addOperand(Inst.getOperand(4)); // Rm
8938     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8939     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8940                                             Spacing));
8941     TmpInst.addOperand(Inst.getOperand(1)); // lane
8942     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
8943     TmpInst.addOperand(Inst.getOperand(6));
8944     Inst = TmpInst;
8945     return true;
8946   }
8947 
8948   case ARM::VST3LNdWB_register_Asm_8:
8949   case ARM::VST3LNdWB_register_Asm_16:
8950   case ARM::VST3LNdWB_register_Asm_32:
8951   case ARM::VST3LNqWB_register_Asm_16:
8952   case ARM::VST3LNqWB_register_Asm_32: {
8953     MCInst TmpInst;
8954     // Shuffle the operands around so the lane index operand is in the
8955     // right place.
8956     unsigned Spacing;
8957     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8958     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8959     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8960     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8961     TmpInst.addOperand(Inst.getOperand(4)); // Rm
8962     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8963     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8964                                             Spacing));
8965     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8966                                             Spacing * 2));
8967     TmpInst.addOperand(Inst.getOperand(1)); // lane
8968     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
8969     TmpInst.addOperand(Inst.getOperand(6));
8970     Inst = TmpInst;
8971     return true;
8972   }
8973 
8974   case ARM::VST4LNdWB_register_Asm_8:
8975   case ARM::VST4LNdWB_register_Asm_16:
8976   case ARM::VST4LNdWB_register_Asm_32:
8977   case ARM::VST4LNqWB_register_Asm_16:
8978   case ARM::VST4LNqWB_register_Asm_32: {
8979     MCInst TmpInst;
8980     // Shuffle the operands around so the lane index operand is in the
8981     // right place.
8982     unsigned Spacing;
8983     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8984     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8985     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8986     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8987     TmpInst.addOperand(Inst.getOperand(4)); // Rm
8988     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8989     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8990                                             Spacing));
8991     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8992                                             Spacing * 2));
8993     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8994                                             Spacing * 3));
8995     TmpInst.addOperand(Inst.getOperand(1)); // lane
8996     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
8997     TmpInst.addOperand(Inst.getOperand(6));
8998     Inst = TmpInst;
8999     return true;
9000   }
9001 
9002   case ARM::VST1LNdWB_fixed_Asm_8:
9003   case ARM::VST1LNdWB_fixed_Asm_16:
9004   case ARM::VST1LNdWB_fixed_Asm_32: {
9005     MCInst TmpInst;
9006     // Shuffle the operands around so the lane index operand is in the
9007     // right place.
9008     unsigned Spacing;
9009     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9010     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
9011     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9012     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9013     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9014     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9015     TmpInst.addOperand(Inst.getOperand(1)); // lane
9016     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9017     TmpInst.addOperand(Inst.getOperand(5));
9018     Inst = TmpInst;
9019     return true;
9020   }
9021 
9022   case ARM::VST2LNdWB_fixed_Asm_8:
9023   case ARM::VST2LNdWB_fixed_Asm_16:
9024   case ARM::VST2LNdWB_fixed_Asm_32:
9025   case ARM::VST2LNqWB_fixed_Asm_16:
9026   case ARM::VST2LNqWB_fixed_Asm_32: {
9027     MCInst TmpInst;
9028     // Shuffle the operands around so the lane index operand is in the
9029     // right place.
9030     unsigned Spacing;
9031     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9032     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
9033     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9034     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9035     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9036     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9037     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9038                                             Spacing));
9039     TmpInst.addOperand(Inst.getOperand(1)); // lane
9040     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9041     TmpInst.addOperand(Inst.getOperand(5));
9042     Inst = TmpInst;
9043     return true;
9044   }
9045 
9046   case ARM::VST3LNdWB_fixed_Asm_8:
9047   case ARM::VST3LNdWB_fixed_Asm_16:
9048   case ARM::VST3LNdWB_fixed_Asm_32:
9049   case ARM::VST3LNqWB_fixed_Asm_16:
9050   case ARM::VST3LNqWB_fixed_Asm_32: {
9051     MCInst TmpInst;
9052     // Shuffle the operands around so the lane index operand is in the
9053     // right place.
9054     unsigned Spacing;
9055     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9056     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
9057     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9058     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9059     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9060     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9061     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9062                                             Spacing));
9063     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9064                                             Spacing * 2));
9065     TmpInst.addOperand(Inst.getOperand(1)); // lane
9066     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9067     TmpInst.addOperand(Inst.getOperand(5));
9068     Inst = TmpInst;
9069     return true;
9070   }
9071 
9072   case ARM::VST4LNdWB_fixed_Asm_8:
9073   case ARM::VST4LNdWB_fixed_Asm_16:
9074   case ARM::VST4LNdWB_fixed_Asm_32:
9075   case ARM::VST4LNqWB_fixed_Asm_16:
9076   case ARM::VST4LNqWB_fixed_Asm_32: {
9077     MCInst TmpInst;
9078     // Shuffle the operands around so the lane index operand is in the
9079     // right place.
9080     unsigned Spacing;
9081     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9082     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
9083     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9084     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9085     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9086     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9087     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9088                                             Spacing));
9089     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9090                                             Spacing * 2));
9091     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9092                                             Spacing * 3));
9093     TmpInst.addOperand(Inst.getOperand(1)); // lane
9094     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9095     TmpInst.addOperand(Inst.getOperand(5));
9096     Inst = TmpInst;
9097     return true;
9098   }
9099 
9100   case ARM::VST1LNdAsm_8:
9101   case ARM::VST1LNdAsm_16:
9102   case ARM::VST1LNdAsm_32: {
9103     MCInst TmpInst;
9104     // Shuffle the operands around so the lane index operand is in the
9105     // right place.
9106     unsigned Spacing;
9107     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9108     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9109     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9110     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9111     TmpInst.addOperand(Inst.getOperand(1)); // lane
9112     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9113     TmpInst.addOperand(Inst.getOperand(5));
9114     Inst = TmpInst;
9115     return true;
9116   }
9117 
9118   case ARM::VST2LNdAsm_8:
9119   case ARM::VST2LNdAsm_16:
9120   case ARM::VST2LNdAsm_32:
9121   case ARM::VST2LNqAsm_16:
9122   case ARM::VST2LNqAsm_32: {
9123     MCInst TmpInst;
9124     // Shuffle the operands around so the lane index operand is in the
9125     // right place.
9126     unsigned Spacing;
9127     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9128     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9129     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9130     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9131     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9132                                             Spacing));
9133     TmpInst.addOperand(Inst.getOperand(1)); // lane
9134     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9135     TmpInst.addOperand(Inst.getOperand(5));
9136     Inst = TmpInst;
9137     return true;
9138   }
9139 
9140   case ARM::VST3LNdAsm_8:
9141   case ARM::VST3LNdAsm_16:
9142   case ARM::VST3LNdAsm_32:
9143   case ARM::VST3LNqAsm_16:
9144   case ARM::VST3LNqAsm_32: {
9145     MCInst TmpInst;
9146     // Shuffle the operands around so the lane index operand is in the
9147     // right place.
9148     unsigned Spacing;
9149     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9150     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9151     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9152     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9153     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9154                                             Spacing));
9155     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9156                                             Spacing * 2));
9157     TmpInst.addOperand(Inst.getOperand(1)); // lane
9158     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9159     TmpInst.addOperand(Inst.getOperand(5));
9160     Inst = TmpInst;
9161     return true;
9162   }
9163 
9164   case ARM::VST4LNdAsm_8:
9165   case ARM::VST4LNdAsm_16:
9166   case ARM::VST4LNdAsm_32:
9167   case ARM::VST4LNqAsm_16:
9168   case ARM::VST4LNqAsm_32: {
9169     MCInst TmpInst;
9170     // Shuffle the operands around so the lane index operand is in the
9171     // right place.
9172     unsigned Spacing;
9173     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9174     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9175     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9176     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9177     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9178                                             Spacing));
9179     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9180                                             Spacing * 2));
9181     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9182                                             Spacing * 3));
9183     TmpInst.addOperand(Inst.getOperand(1)); // lane
9184     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9185     TmpInst.addOperand(Inst.getOperand(5));
9186     Inst = TmpInst;
9187     return true;
9188   }
9189 
9190   // Handle NEON VLD complex aliases.
9191   case ARM::VLD1LNdWB_register_Asm_8:
9192   case ARM::VLD1LNdWB_register_Asm_16:
9193   case ARM::VLD1LNdWB_register_Asm_32: {
9194     MCInst TmpInst;
9195     // Shuffle the operands around so the lane index operand is in the
9196     // right place.
9197     unsigned Spacing;
9198     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9199     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9200     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
9201     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9202     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9203     TmpInst.addOperand(Inst.getOperand(4)); // Rm
9204     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
9205     TmpInst.addOperand(Inst.getOperand(1)); // lane
9206     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
9207     TmpInst.addOperand(Inst.getOperand(6));
9208     Inst = TmpInst;
9209     return true;
9210   }
9211 
9212   case ARM::VLD2LNdWB_register_Asm_8:
9213   case ARM::VLD2LNdWB_register_Asm_16:
9214   case ARM::VLD2LNdWB_register_Asm_32:
9215   case ARM::VLD2LNqWB_register_Asm_16:
9216   case ARM::VLD2LNqWB_register_Asm_32: {
9217     MCInst TmpInst;
9218     // Shuffle the operands around so the lane index operand is in the
9219     // right place.
9220     unsigned Spacing;
9221     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9222     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9223     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9224                                             Spacing));
9225     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
9226     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9227     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9228     TmpInst.addOperand(Inst.getOperand(4)); // Rm
9229     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
9230     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9231                                             Spacing));
9232     TmpInst.addOperand(Inst.getOperand(1)); // lane
9233     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
9234     TmpInst.addOperand(Inst.getOperand(6));
9235     Inst = TmpInst;
9236     return true;
9237   }
9238 
9239   case ARM::VLD3LNdWB_register_Asm_8:
9240   case ARM::VLD3LNdWB_register_Asm_16:
9241   case ARM::VLD3LNdWB_register_Asm_32:
9242   case ARM::VLD3LNqWB_register_Asm_16:
9243   case ARM::VLD3LNqWB_register_Asm_32: {
9244     MCInst TmpInst;
9245     // Shuffle the operands around so the lane index operand is in the
9246     // right place.
9247     unsigned Spacing;
9248     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9249     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9250     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9251                                             Spacing));
9252     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9253                                             Spacing * 2));
9254     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
9255     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9256     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9257     TmpInst.addOperand(Inst.getOperand(4)); // Rm
9258     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
9259     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9260                                             Spacing));
9261     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9262                                             Spacing * 2));
9263     TmpInst.addOperand(Inst.getOperand(1)); // lane
9264     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
9265     TmpInst.addOperand(Inst.getOperand(6));
9266     Inst = TmpInst;
9267     return true;
9268   }
9269 
9270   case ARM::VLD4LNdWB_register_Asm_8:
9271   case ARM::VLD4LNdWB_register_Asm_16:
9272   case ARM::VLD4LNdWB_register_Asm_32:
9273   case ARM::VLD4LNqWB_register_Asm_16:
9274   case ARM::VLD4LNqWB_register_Asm_32: {
9275     MCInst TmpInst;
9276     // Shuffle the operands around so the lane index operand is in the
9277     // right place.
9278     unsigned Spacing;
9279     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9280     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9281     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9282                                             Spacing));
9283     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9284                                             Spacing * 2));
9285     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9286                                             Spacing * 3));
9287     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
9288     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9289     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9290     TmpInst.addOperand(Inst.getOperand(4)); // Rm
9291     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
9292     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9293                                             Spacing));
9294     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9295                                             Spacing * 2));
9296     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9297                                             Spacing * 3));
9298     TmpInst.addOperand(Inst.getOperand(1)); // lane
9299     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
9300     TmpInst.addOperand(Inst.getOperand(6));
9301     Inst = TmpInst;
9302     return true;
9303   }
9304 
9305   case ARM::VLD1LNdWB_fixed_Asm_8:
9306   case ARM::VLD1LNdWB_fixed_Asm_16:
9307   case ARM::VLD1LNdWB_fixed_Asm_32: {
9308     MCInst TmpInst;
9309     // Shuffle the operands around so the lane index operand is in the
9310     // right place.
9311     unsigned Spacing;
9312     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9313     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9314     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
9315     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9316     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9317     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9318     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
9319     TmpInst.addOperand(Inst.getOperand(1)); // lane
9320     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9321     TmpInst.addOperand(Inst.getOperand(5));
9322     Inst = TmpInst;
9323     return true;
9324   }
9325 
9326   case ARM::VLD2LNdWB_fixed_Asm_8:
9327   case ARM::VLD2LNdWB_fixed_Asm_16:
9328   case ARM::VLD2LNdWB_fixed_Asm_32:
9329   case ARM::VLD2LNqWB_fixed_Asm_16:
9330   case ARM::VLD2LNqWB_fixed_Asm_32: {
9331     MCInst TmpInst;
9332     // Shuffle the operands around so the lane index operand is in the
9333     // right place.
9334     unsigned Spacing;
9335     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9336     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9337     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9338                                             Spacing));
9339     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
9340     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9341     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9342     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9343     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
9344     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9345                                             Spacing));
9346     TmpInst.addOperand(Inst.getOperand(1)); // lane
9347     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9348     TmpInst.addOperand(Inst.getOperand(5));
9349     Inst = TmpInst;
9350     return true;
9351   }
9352 
9353   case ARM::VLD3LNdWB_fixed_Asm_8:
9354   case ARM::VLD3LNdWB_fixed_Asm_16:
9355   case ARM::VLD3LNdWB_fixed_Asm_32:
9356   case ARM::VLD3LNqWB_fixed_Asm_16:
9357   case ARM::VLD3LNqWB_fixed_Asm_32: {
9358     MCInst TmpInst;
9359     // Shuffle the operands around so the lane index operand is in the
9360     // right place.
9361     unsigned Spacing;
9362     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9363     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9364     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9365                                             Spacing));
9366     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9367                                             Spacing * 2));
9368     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
9369     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9370     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9371     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9372     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
9373     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9374                                             Spacing));
9375     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9376                                             Spacing * 2));
9377     TmpInst.addOperand(Inst.getOperand(1)); // lane
9378     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9379     TmpInst.addOperand(Inst.getOperand(5));
9380     Inst = TmpInst;
9381     return true;
9382   }
9383 
9384   case ARM::VLD4LNdWB_fixed_Asm_8:
9385   case ARM::VLD4LNdWB_fixed_Asm_16:
9386   case ARM::VLD4LNdWB_fixed_Asm_32:
9387   case ARM::VLD4LNqWB_fixed_Asm_16:
9388   case ARM::VLD4LNqWB_fixed_Asm_32: {
9389     MCInst TmpInst;
9390     // Shuffle the operands around so the lane index operand is in the
9391     // right place.
9392     unsigned Spacing;
9393     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9394     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9395     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9396                                             Spacing));
9397     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9398                                             Spacing * 2));
9399     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9400                                             Spacing * 3));
9401     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
9402     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9403     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9404     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9405     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
9406     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9407                                             Spacing));
9408     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9409                                             Spacing * 2));
9410     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9411                                             Spacing * 3));
9412     TmpInst.addOperand(Inst.getOperand(1)); // lane
9413     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9414     TmpInst.addOperand(Inst.getOperand(5));
9415     Inst = TmpInst;
9416     return true;
9417   }
9418 
9419   case ARM::VLD1LNdAsm_8:
9420   case ARM::VLD1LNdAsm_16:
9421   case ARM::VLD1LNdAsm_32: {
9422     MCInst TmpInst;
9423     // Shuffle the operands around so the lane index operand is in the
9424     // right place.
9425     unsigned Spacing;
9426     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9427     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9428     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9429     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9430     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
9431     TmpInst.addOperand(Inst.getOperand(1)); // lane
9432     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9433     TmpInst.addOperand(Inst.getOperand(5));
9434     Inst = TmpInst;
9435     return true;
9436   }
9437 
9438   case ARM::VLD2LNdAsm_8:
9439   case ARM::VLD2LNdAsm_16:
9440   case ARM::VLD2LNdAsm_32:
9441   case ARM::VLD2LNqAsm_16:
9442   case ARM::VLD2LNqAsm_32: {
9443     MCInst TmpInst;
9444     // Shuffle the operands around so the lane index operand is in the
9445     // right place.
9446     unsigned Spacing;
9447     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9448     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9449     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9450                                             Spacing));
9451     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9452     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9453     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
9454     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9455                                             Spacing));
9456     TmpInst.addOperand(Inst.getOperand(1)); // lane
9457     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9458     TmpInst.addOperand(Inst.getOperand(5));
9459     Inst = TmpInst;
9460     return true;
9461   }
9462 
9463   case ARM::VLD3LNdAsm_8:
9464   case ARM::VLD3LNdAsm_16:
9465   case ARM::VLD3LNdAsm_32:
9466   case ARM::VLD3LNqAsm_16:
9467   case ARM::VLD3LNqAsm_32: {
9468     MCInst TmpInst;
9469     // Shuffle the operands around so the lane index operand is in the
9470     // right place.
9471     unsigned Spacing;
9472     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9473     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9474     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9475                                             Spacing));
9476     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9477                                             Spacing * 2));
9478     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9479     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9480     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
9481     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9482                                             Spacing));
9483     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9484                                             Spacing * 2));
9485     TmpInst.addOperand(Inst.getOperand(1)); // lane
9486     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9487     TmpInst.addOperand(Inst.getOperand(5));
9488     Inst = TmpInst;
9489     return true;
9490   }
9491 
9492   case ARM::VLD4LNdAsm_8:
9493   case ARM::VLD4LNdAsm_16:
9494   case ARM::VLD4LNdAsm_32:
9495   case ARM::VLD4LNqAsm_16:
9496   case ARM::VLD4LNqAsm_32: {
9497     MCInst TmpInst;
9498     // Shuffle the operands around so the lane index operand is in the
9499     // right place.
9500     unsigned Spacing;
9501     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9502     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9503     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9504                                             Spacing));
9505     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9506                                             Spacing * 2));
9507     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9508                                             Spacing * 3));
9509     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9510     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9511     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
9512     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9513                                             Spacing));
9514     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9515                                             Spacing * 2));
9516     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9517                                             Spacing * 3));
9518     TmpInst.addOperand(Inst.getOperand(1)); // lane
9519     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9520     TmpInst.addOperand(Inst.getOperand(5));
9521     Inst = TmpInst;
9522     return true;
9523   }
9524 
9525   // VLD3DUP single 3-element structure to all lanes instructions.
9526   case ARM::VLD3DUPdAsm_8:
9527   case ARM::VLD3DUPdAsm_16:
9528   case ARM::VLD3DUPdAsm_32:
9529   case ARM::VLD3DUPqAsm_8:
9530   case ARM::VLD3DUPqAsm_16:
9531   case ARM::VLD3DUPqAsm_32: {
9532     MCInst TmpInst;
9533     unsigned Spacing;
9534     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9535     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9536     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9537                                             Spacing));
9538     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9539                                             Spacing * 2));
9540     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9541     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9542     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9543     TmpInst.addOperand(Inst.getOperand(4));
9544     Inst = TmpInst;
9545     return true;
9546   }
9547 
9548   case ARM::VLD3DUPdWB_fixed_Asm_8:
9549   case ARM::VLD3DUPdWB_fixed_Asm_16:
9550   case ARM::VLD3DUPdWB_fixed_Asm_32:
9551   case ARM::VLD3DUPqWB_fixed_Asm_8:
9552   case ARM::VLD3DUPqWB_fixed_Asm_16:
9553   case ARM::VLD3DUPqWB_fixed_Asm_32: {
9554     MCInst TmpInst;
9555     unsigned Spacing;
9556     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9557     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9558     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9559                                             Spacing));
9560     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9561                                             Spacing * 2));
9562     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9563     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9564     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9565     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9566     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9567     TmpInst.addOperand(Inst.getOperand(4));
9568     Inst = TmpInst;
9569     return true;
9570   }
9571 
9572   case ARM::VLD3DUPdWB_register_Asm_8:
9573   case ARM::VLD3DUPdWB_register_Asm_16:
9574   case ARM::VLD3DUPdWB_register_Asm_32:
9575   case ARM::VLD3DUPqWB_register_Asm_8:
9576   case ARM::VLD3DUPqWB_register_Asm_16:
9577   case ARM::VLD3DUPqWB_register_Asm_32: {
9578     MCInst TmpInst;
9579     unsigned Spacing;
9580     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9581     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9582     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9583                                             Spacing));
9584     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9585                                             Spacing * 2));
9586     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9587     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9588     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9589     TmpInst.addOperand(Inst.getOperand(3)); // Rm
9590     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9591     TmpInst.addOperand(Inst.getOperand(5));
9592     Inst = TmpInst;
9593     return true;
9594   }
9595 
9596   // VLD3 multiple 3-element structure instructions.
9597   case ARM::VLD3dAsm_8:
9598   case ARM::VLD3dAsm_16:
9599   case ARM::VLD3dAsm_32:
9600   case ARM::VLD3qAsm_8:
9601   case ARM::VLD3qAsm_16:
9602   case ARM::VLD3qAsm_32: {
9603     MCInst TmpInst;
9604     unsigned Spacing;
9605     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9606     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9607     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9608                                             Spacing));
9609     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9610                                             Spacing * 2));
9611     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9612     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9613     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9614     TmpInst.addOperand(Inst.getOperand(4));
9615     Inst = TmpInst;
9616     return true;
9617   }
9618 
9619   case ARM::VLD3dWB_fixed_Asm_8:
9620   case ARM::VLD3dWB_fixed_Asm_16:
9621   case ARM::VLD3dWB_fixed_Asm_32:
9622   case ARM::VLD3qWB_fixed_Asm_8:
9623   case ARM::VLD3qWB_fixed_Asm_16:
9624   case ARM::VLD3qWB_fixed_Asm_32: {
9625     MCInst TmpInst;
9626     unsigned Spacing;
9627     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9628     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9629     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9630                                             Spacing));
9631     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9632                                             Spacing * 2));
9633     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9634     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9635     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9636     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9637     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9638     TmpInst.addOperand(Inst.getOperand(4));
9639     Inst = TmpInst;
9640     return true;
9641   }
9642 
9643   case ARM::VLD3dWB_register_Asm_8:
9644   case ARM::VLD3dWB_register_Asm_16:
9645   case ARM::VLD3dWB_register_Asm_32:
9646   case ARM::VLD3qWB_register_Asm_8:
9647   case ARM::VLD3qWB_register_Asm_16:
9648   case ARM::VLD3qWB_register_Asm_32: {
9649     MCInst TmpInst;
9650     unsigned Spacing;
9651     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9652     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9653     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9654                                             Spacing));
9655     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9656                                             Spacing * 2));
9657     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9658     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9659     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9660     TmpInst.addOperand(Inst.getOperand(3)); // Rm
9661     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9662     TmpInst.addOperand(Inst.getOperand(5));
9663     Inst = TmpInst;
9664     return true;
9665   }
9666 
9667   // VLD4DUP single 3-element structure to all lanes instructions.
9668   case ARM::VLD4DUPdAsm_8:
9669   case ARM::VLD4DUPdAsm_16:
9670   case ARM::VLD4DUPdAsm_32:
9671   case ARM::VLD4DUPqAsm_8:
9672   case ARM::VLD4DUPqAsm_16:
9673   case ARM::VLD4DUPqAsm_32: {
9674     MCInst TmpInst;
9675     unsigned Spacing;
9676     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9677     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9678     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9679                                             Spacing));
9680     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9681                                             Spacing * 2));
9682     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9683                                             Spacing * 3));
9684     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9685     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9686     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9687     TmpInst.addOperand(Inst.getOperand(4));
9688     Inst = TmpInst;
9689     return true;
9690   }
9691 
9692   case ARM::VLD4DUPdWB_fixed_Asm_8:
9693   case ARM::VLD4DUPdWB_fixed_Asm_16:
9694   case ARM::VLD4DUPdWB_fixed_Asm_32:
9695   case ARM::VLD4DUPqWB_fixed_Asm_8:
9696   case ARM::VLD4DUPqWB_fixed_Asm_16:
9697   case ARM::VLD4DUPqWB_fixed_Asm_32: {
9698     MCInst TmpInst;
9699     unsigned Spacing;
9700     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9701     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9702     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9703                                             Spacing));
9704     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9705                                             Spacing * 2));
9706     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9707                                             Spacing * 3));
9708     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9709     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9710     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9711     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9712     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9713     TmpInst.addOperand(Inst.getOperand(4));
9714     Inst = TmpInst;
9715     return true;
9716   }
9717 
9718   case ARM::VLD4DUPdWB_register_Asm_8:
9719   case ARM::VLD4DUPdWB_register_Asm_16:
9720   case ARM::VLD4DUPdWB_register_Asm_32:
9721   case ARM::VLD4DUPqWB_register_Asm_8:
9722   case ARM::VLD4DUPqWB_register_Asm_16:
9723   case ARM::VLD4DUPqWB_register_Asm_32: {
9724     MCInst TmpInst;
9725     unsigned Spacing;
9726     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9727     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9728     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9729                                             Spacing));
9730     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9731                                             Spacing * 2));
9732     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9733                                             Spacing * 3));
9734     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9735     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9736     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9737     TmpInst.addOperand(Inst.getOperand(3)); // Rm
9738     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9739     TmpInst.addOperand(Inst.getOperand(5));
9740     Inst = TmpInst;
9741     return true;
9742   }
9743 
9744   // VLD4 multiple 4-element structure instructions.
9745   case ARM::VLD4dAsm_8:
9746   case ARM::VLD4dAsm_16:
9747   case ARM::VLD4dAsm_32:
9748   case ARM::VLD4qAsm_8:
9749   case ARM::VLD4qAsm_16:
9750   case ARM::VLD4qAsm_32: {
9751     MCInst TmpInst;
9752     unsigned Spacing;
9753     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9754     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9755     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9756                                             Spacing));
9757     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9758                                             Spacing * 2));
9759     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9760                                             Spacing * 3));
9761     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9762     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9763     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9764     TmpInst.addOperand(Inst.getOperand(4));
9765     Inst = TmpInst;
9766     return true;
9767   }
9768 
9769   case ARM::VLD4dWB_fixed_Asm_8:
9770   case ARM::VLD4dWB_fixed_Asm_16:
9771   case ARM::VLD4dWB_fixed_Asm_32:
9772   case ARM::VLD4qWB_fixed_Asm_8:
9773   case ARM::VLD4qWB_fixed_Asm_16:
9774   case ARM::VLD4qWB_fixed_Asm_32: {
9775     MCInst TmpInst;
9776     unsigned Spacing;
9777     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9778     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9779     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9780                                             Spacing));
9781     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9782                                             Spacing * 2));
9783     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9784                                             Spacing * 3));
9785     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9786     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9787     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9788     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9789     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9790     TmpInst.addOperand(Inst.getOperand(4));
9791     Inst = TmpInst;
9792     return true;
9793   }
9794 
9795   case ARM::VLD4dWB_register_Asm_8:
9796   case ARM::VLD4dWB_register_Asm_16:
9797   case ARM::VLD4dWB_register_Asm_32:
9798   case ARM::VLD4qWB_register_Asm_8:
9799   case ARM::VLD4qWB_register_Asm_16:
9800   case ARM::VLD4qWB_register_Asm_32: {
9801     MCInst TmpInst;
9802     unsigned Spacing;
9803     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9804     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9805     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9806                                             Spacing));
9807     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9808                                             Spacing * 2));
9809     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9810                                             Spacing * 3));
9811     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9812     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9813     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9814     TmpInst.addOperand(Inst.getOperand(3)); // Rm
9815     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9816     TmpInst.addOperand(Inst.getOperand(5));
9817     Inst = TmpInst;
9818     return true;
9819   }
9820 
9821   // VST3 multiple 3-element structure instructions.
9822   case ARM::VST3dAsm_8:
9823   case ARM::VST3dAsm_16:
9824   case ARM::VST3dAsm_32:
9825   case ARM::VST3qAsm_8:
9826   case ARM::VST3qAsm_16:
9827   case ARM::VST3qAsm_32: {
9828     MCInst TmpInst;
9829     unsigned Spacing;
9830     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9831     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9832     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9833     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9834     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9835                                             Spacing));
9836     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9837                                             Spacing * 2));
9838     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9839     TmpInst.addOperand(Inst.getOperand(4));
9840     Inst = TmpInst;
9841     return true;
9842   }
9843 
9844   case ARM::VST3dWB_fixed_Asm_8:
9845   case ARM::VST3dWB_fixed_Asm_16:
9846   case ARM::VST3dWB_fixed_Asm_32:
9847   case ARM::VST3qWB_fixed_Asm_8:
9848   case ARM::VST3qWB_fixed_Asm_16:
9849   case ARM::VST3qWB_fixed_Asm_32: {
9850     MCInst TmpInst;
9851     unsigned Spacing;
9852     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9853     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9854     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9855     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9856     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9857     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9858     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9859                                             Spacing));
9860     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9861                                             Spacing * 2));
9862     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9863     TmpInst.addOperand(Inst.getOperand(4));
9864     Inst = TmpInst;
9865     return true;
9866   }
9867 
9868   case ARM::VST3dWB_register_Asm_8:
9869   case ARM::VST3dWB_register_Asm_16:
9870   case ARM::VST3dWB_register_Asm_32:
9871   case ARM::VST3qWB_register_Asm_8:
9872   case ARM::VST3qWB_register_Asm_16:
9873   case ARM::VST3qWB_register_Asm_32: {
9874     MCInst TmpInst;
9875     unsigned Spacing;
9876     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9877     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9878     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9879     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9880     TmpInst.addOperand(Inst.getOperand(3)); // Rm
9881     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9882     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9883                                             Spacing));
9884     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9885                                             Spacing * 2));
9886     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9887     TmpInst.addOperand(Inst.getOperand(5));
9888     Inst = TmpInst;
9889     return true;
9890   }
9891 
9892   // VST4 multiple 3-element structure instructions.
9893   case ARM::VST4dAsm_8:
9894   case ARM::VST4dAsm_16:
9895   case ARM::VST4dAsm_32:
9896   case ARM::VST4qAsm_8:
9897   case ARM::VST4qAsm_16:
9898   case ARM::VST4qAsm_32: {
9899     MCInst TmpInst;
9900     unsigned Spacing;
9901     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9902     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9903     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9904     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9905     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9906                                             Spacing));
9907     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9908                                             Spacing * 2));
9909     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9910                                             Spacing * 3));
9911     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9912     TmpInst.addOperand(Inst.getOperand(4));
9913     Inst = TmpInst;
9914     return true;
9915   }
9916 
9917   case ARM::VST4dWB_fixed_Asm_8:
9918   case ARM::VST4dWB_fixed_Asm_16:
9919   case ARM::VST4dWB_fixed_Asm_32:
9920   case ARM::VST4qWB_fixed_Asm_8:
9921   case ARM::VST4qWB_fixed_Asm_16:
9922   case ARM::VST4qWB_fixed_Asm_32: {
9923     MCInst TmpInst;
9924     unsigned Spacing;
9925     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9926     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9927     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9928     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9929     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9930     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9931     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9932                                             Spacing));
9933     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9934                                             Spacing * 2));
9935     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9936                                             Spacing * 3));
9937     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9938     TmpInst.addOperand(Inst.getOperand(4));
9939     Inst = TmpInst;
9940     return true;
9941   }
9942 
9943   case ARM::VST4dWB_register_Asm_8:
9944   case ARM::VST4dWB_register_Asm_16:
9945   case ARM::VST4dWB_register_Asm_32:
9946   case ARM::VST4qWB_register_Asm_8:
9947   case ARM::VST4qWB_register_Asm_16:
9948   case ARM::VST4qWB_register_Asm_32: {
9949     MCInst TmpInst;
9950     unsigned Spacing;
9951     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9952     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9953     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9954     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9955     TmpInst.addOperand(Inst.getOperand(3)); // Rm
9956     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9957     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9958                                             Spacing));
9959     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9960                                             Spacing * 2));
9961     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9962                                             Spacing * 3));
9963     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9964     TmpInst.addOperand(Inst.getOperand(5));
9965     Inst = TmpInst;
9966     return true;
9967   }
9968 
9969   // Handle encoding choice for the shift-immediate instructions.
9970   case ARM::t2LSLri:
9971   case ARM::t2LSRri:
9972   case ARM::t2ASRri:
9973     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
9974         isARMLowRegister(Inst.getOperand(1).getReg()) &&
9975         Inst.getOperand(5).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
9976         !HasWideQualifier) {
9977       unsigned NewOpc;
9978       switch (Inst.getOpcode()) {
9979       default: llvm_unreachable("unexpected opcode");
9980       case ARM::t2LSLri: NewOpc = ARM::tLSLri; break;
9981       case ARM::t2LSRri: NewOpc = ARM::tLSRri; break;
9982       case ARM::t2ASRri: NewOpc = ARM::tASRri; break;
9983       }
9984       // The Thumb1 operands aren't in the same order. Awesome, eh?
9985       MCInst TmpInst;
9986       TmpInst.setOpcode(NewOpc);
9987       TmpInst.addOperand(Inst.getOperand(0));
9988       TmpInst.addOperand(Inst.getOperand(5));
9989       TmpInst.addOperand(Inst.getOperand(1));
9990       TmpInst.addOperand(Inst.getOperand(2));
9991       TmpInst.addOperand(Inst.getOperand(3));
9992       TmpInst.addOperand(Inst.getOperand(4));
9993       Inst = TmpInst;
9994       return true;
9995     }
9996     return false;
9997 
9998   // Handle the Thumb2 mode MOV complex aliases.
9999   case ARM::t2MOVsr:
10000   case ARM::t2MOVSsr: {
10001     // Which instruction to expand to depends on the CCOut operand and
10002     // whether we're in an IT block if the register operands are low
10003     // registers.
10004     bool isNarrow = false;
10005     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
10006         isARMLowRegister(Inst.getOperand(1).getReg()) &&
10007         isARMLowRegister(Inst.getOperand(2).getReg()) &&
10008         Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() &&
10009         inITBlock() == (Inst.getOpcode() == ARM::t2MOVsr) &&
10010         !HasWideQualifier)
10011       isNarrow = true;
10012     MCInst TmpInst;
10013     unsigned newOpc;
10014     switch(ARM_AM::getSORegShOp(Inst.getOperand(3).getImm())) {
10015     default: llvm_unreachable("unexpected opcode!");
10016     case ARM_AM::asr: newOpc = isNarrow ? ARM::tASRrr : ARM::t2ASRrr; break;
10017     case ARM_AM::lsr: newOpc = isNarrow ? ARM::tLSRrr : ARM::t2LSRrr; break;
10018     case ARM_AM::lsl: newOpc = isNarrow ? ARM::tLSLrr : ARM::t2LSLrr; break;
10019     case ARM_AM::ror: newOpc = isNarrow ? ARM::tROR   : ARM::t2RORrr; break;
10020     }
10021     TmpInst.setOpcode(newOpc);
10022     TmpInst.addOperand(Inst.getOperand(0)); // Rd
10023     if (isNarrow)
10024       TmpInst.addOperand(MCOperand::createReg(
10025           Inst.getOpcode() == ARM::t2MOVSsr ? ARM::CPSR : 0));
10026     TmpInst.addOperand(Inst.getOperand(1)); // Rn
10027     TmpInst.addOperand(Inst.getOperand(2)); // Rm
10028     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
10029     TmpInst.addOperand(Inst.getOperand(5));
10030     if (!isNarrow)
10031       TmpInst.addOperand(MCOperand::createReg(
10032           Inst.getOpcode() == ARM::t2MOVSsr ? ARM::CPSR : 0));
10033     Inst = TmpInst;
10034     return true;
10035   }
10036   case ARM::t2MOVsi:
10037   case ARM::t2MOVSsi: {
10038     // Which instruction to expand to depends on the CCOut operand and
10039     // whether we're in an IT block if the register operands are low
10040     // registers.
10041     bool isNarrow = false;
10042     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
10043         isARMLowRegister(Inst.getOperand(1).getReg()) &&
10044         inITBlock() == (Inst.getOpcode() == ARM::t2MOVsi) &&
10045         !HasWideQualifier)
10046       isNarrow = true;
10047     MCInst TmpInst;
10048     unsigned newOpc;
10049     unsigned Shift = ARM_AM::getSORegShOp(Inst.getOperand(2).getImm());
10050     unsigned Amount = ARM_AM::getSORegOffset(Inst.getOperand(2).getImm());
10051     bool isMov = false;
10052     // MOV rd, rm, LSL #0 is actually a MOV instruction
10053     if (Shift == ARM_AM::lsl && Amount == 0) {
10054       isMov = true;
10055       // The 16-bit encoding of MOV rd, rm, LSL #N is explicitly encoding T2 of
10056       // MOV (register) in the ARMv8-A and ARMv8-M manuals, and immediate 0 is
10057       // unpredictable in an IT block so the 32-bit encoding T3 has to be used
10058       // instead.
10059       if (inITBlock()) {
10060         isNarrow = false;
10061       }
10062       newOpc = isNarrow ? ARM::tMOVSr : ARM::t2MOVr;
10063     } else {
10064       switch(Shift) {
10065       default: llvm_unreachable("unexpected opcode!");
10066       case ARM_AM::asr: newOpc = isNarrow ? ARM::tASRri : ARM::t2ASRri; break;
10067       case ARM_AM::lsr: newOpc = isNarrow ? ARM::tLSRri : ARM::t2LSRri; break;
10068       case ARM_AM::lsl: newOpc = isNarrow ? ARM::tLSLri : ARM::t2LSLri; break;
10069       case ARM_AM::ror: newOpc = ARM::t2RORri; isNarrow = false; break;
10070       case ARM_AM::rrx: isNarrow = false; newOpc = ARM::t2RRX; break;
10071       }
10072     }
10073     if (Amount == 32) Amount = 0;
10074     TmpInst.setOpcode(newOpc);
10075     TmpInst.addOperand(Inst.getOperand(0)); // Rd
10076     if (isNarrow && !isMov)
10077       TmpInst.addOperand(MCOperand::createReg(
10078           Inst.getOpcode() == ARM::t2MOVSsi ? ARM::CPSR : 0));
10079     TmpInst.addOperand(Inst.getOperand(1)); // Rn
10080     if (newOpc != ARM::t2RRX && !isMov)
10081       TmpInst.addOperand(MCOperand::createImm(Amount));
10082     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
10083     TmpInst.addOperand(Inst.getOperand(4));
10084     if (!isNarrow)
10085       TmpInst.addOperand(MCOperand::createReg(
10086           Inst.getOpcode() == ARM::t2MOVSsi ? ARM::CPSR : 0));
10087     Inst = TmpInst;
10088     return true;
10089   }
10090   // Handle the ARM mode MOV complex aliases.
10091   case ARM::ASRr:
10092   case ARM::LSRr:
10093   case ARM::LSLr:
10094   case ARM::RORr: {
10095     ARM_AM::ShiftOpc ShiftTy;
10096     switch(Inst.getOpcode()) {
10097     default: llvm_unreachable("unexpected opcode!");
10098     case ARM::ASRr: ShiftTy = ARM_AM::asr; break;
10099     case ARM::LSRr: ShiftTy = ARM_AM::lsr; break;
10100     case ARM::LSLr: ShiftTy = ARM_AM::lsl; break;
10101     case ARM::RORr: ShiftTy = ARM_AM::ror; break;
10102     }
10103     unsigned Shifter = ARM_AM::getSORegOpc(ShiftTy, 0);
10104     MCInst TmpInst;
10105     TmpInst.setOpcode(ARM::MOVsr);
10106     TmpInst.addOperand(Inst.getOperand(0)); // Rd
10107     TmpInst.addOperand(Inst.getOperand(1)); // Rn
10108     TmpInst.addOperand(Inst.getOperand(2)); // Rm
10109     TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
10110     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
10111     TmpInst.addOperand(Inst.getOperand(4));
10112     TmpInst.addOperand(Inst.getOperand(5)); // cc_out
10113     Inst = TmpInst;
10114     return true;
10115   }
10116   case ARM::ASRi:
10117   case ARM::LSRi:
10118   case ARM::LSLi:
10119   case ARM::RORi: {
10120     ARM_AM::ShiftOpc ShiftTy;
10121     switch(Inst.getOpcode()) {
10122     default: llvm_unreachable("unexpected opcode!");
10123     case ARM::ASRi: ShiftTy = ARM_AM::asr; break;
10124     case ARM::LSRi: ShiftTy = ARM_AM::lsr; break;
10125     case ARM::LSLi: ShiftTy = ARM_AM::lsl; break;
10126     case ARM::RORi: ShiftTy = ARM_AM::ror; break;
10127     }
10128     // A shift by zero is a plain MOVr, not a MOVsi.
10129     unsigned Amt = Inst.getOperand(2).getImm();
10130     unsigned Opc = Amt == 0 ? ARM::MOVr : ARM::MOVsi;
10131     // A shift by 32 should be encoded as 0 when permitted
10132     if (Amt == 32 && (ShiftTy == ARM_AM::lsr || ShiftTy == ARM_AM::asr))
10133       Amt = 0;
10134     unsigned Shifter = ARM_AM::getSORegOpc(ShiftTy, Amt);
10135     MCInst TmpInst;
10136     TmpInst.setOpcode(Opc);
10137     TmpInst.addOperand(Inst.getOperand(0)); // Rd
10138     TmpInst.addOperand(Inst.getOperand(1)); // Rn
10139     if (Opc == ARM::MOVsi)
10140       TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
10141     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
10142     TmpInst.addOperand(Inst.getOperand(4));
10143     TmpInst.addOperand(Inst.getOperand(5)); // cc_out
10144     Inst = TmpInst;
10145     return true;
10146   }
10147   case ARM::RRXi: {
10148     unsigned Shifter = ARM_AM::getSORegOpc(ARM_AM::rrx, 0);
10149     MCInst TmpInst;
10150     TmpInst.setOpcode(ARM::MOVsi);
10151     TmpInst.addOperand(Inst.getOperand(0)); // Rd
10152     TmpInst.addOperand(Inst.getOperand(1)); // Rn
10153     TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
10154     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
10155     TmpInst.addOperand(Inst.getOperand(3));
10156     TmpInst.addOperand(Inst.getOperand(4)); // cc_out
10157     Inst = TmpInst;
10158     return true;
10159   }
10160   case ARM::t2LDMIA_UPD: {
10161     // If this is a load of a single register, then we should use
10162     // a post-indexed LDR instruction instead, per the ARM ARM.
10163     if (Inst.getNumOperands() != 5)
10164       return false;
10165     MCInst TmpInst;
10166     TmpInst.setOpcode(ARM::t2LDR_POST);
10167     TmpInst.addOperand(Inst.getOperand(4)); // Rt
10168     TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
10169     TmpInst.addOperand(Inst.getOperand(1)); // Rn
10170     TmpInst.addOperand(MCOperand::createImm(4));
10171     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
10172     TmpInst.addOperand(Inst.getOperand(3));
10173     Inst = TmpInst;
10174     return true;
10175   }
10176   case ARM::t2STMDB_UPD: {
10177     // If this is a store of a single register, then we should use
10178     // a pre-indexed STR instruction instead, per the ARM ARM.
10179     if (Inst.getNumOperands() != 5)
10180       return false;
10181     MCInst TmpInst;
10182     TmpInst.setOpcode(ARM::t2STR_PRE);
10183     TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
10184     TmpInst.addOperand(Inst.getOperand(4)); // Rt
10185     TmpInst.addOperand(Inst.getOperand(1)); // Rn
10186     TmpInst.addOperand(MCOperand::createImm(-4));
10187     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
10188     TmpInst.addOperand(Inst.getOperand(3));
10189     Inst = TmpInst;
10190     return true;
10191   }
10192   case ARM::LDMIA_UPD:
10193     // If this is a load of a single register via a 'pop', then we should use
10194     // a post-indexed LDR instruction instead, per the ARM ARM.
10195     if (static_cast<ARMOperand &>(*Operands[0]).getToken() == "pop" &&
10196         Inst.getNumOperands() == 5) {
10197       MCInst TmpInst;
10198       TmpInst.setOpcode(ARM::LDR_POST_IMM);
10199       TmpInst.addOperand(Inst.getOperand(4)); // Rt
10200       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
10201       TmpInst.addOperand(Inst.getOperand(1)); // Rn
10202       TmpInst.addOperand(MCOperand::createReg(0));  // am2offset
10203       TmpInst.addOperand(MCOperand::createImm(4));
10204       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
10205       TmpInst.addOperand(Inst.getOperand(3));
10206       Inst = TmpInst;
10207       return true;
10208     }
10209     break;
10210   case ARM::STMDB_UPD:
10211     // If this is a store of a single register via a 'push', then we should use
10212     // a pre-indexed STR instruction instead, per the ARM ARM.
10213     if (static_cast<ARMOperand &>(*Operands[0]).getToken() == "push" &&
10214         Inst.getNumOperands() == 5) {
10215       MCInst TmpInst;
10216       TmpInst.setOpcode(ARM::STR_PRE_IMM);
10217       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
10218       TmpInst.addOperand(Inst.getOperand(4)); // Rt
10219       TmpInst.addOperand(Inst.getOperand(1)); // addrmode_imm12
10220       TmpInst.addOperand(MCOperand::createImm(-4));
10221       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
10222       TmpInst.addOperand(Inst.getOperand(3));
10223       Inst = TmpInst;
10224     }
10225     break;
10226   case ARM::t2ADDri12:
10227   case ARM::t2SUBri12:
10228   case ARM::t2ADDspImm12:
10229   case ARM::t2SUBspImm12: {
10230     // If the immediate fits for encoding T3 and the generic
10231     // mnemonic was used, encoding T3 is preferred.
10232     const StringRef Token = static_cast<ARMOperand &>(*Operands[0]).getToken();
10233     if ((Token != "add" && Token != "sub") ||
10234         ARM_AM::getT2SOImmVal(Inst.getOperand(2).getImm()) == -1)
10235       break;
10236     switch (Inst.getOpcode()) {
10237     case ARM::t2ADDri12:
10238       Inst.setOpcode(ARM::t2ADDri);
10239       break;
10240     case ARM::t2SUBri12:
10241       Inst.setOpcode(ARM::t2SUBri);
10242       break;
10243     case ARM::t2ADDspImm12:
10244       Inst.setOpcode(ARM::t2ADDspImm);
10245       break;
10246     case ARM::t2SUBspImm12:
10247       Inst.setOpcode(ARM::t2SUBspImm);
10248       break;
10249     }
10250 
10251     Inst.addOperand(MCOperand::createReg(0)); // cc_out
10252     return true;
10253   }
10254   case ARM::tADDi8:
10255     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
10256     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
10257     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
10258     // to encoding T1 if <Rd> is omitted."
10259     if ((unsigned)Inst.getOperand(3).getImm() < 8 && Operands.size() == 6) {
10260       Inst.setOpcode(ARM::tADDi3);
10261       return true;
10262     }
10263     break;
10264   case ARM::tSUBi8:
10265     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
10266     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
10267     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
10268     // to encoding T1 if <Rd> is omitted."
10269     if ((unsigned)Inst.getOperand(3).getImm() < 8 && Operands.size() == 6) {
10270       Inst.setOpcode(ARM::tSUBi3);
10271       return true;
10272     }
10273     break;
10274   case ARM::t2ADDri:
10275   case ARM::t2SUBri: {
10276     // If the destination and first source operand are the same, and
10277     // the flags are compatible with the current IT status, use encoding T2
10278     // instead of T3. For compatibility with the system 'as'. Make sure the
10279     // wide encoding wasn't explicit.
10280     if (Inst.getOperand(0).getReg() != Inst.getOperand(1).getReg() ||
10281         !isARMLowRegister(Inst.getOperand(0).getReg()) ||
10282         (Inst.getOperand(2).isImm() &&
10283          (unsigned)Inst.getOperand(2).getImm() > 255) ||
10284         Inst.getOperand(5).getReg() != (inITBlock() ? 0 : ARM::CPSR) ||
10285         HasWideQualifier)
10286       break;
10287     MCInst TmpInst;
10288     TmpInst.setOpcode(Inst.getOpcode() == ARM::t2ADDri ?
10289                       ARM::tADDi8 : ARM::tSUBi8);
10290     TmpInst.addOperand(Inst.getOperand(0));
10291     TmpInst.addOperand(Inst.getOperand(5));
10292     TmpInst.addOperand(Inst.getOperand(0));
10293     TmpInst.addOperand(Inst.getOperand(2));
10294     TmpInst.addOperand(Inst.getOperand(3));
10295     TmpInst.addOperand(Inst.getOperand(4));
10296     Inst = TmpInst;
10297     return true;
10298   }
10299   case ARM::t2ADDspImm:
10300   case ARM::t2SUBspImm: {
10301     // Prefer T1 encoding if possible
10302     if (Inst.getOperand(5).getReg() != 0 || HasWideQualifier)
10303       break;
10304     unsigned V = Inst.getOperand(2).getImm();
10305     if (V & 3 || V > ((1 << 7) - 1) << 2)
10306       break;
10307     MCInst TmpInst;
10308     TmpInst.setOpcode(Inst.getOpcode() == ARM::t2ADDspImm ? ARM::tADDspi
10309                                                           : ARM::tSUBspi);
10310     TmpInst.addOperand(MCOperand::createReg(ARM::SP)); // destination reg
10311     TmpInst.addOperand(MCOperand::createReg(ARM::SP)); // source reg
10312     TmpInst.addOperand(MCOperand::createImm(V / 4));   // immediate
10313     TmpInst.addOperand(Inst.getOperand(3));            // pred
10314     TmpInst.addOperand(Inst.getOperand(4));
10315     Inst = TmpInst;
10316     return true;
10317   }
10318   case ARM::t2ADDrr: {
10319     // If the destination and first source operand are the same, and
10320     // there's no setting of the flags, use encoding T2 instead of T3.
10321     // Note that this is only for ADD, not SUB. This mirrors the system
10322     // 'as' behaviour.  Also take advantage of ADD being commutative.
10323     // Make sure the wide encoding wasn't explicit.
10324     bool Swap = false;
10325     auto DestReg = Inst.getOperand(0).getReg();
10326     bool Transform = DestReg == Inst.getOperand(1).getReg();
10327     if (!Transform && DestReg == Inst.getOperand(2).getReg()) {
10328       Transform = true;
10329       Swap = true;
10330     }
10331     if (!Transform ||
10332         Inst.getOperand(5).getReg() != 0 ||
10333         HasWideQualifier)
10334       break;
10335     MCInst TmpInst;
10336     TmpInst.setOpcode(ARM::tADDhirr);
10337     TmpInst.addOperand(Inst.getOperand(0));
10338     TmpInst.addOperand(Inst.getOperand(0));
10339     TmpInst.addOperand(Inst.getOperand(Swap ? 1 : 2));
10340     TmpInst.addOperand(Inst.getOperand(3));
10341     TmpInst.addOperand(Inst.getOperand(4));
10342     Inst = TmpInst;
10343     return true;
10344   }
10345   case ARM::tADDrSP:
10346     // If the non-SP source operand and the destination operand are not the
10347     // same, we need to use the 32-bit encoding if it's available.
10348     if (Inst.getOperand(0).getReg() != Inst.getOperand(2).getReg()) {
10349       Inst.setOpcode(ARM::t2ADDrr);
10350       Inst.addOperand(MCOperand::createReg(0)); // cc_out
10351       return true;
10352     }
10353     break;
10354   case ARM::tB:
10355     // A Thumb conditional branch outside of an IT block is a tBcc.
10356     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock()) {
10357       Inst.setOpcode(ARM::tBcc);
10358       return true;
10359     }
10360     break;
10361   case ARM::t2B:
10362     // A Thumb2 conditional branch outside of an IT block is a t2Bcc.
10363     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock()){
10364       Inst.setOpcode(ARM::t2Bcc);
10365       return true;
10366     }
10367     break;
10368   case ARM::t2Bcc:
10369     // If the conditional is AL or we're in an IT block, we really want t2B.
10370     if (Inst.getOperand(1).getImm() == ARMCC::AL || inITBlock()) {
10371       Inst.setOpcode(ARM::t2B);
10372       return true;
10373     }
10374     break;
10375   case ARM::tBcc:
10376     // If the conditional is AL, we really want tB.
10377     if (Inst.getOperand(1).getImm() == ARMCC::AL) {
10378       Inst.setOpcode(ARM::tB);
10379       return true;
10380     }
10381     break;
10382   case ARM::tLDMIA: {
10383     // If the register list contains any high registers, or if the writeback
10384     // doesn't match what tLDMIA can do, we need to use the 32-bit encoding
10385     // instead if we're in Thumb2. Otherwise, this should have generated
10386     // an error in validateInstruction().
10387     unsigned Rn = Inst.getOperand(0).getReg();
10388     bool hasWritebackToken =
10389         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
10390          static_cast<ARMOperand &>(*Operands[3]).getToken() == "!");
10391     bool listContainsBase;
10392     if (checkLowRegisterList(Inst, 3, Rn, 0, listContainsBase) ||
10393         (!listContainsBase && !hasWritebackToken) ||
10394         (listContainsBase && hasWritebackToken)) {
10395       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
10396       assert(isThumbTwo());
10397       Inst.setOpcode(hasWritebackToken ? ARM::t2LDMIA_UPD : ARM::t2LDMIA);
10398       // If we're switching to the updating version, we need to insert
10399       // the writeback tied operand.
10400       if (hasWritebackToken)
10401         Inst.insert(Inst.begin(),
10402                     MCOperand::createReg(Inst.getOperand(0).getReg()));
10403       return true;
10404     }
10405     break;
10406   }
10407   case ARM::tSTMIA_UPD: {
10408     // If the register list contains any high registers, we need to use
10409     // the 32-bit encoding instead if we're in Thumb2. Otherwise, this
10410     // should have generated an error in validateInstruction().
10411     unsigned Rn = Inst.getOperand(0).getReg();
10412     bool listContainsBase;
10413     if (checkLowRegisterList(Inst, 4, Rn, 0, listContainsBase)) {
10414       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
10415       assert(isThumbTwo());
10416       Inst.setOpcode(ARM::t2STMIA_UPD);
10417       return true;
10418     }
10419     break;
10420   }
10421   case ARM::tPOP: {
10422     bool listContainsBase;
10423     // If the register list contains any high registers, we need to use
10424     // the 32-bit encoding instead if we're in Thumb2. Otherwise, this
10425     // should have generated an error in validateInstruction().
10426     if (!checkLowRegisterList(Inst, 2, 0, ARM::PC, listContainsBase))
10427       return false;
10428     assert(isThumbTwo());
10429     Inst.setOpcode(ARM::t2LDMIA_UPD);
10430     // Add the base register and writeback operands.
10431     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
10432     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
10433     return true;
10434   }
10435   case ARM::tPUSH: {
10436     bool listContainsBase;
10437     if (!checkLowRegisterList(Inst, 2, 0, ARM::LR, listContainsBase))
10438       return false;
10439     assert(isThumbTwo());
10440     Inst.setOpcode(ARM::t2STMDB_UPD);
10441     // Add the base register and writeback operands.
10442     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
10443     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
10444     return true;
10445   }
10446   case ARM::t2MOVi:
10447     // If we can use the 16-bit encoding and the user didn't explicitly
10448     // request the 32-bit variant, transform it here.
10449     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
10450         (Inst.getOperand(1).isImm() &&
10451          (unsigned)Inst.getOperand(1).getImm() <= 255) &&
10452         Inst.getOperand(4).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
10453         !HasWideQualifier) {
10454       // The operands aren't in the same order for tMOVi8...
10455       MCInst TmpInst;
10456       TmpInst.setOpcode(ARM::tMOVi8);
10457       TmpInst.addOperand(Inst.getOperand(0));
10458       TmpInst.addOperand(Inst.getOperand(4));
10459       TmpInst.addOperand(Inst.getOperand(1));
10460       TmpInst.addOperand(Inst.getOperand(2));
10461       TmpInst.addOperand(Inst.getOperand(3));
10462       Inst = TmpInst;
10463       return true;
10464     }
10465     break;
10466 
10467   case ARM::t2MOVr:
10468     // If we can use the 16-bit encoding and the user didn't explicitly
10469     // request the 32-bit variant, transform it here.
10470     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
10471         isARMLowRegister(Inst.getOperand(1).getReg()) &&
10472         Inst.getOperand(2).getImm() == ARMCC::AL &&
10473         Inst.getOperand(4).getReg() == ARM::CPSR &&
10474         !HasWideQualifier) {
10475       // The operands aren't the same for tMOV[S]r... (no cc_out)
10476       MCInst TmpInst;
10477       unsigned Op = Inst.getOperand(4).getReg() ? ARM::tMOVSr : ARM::tMOVr;
10478       TmpInst.setOpcode(Op);
10479       TmpInst.addOperand(Inst.getOperand(0));
10480       TmpInst.addOperand(Inst.getOperand(1));
10481       if (Op == ARM::tMOVr) {
10482         TmpInst.addOperand(Inst.getOperand(2));
10483         TmpInst.addOperand(Inst.getOperand(3));
10484       }
10485       Inst = TmpInst;
10486       return true;
10487     }
10488     break;
10489 
10490   case ARM::t2SXTH:
10491   case ARM::t2SXTB:
10492   case ARM::t2UXTH:
10493   case ARM::t2UXTB:
10494     // If we can use the 16-bit encoding and the user didn't explicitly
10495     // request the 32-bit variant, transform it here.
10496     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
10497         isARMLowRegister(Inst.getOperand(1).getReg()) &&
10498         Inst.getOperand(2).getImm() == 0 &&
10499         !HasWideQualifier) {
10500       unsigned NewOpc;
10501       switch (Inst.getOpcode()) {
10502       default: llvm_unreachable("Illegal opcode!");
10503       case ARM::t2SXTH: NewOpc = ARM::tSXTH; break;
10504       case ARM::t2SXTB: NewOpc = ARM::tSXTB; break;
10505       case ARM::t2UXTH: NewOpc = ARM::tUXTH; break;
10506       case ARM::t2UXTB: NewOpc = ARM::tUXTB; break;
10507       }
10508       // The operands aren't the same for thumb1 (no rotate operand).
10509       MCInst TmpInst;
10510       TmpInst.setOpcode(NewOpc);
10511       TmpInst.addOperand(Inst.getOperand(0));
10512       TmpInst.addOperand(Inst.getOperand(1));
10513       TmpInst.addOperand(Inst.getOperand(3));
10514       TmpInst.addOperand(Inst.getOperand(4));
10515       Inst = TmpInst;
10516       return true;
10517     }
10518     break;
10519 
10520   case ARM::MOVsi: {
10521     ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(Inst.getOperand(2).getImm());
10522     // rrx shifts and asr/lsr of #32 is encoded as 0
10523     if (SOpc == ARM_AM::rrx || SOpc == ARM_AM::asr || SOpc == ARM_AM::lsr)
10524       return false;
10525     if (ARM_AM::getSORegOffset(Inst.getOperand(2).getImm()) == 0) {
10526       // Shifting by zero is accepted as a vanilla 'MOVr'
10527       MCInst TmpInst;
10528       TmpInst.setOpcode(ARM::MOVr);
10529       TmpInst.addOperand(Inst.getOperand(0));
10530       TmpInst.addOperand(Inst.getOperand(1));
10531       TmpInst.addOperand(Inst.getOperand(3));
10532       TmpInst.addOperand(Inst.getOperand(4));
10533       TmpInst.addOperand(Inst.getOperand(5));
10534       Inst = TmpInst;
10535       return true;
10536     }
10537     return false;
10538   }
10539   case ARM::ANDrsi:
10540   case ARM::ORRrsi:
10541   case ARM::EORrsi:
10542   case ARM::BICrsi:
10543   case ARM::SUBrsi:
10544   case ARM::ADDrsi: {
10545     unsigned newOpc;
10546     ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(Inst.getOperand(3).getImm());
10547     if (SOpc == ARM_AM::rrx) return false;
10548     switch (Inst.getOpcode()) {
10549     default: llvm_unreachable("unexpected opcode!");
10550     case ARM::ANDrsi: newOpc = ARM::ANDrr; break;
10551     case ARM::ORRrsi: newOpc = ARM::ORRrr; break;
10552     case ARM::EORrsi: newOpc = ARM::EORrr; break;
10553     case ARM::BICrsi: newOpc = ARM::BICrr; break;
10554     case ARM::SUBrsi: newOpc = ARM::SUBrr; break;
10555     case ARM::ADDrsi: newOpc = ARM::ADDrr; break;
10556     }
10557     // If the shift is by zero, use the non-shifted instruction definition.
10558     // The exception is for right shifts, where 0 == 32
10559     if (ARM_AM::getSORegOffset(Inst.getOperand(3).getImm()) == 0 &&
10560         !(SOpc == ARM_AM::lsr || SOpc == ARM_AM::asr)) {
10561       MCInst TmpInst;
10562       TmpInst.setOpcode(newOpc);
10563       TmpInst.addOperand(Inst.getOperand(0));
10564       TmpInst.addOperand(Inst.getOperand(1));
10565       TmpInst.addOperand(Inst.getOperand(2));
10566       TmpInst.addOperand(Inst.getOperand(4));
10567       TmpInst.addOperand(Inst.getOperand(5));
10568       TmpInst.addOperand(Inst.getOperand(6));
10569       Inst = TmpInst;
10570       return true;
10571     }
10572     return false;
10573   }
10574   case ARM::ITasm:
10575   case ARM::t2IT: {
10576     // Set up the IT block state according to the IT instruction we just
10577     // matched.
10578     assert(!inITBlock() && "nested IT blocks?!");
10579     startExplicitITBlock(ARMCC::CondCodes(Inst.getOperand(0).getImm()),
10580                          Inst.getOperand(1).getImm());
10581     break;
10582   }
10583   case ARM::t2LSLrr:
10584   case ARM::t2LSRrr:
10585   case ARM::t2ASRrr:
10586   case ARM::t2SBCrr:
10587   case ARM::t2RORrr:
10588   case ARM::t2BICrr:
10589     // Assemblers should use the narrow encodings of these instructions when permissible.
10590     if ((isARMLowRegister(Inst.getOperand(1).getReg()) &&
10591          isARMLowRegister(Inst.getOperand(2).getReg())) &&
10592         Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() &&
10593         Inst.getOperand(5).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
10594         !HasWideQualifier) {
10595       unsigned NewOpc;
10596       switch (Inst.getOpcode()) {
10597         default: llvm_unreachable("unexpected opcode");
10598         case ARM::t2LSLrr: NewOpc = ARM::tLSLrr; break;
10599         case ARM::t2LSRrr: NewOpc = ARM::tLSRrr; break;
10600         case ARM::t2ASRrr: NewOpc = ARM::tASRrr; break;
10601         case ARM::t2SBCrr: NewOpc = ARM::tSBC; break;
10602         case ARM::t2RORrr: NewOpc = ARM::tROR; break;
10603         case ARM::t2BICrr: NewOpc = ARM::tBIC; break;
10604       }
10605       MCInst TmpInst;
10606       TmpInst.setOpcode(NewOpc);
10607       TmpInst.addOperand(Inst.getOperand(0));
10608       TmpInst.addOperand(Inst.getOperand(5));
10609       TmpInst.addOperand(Inst.getOperand(1));
10610       TmpInst.addOperand(Inst.getOperand(2));
10611       TmpInst.addOperand(Inst.getOperand(3));
10612       TmpInst.addOperand(Inst.getOperand(4));
10613       Inst = TmpInst;
10614       return true;
10615     }
10616     return false;
10617 
10618   case ARM::t2ANDrr:
10619   case ARM::t2EORrr:
10620   case ARM::t2ADCrr:
10621   case ARM::t2ORRrr:
10622     // Assemblers should use the narrow encodings of these instructions when permissible.
10623     // These instructions are special in that they are commutable, so shorter encodings
10624     // are available more often.
10625     if ((isARMLowRegister(Inst.getOperand(1).getReg()) &&
10626          isARMLowRegister(Inst.getOperand(2).getReg())) &&
10627         (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() ||
10628          Inst.getOperand(0).getReg() == Inst.getOperand(2).getReg()) &&
10629         Inst.getOperand(5).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
10630         !HasWideQualifier) {
10631       unsigned NewOpc;
10632       switch (Inst.getOpcode()) {
10633         default: llvm_unreachable("unexpected opcode");
10634         case ARM::t2ADCrr: NewOpc = ARM::tADC; break;
10635         case ARM::t2ANDrr: NewOpc = ARM::tAND; break;
10636         case ARM::t2EORrr: NewOpc = ARM::tEOR; break;
10637         case ARM::t2ORRrr: NewOpc = ARM::tORR; break;
10638       }
10639       MCInst TmpInst;
10640       TmpInst.setOpcode(NewOpc);
10641       TmpInst.addOperand(Inst.getOperand(0));
10642       TmpInst.addOperand(Inst.getOperand(5));
10643       if (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg()) {
10644         TmpInst.addOperand(Inst.getOperand(1));
10645         TmpInst.addOperand(Inst.getOperand(2));
10646       } else {
10647         TmpInst.addOperand(Inst.getOperand(2));
10648         TmpInst.addOperand(Inst.getOperand(1));
10649       }
10650       TmpInst.addOperand(Inst.getOperand(3));
10651       TmpInst.addOperand(Inst.getOperand(4));
10652       Inst = TmpInst;
10653       return true;
10654     }
10655     return false;
10656   case ARM::MVE_VPST:
10657   case ARM::MVE_VPTv16i8:
10658   case ARM::MVE_VPTv8i16:
10659   case ARM::MVE_VPTv4i32:
10660   case ARM::MVE_VPTv16u8:
10661   case ARM::MVE_VPTv8u16:
10662   case ARM::MVE_VPTv4u32:
10663   case ARM::MVE_VPTv16s8:
10664   case ARM::MVE_VPTv8s16:
10665   case ARM::MVE_VPTv4s32:
10666   case ARM::MVE_VPTv4f32:
10667   case ARM::MVE_VPTv8f16:
10668   case ARM::MVE_VPTv16i8r:
10669   case ARM::MVE_VPTv8i16r:
10670   case ARM::MVE_VPTv4i32r:
10671   case ARM::MVE_VPTv16u8r:
10672   case ARM::MVE_VPTv8u16r:
10673   case ARM::MVE_VPTv4u32r:
10674   case ARM::MVE_VPTv16s8r:
10675   case ARM::MVE_VPTv8s16r:
10676   case ARM::MVE_VPTv4s32r:
10677   case ARM::MVE_VPTv4f32r:
10678   case ARM::MVE_VPTv8f16r: {
10679     assert(!inVPTBlock() && "Nested VPT blocks are not allowed");
10680     MCOperand &MO = Inst.getOperand(0);
10681     VPTState.Mask = MO.getImm();
10682     VPTState.CurPosition = 0;
10683     break;
10684   }
10685   }
10686   return false;
10687 }
10688 
10689 unsigned ARMAsmParser::checkTargetMatchPredicate(MCInst &Inst) {
10690   // 16-bit thumb arithmetic instructions either require or preclude the 'S'
10691   // suffix depending on whether they're in an IT block or not.
10692   unsigned Opc = Inst.getOpcode();
10693   const MCInstrDesc &MCID = MII.get(Opc);
10694   if (MCID.TSFlags & ARMII::ThumbArithFlagSetting) {
10695     assert(MCID.hasOptionalDef() &&
10696            "optionally flag setting instruction missing optional def operand");
10697     assert(MCID.NumOperands == Inst.getNumOperands() &&
10698            "operand count mismatch!");
10699     // Find the optional-def operand (cc_out).
10700     unsigned OpNo;
10701     for (OpNo = 0;
10702          !MCID.OpInfo[OpNo].isOptionalDef() && OpNo < MCID.NumOperands;
10703          ++OpNo)
10704       ;
10705     // If we're parsing Thumb1, reject it completely.
10706     if (isThumbOne() && Inst.getOperand(OpNo).getReg() != ARM::CPSR)
10707       return Match_RequiresFlagSetting;
10708     // If we're parsing Thumb2, which form is legal depends on whether we're
10709     // in an IT block.
10710     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() != ARM::CPSR &&
10711         !inITBlock())
10712       return Match_RequiresITBlock;
10713     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() == ARM::CPSR &&
10714         inITBlock())
10715       return Match_RequiresNotITBlock;
10716     // LSL with zero immediate is not allowed in an IT block
10717     if (Opc == ARM::tLSLri && Inst.getOperand(3).getImm() == 0 && inITBlock())
10718       return Match_RequiresNotITBlock;
10719   } else if (isThumbOne()) {
10720     // Some high-register supporting Thumb1 encodings only allow both registers
10721     // to be from r0-r7 when in Thumb2.
10722     if (Opc == ARM::tADDhirr && !hasV6MOps() &&
10723         isARMLowRegister(Inst.getOperand(1).getReg()) &&
10724         isARMLowRegister(Inst.getOperand(2).getReg()))
10725       return Match_RequiresThumb2;
10726     // Others only require ARMv6 or later.
10727     else if (Opc == ARM::tMOVr && !hasV6Ops() &&
10728              isARMLowRegister(Inst.getOperand(0).getReg()) &&
10729              isARMLowRegister(Inst.getOperand(1).getReg()))
10730       return Match_RequiresV6;
10731   }
10732 
10733   // Before ARMv8 the rules for when SP is allowed in t2MOVr are more complex
10734   // than the loop below can handle, so it uses the GPRnopc register class and
10735   // we do SP handling here.
10736   if (Opc == ARM::t2MOVr && !hasV8Ops())
10737   {
10738     // SP as both source and destination is not allowed
10739     if (Inst.getOperand(0).getReg() == ARM::SP &&
10740         Inst.getOperand(1).getReg() == ARM::SP)
10741       return Match_RequiresV8;
10742     // When flags-setting SP as either source or destination is not allowed
10743     if (Inst.getOperand(4).getReg() == ARM::CPSR &&
10744         (Inst.getOperand(0).getReg() == ARM::SP ||
10745          Inst.getOperand(1).getReg() == ARM::SP))
10746       return Match_RequiresV8;
10747   }
10748 
10749   switch (Inst.getOpcode()) {
10750   case ARM::VMRS:
10751   case ARM::VMSR:
10752   case ARM::VMRS_FPCXTS:
10753   case ARM::VMRS_FPCXTNS:
10754   case ARM::VMSR_FPCXTS:
10755   case ARM::VMSR_FPCXTNS:
10756   case ARM::VMRS_FPSCR_NZCVQC:
10757   case ARM::VMSR_FPSCR_NZCVQC:
10758   case ARM::FMSTAT:
10759   case ARM::VMRS_VPR:
10760   case ARM::VMRS_P0:
10761   case ARM::VMSR_VPR:
10762   case ARM::VMSR_P0:
10763     // Use of SP for VMRS/VMSR is only allowed in ARM mode with the exception of
10764     // ARMv8-A.
10765     if (Inst.getOperand(0).isReg() && Inst.getOperand(0).getReg() == ARM::SP &&
10766         (isThumb() && !hasV8Ops()))
10767       return Match_InvalidOperand;
10768     break;
10769   case ARM::t2TBB:
10770   case ARM::t2TBH:
10771     // Rn = sp is only allowed with ARMv8-A
10772     if (!hasV8Ops() && (Inst.getOperand(0).getReg() == ARM::SP))
10773       return Match_RequiresV8;
10774     break;
10775   default:
10776     break;
10777   }
10778 
10779   for (unsigned I = 0; I < MCID.NumOperands; ++I)
10780     if (MCID.OpInfo[I].RegClass == ARM::rGPRRegClassID) {
10781       // rGPRRegClass excludes PC, and also excluded SP before ARMv8
10782       const auto &Op = Inst.getOperand(I);
10783       if (!Op.isReg()) {
10784         // This can happen in awkward cases with tied operands, e.g. a
10785         // writeback load/store with a complex addressing mode in
10786         // which there's an output operand corresponding to the
10787         // updated written-back base register: the Tablegen-generated
10788         // AsmMatcher will have written a placeholder operand to that
10789         // slot in the form of an immediate 0, because it can't
10790         // generate the register part of the complex addressing-mode
10791         // operand ahead of time.
10792         continue;
10793       }
10794 
10795       unsigned Reg = Op.getReg();
10796       if ((Reg == ARM::SP) && !hasV8Ops())
10797         return Match_RequiresV8;
10798       else if (Reg == ARM::PC)
10799         return Match_InvalidOperand;
10800     }
10801 
10802   return Match_Success;
10803 }
10804 
10805 namespace llvm {
10806 
10807 template <> inline bool IsCPSRDead<MCInst>(const MCInst *Instr) {
10808   return true; // In an assembly source, no need to second-guess
10809 }
10810 
10811 } // end namespace llvm
10812 
10813 // Returns true if Inst is unpredictable if it is in and IT block, but is not
10814 // the last instruction in the block.
10815 bool ARMAsmParser::isITBlockTerminator(MCInst &Inst) const {
10816   const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
10817 
10818   // All branch & call instructions terminate IT blocks with the exception of
10819   // SVC.
10820   if (MCID.isTerminator() || (MCID.isCall() && Inst.getOpcode() != ARM::tSVC) ||
10821       MCID.isReturn() || MCID.isBranch() || MCID.isIndirectBranch())
10822     return true;
10823 
10824   // Any arithmetic instruction which writes to the PC also terminates the IT
10825   // block.
10826   if (MCID.hasDefOfPhysReg(Inst, ARM::PC, *MRI))
10827     return true;
10828 
10829   return false;
10830 }
10831 
10832 unsigned ARMAsmParser::MatchInstruction(OperandVector &Operands, MCInst &Inst,
10833                                           SmallVectorImpl<NearMissInfo> &NearMisses,
10834                                           bool MatchingInlineAsm,
10835                                           bool &EmitInITBlock,
10836                                           MCStreamer &Out) {
10837   // If we can't use an implicit IT block here, just match as normal.
10838   if (inExplicitITBlock() || !isThumbTwo() || !useImplicitITThumb())
10839     return MatchInstructionImpl(Operands, Inst, &NearMisses, MatchingInlineAsm);
10840 
10841   // Try to match the instruction in an extension of the current IT block (if
10842   // there is one).
10843   if (inImplicitITBlock()) {
10844     extendImplicitITBlock(ITState.Cond);
10845     if (MatchInstructionImpl(Operands, Inst, nullptr, MatchingInlineAsm) ==
10846             Match_Success) {
10847       // The match succeded, but we still have to check that the instruction is
10848       // valid in this implicit IT block.
10849       const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
10850       if (MCID.isPredicable()) {
10851         ARMCC::CondCodes InstCond =
10852             (ARMCC::CondCodes)Inst.getOperand(MCID.findFirstPredOperandIdx())
10853                 .getImm();
10854         ARMCC::CondCodes ITCond = currentITCond();
10855         if (InstCond == ITCond) {
10856           EmitInITBlock = true;
10857           return Match_Success;
10858         } else if (InstCond == ARMCC::getOppositeCondition(ITCond)) {
10859           invertCurrentITCondition();
10860           EmitInITBlock = true;
10861           return Match_Success;
10862         }
10863       }
10864     }
10865     rewindImplicitITPosition();
10866   }
10867 
10868   // Finish the current IT block, and try to match outside any IT block.
10869   flushPendingInstructions(Out);
10870   unsigned PlainMatchResult =
10871       MatchInstructionImpl(Operands, Inst, &NearMisses, MatchingInlineAsm);
10872   if (PlainMatchResult == Match_Success) {
10873     const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
10874     if (MCID.isPredicable()) {
10875       ARMCC::CondCodes InstCond =
10876           (ARMCC::CondCodes)Inst.getOperand(MCID.findFirstPredOperandIdx())
10877               .getImm();
10878       // Some forms of the branch instruction have their own condition code
10879       // fields, so can be conditionally executed without an IT block.
10880       if (Inst.getOpcode() == ARM::tBcc || Inst.getOpcode() == ARM::t2Bcc) {
10881         EmitInITBlock = false;
10882         return Match_Success;
10883       }
10884       if (InstCond == ARMCC::AL) {
10885         EmitInITBlock = false;
10886         return Match_Success;
10887       }
10888     } else {
10889       EmitInITBlock = false;
10890       return Match_Success;
10891     }
10892   }
10893 
10894   // Try to match in a new IT block. The matcher doesn't check the actual
10895   // condition, so we create an IT block with a dummy condition, and fix it up
10896   // once we know the actual condition.
10897   startImplicitITBlock();
10898   if (MatchInstructionImpl(Operands, Inst, nullptr, MatchingInlineAsm) ==
10899       Match_Success) {
10900     const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
10901     if (MCID.isPredicable()) {
10902       ITState.Cond =
10903           (ARMCC::CondCodes)Inst.getOperand(MCID.findFirstPredOperandIdx())
10904               .getImm();
10905       EmitInITBlock = true;
10906       return Match_Success;
10907     }
10908   }
10909   discardImplicitITBlock();
10910 
10911   // If none of these succeed, return the error we got when trying to match
10912   // outside any IT blocks.
10913   EmitInITBlock = false;
10914   return PlainMatchResult;
10915 }
10916 
10917 static std::string ARMMnemonicSpellCheck(StringRef S, const FeatureBitset &FBS,
10918                                          unsigned VariantID = 0);
10919 
10920 static const char *getSubtargetFeatureName(uint64_t Val);
10921 bool ARMAsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
10922                                            OperandVector &Operands,
10923                                            MCStreamer &Out, uint64_t &ErrorInfo,
10924                                            bool MatchingInlineAsm) {
10925   MCInst Inst;
10926   unsigned MatchResult;
10927   bool PendConditionalInstruction = false;
10928 
10929   SmallVector<NearMissInfo, 4> NearMisses;
10930   MatchResult = MatchInstruction(Operands, Inst, NearMisses, MatchingInlineAsm,
10931                                  PendConditionalInstruction, Out);
10932 
10933   switch (MatchResult) {
10934   case Match_Success:
10935     LLVM_DEBUG(dbgs() << "Parsed as: ";
10936                Inst.dump_pretty(dbgs(), MII.getName(Inst.getOpcode()));
10937                dbgs() << "\n");
10938 
10939     // Context sensitive operand constraints aren't handled by the matcher,
10940     // so check them here.
10941     if (validateInstruction(Inst, Operands)) {
10942       // Still progress the IT block, otherwise one wrong condition causes
10943       // nasty cascading errors.
10944       forwardITPosition();
10945       forwardVPTPosition();
10946       return true;
10947     }
10948 
10949     { // processInstruction() updates inITBlock state, we need to save it away
10950       bool wasInITBlock = inITBlock();
10951 
10952       // Some instructions need post-processing to, for example, tweak which
10953       // encoding is selected. Loop on it while changes happen so the
10954       // individual transformations can chain off each other. E.g.,
10955       // tPOP(r8)->t2LDMIA_UPD(sp,r8)->t2STR_POST(sp,r8)
10956       while (processInstruction(Inst, Operands, Out))
10957         LLVM_DEBUG(dbgs() << "Changed to: ";
10958                    Inst.dump_pretty(dbgs(), MII.getName(Inst.getOpcode()));
10959                    dbgs() << "\n");
10960 
10961       // Only after the instruction is fully processed, we can validate it
10962       if (wasInITBlock && hasV8Ops() && isThumb() &&
10963           !isV8EligibleForIT(&Inst)) {
10964         Warning(IDLoc, "deprecated instruction in IT block");
10965       }
10966     }
10967 
10968     // Only move forward at the very end so that everything in validate
10969     // and process gets a consistent answer about whether we're in an IT
10970     // block.
10971     forwardITPosition();
10972     forwardVPTPosition();
10973 
10974     // ITasm is an ARM mode pseudo-instruction that just sets the ITblock and
10975     // doesn't actually encode.
10976     if (Inst.getOpcode() == ARM::ITasm)
10977       return false;
10978 
10979     Inst.setLoc(IDLoc);
10980     if (PendConditionalInstruction) {
10981       PendingConditionalInsts.push_back(Inst);
10982       if (isITBlockFull() || isITBlockTerminator(Inst))
10983         flushPendingInstructions(Out);
10984     } else {
10985       Out.emitInstruction(Inst, getSTI());
10986     }
10987     return false;
10988   case Match_NearMisses:
10989     ReportNearMisses(NearMisses, IDLoc, Operands);
10990     return true;
10991   case Match_MnemonicFail: {
10992     FeatureBitset FBS = ComputeAvailableFeatures(getSTI().getFeatureBits());
10993     std::string Suggestion = ARMMnemonicSpellCheck(
10994       ((ARMOperand &)*Operands[0]).getToken(), FBS);
10995     return Error(IDLoc, "invalid instruction" + Suggestion,
10996                  ((ARMOperand &)*Operands[0]).getLocRange());
10997   }
10998   }
10999 
11000   llvm_unreachable("Implement any new match types added!");
11001 }
11002 
11003 /// parseDirective parses the arm specific directives
11004 bool ARMAsmParser::ParseDirective(AsmToken DirectiveID) {
11005   const MCObjectFileInfo::Environment Format =
11006     getContext().getObjectFileInfo()->getObjectFileType();
11007   bool IsMachO = Format == MCObjectFileInfo::IsMachO;
11008   bool IsCOFF = Format == MCObjectFileInfo::IsCOFF;
11009 
11010   std::string IDVal = DirectiveID.getIdentifier().lower();
11011   if (IDVal == ".word")
11012     parseLiteralValues(4, DirectiveID.getLoc());
11013   else if (IDVal == ".short" || IDVal == ".hword")
11014     parseLiteralValues(2, DirectiveID.getLoc());
11015   else if (IDVal == ".thumb")
11016     parseDirectiveThumb(DirectiveID.getLoc());
11017   else if (IDVal == ".arm")
11018     parseDirectiveARM(DirectiveID.getLoc());
11019   else if (IDVal == ".thumb_func")
11020     parseDirectiveThumbFunc(DirectiveID.getLoc());
11021   else if (IDVal == ".code")
11022     parseDirectiveCode(DirectiveID.getLoc());
11023   else if (IDVal == ".syntax")
11024     parseDirectiveSyntax(DirectiveID.getLoc());
11025   else if (IDVal == ".unreq")
11026     parseDirectiveUnreq(DirectiveID.getLoc());
11027   else if (IDVal == ".fnend")
11028     parseDirectiveFnEnd(DirectiveID.getLoc());
11029   else if (IDVal == ".cantunwind")
11030     parseDirectiveCantUnwind(DirectiveID.getLoc());
11031   else if (IDVal == ".personality")
11032     parseDirectivePersonality(DirectiveID.getLoc());
11033   else if (IDVal == ".handlerdata")
11034     parseDirectiveHandlerData(DirectiveID.getLoc());
11035   else if (IDVal == ".setfp")
11036     parseDirectiveSetFP(DirectiveID.getLoc());
11037   else if (IDVal == ".pad")
11038     parseDirectivePad(DirectiveID.getLoc());
11039   else if (IDVal == ".save")
11040     parseDirectiveRegSave(DirectiveID.getLoc(), false);
11041   else if (IDVal == ".vsave")
11042     parseDirectiveRegSave(DirectiveID.getLoc(), true);
11043   else if (IDVal == ".ltorg" || IDVal == ".pool")
11044     parseDirectiveLtorg(DirectiveID.getLoc());
11045   else if (IDVal == ".even")
11046     parseDirectiveEven(DirectiveID.getLoc());
11047   else if (IDVal == ".personalityindex")
11048     parseDirectivePersonalityIndex(DirectiveID.getLoc());
11049   else if (IDVal == ".unwind_raw")
11050     parseDirectiveUnwindRaw(DirectiveID.getLoc());
11051   else if (IDVal == ".movsp")
11052     parseDirectiveMovSP(DirectiveID.getLoc());
11053   else if (IDVal == ".arch_extension")
11054     parseDirectiveArchExtension(DirectiveID.getLoc());
11055   else if (IDVal == ".align")
11056     return parseDirectiveAlign(DirectiveID.getLoc()); // Use Generic on failure.
11057   else if (IDVal == ".thumb_set")
11058     parseDirectiveThumbSet(DirectiveID.getLoc());
11059   else if (IDVal == ".inst")
11060     parseDirectiveInst(DirectiveID.getLoc());
11061   else if (IDVal == ".inst.n")
11062     parseDirectiveInst(DirectiveID.getLoc(), 'n');
11063   else if (IDVal == ".inst.w")
11064     parseDirectiveInst(DirectiveID.getLoc(), 'w');
11065   else if (!IsMachO && !IsCOFF) {
11066     if (IDVal == ".arch")
11067       parseDirectiveArch(DirectiveID.getLoc());
11068     else if (IDVal == ".cpu")
11069       parseDirectiveCPU(DirectiveID.getLoc());
11070     else if (IDVal == ".eabi_attribute")
11071       parseDirectiveEabiAttr(DirectiveID.getLoc());
11072     else if (IDVal == ".fpu")
11073       parseDirectiveFPU(DirectiveID.getLoc());
11074     else if (IDVal == ".fnstart")
11075       parseDirectiveFnStart(DirectiveID.getLoc());
11076     else if (IDVal == ".object_arch")
11077       parseDirectiveObjectArch(DirectiveID.getLoc());
11078     else if (IDVal == ".tlsdescseq")
11079       parseDirectiveTLSDescSeq(DirectiveID.getLoc());
11080     else
11081       return true;
11082   } else
11083     return true;
11084   return false;
11085 }
11086 
11087 /// parseLiteralValues
11088 ///  ::= .hword expression [, expression]*
11089 ///  ::= .short expression [, expression]*
11090 ///  ::= .word expression [, expression]*
11091 bool ARMAsmParser::parseLiteralValues(unsigned Size, SMLoc L) {
11092   auto parseOne = [&]() -> bool {
11093     const MCExpr *Value;
11094     if (getParser().parseExpression(Value))
11095       return true;
11096     getParser().getStreamer().emitValue(Value, Size, L);
11097     return false;
11098   };
11099   return (parseMany(parseOne));
11100 }
11101 
11102 /// parseDirectiveThumb
11103 ///  ::= .thumb
11104 bool ARMAsmParser::parseDirectiveThumb(SMLoc L) {
11105   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive") ||
11106       check(!hasThumb(), L, "target does not support Thumb mode"))
11107     return true;
11108 
11109   if (!isThumb())
11110     SwitchMode();
11111 
11112   getParser().getStreamer().emitAssemblerFlag(MCAF_Code16);
11113   return false;
11114 }
11115 
11116 /// parseDirectiveARM
11117 ///  ::= .arm
11118 bool ARMAsmParser::parseDirectiveARM(SMLoc L) {
11119   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive") ||
11120       check(!hasARM(), L, "target does not support ARM mode"))
11121     return true;
11122 
11123   if (isThumb())
11124     SwitchMode();
11125   getParser().getStreamer().emitAssemblerFlag(MCAF_Code32);
11126   return false;
11127 }
11128 
11129 void ARMAsmParser::doBeforeLabelEmit(MCSymbol *Symbol) {
11130   // We need to flush the current implicit IT block on a label, because it is
11131   // not legal to branch into an IT block.
11132   flushPendingInstructions(getStreamer());
11133 }
11134 
11135 void ARMAsmParser::onLabelParsed(MCSymbol *Symbol) {
11136   if (NextSymbolIsThumb) {
11137     getParser().getStreamer().emitThumbFunc(Symbol);
11138     NextSymbolIsThumb = false;
11139   }
11140 }
11141 
11142 /// parseDirectiveThumbFunc
11143 ///  ::= .thumbfunc symbol_name
11144 bool ARMAsmParser::parseDirectiveThumbFunc(SMLoc L) {
11145   MCAsmParser &Parser = getParser();
11146   const auto Format = getContext().getObjectFileInfo()->getObjectFileType();
11147   bool IsMachO = Format == MCObjectFileInfo::IsMachO;
11148 
11149   // Darwin asm has (optionally) function name after .thumb_func direction
11150   // ELF doesn't
11151 
11152   if (IsMachO) {
11153     if (Parser.getTok().is(AsmToken::Identifier) ||
11154         Parser.getTok().is(AsmToken::String)) {
11155       MCSymbol *Func = getParser().getContext().getOrCreateSymbol(
11156           Parser.getTok().getIdentifier());
11157       getParser().getStreamer().emitThumbFunc(Func);
11158       Parser.Lex();
11159       if (parseToken(AsmToken::EndOfStatement,
11160                      "unexpected token in '.thumb_func' directive"))
11161         return true;
11162       return false;
11163     }
11164   }
11165 
11166   if (parseToken(AsmToken::EndOfStatement,
11167                  "unexpected token in '.thumb_func' directive"))
11168     return true;
11169 
11170   NextSymbolIsThumb = true;
11171   return false;
11172 }
11173 
11174 /// parseDirectiveSyntax
11175 ///  ::= .syntax unified | divided
11176 bool ARMAsmParser::parseDirectiveSyntax(SMLoc L) {
11177   MCAsmParser &Parser = getParser();
11178   const AsmToken &Tok = Parser.getTok();
11179   if (Tok.isNot(AsmToken::Identifier)) {
11180     Error(L, "unexpected token in .syntax directive");
11181     return false;
11182   }
11183 
11184   StringRef Mode = Tok.getString();
11185   Parser.Lex();
11186   if (check(Mode == "divided" || Mode == "DIVIDED", L,
11187             "'.syntax divided' arm assembly not supported") ||
11188       check(Mode != "unified" && Mode != "UNIFIED", L,
11189             "unrecognized syntax mode in .syntax directive") ||
11190       parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
11191     return true;
11192 
11193   // TODO tell the MC streamer the mode
11194   // getParser().getStreamer().Emit???();
11195   return false;
11196 }
11197 
11198 /// parseDirectiveCode
11199 ///  ::= .code 16 | 32
11200 bool ARMAsmParser::parseDirectiveCode(SMLoc L) {
11201   MCAsmParser &Parser = getParser();
11202   const AsmToken &Tok = Parser.getTok();
11203   if (Tok.isNot(AsmToken::Integer))
11204     return Error(L, "unexpected token in .code directive");
11205   int64_t Val = Parser.getTok().getIntVal();
11206   if (Val != 16 && Val != 32) {
11207     Error(L, "invalid operand to .code directive");
11208     return false;
11209   }
11210   Parser.Lex();
11211 
11212   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
11213     return true;
11214 
11215   if (Val == 16) {
11216     if (!hasThumb())
11217       return Error(L, "target does not support Thumb mode");
11218 
11219     if (!isThumb())
11220       SwitchMode();
11221     getParser().getStreamer().emitAssemblerFlag(MCAF_Code16);
11222   } else {
11223     if (!hasARM())
11224       return Error(L, "target does not support ARM mode");
11225 
11226     if (isThumb())
11227       SwitchMode();
11228     getParser().getStreamer().emitAssemblerFlag(MCAF_Code32);
11229   }
11230 
11231   return false;
11232 }
11233 
11234 /// parseDirectiveReq
11235 ///  ::= name .req registername
11236 bool ARMAsmParser::parseDirectiveReq(StringRef Name, SMLoc L) {
11237   MCAsmParser &Parser = getParser();
11238   Parser.Lex(); // Eat the '.req' token.
11239   unsigned Reg;
11240   SMLoc SRegLoc, ERegLoc;
11241   if (check(ParseRegister(Reg, SRegLoc, ERegLoc), SRegLoc,
11242             "register name expected") ||
11243       parseToken(AsmToken::EndOfStatement,
11244                  "unexpected input in .req directive."))
11245     return true;
11246 
11247   if (RegisterReqs.insert(std::make_pair(Name, Reg)).first->second != Reg)
11248     return Error(SRegLoc,
11249                  "redefinition of '" + Name + "' does not match original.");
11250 
11251   return false;
11252 }
11253 
11254 /// parseDirectiveUneq
11255 ///  ::= .unreq registername
11256 bool ARMAsmParser::parseDirectiveUnreq(SMLoc L) {
11257   MCAsmParser &Parser = getParser();
11258   if (Parser.getTok().isNot(AsmToken::Identifier))
11259     return Error(L, "unexpected input in .unreq directive.");
11260   RegisterReqs.erase(Parser.getTok().getIdentifier().lower());
11261   Parser.Lex(); // Eat the identifier.
11262   if (parseToken(AsmToken::EndOfStatement,
11263                  "unexpected input in '.unreq' directive"))
11264     return true;
11265   return false;
11266 }
11267 
11268 // After changing arch/CPU, try to put the ARM/Thumb mode back to what it was
11269 // before, if supported by the new target, or emit mapping symbols for the mode
11270 // switch.
11271 void ARMAsmParser::FixModeAfterArchChange(bool WasThumb, SMLoc Loc) {
11272   if (WasThumb != isThumb()) {
11273     if (WasThumb && hasThumb()) {
11274       // Stay in Thumb mode
11275       SwitchMode();
11276     } else if (!WasThumb && hasARM()) {
11277       // Stay in ARM mode
11278       SwitchMode();
11279     } else {
11280       // Mode switch forced, because the new arch doesn't support the old mode.
11281       getParser().getStreamer().emitAssemblerFlag(isThumb() ? MCAF_Code16
11282                                                             : MCAF_Code32);
11283       // Warn about the implcit mode switch. GAS does not switch modes here,
11284       // but instead stays in the old mode, reporting an error on any following
11285       // instructions as the mode does not exist on the target.
11286       Warning(Loc, Twine("new target does not support ") +
11287                        (WasThumb ? "thumb" : "arm") + " mode, switching to " +
11288                        (!WasThumb ? "thumb" : "arm") + " mode");
11289     }
11290   }
11291 }
11292 
11293 /// parseDirectiveArch
11294 ///  ::= .arch token
11295 bool ARMAsmParser::parseDirectiveArch(SMLoc L) {
11296   StringRef Arch = getParser().parseStringToEndOfStatement().trim();
11297   ARM::ArchKind ID = ARM::parseArch(Arch);
11298 
11299   if (ID == ARM::ArchKind::INVALID)
11300     return Error(L, "Unknown arch name");
11301 
11302   bool WasThumb = isThumb();
11303   Triple T;
11304   MCSubtargetInfo &STI = copySTI();
11305   STI.setDefaultFeatures("", /*TuneCPU*/ "",
11306                          ("+" + ARM::getArchName(ID)).str());
11307   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
11308   FixModeAfterArchChange(WasThumb, L);
11309 
11310   getTargetStreamer().emitArch(ID);
11311   return false;
11312 }
11313 
11314 /// parseDirectiveEabiAttr
11315 ///  ::= .eabi_attribute int, int [, "str"]
11316 ///  ::= .eabi_attribute Tag_name, int [, "str"]
11317 bool ARMAsmParser::parseDirectiveEabiAttr(SMLoc L) {
11318   MCAsmParser &Parser = getParser();
11319   int64_t Tag;
11320   SMLoc TagLoc;
11321   TagLoc = Parser.getTok().getLoc();
11322   if (Parser.getTok().is(AsmToken::Identifier)) {
11323     StringRef Name = Parser.getTok().getIdentifier();
11324     Optional<unsigned> Ret =
11325         ELFAttrs::attrTypeFromString(Name, ARMBuildAttrs::ARMAttributeTags);
11326     if (!Ret.hasValue()) {
11327       Error(TagLoc, "attribute name not recognised: " + Name);
11328       return false;
11329     }
11330     Tag = Ret.getValue();
11331     Parser.Lex();
11332   } else {
11333     const MCExpr *AttrExpr;
11334 
11335     TagLoc = Parser.getTok().getLoc();
11336     if (Parser.parseExpression(AttrExpr))
11337       return true;
11338 
11339     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(AttrExpr);
11340     if (check(!CE, TagLoc, "expected numeric constant"))
11341       return true;
11342 
11343     Tag = CE->getValue();
11344   }
11345 
11346   if (Parser.parseToken(AsmToken::Comma, "comma expected"))
11347     return true;
11348 
11349   StringRef StringValue = "";
11350   bool IsStringValue = false;
11351 
11352   int64_t IntegerValue = 0;
11353   bool IsIntegerValue = false;
11354 
11355   if (Tag == ARMBuildAttrs::CPU_raw_name || Tag == ARMBuildAttrs::CPU_name)
11356     IsStringValue = true;
11357   else if (Tag == ARMBuildAttrs::compatibility) {
11358     IsStringValue = true;
11359     IsIntegerValue = true;
11360   } else if (Tag < 32 || Tag % 2 == 0)
11361     IsIntegerValue = true;
11362   else if (Tag % 2 == 1)
11363     IsStringValue = true;
11364   else
11365     llvm_unreachable("invalid tag type");
11366 
11367   if (IsIntegerValue) {
11368     const MCExpr *ValueExpr;
11369     SMLoc ValueExprLoc = Parser.getTok().getLoc();
11370     if (Parser.parseExpression(ValueExpr))
11371       return true;
11372 
11373     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ValueExpr);
11374     if (!CE)
11375       return Error(ValueExprLoc, "expected numeric constant");
11376     IntegerValue = CE->getValue();
11377   }
11378 
11379   if (Tag == ARMBuildAttrs::compatibility) {
11380     if (Parser.parseToken(AsmToken::Comma, "comma expected"))
11381       return true;
11382   }
11383 
11384   if (IsStringValue) {
11385     if (Parser.getTok().isNot(AsmToken::String))
11386       return Error(Parser.getTok().getLoc(), "bad string constant");
11387 
11388     StringValue = Parser.getTok().getStringContents();
11389     Parser.Lex();
11390   }
11391 
11392   if (Parser.parseToken(AsmToken::EndOfStatement,
11393                         "unexpected token in '.eabi_attribute' directive"))
11394     return true;
11395 
11396   if (IsIntegerValue && IsStringValue) {
11397     assert(Tag == ARMBuildAttrs::compatibility);
11398     getTargetStreamer().emitIntTextAttribute(Tag, IntegerValue, StringValue);
11399   } else if (IsIntegerValue)
11400     getTargetStreamer().emitAttribute(Tag, IntegerValue);
11401   else if (IsStringValue)
11402     getTargetStreamer().emitTextAttribute(Tag, StringValue);
11403   return false;
11404 }
11405 
11406 /// parseDirectiveCPU
11407 ///  ::= .cpu str
11408 bool ARMAsmParser::parseDirectiveCPU(SMLoc L) {
11409   StringRef CPU = getParser().parseStringToEndOfStatement().trim();
11410   getTargetStreamer().emitTextAttribute(ARMBuildAttrs::CPU_name, CPU);
11411 
11412   // FIXME: This is using table-gen data, but should be moved to
11413   // ARMTargetParser once that is table-gen'd.
11414   if (!getSTI().isCPUStringValid(CPU))
11415     return Error(L, "Unknown CPU name");
11416 
11417   bool WasThumb = isThumb();
11418   MCSubtargetInfo &STI = copySTI();
11419   STI.setDefaultFeatures(CPU, /*TuneCPU*/ CPU, "");
11420   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
11421   FixModeAfterArchChange(WasThumb, L);
11422 
11423   return false;
11424 }
11425 
11426 /// parseDirectiveFPU
11427 ///  ::= .fpu str
11428 bool ARMAsmParser::parseDirectiveFPU(SMLoc L) {
11429   SMLoc FPUNameLoc = getTok().getLoc();
11430   StringRef FPU = getParser().parseStringToEndOfStatement().trim();
11431 
11432   unsigned ID = ARM::parseFPU(FPU);
11433   std::vector<StringRef> Features;
11434   if (!ARM::getFPUFeatures(ID, Features))
11435     return Error(FPUNameLoc, "Unknown FPU name");
11436 
11437   MCSubtargetInfo &STI = copySTI();
11438   for (auto Feature : Features)
11439     STI.ApplyFeatureFlag(Feature);
11440   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
11441 
11442   getTargetStreamer().emitFPU(ID);
11443   return false;
11444 }
11445 
11446 /// parseDirectiveFnStart
11447 ///  ::= .fnstart
11448 bool ARMAsmParser::parseDirectiveFnStart(SMLoc L) {
11449   if (parseToken(AsmToken::EndOfStatement,
11450                  "unexpected token in '.fnstart' directive"))
11451     return true;
11452 
11453   if (UC.hasFnStart()) {
11454     Error(L, ".fnstart starts before the end of previous one");
11455     UC.emitFnStartLocNotes();
11456     return true;
11457   }
11458 
11459   // Reset the unwind directives parser state
11460   UC.reset();
11461 
11462   getTargetStreamer().emitFnStart();
11463 
11464   UC.recordFnStart(L);
11465   return false;
11466 }
11467 
11468 /// parseDirectiveFnEnd
11469 ///  ::= .fnend
11470 bool ARMAsmParser::parseDirectiveFnEnd(SMLoc L) {
11471   if (parseToken(AsmToken::EndOfStatement,
11472                  "unexpected token in '.fnend' directive"))
11473     return true;
11474   // Check the ordering of unwind directives
11475   if (!UC.hasFnStart())
11476     return Error(L, ".fnstart must precede .fnend directive");
11477 
11478   // Reset the unwind directives parser state
11479   getTargetStreamer().emitFnEnd();
11480 
11481   UC.reset();
11482   return false;
11483 }
11484 
11485 /// parseDirectiveCantUnwind
11486 ///  ::= .cantunwind
11487 bool ARMAsmParser::parseDirectiveCantUnwind(SMLoc L) {
11488   if (parseToken(AsmToken::EndOfStatement,
11489                  "unexpected token in '.cantunwind' directive"))
11490     return true;
11491 
11492   UC.recordCantUnwind(L);
11493   // Check the ordering of unwind directives
11494   if (check(!UC.hasFnStart(), L, ".fnstart must precede .cantunwind directive"))
11495     return true;
11496 
11497   if (UC.hasHandlerData()) {
11498     Error(L, ".cantunwind can't be used with .handlerdata directive");
11499     UC.emitHandlerDataLocNotes();
11500     return true;
11501   }
11502   if (UC.hasPersonality()) {
11503     Error(L, ".cantunwind can't be used with .personality directive");
11504     UC.emitPersonalityLocNotes();
11505     return true;
11506   }
11507 
11508   getTargetStreamer().emitCantUnwind();
11509   return false;
11510 }
11511 
11512 /// parseDirectivePersonality
11513 ///  ::= .personality name
11514 bool ARMAsmParser::parseDirectivePersonality(SMLoc L) {
11515   MCAsmParser &Parser = getParser();
11516   bool HasExistingPersonality = UC.hasPersonality();
11517 
11518   // Parse the name of the personality routine
11519   if (Parser.getTok().isNot(AsmToken::Identifier))
11520     return Error(L, "unexpected input in .personality directive.");
11521   StringRef Name(Parser.getTok().getIdentifier());
11522   Parser.Lex();
11523 
11524   if (parseToken(AsmToken::EndOfStatement,
11525                  "unexpected token in '.personality' directive"))
11526     return true;
11527 
11528   UC.recordPersonality(L);
11529 
11530   // Check the ordering of unwind directives
11531   if (!UC.hasFnStart())
11532     return Error(L, ".fnstart must precede .personality directive");
11533   if (UC.cantUnwind()) {
11534     Error(L, ".personality can't be used with .cantunwind directive");
11535     UC.emitCantUnwindLocNotes();
11536     return true;
11537   }
11538   if (UC.hasHandlerData()) {
11539     Error(L, ".personality must precede .handlerdata directive");
11540     UC.emitHandlerDataLocNotes();
11541     return true;
11542   }
11543   if (HasExistingPersonality) {
11544     Error(L, "multiple personality directives");
11545     UC.emitPersonalityLocNotes();
11546     return true;
11547   }
11548 
11549   MCSymbol *PR = getParser().getContext().getOrCreateSymbol(Name);
11550   getTargetStreamer().emitPersonality(PR);
11551   return false;
11552 }
11553 
11554 /// parseDirectiveHandlerData
11555 ///  ::= .handlerdata
11556 bool ARMAsmParser::parseDirectiveHandlerData(SMLoc L) {
11557   if (parseToken(AsmToken::EndOfStatement,
11558                  "unexpected token in '.handlerdata' directive"))
11559     return true;
11560 
11561   UC.recordHandlerData(L);
11562   // Check the ordering of unwind directives
11563   if (!UC.hasFnStart())
11564     return Error(L, ".fnstart must precede .personality directive");
11565   if (UC.cantUnwind()) {
11566     Error(L, ".handlerdata can't be used with .cantunwind directive");
11567     UC.emitCantUnwindLocNotes();
11568     return true;
11569   }
11570 
11571   getTargetStreamer().emitHandlerData();
11572   return false;
11573 }
11574 
11575 /// parseDirectiveSetFP
11576 ///  ::= .setfp fpreg, spreg [, offset]
11577 bool ARMAsmParser::parseDirectiveSetFP(SMLoc L) {
11578   MCAsmParser &Parser = getParser();
11579   // Check the ordering of unwind directives
11580   if (check(!UC.hasFnStart(), L, ".fnstart must precede .setfp directive") ||
11581       check(UC.hasHandlerData(), L,
11582             ".setfp must precede .handlerdata directive"))
11583     return true;
11584 
11585   // Parse fpreg
11586   SMLoc FPRegLoc = Parser.getTok().getLoc();
11587   int FPReg = tryParseRegister();
11588 
11589   if (check(FPReg == -1, FPRegLoc, "frame pointer register expected") ||
11590       Parser.parseToken(AsmToken::Comma, "comma expected"))
11591     return true;
11592 
11593   // Parse spreg
11594   SMLoc SPRegLoc = Parser.getTok().getLoc();
11595   int SPReg = tryParseRegister();
11596   if (check(SPReg == -1, SPRegLoc, "stack pointer register expected") ||
11597       check(SPReg != ARM::SP && SPReg != UC.getFPReg(), SPRegLoc,
11598             "register should be either $sp or the latest fp register"))
11599     return true;
11600 
11601   // Update the frame pointer register
11602   UC.saveFPReg(FPReg);
11603 
11604   // Parse offset
11605   int64_t Offset = 0;
11606   if (Parser.parseOptionalToken(AsmToken::Comma)) {
11607     if (Parser.getTok().isNot(AsmToken::Hash) &&
11608         Parser.getTok().isNot(AsmToken::Dollar))
11609       return Error(Parser.getTok().getLoc(), "'#' expected");
11610     Parser.Lex(); // skip hash token.
11611 
11612     const MCExpr *OffsetExpr;
11613     SMLoc ExLoc = Parser.getTok().getLoc();
11614     SMLoc EndLoc;
11615     if (getParser().parseExpression(OffsetExpr, EndLoc))
11616       return Error(ExLoc, "malformed setfp offset");
11617     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
11618     if (check(!CE, ExLoc, "setfp offset must be an immediate"))
11619       return true;
11620     Offset = CE->getValue();
11621   }
11622 
11623   if (Parser.parseToken(AsmToken::EndOfStatement))
11624     return true;
11625 
11626   getTargetStreamer().emitSetFP(static_cast<unsigned>(FPReg),
11627                                 static_cast<unsigned>(SPReg), Offset);
11628   return false;
11629 }
11630 
11631 /// parseDirective
11632 ///  ::= .pad offset
11633 bool ARMAsmParser::parseDirectivePad(SMLoc L) {
11634   MCAsmParser &Parser = getParser();
11635   // Check the ordering of unwind directives
11636   if (!UC.hasFnStart())
11637     return Error(L, ".fnstart must precede .pad directive");
11638   if (UC.hasHandlerData())
11639     return Error(L, ".pad must precede .handlerdata directive");
11640 
11641   // Parse the offset
11642   if (Parser.getTok().isNot(AsmToken::Hash) &&
11643       Parser.getTok().isNot(AsmToken::Dollar))
11644     return Error(Parser.getTok().getLoc(), "'#' expected");
11645   Parser.Lex(); // skip hash token.
11646 
11647   const MCExpr *OffsetExpr;
11648   SMLoc ExLoc = Parser.getTok().getLoc();
11649   SMLoc EndLoc;
11650   if (getParser().parseExpression(OffsetExpr, EndLoc))
11651     return Error(ExLoc, "malformed pad offset");
11652   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
11653   if (!CE)
11654     return Error(ExLoc, "pad offset must be an immediate");
11655 
11656   if (parseToken(AsmToken::EndOfStatement,
11657                  "unexpected token in '.pad' directive"))
11658     return true;
11659 
11660   getTargetStreamer().emitPad(CE->getValue());
11661   return false;
11662 }
11663 
11664 /// parseDirectiveRegSave
11665 ///  ::= .save  { registers }
11666 ///  ::= .vsave { registers }
11667 bool ARMAsmParser::parseDirectiveRegSave(SMLoc L, bool IsVector) {
11668   // Check the ordering of unwind directives
11669   if (!UC.hasFnStart())
11670     return Error(L, ".fnstart must precede .save or .vsave directives");
11671   if (UC.hasHandlerData())
11672     return Error(L, ".save or .vsave must precede .handlerdata directive");
11673 
11674   // RAII object to make sure parsed operands are deleted.
11675   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> Operands;
11676 
11677   // Parse the register list
11678   if (parseRegisterList(Operands) ||
11679       parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
11680     return true;
11681   ARMOperand &Op = (ARMOperand &)*Operands[0];
11682   if (!IsVector && !Op.isRegList())
11683     return Error(L, ".save expects GPR registers");
11684   if (IsVector && !Op.isDPRRegList())
11685     return Error(L, ".vsave expects DPR registers");
11686 
11687   getTargetStreamer().emitRegSave(Op.getRegList(), IsVector);
11688   return false;
11689 }
11690 
11691 /// parseDirectiveInst
11692 ///  ::= .inst opcode [, ...]
11693 ///  ::= .inst.n opcode [, ...]
11694 ///  ::= .inst.w opcode [, ...]
11695 bool ARMAsmParser::parseDirectiveInst(SMLoc Loc, char Suffix) {
11696   int Width = 4;
11697 
11698   if (isThumb()) {
11699     switch (Suffix) {
11700     case 'n':
11701       Width = 2;
11702       break;
11703     case 'w':
11704       break;
11705     default:
11706       Width = 0;
11707       break;
11708     }
11709   } else {
11710     if (Suffix)
11711       return Error(Loc, "width suffixes are invalid in ARM mode");
11712   }
11713 
11714   auto parseOne = [&]() -> bool {
11715     const MCExpr *Expr;
11716     if (getParser().parseExpression(Expr))
11717       return true;
11718     const MCConstantExpr *Value = dyn_cast_or_null<MCConstantExpr>(Expr);
11719     if (!Value) {
11720       return Error(Loc, "expected constant expression");
11721     }
11722 
11723     char CurSuffix = Suffix;
11724     switch (Width) {
11725     case 2:
11726       if (Value->getValue() > 0xffff)
11727         return Error(Loc, "inst.n operand is too big, use inst.w instead");
11728       break;
11729     case 4:
11730       if (Value->getValue() > 0xffffffff)
11731         return Error(Loc, StringRef(Suffix ? "inst.w" : "inst") +
11732                               " operand is too big");
11733       break;
11734     case 0:
11735       // Thumb mode, no width indicated. Guess from the opcode, if possible.
11736       if (Value->getValue() < 0xe800)
11737         CurSuffix = 'n';
11738       else if (Value->getValue() >= 0xe8000000)
11739         CurSuffix = 'w';
11740       else
11741         return Error(Loc, "cannot determine Thumb instruction size, "
11742                           "use inst.n/inst.w instead");
11743       break;
11744     default:
11745       llvm_unreachable("only supported widths are 2 and 4");
11746     }
11747 
11748     getTargetStreamer().emitInst(Value->getValue(), CurSuffix);
11749     return false;
11750   };
11751 
11752   if (parseOptionalToken(AsmToken::EndOfStatement))
11753     return Error(Loc, "expected expression following directive");
11754   if (parseMany(parseOne))
11755     return true;
11756   return false;
11757 }
11758 
11759 /// parseDirectiveLtorg
11760 ///  ::= .ltorg | .pool
11761 bool ARMAsmParser::parseDirectiveLtorg(SMLoc L) {
11762   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
11763     return true;
11764   getTargetStreamer().emitCurrentConstantPool();
11765   return false;
11766 }
11767 
11768 bool ARMAsmParser::parseDirectiveEven(SMLoc L) {
11769   const MCSection *Section = getStreamer().getCurrentSectionOnly();
11770 
11771   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
11772     return true;
11773 
11774   if (!Section) {
11775     getStreamer().InitSections(false);
11776     Section = getStreamer().getCurrentSectionOnly();
11777   }
11778 
11779   assert(Section && "must have section to emit alignment");
11780   if (Section->UseCodeAlign())
11781     getStreamer().emitCodeAlignment(2);
11782   else
11783     getStreamer().emitValueToAlignment(2);
11784 
11785   return false;
11786 }
11787 
11788 /// parseDirectivePersonalityIndex
11789 ///   ::= .personalityindex index
11790 bool ARMAsmParser::parseDirectivePersonalityIndex(SMLoc L) {
11791   MCAsmParser &Parser = getParser();
11792   bool HasExistingPersonality = UC.hasPersonality();
11793 
11794   const MCExpr *IndexExpression;
11795   SMLoc IndexLoc = Parser.getTok().getLoc();
11796   if (Parser.parseExpression(IndexExpression) ||
11797       parseToken(AsmToken::EndOfStatement,
11798                  "unexpected token in '.personalityindex' directive")) {
11799     return true;
11800   }
11801 
11802   UC.recordPersonalityIndex(L);
11803 
11804   if (!UC.hasFnStart()) {
11805     return Error(L, ".fnstart must precede .personalityindex directive");
11806   }
11807   if (UC.cantUnwind()) {
11808     Error(L, ".personalityindex cannot be used with .cantunwind");
11809     UC.emitCantUnwindLocNotes();
11810     return true;
11811   }
11812   if (UC.hasHandlerData()) {
11813     Error(L, ".personalityindex must precede .handlerdata directive");
11814     UC.emitHandlerDataLocNotes();
11815     return true;
11816   }
11817   if (HasExistingPersonality) {
11818     Error(L, "multiple personality directives");
11819     UC.emitPersonalityLocNotes();
11820     return true;
11821   }
11822 
11823   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(IndexExpression);
11824   if (!CE)
11825     return Error(IndexLoc, "index must be a constant number");
11826   if (CE->getValue() < 0 || CE->getValue() >= ARM::EHABI::NUM_PERSONALITY_INDEX)
11827     return Error(IndexLoc,
11828                  "personality routine index should be in range [0-3]");
11829 
11830   getTargetStreamer().emitPersonalityIndex(CE->getValue());
11831   return false;
11832 }
11833 
11834 /// parseDirectiveUnwindRaw
11835 ///   ::= .unwind_raw offset, opcode [, opcode...]
11836 bool ARMAsmParser::parseDirectiveUnwindRaw(SMLoc L) {
11837   MCAsmParser &Parser = getParser();
11838   int64_t StackOffset;
11839   const MCExpr *OffsetExpr;
11840   SMLoc OffsetLoc = getLexer().getLoc();
11841 
11842   if (!UC.hasFnStart())
11843     return Error(L, ".fnstart must precede .unwind_raw directives");
11844   if (getParser().parseExpression(OffsetExpr))
11845     return Error(OffsetLoc, "expected expression");
11846 
11847   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
11848   if (!CE)
11849     return Error(OffsetLoc, "offset must be a constant");
11850 
11851   StackOffset = CE->getValue();
11852 
11853   if (Parser.parseToken(AsmToken::Comma, "expected comma"))
11854     return true;
11855 
11856   SmallVector<uint8_t, 16> Opcodes;
11857 
11858   auto parseOne = [&]() -> bool {
11859     const MCExpr *OE = nullptr;
11860     SMLoc OpcodeLoc = getLexer().getLoc();
11861     if (check(getLexer().is(AsmToken::EndOfStatement) ||
11862                   Parser.parseExpression(OE),
11863               OpcodeLoc, "expected opcode expression"))
11864       return true;
11865     const MCConstantExpr *OC = dyn_cast<MCConstantExpr>(OE);
11866     if (!OC)
11867       return Error(OpcodeLoc, "opcode value must be a constant");
11868     const int64_t Opcode = OC->getValue();
11869     if (Opcode & ~0xff)
11870       return Error(OpcodeLoc, "invalid opcode");
11871     Opcodes.push_back(uint8_t(Opcode));
11872     return false;
11873   };
11874 
11875   // Must have at least 1 element
11876   SMLoc OpcodeLoc = getLexer().getLoc();
11877   if (parseOptionalToken(AsmToken::EndOfStatement))
11878     return Error(OpcodeLoc, "expected opcode expression");
11879   if (parseMany(parseOne))
11880     return true;
11881 
11882   getTargetStreamer().emitUnwindRaw(StackOffset, Opcodes);
11883   return false;
11884 }
11885 
11886 /// parseDirectiveTLSDescSeq
11887 ///   ::= .tlsdescseq tls-variable
11888 bool ARMAsmParser::parseDirectiveTLSDescSeq(SMLoc L) {
11889   MCAsmParser &Parser = getParser();
11890 
11891   if (getLexer().isNot(AsmToken::Identifier))
11892     return TokError("expected variable after '.tlsdescseq' directive");
11893 
11894   const MCSymbolRefExpr *SRE =
11895     MCSymbolRefExpr::create(Parser.getTok().getIdentifier(),
11896                             MCSymbolRefExpr::VK_ARM_TLSDESCSEQ, getContext());
11897   Lex();
11898 
11899   if (parseToken(AsmToken::EndOfStatement,
11900                  "unexpected token in '.tlsdescseq' directive"))
11901     return true;
11902 
11903   getTargetStreamer().AnnotateTLSDescriptorSequence(SRE);
11904   return false;
11905 }
11906 
11907 /// parseDirectiveMovSP
11908 ///  ::= .movsp reg [, #offset]
11909 bool ARMAsmParser::parseDirectiveMovSP(SMLoc L) {
11910   MCAsmParser &Parser = getParser();
11911   if (!UC.hasFnStart())
11912     return Error(L, ".fnstart must precede .movsp directives");
11913   if (UC.getFPReg() != ARM::SP)
11914     return Error(L, "unexpected .movsp directive");
11915 
11916   SMLoc SPRegLoc = Parser.getTok().getLoc();
11917   int SPReg = tryParseRegister();
11918   if (SPReg == -1)
11919     return Error(SPRegLoc, "register expected");
11920   if (SPReg == ARM::SP || SPReg == ARM::PC)
11921     return Error(SPRegLoc, "sp and pc are not permitted in .movsp directive");
11922 
11923   int64_t Offset = 0;
11924   if (Parser.parseOptionalToken(AsmToken::Comma)) {
11925     if (Parser.parseToken(AsmToken::Hash, "expected #constant"))
11926       return true;
11927 
11928     const MCExpr *OffsetExpr;
11929     SMLoc OffsetLoc = Parser.getTok().getLoc();
11930 
11931     if (Parser.parseExpression(OffsetExpr))
11932       return Error(OffsetLoc, "malformed offset expression");
11933 
11934     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
11935     if (!CE)
11936       return Error(OffsetLoc, "offset must be an immediate constant");
11937 
11938     Offset = CE->getValue();
11939   }
11940 
11941   if (parseToken(AsmToken::EndOfStatement,
11942                  "unexpected token in '.movsp' directive"))
11943     return true;
11944 
11945   getTargetStreamer().emitMovSP(SPReg, Offset);
11946   UC.saveFPReg(SPReg);
11947 
11948   return false;
11949 }
11950 
11951 /// parseDirectiveObjectArch
11952 ///   ::= .object_arch name
11953 bool ARMAsmParser::parseDirectiveObjectArch(SMLoc L) {
11954   MCAsmParser &Parser = getParser();
11955   if (getLexer().isNot(AsmToken::Identifier))
11956     return Error(getLexer().getLoc(), "unexpected token");
11957 
11958   StringRef Arch = Parser.getTok().getString();
11959   SMLoc ArchLoc = Parser.getTok().getLoc();
11960   Lex();
11961 
11962   ARM::ArchKind ID = ARM::parseArch(Arch);
11963 
11964   if (ID == ARM::ArchKind::INVALID)
11965     return Error(ArchLoc, "unknown architecture '" + Arch + "'");
11966   if (parseToken(AsmToken::EndOfStatement))
11967     return true;
11968 
11969   getTargetStreamer().emitObjectArch(ID);
11970   return false;
11971 }
11972 
11973 /// parseDirectiveAlign
11974 ///   ::= .align
11975 bool ARMAsmParser::parseDirectiveAlign(SMLoc L) {
11976   // NOTE: if this is not the end of the statement, fall back to the target
11977   // agnostic handling for this directive which will correctly handle this.
11978   if (parseOptionalToken(AsmToken::EndOfStatement)) {
11979     // '.align' is target specifically handled to mean 2**2 byte alignment.
11980     const MCSection *Section = getStreamer().getCurrentSectionOnly();
11981     assert(Section && "must have section to emit alignment");
11982     if (Section->UseCodeAlign())
11983       getStreamer().emitCodeAlignment(4, 0);
11984     else
11985       getStreamer().emitValueToAlignment(4, 0, 1, 0);
11986     return false;
11987   }
11988   return true;
11989 }
11990 
11991 /// parseDirectiveThumbSet
11992 ///  ::= .thumb_set name, value
11993 bool ARMAsmParser::parseDirectiveThumbSet(SMLoc L) {
11994   MCAsmParser &Parser = getParser();
11995 
11996   StringRef Name;
11997   if (check(Parser.parseIdentifier(Name),
11998             "expected identifier after '.thumb_set'") ||
11999       parseToken(AsmToken::Comma, "expected comma after name '" + Name + "'"))
12000     return true;
12001 
12002   MCSymbol *Sym;
12003   const MCExpr *Value;
12004   if (MCParserUtils::parseAssignmentExpression(Name, /* allow_redef */ true,
12005                                                Parser, Sym, Value))
12006     return true;
12007 
12008   getTargetStreamer().emitThumbSet(Sym, Value);
12009   return false;
12010 }
12011 
12012 /// Force static initialization.
12013 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeARMAsmParser() {
12014   RegisterMCAsmParser<ARMAsmParser> X(getTheARMLETarget());
12015   RegisterMCAsmParser<ARMAsmParser> Y(getTheARMBETarget());
12016   RegisterMCAsmParser<ARMAsmParser> A(getTheThumbLETarget());
12017   RegisterMCAsmParser<ARMAsmParser> B(getTheThumbBETarget());
12018 }
12019 
12020 #define GET_REGISTER_MATCHER
12021 #define GET_SUBTARGET_FEATURE_NAME
12022 #define GET_MATCHER_IMPLEMENTATION
12023 #define GET_MNEMONIC_SPELL_CHECKER
12024 #include "ARMGenAsmMatcher.inc"
12025 
12026 // Some diagnostics need to vary with subtarget features, so they are handled
12027 // here. For example, the DPR class has either 16 or 32 registers, depending
12028 // on the FPU available.
12029 const char *
12030 ARMAsmParser::getCustomOperandDiag(ARMMatchResultTy MatchError) {
12031   switch (MatchError) {
12032   // rGPR contains sp starting with ARMv8.
12033   case Match_rGPR:
12034     return hasV8Ops() ? "operand must be a register in range [r0, r14]"
12035                       : "operand must be a register in range [r0, r12] or r14";
12036   // DPR contains 16 registers for some FPUs, and 32 for others.
12037   case Match_DPR:
12038     return hasD32() ? "operand must be a register in range [d0, d31]"
12039                     : "operand must be a register in range [d0, d15]";
12040   case Match_DPR_RegList:
12041     return hasD32() ? "operand must be a list of registers in range [d0, d31]"
12042                     : "operand must be a list of registers in range [d0, d15]";
12043 
12044   // For all other diags, use the static string from tablegen.
12045   default:
12046     return getMatchKindDiag(MatchError);
12047   }
12048 }
12049 
12050 // Process the list of near-misses, throwing away ones we don't want to report
12051 // to the user, and converting the rest to a source location and string that
12052 // should be reported.
12053 void
12054 ARMAsmParser::FilterNearMisses(SmallVectorImpl<NearMissInfo> &NearMissesIn,
12055                                SmallVectorImpl<NearMissMessage> &NearMissesOut,
12056                                SMLoc IDLoc, OperandVector &Operands) {
12057   // TODO: If operand didn't match, sub in a dummy one and run target
12058   // predicate, so that we can avoid reporting near-misses that are invalid?
12059   // TODO: Many operand types dont have SuperClasses set, so we report
12060   // redundant ones.
12061   // TODO: Some operands are superclasses of registers (e.g.
12062   // MCK_RegShiftedImm), we don't have any way to represent that currently.
12063   // TODO: This is not all ARM-specific, can some of it be factored out?
12064 
12065   // Record some information about near-misses that we have already seen, so
12066   // that we can avoid reporting redundant ones. For example, if there are
12067   // variants of an instruction that take 8- and 16-bit immediates, we want
12068   // to only report the widest one.
12069   std::multimap<unsigned, unsigned> OperandMissesSeen;
12070   SmallSet<FeatureBitset, 4> FeatureMissesSeen;
12071   bool ReportedTooFewOperands = false;
12072 
12073   // Process the near-misses in reverse order, so that we see more general ones
12074   // first, and so can avoid emitting more specific ones.
12075   for (NearMissInfo &I : reverse(NearMissesIn)) {
12076     switch (I.getKind()) {
12077     case NearMissInfo::NearMissOperand: {
12078       SMLoc OperandLoc =
12079           ((ARMOperand &)*Operands[I.getOperandIndex()]).getStartLoc();
12080       const char *OperandDiag =
12081           getCustomOperandDiag((ARMMatchResultTy)I.getOperandError());
12082 
12083       // If we have already emitted a message for a superclass, don't also report
12084       // the sub-class. We consider all operand classes that we don't have a
12085       // specialised diagnostic for to be equal for the propose of this check,
12086       // so that we don't report the generic error multiple times on the same
12087       // operand.
12088       unsigned DupCheckMatchClass = OperandDiag ? I.getOperandClass() : ~0U;
12089       auto PrevReports = OperandMissesSeen.equal_range(I.getOperandIndex());
12090       if (std::any_of(PrevReports.first, PrevReports.second,
12091                       [DupCheckMatchClass](
12092                           const std::pair<unsigned, unsigned> Pair) {
12093             if (DupCheckMatchClass == ~0U || Pair.second == ~0U)
12094               return Pair.second == DupCheckMatchClass;
12095             else
12096               return isSubclass((MatchClassKind)DupCheckMatchClass,
12097                                 (MatchClassKind)Pair.second);
12098           }))
12099         break;
12100       OperandMissesSeen.insert(
12101           std::make_pair(I.getOperandIndex(), DupCheckMatchClass));
12102 
12103       NearMissMessage Message;
12104       Message.Loc = OperandLoc;
12105       if (OperandDiag) {
12106         Message.Message = OperandDiag;
12107       } else if (I.getOperandClass() == InvalidMatchClass) {
12108         Message.Message = "too many operands for instruction";
12109       } else {
12110         Message.Message = "invalid operand for instruction";
12111         LLVM_DEBUG(
12112             dbgs() << "Missing diagnostic string for operand class "
12113                    << getMatchClassName((MatchClassKind)I.getOperandClass())
12114                    << I.getOperandClass() << ", error " << I.getOperandError()
12115                    << ", opcode " << MII.getName(I.getOpcode()) << "\n");
12116       }
12117       NearMissesOut.emplace_back(Message);
12118       break;
12119     }
12120     case NearMissInfo::NearMissFeature: {
12121       const FeatureBitset &MissingFeatures = I.getFeatures();
12122       // Don't report the same set of features twice.
12123       if (FeatureMissesSeen.count(MissingFeatures))
12124         break;
12125       FeatureMissesSeen.insert(MissingFeatures);
12126 
12127       // Special case: don't report a feature set which includes arm-mode for
12128       // targets that don't have ARM mode.
12129       if (MissingFeatures.test(Feature_IsARMBit) && !hasARM())
12130         break;
12131       // Don't report any near-misses that both require switching instruction
12132       // set, and adding other subtarget features.
12133       if (isThumb() && MissingFeatures.test(Feature_IsARMBit) &&
12134           MissingFeatures.count() > 1)
12135         break;
12136       if (!isThumb() && MissingFeatures.test(Feature_IsThumbBit) &&
12137           MissingFeatures.count() > 1)
12138         break;
12139       if (!isThumb() && MissingFeatures.test(Feature_IsThumb2Bit) &&
12140           (MissingFeatures & ~FeatureBitset({Feature_IsThumb2Bit,
12141                                              Feature_IsThumbBit})).any())
12142         break;
12143       if (isMClass() && MissingFeatures.test(Feature_HasNEONBit))
12144         break;
12145 
12146       NearMissMessage Message;
12147       Message.Loc = IDLoc;
12148       raw_svector_ostream OS(Message.Message);
12149 
12150       OS << "instruction requires:";
12151       for (unsigned i = 0, e = MissingFeatures.size(); i != e; ++i)
12152         if (MissingFeatures.test(i))
12153           OS << ' ' << getSubtargetFeatureName(i);
12154 
12155       NearMissesOut.emplace_back(Message);
12156 
12157       break;
12158     }
12159     case NearMissInfo::NearMissPredicate: {
12160       NearMissMessage Message;
12161       Message.Loc = IDLoc;
12162       switch (I.getPredicateError()) {
12163       case Match_RequiresNotITBlock:
12164         Message.Message = "flag setting instruction only valid outside IT block";
12165         break;
12166       case Match_RequiresITBlock:
12167         Message.Message = "instruction only valid inside IT block";
12168         break;
12169       case Match_RequiresV6:
12170         Message.Message = "instruction variant requires ARMv6 or later";
12171         break;
12172       case Match_RequiresThumb2:
12173         Message.Message = "instruction variant requires Thumb2";
12174         break;
12175       case Match_RequiresV8:
12176         Message.Message = "instruction variant requires ARMv8 or later";
12177         break;
12178       case Match_RequiresFlagSetting:
12179         Message.Message = "no flag-preserving variant of this instruction available";
12180         break;
12181       case Match_InvalidOperand:
12182         Message.Message = "invalid operand for instruction";
12183         break;
12184       default:
12185         llvm_unreachable("Unhandled target predicate error");
12186         break;
12187       }
12188       NearMissesOut.emplace_back(Message);
12189       break;
12190     }
12191     case NearMissInfo::NearMissTooFewOperands: {
12192       if (!ReportedTooFewOperands) {
12193         SMLoc EndLoc = ((ARMOperand &)*Operands.back()).getEndLoc();
12194         NearMissesOut.emplace_back(NearMissMessage{
12195             EndLoc, StringRef("too few operands for instruction")});
12196         ReportedTooFewOperands = true;
12197       }
12198       break;
12199     }
12200     case NearMissInfo::NoNearMiss:
12201       // This should never leave the matcher.
12202       llvm_unreachable("not a near-miss");
12203       break;
12204     }
12205   }
12206 }
12207 
12208 void ARMAsmParser::ReportNearMisses(SmallVectorImpl<NearMissInfo> &NearMisses,
12209                                     SMLoc IDLoc, OperandVector &Operands) {
12210   SmallVector<NearMissMessage, 4> Messages;
12211   FilterNearMisses(NearMisses, Messages, IDLoc, Operands);
12212 
12213   if (Messages.size() == 0) {
12214     // No near-misses were found, so the best we can do is "invalid
12215     // instruction".
12216     Error(IDLoc, "invalid instruction");
12217   } else if (Messages.size() == 1) {
12218     // One near miss was found, report it as the sole error.
12219     Error(Messages[0].Loc, Messages[0].Message);
12220   } else {
12221     // More than one near miss, so report a generic "invalid instruction"
12222     // error, followed by notes for each of the near-misses.
12223     Error(IDLoc, "invalid instruction, any one of the following would fix this:");
12224     for (auto &M : Messages) {
12225       Note(M.Loc, M.Message);
12226     }
12227   }
12228 }
12229 
12230 bool ARMAsmParser::enableArchExtFeature(StringRef Name, SMLoc &ExtLoc) {
12231   // FIXME: This structure should be moved inside ARMTargetParser
12232   // when we start to table-generate them, and we can use the ARM
12233   // flags below, that were generated by table-gen.
12234   static const struct {
12235     const uint64_t Kind;
12236     const FeatureBitset ArchCheck;
12237     const FeatureBitset Features;
12238   } Extensions[] = {
12239       {ARM::AEK_CRC, {Feature_HasV8Bit}, {ARM::FeatureCRC}},
12240       {ARM::AEK_AES,
12241        {Feature_HasV8Bit},
12242        {ARM::FeatureAES, ARM::FeatureNEON, ARM::FeatureFPARMv8}},
12243       {ARM::AEK_SHA2,
12244        {Feature_HasV8Bit},
12245        {ARM::FeatureSHA2, ARM::FeatureNEON, ARM::FeatureFPARMv8}},
12246       {ARM::AEK_CRYPTO,
12247        {Feature_HasV8Bit},
12248        {ARM::FeatureCrypto, ARM::FeatureNEON, ARM::FeatureFPARMv8}},
12249       {ARM::AEK_FP,
12250        {Feature_HasV8Bit},
12251        {ARM::FeatureVFP2_SP, ARM::FeatureFPARMv8}},
12252       {(ARM::AEK_HWDIVTHUMB | ARM::AEK_HWDIVARM),
12253        {Feature_HasV7Bit, Feature_IsNotMClassBit},
12254        {ARM::FeatureHWDivThumb, ARM::FeatureHWDivARM}},
12255       {ARM::AEK_MP,
12256        {Feature_HasV7Bit, Feature_IsNotMClassBit},
12257        {ARM::FeatureMP}},
12258       {ARM::AEK_SIMD,
12259        {Feature_HasV8Bit},
12260        {ARM::FeatureNEON, ARM::FeatureVFP2_SP, ARM::FeatureFPARMv8}},
12261       {ARM::AEK_SEC, {Feature_HasV6KBit}, {ARM::FeatureTrustZone}},
12262       // FIXME: Only available in A-class, isel not predicated
12263       {ARM::AEK_VIRT, {Feature_HasV7Bit}, {ARM::FeatureVirtualization}},
12264       {ARM::AEK_FP16,
12265        {Feature_HasV8_2aBit},
12266        {ARM::FeatureFPARMv8, ARM::FeatureFullFP16}},
12267       {ARM::AEK_RAS, {Feature_HasV8Bit}, {ARM::FeatureRAS}},
12268       {ARM::AEK_LOB, {Feature_HasV8_1MMainlineBit}, {ARM::FeatureLOB}},
12269       // FIXME: Unsupported extensions.
12270       {ARM::AEK_OS, {}, {}},
12271       {ARM::AEK_IWMMXT, {}, {}},
12272       {ARM::AEK_IWMMXT2, {}, {}},
12273       {ARM::AEK_MAVERICK, {}, {}},
12274       {ARM::AEK_XSCALE, {}, {}},
12275   };
12276   bool EnableFeature = true;
12277   if (Name.startswith_lower("no")) {
12278     EnableFeature = false;
12279     Name = Name.substr(2);
12280   }
12281   uint64_t FeatureKind = ARM::parseArchExt(Name);
12282   if (FeatureKind == ARM::AEK_INVALID)
12283     return Error(ExtLoc, "unknown architectural extension: " + Name);
12284 
12285   for (const auto &Extension : Extensions) {
12286     if (Extension.Kind != FeatureKind)
12287       continue;
12288 
12289     if (Extension.Features.none())
12290       return Error(ExtLoc, "unsupported architectural extension: " + Name);
12291 
12292     if ((getAvailableFeatures() & Extension.ArchCheck) != Extension.ArchCheck)
12293       return Error(ExtLoc, "architectural extension '" + Name +
12294                                "' is not "
12295                                "allowed for the current base architecture");
12296 
12297     MCSubtargetInfo &STI = copySTI();
12298     if (EnableFeature) {
12299       STI.SetFeatureBitsTransitively(Extension.Features);
12300     } else {
12301       STI.ClearFeatureBitsTransitively(Extension.Features);
12302     }
12303     FeatureBitset Features = ComputeAvailableFeatures(STI.getFeatureBits());
12304     setAvailableFeatures(Features);
12305     return true;
12306   }
12307   return false;
12308 }
12309 
12310 /// parseDirectiveArchExtension
12311 ///   ::= .arch_extension [no]feature
12312 bool ARMAsmParser::parseDirectiveArchExtension(SMLoc L) {
12313 
12314   MCAsmParser &Parser = getParser();
12315 
12316   if (getLexer().isNot(AsmToken::Identifier))
12317     return Error(getLexer().getLoc(), "expected architecture extension name");
12318 
12319   StringRef Name = Parser.getTok().getString();
12320   SMLoc ExtLoc = Parser.getTok().getLoc();
12321   Lex();
12322 
12323   if (parseToken(AsmToken::EndOfStatement,
12324                  "unexpected token in '.arch_extension' directive"))
12325     return true;
12326 
12327   if (Name == "nocrypto") {
12328     enableArchExtFeature("nosha2", ExtLoc);
12329     enableArchExtFeature("noaes", ExtLoc);
12330   }
12331 
12332   if (enableArchExtFeature(Name, ExtLoc))
12333     return false;
12334 
12335   return Error(ExtLoc, "unknown architectural extension: " + Name);
12336 }
12337 
12338 // Define this matcher function after the auto-generated include so we
12339 // have the match class enum definitions.
12340 unsigned ARMAsmParser::validateTargetOperandClass(MCParsedAsmOperand &AsmOp,
12341                                                   unsigned Kind) {
12342   ARMOperand &Op = static_cast<ARMOperand &>(AsmOp);
12343   // If the kind is a token for a literal immediate, check if our asm
12344   // operand matches. This is for InstAliases which have a fixed-value
12345   // immediate in the syntax.
12346   switch (Kind) {
12347   default: break;
12348   case MCK__HASH_0:
12349     if (Op.isImm())
12350       if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm()))
12351         if (CE->getValue() == 0)
12352           return Match_Success;
12353     break;
12354   case MCK__HASH_8:
12355     if (Op.isImm())
12356       if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm()))
12357         if (CE->getValue() == 8)
12358           return Match_Success;
12359     break;
12360   case MCK__HASH_16:
12361     if (Op.isImm())
12362       if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm()))
12363         if (CE->getValue() == 16)
12364           return Match_Success;
12365     break;
12366   case MCK_ModImm:
12367     if (Op.isImm()) {
12368       const MCExpr *SOExpr = Op.getImm();
12369       int64_t Value;
12370       if (!SOExpr->evaluateAsAbsolute(Value))
12371         return Match_Success;
12372       assert((Value >= std::numeric_limits<int32_t>::min() &&
12373               Value <= std::numeric_limits<uint32_t>::max()) &&
12374              "expression value must be representable in 32 bits");
12375     }
12376     break;
12377   case MCK_rGPR:
12378     if (hasV8Ops() && Op.isReg() && Op.getReg() == ARM::SP)
12379       return Match_Success;
12380     return Match_rGPR;
12381   case MCK_GPRPair:
12382     if (Op.isReg() &&
12383         MRI->getRegClass(ARM::GPRRegClassID).contains(Op.getReg()))
12384       return Match_Success;
12385     break;
12386   }
12387   return Match_InvalidOperand;
12388 }
12389 
12390 bool ARMAsmParser::isMnemonicVPTPredicable(StringRef Mnemonic,
12391                                            StringRef ExtraToken) {
12392   if (!hasMVE())
12393     return false;
12394 
12395   return Mnemonic.startswith("vabav") || Mnemonic.startswith("vaddv") ||
12396          Mnemonic.startswith("vaddlv") || Mnemonic.startswith("vminnmv") ||
12397          Mnemonic.startswith("vminnmav") || Mnemonic.startswith("vminv") ||
12398          Mnemonic.startswith("vminav") || Mnemonic.startswith("vmaxnmv") ||
12399          Mnemonic.startswith("vmaxnmav") || Mnemonic.startswith("vmaxv") ||
12400          Mnemonic.startswith("vmaxav") || Mnemonic.startswith("vmladav") ||
12401          Mnemonic.startswith("vrmlaldavh") || Mnemonic.startswith("vrmlalvh") ||
12402          Mnemonic.startswith("vmlsdav") || Mnemonic.startswith("vmlav") ||
12403          Mnemonic.startswith("vmlaldav") || Mnemonic.startswith("vmlalv") ||
12404          Mnemonic.startswith("vmaxnm") || Mnemonic.startswith("vminnm") ||
12405          Mnemonic.startswith("vmax") || Mnemonic.startswith("vmin") ||
12406          Mnemonic.startswith("vshlc") || Mnemonic.startswith("vmovlt") ||
12407          Mnemonic.startswith("vmovlb") || Mnemonic.startswith("vshll") ||
12408          Mnemonic.startswith("vrshrn") || Mnemonic.startswith("vshrn") ||
12409          Mnemonic.startswith("vqrshrun") || Mnemonic.startswith("vqshrun") ||
12410          Mnemonic.startswith("vqrshrn") || Mnemonic.startswith("vqshrn") ||
12411          Mnemonic.startswith("vbic") || Mnemonic.startswith("vrev64") ||
12412          Mnemonic.startswith("vrev32") || Mnemonic.startswith("vrev16") ||
12413          Mnemonic.startswith("vmvn") || Mnemonic.startswith("veor") ||
12414          Mnemonic.startswith("vorn") || Mnemonic.startswith("vorr") ||
12415          Mnemonic.startswith("vand") || Mnemonic.startswith("vmul") ||
12416          Mnemonic.startswith("vqrdmulh") || Mnemonic.startswith("vqdmulh") ||
12417          Mnemonic.startswith("vsub") || Mnemonic.startswith("vadd") ||
12418          Mnemonic.startswith("vqsub") || Mnemonic.startswith("vqadd") ||
12419          Mnemonic.startswith("vabd") || Mnemonic.startswith("vrhadd") ||
12420          Mnemonic.startswith("vhsub") || Mnemonic.startswith("vhadd") ||
12421          Mnemonic.startswith("vdup") || Mnemonic.startswith("vcls") ||
12422          Mnemonic.startswith("vclz") || Mnemonic.startswith("vneg") ||
12423          Mnemonic.startswith("vabs") || Mnemonic.startswith("vqneg") ||
12424          Mnemonic.startswith("vqabs") ||
12425          (Mnemonic.startswith("vrint") && Mnemonic != "vrintr") ||
12426          Mnemonic.startswith("vcmla") || Mnemonic.startswith("vfma") ||
12427          Mnemonic.startswith("vfms") || Mnemonic.startswith("vcadd") ||
12428          Mnemonic.startswith("vadd") || Mnemonic.startswith("vsub") ||
12429          Mnemonic.startswith("vshl") || Mnemonic.startswith("vqshl") ||
12430          Mnemonic.startswith("vqrshl") || Mnemonic.startswith("vrshl") ||
12431          Mnemonic.startswith("vsri") || Mnemonic.startswith("vsli") ||
12432          Mnemonic.startswith("vrshr") || Mnemonic.startswith("vshr") ||
12433          Mnemonic.startswith("vpsel") || Mnemonic.startswith("vcmp") ||
12434          Mnemonic.startswith("vqdmladh") || Mnemonic.startswith("vqrdmladh") ||
12435          Mnemonic.startswith("vqdmlsdh") || Mnemonic.startswith("vqrdmlsdh") ||
12436          Mnemonic.startswith("vcmul") || Mnemonic.startswith("vrmulh") ||
12437          Mnemonic.startswith("vqmovn") || Mnemonic.startswith("vqmovun") ||
12438          Mnemonic.startswith("vmovnt") || Mnemonic.startswith("vmovnb") ||
12439          Mnemonic.startswith("vmaxa") || Mnemonic.startswith("vmaxnma") ||
12440          Mnemonic.startswith("vhcadd") || Mnemonic.startswith("vadc") ||
12441          Mnemonic.startswith("vsbc") || Mnemonic.startswith("vrshr") ||
12442          Mnemonic.startswith("vshr") || Mnemonic.startswith("vstrb") ||
12443          Mnemonic.startswith("vldrb") ||
12444          (Mnemonic.startswith("vstrh") && Mnemonic != "vstrhi") ||
12445          (Mnemonic.startswith("vldrh") && Mnemonic != "vldrhi") ||
12446          Mnemonic.startswith("vstrw") || Mnemonic.startswith("vldrw") ||
12447          Mnemonic.startswith("vldrd") || Mnemonic.startswith("vstrd") ||
12448          Mnemonic.startswith("vqdmull") || Mnemonic.startswith("vbrsr") ||
12449          Mnemonic.startswith("vfmas") || Mnemonic.startswith("vmlas") ||
12450          Mnemonic.startswith("vmla") || Mnemonic.startswith("vqdmlash") ||
12451          Mnemonic.startswith("vqdmlah") || Mnemonic.startswith("vqrdmlash") ||
12452          Mnemonic.startswith("vqrdmlah") || Mnemonic.startswith("viwdup") ||
12453          Mnemonic.startswith("vdwdup") || Mnemonic.startswith("vidup") ||
12454          Mnemonic.startswith("vddup") || Mnemonic.startswith("vctp") ||
12455          Mnemonic.startswith("vpnot") || Mnemonic.startswith("vbic") ||
12456          Mnemonic.startswith("vrmlsldavh") || Mnemonic.startswith("vmlsldav") ||
12457          Mnemonic.startswith("vcvt") ||
12458          MS.isVPTPredicableCDEInstr(Mnemonic) ||
12459          (Mnemonic.startswith("vmov") &&
12460           !(ExtraToken == ".f16" || ExtraToken == ".32" ||
12461             ExtraToken == ".16" || ExtraToken == ".8"));
12462 }
12463