1 //===- ARMAsmParser.cpp - Parse ARM assembly to MCInst instructions -------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "ARMFeatures.h"
10 #include "ARMBaseInstrInfo.h"
11 #include "Utils/ARMBaseInfo.h"
12 #include "MCTargetDesc/ARMAddressingModes.h"
13 #include "MCTargetDesc/ARMBaseInfo.h"
14 #include "MCTargetDesc/ARMInstPrinter.h"
15 #include "MCTargetDesc/ARMMCExpr.h"
16 #include "MCTargetDesc/ARMMCTargetDesc.h"
17 #include "TargetInfo/ARMTargetInfo.h"
18 #include "llvm/ADT/APFloat.h"
19 #include "llvm/ADT/APInt.h"
20 #include "llvm/ADT/None.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/StringMap.h"
25 #include "llvm/ADT/StringRef.h"
26 #include "llvm/ADT/StringSwitch.h"
27 #include "llvm/ADT/Triple.h"
28 #include "llvm/ADT/Twine.h"
29 #include "llvm/MC/MCContext.h"
30 #include "llvm/MC/MCExpr.h"
31 #include "llvm/MC/MCInst.h"
32 #include "llvm/MC/MCInstrDesc.h"
33 #include "llvm/MC/MCInstrInfo.h"
34 #include "llvm/MC/MCObjectFileInfo.h"
35 #include "llvm/MC/MCParser/MCAsmLexer.h"
36 #include "llvm/MC/MCParser/MCAsmParser.h"
37 #include "llvm/MC/MCParser/MCAsmParserExtension.h"
38 #include "llvm/MC/MCParser/MCAsmParserUtils.h"
39 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
40 #include "llvm/MC/MCParser/MCTargetAsmParser.h"
41 #include "llvm/MC/MCRegisterInfo.h"
42 #include "llvm/MC/MCSection.h"
43 #include "llvm/MC/MCStreamer.h"
44 #include "llvm/MC/MCSubtargetInfo.h"
45 #include "llvm/MC/MCSymbol.h"
46 #include "llvm/MC/SubtargetFeature.h"
47 #include "llvm/Support/ARMBuildAttributes.h"
48 #include "llvm/Support/ARMEHABI.h"
49 #include "llvm/Support/Casting.h"
50 #include "llvm/Support/CommandLine.h"
51 #include "llvm/Support/Compiler.h"
52 #include "llvm/Support/ErrorHandling.h"
53 #include "llvm/Support/MathExtras.h"
54 #include "llvm/Support/SMLoc.h"
55 #include "llvm/Support/TargetParser.h"
56 #include "llvm/Support/TargetRegistry.h"
57 #include "llvm/Support/raw_ostream.h"
58 #include <algorithm>
59 #include <cassert>
60 #include <cstddef>
61 #include <cstdint>
62 #include <iterator>
63 #include <limits>
64 #include <memory>
65 #include <string>
66 #include <utility>
67 #include <vector>
68 
69 #define DEBUG_TYPE "asm-parser"
70 
71 using namespace llvm;
72 
73 namespace llvm {
74 extern const MCInstrDesc ARMInsts[];
75 } // end namespace llvm
76 
77 namespace {
78 
79 enum class ImplicitItModeTy { Always, Never, ARMOnly, ThumbOnly };
80 
81 static cl::opt<ImplicitItModeTy> ImplicitItMode(
82     "arm-implicit-it", cl::init(ImplicitItModeTy::ARMOnly),
83     cl::desc("Allow conditional instructions outdside of an IT block"),
84     cl::values(clEnumValN(ImplicitItModeTy::Always, "always",
85                           "Accept in both ISAs, emit implicit ITs in Thumb"),
86                clEnumValN(ImplicitItModeTy::Never, "never",
87                           "Warn in ARM, reject in Thumb"),
88                clEnumValN(ImplicitItModeTy::ARMOnly, "arm",
89                           "Accept in ARM, reject in Thumb"),
90                clEnumValN(ImplicitItModeTy::ThumbOnly, "thumb",
91                           "Warn in ARM, emit implicit ITs in Thumb")));
92 
93 static cl::opt<bool> AddBuildAttributes("arm-add-build-attributes",
94                                         cl::init(false));
95 
96 enum VectorLaneTy { NoLanes, AllLanes, IndexedLane };
97 
98 static inline unsigned extractITMaskBit(unsigned Mask, unsigned Position) {
99   // Position==0 means we're not in an IT block at all. Position==1
100   // means we want the first state bit, which is always 0 (Then).
101   // Position==2 means we want the second state bit, stored at bit 3
102   // of Mask, and so on downwards. So (5 - Position) will shift the
103   // right bit down to bit 0, including the always-0 bit at bit 4 for
104   // the mandatory initial Then.
105   return (Mask >> (5 - Position) & 1);
106 }
107 
108 class UnwindContext {
109   using Locs = SmallVector<SMLoc, 4>;
110 
111   MCAsmParser &Parser;
112   Locs FnStartLocs;
113   Locs CantUnwindLocs;
114   Locs PersonalityLocs;
115   Locs PersonalityIndexLocs;
116   Locs HandlerDataLocs;
117   int FPReg;
118 
119 public:
120   UnwindContext(MCAsmParser &P) : Parser(P), FPReg(ARM::SP) {}
121 
122   bool hasFnStart() const { return !FnStartLocs.empty(); }
123   bool cantUnwind() const { return !CantUnwindLocs.empty(); }
124   bool hasHandlerData() const { return !HandlerDataLocs.empty(); }
125 
126   bool hasPersonality() const {
127     return !(PersonalityLocs.empty() && PersonalityIndexLocs.empty());
128   }
129 
130   void recordFnStart(SMLoc L) { FnStartLocs.push_back(L); }
131   void recordCantUnwind(SMLoc L) { CantUnwindLocs.push_back(L); }
132   void recordPersonality(SMLoc L) { PersonalityLocs.push_back(L); }
133   void recordHandlerData(SMLoc L) { HandlerDataLocs.push_back(L); }
134   void recordPersonalityIndex(SMLoc L) { PersonalityIndexLocs.push_back(L); }
135 
136   void saveFPReg(int Reg) { FPReg = Reg; }
137   int getFPReg() const { return FPReg; }
138 
139   void emitFnStartLocNotes() const {
140     for (Locs::const_iterator FI = FnStartLocs.begin(), FE = FnStartLocs.end();
141          FI != FE; ++FI)
142       Parser.Note(*FI, ".fnstart was specified here");
143   }
144 
145   void emitCantUnwindLocNotes() const {
146     for (Locs::const_iterator UI = CantUnwindLocs.begin(),
147                               UE = CantUnwindLocs.end(); UI != UE; ++UI)
148       Parser.Note(*UI, ".cantunwind was specified here");
149   }
150 
151   void emitHandlerDataLocNotes() const {
152     for (Locs::const_iterator HI = HandlerDataLocs.begin(),
153                               HE = HandlerDataLocs.end(); HI != HE; ++HI)
154       Parser.Note(*HI, ".handlerdata was specified here");
155   }
156 
157   void emitPersonalityLocNotes() const {
158     for (Locs::const_iterator PI = PersonalityLocs.begin(),
159                               PE = PersonalityLocs.end(),
160                               PII = PersonalityIndexLocs.begin(),
161                               PIE = PersonalityIndexLocs.end();
162          PI != PE || PII != PIE;) {
163       if (PI != PE && (PII == PIE || PI->getPointer() < PII->getPointer()))
164         Parser.Note(*PI++, ".personality was specified here");
165       else if (PII != PIE && (PI == PE || PII->getPointer() < PI->getPointer()))
166         Parser.Note(*PII++, ".personalityindex was specified here");
167       else
168         llvm_unreachable(".personality and .personalityindex cannot be "
169                          "at the same location");
170     }
171   }
172 
173   void reset() {
174     FnStartLocs = Locs();
175     CantUnwindLocs = Locs();
176     PersonalityLocs = Locs();
177     HandlerDataLocs = Locs();
178     PersonalityIndexLocs = Locs();
179     FPReg = ARM::SP;
180   }
181 };
182 
183 
184 class ARMAsmParser : public MCTargetAsmParser {
185   const MCRegisterInfo *MRI;
186   UnwindContext UC;
187 
188   ARMTargetStreamer &getTargetStreamer() {
189     assert(getParser().getStreamer().getTargetStreamer() &&
190            "do not have a target streamer");
191     MCTargetStreamer &TS = *getParser().getStreamer().getTargetStreamer();
192     return static_cast<ARMTargetStreamer &>(TS);
193   }
194 
195   // Map of register aliases registers via the .req directive.
196   StringMap<unsigned> RegisterReqs;
197 
198   bool NextSymbolIsThumb;
199 
200   bool useImplicitITThumb() const {
201     return ImplicitItMode == ImplicitItModeTy::Always ||
202            ImplicitItMode == ImplicitItModeTy::ThumbOnly;
203   }
204 
205   bool useImplicitITARM() const {
206     return ImplicitItMode == ImplicitItModeTy::Always ||
207            ImplicitItMode == ImplicitItModeTy::ARMOnly;
208   }
209 
210   struct {
211     ARMCC::CondCodes Cond;    // Condition for IT block.
212     unsigned Mask:4;          // Condition mask for instructions.
213                               // Starting at first 1 (from lsb).
214                               //   '1'  condition as indicated in IT.
215                               //   '0'  inverse of condition (else).
216                               // Count of instructions in IT block is
217                               // 4 - trailingzeroes(mask)
218                               // Note that this does not have the same encoding
219                               // as in the IT instruction, which also depends
220                               // on the low bit of the condition code.
221 
222     unsigned CurPosition;     // Current position in parsing of IT
223                               // block. In range [0,4], with 0 being the IT
224                               // instruction itself. Initialized according to
225                               // count of instructions in block.  ~0U if no
226                               // active IT block.
227 
228     bool IsExplicit;          // true  - The IT instruction was present in the
229                               //         input, we should not modify it.
230                               // false - The IT instruction was added
231                               //         implicitly, we can extend it if that
232                               //         would be legal.
233   } ITState;
234 
235   SmallVector<MCInst, 4> PendingConditionalInsts;
236 
237   void flushPendingInstructions(MCStreamer &Out) override {
238     if (!inImplicitITBlock()) {
239       assert(PendingConditionalInsts.size() == 0);
240       return;
241     }
242 
243     // Emit the IT instruction
244     MCInst ITInst;
245     ITInst.setOpcode(ARM::t2IT);
246     ITInst.addOperand(MCOperand::createImm(ITState.Cond));
247     ITInst.addOperand(MCOperand::createImm(ITState.Mask));
248     Out.emitInstruction(ITInst, getSTI());
249 
250     // Emit the conditonal instructions
251     assert(PendingConditionalInsts.size() <= 4);
252     for (const MCInst &Inst : PendingConditionalInsts) {
253       Out.emitInstruction(Inst, getSTI());
254     }
255     PendingConditionalInsts.clear();
256 
257     // Clear the IT state
258     ITState.Mask = 0;
259     ITState.CurPosition = ~0U;
260   }
261 
262   bool inITBlock() { return ITState.CurPosition != ~0U; }
263   bool inExplicitITBlock() { return inITBlock() && ITState.IsExplicit; }
264   bool inImplicitITBlock() { return inITBlock() && !ITState.IsExplicit; }
265 
266   bool lastInITBlock() {
267     return ITState.CurPosition == 4 - countTrailingZeros(ITState.Mask);
268   }
269 
270   void forwardITPosition() {
271     if (!inITBlock()) return;
272     // Move to the next instruction in the IT block, if there is one. If not,
273     // mark the block as done, except for implicit IT blocks, which we leave
274     // open until we find an instruction that can't be added to it.
275     unsigned TZ = countTrailingZeros(ITState.Mask);
276     if (++ITState.CurPosition == 5 - TZ && ITState.IsExplicit)
277       ITState.CurPosition = ~0U; // Done with the IT block after this.
278   }
279 
280   // Rewind the state of the current IT block, removing the last slot from it.
281   void rewindImplicitITPosition() {
282     assert(inImplicitITBlock());
283     assert(ITState.CurPosition > 1);
284     ITState.CurPosition--;
285     unsigned TZ = countTrailingZeros(ITState.Mask);
286     unsigned NewMask = 0;
287     NewMask |= ITState.Mask & (0xC << TZ);
288     NewMask |= 0x2 << TZ;
289     ITState.Mask = NewMask;
290   }
291 
292   // Rewind the state of the current IT block, removing the last slot from it.
293   // If we were at the first slot, this closes the IT block.
294   void discardImplicitITBlock() {
295     assert(inImplicitITBlock());
296     assert(ITState.CurPosition == 1);
297     ITState.CurPosition = ~0U;
298   }
299 
300   // Return the low-subreg of a given Q register.
301   unsigned getDRegFromQReg(unsigned QReg) const {
302     return MRI->getSubReg(QReg, ARM::dsub_0);
303   }
304 
305   // Get the condition code corresponding to the current IT block slot.
306   ARMCC::CondCodes currentITCond() {
307     unsigned MaskBit = extractITMaskBit(ITState.Mask, ITState.CurPosition);
308     return MaskBit ? ARMCC::getOppositeCondition(ITState.Cond) : ITState.Cond;
309   }
310 
311   // Invert the condition of the current IT block slot without changing any
312   // other slots in the same block.
313   void invertCurrentITCondition() {
314     if (ITState.CurPosition == 1) {
315       ITState.Cond = ARMCC::getOppositeCondition(ITState.Cond);
316     } else {
317       ITState.Mask ^= 1 << (5 - ITState.CurPosition);
318     }
319   }
320 
321   // Returns true if the current IT block is full (all 4 slots used).
322   bool isITBlockFull() {
323     return inITBlock() && (ITState.Mask & 1);
324   }
325 
326   // Extend the current implicit IT block to have one more slot with the given
327   // condition code.
328   void extendImplicitITBlock(ARMCC::CondCodes Cond) {
329     assert(inImplicitITBlock());
330     assert(!isITBlockFull());
331     assert(Cond == ITState.Cond ||
332            Cond == ARMCC::getOppositeCondition(ITState.Cond));
333     unsigned TZ = countTrailingZeros(ITState.Mask);
334     unsigned NewMask = 0;
335     // Keep any existing condition bits.
336     NewMask |= ITState.Mask & (0xE << TZ);
337     // Insert the new condition bit.
338     NewMask |= (Cond != ITState.Cond) << TZ;
339     // Move the trailing 1 down one bit.
340     NewMask |= 1 << (TZ - 1);
341     ITState.Mask = NewMask;
342   }
343 
344   // Create a new implicit IT block with a dummy condition code.
345   void startImplicitITBlock() {
346     assert(!inITBlock());
347     ITState.Cond = ARMCC::AL;
348     ITState.Mask = 8;
349     ITState.CurPosition = 1;
350     ITState.IsExplicit = false;
351   }
352 
353   // Create a new explicit IT block with the given condition and mask.
354   // The mask should be in the format used in ARMOperand and
355   // MCOperand, with a 1 implying 'e', regardless of the low bit of
356   // the condition.
357   void startExplicitITBlock(ARMCC::CondCodes Cond, unsigned Mask) {
358     assert(!inITBlock());
359     ITState.Cond = Cond;
360     ITState.Mask = Mask;
361     ITState.CurPosition = 0;
362     ITState.IsExplicit = true;
363   }
364 
365   struct {
366     unsigned Mask : 4;
367     unsigned CurPosition;
368   } VPTState;
369   bool inVPTBlock() { return VPTState.CurPosition != ~0U; }
370   void forwardVPTPosition() {
371     if (!inVPTBlock()) return;
372     unsigned TZ = countTrailingZeros(VPTState.Mask);
373     if (++VPTState.CurPosition == 5 - TZ)
374       VPTState.CurPosition = ~0U;
375   }
376 
377   void Note(SMLoc L, const Twine &Msg, SMRange Range = None) {
378     return getParser().Note(L, Msg, Range);
379   }
380 
381   bool Warning(SMLoc L, const Twine &Msg, SMRange Range = None) {
382     return getParser().Warning(L, Msg, Range);
383   }
384 
385   bool Error(SMLoc L, const Twine &Msg, SMRange Range = None) {
386     return getParser().Error(L, Msg, Range);
387   }
388 
389   bool validatetLDMRegList(const MCInst &Inst, const OperandVector &Operands,
390                            unsigned ListNo, bool IsARPop = false);
391   bool validatetSTMRegList(const MCInst &Inst, const OperandVector &Operands,
392                            unsigned ListNo);
393 
394   int tryParseRegister();
395   bool tryParseRegisterWithWriteBack(OperandVector &);
396   int tryParseShiftRegister(OperandVector &);
397   bool parseRegisterList(OperandVector &, bool EnforceOrder = true);
398   bool parseMemory(OperandVector &);
399   bool parseOperand(OperandVector &, StringRef Mnemonic);
400   bool parsePrefix(ARMMCExpr::VariantKind &RefKind);
401   bool parseMemRegOffsetShift(ARM_AM::ShiftOpc &ShiftType,
402                               unsigned &ShiftAmount);
403   bool parseLiteralValues(unsigned Size, SMLoc L);
404   bool parseDirectiveThumb(SMLoc L);
405   bool parseDirectiveARM(SMLoc L);
406   bool parseDirectiveThumbFunc(SMLoc L);
407   bool parseDirectiveCode(SMLoc L);
408   bool parseDirectiveSyntax(SMLoc L);
409   bool parseDirectiveReq(StringRef Name, SMLoc L);
410   bool parseDirectiveUnreq(SMLoc L);
411   bool parseDirectiveArch(SMLoc L);
412   bool parseDirectiveEabiAttr(SMLoc L);
413   bool parseDirectiveCPU(SMLoc L);
414   bool parseDirectiveFPU(SMLoc L);
415   bool parseDirectiveFnStart(SMLoc L);
416   bool parseDirectiveFnEnd(SMLoc L);
417   bool parseDirectiveCantUnwind(SMLoc L);
418   bool parseDirectivePersonality(SMLoc L);
419   bool parseDirectiveHandlerData(SMLoc L);
420   bool parseDirectiveSetFP(SMLoc L);
421   bool parseDirectivePad(SMLoc L);
422   bool parseDirectiveRegSave(SMLoc L, bool IsVector);
423   bool parseDirectiveInst(SMLoc L, char Suffix = '\0');
424   bool parseDirectiveLtorg(SMLoc L);
425   bool parseDirectiveEven(SMLoc L);
426   bool parseDirectivePersonalityIndex(SMLoc L);
427   bool parseDirectiveUnwindRaw(SMLoc L);
428   bool parseDirectiveTLSDescSeq(SMLoc L);
429   bool parseDirectiveMovSP(SMLoc L);
430   bool parseDirectiveObjectArch(SMLoc L);
431   bool parseDirectiveArchExtension(SMLoc L);
432   bool parseDirectiveAlign(SMLoc L);
433   bool parseDirectiveThumbSet(SMLoc L);
434 
435   bool isMnemonicVPTPredicable(StringRef Mnemonic, StringRef ExtraToken);
436   StringRef splitMnemonic(StringRef Mnemonic, StringRef ExtraToken,
437                           unsigned &PredicationCode,
438                           unsigned &VPTPredicationCode, bool &CarrySetting,
439                           unsigned &ProcessorIMod, StringRef &ITMask);
440   void getMnemonicAcceptInfo(StringRef Mnemonic, StringRef ExtraToken,
441                              StringRef FullInst, bool &CanAcceptCarrySet,
442                              bool &CanAcceptPredicationCode,
443                              bool &CanAcceptVPTPredicationCode);
444 
445   void tryConvertingToTwoOperandForm(StringRef Mnemonic, bool CarrySetting,
446                                      OperandVector &Operands);
447   bool isThumb() const {
448     // FIXME: Can tablegen auto-generate this?
449     return getSTI().getFeatureBits()[ARM::ModeThumb];
450   }
451 
452   bool isThumbOne() const {
453     return isThumb() && !getSTI().getFeatureBits()[ARM::FeatureThumb2];
454   }
455 
456   bool isThumbTwo() const {
457     return isThumb() && getSTI().getFeatureBits()[ARM::FeatureThumb2];
458   }
459 
460   bool hasThumb() const {
461     return getSTI().getFeatureBits()[ARM::HasV4TOps];
462   }
463 
464   bool hasThumb2() const {
465     return getSTI().getFeatureBits()[ARM::FeatureThumb2];
466   }
467 
468   bool hasV6Ops() const {
469     return getSTI().getFeatureBits()[ARM::HasV6Ops];
470   }
471 
472   bool hasV6T2Ops() const {
473     return getSTI().getFeatureBits()[ARM::HasV6T2Ops];
474   }
475 
476   bool hasV6MOps() const {
477     return getSTI().getFeatureBits()[ARM::HasV6MOps];
478   }
479 
480   bool hasV7Ops() const {
481     return getSTI().getFeatureBits()[ARM::HasV7Ops];
482   }
483 
484   bool hasV8Ops() const {
485     return getSTI().getFeatureBits()[ARM::HasV8Ops];
486   }
487 
488   bool hasV8MBaseline() const {
489     return getSTI().getFeatureBits()[ARM::HasV8MBaselineOps];
490   }
491 
492   bool hasV8MMainline() const {
493     return getSTI().getFeatureBits()[ARM::HasV8MMainlineOps];
494   }
495   bool hasV8_1MMainline() const {
496     return getSTI().getFeatureBits()[ARM::HasV8_1MMainlineOps];
497   }
498   bool hasMVE() const {
499     return getSTI().getFeatureBits()[ARM::HasMVEIntegerOps];
500   }
501   bool hasMVEFloat() const {
502     return getSTI().getFeatureBits()[ARM::HasMVEFloatOps];
503   }
504   bool has8MSecExt() const {
505     return getSTI().getFeatureBits()[ARM::Feature8MSecExt];
506   }
507 
508   bool hasARM() const {
509     return !getSTI().getFeatureBits()[ARM::FeatureNoARM];
510   }
511 
512   bool hasDSP() const {
513     return getSTI().getFeatureBits()[ARM::FeatureDSP];
514   }
515 
516   bool hasD32() const {
517     return getSTI().getFeatureBits()[ARM::FeatureD32];
518   }
519 
520   bool hasV8_1aOps() const {
521     return getSTI().getFeatureBits()[ARM::HasV8_1aOps];
522   }
523 
524   bool hasRAS() const {
525     return getSTI().getFeatureBits()[ARM::FeatureRAS];
526   }
527 
528   void SwitchMode() {
529     MCSubtargetInfo &STI = copySTI();
530     auto FB = ComputeAvailableFeatures(STI.ToggleFeature(ARM::ModeThumb));
531     setAvailableFeatures(FB);
532   }
533 
534   void FixModeAfterArchChange(bool WasThumb, SMLoc Loc);
535 
536   bool isMClass() const {
537     return getSTI().getFeatureBits()[ARM::FeatureMClass];
538   }
539 
540   /// @name Auto-generated Match Functions
541   /// {
542 
543 #define GET_ASSEMBLER_HEADER
544 #include "ARMGenAsmMatcher.inc"
545 
546   /// }
547 
548   OperandMatchResultTy parseITCondCode(OperandVector &);
549   OperandMatchResultTy parseCoprocNumOperand(OperandVector &);
550   OperandMatchResultTy parseCoprocRegOperand(OperandVector &);
551   OperandMatchResultTy parseCoprocOptionOperand(OperandVector &);
552   OperandMatchResultTy parseMemBarrierOptOperand(OperandVector &);
553   OperandMatchResultTy parseTraceSyncBarrierOptOperand(OperandVector &);
554   OperandMatchResultTy parseInstSyncBarrierOptOperand(OperandVector &);
555   OperandMatchResultTy parseProcIFlagsOperand(OperandVector &);
556   OperandMatchResultTy parseMSRMaskOperand(OperandVector &);
557   OperandMatchResultTy parseBankedRegOperand(OperandVector &);
558   OperandMatchResultTy parsePKHImm(OperandVector &O, StringRef Op, int Low,
559                                    int High);
560   OperandMatchResultTy parsePKHLSLImm(OperandVector &O) {
561     return parsePKHImm(O, "lsl", 0, 31);
562   }
563   OperandMatchResultTy parsePKHASRImm(OperandVector &O) {
564     return parsePKHImm(O, "asr", 1, 32);
565   }
566   OperandMatchResultTy parseSetEndImm(OperandVector &);
567   OperandMatchResultTy parseShifterImm(OperandVector &);
568   OperandMatchResultTy parseRotImm(OperandVector &);
569   OperandMatchResultTy parseModImm(OperandVector &);
570   OperandMatchResultTy parseBitfield(OperandVector &);
571   OperandMatchResultTy parsePostIdxReg(OperandVector &);
572   OperandMatchResultTy parseAM3Offset(OperandVector &);
573   OperandMatchResultTy parseFPImm(OperandVector &);
574   OperandMatchResultTy parseVectorList(OperandVector &);
575   OperandMatchResultTy parseVectorLane(VectorLaneTy &LaneKind, unsigned &Index,
576                                        SMLoc &EndLoc);
577 
578   // Asm Match Converter Methods
579   void cvtThumbMultiply(MCInst &Inst, const OperandVector &);
580   void cvtThumbBranches(MCInst &Inst, const OperandVector &);
581   void cvtMVEVMOVQtoDReg(MCInst &Inst, const OperandVector &);
582 
583   bool validateInstruction(MCInst &Inst, const OperandVector &Ops);
584   bool processInstruction(MCInst &Inst, const OperandVector &Ops, MCStreamer &Out);
585   bool shouldOmitCCOutOperand(StringRef Mnemonic, OperandVector &Operands);
586   bool shouldOmitPredicateOperand(StringRef Mnemonic, OperandVector &Operands);
587   bool shouldOmitVectorPredicateOperand(StringRef Mnemonic, OperandVector &Operands);
588   bool isITBlockTerminator(MCInst &Inst) const;
589   void fixupGNULDRDAlias(StringRef Mnemonic, OperandVector &Operands);
590   bool validateLDRDSTRD(MCInst &Inst, const OperandVector &Operands,
591                         bool Load, bool ARMMode, bool Writeback);
592 
593 public:
594   enum ARMMatchResultTy {
595     Match_RequiresITBlock = FIRST_TARGET_MATCH_RESULT_TY,
596     Match_RequiresNotITBlock,
597     Match_RequiresV6,
598     Match_RequiresThumb2,
599     Match_RequiresV8,
600     Match_RequiresFlagSetting,
601 #define GET_OPERAND_DIAGNOSTIC_TYPES
602 #include "ARMGenAsmMatcher.inc"
603 
604   };
605 
606   ARMAsmParser(const MCSubtargetInfo &STI, MCAsmParser &Parser,
607                const MCInstrInfo &MII, const MCTargetOptions &Options)
608     : MCTargetAsmParser(Options, STI, MII), UC(Parser) {
609     MCAsmParserExtension::Initialize(Parser);
610 
611     // Cache the MCRegisterInfo.
612     MRI = getContext().getRegisterInfo();
613 
614     // Initialize the set of available features.
615     setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
616 
617     // Add build attributes based on the selected target.
618     if (AddBuildAttributes)
619       getTargetStreamer().emitTargetAttributes(STI);
620 
621     // Not in an ITBlock to start with.
622     ITState.CurPosition = ~0U;
623 
624     VPTState.CurPosition = ~0U;
625 
626     NextSymbolIsThumb = false;
627   }
628 
629   // Implementation of the MCTargetAsmParser interface:
630   bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc) override;
631   OperandMatchResultTy tryParseRegister(unsigned &RegNo, SMLoc &StartLoc,
632                                         SMLoc &EndLoc) override;
633   bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
634                         SMLoc NameLoc, OperandVector &Operands) override;
635   bool ParseDirective(AsmToken DirectiveID) override;
636 
637   unsigned validateTargetOperandClass(MCParsedAsmOperand &Op,
638                                       unsigned Kind) override;
639   unsigned checkTargetMatchPredicate(MCInst &Inst) override;
640 
641   bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
642                                OperandVector &Operands, MCStreamer &Out,
643                                uint64_t &ErrorInfo,
644                                bool MatchingInlineAsm) override;
645   unsigned MatchInstruction(OperandVector &Operands, MCInst &Inst,
646                             SmallVectorImpl<NearMissInfo> &NearMisses,
647                             bool MatchingInlineAsm, bool &EmitInITBlock,
648                             MCStreamer &Out);
649 
650   struct NearMissMessage {
651     SMLoc Loc;
652     SmallString<128> Message;
653   };
654 
655   const char *getCustomOperandDiag(ARMMatchResultTy MatchError);
656 
657   void FilterNearMisses(SmallVectorImpl<NearMissInfo> &NearMissesIn,
658                         SmallVectorImpl<NearMissMessage> &NearMissesOut,
659                         SMLoc IDLoc, OperandVector &Operands);
660   void ReportNearMisses(SmallVectorImpl<NearMissInfo> &NearMisses, SMLoc IDLoc,
661                         OperandVector &Operands);
662 
663   void doBeforeLabelEmit(MCSymbol *Symbol) override;
664 
665   void onLabelParsed(MCSymbol *Symbol) override;
666 };
667 
668 /// ARMOperand - Instances of this class represent a parsed ARM machine
669 /// operand.
670 class ARMOperand : public MCParsedAsmOperand {
671   enum KindTy {
672     k_CondCode,
673     k_VPTPred,
674     k_CCOut,
675     k_ITCondMask,
676     k_CoprocNum,
677     k_CoprocReg,
678     k_CoprocOption,
679     k_Immediate,
680     k_MemBarrierOpt,
681     k_InstSyncBarrierOpt,
682     k_TraceSyncBarrierOpt,
683     k_Memory,
684     k_PostIndexRegister,
685     k_MSRMask,
686     k_BankedReg,
687     k_ProcIFlags,
688     k_VectorIndex,
689     k_Register,
690     k_RegisterList,
691     k_RegisterListWithAPSR,
692     k_DPRRegisterList,
693     k_SPRRegisterList,
694     k_FPSRegisterListWithVPR,
695     k_FPDRegisterListWithVPR,
696     k_VectorList,
697     k_VectorListAllLanes,
698     k_VectorListIndexed,
699     k_ShiftedRegister,
700     k_ShiftedImmediate,
701     k_ShifterImmediate,
702     k_RotateImmediate,
703     k_ModifiedImmediate,
704     k_ConstantPoolImmediate,
705     k_BitfieldDescriptor,
706     k_Token,
707   } Kind;
708 
709   SMLoc StartLoc, EndLoc, AlignmentLoc;
710   SmallVector<unsigned, 8> Registers;
711 
712   struct CCOp {
713     ARMCC::CondCodes Val;
714   };
715 
716   struct VCCOp {
717     ARMVCC::VPTCodes Val;
718   };
719 
720   struct CopOp {
721     unsigned Val;
722   };
723 
724   struct CoprocOptionOp {
725     unsigned Val;
726   };
727 
728   struct ITMaskOp {
729     unsigned Mask:4;
730   };
731 
732   struct MBOptOp {
733     ARM_MB::MemBOpt Val;
734   };
735 
736   struct ISBOptOp {
737     ARM_ISB::InstSyncBOpt Val;
738   };
739 
740   struct TSBOptOp {
741     ARM_TSB::TraceSyncBOpt Val;
742   };
743 
744   struct IFlagsOp {
745     ARM_PROC::IFlags Val;
746   };
747 
748   struct MMaskOp {
749     unsigned Val;
750   };
751 
752   struct BankedRegOp {
753     unsigned Val;
754   };
755 
756   struct TokOp {
757     const char *Data;
758     unsigned Length;
759   };
760 
761   struct RegOp {
762     unsigned RegNum;
763   };
764 
765   // A vector register list is a sequential list of 1 to 4 registers.
766   struct VectorListOp {
767     unsigned RegNum;
768     unsigned Count;
769     unsigned LaneIndex;
770     bool isDoubleSpaced;
771   };
772 
773   struct VectorIndexOp {
774     unsigned Val;
775   };
776 
777   struct ImmOp {
778     const MCExpr *Val;
779   };
780 
781   /// Combined record for all forms of ARM address expressions.
782   struct MemoryOp {
783     unsigned BaseRegNum;
784     // Offset is in OffsetReg or OffsetImm. If both are zero, no offset
785     // was specified.
786     const MCConstantExpr *OffsetImm;  // Offset immediate value
787     unsigned OffsetRegNum;    // Offset register num, when OffsetImm == NULL
788     ARM_AM::ShiftOpc ShiftType; // Shift type for OffsetReg
789     unsigned ShiftImm;        // shift for OffsetReg.
790     unsigned Alignment;       // 0 = no alignment specified
791     // n = alignment in bytes (2, 4, 8, 16, or 32)
792     unsigned isNegative : 1;  // Negated OffsetReg? (~'U' bit)
793   };
794 
795   struct PostIdxRegOp {
796     unsigned RegNum;
797     bool isAdd;
798     ARM_AM::ShiftOpc ShiftTy;
799     unsigned ShiftImm;
800   };
801 
802   struct ShifterImmOp {
803     bool isASR;
804     unsigned Imm;
805   };
806 
807   struct RegShiftedRegOp {
808     ARM_AM::ShiftOpc ShiftTy;
809     unsigned SrcReg;
810     unsigned ShiftReg;
811     unsigned ShiftImm;
812   };
813 
814   struct RegShiftedImmOp {
815     ARM_AM::ShiftOpc ShiftTy;
816     unsigned SrcReg;
817     unsigned ShiftImm;
818   };
819 
820   struct RotImmOp {
821     unsigned Imm;
822   };
823 
824   struct ModImmOp {
825     unsigned Bits;
826     unsigned Rot;
827   };
828 
829   struct BitfieldOp {
830     unsigned LSB;
831     unsigned Width;
832   };
833 
834   union {
835     struct CCOp CC;
836     struct VCCOp VCC;
837     struct CopOp Cop;
838     struct CoprocOptionOp CoprocOption;
839     struct MBOptOp MBOpt;
840     struct ISBOptOp ISBOpt;
841     struct TSBOptOp TSBOpt;
842     struct ITMaskOp ITMask;
843     struct IFlagsOp IFlags;
844     struct MMaskOp MMask;
845     struct BankedRegOp BankedReg;
846     struct TokOp Tok;
847     struct RegOp Reg;
848     struct VectorListOp VectorList;
849     struct VectorIndexOp VectorIndex;
850     struct ImmOp Imm;
851     struct MemoryOp Memory;
852     struct PostIdxRegOp PostIdxReg;
853     struct ShifterImmOp ShifterImm;
854     struct RegShiftedRegOp RegShiftedReg;
855     struct RegShiftedImmOp RegShiftedImm;
856     struct RotImmOp RotImm;
857     struct ModImmOp ModImm;
858     struct BitfieldOp Bitfield;
859   };
860 
861 public:
862   ARMOperand(KindTy K) : MCParsedAsmOperand(), Kind(K) {}
863 
864   /// getStartLoc - Get the location of the first token of this operand.
865   SMLoc getStartLoc() const override { return StartLoc; }
866 
867   /// getEndLoc - Get the location of the last token of this operand.
868   SMLoc getEndLoc() const override { return EndLoc; }
869 
870   /// getLocRange - Get the range between the first and last token of this
871   /// operand.
872   SMRange getLocRange() const { return SMRange(StartLoc, EndLoc); }
873 
874   /// getAlignmentLoc - Get the location of the Alignment token of this operand.
875   SMLoc getAlignmentLoc() const {
876     assert(Kind == k_Memory && "Invalid access!");
877     return AlignmentLoc;
878   }
879 
880   ARMCC::CondCodes getCondCode() const {
881     assert(Kind == k_CondCode && "Invalid access!");
882     return CC.Val;
883   }
884 
885   ARMVCC::VPTCodes getVPTPred() const {
886     assert(isVPTPred() && "Invalid access!");
887     return VCC.Val;
888   }
889 
890   unsigned getCoproc() const {
891     assert((Kind == k_CoprocNum || Kind == k_CoprocReg) && "Invalid access!");
892     return Cop.Val;
893   }
894 
895   StringRef getToken() const {
896     assert(Kind == k_Token && "Invalid access!");
897     return StringRef(Tok.Data, Tok.Length);
898   }
899 
900   unsigned getReg() const override {
901     assert((Kind == k_Register || Kind == k_CCOut) && "Invalid access!");
902     return Reg.RegNum;
903   }
904 
905   const SmallVectorImpl<unsigned> &getRegList() const {
906     assert((Kind == k_RegisterList || Kind == k_RegisterListWithAPSR ||
907             Kind == k_DPRRegisterList || Kind == k_SPRRegisterList ||
908             Kind == k_FPSRegisterListWithVPR ||
909             Kind == k_FPDRegisterListWithVPR) &&
910            "Invalid access!");
911     return Registers;
912   }
913 
914   const MCExpr *getImm() const {
915     assert(isImm() && "Invalid access!");
916     return Imm.Val;
917   }
918 
919   const MCExpr *getConstantPoolImm() const {
920     assert(isConstantPoolImm() && "Invalid access!");
921     return Imm.Val;
922   }
923 
924   unsigned getVectorIndex() const {
925     assert(Kind == k_VectorIndex && "Invalid access!");
926     return VectorIndex.Val;
927   }
928 
929   ARM_MB::MemBOpt getMemBarrierOpt() const {
930     assert(Kind == k_MemBarrierOpt && "Invalid access!");
931     return MBOpt.Val;
932   }
933 
934   ARM_ISB::InstSyncBOpt getInstSyncBarrierOpt() const {
935     assert(Kind == k_InstSyncBarrierOpt && "Invalid access!");
936     return ISBOpt.Val;
937   }
938 
939   ARM_TSB::TraceSyncBOpt getTraceSyncBarrierOpt() const {
940     assert(Kind == k_TraceSyncBarrierOpt && "Invalid access!");
941     return TSBOpt.Val;
942   }
943 
944   ARM_PROC::IFlags getProcIFlags() const {
945     assert(Kind == k_ProcIFlags && "Invalid access!");
946     return IFlags.Val;
947   }
948 
949   unsigned getMSRMask() const {
950     assert(Kind == k_MSRMask && "Invalid access!");
951     return MMask.Val;
952   }
953 
954   unsigned getBankedReg() const {
955     assert(Kind == k_BankedReg && "Invalid access!");
956     return BankedReg.Val;
957   }
958 
959   bool isCoprocNum() const { return Kind == k_CoprocNum; }
960   bool isCoprocReg() const { return Kind == k_CoprocReg; }
961   bool isCoprocOption() const { return Kind == k_CoprocOption; }
962   bool isCondCode() const { return Kind == k_CondCode; }
963   bool isVPTPred() const { return Kind == k_VPTPred; }
964   bool isCCOut() const { return Kind == k_CCOut; }
965   bool isITMask() const { return Kind == k_ITCondMask; }
966   bool isITCondCode() const { return Kind == k_CondCode; }
967   bool isImm() const override {
968     return Kind == k_Immediate;
969   }
970 
971   bool isARMBranchTarget() const {
972     if (!isImm()) return false;
973 
974     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm()))
975       return CE->getValue() % 4 == 0;
976     return true;
977   }
978 
979 
980   bool isThumbBranchTarget() const {
981     if (!isImm()) return false;
982 
983     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm()))
984       return CE->getValue() % 2 == 0;
985     return true;
986   }
987 
988   // checks whether this operand is an unsigned offset which fits is a field
989   // of specified width and scaled by a specific number of bits
990   template<unsigned width, unsigned scale>
991   bool isUnsignedOffset() const {
992     if (!isImm()) return false;
993     if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
994     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val)) {
995       int64_t Val = CE->getValue();
996       int64_t Align = 1LL << scale;
997       int64_t Max = Align * ((1LL << width) - 1);
998       return ((Val % Align) == 0) && (Val >= 0) && (Val <= Max);
999     }
1000     return false;
1001   }
1002 
1003   // checks whether this operand is an signed offset which fits is a field
1004   // of specified width and scaled by a specific number of bits
1005   template<unsigned width, unsigned scale>
1006   bool isSignedOffset() const {
1007     if (!isImm()) return false;
1008     if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
1009     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val)) {
1010       int64_t Val = CE->getValue();
1011       int64_t Align = 1LL << scale;
1012       int64_t Max = Align * ((1LL << (width-1)) - 1);
1013       int64_t Min = -Align * (1LL << (width-1));
1014       return ((Val % Align) == 0) && (Val >= Min) && (Val <= Max);
1015     }
1016     return false;
1017   }
1018 
1019   // checks whether this operand is an offset suitable for the LE /
1020   // LETP instructions in Arm v8.1M
1021   bool isLEOffset() const {
1022     if (!isImm()) return false;
1023     if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
1024     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val)) {
1025       int64_t Val = CE->getValue();
1026       return Val < 0 && Val >= -4094 && (Val & 1) == 0;
1027     }
1028     return false;
1029   }
1030 
1031   // checks whether this operand is a memory operand computed as an offset
1032   // applied to PC. the offset may have 8 bits of magnitude and is represented
1033   // with two bits of shift. textually it may be either [pc, #imm], #imm or
1034   // relocable expression...
1035   bool isThumbMemPC() const {
1036     int64_t Val = 0;
1037     if (isImm()) {
1038       if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
1039       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val);
1040       if (!CE) return false;
1041       Val = CE->getValue();
1042     }
1043     else if (isGPRMem()) {
1044       if(!Memory.OffsetImm || Memory.OffsetRegNum) return false;
1045       if(Memory.BaseRegNum != ARM::PC) return false;
1046       Val = Memory.OffsetImm->getValue();
1047     }
1048     else return false;
1049     return ((Val % 4) == 0) && (Val >= 0) && (Val <= 1020);
1050   }
1051 
1052   bool isFPImm() const {
1053     if (!isImm()) return false;
1054     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1055     if (!CE) return false;
1056     int Val = ARM_AM::getFP32Imm(APInt(32, CE->getValue()));
1057     return Val != -1;
1058   }
1059 
1060   template<int64_t N, int64_t M>
1061   bool isImmediate() const {
1062     if (!isImm()) return false;
1063     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1064     if (!CE) return false;
1065     int64_t Value = CE->getValue();
1066     return Value >= N && Value <= M;
1067   }
1068 
1069   template<int64_t N, int64_t M>
1070   bool isImmediateS4() const {
1071     if (!isImm()) return false;
1072     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1073     if (!CE) return false;
1074     int64_t Value = CE->getValue();
1075     return ((Value & 3) == 0) && Value >= N && Value <= M;
1076   }
1077   template<int64_t N, int64_t M>
1078   bool isImmediateS2() const {
1079     if (!isImm()) return false;
1080     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1081     if (!CE) return false;
1082     int64_t Value = CE->getValue();
1083     return ((Value & 1) == 0) && Value >= N && Value <= M;
1084   }
1085   bool isFBits16() const {
1086     return isImmediate<0, 17>();
1087   }
1088   bool isFBits32() const {
1089     return isImmediate<1, 33>();
1090   }
1091   bool isImm8s4() const {
1092     return isImmediateS4<-1020, 1020>();
1093   }
1094   bool isImm7s4() const {
1095     return isImmediateS4<-508, 508>();
1096   }
1097   bool isImm7Shift0() const {
1098     return isImmediate<-127, 127>();
1099   }
1100   bool isImm7Shift1() const {
1101     return isImmediateS2<-255, 255>();
1102   }
1103   bool isImm7Shift2() const {
1104     return isImmediateS4<-511, 511>();
1105   }
1106   bool isImm7() const {
1107     return isImmediate<-127, 127>();
1108   }
1109   bool isImm0_1020s4() const {
1110     return isImmediateS4<0, 1020>();
1111   }
1112   bool isImm0_508s4() const {
1113     return isImmediateS4<0, 508>();
1114   }
1115   bool isImm0_508s4Neg() const {
1116     if (!isImm()) return false;
1117     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1118     if (!CE) return false;
1119     int64_t Value = -CE->getValue();
1120     // explicitly exclude zero. we want that to use the normal 0_508 version.
1121     return ((Value & 3) == 0) && Value > 0 && Value <= 508;
1122   }
1123 
1124   bool isImm0_4095Neg() const {
1125     if (!isImm()) return false;
1126     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1127     if (!CE) return false;
1128     // isImm0_4095Neg is used with 32-bit immediates only.
1129     // 32-bit immediates are zero extended to 64-bit when parsed,
1130     // thus simple -CE->getValue() results in a big negative number,
1131     // not a small positive number as intended
1132     if ((CE->getValue() >> 32) > 0) return false;
1133     uint32_t Value = -static_cast<uint32_t>(CE->getValue());
1134     return Value > 0 && Value < 4096;
1135   }
1136 
1137   bool isImm0_7() const {
1138     return isImmediate<0, 7>();
1139   }
1140 
1141   bool isImm1_16() const {
1142     return isImmediate<1, 16>();
1143   }
1144 
1145   bool isImm1_32() const {
1146     return isImmediate<1, 32>();
1147   }
1148 
1149   bool isImm8_255() const {
1150     return isImmediate<8, 255>();
1151   }
1152 
1153   bool isImm256_65535Expr() const {
1154     if (!isImm()) return false;
1155     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1156     // If it's not a constant expression, it'll generate a fixup and be
1157     // handled later.
1158     if (!CE) return true;
1159     int64_t Value = CE->getValue();
1160     return Value >= 256 && Value < 65536;
1161   }
1162 
1163   bool isImm0_65535Expr() const {
1164     if (!isImm()) return false;
1165     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1166     // If it's not a constant expression, it'll generate a fixup and be
1167     // handled later.
1168     if (!CE) return true;
1169     int64_t Value = CE->getValue();
1170     return Value >= 0 && Value < 65536;
1171   }
1172 
1173   bool isImm24bit() const {
1174     return isImmediate<0, 0xffffff + 1>();
1175   }
1176 
1177   bool isImmThumbSR() const {
1178     return isImmediate<1, 33>();
1179   }
1180 
1181   template<int shift>
1182   bool isExpImmValue(uint64_t Value) const {
1183     uint64_t mask = (1 << shift) - 1;
1184     if ((Value & mask) != 0 || (Value >> shift) > 0xff)
1185       return false;
1186     return true;
1187   }
1188 
1189   template<int shift>
1190   bool isExpImm() const {
1191     if (!isImm()) return false;
1192     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1193     if (!CE) return false;
1194 
1195     return isExpImmValue<shift>(CE->getValue());
1196   }
1197 
1198   template<int shift, int size>
1199   bool isInvertedExpImm() const {
1200     if (!isImm()) return false;
1201     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1202     if (!CE) return false;
1203 
1204     uint64_t OriginalValue = CE->getValue();
1205     uint64_t InvertedValue = OriginalValue ^ (((uint64_t)1 << size) - 1);
1206     return isExpImmValue<shift>(InvertedValue);
1207   }
1208 
1209   bool isPKHLSLImm() const {
1210     return isImmediate<0, 32>();
1211   }
1212 
1213   bool isPKHASRImm() const {
1214     return isImmediate<0, 33>();
1215   }
1216 
1217   bool isAdrLabel() const {
1218     // If we have an immediate that's not a constant, treat it as a label
1219     // reference needing a fixup.
1220     if (isImm() && !isa<MCConstantExpr>(getImm()))
1221       return true;
1222 
1223     // If it is a constant, it must fit into a modified immediate encoding.
1224     if (!isImm()) return false;
1225     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1226     if (!CE) return false;
1227     int64_t Value = CE->getValue();
1228     return (ARM_AM::getSOImmVal(Value) != -1 ||
1229             ARM_AM::getSOImmVal(-Value) != -1);
1230   }
1231 
1232   bool isT2SOImm() const {
1233     // If we have an immediate that's not a constant, treat it as an expression
1234     // needing a fixup.
1235     if (isImm() && !isa<MCConstantExpr>(getImm())) {
1236       // We want to avoid matching :upper16: and :lower16: as we want these
1237       // expressions to match in isImm0_65535Expr()
1238       const ARMMCExpr *ARM16Expr = dyn_cast<ARMMCExpr>(getImm());
1239       return (!ARM16Expr || (ARM16Expr->getKind() != ARMMCExpr::VK_ARM_HI16 &&
1240                              ARM16Expr->getKind() != ARMMCExpr::VK_ARM_LO16));
1241     }
1242     if (!isImm()) return false;
1243     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1244     if (!CE) return false;
1245     int64_t Value = CE->getValue();
1246     return ARM_AM::getT2SOImmVal(Value) != -1;
1247   }
1248 
1249   bool isT2SOImmNot() const {
1250     if (!isImm()) return false;
1251     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1252     if (!CE) return false;
1253     int64_t Value = CE->getValue();
1254     return ARM_AM::getT2SOImmVal(Value) == -1 &&
1255       ARM_AM::getT2SOImmVal(~Value) != -1;
1256   }
1257 
1258   bool isT2SOImmNeg() const {
1259     if (!isImm()) return false;
1260     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1261     if (!CE) return false;
1262     int64_t Value = CE->getValue();
1263     // Only use this when not representable as a plain so_imm.
1264     return ARM_AM::getT2SOImmVal(Value) == -1 &&
1265       ARM_AM::getT2SOImmVal(-Value) != -1;
1266   }
1267 
1268   bool isSetEndImm() const {
1269     if (!isImm()) return false;
1270     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1271     if (!CE) return false;
1272     int64_t Value = CE->getValue();
1273     return Value == 1 || Value == 0;
1274   }
1275 
1276   bool isReg() const override { return Kind == k_Register; }
1277   bool isRegList() const { return Kind == k_RegisterList; }
1278   bool isRegListWithAPSR() const {
1279     return Kind == k_RegisterListWithAPSR || Kind == k_RegisterList;
1280   }
1281   bool isDPRRegList() const { return Kind == k_DPRRegisterList; }
1282   bool isSPRRegList() const { return Kind == k_SPRRegisterList; }
1283   bool isFPSRegListWithVPR() const { return Kind == k_FPSRegisterListWithVPR; }
1284   bool isFPDRegListWithVPR() const { return Kind == k_FPDRegisterListWithVPR; }
1285   bool isToken() const override { return Kind == k_Token; }
1286   bool isMemBarrierOpt() const { return Kind == k_MemBarrierOpt; }
1287   bool isInstSyncBarrierOpt() const { return Kind == k_InstSyncBarrierOpt; }
1288   bool isTraceSyncBarrierOpt() const { return Kind == k_TraceSyncBarrierOpt; }
1289   bool isMem() const override {
1290       return isGPRMem() || isMVEMem();
1291   }
1292   bool isMVEMem() const {
1293     if (Kind != k_Memory)
1294       return false;
1295     if (Memory.BaseRegNum &&
1296         !ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Memory.BaseRegNum) &&
1297         !ARMMCRegisterClasses[ARM::MQPRRegClassID].contains(Memory.BaseRegNum))
1298       return false;
1299     if (Memory.OffsetRegNum &&
1300         !ARMMCRegisterClasses[ARM::MQPRRegClassID].contains(
1301             Memory.OffsetRegNum))
1302       return false;
1303     return true;
1304   }
1305   bool isGPRMem() const {
1306     if (Kind != k_Memory)
1307       return false;
1308     if (Memory.BaseRegNum &&
1309         !ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Memory.BaseRegNum))
1310       return false;
1311     if (Memory.OffsetRegNum &&
1312         !ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Memory.OffsetRegNum))
1313       return false;
1314     return true;
1315   }
1316   bool isShifterImm() const { return Kind == k_ShifterImmediate; }
1317   bool isRegShiftedReg() const {
1318     return Kind == k_ShiftedRegister &&
1319            ARMMCRegisterClasses[ARM::GPRRegClassID].contains(
1320                RegShiftedReg.SrcReg) &&
1321            ARMMCRegisterClasses[ARM::GPRRegClassID].contains(
1322                RegShiftedReg.ShiftReg);
1323   }
1324   bool isRegShiftedImm() const {
1325     return Kind == k_ShiftedImmediate &&
1326            ARMMCRegisterClasses[ARM::GPRRegClassID].contains(
1327                RegShiftedImm.SrcReg);
1328   }
1329   bool isRotImm() const { return Kind == k_RotateImmediate; }
1330 
1331   template<unsigned Min, unsigned Max>
1332   bool isPowerTwoInRange() const {
1333     if (!isImm()) return false;
1334     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1335     if (!CE) return false;
1336     int64_t Value = CE->getValue();
1337     return Value > 0 && countPopulation((uint64_t)Value) == 1 &&
1338            Value >= Min && Value <= Max;
1339   }
1340   bool isModImm() const { return Kind == k_ModifiedImmediate; }
1341 
1342   bool isModImmNot() const {
1343     if (!isImm()) return false;
1344     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1345     if (!CE) return false;
1346     int64_t Value = CE->getValue();
1347     return ARM_AM::getSOImmVal(~Value) != -1;
1348   }
1349 
1350   bool isModImmNeg() const {
1351     if (!isImm()) return false;
1352     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1353     if (!CE) return false;
1354     int64_t Value = CE->getValue();
1355     return ARM_AM::getSOImmVal(Value) == -1 &&
1356       ARM_AM::getSOImmVal(-Value) != -1;
1357   }
1358 
1359   bool isThumbModImmNeg1_7() const {
1360     if (!isImm()) return false;
1361     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1362     if (!CE) return false;
1363     int32_t Value = -(int32_t)CE->getValue();
1364     return 0 < Value && Value < 8;
1365   }
1366 
1367   bool isThumbModImmNeg8_255() const {
1368     if (!isImm()) return false;
1369     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1370     if (!CE) return false;
1371     int32_t Value = -(int32_t)CE->getValue();
1372     return 7 < Value && Value < 256;
1373   }
1374 
1375   bool isConstantPoolImm() const { return Kind == k_ConstantPoolImmediate; }
1376   bool isBitfield() const { return Kind == k_BitfieldDescriptor; }
1377   bool isPostIdxRegShifted() const {
1378     return Kind == k_PostIndexRegister &&
1379            ARMMCRegisterClasses[ARM::GPRRegClassID].contains(PostIdxReg.RegNum);
1380   }
1381   bool isPostIdxReg() const {
1382     return isPostIdxRegShifted() && PostIdxReg.ShiftTy == ARM_AM::no_shift;
1383   }
1384   bool isMemNoOffset(bool alignOK = false, unsigned Alignment = 0) const {
1385     if (!isGPRMem())
1386       return false;
1387     // No offset of any kind.
1388     return Memory.OffsetRegNum == 0 && Memory.OffsetImm == nullptr &&
1389      (alignOK || Memory.Alignment == Alignment);
1390   }
1391   bool isMemNoOffsetT2(bool alignOK = false, unsigned Alignment = 0) const {
1392     if (!isGPRMem())
1393       return false;
1394 
1395     if (!ARMMCRegisterClasses[ARM::GPRnopcRegClassID].contains(
1396             Memory.BaseRegNum))
1397       return false;
1398 
1399     // No offset of any kind.
1400     return Memory.OffsetRegNum == 0 && Memory.OffsetImm == nullptr &&
1401      (alignOK || Memory.Alignment == Alignment);
1402   }
1403   bool isMemNoOffsetT2NoSp(bool alignOK = false, unsigned Alignment = 0) const {
1404     if (!isGPRMem())
1405       return false;
1406 
1407     if (!ARMMCRegisterClasses[ARM::rGPRRegClassID].contains(
1408             Memory.BaseRegNum))
1409       return false;
1410 
1411     // No offset of any kind.
1412     return Memory.OffsetRegNum == 0 && Memory.OffsetImm == nullptr &&
1413      (alignOK || Memory.Alignment == Alignment);
1414   }
1415   bool isMemNoOffsetT(bool alignOK = false, unsigned Alignment = 0) const {
1416     if (!isGPRMem())
1417       return false;
1418 
1419     if (!ARMMCRegisterClasses[ARM::tGPRRegClassID].contains(
1420             Memory.BaseRegNum))
1421       return false;
1422 
1423     // No offset of any kind.
1424     return Memory.OffsetRegNum == 0 && Memory.OffsetImm == nullptr &&
1425      (alignOK || Memory.Alignment == Alignment);
1426   }
1427   bool isMemPCRelImm12() const {
1428     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1429       return false;
1430     // Base register must be PC.
1431     if (Memory.BaseRegNum != ARM::PC)
1432       return false;
1433     // Immediate offset in range [-4095, 4095].
1434     if (!Memory.OffsetImm) return true;
1435     int64_t Val = Memory.OffsetImm->getValue();
1436     return (Val > -4096 && Val < 4096) ||
1437            (Val == std::numeric_limits<int32_t>::min());
1438   }
1439 
1440   bool isAlignedMemory() const {
1441     return isMemNoOffset(true);
1442   }
1443 
1444   bool isAlignedMemoryNone() const {
1445     return isMemNoOffset(false, 0);
1446   }
1447 
1448   bool isDupAlignedMemoryNone() const {
1449     return isMemNoOffset(false, 0);
1450   }
1451 
1452   bool isAlignedMemory16() const {
1453     if (isMemNoOffset(false, 2)) // alignment in bytes for 16-bits is 2.
1454       return true;
1455     return isMemNoOffset(false, 0);
1456   }
1457 
1458   bool isDupAlignedMemory16() const {
1459     if (isMemNoOffset(false, 2)) // alignment in bytes for 16-bits is 2.
1460       return true;
1461     return isMemNoOffset(false, 0);
1462   }
1463 
1464   bool isAlignedMemory32() const {
1465     if (isMemNoOffset(false, 4)) // alignment in bytes for 32-bits is 4.
1466       return true;
1467     return isMemNoOffset(false, 0);
1468   }
1469 
1470   bool isDupAlignedMemory32() const {
1471     if (isMemNoOffset(false, 4)) // alignment in bytes for 32-bits is 4.
1472       return true;
1473     return isMemNoOffset(false, 0);
1474   }
1475 
1476   bool isAlignedMemory64() const {
1477     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1478       return true;
1479     return isMemNoOffset(false, 0);
1480   }
1481 
1482   bool isDupAlignedMemory64() const {
1483     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1484       return true;
1485     return isMemNoOffset(false, 0);
1486   }
1487 
1488   bool isAlignedMemory64or128() const {
1489     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1490       return true;
1491     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1492       return true;
1493     return isMemNoOffset(false, 0);
1494   }
1495 
1496   bool isDupAlignedMemory64or128() const {
1497     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1498       return true;
1499     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1500       return true;
1501     return isMemNoOffset(false, 0);
1502   }
1503 
1504   bool isAlignedMemory64or128or256() const {
1505     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1506       return true;
1507     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1508       return true;
1509     if (isMemNoOffset(false, 32)) // alignment in bytes for 256-bits is 32.
1510       return true;
1511     return isMemNoOffset(false, 0);
1512   }
1513 
1514   bool isAddrMode2() const {
1515     if (!isGPRMem() || Memory.Alignment != 0) return false;
1516     // Check for register offset.
1517     if (Memory.OffsetRegNum) return true;
1518     // Immediate offset in range [-4095, 4095].
1519     if (!Memory.OffsetImm) return true;
1520     int64_t Val = Memory.OffsetImm->getValue();
1521     return Val > -4096 && Val < 4096;
1522   }
1523 
1524   bool isAM2OffsetImm() const {
1525     if (!isImm()) return false;
1526     // Immediate offset in range [-4095, 4095].
1527     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1528     if (!CE) return false;
1529     int64_t Val = CE->getValue();
1530     return (Val == std::numeric_limits<int32_t>::min()) ||
1531            (Val > -4096 && Val < 4096);
1532   }
1533 
1534   bool isAddrMode3() const {
1535     // If we have an immediate that's not a constant, treat it as a label
1536     // reference needing a fixup. If it is a constant, it's something else
1537     // and we reject it.
1538     if (isImm() && !isa<MCConstantExpr>(getImm()))
1539       return true;
1540     if (!isGPRMem() || Memory.Alignment != 0) return false;
1541     // No shifts are legal for AM3.
1542     if (Memory.ShiftType != ARM_AM::no_shift) return false;
1543     // Check for register offset.
1544     if (Memory.OffsetRegNum) return true;
1545     // Immediate offset in range [-255, 255].
1546     if (!Memory.OffsetImm) return true;
1547     int64_t Val = Memory.OffsetImm->getValue();
1548     // The #-0 offset is encoded as std::numeric_limits<int32_t>::min(), and we
1549     // have to check for this too.
1550     return (Val > -256 && Val < 256) ||
1551            Val == std::numeric_limits<int32_t>::min();
1552   }
1553 
1554   bool isAM3Offset() const {
1555     if (isPostIdxReg())
1556       return true;
1557     if (!isImm())
1558       return false;
1559     // Immediate offset in range [-255, 255].
1560     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1561     if (!CE) return false;
1562     int64_t Val = CE->getValue();
1563     // Special case, #-0 is std::numeric_limits<int32_t>::min().
1564     return (Val > -256 && Val < 256) ||
1565            Val == std::numeric_limits<int32_t>::min();
1566   }
1567 
1568   bool isAddrMode5() const {
1569     // If we have an immediate that's not a constant, treat it as a label
1570     // reference needing a fixup. If it is a constant, it's something else
1571     // and we reject it.
1572     if (isImm() && !isa<MCConstantExpr>(getImm()))
1573       return true;
1574     if (!isGPRMem() || Memory.Alignment != 0) return false;
1575     // Check for register offset.
1576     if (Memory.OffsetRegNum) return false;
1577     // Immediate offset in range [-1020, 1020] and a multiple of 4.
1578     if (!Memory.OffsetImm) return true;
1579     int64_t Val = Memory.OffsetImm->getValue();
1580     return (Val >= -1020 && Val <= 1020 && ((Val & 3) == 0)) ||
1581       Val == std::numeric_limits<int32_t>::min();
1582   }
1583 
1584   bool isAddrMode5FP16() const {
1585     // If we have an immediate that's not a constant, treat it as a label
1586     // reference needing a fixup. If it is a constant, it's something else
1587     // and we reject it.
1588     if (isImm() && !isa<MCConstantExpr>(getImm()))
1589       return true;
1590     if (!isGPRMem() || Memory.Alignment != 0) return false;
1591     // Check for register offset.
1592     if (Memory.OffsetRegNum) return false;
1593     // Immediate offset in range [-510, 510] and a multiple of 2.
1594     if (!Memory.OffsetImm) return true;
1595     int64_t Val = Memory.OffsetImm->getValue();
1596     return (Val >= -510 && Val <= 510 && ((Val & 1) == 0)) ||
1597            Val == std::numeric_limits<int32_t>::min();
1598   }
1599 
1600   bool isMemTBB() const {
1601     if (!isGPRMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1602         Memory.ShiftType != ARM_AM::no_shift || Memory.Alignment != 0)
1603       return false;
1604     return true;
1605   }
1606 
1607   bool isMemTBH() const {
1608     if (!isGPRMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1609         Memory.ShiftType != ARM_AM::lsl || Memory.ShiftImm != 1 ||
1610         Memory.Alignment != 0 )
1611       return false;
1612     return true;
1613   }
1614 
1615   bool isMemRegOffset() const {
1616     if (!isGPRMem() || !Memory.OffsetRegNum || Memory.Alignment != 0)
1617       return false;
1618     return true;
1619   }
1620 
1621   bool isT2MemRegOffset() const {
1622     if (!isGPRMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1623         Memory.Alignment != 0 || Memory.BaseRegNum == ARM::PC)
1624       return false;
1625     // Only lsl #{0, 1, 2, 3} allowed.
1626     if (Memory.ShiftType == ARM_AM::no_shift)
1627       return true;
1628     if (Memory.ShiftType != ARM_AM::lsl || Memory.ShiftImm > 3)
1629       return false;
1630     return true;
1631   }
1632 
1633   bool isMemThumbRR() const {
1634     // Thumb reg+reg addressing is simple. Just two registers, a base and
1635     // an offset. No shifts, negations or any other complicating factors.
1636     if (!isGPRMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1637         Memory.ShiftType != ARM_AM::no_shift || Memory.Alignment != 0)
1638       return false;
1639     return isARMLowRegister(Memory.BaseRegNum) &&
1640       (!Memory.OffsetRegNum || isARMLowRegister(Memory.OffsetRegNum));
1641   }
1642 
1643   bool isMemThumbRIs4() const {
1644     if (!isGPRMem() || Memory.OffsetRegNum != 0 ||
1645         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1646       return false;
1647     // Immediate offset, multiple of 4 in range [0, 124].
1648     if (!Memory.OffsetImm) return true;
1649     int64_t Val = Memory.OffsetImm->getValue();
1650     return Val >= 0 && Val <= 124 && (Val % 4) == 0;
1651   }
1652 
1653   bool isMemThumbRIs2() const {
1654     if (!isGPRMem() || Memory.OffsetRegNum != 0 ||
1655         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1656       return false;
1657     // Immediate offset, multiple of 4 in range [0, 62].
1658     if (!Memory.OffsetImm) return true;
1659     int64_t Val = Memory.OffsetImm->getValue();
1660     return Val >= 0 && Val <= 62 && (Val % 2) == 0;
1661   }
1662 
1663   bool isMemThumbRIs1() const {
1664     if (!isGPRMem() || Memory.OffsetRegNum != 0 ||
1665         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1666       return false;
1667     // Immediate offset in range [0, 31].
1668     if (!Memory.OffsetImm) return true;
1669     int64_t Val = Memory.OffsetImm->getValue();
1670     return Val >= 0 && Val <= 31;
1671   }
1672 
1673   bool isMemThumbSPI() const {
1674     if (!isGPRMem() || Memory.OffsetRegNum != 0 ||
1675         Memory.BaseRegNum != ARM::SP || Memory.Alignment != 0)
1676       return false;
1677     // Immediate offset, multiple of 4 in range [0, 1020].
1678     if (!Memory.OffsetImm) return true;
1679     int64_t Val = Memory.OffsetImm->getValue();
1680     return Val >= 0 && Val <= 1020 && (Val % 4) == 0;
1681   }
1682 
1683   bool isMemImm8s4Offset() const {
1684     // If we have an immediate that's not a constant, treat it as a label
1685     // reference needing a fixup. If it is a constant, it's something else
1686     // and we reject it.
1687     if (isImm() && !isa<MCConstantExpr>(getImm()))
1688       return true;
1689     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1690       return false;
1691     // Immediate offset a multiple of 4 in range [-1020, 1020].
1692     if (!Memory.OffsetImm) return true;
1693     int64_t Val = Memory.OffsetImm->getValue();
1694     // Special case, #-0 is std::numeric_limits<int32_t>::min().
1695     return (Val >= -1020 && Val <= 1020 && (Val & 3) == 0) ||
1696            Val == std::numeric_limits<int32_t>::min();
1697   }
1698   bool isMemImm7s4Offset() const {
1699     // If we have an immediate that's not a constant, treat it as a label
1700     // reference needing a fixup. If it is a constant, it's something else
1701     // and we reject it.
1702     if (isImm() && !isa<MCConstantExpr>(getImm()))
1703       return true;
1704     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0 ||
1705         !ARMMCRegisterClasses[ARM::GPRnopcRegClassID].contains(
1706             Memory.BaseRegNum))
1707       return false;
1708     // Immediate offset a multiple of 4 in range [-508, 508].
1709     if (!Memory.OffsetImm) return true;
1710     int64_t Val = Memory.OffsetImm->getValue();
1711     // Special case, #-0 is INT32_MIN.
1712     return (Val >= -508 && Val <= 508 && (Val & 3) == 0) || Val == INT32_MIN;
1713   }
1714   bool isMemImm0_1020s4Offset() const {
1715     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1716       return false;
1717     // Immediate offset a multiple of 4 in range [0, 1020].
1718     if (!Memory.OffsetImm) return true;
1719     int64_t Val = Memory.OffsetImm->getValue();
1720     return Val >= 0 && Val <= 1020 && (Val & 3) == 0;
1721   }
1722 
1723   bool isMemImm8Offset() const {
1724     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1725       return false;
1726     // Base reg of PC isn't allowed for these encodings.
1727     if (Memory.BaseRegNum == ARM::PC) return false;
1728     // Immediate offset in range [-255, 255].
1729     if (!Memory.OffsetImm) return true;
1730     int64_t Val = Memory.OffsetImm->getValue();
1731     return (Val == std::numeric_limits<int32_t>::min()) ||
1732            (Val > -256 && Val < 256);
1733   }
1734 
1735   template<unsigned Bits, unsigned RegClassID>
1736   bool isMemImm7ShiftedOffset() const {
1737     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0 ||
1738         !ARMMCRegisterClasses[RegClassID].contains(Memory.BaseRegNum))
1739       return false;
1740 
1741     // Expect an immediate offset equal to an element of the range
1742     // [-127, 127], shifted left by Bits.
1743 
1744     if (!Memory.OffsetImm) return true;
1745     int64_t Val = Memory.OffsetImm->getValue();
1746 
1747     // INT32_MIN is a special-case value (indicating the encoding with
1748     // zero offset and the subtract bit set)
1749     if (Val == INT32_MIN)
1750       return true;
1751 
1752     unsigned Divisor = 1U << Bits;
1753 
1754     // Check that the low bits are zero
1755     if (Val % Divisor != 0)
1756       return false;
1757 
1758     // Check that the remaining offset is within range.
1759     Val /= Divisor;
1760     return (Val >= -127 && Val <= 127);
1761   }
1762 
1763   template <int shift> bool isMemRegRQOffset() const {
1764     if (!isMVEMem() || Memory.OffsetImm != 0 || Memory.Alignment != 0)
1765       return false;
1766 
1767     if (!ARMMCRegisterClasses[ARM::GPRnopcRegClassID].contains(
1768             Memory.BaseRegNum))
1769       return false;
1770     if (!ARMMCRegisterClasses[ARM::MQPRRegClassID].contains(
1771             Memory.OffsetRegNum))
1772       return false;
1773 
1774     if (shift == 0 && Memory.ShiftType != ARM_AM::no_shift)
1775       return false;
1776 
1777     if (shift > 0 &&
1778         (Memory.ShiftType != ARM_AM::uxtw || Memory.ShiftImm != shift))
1779       return false;
1780 
1781     return true;
1782   }
1783 
1784   template <int shift> bool isMemRegQOffset() const {
1785     if (!isMVEMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1786       return false;
1787 
1788     if (!ARMMCRegisterClasses[ARM::MQPRRegClassID].contains(
1789             Memory.BaseRegNum))
1790       return false;
1791 
1792     if(!Memory.OffsetImm) return true;
1793     static_assert(shift < 56,
1794                   "Such that we dont shift by a value higher than 62");
1795     int64_t Val = Memory.OffsetImm->getValue();
1796 
1797     // The value must be a multiple of (1 << shift)
1798     if ((Val & ((1U << shift) - 1)) != 0)
1799       return false;
1800 
1801     // And be in the right range, depending on the amount that it is shifted
1802     // by.  Shift 0, is equal to 7 unsigned bits, the sign bit is set
1803     // separately.
1804     int64_t Range = (1U << (7+shift)) - 1;
1805     return (Val == INT32_MIN) || (Val > -Range && Val < Range);
1806   }
1807 
1808   bool isMemPosImm8Offset() const {
1809     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1810       return false;
1811     // Immediate offset in range [0, 255].
1812     if (!Memory.OffsetImm) return true;
1813     int64_t Val = Memory.OffsetImm->getValue();
1814     return Val >= 0 && Val < 256;
1815   }
1816 
1817   bool isMemNegImm8Offset() const {
1818     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1819       return false;
1820     // Base reg of PC isn't allowed for these encodings.
1821     if (Memory.BaseRegNum == ARM::PC) return false;
1822     // Immediate offset in range [-255, -1].
1823     if (!Memory.OffsetImm) return false;
1824     int64_t Val = Memory.OffsetImm->getValue();
1825     return (Val == std::numeric_limits<int32_t>::min()) ||
1826            (Val > -256 && Val < 0);
1827   }
1828 
1829   bool isMemUImm12Offset() const {
1830     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1831       return false;
1832     // Immediate offset in range [0, 4095].
1833     if (!Memory.OffsetImm) return true;
1834     int64_t Val = Memory.OffsetImm->getValue();
1835     return (Val >= 0 && Val < 4096);
1836   }
1837 
1838   bool isMemImm12Offset() const {
1839     // If we have an immediate that's not a constant, treat it as a label
1840     // reference needing a fixup. If it is a constant, it's something else
1841     // and we reject it.
1842 
1843     if (isImm() && !isa<MCConstantExpr>(getImm()))
1844       return true;
1845 
1846     if (!isGPRMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1847       return false;
1848     // Immediate offset in range [-4095, 4095].
1849     if (!Memory.OffsetImm) return true;
1850     int64_t Val = Memory.OffsetImm->getValue();
1851     return (Val > -4096 && Val < 4096) ||
1852            (Val == std::numeric_limits<int32_t>::min());
1853   }
1854 
1855   bool isConstPoolAsmImm() const {
1856     // Delay processing of Constant Pool Immediate, this will turn into
1857     // a constant. Match no other operand
1858     return (isConstantPoolImm());
1859   }
1860 
1861   bool isPostIdxImm8() const {
1862     if (!isImm()) return false;
1863     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1864     if (!CE) return false;
1865     int64_t Val = CE->getValue();
1866     return (Val > -256 && Val < 256) ||
1867            (Val == std::numeric_limits<int32_t>::min());
1868   }
1869 
1870   bool isPostIdxImm8s4() const {
1871     if (!isImm()) return false;
1872     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1873     if (!CE) return false;
1874     int64_t Val = CE->getValue();
1875     return ((Val & 3) == 0 && Val >= -1020 && Val <= 1020) ||
1876            (Val == std::numeric_limits<int32_t>::min());
1877   }
1878 
1879   bool isMSRMask() const { return Kind == k_MSRMask; }
1880   bool isBankedReg() const { return Kind == k_BankedReg; }
1881   bool isProcIFlags() const { return Kind == k_ProcIFlags; }
1882 
1883   // NEON operands.
1884   bool isSingleSpacedVectorList() const {
1885     return Kind == k_VectorList && !VectorList.isDoubleSpaced;
1886   }
1887 
1888   bool isDoubleSpacedVectorList() const {
1889     return Kind == k_VectorList && VectorList.isDoubleSpaced;
1890   }
1891 
1892   bool isVecListOneD() const {
1893     if (!isSingleSpacedVectorList()) return false;
1894     return VectorList.Count == 1;
1895   }
1896 
1897   bool isVecListTwoMQ() const {
1898     return isSingleSpacedVectorList() && VectorList.Count == 2 &&
1899            ARMMCRegisterClasses[ARM::MQPRRegClassID].contains(
1900                VectorList.RegNum);
1901   }
1902 
1903   bool isVecListDPair() const {
1904     if (!isSingleSpacedVectorList()) return false;
1905     return (ARMMCRegisterClasses[ARM::DPairRegClassID]
1906               .contains(VectorList.RegNum));
1907   }
1908 
1909   bool isVecListThreeD() const {
1910     if (!isSingleSpacedVectorList()) return false;
1911     return VectorList.Count == 3;
1912   }
1913 
1914   bool isVecListFourD() const {
1915     if (!isSingleSpacedVectorList()) return false;
1916     return VectorList.Count == 4;
1917   }
1918 
1919   bool isVecListDPairSpaced() const {
1920     if (Kind != k_VectorList) return false;
1921     if (isSingleSpacedVectorList()) return false;
1922     return (ARMMCRegisterClasses[ARM::DPairSpcRegClassID]
1923               .contains(VectorList.RegNum));
1924   }
1925 
1926   bool isVecListThreeQ() const {
1927     if (!isDoubleSpacedVectorList()) return false;
1928     return VectorList.Count == 3;
1929   }
1930 
1931   bool isVecListFourQ() const {
1932     if (!isDoubleSpacedVectorList()) return false;
1933     return VectorList.Count == 4;
1934   }
1935 
1936   bool isVecListFourMQ() const {
1937     return isSingleSpacedVectorList() && VectorList.Count == 4 &&
1938            ARMMCRegisterClasses[ARM::MQPRRegClassID].contains(
1939                VectorList.RegNum);
1940   }
1941 
1942   bool isSingleSpacedVectorAllLanes() const {
1943     return Kind == k_VectorListAllLanes && !VectorList.isDoubleSpaced;
1944   }
1945 
1946   bool isDoubleSpacedVectorAllLanes() const {
1947     return Kind == k_VectorListAllLanes && VectorList.isDoubleSpaced;
1948   }
1949 
1950   bool isVecListOneDAllLanes() const {
1951     if (!isSingleSpacedVectorAllLanes()) return false;
1952     return VectorList.Count == 1;
1953   }
1954 
1955   bool isVecListDPairAllLanes() const {
1956     if (!isSingleSpacedVectorAllLanes()) return false;
1957     return (ARMMCRegisterClasses[ARM::DPairRegClassID]
1958               .contains(VectorList.RegNum));
1959   }
1960 
1961   bool isVecListDPairSpacedAllLanes() const {
1962     if (!isDoubleSpacedVectorAllLanes()) return false;
1963     return VectorList.Count == 2;
1964   }
1965 
1966   bool isVecListThreeDAllLanes() const {
1967     if (!isSingleSpacedVectorAllLanes()) return false;
1968     return VectorList.Count == 3;
1969   }
1970 
1971   bool isVecListThreeQAllLanes() const {
1972     if (!isDoubleSpacedVectorAllLanes()) return false;
1973     return VectorList.Count == 3;
1974   }
1975 
1976   bool isVecListFourDAllLanes() const {
1977     if (!isSingleSpacedVectorAllLanes()) return false;
1978     return VectorList.Count == 4;
1979   }
1980 
1981   bool isVecListFourQAllLanes() const {
1982     if (!isDoubleSpacedVectorAllLanes()) return false;
1983     return VectorList.Count == 4;
1984   }
1985 
1986   bool isSingleSpacedVectorIndexed() const {
1987     return Kind == k_VectorListIndexed && !VectorList.isDoubleSpaced;
1988   }
1989 
1990   bool isDoubleSpacedVectorIndexed() const {
1991     return Kind == k_VectorListIndexed && VectorList.isDoubleSpaced;
1992   }
1993 
1994   bool isVecListOneDByteIndexed() const {
1995     if (!isSingleSpacedVectorIndexed()) return false;
1996     return VectorList.Count == 1 && VectorList.LaneIndex <= 7;
1997   }
1998 
1999   bool isVecListOneDHWordIndexed() const {
2000     if (!isSingleSpacedVectorIndexed()) return false;
2001     return VectorList.Count == 1 && VectorList.LaneIndex <= 3;
2002   }
2003 
2004   bool isVecListOneDWordIndexed() const {
2005     if (!isSingleSpacedVectorIndexed()) return false;
2006     return VectorList.Count == 1 && VectorList.LaneIndex <= 1;
2007   }
2008 
2009   bool isVecListTwoDByteIndexed() const {
2010     if (!isSingleSpacedVectorIndexed()) return false;
2011     return VectorList.Count == 2 && VectorList.LaneIndex <= 7;
2012   }
2013 
2014   bool isVecListTwoDHWordIndexed() const {
2015     if (!isSingleSpacedVectorIndexed()) return false;
2016     return VectorList.Count == 2 && VectorList.LaneIndex <= 3;
2017   }
2018 
2019   bool isVecListTwoQWordIndexed() const {
2020     if (!isDoubleSpacedVectorIndexed()) return false;
2021     return VectorList.Count == 2 && VectorList.LaneIndex <= 1;
2022   }
2023 
2024   bool isVecListTwoQHWordIndexed() const {
2025     if (!isDoubleSpacedVectorIndexed()) return false;
2026     return VectorList.Count == 2 && VectorList.LaneIndex <= 3;
2027   }
2028 
2029   bool isVecListTwoDWordIndexed() const {
2030     if (!isSingleSpacedVectorIndexed()) return false;
2031     return VectorList.Count == 2 && VectorList.LaneIndex <= 1;
2032   }
2033 
2034   bool isVecListThreeDByteIndexed() const {
2035     if (!isSingleSpacedVectorIndexed()) return false;
2036     return VectorList.Count == 3 && VectorList.LaneIndex <= 7;
2037   }
2038 
2039   bool isVecListThreeDHWordIndexed() const {
2040     if (!isSingleSpacedVectorIndexed()) return false;
2041     return VectorList.Count == 3 && VectorList.LaneIndex <= 3;
2042   }
2043 
2044   bool isVecListThreeQWordIndexed() const {
2045     if (!isDoubleSpacedVectorIndexed()) return false;
2046     return VectorList.Count == 3 && VectorList.LaneIndex <= 1;
2047   }
2048 
2049   bool isVecListThreeQHWordIndexed() const {
2050     if (!isDoubleSpacedVectorIndexed()) return false;
2051     return VectorList.Count == 3 && VectorList.LaneIndex <= 3;
2052   }
2053 
2054   bool isVecListThreeDWordIndexed() const {
2055     if (!isSingleSpacedVectorIndexed()) return false;
2056     return VectorList.Count == 3 && VectorList.LaneIndex <= 1;
2057   }
2058 
2059   bool isVecListFourDByteIndexed() const {
2060     if (!isSingleSpacedVectorIndexed()) return false;
2061     return VectorList.Count == 4 && VectorList.LaneIndex <= 7;
2062   }
2063 
2064   bool isVecListFourDHWordIndexed() const {
2065     if (!isSingleSpacedVectorIndexed()) return false;
2066     return VectorList.Count == 4 && VectorList.LaneIndex <= 3;
2067   }
2068 
2069   bool isVecListFourQWordIndexed() const {
2070     if (!isDoubleSpacedVectorIndexed()) return false;
2071     return VectorList.Count == 4 && VectorList.LaneIndex <= 1;
2072   }
2073 
2074   bool isVecListFourQHWordIndexed() const {
2075     if (!isDoubleSpacedVectorIndexed()) return false;
2076     return VectorList.Count == 4 && VectorList.LaneIndex <= 3;
2077   }
2078 
2079   bool isVecListFourDWordIndexed() const {
2080     if (!isSingleSpacedVectorIndexed()) return false;
2081     return VectorList.Count == 4 && VectorList.LaneIndex <= 1;
2082   }
2083 
2084   bool isVectorIndex() const { return Kind == k_VectorIndex; }
2085 
2086   template <unsigned NumLanes>
2087   bool isVectorIndexInRange() const {
2088     if (Kind != k_VectorIndex) return false;
2089     return VectorIndex.Val < NumLanes;
2090   }
2091 
2092   bool isVectorIndex8()  const { return isVectorIndexInRange<8>(); }
2093   bool isVectorIndex16() const { return isVectorIndexInRange<4>(); }
2094   bool isVectorIndex32() const { return isVectorIndexInRange<2>(); }
2095   bool isVectorIndex64() const { return isVectorIndexInRange<1>(); }
2096 
2097   template<int PermittedValue, int OtherPermittedValue>
2098   bool isMVEPairVectorIndex() const {
2099     if (Kind != k_VectorIndex) return false;
2100     return VectorIndex.Val == PermittedValue ||
2101            VectorIndex.Val == OtherPermittedValue;
2102   }
2103 
2104   bool isNEONi8splat() const {
2105     if (!isImm()) return false;
2106     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2107     // Must be a constant.
2108     if (!CE) return false;
2109     int64_t Value = CE->getValue();
2110     // i8 value splatted across 8 bytes. The immediate is just the 8 byte
2111     // value.
2112     return Value >= 0 && Value < 256;
2113   }
2114 
2115   bool isNEONi16splat() const {
2116     if (isNEONByteReplicate(2))
2117       return false; // Leave that for bytes replication and forbid by default.
2118     if (!isImm())
2119       return false;
2120     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2121     // Must be a constant.
2122     if (!CE) return false;
2123     unsigned Value = CE->getValue();
2124     return ARM_AM::isNEONi16splat(Value);
2125   }
2126 
2127   bool isNEONi16splatNot() const {
2128     if (!isImm())
2129       return false;
2130     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2131     // Must be a constant.
2132     if (!CE) return false;
2133     unsigned Value = CE->getValue();
2134     return ARM_AM::isNEONi16splat(~Value & 0xffff);
2135   }
2136 
2137   bool isNEONi32splat() const {
2138     if (isNEONByteReplicate(4))
2139       return false; // Leave that for bytes replication and forbid by default.
2140     if (!isImm())
2141       return false;
2142     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2143     // Must be a constant.
2144     if (!CE) return false;
2145     unsigned Value = CE->getValue();
2146     return ARM_AM::isNEONi32splat(Value);
2147   }
2148 
2149   bool isNEONi32splatNot() const {
2150     if (!isImm())
2151       return false;
2152     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2153     // Must be a constant.
2154     if (!CE) return false;
2155     unsigned Value = CE->getValue();
2156     return ARM_AM::isNEONi32splat(~Value);
2157   }
2158 
2159   static bool isValidNEONi32vmovImm(int64_t Value) {
2160     // i32 value with set bits only in one byte X000, 0X00, 00X0, or 000X,
2161     // for VMOV/VMVN only, 00Xf or 0Xff are also accepted.
2162     return ((Value & 0xffffffffffffff00) == 0) ||
2163            ((Value & 0xffffffffffff00ff) == 0) ||
2164            ((Value & 0xffffffffff00ffff) == 0) ||
2165            ((Value & 0xffffffff00ffffff) == 0) ||
2166            ((Value & 0xffffffffffff00ff) == 0xff) ||
2167            ((Value & 0xffffffffff00ffff) == 0xffff);
2168   }
2169 
2170   bool isNEONReplicate(unsigned Width, unsigned NumElems, bool Inv) const {
2171     assert((Width == 8 || Width == 16 || Width == 32) &&
2172            "Invalid element width");
2173     assert(NumElems * Width <= 64 && "Invalid result width");
2174 
2175     if (!isImm())
2176       return false;
2177     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2178     // Must be a constant.
2179     if (!CE)
2180       return false;
2181     int64_t Value = CE->getValue();
2182     if (!Value)
2183       return false; // Don't bother with zero.
2184     if (Inv)
2185       Value = ~Value;
2186 
2187     uint64_t Mask = (1ull << Width) - 1;
2188     uint64_t Elem = Value & Mask;
2189     if (Width == 16 && (Elem & 0x00ff) != 0 && (Elem & 0xff00) != 0)
2190       return false;
2191     if (Width == 32 && !isValidNEONi32vmovImm(Elem))
2192       return false;
2193 
2194     for (unsigned i = 1; i < NumElems; ++i) {
2195       Value >>= Width;
2196       if ((Value & Mask) != Elem)
2197         return false;
2198     }
2199     return true;
2200   }
2201 
2202   bool isNEONByteReplicate(unsigned NumBytes) const {
2203     return isNEONReplicate(8, NumBytes, false);
2204   }
2205 
2206   static void checkNeonReplicateArgs(unsigned FromW, unsigned ToW) {
2207     assert((FromW == 8 || FromW == 16 || FromW == 32) &&
2208            "Invalid source width");
2209     assert((ToW == 16 || ToW == 32 || ToW == 64) &&
2210            "Invalid destination width");
2211     assert(FromW < ToW && "ToW is not less than FromW");
2212   }
2213 
2214   template<unsigned FromW, unsigned ToW>
2215   bool isNEONmovReplicate() const {
2216     checkNeonReplicateArgs(FromW, ToW);
2217     if (ToW == 64 && isNEONi64splat())
2218       return false;
2219     return isNEONReplicate(FromW, ToW / FromW, false);
2220   }
2221 
2222   template<unsigned FromW, unsigned ToW>
2223   bool isNEONinvReplicate() const {
2224     checkNeonReplicateArgs(FromW, ToW);
2225     return isNEONReplicate(FromW, ToW / FromW, true);
2226   }
2227 
2228   bool isNEONi32vmov() const {
2229     if (isNEONByteReplicate(4))
2230       return false; // Let it to be classified as byte-replicate case.
2231     if (!isImm())
2232       return false;
2233     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2234     // Must be a constant.
2235     if (!CE)
2236       return false;
2237     return isValidNEONi32vmovImm(CE->getValue());
2238   }
2239 
2240   bool isNEONi32vmovNeg() const {
2241     if (!isImm()) return false;
2242     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2243     // Must be a constant.
2244     if (!CE) return false;
2245     return isValidNEONi32vmovImm(~CE->getValue());
2246   }
2247 
2248   bool isNEONi64splat() const {
2249     if (!isImm()) return false;
2250     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2251     // Must be a constant.
2252     if (!CE) return false;
2253     uint64_t Value = CE->getValue();
2254     // i64 value with each byte being either 0 or 0xff.
2255     for (unsigned i = 0; i < 8; ++i, Value >>= 8)
2256       if ((Value & 0xff) != 0 && (Value & 0xff) != 0xff) return false;
2257     return true;
2258   }
2259 
2260   template<int64_t Angle, int64_t Remainder>
2261   bool isComplexRotation() const {
2262     if (!isImm()) return false;
2263 
2264     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2265     if (!CE) return false;
2266     uint64_t Value = CE->getValue();
2267 
2268     return (Value % Angle == Remainder && Value <= 270);
2269   }
2270 
2271   bool isMVELongShift() const {
2272     if (!isImm()) return false;
2273     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2274     // Must be a constant.
2275     if (!CE) return false;
2276     uint64_t Value = CE->getValue();
2277     return Value >= 1 && Value <= 32;
2278   }
2279 
2280   bool isMveSaturateOp() const {
2281     if (!isImm()) return false;
2282     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2283     if (!CE) return false;
2284     uint64_t Value = CE->getValue();
2285     return Value == 48 || Value == 64;
2286   }
2287 
2288   bool isITCondCodeNoAL() const {
2289     if (!isITCondCode()) return false;
2290     ARMCC::CondCodes CC = getCondCode();
2291     return CC != ARMCC::AL;
2292   }
2293 
2294   bool isITCondCodeRestrictedI() const {
2295     if (!isITCondCode())
2296       return false;
2297     ARMCC::CondCodes CC = getCondCode();
2298     return CC == ARMCC::EQ || CC == ARMCC::NE;
2299   }
2300 
2301   bool isITCondCodeRestrictedS() const {
2302     if (!isITCondCode())
2303       return false;
2304     ARMCC::CondCodes CC = getCondCode();
2305     return CC == ARMCC::LT || CC == ARMCC::GT || CC == ARMCC::LE ||
2306            CC == ARMCC::GE;
2307   }
2308 
2309   bool isITCondCodeRestrictedU() const {
2310     if (!isITCondCode())
2311       return false;
2312     ARMCC::CondCodes CC = getCondCode();
2313     return CC == ARMCC::HS || CC == ARMCC::HI;
2314   }
2315 
2316   bool isITCondCodeRestrictedFP() const {
2317     if (!isITCondCode())
2318       return false;
2319     ARMCC::CondCodes CC = getCondCode();
2320     return CC == ARMCC::EQ || CC == ARMCC::NE || CC == ARMCC::LT ||
2321            CC == ARMCC::GT || CC == ARMCC::LE || CC == ARMCC::GE;
2322   }
2323 
2324   void addExpr(MCInst &Inst, const MCExpr *Expr) const {
2325     // Add as immediates when possible.  Null MCExpr = 0.
2326     if (!Expr)
2327       Inst.addOperand(MCOperand::createImm(0));
2328     else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
2329       Inst.addOperand(MCOperand::createImm(CE->getValue()));
2330     else
2331       Inst.addOperand(MCOperand::createExpr(Expr));
2332   }
2333 
2334   void addARMBranchTargetOperands(MCInst &Inst, unsigned N) const {
2335     assert(N == 1 && "Invalid number of operands!");
2336     addExpr(Inst, getImm());
2337   }
2338 
2339   void addThumbBranchTargetOperands(MCInst &Inst, unsigned N) const {
2340     assert(N == 1 && "Invalid number of operands!");
2341     addExpr(Inst, getImm());
2342   }
2343 
2344   void addCondCodeOperands(MCInst &Inst, unsigned N) const {
2345     assert(N == 2 && "Invalid number of operands!");
2346     Inst.addOperand(MCOperand::createImm(unsigned(getCondCode())));
2347     unsigned RegNum = getCondCode() == ARMCC::AL ? 0: ARM::CPSR;
2348     Inst.addOperand(MCOperand::createReg(RegNum));
2349   }
2350 
2351   void addVPTPredNOperands(MCInst &Inst, unsigned N) const {
2352     assert(N == 2 && "Invalid number of operands!");
2353     Inst.addOperand(MCOperand::createImm(unsigned(getVPTPred())));
2354     unsigned RegNum = getVPTPred() == ARMVCC::None ? 0: ARM::P0;
2355     Inst.addOperand(MCOperand::createReg(RegNum));
2356   }
2357 
2358   void addVPTPredROperands(MCInst &Inst, unsigned N) const {
2359     assert(N == 3 && "Invalid number of operands!");
2360     addVPTPredNOperands(Inst, N-1);
2361     unsigned RegNum;
2362     if (getVPTPred() == ARMVCC::None) {
2363       RegNum = 0;
2364     } else {
2365       unsigned NextOpIndex = Inst.getNumOperands();
2366       const MCInstrDesc &MCID = ARMInsts[Inst.getOpcode()];
2367       int TiedOp = MCID.getOperandConstraint(NextOpIndex, MCOI::TIED_TO);
2368       assert(TiedOp >= 0 &&
2369              "Inactive register in vpred_r is not tied to an output!");
2370       RegNum = Inst.getOperand(TiedOp).getReg();
2371     }
2372     Inst.addOperand(MCOperand::createReg(RegNum));
2373   }
2374 
2375   void addCoprocNumOperands(MCInst &Inst, unsigned N) const {
2376     assert(N == 1 && "Invalid number of operands!");
2377     Inst.addOperand(MCOperand::createImm(getCoproc()));
2378   }
2379 
2380   void addCoprocRegOperands(MCInst &Inst, unsigned N) const {
2381     assert(N == 1 && "Invalid number of operands!");
2382     Inst.addOperand(MCOperand::createImm(getCoproc()));
2383   }
2384 
2385   void addCoprocOptionOperands(MCInst &Inst, unsigned N) const {
2386     assert(N == 1 && "Invalid number of operands!");
2387     Inst.addOperand(MCOperand::createImm(CoprocOption.Val));
2388   }
2389 
2390   void addITMaskOperands(MCInst &Inst, unsigned N) const {
2391     assert(N == 1 && "Invalid number of operands!");
2392     Inst.addOperand(MCOperand::createImm(ITMask.Mask));
2393   }
2394 
2395   void addITCondCodeOperands(MCInst &Inst, unsigned N) const {
2396     assert(N == 1 && "Invalid number of operands!");
2397     Inst.addOperand(MCOperand::createImm(unsigned(getCondCode())));
2398   }
2399 
2400   void addITCondCodeInvOperands(MCInst &Inst, unsigned N) const {
2401     assert(N == 1 && "Invalid number of operands!");
2402     Inst.addOperand(MCOperand::createImm(unsigned(ARMCC::getOppositeCondition(getCondCode()))));
2403   }
2404 
2405   void addCCOutOperands(MCInst &Inst, unsigned N) const {
2406     assert(N == 1 && "Invalid number of operands!");
2407     Inst.addOperand(MCOperand::createReg(getReg()));
2408   }
2409 
2410   void addRegOperands(MCInst &Inst, unsigned N) const {
2411     assert(N == 1 && "Invalid number of operands!");
2412     Inst.addOperand(MCOperand::createReg(getReg()));
2413   }
2414 
2415   void addRegShiftedRegOperands(MCInst &Inst, unsigned N) const {
2416     assert(N == 3 && "Invalid number of operands!");
2417     assert(isRegShiftedReg() &&
2418            "addRegShiftedRegOperands() on non-RegShiftedReg!");
2419     Inst.addOperand(MCOperand::createReg(RegShiftedReg.SrcReg));
2420     Inst.addOperand(MCOperand::createReg(RegShiftedReg.ShiftReg));
2421     Inst.addOperand(MCOperand::createImm(
2422       ARM_AM::getSORegOpc(RegShiftedReg.ShiftTy, RegShiftedReg.ShiftImm)));
2423   }
2424 
2425   void addRegShiftedImmOperands(MCInst &Inst, unsigned N) const {
2426     assert(N == 2 && "Invalid number of operands!");
2427     assert(isRegShiftedImm() &&
2428            "addRegShiftedImmOperands() on non-RegShiftedImm!");
2429     Inst.addOperand(MCOperand::createReg(RegShiftedImm.SrcReg));
2430     // Shift of #32 is encoded as 0 where permitted
2431     unsigned Imm = (RegShiftedImm.ShiftImm == 32 ? 0 : RegShiftedImm.ShiftImm);
2432     Inst.addOperand(MCOperand::createImm(
2433       ARM_AM::getSORegOpc(RegShiftedImm.ShiftTy, Imm)));
2434   }
2435 
2436   void addShifterImmOperands(MCInst &Inst, unsigned N) const {
2437     assert(N == 1 && "Invalid number of operands!");
2438     Inst.addOperand(MCOperand::createImm((ShifterImm.isASR << 5) |
2439                                          ShifterImm.Imm));
2440   }
2441 
2442   void addRegListOperands(MCInst &Inst, unsigned N) const {
2443     assert(N == 1 && "Invalid number of operands!");
2444     const SmallVectorImpl<unsigned> &RegList = getRegList();
2445     for (SmallVectorImpl<unsigned>::const_iterator
2446            I = RegList.begin(), E = RegList.end(); I != E; ++I)
2447       Inst.addOperand(MCOperand::createReg(*I));
2448   }
2449 
2450   void addRegListWithAPSROperands(MCInst &Inst, unsigned N) const {
2451     assert(N == 1 && "Invalid number of operands!");
2452     const SmallVectorImpl<unsigned> &RegList = getRegList();
2453     for (SmallVectorImpl<unsigned>::const_iterator
2454            I = RegList.begin(), E = RegList.end(); I != E; ++I)
2455       Inst.addOperand(MCOperand::createReg(*I));
2456   }
2457 
2458   void addDPRRegListOperands(MCInst &Inst, unsigned N) const {
2459     addRegListOperands(Inst, N);
2460   }
2461 
2462   void addSPRRegListOperands(MCInst &Inst, unsigned N) const {
2463     addRegListOperands(Inst, N);
2464   }
2465 
2466   void addFPSRegListWithVPROperands(MCInst &Inst, unsigned N) const {
2467     addRegListOperands(Inst, N);
2468   }
2469 
2470   void addFPDRegListWithVPROperands(MCInst &Inst, unsigned N) const {
2471     addRegListOperands(Inst, N);
2472   }
2473 
2474   void addRotImmOperands(MCInst &Inst, unsigned N) const {
2475     assert(N == 1 && "Invalid number of operands!");
2476     // Encoded as val>>3. The printer handles display as 8, 16, 24.
2477     Inst.addOperand(MCOperand::createImm(RotImm.Imm >> 3));
2478   }
2479 
2480   void addModImmOperands(MCInst &Inst, unsigned N) const {
2481     assert(N == 1 && "Invalid number of operands!");
2482 
2483     // Support for fixups (MCFixup)
2484     if (isImm())
2485       return addImmOperands(Inst, N);
2486 
2487     Inst.addOperand(MCOperand::createImm(ModImm.Bits | (ModImm.Rot << 7)));
2488   }
2489 
2490   void addModImmNotOperands(MCInst &Inst, unsigned N) const {
2491     assert(N == 1 && "Invalid number of operands!");
2492     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2493     uint32_t Enc = ARM_AM::getSOImmVal(~CE->getValue());
2494     Inst.addOperand(MCOperand::createImm(Enc));
2495   }
2496 
2497   void addModImmNegOperands(MCInst &Inst, unsigned N) const {
2498     assert(N == 1 && "Invalid number of operands!");
2499     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2500     uint32_t Enc = ARM_AM::getSOImmVal(-CE->getValue());
2501     Inst.addOperand(MCOperand::createImm(Enc));
2502   }
2503 
2504   void addThumbModImmNeg8_255Operands(MCInst &Inst, unsigned N) const {
2505     assert(N == 1 && "Invalid number of operands!");
2506     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2507     uint32_t Val = -CE->getValue();
2508     Inst.addOperand(MCOperand::createImm(Val));
2509   }
2510 
2511   void addThumbModImmNeg1_7Operands(MCInst &Inst, unsigned N) const {
2512     assert(N == 1 && "Invalid number of operands!");
2513     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2514     uint32_t Val = -CE->getValue();
2515     Inst.addOperand(MCOperand::createImm(Val));
2516   }
2517 
2518   void addBitfieldOperands(MCInst &Inst, unsigned N) const {
2519     assert(N == 1 && "Invalid number of operands!");
2520     // Munge the lsb/width into a bitfield mask.
2521     unsigned lsb = Bitfield.LSB;
2522     unsigned width = Bitfield.Width;
2523     // Make a 32-bit mask w/ the referenced bits clear and all other bits set.
2524     uint32_t Mask = ~(((uint32_t)0xffffffff >> lsb) << (32 - width) >>
2525                       (32 - (lsb + width)));
2526     Inst.addOperand(MCOperand::createImm(Mask));
2527   }
2528 
2529   void addImmOperands(MCInst &Inst, unsigned N) const {
2530     assert(N == 1 && "Invalid number of operands!");
2531     addExpr(Inst, getImm());
2532   }
2533 
2534   void addFBits16Operands(MCInst &Inst, unsigned N) const {
2535     assert(N == 1 && "Invalid number of operands!");
2536     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2537     Inst.addOperand(MCOperand::createImm(16 - CE->getValue()));
2538   }
2539 
2540   void addFBits32Operands(MCInst &Inst, unsigned N) const {
2541     assert(N == 1 && "Invalid number of operands!");
2542     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2543     Inst.addOperand(MCOperand::createImm(32 - CE->getValue()));
2544   }
2545 
2546   void addFPImmOperands(MCInst &Inst, unsigned N) const {
2547     assert(N == 1 && "Invalid number of operands!");
2548     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2549     int Val = ARM_AM::getFP32Imm(APInt(32, CE->getValue()));
2550     Inst.addOperand(MCOperand::createImm(Val));
2551   }
2552 
2553   void addImm8s4Operands(MCInst &Inst, unsigned N) const {
2554     assert(N == 1 && "Invalid number of operands!");
2555     // FIXME: We really want to scale the value here, but the LDRD/STRD
2556     // instruction don't encode operands that way yet.
2557     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2558     Inst.addOperand(MCOperand::createImm(CE->getValue()));
2559   }
2560 
2561   void addImm7s4Operands(MCInst &Inst, unsigned N) const {
2562     assert(N == 1 && "Invalid number of operands!");
2563     // FIXME: We really want to scale the value here, but the VSTR/VLDR_VSYSR
2564     // instruction don't encode operands that way yet.
2565     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2566     Inst.addOperand(MCOperand::createImm(CE->getValue()));
2567   }
2568 
2569   void addImm7Shift0Operands(MCInst &Inst, unsigned N) const {
2570     assert(N == 1 && "Invalid number of operands!");
2571     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2572     Inst.addOperand(MCOperand::createImm(CE->getValue()));
2573   }
2574 
2575   void addImm7Shift1Operands(MCInst &Inst, unsigned N) const {
2576     assert(N == 1 && "Invalid number of operands!");
2577     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2578     Inst.addOperand(MCOperand::createImm(CE->getValue()));
2579   }
2580 
2581   void addImm7Shift2Operands(MCInst &Inst, unsigned N) const {
2582     assert(N == 1 && "Invalid number of operands!");
2583     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2584     Inst.addOperand(MCOperand::createImm(CE->getValue()));
2585   }
2586 
2587   void addImm7Operands(MCInst &Inst, unsigned N) const {
2588     assert(N == 1 && "Invalid number of operands!");
2589     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2590     Inst.addOperand(MCOperand::createImm(CE->getValue()));
2591   }
2592 
2593   void addImm0_1020s4Operands(MCInst &Inst, unsigned N) const {
2594     assert(N == 1 && "Invalid number of operands!");
2595     // The immediate is scaled by four in the encoding and is stored
2596     // in the MCInst as such. Lop off the low two bits here.
2597     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2598     Inst.addOperand(MCOperand::createImm(CE->getValue() / 4));
2599   }
2600 
2601   void addImm0_508s4NegOperands(MCInst &Inst, unsigned N) const {
2602     assert(N == 1 && "Invalid number of operands!");
2603     // The immediate is scaled by four in the encoding and is stored
2604     // in the MCInst as such. Lop off the low two bits here.
2605     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2606     Inst.addOperand(MCOperand::createImm(-(CE->getValue() / 4)));
2607   }
2608 
2609   void addImm0_508s4Operands(MCInst &Inst, unsigned N) const {
2610     assert(N == 1 && "Invalid number of operands!");
2611     // The immediate is scaled by four in the encoding and is stored
2612     // in the MCInst as such. Lop off the low two bits here.
2613     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2614     Inst.addOperand(MCOperand::createImm(CE->getValue() / 4));
2615   }
2616 
2617   void addImm1_16Operands(MCInst &Inst, unsigned N) const {
2618     assert(N == 1 && "Invalid number of operands!");
2619     // The constant encodes as the immediate-1, and we store in the instruction
2620     // the bits as encoded, so subtract off one here.
2621     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2622     Inst.addOperand(MCOperand::createImm(CE->getValue() - 1));
2623   }
2624 
2625   void addImm1_32Operands(MCInst &Inst, unsigned N) const {
2626     assert(N == 1 && "Invalid number of operands!");
2627     // The constant encodes as the immediate-1, and we store in the instruction
2628     // the bits as encoded, so subtract off one here.
2629     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2630     Inst.addOperand(MCOperand::createImm(CE->getValue() - 1));
2631   }
2632 
2633   void addImmThumbSROperands(MCInst &Inst, unsigned N) const {
2634     assert(N == 1 && "Invalid number of operands!");
2635     // The constant encodes as the immediate, except for 32, which encodes as
2636     // zero.
2637     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2638     unsigned Imm = CE->getValue();
2639     Inst.addOperand(MCOperand::createImm((Imm == 32 ? 0 : Imm)));
2640   }
2641 
2642   void addPKHASRImmOperands(MCInst &Inst, unsigned N) const {
2643     assert(N == 1 && "Invalid number of operands!");
2644     // An ASR value of 32 encodes as 0, so that's how we want to add it to
2645     // the instruction as well.
2646     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2647     int Val = CE->getValue();
2648     Inst.addOperand(MCOperand::createImm(Val == 32 ? 0 : Val));
2649   }
2650 
2651   void addT2SOImmNotOperands(MCInst &Inst, unsigned N) const {
2652     assert(N == 1 && "Invalid number of operands!");
2653     // The operand is actually a t2_so_imm, but we have its bitwise
2654     // negation in the assembly source, so twiddle it here.
2655     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2656     Inst.addOperand(MCOperand::createImm(~(uint32_t)CE->getValue()));
2657   }
2658 
2659   void addT2SOImmNegOperands(MCInst &Inst, unsigned N) const {
2660     assert(N == 1 && "Invalid number of operands!");
2661     // The operand is actually a t2_so_imm, but we have its
2662     // negation in the assembly source, so twiddle it here.
2663     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2664     Inst.addOperand(MCOperand::createImm(-(uint32_t)CE->getValue()));
2665   }
2666 
2667   void addImm0_4095NegOperands(MCInst &Inst, unsigned N) const {
2668     assert(N == 1 && "Invalid number of operands!");
2669     // The operand is actually an imm0_4095, but we have its
2670     // negation in the assembly source, so twiddle it here.
2671     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2672     Inst.addOperand(MCOperand::createImm(-(uint32_t)CE->getValue()));
2673   }
2674 
2675   void addUnsignedOffset_b8s2Operands(MCInst &Inst, unsigned N) const {
2676     if(const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm())) {
2677       Inst.addOperand(MCOperand::createImm(CE->getValue() >> 2));
2678       return;
2679     }
2680     const MCSymbolRefExpr *SR = cast<MCSymbolRefExpr>(Imm.Val);
2681     Inst.addOperand(MCOperand::createExpr(SR));
2682   }
2683 
2684   void addThumbMemPCOperands(MCInst &Inst, unsigned N) const {
2685     assert(N == 1 && "Invalid number of operands!");
2686     if (isImm()) {
2687       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2688       if (CE) {
2689         Inst.addOperand(MCOperand::createImm(CE->getValue()));
2690         return;
2691       }
2692       const MCSymbolRefExpr *SR = cast<MCSymbolRefExpr>(Imm.Val);
2693       Inst.addOperand(MCOperand::createExpr(SR));
2694       return;
2695     }
2696 
2697     assert(isGPRMem()  && "Unknown value type!");
2698     assert(isa<MCConstantExpr>(Memory.OffsetImm) && "Unknown value type!");
2699     Inst.addOperand(MCOperand::createImm(Memory.OffsetImm->getValue()));
2700   }
2701 
2702   void addMemBarrierOptOperands(MCInst &Inst, unsigned N) const {
2703     assert(N == 1 && "Invalid number of operands!");
2704     Inst.addOperand(MCOperand::createImm(unsigned(getMemBarrierOpt())));
2705   }
2706 
2707   void addInstSyncBarrierOptOperands(MCInst &Inst, unsigned N) const {
2708     assert(N == 1 && "Invalid number of operands!");
2709     Inst.addOperand(MCOperand::createImm(unsigned(getInstSyncBarrierOpt())));
2710   }
2711 
2712   void addTraceSyncBarrierOptOperands(MCInst &Inst, unsigned N) const {
2713     assert(N == 1 && "Invalid number of operands!");
2714     Inst.addOperand(MCOperand::createImm(unsigned(getTraceSyncBarrierOpt())));
2715   }
2716 
2717   void addMemNoOffsetOperands(MCInst &Inst, unsigned N) const {
2718     assert(N == 1 && "Invalid number of operands!");
2719     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2720   }
2721 
2722   void addMemNoOffsetT2Operands(MCInst &Inst, unsigned N) const {
2723     assert(N == 1 && "Invalid number of operands!");
2724     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2725   }
2726 
2727   void addMemNoOffsetT2NoSpOperands(MCInst &Inst, unsigned N) const {
2728     assert(N == 1 && "Invalid number of operands!");
2729     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2730   }
2731 
2732   void addMemNoOffsetTOperands(MCInst &Inst, unsigned N) const {
2733     assert(N == 1 && "Invalid number of operands!");
2734     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2735   }
2736 
2737   void addMemPCRelImm12Operands(MCInst &Inst, unsigned N) const {
2738     assert(N == 1 && "Invalid number of operands!");
2739     int32_t Imm = Memory.OffsetImm->getValue();
2740     Inst.addOperand(MCOperand::createImm(Imm));
2741   }
2742 
2743   void addAdrLabelOperands(MCInst &Inst, unsigned N) const {
2744     assert(N == 1 && "Invalid number of operands!");
2745     assert(isImm() && "Not an immediate!");
2746 
2747     // If we have an immediate that's not a constant, treat it as a label
2748     // reference needing a fixup.
2749     if (!isa<MCConstantExpr>(getImm())) {
2750       Inst.addOperand(MCOperand::createExpr(getImm()));
2751       return;
2752     }
2753 
2754     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
2755     int Val = CE->getValue();
2756     Inst.addOperand(MCOperand::createImm(Val));
2757   }
2758 
2759   void addAlignedMemoryOperands(MCInst &Inst, unsigned N) const {
2760     assert(N == 2 && "Invalid number of operands!");
2761     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2762     Inst.addOperand(MCOperand::createImm(Memory.Alignment));
2763   }
2764 
2765   void addDupAlignedMemoryNoneOperands(MCInst &Inst, unsigned N) const {
2766     addAlignedMemoryOperands(Inst, N);
2767   }
2768 
2769   void addAlignedMemoryNoneOperands(MCInst &Inst, unsigned N) const {
2770     addAlignedMemoryOperands(Inst, N);
2771   }
2772 
2773   void addAlignedMemory16Operands(MCInst &Inst, unsigned N) const {
2774     addAlignedMemoryOperands(Inst, N);
2775   }
2776 
2777   void addDupAlignedMemory16Operands(MCInst &Inst, unsigned N) const {
2778     addAlignedMemoryOperands(Inst, N);
2779   }
2780 
2781   void addAlignedMemory32Operands(MCInst &Inst, unsigned N) const {
2782     addAlignedMemoryOperands(Inst, N);
2783   }
2784 
2785   void addDupAlignedMemory32Operands(MCInst &Inst, unsigned N) const {
2786     addAlignedMemoryOperands(Inst, N);
2787   }
2788 
2789   void addAlignedMemory64Operands(MCInst &Inst, unsigned N) const {
2790     addAlignedMemoryOperands(Inst, N);
2791   }
2792 
2793   void addDupAlignedMemory64Operands(MCInst &Inst, unsigned N) const {
2794     addAlignedMemoryOperands(Inst, N);
2795   }
2796 
2797   void addAlignedMemory64or128Operands(MCInst &Inst, unsigned N) const {
2798     addAlignedMemoryOperands(Inst, N);
2799   }
2800 
2801   void addDupAlignedMemory64or128Operands(MCInst &Inst, unsigned N) const {
2802     addAlignedMemoryOperands(Inst, N);
2803   }
2804 
2805   void addAlignedMemory64or128or256Operands(MCInst &Inst, unsigned N) const {
2806     addAlignedMemoryOperands(Inst, N);
2807   }
2808 
2809   void addAddrMode2Operands(MCInst &Inst, unsigned N) const {
2810     assert(N == 3 && "Invalid number of operands!");
2811     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2812     if (!Memory.OffsetRegNum) {
2813       ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2814       // Special case for #-0
2815       if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2816       if (Val < 0) Val = -Val;
2817       Val = ARM_AM::getAM2Opc(AddSub, Val, ARM_AM::no_shift);
2818     } else {
2819       // For register offset, we encode the shift type and negation flag
2820       // here.
2821       Val = ARM_AM::getAM2Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add,
2822                               Memory.ShiftImm, Memory.ShiftType);
2823     }
2824     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2825     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2826     Inst.addOperand(MCOperand::createImm(Val));
2827   }
2828 
2829   void addAM2OffsetImmOperands(MCInst &Inst, unsigned N) const {
2830     assert(N == 2 && "Invalid number of operands!");
2831     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2832     assert(CE && "non-constant AM2OffsetImm operand!");
2833     int32_t Val = CE->getValue();
2834     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2835     // Special case for #-0
2836     if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2837     if (Val < 0) Val = -Val;
2838     Val = ARM_AM::getAM2Opc(AddSub, Val, ARM_AM::no_shift);
2839     Inst.addOperand(MCOperand::createReg(0));
2840     Inst.addOperand(MCOperand::createImm(Val));
2841   }
2842 
2843   void addAddrMode3Operands(MCInst &Inst, unsigned N) const {
2844     assert(N == 3 && "Invalid number of operands!");
2845     // If we have an immediate that's not a constant, treat it as a label
2846     // reference needing a fixup. If it is a constant, it's something else
2847     // and we reject it.
2848     if (isImm()) {
2849       Inst.addOperand(MCOperand::createExpr(getImm()));
2850       Inst.addOperand(MCOperand::createReg(0));
2851       Inst.addOperand(MCOperand::createImm(0));
2852       return;
2853     }
2854 
2855     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2856     if (!Memory.OffsetRegNum) {
2857       ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2858       // Special case for #-0
2859       if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2860       if (Val < 0) Val = -Val;
2861       Val = ARM_AM::getAM3Opc(AddSub, Val);
2862     } else {
2863       // For register offset, we encode the shift type and negation flag
2864       // here.
2865       Val = ARM_AM::getAM3Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add, 0);
2866     }
2867     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2868     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2869     Inst.addOperand(MCOperand::createImm(Val));
2870   }
2871 
2872   void addAM3OffsetOperands(MCInst &Inst, unsigned N) const {
2873     assert(N == 2 && "Invalid number of operands!");
2874     if (Kind == k_PostIndexRegister) {
2875       int32_t Val =
2876         ARM_AM::getAM3Opc(PostIdxReg.isAdd ? ARM_AM::add : ARM_AM::sub, 0);
2877       Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
2878       Inst.addOperand(MCOperand::createImm(Val));
2879       return;
2880     }
2881 
2882     // Constant offset.
2883     const MCConstantExpr *CE = static_cast<const MCConstantExpr*>(getImm());
2884     int32_t Val = CE->getValue();
2885     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2886     // Special case for #-0
2887     if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2888     if (Val < 0) Val = -Val;
2889     Val = ARM_AM::getAM3Opc(AddSub, Val);
2890     Inst.addOperand(MCOperand::createReg(0));
2891     Inst.addOperand(MCOperand::createImm(Val));
2892   }
2893 
2894   void addAddrMode5Operands(MCInst &Inst, unsigned N) const {
2895     assert(N == 2 && "Invalid number of operands!");
2896     // If we have an immediate that's not a constant, treat it as a label
2897     // reference needing a fixup. If it is a constant, it's something else
2898     // and we reject it.
2899     if (isImm()) {
2900       Inst.addOperand(MCOperand::createExpr(getImm()));
2901       Inst.addOperand(MCOperand::createImm(0));
2902       return;
2903     }
2904 
2905     // The lower two bits are always zero and as such are not encoded.
2906     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 4 : 0;
2907     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2908     // Special case for #-0
2909     if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2910     if (Val < 0) Val = -Val;
2911     Val = ARM_AM::getAM5Opc(AddSub, Val);
2912     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2913     Inst.addOperand(MCOperand::createImm(Val));
2914   }
2915 
2916   void addAddrMode5FP16Operands(MCInst &Inst, unsigned N) const {
2917     assert(N == 2 && "Invalid number of operands!");
2918     // If we have an immediate that's not a constant, treat it as a label
2919     // reference needing a fixup. If it is a constant, it's something else
2920     // and we reject it.
2921     if (isImm()) {
2922       Inst.addOperand(MCOperand::createExpr(getImm()));
2923       Inst.addOperand(MCOperand::createImm(0));
2924       return;
2925     }
2926 
2927     // The lower bit is always zero and as such is not encoded.
2928     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 2 : 0;
2929     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2930     // Special case for #-0
2931     if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2932     if (Val < 0) Val = -Val;
2933     Val = ARM_AM::getAM5FP16Opc(AddSub, Val);
2934     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2935     Inst.addOperand(MCOperand::createImm(Val));
2936   }
2937 
2938   void addMemImm8s4OffsetOperands(MCInst &Inst, unsigned N) const {
2939     assert(N == 2 && "Invalid number of operands!");
2940     // If we have an immediate that's not a constant, treat it as a label
2941     // reference needing a fixup. If it is a constant, it's something else
2942     // and we reject it.
2943     if (isImm()) {
2944       Inst.addOperand(MCOperand::createExpr(getImm()));
2945       Inst.addOperand(MCOperand::createImm(0));
2946       return;
2947     }
2948 
2949     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2950     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2951     Inst.addOperand(MCOperand::createImm(Val));
2952   }
2953 
2954   void addMemImm7s4OffsetOperands(MCInst &Inst, unsigned N) const {
2955     assert(N == 2 && "Invalid number of operands!");
2956     // If we have an immediate that's not a constant, treat it as a label
2957     // reference needing a fixup. If it is a constant, it's something else
2958     // and we reject it.
2959     if (isImm()) {
2960       Inst.addOperand(MCOperand::createExpr(getImm()));
2961       Inst.addOperand(MCOperand::createImm(0));
2962       return;
2963     }
2964 
2965     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2966     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2967     Inst.addOperand(MCOperand::createImm(Val));
2968   }
2969 
2970   void addMemImm0_1020s4OffsetOperands(MCInst &Inst, unsigned N) const {
2971     assert(N == 2 && "Invalid number of operands!");
2972     // The lower two bits are always zero and as such are not encoded.
2973     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 4 : 0;
2974     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2975     Inst.addOperand(MCOperand::createImm(Val));
2976   }
2977 
2978   void addMemImmOffsetOperands(MCInst &Inst, unsigned N) const {
2979     assert(N == 2 && "Invalid number of operands!");
2980     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2981     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2982     Inst.addOperand(MCOperand::createImm(Val));
2983   }
2984 
2985   void addMemRegRQOffsetOperands(MCInst &Inst, unsigned N) const {
2986     assert(N == 2 && "Invalid number of operands!");
2987     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2988     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2989   }
2990 
2991   void addMemUImm12OffsetOperands(MCInst &Inst, unsigned N) const {
2992     assert(N == 2 && "Invalid number of operands!");
2993     // If this is an immediate, it's a label reference.
2994     if (isImm()) {
2995       addExpr(Inst, getImm());
2996       Inst.addOperand(MCOperand::createImm(0));
2997       return;
2998     }
2999 
3000     // Otherwise, it's a normal memory reg+offset.
3001     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
3002     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3003     Inst.addOperand(MCOperand::createImm(Val));
3004   }
3005 
3006   void addMemImm12OffsetOperands(MCInst &Inst, unsigned N) const {
3007     assert(N == 2 && "Invalid number of operands!");
3008     // If this is an immediate, it's a label reference.
3009     if (isImm()) {
3010       addExpr(Inst, getImm());
3011       Inst.addOperand(MCOperand::createImm(0));
3012       return;
3013     }
3014 
3015     // Otherwise, it's a normal memory reg+offset.
3016     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
3017     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3018     Inst.addOperand(MCOperand::createImm(Val));
3019   }
3020 
3021   void addConstPoolAsmImmOperands(MCInst &Inst, unsigned N) const {
3022     assert(N == 1 && "Invalid number of operands!");
3023     // This is container for the immediate that we will create the constant
3024     // pool from
3025     addExpr(Inst, getConstantPoolImm());
3026     return;
3027   }
3028 
3029   void addMemTBBOperands(MCInst &Inst, unsigned N) const {
3030     assert(N == 2 && "Invalid number of operands!");
3031     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3032     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
3033   }
3034 
3035   void addMemTBHOperands(MCInst &Inst, unsigned N) const {
3036     assert(N == 2 && "Invalid number of operands!");
3037     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3038     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
3039   }
3040 
3041   void addMemRegOffsetOperands(MCInst &Inst, unsigned N) const {
3042     assert(N == 3 && "Invalid number of operands!");
3043     unsigned Val =
3044       ARM_AM::getAM2Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add,
3045                         Memory.ShiftImm, Memory.ShiftType);
3046     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3047     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
3048     Inst.addOperand(MCOperand::createImm(Val));
3049   }
3050 
3051   void addT2MemRegOffsetOperands(MCInst &Inst, unsigned N) const {
3052     assert(N == 3 && "Invalid number of operands!");
3053     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3054     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
3055     Inst.addOperand(MCOperand::createImm(Memory.ShiftImm));
3056   }
3057 
3058   void addMemThumbRROperands(MCInst &Inst, unsigned N) const {
3059     assert(N == 2 && "Invalid number of operands!");
3060     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3061     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
3062   }
3063 
3064   void addMemThumbRIs4Operands(MCInst &Inst, unsigned N) const {
3065     assert(N == 2 && "Invalid number of operands!");
3066     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 4) : 0;
3067     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3068     Inst.addOperand(MCOperand::createImm(Val));
3069   }
3070 
3071   void addMemThumbRIs2Operands(MCInst &Inst, unsigned N) const {
3072     assert(N == 2 && "Invalid number of operands!");
3073     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 2) : 0;
3074     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3075     Inst.addOperand(MCOperand::createImm(Val));
3076   }
3077 
3078   void addMemThumbRIs1Operands(MCInst &Inst, unsigned N) const {
3079     assert(N == 2 && "Invalid number of operands!");
3080     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue()) : 0;
3081     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3082     Inst.addOperand(MCOperand::createImm(Val));
3083   }
3084 
3085   void addMemThumbSPIOperands(MCInst &Inst, unsigned N) const {
3086     assert(N == 2 && "Invalid number of operands!");
3087     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 4) : 0;
3088     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
3089     Inst.addOperand(MCOperand::createImm(Val));
3090   }
3091 
3092   void addPostIdxImm8Operands(MCInst &Inst, unsigned N) const {
3093     assert(N == 1 && "Invalid number of operands!");
3094     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
3095     assert(CE && "non-constant post-idx-imm8 operand!");
3096     int Imm = CE->getValue();
3097     bool isAdd = Imm >= 0;
3098     if (Imm == std::numeric_limits<int32_t>::min()) Imm = 0;
3099     Imm = (Imm < 0 ? -Imm : Imm) | (int)isAdd << 8;
3100     Inst.addOperand(MCOperand::createImm(Imm));
3101   }
3102 
3103   void addPostIdxImm8s4Operands(MCInst &Inst, unsigned N) const {
3104     assert(N == 1 && "Invalid number of operands!");
3105     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
3106     assert(CE && "non-constant post-idx-imm8s4 operand!");
3107     int Imm = CE->getValue();
3108     bool isAdd = Imm >= 0;
3109     if (Imm == std::numeric_limits<int32_t>::min()) Imm = 0;
3110     // Immediate is scaled by 4.
3111     Imm = ((Imm < 0 ? -Imm : Imm) / 4) | (int)isAdd << 8;
3112     Inst.addOperand(MCOperand::createImm(Imm));
3113   }
3114 
3115   void addPostIdxRegOperands(MCInst &Inst, unsigned N) const {
3116     assert(N == 2 && "Invalid number of operands!");
3117     Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
3118     Inst.addOperand(MCOperand::createImm(PostIdxReg.isAdd));
3119   }
3120 
3121   void addPostIdxRegShiftedOperands(MCInst &Inst, unsigned N) const {
3122     assert(N == 2 && "Invalid number of operands!");
3123     Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
3124     // The sign, shift type, and shift amount are encoded in a single operand
3125     // using the AM2 encoding helpers.
3126     ARM_AM::AddrOpc opc = PostIdxReg.isAdd ? ARM_AM::add : ARM_AM::sub;
3127     unsigned Imm = ARM_AM::getAM2Opc(opc, PostIdxReg.ShiftImm,
3128                                      PostIdxReg.ShiftTy);
3129     Inst.addOperand(MCOperand::createImm(Imm));
3130   }
3131 
3132   void addPowerTwoOperands(MCInst &Inst, unsigned N) const {
3133     assert(N == 1 && "Invalid number of operands!");
3134     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3135     Inst.addOperand(MCOperand::createImm(CE->getValue()));
3136   }
3137 
3138   void addMSRMaskOperands(MCInst &Inst, unsigned N) const {
3139     assert(N == 1 && "Invalid number of operands!");
3140     Inst.addOperand(MCOperand::createImm(unsigned(getMSRMask())));
3141   }
3142 
3143   void addBankedRegOperands(MCInst &Inst, unsigned N) const {
3144     assert(N == 1 && "Invalid number of operands!");
3145     Inst.addOperand(MCOperand::createImm(unsigned(getBankedReg())));
3146   }
3147 
3148   void addProcIFlagsOperands(MCInst &Inst, unsigned N) const {
3149     assert(N == 1 && "Invalid number of operands!");
3150     Inst.addOperand(MCOperand::createImm(unsigned(getProcIFlags())));
3151   }
3152 
3153   void addVecListOperands(MCInst &Inst, unsigned N) const {
3154     assert(N == 1 && "Invalid number of operands!");
3155     Inst.addOperand(MCOperand::createReg(VectorList.RegNum));
3156   }
3157 
3158   void addMVEVecListOperands(MCInst &Inst, unsigned N) const {
3159     assert(N == 1 && "Invalid number of operands!");
3160 
3161     // When we come here, the VectorList field will identify a range
3162     // of q-registers by its base register and length, and it will
3163     // have already been error-checked to be the expected length of
3164     // range and contain only q-regs in the range q0-q7. So we can
3165     // count on the base register being in the range q0-q6 (for 2
3166     // regs) or q0-q4 (for 4)
3167     //
3168     // The MVE instructions taking a register range of this kind will
3169     // need an operand in the QQPR or QQQQPR class, representing the
3170     // entire range as a unit. So we must translate into that class,
3171     // by finding the index of the base register in the MQPR reg
3172     // class, and returning the super-register at the corresponding
3173     // index in the target class.
3174 
3175     const MCRegisterClass *RC_in = &ARMMCRegisterClasses[ARM::MQPRRegClassID];
3176     const MCRegisterClass *RC_out = (VectorList.Count == 2) ?
3177       &ARMMCRegisterClasses[ARM::QQPRRegClassID] :
3178       &ARMMCRegisterClasses[ARM::QQQQPRRegClassID];
3179 
3180     unsigned I, E = RC_out->getNumRegs();
3181     for (I = 0; I < E; I++)
3182       if (RC_in->getRegister(I) == VectorList.RegNum)
3183         break;
3184     assert(I < E && "Invalid vector list start register!");
3185 
3186     Inst.addOperand(MCOperand::createReg(RC_out->getRegister(I)));
3187   }
3188 
3189   void addVecListIndexedOperands(MCInst &Inst, unsigned N) const {
3190     assert(N == 2 && "Invalid number of operands!");
3191     Inst.addOperand(MCOperand::createReg(VectorList.RegNum));
3192     Inst.addOperand(MCOperand::createImm(VectorList.LaneIndex));
3193   }
3194 
3195   void addVectorIndex8Operands(MCInst &Inst, unsigned N) const {
3196     assert(N == 1 && "Invalid number of operands!");
3197     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
3198   }
3199 
3200   void addVectorIndex16Operands(MCInst &Inst, unsigned N) const {
3201     assert(N == 1 && "Invalid number of operands!");
3202     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
3203   }
3204 
3205   void addVectorIndex32Operands(MCInst &Inst, unsigned N) const {
3206     assert(N == 1 && "Invalid number of operands!");
3207     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
3208   }
3209 
3210   void addVectorIndex64Operands(MCInst &Inst, unsigned N) const {
3211     assert(N == 1 && "Invalid number of operands!");
3212     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
3213   }
3214 
3215   void addMVEVectorIndexOperands(MCInst &Inst, unsigned N) const {
3216     assert(N == 1 && "Invalid number of operands!");
3217     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
3218   }
3219 
3220   void addMVEPairVectorIndexOperands(MCInst &Inst, unsigned N) const {
3221     assert(N == 1 && "Invalid number of operands!");
3222     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
3223   }
3224 
3225   void addNEONi8splatOperands(MCInst &Inst, unsigned N) const {
3226     assert(N == 1 && "Invalid number of operands!");
3227     // The immediate encodes the type of constant as well as the value.
3228     // Mask in that this is an i8 splat.
3229     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3230     Inst.addOperand(MCOperand::createImm(CE->getValue() | 0xe00));
3231   }
3232 
3233   void addNEONi16splatOperands(MCInst &Inst, unsigned N) const {
3234     assert(N == 1 && "Invalid number of operands!");
3235     // The immediate encodes the type of constant as well as the value.
3236     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3237     unsigned Value = CE->getValue();
3238     Value = ARM_AM::encodeNEONi16splat(Value);
3239     Inst.addOperand(MCOperand::createImm(Value));
3240   }
3241 
3242   void addNEONi16splatNotOperands(MCInst &Inst, unsigned N) const {
3243     assert(N == 1 && "Invalid number of operands!");
3244     // The immediate encodes the type of constant as well as the value.
3245     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3246     unsigned Value = CE->getValue();
3247     Value = ARM_AM::encodeNEONi16splat(~Value & 0xffff);
3248     Inst.addOperand(MCOperand::createImm(Value));
3249   }
3250 
3251   void addNEONi32splatOperands(MCInst &Inst, unsigned N) const {
3252     assert(N == 1 && "Invalid number of operands!");
3253     // The immediate encodes the type of constant as well as the value.
3254     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3255     unsigned Value = CE->getValue();
3256     Value = ARM_AM::encodeNEONi32splat(Value);
3257     Inst.addOperand(MCOperand::createImm(Value));
3258   }
3259 
3260   void addNEONi32splatNotOperands(MCInst &Inst, unsigned N) const {
3261     assert(N == 1 && "Invalid number of operands!");
3262     // The immediate encodes the type of constant as well as the value.
3263     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3264     unsigned Value = CE->getValue();
3265     Value = ARM_AM::encodeNEONi32splat(~Value);
3266     Inst.addOperand(MCOperand::createImm(Value));
3267   }
3268 
3269   void addNEONi8ReplicateOperands(MCInst &Inst, bool Inv) const {
3270     // The immediate encodes the type of constant as well as the value.
3271     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3272     assert((Inst.getOpcode() == ARM::VMOVv8i8 ||
3273             Inst.getOpcode() == ARM::VMOVv16i8) &&
3274           "All instructions that wants to replicate non-zero byte "
3275           "always must be replaced with VMOVv8i8 or VMOVv16i8.");
3276     unsigned Value = CE->getValue();
3277     if (Inv)
3278       Value = ~Value;
3279     unsigned B = Value & 0xff;
3280     B |= 0xe00; // cmode = 0b1110
3281     Inst.addOperand(MCOperand::createImm(B));
3282   }
3283 
3284   void addNEONinvi8ReplicateOperands(MCInst &Inst, unsigned N) const {
3285     assert(N == 1 && "Invalid number of operands!");
3286     addNEONi8ReplicateOperands(Inst, true);
3287   }
3288 
3289   static unsigned encodeNeonVMOVImmediate(unsigned Value) {
3290     if (Value >= 256 && Value <= 0xffff)
3291       Value = (Value >> 8) | ((Value & 0xff) ? 0xc00 : 0x200);
3292     else if (Value > 0xffff && Value <= 0xffffff)
3293       Value = (Value >> 16) | ((Value & 0xff) ? 0xd00 : 0x400);
3294     else if (Value > 0xffffff)
3295       Value = (Value >> 24) | 0x600;
3296     return Value;
3297   }
3298 
3299   void addNEONi32vmovOperands(MCInst &Inst, unsigned N) const {
3300     assert(N == 1 && "Invalid number of operands!");
3301     // The immediate encodes the type of constant as well as the value.
3302     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3303     unsigned Value = encodeNeonVMOVImmediate(CE->getValue());
3304     Inst.addOperand(MCOperand::createImm(Value));
3305   }
3306 
3307   void addNEONvmovi8ReplicateOperands(MCInst &Inst, unsigned N) const {
3308     assert(N == 1 && "Invalid number of operands!");
3309     addNEONi8ReplicateOperands(Inst, false);
3310   }
3311 
3312   void addNEONvmovi16ReplicateOperands(MCInst &Inst, unsigned N) const {
3313     assert(N == 1 && "Invalid number of operands!");
3314     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3315     assert((Inst.getOpcode() == ARM::VMOVv4i16 ||
3316             Inst.getOpcode() == ARM::VMOVv8i16 ||
3317             Inst.getOpcode() == ARM::VMVNv4i16 ||
3318             Inst.getOpcode() == ARM::VMVNv8i16) &&
3319           "All instructions that want to replicate non-zero half-word "
3320           "always must be replaced with V{MOV,MVN}v{4,8}i16.");
3321     uint64_t Value = CE->getValue();
3322     unsigned Elem = Value & 0xffff;
3323     if (Elem >= 256)
3324       Elem = (Elem >> 8) | 0x200;
3325     Inst.addOperand(MCOperand::createImm(Elem));
3326   }
3327 
3328   void addNEONi32vmovNegOperands(MCInst &Inst, unsigned N) const {
3329     assert(N == 1 && "Invalid number of operands!");
3330     // The immediate encodes the type of constant as well as the value.
3331     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3332     unsigned Value = encodeNeonVMOVImmediate(~CE->getValue());
3333     Inst.addOperand(MCOperand::createImm(Value));
3334   }
3335 
3336   void addNEONvmovi32ReplicateOperands(MCInst &Inst, unsigned N) const {
3337     assert(N == 1 && "Invalid number of operands!");
3338     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3339     assert((Inst.getOpcode() == ARM::VMOVv2i32 ||
3340             Inst.getOpcode() == ARM::VMOVv4i32 ||
3341             Inst.getOpcode() == ARM::VMVNv2i32 ||
3342             Inst.getOpcode() == ARM::VMVNv4i32) &&
3343           "All instructions that want to replicate non-zero word "
3344           "always must be replaced with V{MOV,MVN}v{2,4}i32.");
3345     uint64_t Value = CE->getValue();
3346     unsigned Elem = encodeNeonVMOVImmediate(Value & 0xffffffff);
3347     Inst.addOperand(MCOperand::createImm(Elem));
3348   }
3349 
3350   void addNEONi64splatOperands(MCInst &Inst, unsigned N) const {
3351     assert(N == 1 && "Invalid number of operands!");
3352     // The immediate encodes the type of constant as well as the value.
3353     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3354     uint64_t Value = CE->getValue();
3355     unsigned Imm = 0;
3356     for (unsigned i = 0; i < 8; ++i, Value >>= 8) {
3357       Imm |= (Value & 1) << i;
3358     }
3359     Inst.addOperand(MCOperand::createImm(Imm | 0x1e00));
3360   }
3361 
3362   void addComplexRotationEvenOperands(MCInst &Inst, unsigned N) const {
3363     assert(N == 1 && "Invalid number of operands!");
3364     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3365     Inst.addOperand(MCOperand::createImm(CE->getValue() / 90));
3366   }
3367 
3368   void addComplexRotationOddOperands(MCInst &Inst, unsigned N) const {
3369     assert(N == 1 && "Invalid number of operands!");
3370     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3371     Inst.addOperand(MCOperand::createImm((CE->getValue() - 90) / 180));
3372   }
3373 
3374   void addMveSaturateOperands(MCInst &Inst, unsigned N) const {
3375     assert(N == 1 && "Invalid number of operands!");
3376     const MCConstantExpr *CE = cast<MCConstantExpr>(getImm());
3377     unsigned Imm = CE->getValue();
3378     assert((Imm == 48 || Imm == 64) && "Invalid saturate operand");
3379     Inst.addOperand(MCOperand::createImm(Imm == 48 ? 1 : 0));
3380   }
3381 
3382   void print(raw_ostream &OS) const override;
3383 
3384   static std::unique_ptr<ARMOperand> CreateITMask(unsigned Mask, SMLoc S) {
3385     auto Op = std::make_unique<ARMOperand>(k_ITCondMask);
3386     Op->ITMask.Mask = Mask;
3387     Op->StartLoc = S;
3388     Op->EndLoc = S;
3389     return Op;
3390   }
3391 
3392   static std::unique_ptr<ARMOperand> CreateCondCode(ARMCC::CondCodes CC,
3393                                                     SMLoc S) {
3394     auto Op = std::make_unique<ARMOperand>(k_CondCode);
3395     Op->CC.Val = CC;
3396     Op->StartLoc = S;
3397     Op->EndLoc = S;
3398     return Op;
3399   }
3400 
3401   static std::unique_ptr<ARMOperand> CreateVPTPred(ARMVCC::VPTCodes CC,
3402                                                    SMLoc S) {
3403     auto Op = std::make_unique<ARMOperand>(k_VPTPred);
3404     Op->VCC.Val = CC;
3405     Op->StartLoc = S;
3406     Op->EndLoc = S;
3407     return Op;
3408   }
3409 
3410   static std::unique_ptr<ARMOperand> CreateCoprocNum(unsigned CopVal, SMLoc S) {
3411     auto Op = std::make_unique<ARMOperand>(k_CoprocNum);
3412     Op->Cop.Val = CopVal;
3413     Op->StartLoc = S;
3414     Op->EndLoc = S;
3415     return Op;
3416   }
3417 
3418   static std::unique_ptr<ARMOperand> CreateCoprocReg(unsigned CopVal, SMLoc S) {
3419     auto Op = std::make_unique<ARMOperand>(k_CoprocReg);
3420     Op->Cop.Val = CopVal;
3421     Op->StartLoc = S;
3422     Op->EndLoc = S;
3423     return Op;
3424   }
3425 
3426   static std::unique_ptr<ARMOperand> CreateCoprocOption(unsigned Val, SMLoc S,
3427                                                         SMLoc E) {
3428     auto Op = std::make_unique<ARMOperand>(k_CoprocOption);
3429     Op->Cop.Val = Val;
3430     Op->StartLoc = S;
3431     Op->EndLoc = E;
3432     return Op;
3433   }
3434 
3435   static std::unique_ptr<ARMOperand> CreateCCOut(unsigned RegNum, SMLoc S) {
3436     auto Op = std::make_unique<ARMOperand>(k_CCOut);
3437     Op->Reg.RegNum = RegNum;
3438     Op->StartLoc = S;
3439     Op->EndLoc = S;
3440     return Op;
3441   }
3442 
3443   static std::unique_ptr<ARMOperand> CreateToken(StringRef Str, SMLoc S) {
3444     auto Op = std::make_unique<ARMOperand>(k_Token);
3445     Op->Tok.Data = Str.data();
3446     Op->Tok.Length = Str.size();
3447     Op->StartLoc = S;
3448     Op->EndLoc = S;
3449     return Op;
3450   }
3451 
3452   static std::unique_ptr<ARMOperand> CreateReg(unsigned RegNum, SMLoc S,
3453                                                SMLoc E) {
3454     auto Op = std::make_unique<ARMOperand>(k_Register);
3455     Op->Reg.RegNum = RegNum;
3456     Op->StartLoc = S;
3457     Op->EndLoc = E;
3458     return Op;
3459   }
3460 
3461   static std::unique_ptr<ARMOperand>
3462   CreateShiftedRegister(ARM_AM::ShiftOpc ShTy, unsigned SrcReg,
3463                         unsigned ShiftReg, unsigned ShiftImm, SMLoc S,
3464                         SMLoc E) {
3465     auto Op = std::make_unique<ARMOperand>(k_ShiftedRegister);
3466     Op->RegShiftedReg.ShiftTy = ShTy;
3467     Op->RegShiftedReg.SrcReg = SrcReg;
3468     Op->RegShiftedReg.ShiftReg = ShiftReg;
3469     Op->RegShiftedReg.ShiftImm = ShiftImm;
3470     Op->StartLoc = S;
3471     Op->EndLoc = E;
3472     return Op;
3473   }
3474 
3475   static std::unique_ptr<ARMOperand>
3476   CreateShiftedImmediate(ARM_AM::ShiftOpc ShTy, unsigned SrcReg,
3477                          unsigned ShiftImm, SMLoc S, SMLoc E) {
3478     auto Op = std::make_unique<ARMOperand>(k_ShiftedImmediate);
3479     Op->RegShiftedImm.ShiftTy = ShTy;
3480     Op->RegShiftedImm.SrcReg = SrcReg;
3481     Op->RegShiftedImm.ShiftImm = ShiftImm;
3482     Op->StartLoc = S;
3483     Op->EndLoc = E;
3484     return Op;
3485   }
3486 
3487   static std::unique_ptr<ARMOperand> CreateShifterImm(bool isASR, unsigned Imm,
3488                                                       SMLoc S, SMLoc E) {
3489     auto Op = std::make_unique<ARMOperand>(k_ShifterImmediate);
3490     Op->ShifterImm.isASR = isASR;
3491     Op->ShifterImm.Imm = Imm;
3492     Op->StartLoc = S;
3493     Op->EndLoc = E;
3494     return Op;
3495   }
3496 
3497   static std::unique_ptr<ARMOperand> CreateRotImm(unsigned Imm, SMLoc S,
3498                                                   SMLoc E) {
3499     auto Op = std::make_unique<ARMOperand>(k_RotateImmediate);
3500     Op->RotImm.Imm = Imm;
3501     Op->StartLoc = S;
3502     Op->EndLoc = E;
3503     return Op;
3504   }
3505 
3506   static std::unique_ptr<ARMOperand> CreateModImm(unsigned Bits, unsigned Rot,
3507                                                   SMLoc S, SMLoc E) {
3508     auto Op = std::make_unique<ARMOperand>(k_ModifiedImmediate);
3509     Op->ModImm.Bits = Bits;
3510     Op->ModImm.Rot = Rot;
3511     Op->StartLoc = S;
3512     Op->EndLoc = E;
3513     return Op;
3514   }
3515 
3516   static std::unique_ptr<ARMOperand>
3517   CreateConstantPoolImm(const MCExpr *Val, SMLoc S, SMLoc E) {
3518     auto Op = std::make_unique<ARMOperand>(k_ConstantPoolImmediate);
3519     Op->Imm.Val = Val;
3520     Op->StartLoc = S;
3521     Op->EndLoc = E;
3522     return Op;
3523   }
3524 
3525   static std::unique_ptr<ARMOperand>
3526   CreateBitfield(unsigned LSB, unsigned Width, SMLoc S, SMLoc E) {
3527     auto Op = std::make_unique<ARMOperand>(k_BitfieldDescriptor);
3528     Op->Bitfield.LSB = LSB;
3529     Op->Bitfield.Width = Width;
3530     Op->StartLoc = S;
3531     Op->EndLoc = E;
3532     return Op;
3533   }
3534 
3535   static std::unique_ptr<ARMOperand>
3536   CreateRegList(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs,
3537                 SMLoc StartLoc, SMLoc EndLoc) {
3538     assert(Regs.size() > 0 && "RegList contains no registers?");
3539     KindTy Kind = k_RegisterList;
3540 
3541     if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(
3542             Regs.front().second)) {
3543       if (Regs.back().second == ARM::VPR)
3544         Kind = k_FPDRegisterListWithVPR;
3545       else
3546         Kind = k_DPRRegisterList;
3547     } else if (ARMMCRegisterClasses[ARM::SPRRegClassID].contains(
3548                    Regs.front().second)) {
3549       if (Regs.back().second == ARM::VPR)
3550         Kind = k_FPSRegisterListWithVPR;
3551       else
3552         Kind = k_SPRRegisterList;
3553     }
3554 
3555     if (Kind == k_RegisterList && Regs.back().second == ARM::APSR)
3556       Kind = k_RegisterListWithAPSR;
3557 
3558     assert(std::is_sorted(Regs.begin(), Regs.end()) &&
3559            "Register list must be sorted by encoding");
3560 
3561     auto Op = std::make_unique<ARMOperand>(Kind);
3562     for (const auto &P : Regs)
3563       Op->Registers.push_back(P.second);
3564 
3565     Op->StartLoc = StartLoc;
3566     Op->EndLoc = EndLoc;
3567     return Op;
3568   }
3569 
3570   static std::unique_ptr<ARMOperand> CreateVectorList(unsigned RegNum,
3571                                                       unsigned Count,
3572                                                       bool isDoubleSpaced,
3573                                                       SMLoc S, SMLoc E) {
3574     auto Op = std::make_unique<ARMOperand>(k_VectorList);
3575     Op->VectorList.RegNum = RegNum;
3576     Op->VectorList.Count = Count;
3577     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
3578     Op->StartLoc = S;
3579     Op->EndLoc = E;
3580     return Op;
3581   }
3582 
3583   static std::unique_ptr<ARMOperand>
3584   CreateVectorListAllLanes(unsigned RegNum, unsigned Count, bool isDoubleSpaced,
3585                            SMLoc S, SMLoc E) {
3586     auto Op = std::make_unique<ARMOperand>(k_VectorListAllLanes);
3587     Op->VectorList.RegNum = RegNum;
3588     Op->VectorList.Count = Count;
3589     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
3590     Op->StartLoc = S;
3591     Op->EndLoc = E;
3592     return Op;
3593   }
3594 
3595   static std::unique_ptr<ARMOperand>
3596   CreateVectorListIndexed(unsigned RegNum, unsigned Count, unsigned Index,
3597                           bool isDoubleSpaced, SMLoc S, SMLoc E) {
3598     auto Op = std::make_unique<ARMOperand>(k_VectorListIndexed);
3599     Op->VectorList.RegNum = RegNum;
3600     Op->VectorList.Count = Count;
3601     Op->VectorList.LaneIndex = Index;
3602     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
3603     Op->StartLoc = S;
3604     Op->EndLoc = E;
3605     return Op;
3606   }
3607 
3608   static std::unique_ptr<ARMOperand>
3609   CreateVectorIndex(unsigned Idx, SMLoc S, SMLoc E, MCContext &Ctx) {
3610     auto Op = std::make_unique<ARMOperand>(k_VectorIndex);
3611     Op->VectorIndex.Val = Idx;
3612     Op->StartLoc = S;
3613     Op->EndLoc = E;
3614     return Op;
3615   }
3616 
3617   static std::unique_ptr<ARMOperand> CreateImm(const MCExpr *Val, SMLoc S,
3618                                                SMLoc E) {
3619     auto Op = std::make_unique<ARMOperand>(k_Immediate);
3620     Op->Imm.Val = Val;
3621     Op->StartLoc = S;
3622     Op->EndLoc = E;
3623     return Op;
3624   }
3625 
3626   static std::unique_ptr<ARMOperand>
3627   CreateMem(unsigned BaseRegNum, const MCConstantExpr *OffsetImm,
3628             unsigned OffsetRegNum, ARM_AM::ShiftOpc ShiftType,
3629             unsigned ShiftImm, unsigned Alignment, bool isNegative, SMLoc S,
3630             SMLoc E, SMLoc AlignmentLoc = SMLoc()) {
3631     auto Op = std::make_unique<ARMOperand>(k_Memory);
3632     Op->Memory.BaseRegNum = BaseRegNum;
3633     Op->Memory.OffsetImm = OffsetImm;
3634     Op->Memory.OffsetRegNum = OffsetRegNum;
3635     Op->Memory.ShiftType = ShiftType;
3636     Op->Memory.ShiftImm = ShiftImm;
3637     Op->Memory.Alignment = Alignment;
3638     Op->Memory.isNegative = isNegative;
3639     Op->StartLoc = S;
3640     Op->EndLoc = E;
3641     Op->AlignmentLoc = AlignmentLoc;
3642     return Op;
3643   }
3644 
3645   static std::unique_ptr<ARMOperand>
3646   CreatePostIdxReg(unsigned RegNum, bool isAdd, ARM_AM::ShiftOpc ShiftTy,
3647                    unsigned ShiftImm, SMLoc S, SMLoc E) {
3648     auto Op = std::make_unique<ARMOperand>(k_PostIndexRegister);
3649     Op->PostIdxReg.RegNum = RegNum;
3650     Op->PostIdxReg.isAdd = isAdd;
3651     Op->PostIdxReg.ShiftTy = ShiftTy;
3652     Op->PostIdxReg.ShiftImm = ShiftImm;
3653     Op->StartLoc = S;
3654     Op->EndLoc = E;
3655     return Op;
3656   }
3657 
3658   static std::unique_ptr<ARMOperand> CreateMemBarrierOpt(ARM_MB::MemBOpt Opt,
3659                                                          SMLoc S) {
3660     auto Op = std::make_unique<ARMOperand>(k_MemBarrierOpt);
3661     Op->MBOpt.Val = Opt;
3662     Op->StartLoc = S;
3663     Op->EndLoc = S;
3664     return Op;
3665   }
3666 
3667   static std::unique_ptr<ARMOperand>
3668   CreateInstSyncBarrierOpt(ARM_ISB::InstSyncBOpt Opt, SMLoc S) {
3669     auto Op = std::make_unique<ARMOperand>(k_InstSyncBarrierOpt);
3670     Op->ISBOpt.Val = Opt;
3671     Op->StartLoc = S;
3672     Op->EndLoc = S;
3673     return Op;
3674   }
3675 
3676   static std::unique_ptr<ARMOperand>
3677   CreateTraceSyncBarrierOpt(ARM_TSB::TraceSyncBOpt Opt, SMLoc S) {
3678     auto Op = std::make_unique<ARMOperand>(k_TraceSyncBarrierOpt);
3679     Op->TSBOpt.Val = Opt;
3680     Op->StartLoc = S;
3681     Op->EndLoc = S;
3682     return Op;
3683   }
3684 
3685   static std::unique_ptr<ARMOperand> CreateProcIFlags(ARM_PROC::IFlags IFlags,
3686                                                       SMLoc S) {
3687     auto Op = std::make_unique<ARMOperand>(k_ProcIFlags);
3688     Op->IFlags.Val = IFlags;
3689     Op->StartLoc = S;
3690     Op->EndLoc = S;
3691     return Op;
3692   }
3693 
3694   static std::unique_ptr<ARMOperand> CreateMSRMask(unsigned MMask, SMLoc S) {
3695     auto Op = std::make_unique<ARMOperand>(k_MSRMask);
3696     Op->MMask.Val = MMask;
3697     Op->StartLoc = S;
3698     Op->EndLoc = S;
3699     return Op;
3700   }
3701 
3702   static std::unique_ptr<ARMOperand> CreateBankedReg(unsigned Reg, SMLoc S) {
3703     auto Op = std::make_unique<ARMOperand>(k_BankedReg);
3704     Op->BankedReg.Val = Reg;
3705     Op->StartLoc = S;
3706     Op->EndLoc = S;
3707     return Op;
3708   }
3709 };
3710 
3711 } // end anonymous namespace.
3712 
3713 void ARMOperand::print(raw_ostream &OS) const {
3714   auto RegName = [](unsigned Reg) {
3715     if (Reg)
3716       return ARMInstPrinter::getRegisterName(Reg);
3717     else
3718       return "noreg";
3719   };
3720 
3721   switch (Kind) {
3722   case k_CondCode:
3723     OS << "<ARMCC::" << ARMCondCodeToString(getCondCode()) << ">";
3724     break;
3725   case k_VPTPred:
3726     OS << "<ARMVCC::" << ARMVPTPredToString(getVPTPred()) << ">";
3727     break;
3728   case k_CCOut:
3729     OS << "<ccout " << RegName(getReg()) << ">";
3730     break;
3731   case k_ITCondMask: {
3732     static const char *const MaskStr[] = {
3733       "(invalid)", "(tttt)", "(ttt)", "(ttte)",
3734       "(tt)",      "(ttet)", "(tte)", "(ttee)",
3735       "(t)",       "(tett)", "(tet)", "(tete)",
3736       "(te)",      "(teet)", "(tee)", "(teee)",
3737     };
3738     assert((ITMask.Mask & 0xf) == ITMask.Mask);
3739     OS << "<it-mask " << MaskStr[ITMask.Mask] << ">";
3740     break;
3741   }
3742   case k_CoprocNum:
3743     OS << "<coprocessor number: " << getCoproc() << ">";
3744     break;
3745   case k_CoprocReg:
3746     OS << "<coprocessor register: " << getCoproc() << ">";
3747     break;
3748   case k_CoprocOption:
3749     OS << "<coprocessor option: " << CoprocOption.Val << ">";
3750     break;
3751   case k_MSRMask:
3752     OS << "<mask: " << getMSRMask() << ">";
3753     break;
3754   case k_BankedReg:
3755     OS << "<banked reg: " << getBankedReg() << ">";
3756     break;
3757   case k_Immediate:
3758     OS << *getImm();
3759     break;
3760   case k_MemBarrierOpt:
3761     OS << "<ARM_MB::" << MemBOptToString(getMemBarrierOpt(), false) << ">";
3762     break;
3763   case k_InstSyncBarrierOpt:
3764     OS << "<ARM_ISB::" << InstSyncBOptToString(getInstSyncBarrierOpt()) << ">";
3765     break;
3766   case k_TraceSyncBarrierOpt:
3767     OS << "<ARM_TSB::" << TraceSyncBOptToString(getTraceSyncBarrierOpt()) << ">";
3768     break;
3769   case k_Memory:
3770     OS << "<memory";
3771     if (Memory.BaseRegNum)
3772       OS << " base:" << RegName(Memory.BaseRegNum);
3773     if (Memory.OffsetImm)
3774       OS << " offset-imm:" << *Memory.OffsetImm;
3775     if (Memory.OffsetRegNum)
3776       OS << " offset-reg:" << (Memory.isNegative ? "-" : "")
3777          << RegName(Memory.OffsetRegNum);
3778     if (Memory.ShiftType != ARM_AM::no_shift) {
3779       OS << " shift-type:" << ARM_AM::getShiftOpcStr(Memory.ShiftType);
3780       OS << " shift-imm:" << Memory.ShiftImm;
3781     }
3782     if (Memory.Alignment)
3783       OS << " alignment:" << Memory.Alignment;
3784     OS << ">";
3785     break;
3786   case k_PostIndexRegister:
3787     OS << "post-idx register " << (PostIdxReg.isAdd ? "" : "-")
3788        << RegName(PostIdxReg.RegNum);
3789     if (PostIdxReg.ShiftTy != ARM_AM::no_shift)
3790       OS << ARM_AM::getShiftOpcStr(PostIdxReg.ShiftTy) << " "
3791          << PostIdxReg.ShiftImm;
3792     OS << ">";
3793     break;
3794   case k_ProcIFlags: {
3795     OS << "<ARM_PROC::";
3796     unsigned IFlags = getProcIFlags();
3797     for (int i=2; i >= 0; --i)
3798       if (IFlags & (1 << i))
3799         OS << ARM_PROC::IFlagsToString(1 << i);
3800     OS << ">";
3801     break;
3802   }
3803   case k_Register:
3804     OS << "<register " << RegName(getReg()) << ">";
3805     break;
3806   case k_ShifterImmediate:
3807     OS << "<shift " << (ShifterImm.isASR ? "asr" : "lsl")
3808        << " #" << ShifterImm.Imm << ">";
3809     break;
3810   case k_ShiftedRegister:
3811     OS << "<so_reg_reg " << RegName(RegShiftedReg.SrcReg) << " "
3812        << ARM_AM::getShiftOpcStr(RegShiftedReg.ShiftTy) << " "
3813        << RegName(RegShiftedReg.ShiftReg) << ">";
3814     break;
3815   case k_ShiftedImmediate:
3816     OS << "<so_reg_imm " << RegName(RegShiftedImm.SrcReg) << " "
3817        << ARM_AM::getShiftOpcStr(RegShiftedImm.ShiftTy) << " #"
3818        << RegShiftedImm.ShiftImm << ">";
3819     break;
3820   case k_RotateImmediate:
3821     OS << "<ror " << " #" << (RotImm.Imm * 8) << ">";
3822     break;
3823   case k_ModifiedImmediate:
3824     OS << "<mod_imm #" << ModImm.Bits << ", #"
3825        <<  ModImm.Rot << ")>";
3826     break;
3827   case k_ConstantPoolImmediate:
3828     OS << "<constant_pool_imm #" << *getConstantPoolImm();
3829     break;
3830   case k_BitfieldDescriptor:
3831     OS << "<bitfield " << "lsb: " << Bitfield.LSB
3832        << ", width: " << Bitfield.Width << ">";
3833     break;
3834   case k_RegisterList:
3835   case k_RegisterListWithAPSR:
3836   case k_DPRRegisterList:
3837   case k_SPRRegisterList:
3838   case k_FPSRegisterListWithVPR:
3839   case k_FPDRegisterListWithVPR: {
3840     OS << "<register_list ";
3841 
3842     const SmallVectorImpl<unsigned> &RegList = getRegList();
3843     for (SmallVectorImpl<unsigned>::const_iterator
3844            I = RegList.begin(), E = RegList.end(); I != E; ) {
3845       OS << RegName(*I);
3846       if (++I < E) OS << ", ";
3847     }
3848 
3849     OS << ">";
3850     break;
3851   }
3852   case k_VectorList:
3853     OS << "<vector_list " << VectorList.Count << " * "
3854        << RegName(VectorList.RegNum) << ">";
3855     break;
3856   case k_VectorListAllLanes:
3857     OS << "<vector_list(all lanes) " << VectorList.Count << " * "
3858        << RegName(VectorList.RegNum) << ">";
3859     break;
3860   case k_VectorListIndexed:
3861     OS << "<vector_list(lane " << VectorList.LaneIndex << ") "
3862        << VectorList.Count << " * " << RegName(VectorList.RegNum) << ">";
3863     break;
3864   case k_Token:
3865     OS << "'" << getToken() << "'";
3866     break;
3867   case k_VectorIndex:
3868     OS << "<vectorindex " << getVectorIndex() << ">";
3869     break;
3870   }
3871 }
3872 
3873 /// @name Auto-generated Match Functions
3874 /// {
3875 
3876 static unsigned MatchRegisterName(StringRef Name);
3877 
3878 /// }
3879 
3880 bool ARMAsmParser::ParseRegister(unsigned &RegNo,
3881                                  SMLoc &StartLoc, SMLoc &EndLoc) {
3882   const AsmToken &Tok = getParser().getTok();
3883   StartLoc = Tok.getLoc();
3884   EndLoc = Tok.getEndLoc();
3885   RegNo = tryParseRegister();
3886 
3887   return (RegNo == (unsigned)-1);
3888 }
3889 
3890 OperandMatchResultTy ARMAsmParser::tryParseRegister(unsigned &RegNo,
3891                                                     SMLoc &StartLoc,
3892                                                     SMLoc &EndLoc) {
3893   if (ParseRegister(RegNo, StartLoc, EndLoc))
3894     return MatchOperand_NoMatch;
3895   return MatchOperand_Success;
3896 }
3897 
3898 /// Try to parse a register name.  The token must be an Identifier when called,
3899 /// and if it is a register name the token is eaten and the register number is
3900 /// returned.  Otherwise return -1.
3901 int ARMAsmParser::tryParseRegister() {
3902   MCAsmParser &Parser = getParser();
3903   const AsmToken &Tok = Parser.getTok();
3904   if (Tok.isNot(AsmToken::Identifier)) return -1;
3905 
3906   std::string lowerCase = Tok.getString().lower();
3907   unsigned RegNum = MatchRegisterName(lowerCase);
3908   if (!RegNum) {
3909     RegNum = StringSwitch<unsigned>(lowerCase)
3910       .Case("r13", ARM::SP)
3911       .Case("r14", ARM::LR)
3912       .Case("r15", ARM::PC)
3913       .Case("ip", ARM::R12)
3914       // Additional register name aliases for 'gas' compatibility.
3915       .Case("a1", ARM::R0)
3916       .Case("a2", ARM::R1)
3917       .Case("a3", ARM::R2)
3918       .Case("a4", ARM::R3)
3919       .Case("v1", ARM::R4)
3920       .Case("v2", ARM::R5)
3921       .Case("v3", ARM::R6)
3922       .Case("v4", ARM::R7)
3923       .Case("v5", ARM::R8)
3924       .Case("v6", ARM::R9)
3925       .Case("v7", ARM::R10)
3926       .Case("v8", ARM::R11)
3927       .Case("sb", ARM::R9)
3928       .Case("sl", ARM::R10)
3929       .Case("fp", ARM::R11)
3930       .Default(0);
3931   }
3932   if (!RegNum) {
3933     // Check for aliases registered via .req. Canonicalize to lower case.
3934     // That's more consistent since register names are case insensitive, and
3935     // it's how the original entry was passed in from MC/MCParser/AsmParser.
3936     StringMap<unsigned>::const_iterator Entry = RegisterReqs.find(lowerCase);
3937     // If no match, return failure.
3938     if (Entry == RegisterReqs.end())
3939       return -1;
3940     Parser.Lex(); // Eat identifier token.
3941     return Entry->getValue();
3942   }
3943 
3944   // Some FPUs only have 16 D registers, so D16-D31 are invalid
3945   if (!hasD32() && RegNum >= ARM::D16 && RegNum <= ARM::D31)
3946     return -1;
3947 
3948   Parser.Lex(); // Eat identifier token.
3949 
3950   return RegNum;
3951 }
3952 
3953 // Try to parse a shifter  (e.g., "lsl <amt>"). On success, return 0.
3954 // If a recoverable error occurs, return 1. If an irrecoverable error
3955 // occurs, return -1. An irrecoverable error is one where tokens have been
3956 // consumed in the process of trying to parse the shifter (i.e., when it is
3957 // indeed a shifter operand, but malformed).
3958 int ARMAsmParser::tryParseShiftRegister(OperandVector &Operands) {
3959   MCAsmParser &Parser = getParser();
3960   SMLoc S = Parser.getTok().getLoc();
3961   const AsmToken &Tok = Parser.getTok();
3962   if (Tok.isNot(AsmToken::Identifier))
3963     return -1;
3964 
3965   std::string lowerCase = Tok.getString().lower();
3966   ARM_AM::ShiftOpc ShiftTy = StringSwitch<ARM_AM::ShiftOpc>(lowerCase)
3967       .Case("asl", ARM_AM::lsl)
3968       .Case("lsl", ARM_AM::lsl)
3969       .Case("lsr", ARM_AM::lsr)
3970       .Case("asr", ARM_AM::asr)
3971       .Case("ror", ARM_AM::ror)
3972       .Case("rrx", ARM_AM::rrx)
3973       .Default(ARM_AM::no_shift);
3974 
3975   if (ShiftTy == ARM_AM::no_shift)
3976     return 1;
3977 
3978   Parser.Lex(); // Eat the operator.
3979 
3980   // The source register for the shift has already been added to the
3981   // operand list, so we need to pop it off and combine it into the shifted
3982   // register operand instead.
3983   std::unique_ptr<ARMOperand> PrevOp(
3984       (ARMOperand *)Operands.pop_back_val().release());
3985   if (!PrevOp->isReg())
3986     return Error(PrevOp->getStartLoc(), "shift must be of a register");
3987   int SrcReg = PrevOp->getReg();
3988 
3989   SMLoc EndLoc;
3990   int64_t Imm = 0;
3991   int ShiftReg = 0;
3992   if (ShiftTy == ARM_AM::rrx) {
3993     // RRX Doesn't have an explicit shift amount. The encoder expects
3994     // the shift register to be the same as the source register. Seems odd,
3995     // but OK.
3996     ShiftReg = SrcReg;
3997   } else {
3998     // Figure out if this is shifted by a constant or a register (for non-RRX).
3999     if (Parser.getTok().is(AsmToken::Hash) ||
4000         Parser.getTok().is(AsmToken::Dollar)) {
4001       Parser.Lex(); // Eat hash.
4002       SMLoc ImmLoc = Parser.getTok().getLoc();
4003       const MCExpr *ShiftExpr = nullptr;
4004       if (getParser().parseExpression(ShiftExpr, EndLoc)) {
4005         Error(ImmLoc, "invalid immediate shift value");
4006         return -1;
4007       }
4008       // The expression must be evaluatable as an immediate.
4009       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftExpr);
4010       if (!CE) {
4011         Error(ImmLoc, "invalid immediate shift value");
4012         return -1;
4013       }
4014       // Range check the immediate.
4015       // lsl, ror: 0 <= imm <= 31
4016       // lsr, asr: 0 <= imm <= 32
4017       Imm = CE->getValue();
4018       if (Imm < 0 ||
4019           ((ShiftTy == ARM_AM::lsl || ShiftTy == ARM_AM::ror) && Imm > 31) ||
4020           ((ShiftTy == ARM_AM::lsr || ShiftTy == ARM_AM::asr) && Imm > 32)) {
4021         Error(ImmLoc, "immediate shift value out of range");
4022         return -1;
4023       }
4024       // shift by zero is a nop. Always send it through as lsl.
4025       // ('as' compatibility)
4026       if (Imm == 0)
4027         ShiftTy = ARM_AM::lsl;
4028     } else if (Parser.getTok().is(AsmToken::Identifier)) {
4029       SMLoc L = Parser.getTok().getLoc();
4030       EndLoc = Parser.getTok().getEndLoc();
4031       ShiftReg = tryParseRegister();
4032       if (ShiftReg == -1) {
4033         Error(L, "expected immediate or register in shift operand");
4034         return -1;
4035       }
4036     } else {
4037       Error(Parser.getTok().getLoc(),
4038             "expected immediate or register in shift operand");
4039       return -1;
4040     }
4041   }
4042 
4043   if (ShiftReg && ShiftTy != ARM_AM::rrx)
4044     Operands.push_back(ARMOperand::CreateShiftedRegister(ShiftTy, SrcReg,
4045                                                          ShiftReg, Imm,
4046                                                          S, EndLoc));
4047   else
4048     Operands.push_back(ARMOperand::CreateShiftedImmediate(ShiftTy, SrcReg, Imm,
4049                                                           S, EndLoc));
4050 
4051   return 0;
4052 }
4053 
4054 /// Try to parse a register name.  The token must be an Identifier when called.
4055 /// If it's a register, an AsmOperand is created. Another AsmOperand is created
4056 /// if there is a "writeback". 'true' if it's not a register.
4057 ///
4058 /// TODO this is likely to change to allow different register types and or to
4059 /// parse for a specific register type.
4060 bool ARMAsmParser::tryParseRegisterWithWriteBack(OperandVector &Operands) {
4061   MCAsmParser &Parser = getParser();
4062   SMLoc RegStartLoc = Parser.getTok().getLoc();
4063   SMLoc RegEndLoc = Parser.getTok().getEndLoc();
4064   int RegNo = tryParseRegister();
4065   if (RegNo == -1)
4066     return true;
4067 
4068   Operands.push_back(ARMOperand::CreateReg(RegNo, RegStartLoc, RegEndLoc));
4069 
4070   const AsmToken &ExclaimTok = Parser.getTok();
4071   if (ExclaimTok.is(AsmToken::Exclaim)) {
4072     Operands.push_back(ARMOperand::CreateToken(ExclaimTok.getString(),
4073                                                ExclaimTok.getLoc()));
4074     Parser.Lex(); // Eat exclaim token
4075     return false;
4076   }
4077 
4078   // Also check for an index operand. This is only legal for vector registers,
4079   // but that'll get caught OK in operand matching, so we don't need to
4080   // explicitly filter everything else out here.
4081   if (Parser.getTok().is(AsmToken::LBrac)) {
4082     SMLoc SIdx = Parser.getTok().getLoc();
4083     Parser.Lex(); // Eat left bracket token.
4084 
4085     const MCExpr *ImmVal;
4086     if (getParser().parseExpression(ImmVal))
4087       return true;
4088     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(ImmVal);
4089     if (!MCE)
4090       return TokError("immediate value expected for vector index");
4091 
4092     if (Parser.getTok().isNot(AsmToken::RBrac))
4093       return Error(Parser.getTok().getLoc(), "']' expected");
4094 
4095     SMLoc E = Parser.getTok().getEndLoc();
4096     Parser.Lex(); // Eat right bracket token.
4097 
4098     Operands.push_back(ARMOperand::CreateVectorIndex(MCE->getValue(),
4099                                                      SIdx, E,
4100                                                      getContext()));
4101   }
4102 
4103   return false;
4104 }
4105 
4106 /// MatchCoprocessorOperandName - Try to parse an coprocessor related
4107 /// instruction with a symbolic operand name.
4108 /// We accept "crN" syntax for GAS compatibility.
4109 /// <operand-name> ::= <prefix><number>
4110 /// If CoprocOp is 'c', then:
4111 ///   <prefix> ::= c | cr
4112 /// If CoprocOp is 'p', then :
4113 ///   <prefix> ::= p
4114 /// <number> ::= integer in range [0, 15]
4115 static int MatchCoprocessorOperandName(StringRef Name, char CoprocOp) {
4116   // Use the same layout as the tablegen'erated register name matcher. Ugly,
4117   // but efficient.
4118   if (Name.size() < 2 || Name[0] != CoprocOp)
4119     return -1;
4120   Name = (Name[1] == 'r') ? Name.drop_front(2) : Name.drop_front();
4121 
4122   switch (Name.size()) {
4123   default: return -1;
4124   case 1:
4125     switch (Name[0]) {
4126     default:  return -1;
4127     case '0': return 0;
4128     case '1': return 1;
4129     case '2': return 2;
4130     case '3': return 3;
4131     case '4': return 4;
4132     case '5': return 5;
4133     case '6': return 6;
4134     case '7': return 7;
4135     case '8': return 8;
4136     case '9': return 9;
4137     }
4138   case 2:
4139     if (Name[0] != '1')
4140       return -1;
4141     switch (Name[1]) {
4142     default:  return -1;
4143     // CP10 and CP11 are VFP/NEON and so vector instructions should be used.
4144     // However, old cores (v5/v6) did use them in that way.
4145     case '0': return 10;
4146     case '1': return 11;
4147     case '2': return 12;
4148     case '3': return 13;
4149     case '4': return 14;
4150     case '5': return 15;
4151     }
4152   }
4153 }
4154 
4155 /// parseITCondCode - Try to parse a condition code for an IT instruction.
4156 OperandMatchResultTy
4157 ARMAsmParser::parseITCondCode(OperandVector &Operands) {
4158   MCAsmParser &Parser = getParser();
4159   SMLoc S = Parser.getTok().getLoc();
4160   const AsmToken &Tok = Parser.getTok();
4161   if (!Tok.is(AsmToken::Identifier))
4162     return MatchOperand_NoMatch;
4163   unsigned CC = ARMCondCodeFromString(Tok.getString());
4164   if (CC == ~0U)
4165     return MatchOperand_NoMatch;
4166   Parser.Lex(); // Eat the token.
4167 
4168   Operands.push_back(ARMOperand::CreateCondCode(ARMCC::CondCodes(CC), S));
4169 
4170   return MatchOperand_Success;
4171 }
4172 
4173 /// parseCoprocNumOperand - Try to parse an coprocessor number operand. The
4174 /// token must be an Identifier when called, and if it is a coprocessor
4175 /// number, the token is eaten and the operand is added to the operand list.
4176 OperandMatchResultTy
4177 ARMAsmParser::parseCoprocNumOperand(OperandVector &Operands) {
4178   MCAsmParser &Parser = getParser();
4179   SMLoc S = Parser.getTok().getLoc();
4180   const AsmToken &Tok = Parser.getTok();
4181   if (Tok.isNot(AsmToken::Identifier))
4182     return MatchOperand_NoMatch;
4183 
4184   int Num = MatchCoprocessorOperandName(Tok.getString().lower(), 'p');
4185   if (Num == -1)
4186     return MatchOperand_NoMatch;
4187   if (!isValidCoprocessorNumber(Num, getSTI().getFeatureBits()))
4188     return MatchOperand_NoMatch;
4189 
4190   Parser.Lex(); // Eat identifier token.
4191   Operands.push_back(ARMOperand::CreateCoprocNum(Num, S));
4192   return MatchOperand_Success;
4193 }
4194 
4195 /// parseCoprocRegOperand - Try to parse an coprocessor register operand. The
4196 /// token must be an Identifier when called, and if it is a coprocessor
4197 /// number, the token is eaten and the operand is added to the operand list.
4198 OperandMatchResultTy
4199 ARMAsmParser::parseCoprocRegOperand(OperandVector &Operands) {
4200   MCAsmParser &Parser = getParser();
4201   SMLoc S = Parser.getTok().getLoc();
4202   const AsmToken &Tok = Parser.getTok();
4203   if (Tok.isNot(AsmToken::Identifier))
4204     return MatchOperand_NoMatch;
4205 
4206   int Reg = MatchCoprocessorOperandName(Tok.getString().lower(), 'c');
4207   if (Reg == -1)
4208     return MatchOperand_NoMatch;
4209 
4210   Parser.Lex(); // Eat identifier token.
4211   Operands.push_back(ARMOperand::CreateCoprocReg(Reg, S));
4212   return MatchOperand_Success;
4213 }
4214 
4215 /// parseCoprocOptionOperand - Try to parse an coprocessor option operand.
4216 /// coproc_option : '{' imm0_255 '}'
4217 OperandMatchResultTy
4218 ARMAsmParser::parseCoprocOptionOperand(OperandVector &Operands) {
4219   MCAsmParser &Parser = getParser();
4220   SMLoc S = Parser.getTok().getLoc();
4221 
4222   // If this isn't a '{', this isn't a coprocessor immediate operand.
4223   if (Parser.getTok().isNot(AsmToken::LCurly))
4224     return MatchOperand_NoMatch;
4225   Parser.Lex(); // Eat the '{'
4226 
4227   const MCExpr *Expr;
4228   SMLoc Loc = Parser.getTok().getLoc();
4229   if (getParser().parseExpression(Expr)) {
4230     Error(Loc, "illegal expression");
4231     return MatchOperand_ParseFail;
4232   }
4233   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
4234   if (!CE || CE->getValue() < 0 || CE->getValue() > 255) {
4235     Error(Loc, "coprocessor option must be an immediate in range [0, 255]");
4236     return MatchOperand_ParseFail;
4237   }
4238   int Val = CE->getValue();
4239 
4240   // Check for and consume the closing '}'
4241   if (Parser.getTok().isNot(AsmToken::RCurly))
4242     return MatchOperand_ParseFail;
4243   SMLoc E = Parser.getTok().getEndLoc();
4244   Parser.Lex(); // Eat the '}'
4245 
4246   Operands.push_back(ARMOperand::CreateCoprocOption(Val, S, E));
4247   return MatchOperand_Success;
4248 }
4249 
4250 // For register list parsing, we need to map from raw GPR register numbering
4251 // to the enumeration values. The enumeration values aren't sorted by
4252 // register number due to our using "sp", "lr" and "pc" as canonical names.
4253 static unsigned getNextRegister(unsigned Reg) {
4254   // If this is a GPR, we need to do it manually, otherwise we can rely
4255   // on the sort ordering of the enumeration since the other reg-classes
4256   // are sane.
4257   if (!ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
4258     return Reg + 1;
4259   switch(Reg) {
4260   default: llvm_unreachable("Invalid GPR number!");
4261   case ARM::R0:  return ARM::R1;  case ARM::R1:  return ARM::R2;
4262   case ARM::R2:  return ARM::R3;  case ARM::R3:  return ARM::R4;
4263   case ARM::R4:  return ARM::R5;  case ARM::R5:  return ARM::R6;
4264   case ARM::R6:  return ARM::R7;  case ARM::R7:  return ARM::R8;
4265   case ARM::R8:  return ARM::R9;  case ARM::R9:  return ARM::R10;
4266   case ARM::R10: return ARM::R11; case ARM::R11: return ARM::R12;
4267   case ARM::R12: return ARM::SP;  case ARM::SP:  return ARM::LR;
4268   case ARM::LR:  return ARM::PC;  case ARM::PC:  return ARM::R0;
4269   }
4270 }
4271 
4272 // Insert an <Encoding, Register> pair in an ordered vector. Return true on
4273 // success, or false, if duplicate encoding found.
4274 static bool
4275 insertNoDuplicates(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs,
4276                    unsigned Enc, unsigned Reg) {
4277   Regs.emplace_back(Enc, Reg);
4278   for (auto I = Regs.rbegin(), J = I + 1, E = Regs.rend(); J != E; ++I, ++J) {
4279     if (J->first == Enc) {
4280       Regs.erase(J.base());
4281       return false;
4282     }
4283     if (J->first < Enc)
4284       break;
4285     std::swap(*I, *J);
4286   }
4287   return true;
4288 }
4289 
4290 /// Parse a register list.
4291 bool ARMAsmParser::parseRegisterList(OperandVector &Operands,
4292                                      bool EnforceOrder) {
4293   MCAsmParser &Parser = getParser();
4294   if (Parser.getTok().isNot(AsmToken::LCurly))
4295     return TokError("Token is not a Left Curly Brace");
4296   SMLoc S = Parser.getTok().getLoc();
4297   Parser.Lex(); // Eat '{' token.
4298   SMLoc RegLoc = Parser.getTok().getLoc();
4299 
4300   // Check the first register in the list to see what register class
4301   // this is a list of.
4302   int Reg = tryParseRegister();
4303   if (Reg == -1)
4304     return Error(RegLoc, "register expected");
4305 
4306   // The reglist instructions have at most 16 registers, so reserve
4307   // space for that many.
4308   int EReg = 0;
4309   SmallVector<std::pair<unsigned, unsigned>, 16> Registers;
4310 
4311   // Allow Q regs and just interpret them as the two D sub-registers.
4312   if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
4313     Reg = getDRegFromQReg(Reg);
4314     EReg = MRI->getEncodingValue(Reg);
4315     Registers.emplace_back(EReg, Reg);
4316     ++Reg;
4317   }
4318   const MCRegisterClass *RC;
4319   if (ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
4320     RC = &ARMMCRegisterClasses[ARM::GPRRegClassID];
4321   else if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Reg))
4322     RC = &ARMMCRegisterClasses[ARM::DPRRegClassID];
4323   else if (ARMMCRegisterClasses[ARM::SPRRegClassID].contains(Reg))
4324     RC = &ARMMCRegisterClasses[ARM::SPRRegClassID];
4325   else if (ARMMCRegisterClasses[ARM::GPRwithAPSRnospRegClassID].contains(Reg))
4326     RC = &ARMMCRegisterClasses[ARM::GPRwithAPSRnospRegClassID];
4327   else
4328     return Error(RegLoc, "invalid register in register list");
4329 
4330   // Store the register.
4331   EReg = MRI->getEncodingValue(Reg);
4332   Registers.emplace_back(EReg, Reg);
4333 
4334   // This starts immediately after the first register token in the list,
4335   // so we can see either a comma or a minus (range separator) as a legal
4336   // next token.
4337   while (Parser.getTok().is(AsmToken::Comma) ||
4338          Parser.getTok().is(AsmToken::Minus)) {
4339     if (Parser.getTok().is(AsmToken::Minus)) {
4340       Parser.Lex(); // Eat the minus.
4341       SMLoc AfterMinusLoc = Parser.getTok().getLoc();
4342       int EndReg = tryParseRegister();
4343       if (EndReg == -1)
4344         return Error(AfterMinusLoc, "register expected");
4345       // Allow Q regs and just interpret them as the two D sub-registers.
4346       if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(EndReg))
4347         EndReg = getDRegFromQReg(EndReg) + 1;
4348       // If the register is the same as the start reg, there's nothing
4349       // more to do.
4350       if (Reg == EndReg)
4351         continue;
4352       // The register must be in the same register class as the first.
4353       if (!RC->contains(EndReg))
4354         return Error(AfterMinusLoc, "invalid register in register list");
4355       // Ranges must go from low to high.
4356       if (MRI->getEncodingValue(Reg) > MRI->getEncodingValue(EndReg))
4357         return Error(AfterMinusLoc, "bad range in register list");
4358 
4359       // Add all the registers in the range to the register list.
4360       while (Reg != EndReg) {
4361         Reg = getNextRegister(Reg);
4362         EReg = MRI->getEncodingValue(Reg);
4363         if (!insertNoDuplicates(Registers, EReg, Reg)) {
4364           Warning(AfterMinusLoc, StringRef("duplicated register (") +
4365                                      ARMInstPrinter::getRegisterName(Reg) +
4366                                      ") in register list");
4367         }
4368       }
4369       continue;
4370     }
4371     Parser.Lex(); // Eat the comma.
4372     RegLoc = Parser.getTok().getLoc();
4373     int OldReg = Reg;
4374     const AsmToken RegTok = Parser.getTok();
4375     Reg = tryParseRegister();
4376     if (Reg == -1)
4377       return Error(RegLoc, "register expected");
4378     // Allow Q regs and just interpret them as the two D sub-registers.
4379     bool isQReg = false;
4380     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
4381       Reg = getDRegFromQReg(Reg);
4382       isQReg = true;
4383     }
4384     if (!RC->contains(Reg) &&
4385         RC->getID() == ARMMCRegisterClasses[ARM::GPRRegClassID].getID() &&
4386         ARMMCRegisterClasses[ARM::GPRwithAPSRnospRegClassID].contains(Reg)) {
4387       // switch the register classes, as GPRwithAPSRnospRegClassID is a partial
4388       // subset of GPRRegClassId except it contains APSR as well.
4389       RC = &ARMMCRegisterClasses[ARM::GPRwithAPSRnospRegClassID];
4390     }
4391     if (Reg == ARM::VPR &&
4392         (RC == &ARMMCRegisterClasses[ARM::SPRRegClassID] ||
4393          RC == &ARMMCRegisterClasses[ARM::DPRRegClassID] ||
4394          RC == &ARMMCRegisterClasses[ARM::FPWithVPRRegClassID])) {
4395       RC = &ARMMCRegisterClasses[ARM::FPWithVPRRegClassID];
4396       EReg = MRI->getEncodingValue(Reg);
4397       if (!insertNoDuplicates(Registers, EReg, Reg)) {
4398         Warning(RegLoc, "duplicated register (" + RegTok.getString() +
4399                             ") in register list");
4400       }
4401       continue;
4402     }
4403     // The register must be in the same register class as the first.
4404     if (!RC->contains(Reg))
4405       return Error(RegLoc, "invalid register in register list");
4406     // In most cases, the list must be monotonically increasing. An
4407     // exception is CLRM, which is order-independent anyway, so
4408     // there's no potential for confusion if you write clrm {r2,r1}
4409     // instead of clrm {r1,r2}.
4410     if (EnforceOrder &&
4411         MRI->getEncodingValue(Reg) < MRI->getEncodingValue(OldReg)) {
4412       if (ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
4413         Warning(RegLoc, "register list not in ascending order");
4414       else if (!ARMMCRegisterClasses[ARM::GPRwithAPSRnospRegClassID].contains(Reg))
4415         return Error(RegLoc, "register list not in ascending order");
4416     }
4417     // VFP register lists must also be contiguous.
4418     if (RC != &ARMMCRegisterClasses[ARM::GPRRegClassID] &&
4419         RC != &ARMMCRegisterClasses[ARM::GPRwithAPSRnospRegClassID] &&
4420         Reg != OldReg + 1)
4421       return Error(RegLoc, "non-contiguous register range");
4422     EReg = MRI->getEncodingValue(Reg);
4423     if (!insertNoDuplicates(Registers, EReg, Reg)) {
4424       Warning(RegLoc, "duplicated register (" + RegTok.getString() +
4425                           ") in register list");
4426     }
4427     if (isQReg) {
4428       EReg = MRI->getEncodingValue(++Reg);
4429       Registers.emplace_back(EReg, Reg);
4430     }
4431   }
4432 
4433   if (Parser.getTok().isNot(AsmToken::RCurly))
4434     return Error(Parser.getTok().getLoc(), "'}' expected");
4435   SMLoc E = Parser.getTok().getEndLoc();
4436   Parser.Lex(); // Eat '}' token.
4437 
4438   // Push the register list operand.
4439   Operands.push_back(ARMOperand::CreateRegList(Registers, S, E));
4440 
4441   // The ARM system instruction variants for LDM/STM have a '^' token here.
4442   if (Parser.getTok().is(AsmToken::Caret)) {
4443     Operands.push_back(ARMOperand::CreateToken("^",Parser.getTok().getLoc()));
4444     Parser.Lex(); // Eat '^' token.
4445   }
4446 
4447   return false;
4448 }
4449 
4450 // Helper function to parse the lane index for vector lists.
4451 OperandMatchResultTy ARMAsmParser::
4452 parseVectorLane(VectorLaneTy &LaneKind, unsigned &Index, SMLoc &EndLoc) {
4453   MCAsmParser &Parser = getParser();
4454   Index = 0; // Always return a defined index value.
4455   if (Parser.getTok().is(AsmToken::LBrac)) {
4456     Parser.Lex(); // Eat the '['.
4457     if (Parser.getTok().is(AsmToken::RBrac)) {
4458       // "Dn[]" is the 'all lanes' syntax.
4459       LaneKind = AllLanes;
4460       EndLoc = Parser.getTok().getEndLoc();
4461       Parser.Lex(); // Eat the ']'.
4462       return MatchOperand_Success;
4463     }
4464 
4465     // There's an optional '#' token here. Normally there wouldn't be, but
4466     // inline assemble puts one in, and it's friendly to accept that.
4467     if (Parser.getTok().is(AsmToken::Hash))
4468       Parser.Lex(); // Eat '#' or '$'.
4469 
4470     const MCExpr *LaneIndex;
4471     SMLoc Loc = Parser.getTok().getLoc();
4472     if (getParser().parseExpression(LaneIndex)) {
4473       Error(Loc, "illegal expression");
4474       return MatchOperand_ParseFail;
4475     }
4476     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(LaneIndex);
4477     if (!CE) {
4478       Error(Loc, "lane index must be empty or an integer");
4479       return MatchOperand_ParseFail;
4480     }
4481     if (Parser.getTok().isNot(AsmToken::RBrac)) {
4482       Error(Parser.getTok().getLoc(), "']' expected");
4483       return MatchOperand_ParseFail;
4484     }
4485     EndLoc = Parser.getTok().getEndLoc();
4486     Parser.Lex(); // Eat the ']'.
4487     int64_t Val = CE->getValue();
4488 
4489     // FIXME: Make this range check context sensitive for .8, .16, .32.
4490     if (Val < 0 || Val > 7) {
4491       Error(Parser.getTok().getLoc(), "lane index out of range");
4492       return MatchOperand_ParseFail;
4493     }
4494     Index = Val;
4495     LaneKind = IndexedLane;
4496     return MatchOperand_Success;
4497   }
4498   LaneKind = NoLanes;
4499   return MatchOperand_Success;
4500 }
4501 
4502 // parse a vector register list
4503 OperandMatchResultTy
4504 ARMAsmParser::parseVectorList(OperandVector &Operands) {
4505   MCAsmParser &Parser = getParser();
4506   VectorLaneTy LaneKind;
4507   unsigned LaneIndex;
4508   SMLoc S = Parser.getTok().getLoc();
4509   // As an extension (to match gas), support a plain D register or Q register
4510   // (without encosing curly braces) as a single or double entry list,
4511   // respectively.
4512   if (!hasMVE() && Parser.getTok().is(AsmToken::Identifier)) {
4513     SMLoc E = Parser.getTok().getEndLoc();
4514     int Reg = tryParseRegister();
4515     if (Reg == -1)
4516       return MatchOperand_NoMatch;
4517     if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Reg)) {
4518       OperandMatchResultTy Res = parseVectorLane(LaneKind, LaneIndex, E);
4519       if (Res != MatchOperand_Success)
4520         return Res;
4521       switch (LaneKind) {
4522       case NoLanes:
4523         Operands.push_back(ARMOperand::CreateVectorList(Reg, 1, false, S, E));
4524         break;
4525       case AllLanes:
4526         Operands.push_back(ARMOperand::CreateVectorListAllLanes(Reg, 1, false,
4527                                                                 S, E));
4528         break;
4529       case IndexedLane:
4530         Operands.push_back(ARMOperand::CreateVectorListIndexed(Reg, 1,
4531                                                                LaneIndex,
4532                                                                false, S, E));
4533         break;
4534       }
4535       return MatchOperand_Success;
4536     }
4537     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
4538       Reg = getDRegFromQReg(Reg);
4539       OperandMatchResultTy Res = parseVectorLane(LaneKind, LaneIndex, E);
4540       if (Res != MatchOperand_Success)
4541         return Res;
4542       switch (LaneKind) {
4543       case NoLanes:
4544         Reg = MRI->getMatchingSuperReg(Reg, ARM::dsub_0,
4545                                    &ARMMCRegisterClasses[ARM::DPairRegClassID]);
4546         Operands.push_back(ARMOperand::CreateVectorList(Reg, 2, false, S, E));
4547         break;
4548       case AllLanes:
4549         Reg = MRI->getMatchingSuperReg(Reg, ARM::dsub_0,
4550                                    &ARMMCRegisterClasses[ARM::DPairRegClassID]);
4551         Operands.push_back(ARMOperand::CreateVectorListAllLanes(Reg, 2, false,
4552                                                                 S, E));
4553         break;
4554       case IndexedLane:
4555         Operands.push_back(ARMOperand::CreateVectorListIndexed(Reg, 2,
4556                                                                LaneIndex,
4557                                                                false, S, E));
4558         break;
4559       }
4560       return MatchOperand_Success;
4561     }
4562     Error(S, "vector register expected");
4563     return MatchOperand_ParseFail;
4564   }
4565 
4566   if (Parser.getTok().isNot(AsmToken::LCurly))
4567     return MatchOperand_NoMatch;
4568 
4569   Parser.Lex(); // Eat '{' token.
4570   SMLoc RegLoc = Parser.getTok().getLoc();
4571 
4572   int Reg = tryParseRegister();
4573   if (Reg == -1) {
4574     Error(RegLoc, "register expected");
4575     return MatchOperand_ParseFail;
4576   }
4577   unsigned Count = 1;
4578   int Spacing = 0;
4579   unsigned FirstReg = Reg;
4580 
4581   if (hasMVE() && !ARMMCRegisterClasses[ARM::MQPRRegClassID].contains(Reg)) {
4582       Error(Parser.getTok().getLoc(), "vector register in range Q0-Q7 expected");
4583       return MatchOperand_ParseFail;
4584   }
4585   // The list is of D registers, but we also allow Q regs and just interpret
4586   // them as the two D sub-registers.
4587   else if (!hasMVE() && ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
4588     FirstReg = Reg = getDRegFromQReg(Reg);
4589     Spacing = 1; // double-spacing requires explicit D registers, otherwise
4590                  // it's ambiguous with four-register single spaced.
4591     ++Reg;
4592     ++Count;
4593   }
4594 
4595   SMLoc E;
4596   if (parseVectorLane(LaneKind, LaneIndex, E) != MatchOperand_Success)
4597     return MatchOperand_ParseFail;
4598 
4599   while (Parser.getTok().is(AsmToken::Comma) ||
4600          Parser.getTok().is(AsmToken::Minus)) {
4601     if (Parser.getTok().is(AsmToken::Minus)) {
4602       if (!Spacing)
4603         Spacing = 1; // Register range implies a single spaced list.
4604       else if (Spacing == 2) {
4605         Error(Parser.getTok().getLoc(),
4606               "sequential registers in double spaced list");
4607         return MatchOperand_ParseFail;
4608       }
4609       Parser.Lex(); // Eat the minus.
4610       SMLoc AfterMinusLoc = Parser.getTok().getLoc();
4611       int EndReg = tryParseRegister();
4612       if (EndReg == -1) {
4613         Error(AfterMinusLoc, "register expected");
4614         return MatchOperand_ParseFail;
4615       }
4616       // Allow Q regs and just interpret them as the two D sub-registers.
4617       if (!hasMVE() && ARMMCRegisterClasses[ARM::QPRRegClassID].contains(EndReg))
4618         EndReg = getDRegFromQReg(EndReg) + 1;
4619       // If the register is the same as the start reg, there's nothing
4620       // more to do.
4621       if (Reg == EndReg)
4622         continue;
4623       // The register must be in the same register class as the first.
4624       if ((hasMVE() &&
4625            !ARMMCRegisterClasses[ARM::MQPRRegClassID].contains(EndReg)) ||
4626           (!hasMVE() &&
4627            !ARMMCRegisterClasses[ARM::DPRRegClassID].contains(EndReg))) {
4628         Error(AfterMinusLoc, "invalid register in register list");
4629         return MatchOperand_ParseFail;
4630       }
4631       // Ranges must go from low to high.
4632       if (Reg > EndReg) {
4633         Error(AfterMinusLoc, "bad range in register list");
4634         return MatchOperand_ParseFail;
4635       }
4636       // Parse the lane specifier if present.
4637       VectorLaneTy NextLaneKind;
4638       unsigned NextLaneIndex;
4639       if (parseVectorLane(NextLaneKind, NextLaneIndex, E) !=
4640           MatchOperand_Success)
4641         return MatchOperand_ParseFail;
4642       if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
4643         Error(AfterMinusLoc, "mismatched lane index in register list");
4644         return MatchOperand_ParseFail;
4645       }
4646 
4647       // Add all the registers in the range to the register list.
4648       Count += EndReg - Reg;
4649       Reg = EndReg;
4650       continue;
4651     }
4652     Parser.Lex(); // Eat the comma.
4653     RegLoc = Parser.getTok().getLoc();
4654     int OldReg = Reg;
4655     Reg = tryParseRegister();
4656     if (Reg == -1) {
4657       Error(RegLoc, "register expected");
4658       return MatchOperand_ParseFail;
4659     }
4660 
4661     if (hasMVE()) {
4662       if (!ARMMCRegisterClasses[ARM::MQPRRegClassID].contains(Reg)) {
4663         Error(RegLoc, "vector register in range Q0-Q7 expected");
4664         return MatchOperand_ParseFail;
4665       }
4666       Spacing = 1;
4667     }
4668     // vector register lists must be contiguous.
4669     // It's OK to use the enumeration values directly here rather, as the
4670     // VFP register classes have the enum sorted properly.
4671     //
4672     // The list is of D registers, but we also allow Q regs and just interpret
4673     // them as the two D sub-registers.
4674     else if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
4675       if (!Spacing)
4676         Spacing = 1; // Register range implies a single spaced list.
4677       else if (Spacing == 2) {
4678         Error(RegLoc,
4679               "invalid register in double-spaced list (must be 'D' register')");
4680         return MatchOperand_ParseFail;
4681       }
4682       Reg = getDRegFromQReg(Reg);
4683       if (Reg != OldReg + 1) {
4684         Error(RegLoc, "non-contiguous register range");
4685         return MatchOperand_ParseFail;
4686       }
4687       ++Reg;
4688       Count += 2;
4689       // Parse the lane specifier if present.
4690       VectorLaneTy NextLaneKind;
4691       unsigned NextLaneIndex;
4692       SMLoc LaneLoc = Parser.getTok().getLoc();
4693       if (parseVectorLane(NextLaneKind, NextLaneIndex, E) !=
4694           MatchOperand_Success)
4695         return MatchOperand_ParseFail;
4696       if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
4697         Error(LaneLoc, "mismatched lane index in register list");
4698         return MatchOperand_ParseFail;
4699       }
4700       continue;
4701     }
4702     // Normal D register.
4703     // Figure out the register spacing (single or double) of the list if
4704     // we don't know it already.
4705     if (!Spacing)
4706       Spacing = 1 + (Reg == OldReg + 2);
4707 
4708     // Just check that it's contiguous and keep going.
4709     if (Reg != OldReg + Spacing) {
4710       Error(RegLoc, "non-contiguous register range");
4711       return MatchOperand_ParseFail;
4712     }
4713     ++Count;
4714     // Parse the lane specifier if present.
4715     VectorLaneTy NextLaneKind;
4716     unsigned NextLaneIndex;
4717     SMLoc EndLoc = Parser.getTok().getLoc();
4718     if (parseVectorLane(NextLaneKind, NextLaneIndex, E) != MatchOperand_Success)
4719       return MatchOperand_ParseFail;
4720     if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
4721       Error(EndLoc, "mismatched lane index in register list");
4722       return MatchOperand_ParseFail;
4723     }
4724   }
4725 
4726   if (Parser.getTok().isNot(AsmToken::RCurly)) {
4727     Error(Parser.getTok().getLoc(), "'}' expected");
4728     return MatchOperand_ParseFail;
4729   }
4730   E = Parser.getTok().getEndLoc();
4731   Parser.Lex(); // Eat '}' token.
4732 
4733   switch (LaneKind) {
4734   case NoLanes:
4735   case AllLanes: {
4736     // Two-register operands have been converted to the
4737     // composite register classes.
4738     if (Count == 2 && !hasMVE()) {
4739       const MCRegisterClass *RC = (Spacing == 1) ?
4740         &ARMMCRegisterClasses[ARM::DPairRegClassID] :
4741         &ARMMCRegisterClasses[ARM::DPairSpcRegClassID];
4742       FirstReg = MRI->getMatchingSuperReg(FirstReg, ARM::dsub_0, RC);
4743     }
4744     auto Create = (LaneKind == NoLanes ? ARMOperand::CreateVectorList :
4745                    ARMOperand::CreateVectorListAllLanes);
4746     Operands.push_back(Create(FirstReg, Count, (Spacing == 2), S, E));
4747     break;
4748   }
4749   case IndexedLane:
4750     Operands.push_back(ARMOperand::CreateVectorListIndexed(FirstReg, Count,
4751                                                            LaneIndex,
4752                                                            (Spacing == 2),
4753                                                            S, E));
4754     break;
4755   }
4756   return MatchOperand_Success;
4757 }
4758 
4759 /// parseMemBarrierOptOperand - Try to parse DSB/DMB data barrier options.
4760 OperandMatchResultTy
4761 ARMAsmParser::parseMemBarrierOptOperand(OperandVector &Operands) {
4762   MCAsmParser &Parser = getParser();
4763   SMLoc S = Parser.getTok().getLoc();
4764   const AsmToken &Tok = Parser.getTok();
4765   unsigned Opt;
4766 
4767   if (Tok.is(AsmToken::Identifier)) {
4768     StringRef OptStr = Tok.getString();
4769 
4770     Opt = StringSwitch<unsigned>(OptStr.slice(0, OptStr.size()).lower())
4771       .Case("sy",    ARM_MB::SY)
4772       .Case("st",    ARM_MB::ST)
4773       .Case("ld",    ARM_MB::LD)
4774       .Case("sh",    ARM_MB::ISH)
4775       .Case("ish",   ARM_MB::ISH)
4776       .Case("shst",  ARM_MB::ISHST)
4777       .Case("ishst", ARM_MB::ISHST)
4778       .Case("ishld", ARM_MB::ISHLD)
4779       .Case("nsh",   ARM_MB::NSH)
4780       .Case("un",    ARM_MB::NSH)
4781       .Case("nshst", ARM_MB::NSHST)
4782       .Case("nshld", ARM_MB::NSHLD)
4783       .Case("unst",  ARM_MB::NSHST)
4784       .Case("osh",   ARM_MB::OSH)
4785       .Case("oshst", ARM_MB::OSHST)
4786       .Case("oshld", ARM_MB::OSHLD)
4787       .Default(~0U);
4788 
4789     // ishld, oshld, nshld and ld are only available from ARMv8.
4790     if (!hasV8Ops() && (Opt == ARM_MB::ISHLD || Opt == ARM_MB::OSHLD ||
4791                         Opt == ARM_MB::NSHLD || Opt == ARM_MB::LD))
4792       Opt = ~0U;
4793 
4794     if (Opt == ~0U)
4795       return MatchOperand_NoMatch;
4796 
4797     Parser.Lex(); // Eat identifier token.
4798   } else if (Tok.is(AsmToken::Hash) ||
4799              Tok.is(AsmToken::Dollar) ||
4800              Tok.is(AsmToken::Integer)) {
4801     if (Parser.getTok().isNot(AsmToken::Integer))
4802       Parser.Lex(); // Eat '#' or '$'.
4803     SMLoc Loc = Parser.getTok().getLoc();
4804 
4805     const MCExpr *MemBarrierID;
4806     if (getParser().parseExpression(MemBarrierID)) {
4807       Error(Loc, "illegal expression");
4808       return MatchOperand_ParseFail;
4809     }
4810 
4811     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(MemBarrierID);
4812     if (!CE) {
4813       Error(Loc, "constant expression expected");
4814       return MatchOperand_ParseFail;
4815     }
4816 
4817     int Val = CE->getValue();
4818     if (Val & ~0xf) {
4819       Error(Loc, "immediate value out of range");
4820       return MatchOperand_ParseFail;
4821     }
4822 
4823     Opt = ARM_MB::RESERVED_0 + Val;
4824   } else
4825     return MatchOperand_ParseFail;
4826 
4827   Operands.push_back(ARMOperand::CreateMemBarrierOpt((ARM_MB::MemBOpt)Opt, S));
4828   return MatchOperand_Success;
4829 }
4830 
4831 OperandMatchResultTy
4832 ARMAsmParser::parseTraceSyncBarrierOptOperand(OperandVector &Operands) {
4833   MCAsmParser &Parser = getParser();
4834   SMLoc S = Parser.getTok().getLoc();
4835   const AsmToken &Tok = Parser.getTok();
4836 
4837   if (Tok.isNot(AsmToken::Identifier))
4838      return MatchOperand_NoMatch;
4839 
4840   if (!Tok.getString().equals_lower("csync"))
4841     return MatchOperand_NoMatch;
4842 
4843   Parser.Lex(); // Eat identifier token.
4844 
4845   Operands.push_back(ARMOperand::CreateTraceSyncBarrierOpt(ARM_TSB::CSYNC, S));
4846   return MatchOperand_Success;
4847 }
4848 
4849 /// parseInstSyncBarrierOptOperand - Try to parse ISB inst sync barrier options.
4850 OperandMatchResultTy
4851 ARMAsmParser::parseInstSyncBarrierOptOperand(OperandVector &Operands) {
4852   MCAsmParser &Parser = getParser();
4853   SMLoc S = Parser.getTok().getLoc();
4854   const AsmToken &Tok = Parser.getTok();
4855   unsigned Opt;
4856 
4857   if (Tok.is(AsmToken::Identifier)) {
4858     StringRef OptStr = Tok.getString();
4859 
4860     if (OptStr.equals_lower("sy"))
4861       Opt = ARM_ISB::SY;
4862     else
4863       return MatchOperand_NoMatch;
4864 
4865     Parser.Lex(); // Eat identifier token.
4866   } else if (Tok.is(AsmToken::Hash) ||
4867              Tok.is(AsmToken::Dollar) ||
4868              Tok.is(AsmToken::Integer)) {
4869     if (Parser.getTok().isNot(AsmToken::Integer))
4870       Parser.Lex(); // Eat '#' or '$'.
4871     SMLoc Loc = Parser.getTok().getLoc();
4872 
4873     const MCExpr *ISBarrierID;
4874     if (getParser().parseExpression(ISBarrierID)) {
4875       Error(Loc, "illegal expression");
4876       return MatchOperand_ParseFail;
4877     }
4878 
4879     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ISBarrierID);
4880     if (!CE) {
4881       Error(Loc, "constant expression expected");
4882       return MatchOperand_ParseFail;
4883     }
4884 
4885     int Val = CE->getValue();
4886     if (Val & ~0xf) {
4887       Error(Loc, "immediate value out of range");
4888       return MatchOperand_ParseFail;
4889     }
4890 
4891     Opt = ARM_ISB::RESERVED_0 + Val;
4892   } else
4893     return MatchOperand_ParseFail;
4894 
4895   Operands.push_back(ARMOperand::CreateInstSyncBarrierOpt(
4896           (ARM_ISB::InstSyncBOpt)Opt, S));
4897   return MatchOperand_Success;
4898 }
4899 
4900 
4901 /// parseProcIFlagsOperand - Try to parse iflags from CPS instruction.
4902 OperandMatchResultTy
4903 ARMAsmParser::parseProcIFlagsOperand(OperandVector &Operands) {
4904   MCAsmParser &Parser = getParser();
4905   SMLoc S = Parser.getTok().getLoc();
4906   const AsmToken &Tok = Parser.getTok();
4907   if (!Tok.is(AsmToken::Identifier))
4908     return MatchOperand_NoMatch;
4909   StringRef IFlagsStr = Tok.getString();
4910 
4911   // An iflags string of "none" is interpreted to mean that none of the AIF
4912   // bits are set.  Not a terribly useful instruction, but a valid encoding.
4913   unsigned IFlags = 0;
4914   if (IFlagsStr != "none") {
4915         for (int i = 0, e = IFlagsStr.size(); i != e; ++i) {
4916       unsigned Flag = StringSwitch<unsigned>(IFlagsStr.substr(i, 1).lower())
4917         .Case("a", ARM_PROC::A)
4918         .Case("i", ARM_PROC::I)
4919         .Case("f", ARM_PROC::F)
4920         .Default(~0U);
4921 
4922       // If some specific iflag is already set, it means that some letter is
4923       // present more than once, this is not acceptable.
4924       if (Flag == ~0U || (IFlags & Flag))
4925         return MatchOperand_NoMatch;
4926 
4927       IFlags |= Flag;
4928     }
4929   }
4930 
4931   Parser.Lex(); // Eat identifier token.
4932   Operands.push_back(ARMOperand::CreateProcIFlags((ARM_PROC::IFlags)IFlags, S));
4933   return MatchOperand_Success;
4934 }
4935 
4936 /// parseMSRMaskOperand - Try to parse mask flags from MSR instruction.
4937 OperandMatchResultTy
4938 ARMAsmParser::parseMSRMaskOperand(OperandVector &Operands) {
4939   MCAsmParser &Parser = getParser();
4940   SMLoc S = Parser.getTok().getLoc();
4941   const AsmToken &Tok = Parser.getTok();
4942 
4943   if (Tok.is(AsmToken::Integer)) {
4944     int64_t Val = Tok.getIntVal();
4945     if (Val > 255 || Val < 0) {
4946       return MatchOperand_NoMatch;
4947     }
4948     unsigned SYSmvalue = Val & 0xFF;
4949     Parser.Lex();
4950     Operands.push_back(ARMOperand::CreateMSRMask(SYSmvalue, S));
4951     return MatchOperand_Success;
4952   }
4953 
4954   if (!Tok.is(AsmToken::Identifier))
4955     return MatchOperand_NoMatch;
4956   StringRef Mask = Tok.getString();
4957 
4958   if (isMClass()) {
4959     auto TheReg = ARMSysReg::lookupMClassSysRegByName(Mask.lower());
4960     if (!TheReg || !TheReg->hasRequiredFeatures(getSTI().getFeatureBits()))
4961       return MatchOperand_NoMatch;
4962 
4963     unsigned SYSmvalue = TheReg->Encoding & 0xFFF;
4964 
4965     Parser.Lex(); // Eat identifier token.
4966     Operands.push_back(ARMOperand::CreateMSRMask(SYSmvalue, S));
4967     return MatchOperand_Success;
4968   }
4969 
4970   // Split spec_reg from flag, example: CPSR_sxf => "CPSR" and "sxf"
4971   size_t Start = 0, Next = Mask.find('_');
4972   StringRef Flags = "";
4973   std::string SpecReg = Mask.slice(Start, Next).lower();
4974   if (Next != StringRef::npos)
4975     Flags = Mask.slice(Next+1, Mask.size());
4976 
4977   // FlagsVal contains the complete mask:
4978   // 3-0: Mask
4979   // 4: Special Reg (cpsr, apsr => 0; spsr => 1)
4980   unsigned FlagsVal = 0;
4981 
4982   if (SpecReg == "apsr") {
4983     FlagsVal = StringSwitch<unsigned>(Flags)
4984     .Case("nzcvq",  0x8) // same as CPSR_f
4985     .Case("g",      0x4) // same as CPSR_s
4986     .Case("nzcvqg", 0xc) // same as CPSR_fs
4987     .Default(~0U);
4988 
4989     if (FlagsVal == ~0U) {
4990       if (!Flags.empty())
4991         return MatchOperand_NoMatch;
4992       else
4993         FlagsVal = 8; // No flag
4994     }
4995   } else if (SpecReg == "cpsr" || SpecReg == "spsr") {
4996     // cpsr_all is an alias for cpsr_fc, as is plain cpsr.
4997     if (Flags == "all" || Flags == "")
4998       Flags = "fc";
4999     for (int i = 0, e = Flags.size(); i != e; ++i) {
5000       unsigned Flag = StringSwitch<unsigned>(Flags.substr(i, 1))
5001       .Case("c", 1)
5002       .Case("x", 2)
5003       .Case("s", 4)
5004       .Case("f", 8)
5005       .Default(~0U);
5006 
5007       // If some specific flag is already set, it means that some letter is
5008       // present more than once, this is not acceptable.
5009       if (Flag == ~0U || (FlagsVal & Flag))
5010         return MatchOperand_NoMatch;
5011       FlagsVal |= Flag;
5012     }
5013   } else // No match for special register.
5014     return MatchOperand_NoMatch;
5015 
5016   // Special register without flags is NOT equivalent to "fc" flags.
5017   // NOTE: This is a divergence from gas' behavior.  Uncommenting the following
5018   // two lines would enable gas compatibility at the expense of breaking
5019   // round-tripping.
5020   //
5021   // if (!FlagsVal)
5022   //  FlagsVal = 0x9;
5023 
5024   // Bit 4: Special Reg (cpsr, apsr => 0; spsr => 1)
5025   if (SpecReg == "spsr")
5026     FlagsVal |= 16;
5027 
5028   Parser.Lex(); // Eat identifier token.
5029   Operands.push_back(ARMOperand::CreateMSRMask(FlagsVal, S));
5030   return MatchOperand_Success;
5031 }
5032 
5033 /// parseBankedRegOperand - Try to parse a banked register (e.g. "lr_irq") for
5034 /// use in the MRS/MSR instructions added to support virtualization.
5035 OperandMatchResultTy
5036 ARMAsmParser::parseBankedRegOperand(OperandVector &Operands) {
5037   MCAsmParser &Parser = getParser();
5038   SMLoc S = Parser.getTok().getLoc();
5039   const AsmToken &Tok = Parser.getTok();
5040   if (!Tok.is(AsmToken::Identifier))
5041     return MatchOperand_NoMatch;
5042   StringRef RegName = Tok.getString();
5043 
5044   auto TheReg = ARMBankedReg::lookupBankedRegByName(RegName.lower());
5045   if (!TheReg)
5046     return MatchOperand_NoMatch;
5047   unsigned Encoding = TheReg->Encoding;
5048 
5049   Parser.Lex(); // Eat identifier token.
5050   Operands.push_back(ARMOperand::CreateBankedReg(Encoding, S));
5051   return MatchOperand_Success;
5052 }
5053 
5054 OperandMatchResultTy
5055 ARMAsmParser::parsePKHImm(OperandVector &Operands, StringRef Op, int Low,
5056                           int High) {
5057   MCAsmParser &Parser = getParser();
5058   const AsmToken &Tok = Parser.getTok();
5059   if (Tok.isNot(AsmToken::Identifier)) {
5060     Error(Parser.getTok().getLoc(), Op + " operand expected.");
5061     return MatchOperand_ParseFail;
5062   }
5063   StringRef ShiftName = Tok.getString();
5064   std::string LowerOp = Op.lower();
5065   std::string UpperOp = Op.upper();
5066   if (ShiftName != LowerOp && ShiftName != UpperOp) {
5067     Error(Parser.getTok().getLoc(), Op + " operand expected.");
5068     return MatchOperand_ParseFail;
5069   }
5070   Parser.Lex(); // Eat shift type token.
5071 
5072   // There must be a '#' and a shift amount.
5073   if (Parser.getTok().isNot(AsmToken::Hash) &&
5074       Parser.getTok().isNot(AsmToken::Dollar)) {
5075     Error(Parser.getTok().getLoc(), "'#' expected");
5076     return MatchOperand_ParseFail;
5077   }
5078   Parser.Lex(); // Eat hash token.
5079 
5080   const MCExpr *ShiftAmount;
5081   SMLoc Loc = Parser.getTok().getLoc();
5082   SMLoc EndLoc;
5083   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
5084     Error(Loc, "illegal expression");
5085     return MatchOperand_ParseFail;
5086   }
5087   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
5088   if (!CE) {
5089     Error(Loc, "constant expression expected");
5090     return MatchOperand_ParseFail;
5091   }
5092   int Val = CE->getValue();
5093   if (Val < Low || Val > High) {
5094     Error(Loc, "immediate value out of range");
5095     return MatchOperand_ParseFail;
5096   }
5097 
5098   Operands.push_back(ARMOperand::CreateImm(CE, Loc, EndLoc));
5099 
5100   return MatchOperand_Success;
5101 }
5102 
5103 OperandMatchResultTy
5104 ARMAsmParser::parseSetEndImm(OperandVector &Operands) {
5105   MCAsmParser &Parser = getParser();
5106   const AsmToken &Tok = Parser.getTok();
5107   SMLoc S = Tok.getLoc();
5108   if (Tok.isNot(AsmToken::Identifier)) {
5109     Error(S, "'be' or 'le' operand expected");
5110     return MatchOperand_ParseFail;
5111   }
5112   int Val = StringSwitch<int>(Tok.getString().lower())
5113     .Case("be", 1)
5114     .Case("le", 0)
5115     .Default(-1);
5116   Parser.Lex(); // Eat the token.
5117 
5118   if (Val == -1) {
5119     Error(S, "'be' or 'le' operand expected");
5120     return MatchOperand_ParseFail;
5121   }
5122   Operands.push_back(ARMOperand::CreateImm(MCConstantExpr::create(Val,
5123                                                                   getContext()),
5124                                            S, Tok.getEndLoc()));
5125   return MatchOperand_Success;
5126 }
5127 
5128 /// parseShifterImm - Parse the shifter immediate operand for SSAT/USAT
5129 /// instructions. Legal values are:
5130 ///     lsl #n  'n' in [0,31]
5131 ///     asr #n  'n' in [1,32]
5132 ///             n == 32 encoded as n == 0.
5133 OperandMatchResultTy
5134 ARMAsmParser::parseShifterImm(OperandVector &Operands) {
5135   MCAsmParser &Parser = getParser();
5136   const AsmToken &Tok = Parser.getTok();
5137   SMLoc S = Tok.getLoc();
5138   if (Tok.isNot(AsmToken::Identifier)) {
5139     Error(S, "shift operator 'asr' or 'lsl' expected");
5140     return MatchOperand_ParseFail;
5141   }
5142   StringRef ShiftName = Tok.getString();
5143   bool isASR;
5144   if (ShiftName == "lsl" || ShiftName == "LSL")
5145     isASR = false;
5146   else if (ShiftName == "asr" || ShiftName == "ASR")
5147     isASR = true;
5148   else {
5149     Error(S, "shift operator 'asr' or 'lsl' expected");
5150     return MatchOperand_ParseFail;
5151   }
5152   Parser.Lex(); // Eat the operator.
5153 
5154   // A '#' and a shift amount.
5155   if (Parser.getTok().isNot(AsmToken::Hash) &&
5156       Parser.getTok().isNot(AsmToken::Dollar)) {
5157     Error(Parser.getTok().getLoc(), "'#' expected");
5158     return MatchOperand_ParseFail;
5159   }
5160   Parser.Lex(); // Eat hash token.
5161   SMLoc ExLoc = Parser.getTok().getLoc();
5162 
5163   const MCExpr *ShiftAmount;
5164   SMLoc EndLoc;
5165   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
5166     Error(ExLoc, "malformed shift expression");
5167     return MatchOperand_ParseFail;
5168   }
5169   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
5170   if (!CE) {
5171     Error(ExLoc, "shift amount must be an immediate");
5172     return MatchOperand_ParseFail;
5173   }
5174 
5175   int64_t Val = CE->getValue();
5176   if (isASR) {
5177     // Shift amount must be in [1,32]
5178     if (Val < 1 || Val > 32) {
5179       Error(ExLoc, "'asr' shift amount must be in range [1,32]");
5180       return MatchOperand_ParseFail;
5181     }
5182     // asr #32 encoded as asr #0, but is not allowed in Thumb2 mode.
5183     if (isThumb() && Val == 32) {
5184       Error(ExLoc, "'asr #32' shift amount not allowed in Thumb mode");
5185       return MatchOperand_ParseFail;
5186     }
5187     if (Val == 32) Val = 0;
5188   } else {
5189     // Shift amount must be in [1,32]
5190     if (Val < 0 || Val > 31) {
5191       Error(ExLoc, "'lsr' shift amount must be in range [0,31]");
5192       return MatchOperand_ParseFail;
5193     }
5194   }
5195 
5196   Operands.push_back(ARMOperand::CreateShifterImm(isASR, Val, S, EndLoc));
5197 
5198   return MatchOperand_Success;
5199 }
5200 
5201 /// parseRotImm - Parse the shifter immediate operand for SXTB/UXTB family
5202 /// of instructions. Legal values are:
5203 ///     ror #n  'n' in {0, 8, 16, 24}
5204 OperandMatchResultTy
5205 ARMAsmParser::parseRotImm(OperandVector &Operands) {
5206   MCAsmParser &Parser = getParser();
5207   const AsmToken &Tok = Parser.getTok();
5208   SMLoc S = Tok.getLoc();
5209   if (Tok.isNot(AsmToken::Identifier))
5210     return MatchOperand_NoMatch;
5211   StringRef ShiftName = Tok.getString();
5212   if (ShiftName != "ror" && ShiftName != "ROR")
5213     return MatchOperand_NoMatch;
5214   Parser.Lex(); // Eat the operator.
5215 
5216   // A '#' and a rotate amount.
5217   if (Parser.getTok().isNot(AsmToken::Hash) &&
5218       Parser.getTok().isNot(AsmToken::Dollar)) {
5219     Error(Parser.getTok().getLoc(), "'#' expected");
5220     return MatchOperand_ParseFail;
5221   }
5222   Parser.Lex(); // Eat hash token.
5223   SMLoc ExLoc = Parser.getTok().getLoc();
5224 
5225   const MCExpr *ShiftAmount;
5226   SMLoc EndLoc;
5227   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
5228     Error(ExLoc, "malformed rotate expression");
5229     return MatchOperand_ParseFail;
5230   }
5231   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
5232   if (!CE) {
5233     Error(ExLoc, "rotate amount must be an immediate");
5234     return MatchOperand_ParseFail;
5235   }
5236 
5237   int64_t Val = CE->getValue();
5238   // Shift amount must be in {0, 8, 16, 24} (0 is undocumented extension)
5239   // normally, zero is represented in asm by omitting the rotate operand
5240   // entirely.
5241   if (Val != 8 && Val != 16 && Val != 24 && Val != 0) {
5242     Error(ExLoc, "'ror' rotate amount must be 8, 16, or 24");
5243     return MatchOperand_ParseFail;
5244   }
5245 
5246   Operands.push_back(ARMOperand::CreateRotImm(Val, S, EndLoc));
5247 
5248   return MatchOperand_Success;
5249 }
5250 
5251 OperandMatchResultTy
5252 ARMAsmParser::parseModImm(OperandVector &Operands) {
5253   MCAsmParser &Parser = getParser();
5254   MCAsmLexer &Lexer = getLexer();
5255   int64_t Imm1, Imm2;
5256 
5257   SMLoc S = Parser.getTok().getLoc();
5258 
5259   // 1) A mod_imm operand can appear in the place of a register name:
5260   //   add r0, #mod_imm
5261   //   add r0, r0, #mod_imm
5262   // to correctly handle the latter, we bail out as soon as we see an
5263   // identifier.
5264   //
5265   // 2) Similarly, we do not want to parse into complex operands:
5266   //   mov r0, #mod_imm
5267   //   mov r0, :lower16:(_foo)
5268   if (Parser.getTok().is(AsmToken::Identifier) ||
5269       Parser.getTok().is(AsmToken::Colon))
5270     return MatchOperand_NoMatch;
5271 
5272   // Hash (dollar) is optional as per the ARMARM
5273   if (Parser.getTok().is(AsmToken::Hash) ||
5274       Parser.getTok().is(AsmToken::Dollar)) {
5275     // Avoid parsing into complex operands (#:)
5276     if (Lexer.peekTok().is(AsmToken::Colon))
5277       return MatchOperand_NoMatch;
5278 
5279     // Eat the hash (dollar)
5280     Parser.Lex();
5281   }
5282 
5283   SMLoc Sx1, Ex1;
5284   Sx1 = Parser.getTok().getLoc();
5285   const MCExpr *Imm1Exp;
5286   if (getParser().parseExpression(Imm1Exp, Ex1)) {
5287     Error(Sx1, "malformed expression");
5288     return MatchOperand_ParseFail;
5289   }
5290 
5291   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm1Exp);
5292 
5293   if (CE) {
5294     // Immediate must fit within 32-bits
5295     Imm1 = CE->getValue();
5296     int Enc = ARM_AM::getSOImmVal(Imm1);
5297     if (Enc != -1 && Parser.getTok().is(AsmToken::EndOfStatement)) {
5298       // We have a match!
5299       Operands.push_back(ARMOperand::CreateModImm((Enc & 0xFF),
5300                                                   (Enc & 0xF00) >> 7,
5301                                                   Sx1, Ex1));
5302       return MatchOperand_Success;
5303     }
5304 
5305     // We have parsed an immediate which is not for us, fallback to a plain
5306     // immediate. This can happen for instruction aliases. For an example,
5307     // ARMInstrInfo.td defines the alias [mov <-> mvn] which can transform
5308     // a mov (mvn) with a mod_imm_neg/mod_imm_not operand into the opposite
5309     // instruction with a mod_imm operand. The alias is defined such that the
5310     // parser method is shared, that's why we have to do this here.
5311     if (Parser.getTok().is(AsmToken::EndOfStatement)) {
5312       Operands.push_back(ARMOperand::CreateImm(Imm1Exp, Sx1, Ex1));
5313       return MatchOperand_Success;
5314     }
5315   } else {
5316     // Operands like #(l1 - l2) can only be evaluated at a later stage (via an
5317     // MCFixup). Fallback to a plain immediate.
5318     Operands.push_back(ARMOperand::CreateImm(Imm1Exp, Sx1, Ex1));
5319     return MatchOperand_Success;
5320   }
5321 
5322   // From this point onward, we expect the input to be a (#bits, #rot) pair
5323   if (Parser.getTok().isNot(AsmToken::Comma)) {
5324     Error(Sx1, "expected modified immediate operand: #[0, 255], #even[0-30]");
5325     return MatchOperand_ParseFail;
5326   }
5327 
5328   if (Imm1 & ~0xFF) {
5329     Error(Sx1, "immediate operand must a number in the range [0, 255]");
5330     return MatchOperand_ParseFail;
5331   }
5332 
5333   // Eat the comma
5334   Parser.Lex();
5335 
5336   // Repeat for #rot
5337   SMLoc Sx2, Ex2;
5338   Sx2 = Parser.getTok().getLoc();
5339 
5340   // Eat the optional hash (dollar)
5341   if (Parser.getTok().is(AsmToken::Hash) ||
5342       Parser.getTok().is(AsmToken::Dollar))
5343     Parser.Lex();
5344 
5345   const MCExpr *Imm2Exp;
5346   if (getParser().parseExpression(Imm2Exp, Ex2)) {
5347     Error(Sx2, "malformed expression");
5348     return MatchOperand_ParseFail;
5349   }
5350 
5351   CE = dyn_cast<MCConstantExpr>(Imm2Exp);
5352 
5353   if (CE) {
5354     Imm2 = CE->getValue();
5355     if (!(Imm2 & ~0x1E)) {
5356       // We have a match!
5357       Operands.push_back(ARMOperand::CreateModImm(Imm1, Imm2, S, Ex2));
5358       return MatchOperand_Success;
5359     }
5360     Error(Sx2, "immediate operand must an even number in the range [0, 30]");
5361     return MatchOperand_ParseFail;
5362   } else {
5363     Error(Sx2, "constant expression expected");
5364     return MatchOperand_ParseFail;
5365   }
5366 }
5367 
5368 OperandMatchResultTy
5369 ARMAsmParser::parseBitfield(OperandVector &Operands) {
5370   MCAsmParser &Parser = getParser();
5371   SMLoc S = Parser.getTok().getLoc();
5372   // The bitfield descriptor is really two operands, the LSB and the width.
5373   if (Parser.getTok().isNot(AsmToken::Hash) &&
5374       Parser.getTok().isNot(AsmToken::Dollar)) {
5375     Error(Parser.getTok().getLoc(), "'#' expected");
5376     return MatchOperand_ParseFail;
5377   }
5378   Parser.Lex(); // Eat hash token.
5379 
5380   const MCExpr *LSBExpr;
5381   SMLoc E = Parser.getTok().getLoc();
5382   if (getParser().parseExpression(LSBExpr)) {
5383     Error(E, "malformed immediate expression");
5384     return MatchOperand_ParseFail;
5385   }
5386   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(LSBExpr);
5387   if (!CE) {
5388     Error(E, "'lsb' operand must be an immediate");
5389     return MatchOperand_ParseFail;
5390   }
5391 
5392   int64_t LSB = CE->getValue();
5393   // The LSB must be in the range [0,31]
5394   if (LSB < 0 || LSB > 31) {
5395     Error(E, "'lsb' operand must be in the range [0,31]");
5396     return MatchOperand_ParseFail;
5397   }
5398   E = Parser.getTok().getLoc();
5399 
5400   // Expect another immediate operand.
5401   if (Parser.getTok().isNot(AsmToken::Comma)) {
5402     Error(Parser.getTok().getLoc(), "too few operands");
5403     return MatchOperand_ParseFail;
5404   }
5405   Parser.Lex(); // Eat hash token.
5406   if (Parser.getTok().isNot(AsmToken::Hash) &&
5407       Parser.getTok().isNot(AsmToken::Dollar)) {
5408     Error(Parser.getTok().getLoc(), "'#' expected");
5409     return MatchOperand_ParseFail;
5410   }
5411   Parser.Lex(); // Eat hash token.
5412 
5413   const MCExpr *WidthExpr;
5414   SMLoc EndLoc;
5415   if (getParser().parseExpression(WidthExpr, EndLoc)) {
5416     Error(E, "malformed immediate expression");
5417     return MatchOperand_ParseFail;
5418   }
5419   CE = dyn_cast<MCConstantExpr>(WidthExpr);
5420   if (!CE) {
5421     Error(E, "'width' operand must be an immediate");
5422     return MatchOperand_ParseFail;
5423   }
5424 
5425   int64_t Width = CE->getValue();
5426   // The LSB must be in the range [1,32-lsb]
5427   if (Width < 1 || Width > 32 - LSB) {
5428     Error(E, "'width' operand must be in the range [1,32-lsb]");
5429     return MatchOperand_ParseFail;
5430   }
5431 
5432   Operands.push_back(ARMOperand::CreateBitfield(LSB, Width, S, EndLoc));
5433 
5434   return MatchOperand_Success;
5435 }
5436 
5437 OperandMatchResultTy
5438 ARMAsmParser::parsePostIdxReg(OperandVector &Operands) {
5439   // Check for a post-index addressing register operand. Specifically:
5440   // postidx_reg := '+' register {, shift}
5441   //              | '-' register {, shift}
5442   //              | register {, shift}
5443 
5444   // This method must return MatchOperand_NoMatch without consuming any tokens
5445   // in the case where there is no match, as other alternatives take other
5446   // parse methods.
5447   MCAsmParser &Parser = getParser();
5448   AsmToken Tok = Parser.getTok();
5449   SMLoc S = Tok.getLoc();
5450   bool haveEaten = false;
5451   bool isAdd = true;
5452   if (Tok.is(AsmToken::Plus)) {
5453     Parser.Lex(); // Eat the '+' token.
5454     haveEaten = true;
5455   } else if (Tok.is(AsmToken::Minus)) {
5456     Parser.Lex(); // Eat the '-' token.
5457     isAdd = false;
5458     haveEaten = true;
5459   }
5460 
5461   SMLoc E = Parser.getTok().getEndLoc();
5462   int Reg = tryParseRegister();
5463   if (Reg == -1) {
5464     if (!haveEaten)
5465       return MatchOperand_NoMatch;
5466     Error(Parser.getTok().getLoc(), "register expected");
5467     return MatchOperand_ParseFail;
5468   }
5469 
5470   ARM_AM::ShiftOpc ShiftTy = ARM_AM::no_shift;
5471   unsigned ShiftImm = 0;
5472   if (Parser.getTok().is(AsmToken::Comma)) {
5473     Parser.Lex(); // Eat the ','.
5474     if (parseMemRegOffsetShift(ShiftTy, ShiftImm))
5475       return MatchOperand_ParseFail;
5476 
5477     // FIXME: Only approximates end...may include intervening whitespace.
5478     E = Parser.getTok().getLoc();
5479   }
5480 
5481   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ShiftTy,
5482                                                   ShiftImm, S, E));
5483 
5484   return MatchOperand_Success;
5485 }
5486 
5487 OperandMatchResultTy
5488 ARMAsmParser::parseAM3Offset(OperandVector &Operands) {
5489   // Check for a post-index addressing register operand. Specifically:
5490   // am3offset := '+' register
5491   //              | '-' register
5492   //              | register
5493   //              | # imm
5494   //              | # + imm
5495   //              | # - imm
5496 
5497   // This method must return MatchOperand_NoMatch without consuming any tokens
5498   // in the case where there is no match, as other alternatives take other
5499   // parse methods.
5500   MCAsmParser &Parser = getParser();
5501   AsmToken Tok = Parser.getTok();
5502   SMLoc S = Tok.getLoc();
5503 
5504   // Do immediates first, as we always parse those if we have a '#'.
5505   if (Parser.getTok().is(AsmToken::Hash) ||
5506       Parser.getTok().is(AsmToken::Dollar)) {
5507     Parser.Lex(); // Eat '#' or '$'.
5508     // Explicitly look for a '-', as we need to encode negative zero
5509     // differently.
5510     bool isNegative = Parser.getTok().is(AsmToken::Minus);
5511     const MCExpr *Offset;
5512     SMLoc E;
5513     if (getParser().parseExpression(Offset, E))
5514       return MatchOperand_ParseFail;
5515     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
5516     if (!CE) {
5517       Error(S, "constant expression expected");
5518       return MatchOperand_ParseFail;
5519     }
5520     // Negative zero is encoded as the flag value
5521     // std::numeric_limits<int32_t>::min().
5522     int32_t Val = CE->getValue();
5523     if (isNegative && Val == 0)
5524       Val = std::numeric_limits<int32_t>::min();
5525 
5526     Operands.push_back(
5527       ARMOperand::CreateImm(MCConstantExpr::create(Val, getContext()), S, E));
5528 
5529     return MatchOperand_Success;
5530   }
5531 
5532   bool haveEaten = false;
5533   bool isAdd = true;
5534   if (Tok.is(AsmToken::Plus)) {
5535     Parser.Lex(); // Eat the '+' token.
5536     haveEaten = true;
5537   } else if (Tok.is(AsmToken::Minus)) {
5538     Parser.Lex(); // Eat the '-' token.
5539     isAdd = false;
5540     haveEaten = true;
5541   }
5542 
5543   Tok = Parser.getTok();
5544   int Reg = tryParseRegister();
5545   if (Reg == -1) {
5546     if (!haveEaten)
5547       return MatchOperand_NoMatch;
5548     Error(Tok.getLoc(), "register expected");
5549     return MatchOperand_ParseFail;
5550   }
5551 
5552   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ARM_AM::no_shift,
5553                                                   0, S, Tok.getEndLoc()));
5554 
5555   return MatchOperand_Success;
5556 }
5557 
5558 /// Convert parsed operands to MCInst.  Needed here because this instruction
5559 /// only has two register operands, but multiplication is commutative so
5560 /// assemblers should accept both "mul rD, rN, rD" and "mul rD, rD, rN".
5561 void ARMAsmParser::cvtThumbMultiply(MCInst &Inst,
5562                                     const OperandVector &Operands) {
5563   ((ARMOperand &)*Operands[3]).addRegOperands(Inst, 1);
5564   ((ARMOperand &)*Operands[1]).addCCOutOperands(Inst, 1);
5565   // If we have a three-operand form, make sure to set Rn to be the operand
5566   // that isn't the same as Rd.
5567   unsigned RegOp = 4;
5568   if (Operands.size() == 6 &&
5569       ((ARMOperand &)*Operands[4]).getReg() ==
5570           ((ARMOperand &)*Operands[3]).getReg())
5571     RegOp = 5;
5572   ((ARMOperand &)*Operands[RegOp]).addRegOperands(Inst, 1);
5573   Inst.addOperand(Inst.getOperand(0));
5574   ((ARMOperand &)*Operands[2]).addCondCodeOperands(Inst, 2);
5575 }
5576 
5577 void ARMAsmParser::cvtThumbBranches(MCInst &Inst,
5578                                     const OperandVector &Operands) {
5579   int CondOp = -1, ImmOp = -1;
5580   switch(Inst.getOpcode()) {
5581     case ARM::tB:
5582     case ARM::tBcc:  CondOp = 1; ImmOp = 2; break;
5583 
5584     case ARM::t2B:
5585     case ARM::t2Bcc: CondOp = 1; ImmOp = 3; break;
5586 
5587     default: llvm_unreachable("Unexpected instruction in cvtThumbBranches");
5588   }
5589   // first decide whether or not the branch should be conditional
5590   // by looking at it's location relative to an IT block
5591   if(inITBlock()) {
5592     // inside an IT block we cannot have any conditional branches. any
5593     // such instructions needs to be converted to unconditional form
5594     switch(Inst.getOpcode()) {
5595       case ARM::tBcc: Inst.setOpcode(ARM::tB); break;
5596       case ARM::t2Bcc: Inst.setOpcode(ARM::t2B); break;
5597     }
5598   } else {
5599     // outside IT blocks we can only have unconditional branches with AL
5600     // condition code or conditional branches with non-AL condition code
5601     unsigned Cond = static_cast<ARMOperand &>(*Operands[CondOp]).getCondCode();
5602     switch(Inst.getOpcode()) {
5603       case ARM::tB:
5604       case ARM::tBcc:
5605         Inst.setOpcode(Cond == ARMCC::AL ? ARM::tB : ARM::tBcc);
5606         break;
5607       case ARM::t2B:
5608       case ARM::t2Bcc:
5609         Inst.setOpcode(Cond == ARMCC::AL ? ARM::t2B : ARM::t2Bcc);
5610         break;
5611     }
5612   }
5613 
5614   // now decide on encoding size based on branch target range
5615   switch(Inst.getOpcode()) {
5616     // classify tB as either t2B or t1B based on range of immediate operand
5617     case ARM::tB: {
5618       ARMOperand &op = static_cast<ARMOperand &>(*Operands[ImmOp]);
5619       if (!op.isSignedOffset<11, 1>() && isThumb() && hasV8MBaseline())
5620         Inst.setOpcode(ARM::t2B);
5621       break;
5622     }
5623     // classify tBcc as either t2Bcc or t1Bcc based on range of immediate operand
5624     case ARM::tBcc: {
5625       ARMOperand &op = static_cast<ARMOperand &>(*Operands[ImmOp]);
5626       if (!op.isSignedOffset<8, 1>() && isThumb() && hasV8MBaseline())
5627         Inst.setOpcode(ARM::t2Bcc);
5628       break;
5629     }
5630   }
5631   ((ARMOperand &)*Operands[ImmOp]).addImmOperands(Inst, 1);
5632   ((ARMOperand &)*Operands[CondOp]).addCondCodeOperands(Inst, 2);
5633 }
5634 
5635 void ARMAsmParser::cvtMVEVMOVQtoDReg(
5636   MCInst &Inst, const OperandVector &Operands) {
5637 
5638   // mnemonic, condition code, Rt, Rt2, Qd, idx, Qd again, idx2
5639   assert(Operands.size() == 8);
5640 
5641   ((ARMOperand &)*Operands[2]).addRegOperands(Inst, 1); // Rt
5642   ((ARMOperand &)*Operands[3]).addRegOperands(Inst, 1); // Rt2
5643   ((ARMOperand &)*Operands[4]).addRegOperands(Inst, 1); // Qd
5644   ((ARMOperand &)*Operands[5]).addMVEPairVectorIndexOperands(Inst, 1); // idx
5645   // skip second copy of Qd in Operands[6]
5646   ((ARMOperand &)*Operands[7]).addMVEPairVectorIndexOperands(Inst, 1); // idx2
5647   ((ARMOperand &)*Operands[1]).addCondCodeOperands(Inst, 2); // condition code
5648 }
5649 
5650 /// Parse an ARM memory expression, return false if successful else return true
5651 /// or an error.  The first token must be a '[' when called.
5652 bool ARMAsmParser::parseMemory(OperandVector &Operands) {
5653   MCAsmParser &Parser = getParser();
5654   SMLoc S, E;
5655   if (Parser.getTok().isNot(AsmToken::LBrac))
5656     return TokError("Token is not a Left Bracket");
5657   S = Parser.getTok().getLoc();
5658   Parser.Lex(); // Eat left bracket token.
5659 
5660   const AsmToken &BaseRegTok = Parser.getTok();
5661   int BaseRegNum = tryParseRegister();
5662   if (BaseRegNum == -1)
5663     return Error(BaseRegTok.getLoc(), "register expected");
5664 
5665   // The next token must either be a comma, a colon or a closing bracket.
5666   const AsmToken &Tok = Parser.getTok();
5667   if (!Tok.is(AsmToken::Colon) && !Tok.is(AsmToken::Comma) &&
5668       !Tok.is(AsmToken::RBrac))
5669     return Error(Tok.getLoc(), "malformed memory operand");
5670 
5671   if (Tok.is(AsmToken::RBrac)) {
5672     E = Tok.getEndLoc();
5673     Parser.Lex(); // Eat right bracket token.
5674 
5675     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, 0,
5676                                              ARM_AM::no_shift, 0, 0, false,
5677                                              S, E));
5678 
5679     // If there's a pre-indexing writeback marker, '!', just add it as a token
5680     // operand. It's rather odd, but syntactically valid.
5681     if (Parser.getTok().is(AsmToken::Exclaim)) {
5682       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
5683       Parser.Lex(); // Eat the '!'.
5684     }
5685 
5686     return false;
5687   }
5688 
5689   assert((Tok.is(AsmToken::Colon) || Tok.is(AsmToken::Comma)) &&
5690          "Lost colon or comma in memory operand?!");
5691   if (Tok.is(AsmToken::Comma)) {
5692     Parser.Lex(); // Eat the comma.
5693   }
5694 
5695   // If we have a ':', it's an alignment specifier.
5696   if (Parser.getTok().is(AsmToken::Colon)) {
5697     Parser.Lex(); // Eat the ':'.
5698     E = Parser.getTok().getLoc();
5699     SMLoc AlignmentLoc = Tok.getLoc();
5700 
5701     const MCExpr *Expr;
5702     if (getParser().parseExpression(Expr))
5703      return true;
5704 
5705     // The expression has to be a constant. Memory references with relocations
5706     // don't come through here, as they use the <label> forms of the relevant
5707     // instructions.
5708     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
5709     if (!CE)
5710       return Error (E, "constant expression expected");
5711 
5712     unsigned Align = 0;
5713     switch (CE->getValue()) {
5714     default:
5715       return Error(E,
5716                    "alignment specifier must be 16, 32, 64, 128, or 256 bits");
5717     case 16:  Align = 2; break;
5718     case 32:  Align = 4; break;
5719     case 64:  Align = 8; break;
5720     case 128: Align = 16; break;
5721     case 256: Align = 32; break;
5722     }
5723 
5724     // Now we should have the closing ']'
5725     if (Parser.getTok().isNot(AsmToken::RBrac))
5726       return Error(Parser.getTok().getLoc(), "']' expected");
5727     E = Parser.getTok().getEndLoc();
5728     Parser.Lex(); // Eat right bracket token.
5729 
5730     // Don't worry about range checking the value here. That's handled by
5731     // the is*() predicates.
5732     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, 0,
5733                                              ARM_AM::no_shift, 0, Align,
5734                                              false, S, E, AlignmentLoc));
5735 
5736     // If there's a pre-indexing writeback marker, '!', just add it as a token
5737     // operand.
5738     if (Parser.getTok().is(AsmToken::Exclaim)) {
5739       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
5740       Parser.Lex(); // Eat the '!'.
5741     }
5742 
5743     return false;
5744   }
5745 
5746   // If we have a '#' or '$', it's an immediate offset, else assume it's a
5747   // register offset. Be friendly and also accept a plain integer or expression
5748   // (without a leading hash) for gas compatibility.
5749   if (Parser.getTok().is(AsmToken::Hash) ||
5750       Parser.getTok().is(AsmToken::Dollar) ||
5751       Parser.getTok().is(AsmToken::LParen) ||
5752       Parser.getTok().is(AsmToken::Integer)) {
5753     if (Parser.getTok().is(AsmToken::Hash) ||
5754         Parser.getTok().is(AsmToken::Dollar))
5755       Parser.Lex(); // Eat '#' or '$'
5756     E = Parser.getTok().getLoc();
5757 
5758     bool isNegative = getParser().getTok().is(AsmToken::Minus);
5759     const MCExpr *Offset;
5760     if (getParser().parseExpression(Offset))
5761      return true;
5762 
5763     // The expression has to be a constant. Memory references with relocations
5764     // don't come through here, as they use the <label> forms of the relevant
5765     // instructions.
5766     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
5767     if (!CE)
5768       return Error (E, "constant expression expected");
5769 
5770     // If the constant was #-0, represent it as
5771     // std::numeric_limits<int32_t>::min().
5772     int32_t Val = CE->getValue();
5773     if (isNegative && Val == 0)
5774       CE = MCConstantExpr::create(std::numeric_limits<int32_t>::min(),
5775                                   getContext());
5776 
5777     // Now we should have the closing ']'
5778     if (Parser.getTok().isNot(AsmToken::RBrac))
5779       return Error(Parser.getTok().getLoc(), "']' expected");
5780     E = Parser.getTok().getEndLoc();
5781     Parser.Lex(); // Eat right bracket token.
5782 
5783     // Don't worry about range checking the value here. That's handled by
5784     // the is*() predicates.
5785     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, CE, 0,
5786                                              ARM_AM::no_shift, 0, 0,
5787                                              false, S, E));
5788 
5789     // If there's a pre-indexing writeback marker, '!', just add it as a token
5790     // operand.
5791     if (Parser.getTok().is(AsmToken::Exclaim)) {
5792       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
5793       Parser.Lex(); // Eat the '!'.
5794     }
5795 
5796     return false;
5797   }
5798 
5799   // The register offset is optionally preceded by a '+' or '-'
5800   bool isNegative = false;
5801   if (Parser.getTok().is(AsmToken::Minus)) {
5802     isNegative = true;
5803     Parser.Lex(); // Eat the '-'.
5804   } else if (Parser.getTok().is(AsmToken::Plus)) {
5805     // Nothing to do.
5806     Parser.Lex(); // Eat the '+'.
5807   }
5808 
5809   E = Parser.getTok().getLoc();
5810   int OffsetRegNum = tryParseRegister();
5811   if (OffsetRegNum == -1)
5812     return Error(E, "register expected");
5813 
5814   // If there's a shift operator, handle it.
5815   ARM_AM::ShiftOpc ShiftType = ARM_AM::no_shift;
5816   unsigned ShiftImm = 0;
5817   if (Parser.getTok().is(AsmToken::Comma)) {
5818     Parser.Lex(); // Eat the ','.
5819     if (parseMemRegOffsetShift(ShiftType, ShiftImm))
5820       return true;
5821   }
5822 
5823   // Now we should have the closing ']'
5824   if (Parser.getTok().isNot(AsmToken::RBrac))
5825     return Error(Parser.getTok().getLoc(), "']' expected");
5826   E = Parser.getTok().getEndLoc();
5827   Parser.Lex(); // Eat right bracket token.
5828 
5829   Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, OffsetRegNum,
5830                                            ShiftType, ShiftImm, 0, isNegative,
5831                                            S, E));
5832 
5833   // If there's a pre-indexing writeback marker, '!', just add it as a token
5834   // operand.
5835   if (Parser.getTok().is(AsmToken::Exclaim)) {
5836     Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
5837     Parser.Lex(); // Eat the '!'.
5838   }
5839 
5840   return false;
5841 }
5842 
5843 /// parseMemRegOffsetShift - one of these two:
5844 ///   ( lsl | lsr | asr | ror ) , # shift_amount
5845 ///   rrx
5846 /// return true if it parses a shift otherwise it returns false.
5847 bool ARMAsmParser::parseMemRegOffsetShift(ARM_AM::ShiftOpc &St,
5848                                           unsigned &Amount) {
5849   MCAsmParser &Parser = getParser();
5850   SMLoc Loc = Parser.getTok().getLoc();
5851   const AsmToken &Tok = Parser.getTok();
5852   if (Tok.isNot(AsmToken::Identifier))
5853     return Error(Loc, "illegal shift operator");
5854   StringRef ShiftName = Tok.getString();
5855   if (ShiftName == "lsl" || ShiftName == "LSL" ||
5856       ShiftName == "asl" || ShiftName == "ASL")
5857     St = ARM_AM::lsl;
5858   else if (ShiftName == "lsr" || ShiftName == "LSR")
5859     St = ARM_AM::lsr;
5860   else if (ShiftName == "asr" || ShiftName == "ASR")
5861     St = ARM_AM::asr;
5862   else if (ShiftName == "ror" || ShiftName == "ROR")
5863     St = ARM_AM::ror;
5864   else if (ShiftName == "rrx" || ShiftName == "RRX")
5865     St = ARM_AM::rrx;
5866   else if (ShiftName == "uxtw" || ShiftName == "UXTW")
5867     St = ARM_AM::uxtw;
5868   else
5869     return Error(Loc, "illegal shift operator");
5870   Parser.Lex(); // Eat shift type token.
5871 
5872   // rrx stands alone.
5873   Amount = 0;
5874   if (St != ARM_AM::rrx) {
5875     Loc = Parser.getTok().getLoc();
5876     // A '#' and a shift amount.
5877     const AsmToken &HashTok = Parser.getTok();
5878     if (HashTok.isNot(AsmToken::Hash) &&
5879         HashTok.isNot(AsmToken::Dollar))
5880       return Error(HashTok.getLoc(), "'#' expected");
5881     Parser.Lex(); // Eat hash token.
5882 
5883     const MCExpr *Expr;
5884     if (getParser().parseExpression(Expr))
5885       return true;
5886     // Range check the immediate.
5887     // lsl, ror: 0 <= imm <= 31
5888     // lsr, asr: 0 <= imm <= 32
5889     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
5890     if (!CE)
5891       return Error(Loc, "shift amount must be an immediate");
5892     int64_t Imm = CE->getValue();
5893     if (Imm < 0 ||
5894         ((St == ARM_AM::lsl || St == ARM_AM::ror) && Imm > 31) ||
5895         ((St == ARM_AM::lsr || St == ARM_AM::asr) && Imm > 32))
5896       return Error(Loc, "immediate shift value out of range");
5897     // If <ShiftTy> #0, turn it into a no_shift.
5898     if (Imm == 0)
5899       St = ARM_AM::lsl;
5900     // For consistency, treat lsr #32 and asr #32 as having immediate value 0.
5901     if (Imm == 32)
5902       Imm = 0;
5903     Amount = Imm;
5904   }
5905 
5906   return false;
5907 }
5908 
5909 /// parseFPImm - A floating point immediate expression operand.
5910 OperandMatchResultTy
5911 ARMAsmParser::parseFPImm(OperandVector &Operands) {
5912   MCAsmParser &Parser = getParser();
5913   // Anything that can accept a floating point constant as an operand
5914   // needs to go through here, as the regular parseExpression is
5915   // integer only.
5916   //
5917   // This routine still creates a generic Immediate operand, containing
5918   // a bitcast of the 64-bit floating point value. The various operands
5919   // that accept floats can check whether the value is valid for them
5920   // via the standard is*() predicates.
5921 
5922   SMLoc S = Parser.getTok().getLoc();
5923 
5924   if (Parser.getTok().isNot(AsmToken::Hash) &&
5925       Parser.getTok().isNot(AsmToken::Dollar))
5926     return MatchOperand_NoMatch;
5927 
5928   // Disambiguate the VMOV forms that can accept an FP immediate.
5929   // vmov.f32 <sreg>, #imm
5930   // vmov.f64 <dreg>, #imm
5931   // vmov.f32 <dreg>, #imm  @ vector f32x2
5932   // vmov.f32 <qreg>, #imm  @ vector f32x4
5933   //
5934   // There are also the NEON VMOV instructions which expect an
5935   // integer constant. Make sure we don't try to parse an FPImm
5936   // for these:
5937   // vmov.i{8|16|32|64} <dreg|qreg>, #imm
5938   ARMOperand &TyOp = static_cast<ARMOperand &>(*Operands[2]);
5939   bool isVmovf = TyOp.isToken() &&
5940                  (TyOp.getToken() == ".f32" || TyOp.getToken() == ".f64" ||
5941                   TyOp.getToken() == ".f16");
5942   ARMOperand &Mnemonic = static_cast<ARMOperand &>(*Operands[0]);
5943   bool isFconst = Mnemonic.isToken() && (Mnemonic.getToken() == "fconstd" ||
5944                                          Mnemonic.getToken() == "fconsts");
5945   if (!(isVmovf || isFconst))
5946     return MatchOperand_NoMatch;
5947 
5948   Parser.Lex(); // Eat '#' or '$'.
5949 
5950   // Handle negation, as that still comes through as a separate token.
5951   bool isNegative = false;
5952   if (Parser.getTok().is(AsmToken::Minus)) {
5953     isNegative = true;
5954     Parser.Lex();
5955   }
5956   const AsmToken &Tok = Parser.getTok();
5957   SMLoc Loc = Tok.getLoc();
5958   if (Tok.is(AsmToken::Real) && isVmovf) {
5959     APFloat RealVal(APFloat::IEEEsingle(), Tok.getString());
5960     uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
5961     // If we had a '-' in front, toggle the sign bit.
5962     IntVal ^= (uint64_t)isNegative << 31;
5963     Parser.Lex(); // Eat the token.
5964     Operands.push_back(ARMOperand::CreateImm(
5965           MCConstantExpr::create(IntVal, getContext()),
5966           S, Parser.getTok().getLoc()));
5967     return MatchOperand_Success;
5968   }
5969   // Also handle plain integers. Instructions which allow floating point
5970   // immediates also allow a raw encoded 8-bit value.
5971   if (Tok.is(AsmToken::Integer) && isFconst) {
5972     int64_t Val = Tok.getIntVal();
5973     Parser.Lex(); // Eat the token.
5974     if (Val > 255 || Val < 0) {
5975       Error(Loc, "encoded floating point value out of range");
5976       return MatchOperand_ParseFail;
5977     }
5978     float RealVal = ARM_AM::getFPImmFloat(Val);
5979     Val = APFloat(RealVal).bitcastToAPInt().getZExtValue();
5980 
5981     Operands.push_back(ARMOperand::CreateImm(
5982         MCConstantExpr::create(Val, getContext()), S,
5983         Parser.getTok().getLoc()));
5984     return MatchOperand_Success;
5985   }
5986 
5987   Error(Loc, "invalid floating point immediate");
5988   return MatchOperand_ParseFail;
5989 }
5990 
5991 /// Parse a arm instruction operand.  For now this parses the operand regardless
5992 /// of the mnemonic.
5993 bool ARMAsmParser::parseOperand(OperandVector &Operands, StringRef Mnemonic) {
5994   MCAsmParser &Parser = getParser();
5995   SMLoc S, E;
5996 
5997   // Check if the current operand has a custom associated parser, if so, try to
5998   // custom parse the operand, or fallback to the general approach.
5999   OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
6000   if (ResTy == MatchOperand_Success)
6001     return false;
6002   // If there wasn't a custom match, try the generic matcher below. Otherwise,
6003   // there was a match, but an error occurred, in which case, just return that
6004   // the operand parsing failed.
6005   if (ResTy == MatchOperand_ParseFail)
6006     return true;
6007 
6008   switch (getLexer().getKind()) {
6009   default:
6010     Error(Parser.getTok().getLoc(), "unexpected token in operand");
6011     return true;
6012   case AsmToken::Identifier: {
6013     // If we've seen a branch mnemonic, the next operand must be a label.  This
6014     // is true even if the label is a register name.  So "br r1" means branch to
6015     // label "r1".
6016     bool ExpectLabel = Mnemonic == "b" || Mnemonic == "bl";
6017     if (!ExpectLabel) {
6018       if (!tryParseRegisterWithWriteBack(Operands))
6019         return false;
6020       int Res = tryParseShiftRegister(Operands);
6021       if (Res == 0) // success
6022         return false;
6023       else if (Res == -1) // irrecoverable error
6024         return true;
6025       // If this is VMRS, check for the apsr_nzcv operand.
6026       if (Mnemonic == "vmrs" &&
6027           Parser.getTok().getString().equals_lower("apsr_nzcv")) {
6028         S = Parser.getTok().getLoc();
6029         Parser.Lex();
6030         Operands.push_back(ARMOperand::CreateToken("APSR_nzcv", S));
6031         return false;
6032       }
6033     }
6034 
6035     // Fall though for the Identifier case that is not a register or a
6036     // special name.
6037     LLVM_FALLTHROUGH;
6038   }
6039   case AsmToken::LParen:  // parenthesized expressions like (_strcmp-4)
6040   case AsmToken::Integer: // things like 1f and 2b as a branch targets
6041   case AsmToken::String:  // quoted label names.
6042   case AsmToken::Dot: {   // . as a branch target
6043     // This was not a register so parse other operands that start with an
6044     // identifier (like labels) as expressions and create them as immediates.
6045     const MCExpr *IdVal;
6046     S = Parser.getTok().getLoc();
6047     if (getParser().parseExpression(IdVal))
6048       return true;
6049     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
6050     Operands.push_back(ARMOperand::CreateImm(IdVal, S, E));
6051     return false;
6052   }
6053   case AsmToken::LBrac:
6054     return parseMemory(Operands);
6055   case AsmToken::LCurly:
6056     return parseRegisterList(Operands, !Mnemonic.startswith("clr"));
6057   case AsmToken::Dollar:
6058   case AsmToken::Hash:
6059     // #42 -> immediate.
6060     S = Parser.getTok().getLoc();
6061     Parser.Lex();
6062 
6063     if (Parser.getTok().isNot(AsmToken::Colon)) {
6064       bool isNegative = Parser.getTok().is(AsmToken::Minus);
6065       const MCExpr *ImmVal;
6066       if (getParser().parseExpression(ImmVal))
6067         return true;
6068       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ImmVal);
6069       if (CE) {
6070         int32_t Val = CE->getValue();
6071         if (isNegative && Val == 0)
6072           ImmVal = MCConstantExpr::create(std::numeric_limits<int32_t>::min(),
6073                                           getContext());
6074       }
6075       E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
6076       Operands.push_back(ARMOperand::CreateImm(ImmVal, S, E));
6077 
6078       // There can be a trailing '!' on operands that we want as a separate
6079       // '!' Token operand. Handle that here. For example, the compatibility
6080       // alias for 'srsdb sp!, #imm' is 'srsdb #imm!'.
6081       if (Parser.getTok().is(AsmToken::Exclaim)) {
6082         Operands.push_back(ARMOperand::CreateToken(Parser.getTok().getString(),
6083                                                    Parser.getTok().getLoc()));
6084         Parser.Lex(); // Eat exclaim token
6085       }
6086       return false;
6087     }
6088     // w/ a ':' after the '#', it's just like a plain ':'.
6089     LLVM_FALLTHROUGH;
6090 
6091   case AsmToken::Colon: {
6092     S = Parser.getTok().getLoc();
6093     // ":lower16:" and ":upper16:" expression prefixes
6094     // FIXME: Check it's an expression prefix,
6095     // e.g. (FOO - :lower16:BAR) isn't legal.
6096     ARMMCExpr::VariantKind RefKind;
6097     if (parsePrefix(RefKind))
6098       return true;
6099 
6100     const MCExpr *SubExprVal;
6101     if (getParser().parseExpression(SubExprVal))
6102       return true;
6103 
6104     const MCExpr *ExprVal = ARMMCExpr::create(RefKind, SubExprVal,
6105                                               getContext());
6106     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
6107     Operands.push_back(ARMOperand::CreateImm(ExprVal, S, E));
6108     return false;
6109   }
6110   case AsmToken::Equal: {
6111     S = Parser.getTok().getLoc();
6112     if (Mnemonic != "ldr") // only parse for ldr pseudo (e.g. ldr r0, =val)
6113       return Error(S, "unexpected token in operand");
6114     Parser.Lex(); // Eat '='
6115     const MCExpr *SubExprVal;
6116     if (getParser().parseExpression(SubExprVal))
6117       return true;
6118     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
6119 
6120     // execute-only: we assume that assembly programmers know what they are
6121     // doing and allow literal pool creation here
6122     Operands.push_back(ARMOperand::CreateConstantPoolImm(SubExprVal, S, E));
6123     return false;
6124   }
6125   }
6126 }
6127 
6128 // parsePrefix - Parse ARM 16-bit relocations expression prefix, i.e.
6129 //  :lower16: and :upper16:.
6130 bool ARMAsmParser::parsePrefix(ARMMCExpr::VariantKind &RefKind) {
6131   MCAsmParser &Parser = getParser();
6132   RefKind = ARMMCExpr::VK_ARM_None;
6133 
6134   // consume an optional '#' (GNU compatibility)
6135   if (getLexer().is(AsmToken::Hash))
6136     Parser.Lex();
6137 
6138   // :lower16: and :upper16: modifiers
6139   assert(getLexer().is(AsmToken::Colon) && "expected a :");
6140   Parser.Lex(); // Eat ':'
6141 
6142   if (getLexer().isNot(AsmToken::Identifier)) {
6143     Error(Parser.getTok().getLoc(), "expected prefix identifier in operand");
6144     return true;
6145   }
6146 
6147   enum {
6148     COFF = (1 << MCObjectFileInfo::IsCOFF),
6149     ELF = (1 << MCObjectFileInfo::IsELF),
6150     MACHO = (1 << MCObjectFileInfo::IsMachO),
6151     WASM = (1 << MCObjectFileInfo::IsWasm),
6152   };
6153   static const struct PrefixEntry {
6154     const char *Spelling;
6155     ARMMCExpr::VariantKind VariantKind;
6156     uint8_t SupportedFormats;
6157   } PrefixEntries[] = {
6158     { "lower16", ARMMCExpr::VK_ARM_LO16, COFF | ELF | MACHO },
6159     { "upper16", ARMMCExpr::VK_ARM_HI16, COFF | ELF | MACHO },
6160   };
6161 
6162   StringRef IDVal = Parser.getTok().getIdentifier();
6163 
6164   const auto &Prefix =
6165       std::find_if(std::begin(PrefixEntries), std::end(PrefixEntries),
6166                    [&IDVal](const PrefixEntry &PE) {
6167                       return PE.Spelling == IDVal;
6168                    });
6169   if (Prefix == std::end(PrefixEntries)) {
6170     Error(Parser.getTok().getLoc(), "unexpected prefix in operand");
6171     return true;
6172   }
6173 
6174   uint8_t CurrentFormat;
6175   switch (getContext().getObjectFileInfo()->getObjectFileType()) {
6176   case MCObjectFileInfo::IsMachO:
6177     CurrentFormat = MACHO;
6178     break;
6179   case MCObjectFileInfo::IsELF:
6180     CurrentFormat = ELF;
6181     break;
6182   case MCObjectFileInfo::IsCOFF:
6183     CurrentFormat = COFF;
6184     break;
6185   case MCObjectFileInfo::IsWasm:
6186     CurrentFormat = WASM;
6187     break;
6188   case MCObjectFileInfo::IsXCOFF:
6189     llvm_unreachable("unexpected object format");
6190     break;
6191   }
6192 
6193   if (~Prefix->SupportedFormats & CurrentFormat) {
6194     Error(Parser.getTok().getLoc(),
6195           "cannot represent relocation in the current file format");
6196     return true;
6197   }
6198 
6199   RefKind = Prefix->VariantKind;
6200   Parser.Lex();
6201 
6202   if (getLexer().isNot(AsmToken::Colon)) {
6203     Error(Parser.getTok().getLoc(), "unexpected token after prefix");
6204     return true;
6205   }
6206   Parser.Lex(); // Eat the last ':'
6207 
6208   return false;
6209 }
6210 
6211 /// Given a mnemonic, split out possible predication code and carry
6212 /// setting letters to form a canonical mnemonic and flags.
6213 //
6214 // FIXME: Would be nice to autogen this.
6215 // FIXME: This is a bit of a maze of special cases.
6216 StringRef ARMAsmParser::splitMnemonic(StringRef Mnemonic,
6217                                       StringRef ExtraToken,
6218                                       unsigned &PredicationCode,
6219                                       unsigned &VPTPredicationCode,
6220                                       bool &CarrySetting,
6221                                       unsigned &ProcessorIMod,
6222                                       StringRef &ITMask) {
6223   PredicationCode = ARMCC::AL;
6224   VPTPredicationCode = ARMVCC::None;
6225   CarrySetting = false;
6226   ProcessorIMod = 0;
6227 
6228   // Ignore some mnemonics we know aren't predicated forms.
6229   //
6230   // FIXME: Would be nice to autogen this.
6231   if ((Mnemonic == "movs" && isThumb()) ||
6232       Mnemonic == "teq"   || Mnemonic == "vceq"   || Mnemonic == "svc"   ||
6233       Mnemonic == "mls"   || Mnemonic == "smmls"  || Mnemonic == "vcls"  ||
6234       Mnemonic == "vmls"  || Mnemonic == "vnmls"  || Mnemonic == "vacge" ||
6235       Mnemonic == "vcge"  || Mnemonic == "vclt"   || Mnemonic == "vacgt" ||
6236       Mnemonic == "vaclt" || Mnemonic == "vacle"  || Mnemonic == "hlt" ||
6237       Mnemonic == "vcgt"  || Mnemonic == "vcle"   || Mnemonic == "smlal" ||
6238       Mnemonic == "umaal" || Mnemonic == "umlal"  || Mnemonic == "vabal" ||
6239       Mnemonic == "vmlal" || Mnemonic == "vpadal" || Mnemonic == "vqdmlal" ||
6240       Mnemonic == "fmuls" || Mnemonic == "vmaxnm" || Mnemonic == "vminnm" ||
6241       Mnemonic == "vcvta" || Mnemonic == "vcvtn"  || Mnemonic == "vcvtp" ||
6242       Mnemonic == "vcvtm" || Mnemonic == "vrinta" || Mnemonic == "vrintn" ||
6243       Mnemonic == "vrintp" || Mnemonic == "vrintm" || Mnemonic == "hvc" ||
6244       Mnemonic.startswith("vsel") || Mnemonic == "vins" || Mnemonic == "vmovx" ||
6245       Mnemonic == "bxns"  || Mnemonic == "blxns" ||
6246       Mnemonic == "vudot" || Mnemonic == "vsdot" ||
6247       Mnemonic == "vcmla" || Mnemonic == "vcadd" ||
6248       Mnemonic == "vfmal" || Mnemonic == "vfmsl" ||
6249       Mnemonic == "wls" || Mnemonic == "le" || Mnemonic == "dls" ||
6250       Mnemonic == "csel" || Mnemonic == "csinc" ||
6251       Mnemonic == "csinv" || Mnemonic == "csneg" || Mnemonic == "cinc" ||
6252       Mnemonic == "cinv" || Mnemonic == "cneg" || Mnemonic == "cset" ||
6253       Mnemonic == "csetm")
6254     return Mnemonic;
6255 
6256   // First, split out any predication code. Ignore mnemonics we know aren't
6257   // predicated but do have a carry-set and so weren't caught above.
6258   if (Mnemonic != "adcs" && Mnemonic != "bics" && Mnemonic != "movs" &&
6259       Mnemonic != "muls" && Mnemonic != "smlals" && Mnemonic != "smulls" &&
6260       Mnemonic != "umlals" && Mnemonic != "umulls" && Mnemonic != "lsls" &&
6261       Mnemonic != "sbcs" && Mnemonic != "rscs" &&
6262       !(hasMVE() &&
6263         (Mnemonic == "vmine" ||
6264          Mnemonic == "vshle" || Mnemonic == "vshlt" || Mnemonic == "vshllt" ||
6265          Mnemonic == "vrshle" || Mnemonic == "vrshlt" ||
6266          Mnemonic == "vmvne" || Mnemonic == "vorne" ||
6267          Mnemonic == "vnege" || Mnemonic == "vnegt" ||
6268          Mnemonic == "vmule" || Mnemonic == "vmult" ||
6269          Mnemonic == "vrintne" ||
6270          Mnemonic == "vcmult" || Mnemonic == "vcmule" ||
6271          Mnemonic == "vpsele" || Mnemonic == "vpselt" ||
6272          Mnemonic.startswith("vq")))) {
6273     unsigned CC = ARMCondCodeFromString(Mnemonic.substr(Mnemonic.size()-2));
6274     if (CC != ~0U) {
6275       Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 2);
6276       PredicationCode = CC;
6277     }
6278   }
6279 
6280   // Next, determine if we have a carry setting bit. We explicitly ignore all
6281   // the instructions we know end in 's'.
6282   if (Mnemonic.endswith("s") &&
6283       !(Mnemonic == "cps" || Mnemonic == "mls" ||
6284         Mnemonic == "mrs" || Mnemonic == "smmls" || Mnemonic == "vabs" ||
6285         Mnemonic == "vcls" || Mnemonic == "vmls" || Mnemonic == "vmrs" ||
6286         Mnemonic == "vnmls" || Mnemonic == "vqabs" || Mnemonic == "vrecps" ||
6287         Mnemonic == "vrsqrts" || Mnemonic == "srs" || Mnemonic == "flds" ||
6288         Mnemonic == "fmrs" || Mnemonic == "fsqrts" || Mnemonic == "fsubs" ||
6289         Mnemonic == "fsts" || Mnemonic == "fcpys" || Mnemonic == "fdivs" ||
6290         Mnemonic == "fmuls" || Mnemonic == "fcmps" || Mnemonic == "fcmpzs" ||
6291         Mnemonic == "vfms" || Mnemonic == "vfnms" || Mnemonic == "fconsts" ||
6292         Mnemonic == "bxns" || Mnemonic == "blxns" || Mnemonic == "vfmas" ||
6293         Mnemonic == "vmlas" ||
6294         (Mnemonic == "movs" && isThumb()))) {
6295     Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 1);
6296     CarrySetting = true;
6297   }
6298 
6299   // The "cps" instruction can have a interrupt mode operand which is glued into
6300   // the mnemonic. Check if this is the case, split it and parse the imod op
6301   if (Mnemonic.startswith("cps")) {
6302     // Split out any imod code.
6303     unsigned IMod =
6304       StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2, 2))
6305       .Case("ie", ARM_PROC::IE)
6306       .Case("id", ARM_PROC::ID)
6307       .Default(~0U);
6308     if (IMod != ~0U) {
6309       Mnemonic = Mnemonic.slice(0, Mnemonic.size()-2);
6310       ProcessorIMod = IMod;
6311     }
6312   }
6313 
6314   if (isMnemonicVPTPredicable(Mnemonic, ExtraToken) && Mnemonic != "vmovlt" &&
6315       Mnemonic != "vshllt" && Mnemonic != "vrshrnt" && Mnemonic != "vshrnt" &&
6316       Mnemonic != "vqrshrunt" && Mnemonic != "vqshrunt" &&
6317       Mnemonic != "vqrshrnt" && Mnemonic != "vqshrnt" && Mnemonic != "vmullt" &&
6318       Mnemonic != "vqmovnt" && Mnemonic != "vqmovunt" &&
6319       Mnemonic != "vqmovnt" && Mnemonic != "vmovnt" && Mnemonic != "vqdmullt" &&
6320       Mnemonic != "vpnot" && Mnemonic != "vcvtt" && Mnemonic != "vcvt") {
6321     unsigned CC = ARMVectorCondCodeFromString(Mnemonic.substr(Mnemonic.size()-1));
6322     if (CC != ~0U) {
6323       Mnemonic = Mnemonic.slice(0, Mnemonic.size()-1);
6324       VPTPredicationCode = CC;
6325     }
6326     return Mnemonic;
6327   }
6328 
6329   // The "it" instruction has the condition mask on the end of the mnemonic.
6330   if (Mnemonic.startswith("it")) {
6331     ITMask = Mnemonic.slice(2, Mnemonic.size());
6332     Mnemonic = Mnemonic.slice(0, 2);
6333   }
6334 
6335   if (Mnemonic.startswith("vpst")) {
6336     ITMask = Mnemonic.slice(4, Mnemonic.size());
6337     Mnemonic = Mnemonic.slice(0, 4);
6338   }
6339   else if (Mnemonic.startswith("vpt")) {
6340     ITMask = Mnemonic.slice(3, Mnemonic.size());
6341     Mnemonic = Mnemonic.slice(0, 3);
6342   }
6343 
6344   return Mnemonic;
6345 }
6346 
6347 /// Given a canonical mnemonic, determine if the instruction ever allows
6348 /// inclusion of carry set or predication code operands.
6349 //
6350 // FIXME: It would be nice to autogen this.
6351 void ARMAsmParser::getMnemonicAcceptInfo(StringRef Mnemonic,
6352                                          StringRef ExtraToken,
6353                                          StringRef FullInst,
6354                                          bool &CanAcceptCarrySet,
6355                                          bool &CanAcceptPredicationCode,
6356                                          bool &CanAcceptVPTPredicationCode) {
6357   CanAcceptVPTPredicationCode = isMnemonicVPTPredicable(Mnemonic, ExtraToken);
6358 
6359   CanAcceptCarrySet =
6360       Mnemonic == "and" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
6361       Mnemonic == "rrx" || Mnemonic == "ror" || Mnemonic == "sub" ||
6362       Mnemonic == "add" || Mnemonic == "adc" || Mnemonic == "mul" ||
6363       Mnemonic == "bic" || Mnemonic == "asr" || Mnemonic == "orr" ||
6364       Mnemonic == "mvn" || Mnemonic == "rsb" || Mnemonic == "rsc" ||
6365       Mnemonic == "orn" || Mnemonic == "sbc" || Mnemonic == "eor" ||
6366       Mnemonic == "neg" || Mnemonic == "vfm" || Mnemonic == "vfnm" ||
6367       (!isThumb() &&
6368        (Mnemonic == "smull" || Mnemonic == "mov" || Mnemonic == "mla" ||
6369         Mnemonic == "smlal" || Mnemonic == "umlal" || Mnemonic == "umull"));
6370 
6371   if (Mnemonic == "bkpt" || Mnemonic == "cbnz" || Mnemonic == "setend" ||
6372       Mnemonic == "cps" || Mnemonic == "it" || Mnemonic == "cbz" ||
6373       Mnemonic == "trap" || Mnemonic == "hlt" || Mnemonic == "udf" ||
6374       Mnemonic.startswith("crc32") || Mnemonic.startswith("cps") ||
6375       Mnemonic.startswith("vsel") || Mnemonic == "vmaxnm" ||
6376       Mnemonic == "vminnm" || Mnemonic == "vcvta" || Mnemonic == "vcvtn" ||
6377       Mnemonic == "vcvtp" || Mnemonic == "vcvtm" || Mnemonic == "vrinta" ||
6378       Mnemonic == "vrintn" || Mnemonic == "vrintp" || Mnemonic == "vrintm" ||
6379       Mnemonic.startswith("aes") || Mnemonic == "hvc" || Mnemonic == "setpan" ||
6380       Mnemonic.startswith("sha1") || Mnemonic.startswith("sha256") ||
6381       (FullInst.startswith("vmull") && FullInst.endswith(".p64")) ||
6382       Mnemonic == "vmovx" || Mnemonic == "vins" ||
6383       Mnemonic == "vudot" || Mnemonic == "vsdot" ||
6384       Mnemonic == "vcmla" || Mnemonic == "vcadd" ||
6385       Mnemonic == "vfmal" || Mnemonic == "vfmsl" ||
6386       Mnemonic == "sb"    || Mnemonic == "ssbb"  ||
6387       Mnemonic == "pssbb" ||
6388       Mnemonic == "bfcsel" || Mnemonic == "wls" ||
6389       Mnemonic == "dls" || Mnemonic == "le" || Mnemonic == "csel" ||
6390       Mnemonic == "csinc" || Mnemonic == "csinv" || Mnemonic == "csneg" ||
6391       Mnemonic == "cinc" || Mnemonic == "cinv" || Mnemonic == "cneg" ||
6392       Mnemonic == "cset" || Mnemonic == "csetm" ||
6393       Mnemonic.startswith("vpt") || Mnemonic.startswith("vpst") ||
6394       (hasMVE() &&
6395        (Mnemonic.startswith("vst2") || Mnemonic.startswith("vld2") ||
6396         Mnemonic.startswith("vst4") || Mnemonic.startswith("vld4") ||
6397         Mnemonic.startswith("wlstp") || Mnemonic.startswith("dlstp") ||
6398         Mnemonic.startswith("letp")))) {
6399     // These mnemonics are never predicable
6400     CanAcceptPredicationCode = false;
6401   } else if (!isThumb()) {
6402     // Some instructions are only predicable in Thumb mode
6403     CanAcceptPredicationCode =
6404         Mnemonic != "cdp2" && Mnemonic != "clrex" && Mnemonic != "mcr2" &&
6405         Mnemonic != "mcrr2" && Mnemonic != "mrc2" && Mnemonic != "mrrc2" &&
6406         Mnemonic != "dmb" && Mnemonic != "dfb" && Mnemonic != "dsb" &&
6407         Mnemonic != "isb" && Mnemonic != "pld" && Mnemonic != "pli" &&
6408         Mnemonic != "pldw" && Mnemonic != "ldc2" && Mnemonic != "ldc2l" &&
6409         Mnemonic != "stc2" && Mnemonic != "stc2l" &&
6410         Mnemonic != "tsb" &&
6411         !Mnemonic.startswith("rfe") && !Mnemonic.startswith("srs");
6412   } else if (isThumbOne()) {
6413     if (hasV6MOps())
6414       CanAcceptPredicationCode = Mnemonic != "movs";
6415     else
6416       CanAcceptPredicationCode = Mnemonic != "nop" && Mnemonic != "movs";
6417   } else
6418     CanAcceptPredicationCode = true;
6419 }
6420 
6421 // Some Thumb instructions have two operand forms that are not
6422 // available as three operand, convert to two operand form if possible.
6423 //
6424 // FIXME: We would really like to be able to tablegen'erate this.
6425 void ARMAsmParser::tryConvertingToTwoOperandForm(StringRef Mnemonic,
6426                                                  bool CarrySetting,
6427                                                  OperandVector &Operands) {
6428   if (Operands.size() != 6)
6429     return;
6430 
6431   const auto &Op3 = static_cast<ARMOperand &>(*Operands[3]);
6432         auto &Op4 = static_cast<ARMOperand &>(*Operands[4]);
6433   if (!Op3.isReg() || !Op4.isReg())
6434     return;
6435 
6436   auto Op3Reg = Op3.getReg();
6437   auto Op4Reg = Op4.getReg();
6438 
6439   // For most Thumb2 cases we just generate the 3 operand form and reduce
6440   // it in processInstruction(), but the 3 operand form of ADD (t2ADDrr)
6441   // won't accept SP or PC so we do the transformation here taking care
6442   // with immediate range in the 'add sp, sp #imm' case.
6443   auto &Op5 = static_cast<ARMOperand &>(*Operands[5]);
6444   if (isThumbTwo()) {
6445     if (Mnemonic != "add")
6446       return;
6447     bool TryTransform = Op3Reg == ARM::PC || Op4Reg == ARM::PC ||
6448                         (Op5.isReg() && Op5.getReg() == ARM::PC);
6449     if (!TryTransform) {
6450       TryTransform = (Op3Reg == ARM::SP || Op4Reg == ARM::SP ||
6451                       (Op5.isReg() && Op5.getReg() == ARM::SP)) &&
6452                      !(Op3Reg == ARM::SP && Op4Reg == ARM::SP &&
6453                        Op5.isImm() && !Op5.isImm0_508s4());
6454     }
6455     if (!TryTransform)
6456       return;
6457   } else if (!isThumbOne())
6458     return;
6459 
6460   if (!(Mnemonic == "add" || Mnemonic == "sub" || Mnemonic == "and" ||
6461         Mnemonic == "eor" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
6462         Mnemonic == "asr" || Mnemonic == "adc" || Mnemonic == "sbc" ||
6463         Mnemonic == "ror" || Mnemonic == "orr" || Mnemonic == "bic"))
6464     return;
6465 
6466   // If first 2 operands of a 3 operand instruction are the same
6467   // then transform to 2 operand version of the same instruction
6468   // e.g. 'adds r0, r0, #1' transforms to 'adds r0, #1'
6469   bool Transform = Op3Reg == Op4Reg;
6470 
6471   // For communtative operations, we might be able to transform if we swap
6472   // Op4 and Op5.  The 'ADD Rdm, SP, Rdm' form is already handled specially
6473   // as tADDrsp.
6474   const ARMOperand *LastOp = &Op5;
6475   bool Swap = false;
6476   if (!Transform && Op5.isReg() && Op3Reg == Op5.getReg() &&
6477       ((Mnemonic == "add" && Op4Reg != ARM::SP) ||
6478        Mnemonic == "and" || Mnemonic == "eor" ||
6479        Mnemonic == "adc" || Mnemonic == "orr")) {
6480     Swap = true;
6481     LastOp = &Op4;
6482     Transform = true;
6483   }
6484 
6485   // If both registers are the same then remove one of them from
6486   // the operand list, with certain exceptions.
6487   if (Transform) {
6488     // Don't transform 'adds Rd, Rd, Rm' or 'sub{s} Rd, Rd, Rm' because the
6489     // 2 operand forms don't exist.
6490     if (((Mnemonic == "add" && CarrySetting) || Mnemonic == "sub") &&
6491         LastOp->isReg())
6492       Transform = false;
6493 
6494     // Don't transform 'add/sub{s} Rd, Rd, #imm' if the immediate fits into
6495     // 3-bits because the ARMARM says not to.
6496     if ((Mnemonic == "add" || Mnemonic == "sub") && LastOp->isImm0_7())
6497       Transform = false;
6498   }
6499 
6500   if (Transform) {
6501     if (Swap)
6502       std::swap(Op4, Op5);
6503     Operands.erase(Operands.begin() + 3);
6504   }
6505 }
6506 
6507 bool ARMAsmParser::shouldOmitCCOutOperand(StringRef Mnemonic,
6508                                           OperandVector &Operands) {
6509   // FIXME: This is all horribly hacky. We really need a better way to deal
6510   // with optional operands like this in the matcher table.
6511 
6512   // The 'mov' mnemonic is special. One variant has a cc_out operand, while
6513   // another does not. Specifically, the MOVW instruction does not. So we
6514   // special case it here and remove the defaulted (non-setting) cc_out
6515   // operand if that's the instruction we're trying to match.
6516   //
6517   // We do this as post-processing of the explicit operands rather than just
6518   // conditionally adding the cc_out in the first place because we need
6519   // to check the type of the parsed immediate operand.
6520   if (Mnemonic == "mov" && Operands.size() > 4 && !isThumb() &&
6521       !static_cast<ARMOperand &>(*Operands[4]).isModImm() &&
6522       static_cast<ARMOperand &>(*Operands[4]).isImm0_65535Expr() &&
6523       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0)
6524     return true;
6525 
6526   // Register-register 'add' for thumb does not have a cc_out operand
6527   // when there are only two register operands.
6528   if (isThumb() && Mnemonic == "add" && Operands.size() == 5 &&
6529       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6530       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
6531       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0)
6532     return true;
6533   // Register-register 'add' for thumb does not have a cc_out operand
6534   // when it's an ADD Rdm, SP, {Rdm|#imm0_255} instruction. We do
6535   // have to check the immediate range here since Thumb2 has a variant
6536   // that can handle a different range and has a cc_out operand.
6537   if (((isThumb() && Mnemonic == "add") ||
6538        (isThumbTwo() && Mnemonic == "sub")) &&
6539       Operands.size() == 6 && static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6540       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
6541       static_cast<ARMOperand &>(*Operands[4]).getReg() == ARM::SP &&
6542       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
6543       ((Mnemonic == "add" && static_cast<ARMOperand &>(*Operands[5]).isReg()) ||
6544        static_cast<ARMOperand &>(*Operands[5]).isImm0_1020s4()))
6545     return true;
6546   // For Thumb2, add/sub immediate does not have a cc_out operand for the
6547   // imm0_4095 variant. That's the least-preferred variant when
6548   // selecting via the generic "add" mnemonic, so to know that we
6549   // should remove the cc_out operand, we have to explicitly check that
6550   // it's not one of the other variants. Ugh.
6551   if (isThumbTwo() && (Mnemonic == "add" || Mnemonic == "sub") &&
6552       Operands.size() == 6 && static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6553       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
6554       static_cast<ARMOperand &>(*Operands[5]).isImm()) {
6555     // Nest conditions rather than one big 'if' statement for readability.
6556     //
6557     // If both registers are low, we're in an IT block, and the immediate is
6558     // in range, we should use encoding T1 instead, which has a cc_out.
6559     if (inITBlock() &&
6560         isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) &&
6561         isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) &&
6562         static_cast<ARMOperand &>(*Operands[5]).isImm0_7())
6563       return false;
6564     // Check against T3. If the second register is the PC, this is an
6565     // alternate form of ADR, which uses encoding T4, so check for that too.
6566     if (static_cast<ARMOperand &>(*Operands[4]).getReg() != ARM::PC &&
6567         (static_cast<ARMOperand &>(*Operands[5]).isT2SOImm() ||
6568          static_cast<ARMOperand &>(*Operands[5]).isT2SOImmNeg()))
6569       return false;
6570 
6571     // Otherwise, we use encoding T4, which does not have a cc_out
6572     // operand.
6573     return true;
6574   }
6575 
6576   // The thumb2 multiply instruction doesn't have a CCOut register, so
6577   // if we have a "mul" mnemonic in Thumb mode, check if we'll be able to
6578   // use the 16-bit encoding or not.
6579   if (isThumbTwo() && Mnemonic == "mul" && Operands.size() == 6 &&
6580       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
6581       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6582       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
6583       static_cast<ARMOperand &>(*Operands[5]).isReg() &&
6584       // If the registers aren't low regs, the destination reg isn't the
6585       // same as one of the source regs, or the cc_out operand is zero
6586       // outside of an IT block, we have to use the 32-bit encoding, so
6587       // remove the cc_out operand.
6588       (!isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) ||
6589        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) ||
6590        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[5]).getReg()) ||
6591        !inITBlock() || (static_cast<ARMOperand &>(*Operands[3]).getReg() !=
6592                             static_cast<ARMOperand &>(*Operands[5]).getReg() &&
6593                         static_cast<ARMOperand &>(*Operands[3]).getReg() !=
6594                             static_cast<ARMOperand &>(*Operands[4]).getReg())))
6595     return true;
6596 
6597   // Also check the 'mul' syntax variant that doesn't specify an explicit
6598   // destination register.
6599   if (isThumbTwo() && Mnemonic == "mul" && Operands.size() == 5 &&
6600       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
6601       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6602       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
6603       // If the registers aren't low regs  or the cc_out operand is zero
6604       // outside of an IT block, we have to use the 32-bit encoding, so
6605       // remove the cc_out operand.
6606       (!isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) ||
6607        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) ||
6608        !inITBlock()))
6609     return true;
6610 
6611   // Register-register 'add/sub' for thumb does not have a cc_out operand
6612   // when it's an ADD/SUB SP, #imm. Be lenient on count since there's also
6613   // the "add/sub SP, SP, #imm" version. If the follow-up operands aren't
6614   // right, this will result in better diagnostics (which operand is off)
6615   // anyway.
6616   if (isThumb() && (Mnemonic == "add" || Mnemonic == "sub") &&
6617       (Operands.size() == 5 || Operands.size() == 6) &&
6618       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6619       static_cast<ARMOperand &>(*Operands[3]).getReg() == ARM::SP &&
6620       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
6621       (static_cast<ARMOperand &>(*Operands[4]).isImm() ||
6622        (Operands.size() == 6 &&
6623         static_cast<ARMOperand &>(*Operands[5]).isImm()))) {
6624     // Thumb2 (add|sub){s}{p}.w GPRnopc, sp, #{T2SOImm} has cc_out
6625     return (!(isThumbTwo() &&
6626               (static_cast<ARMOperand &>(*Operands[4]).isT2SOImm() ||
6627                static_cast<ARMOperand &>(*Operands[4]).isT2SOImmNeg())));
6628   }
6629   // Fixme: Should join all the thumb+thumb2 (add|sub) in a single if case
6630   // Thumb2 ADD r0, #4095 -> ADDW r0, r0, #4095 (T4)
6631   // Thumb2 SUB r0, #4095 -> SUBW r0, r0, #4095
6632   if (isThumbTwo() && (Mnemonic == "add" || Mnemonic == "sub") &&
6633       (Operands.size() == 5) &&
6634       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6635       static_cast<ARMOperand &>(*Operands[3]).getReg() != ARM::SP &&
6636       static_cast<ARMOperand &>(*Operands[3]).getReg() != ARM::PC &&
6637       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
6638       static_cast<ARMOperand &>(*Operands[4]).isImm()) {
6639     const ARMOperand &IMM = static_cast<ARMOperand &>(*Operands[4]);
6640     if (IMM.isT2SOImm() || IMM.isT2SOImmNeg())
6641       return false; // add.w / sub.w
6642     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(IMM.getImm())) {
6643       const int64_t Value = CE->getValue();
6644       // Thumb1 imm8 sub / add
6645       if ((Value < ((1 << 7) - 1) << 2) && inITBlock() && (!(Value & 3)) &&
6646           isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()))
6647         return false;
6648       return true; // Thumb2 T4 addw / subw
6649     }
6650   }
6651   return false;
6652 }
6653 
6654 bool ARMAsmParser::shouldOmitPredicateOperand(StringRef Mnemonic,
6655                                               OperandVector &Operands) {
6656   // VRINT{Z, X} have a predicate operand in VFP, but not in NEON
6657   unsigned RegIdx = 3;
6658   if ((((Mnemonic == "vrintz" || Mnemonic == "vrintx") && !hasMVE()) ||
6659       Mnemonic == "vrintr") &&
6660       (static_cast<ARMOperand &>(*Operands[2]).getToken() == ".f32" ||
6661        static_cast<ARMOperand &>(*Operands[2]).getToken() == ".f16")) {
6662     if (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
6663         (static_cast<ARMOperand &>(*Operands[3]).getToken() == ".f32" ||
6664          static_cast<ARMOperand &>(*Operands[3]).getToken() == ".f16"))
6665       RegIdx = 4;
6666 
6667     if (static_cast<ARMOperand &>(*Operands[RegIdx]).isReg() &&
6668         (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(
6669              static_cast<ARMOperand &>(*Operands[RegIdx]).getReg()) ||
6670          ARMMCRegisterClasses[ARM::QPRRegClassID].contains(
6671              static_cast<ARMOperand &>(*Operands[RegIdx]).getReg())))
6672       return true;
6673   }
6674   return false;
6675 }
6676 
6677 bool ARMAsmParser::shouldOmitVectorPredicateOperand(StringRef Mnemonic,
6678                                                     OperandVector &Operands) {
6679   if (!hasMVE() || Operands.size() < 3)
6680     return true;
6681 
6682   if (Mnemonic.startswith("vld2") || Mnemonic.startswith("vld4") ||
6683       Mnemonic.startswith("vst2") || Mnemonic.startswith("vst4"))
6684     return true;
6685 
6686   if (Mnemonic.startswith("vctp") || Mnemonic.startswith("vpnot"))
6687     return false;
6688 
6689   if (Mnemonic.startswith("vmov") &&
6690       !(Mnemonic.startswith("vmovl") || Mnemonic.startswith("vmovn") ||
6691         Mnemonic.startswith("vmovx"))) {
6692     for (auto &Operand : Operands) {
6693       if (static_cast<ARMOperand &>(*Operand).isVectorIndex() ||
6694           ((*Operand).isReg() &&
6695            (ARMMCRegisterClasses[ARM::SPRRegClassID].contains(
6696              (*Operand).getReg()) ||
6697             ARMMCRegisterClasses[ARM::DPRRegClassID].contains(
6698               (*Operand).getReg())))) {
6699         return true;
6700       }
6701     }
6702     return false;
6703   } else {
6704     for (auto &Operand : Operands) {
6705       // We check the larger class QPR instead of just the legal class
6706       // MQPR, to more accurately report errors when using Q registers
6707       // outside of the allowed range.
6708       if (static_cast<ARMOperand &>(*Operand).isVectorIndex() ||
6709           (Operand->isReg() &&
6710            (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(
6711              Operand->getReg()))))
6712         return false;
6713     }
6714     return true;
6715   }
6716 }
6717 
6718 static bool isDataTypeToken(StringRef Tok) {
6719   return Tok == ".8" || Tok == ".16" || Tok == ".32" || Tok == ".64" ||
6720     Tok == ".i8" || Tok == ".i16" || Tok == ".i32" || Tok == ".i64" ||
6721     Tok == ".u8" || Tok == ".u16" || Tok == ".u32" || Tok == ".u64" ||
6722     Tok == ".s8" || Tok == ".s16" || Tok == ".s32" || Tok == ".s64" ||
6723     Tok == ".p8" || Tok == ".p16" || Tok == ".f32" || Tok == ".f64" ||
6724     Tok == ".f" || Tok == ".d";
6725 }
6726 
6727 // FIXME: This bit should probably be handled via an explicit match class
6728 // in the .td files that matches the suffix instead of having it be
6729 // a literal string token the way it is now.
6730 static bool doesIgnoreDataTypeSuffix(StringRef Mnemonic, StringRef DT) {
6731   return Mnemonic.startswith("vldm") || Mnemonic.startswith("vstm");
6732 }
6733 
6734 static void applyMnemonicAliases(StringRef &Mnemonic,
6735                                  const FeatureBitset &Features,
6736                                  unsigned VariantID);
6737 
6738 // The GNU assembler has aliases of ldrd and strd with the second register
6739 // omitted. We don't have a way to do that in tablegen, so fix it up here.
6740 //
6741 // We have to be careful to not emit an invalid Rt2 here, because the rest of
6742 // the assembly parser could then generate confusing diagnostics refering to
6743 // it. If we do find anything that prevents us from doing the transformation we
6744 // bail out, and let the assembly parser report an error on the instruction as
6745 // it is written.
6746 void ARMAsmParser::fixupGNULDRDAlias(StringRef Mnemonic,
6747                                      OperandVector &Operands) {
6748   if (Mnemonic != "ldrd" && Mnemonic != "strd")
6749     return;
6750   if (Operands.size() < 4)
6751     return;
6752 
6753   ARMOperand &Op2 = static_cast<ARMOperand &>(*Operands[2]);
6754   ARMOperand &Op3 = static_cast<ARMOperand &>(*Operands[3]);
6755 
6756   if (!Op2.isReg())
6757     return;
6758   if (!Op3.isGPRMem())
6759     return;
6760 
6761   const MCRegisterClass &GPR = MRI->getRegClass(ARM::GPRRegClassID);
6762   if (!GPR.contains(Op2.getReg()))
6763     return;
6764 
6765   unsigned RtEncoding = MRI->getEncodingValue(Op2.getReg());
6766   if (!isThumb() && (RtEncoding & 1)) {
6767     // In ARM mode, the registers must be from an aligned pair, this
6768     // restriction does not apply in Thumb mode.
6769     return;
6770   }
6771   if (Op2.getReg() == ARM::PC)
6772     return;
6773   unsigned PairedReg = GPR.getRegister(RtEncoding + 1);
6774   if (!PairedReg || PairedReg == ARM::PC ||
6775       (PairedReg == ARM::SP && !hasV8Ops()))
6776     return;
6777 
6778   Operands.insert(
6779       Operands.begin() + 3,
6780       ARMOperand::CreateReg(PairedReg, Op2.getStartLoc(), Op2.getEndLoc()));
6781 }
6782 
6783 /// Parse an arm instruction mnemonic followed by its operands.
6784 bool ARMAsmParser::ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
6785                                     SMLoc NameLoc, OperandVector &Operands) {
6786   MCAsmParser &Parser = getParser();
6787 
6788   // Apply mnemonic aliases before doing anything else, as the destination
6789   // mnemonic may include suffices and we want to handle them normally.
6790   // The generic tblgen'erated code does this later, at the start of
6791   // MatchInstructionImpl(), but that's too late for aliases that include
6792   // any sort of suffix.
6793   const FeatureBitset &AvailableFeatures = getAvailableFeatures();
6794   unsigned AssemblerDialect = getParser().getAssemblerDialect();
6795   applyMnemonicAliases(Name, AvailableFeatures, AssemblerDialect);
6796 
6797   // First check for the ARM-specific .req directive.
6798   if (Parser.getTok().is(AsmToken::Identifier) &&
6799       Parser.getTok().getIdentifier().lower() == ".req") {
6800     parseDirectiveReq(Name, NameLoc);
6801     // We always return 'error' for this, as we're done with this
6802     // statement and don't need to match the 'instruction."
6803     return true;
6804   }
6805 
6806   // Create the leading tokens for the mnemonic, split by '.' characters.
6807   size_t Start = 0, Next = Name.find('.');
6808   StringRef Mnemonic = Name.slice(Start, Next);
6809   StringRef ExtraToken = Name.slice(Next, Name.find(' ', Next + 1));
6810 
6811   // Split out the predication code and carry setting flag from the mnemonic.
6812   unsigned PredicationCode;
6813   unsigned VPTPredicationCode;
6814   unsigned ProcessorIMod;
6815   bool CarrySetting;
6816   StringRef ITMask;
6817   Mnemonic = splitMnemonic(Mnemonic, ExtraToken, PredicationCode, VPTPredicationCode,
6818                            CarrySetting, ProcessorIMod, ITMask);
6819 
6820   // In Thumb1, only the branch (B) instruction can be predicated.
6821   if (isThumbOne() && PredicationCode != ARMCC::AL && Mnemonic != "b") {
6822     return Error(NameLoc, "conditional execution not supported in Thumb1");
6823   }
6824 
6825   Operands.push_back(ARMOperand::CreateToken(Mnemonic, NameLoc));
6826 
6827   // Handle the mask for IT and VPT instructions. In ARMOperand and
6828   // MCOperand, this is stored in a format independent of the
6829   // condition code: the lowest set bit indicates the end of the
6830   // encoding, and above that, a 1 bit indicates 'else', and an 0
6831   // indicates 'then'. E.g.
6832   //    IT    -> 1000
6833   //    ITx   -> x100    (ITT -> 0100, ITE -> 1100)
6834   //    ITxy  -> xy10    (e.g. ITET -> 1010)
6835   //    ITxyz -> xyz1    (e.g. ITEET -> 1101)
6836   if (Mnemonic == "it" || Mnemonic.startswith("vpt") ||
6837       Mnemonic.startswith("vpst")) {
6838     SMLoc Loc = Mnemonic == "it"  ? SMLoc::getFromPointer(NameLoc.getPointer() + 2) :
6839                 Mnemonic == "vpt" ? SMLoc::getFromPointer(NameLoc.getPointer() + 3) :
6840                                     SMLoc::getFromPointer(NameLoc.getPointer() + 4);
6841     if (ITMask.size() > 3) {
6842       if (Mnemonic == "it")
6843         return Error(Loc, "too many conditions on IT instruction");
6844       return Error(Loc, "too many conditions on VPT instruction");
6845     }
6846     unsigned Mask = 8;
6847     for (unsigned i = ITMask.size(); i != 0; --i) {
6848       char pos = ITMask[i - 1];
6849       if (pos != 't' && pos != 'e') {
6850         return Error(Loc, "illegal IT block condition mask '" + ITMask + "'");
6851       }
6852       Mask >>= 1;
6853       if (ITMask[i - 1] == 'e')
6854         Mask |= 8;
6855     }
6856     Operands.push_back(ARMOperand::CreateITMask(Mask, Loc));
6857   }
6858 
6859   // FIXME: This is all a pretty gross hack. We should automatically handle
6860   // optional operands like this via tblgen.
6861 
6862   // Next, add the CCOut and ConditionCode operands, if needed.
6863   //
6864   // For mnemonics which can ever incorporate a carry setting bit or predication
6865   // code, our matching model involves us always generating CCOut and
6866   // ConditionCode operands to match the mnemonic "as written" and then we let
6867   // the matcher deal with finding the right instruction or generating an
6868   // appropriate error.
6869   bool CanAcceptCarrySet, CanAcceptPredicationCode, CanAcceptVPTPredicationCode;
6870   getMnemonicAcceptInfo(Mnemonic, ExtraToken, Name, CanAcceptCarrySet,
6871                         CanAcceptPredicationCode, CanAcceptVPTPredicationCode);
6872 
6873   // If we had a carry-set on an instruction that can't do that, issue an
6874   // error.
6875   if (!CanAcceptCarrySet && CarrySetting) {
6876     return Error(NameLoc, "instruction '" + Mnemonic +
6877                  "' can not set flags, but 's' suffix specified");
6878   }
6879   // If we had a predication code on an instruction that can't do that, issue an
6880   // error.
6881   if (!CanAcceptPredicationCode && PredicationCode != ARMCC::AL) {
6882     return Error(NameLoc, "instruction '" + Mnemonic +
6883                  "' is not predicable, but condition code specified");
6884   }
6885 
6886   // If we had a VPT predication code on an instruction that can't do that, issue an
6887   // error.
6888   if (!CanAcceptVPTPredicationCode && VPTPredicationCode != ARMVCC::None) {
6889     return Error(NameLoc, "instruction '" + Mnemonic +
6890                  "' is not VPT predicable, but VPT code T/E is specified");
6891   }
6892 
6893   // Add the carry setting operand, if necessary.
6894   if (CanAcceptCarrySet) {
6895     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size());
6896     Operands.push_back(ARMOperand::CreateCCOut(CarrySetting ? ARM::CPSR : 0,
6897                                                Loc));
6898   }
6899 
6900   // Add the predication code operand, if necessary.
6901   if (CanAcceptPredicationCode) {
6902     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size() +
6903                                       CarrySetting);
6904     Operands.push_back(ARMOperand::CreateCondCode(
6905                        ARMCC::CondCodes(PredicationCode), Loc));
6906   }
6907 
6908   // Add the VPT predication code operand, if necessary.
6909   // FIXME: We don't add them for the instructions filtered below as these can
6910   // have custom operands which need special parsing.  This parsing requires
6911   // the operand to be in the same place in the OperandVector as their
6912   // definition in tblgen.  Since these instructions may also have the
6913   // scalar predication operand we do not add the vector one and leave until
6914   // now to fix it up.
6915   if (CanAcceptVPTPredicationCode && Mnemonic != "vmov" &&
6916       !Mnemonic.startswith("vcmp") &&
6917       !(Mnemonic.startswith("vcvt") && Mnemonic != "vcvta" &&
6918         Mnemonic != "vcvtn" && Mnemonic != "vcvtp" && Mnemonic != "vcvtm")) {
6919     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size() +
6920                                       CarrySetting);
6921     Operands.push_back(ARMOperand::CreateVPTPred(
6922                          ARMVCC::VPTCodes(VPTPredicationCode), Loc));
6923   }
6924 
6925   // Add the processor imod operand, if necessary.
6926   if (ProcessorIMod) {
6927     Operands.push_back(ARMOperand::CreateImm(
6928           MCConstantExpr::create(ProcessorIMod, getContext()),
6929                                  NameLoc, NameLoc));
6930   } else if (Mnemonic == "cps" && isMClass()) {
6931     return Error(NameLoc, "instruction 'cps' requires effect for M-class");
6932   }
6933 
6934   // Add the remaining tokens in the mnemonic.
6935   while (Next != StringRef::npos) {
6936     Start = Next;
6937     Next = Name.find('.', Start + 1);
6938     ExtraToken = Name.slice(Start, Next);
6939 
6940     // Some NEON instructions have an optional datatype suffix that is
6941     // completely ignored. Check for that.
6942     if (isDataTypeToken(ExtraToken) &&
6943         doesIgnoreDataTypeSuffix(Mnemonic, ExtraToken))
6944       continue;
6945 
6946     // For for ARM mode generate an error if the .n qualifier is used.
6947     if (ExtraToken == ".n" && !isThumb()) {
6948       SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Start);
6949       return Error(Loc, "instruction with .n (narrow) qualifier not allowed in "
6950                    "arm mode");
6951     }
6952 
6953     // The .n qualifier is always discarded as that is what the tables
6954     // and matcher expect.  In ARM mode the .w qualifier has no effect,
6955     // so discard it to avoid errors that can be caused by the matcher.
6956     if (ExtraToken != ".n" && (isThumb() || ExtraToken != ".w")) {
6957       SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Start);
6958       Operands.push_back(ARMOperand::CreateToken(ExtraToken, Loc));
6959     }
6960   }
6961 
6962   // Read the remaining operands.
6963   if (getLexer().isNot(AsmToken::EndOfStatement)) {
6964     // Read the first operand.
6965     if (parseOperand(Operands, Mnemonic)) {
6966       return true;
6967     }
6968 
6969     while (parseOptionalToken(AsmToken::Comma)) {
6970       // Parse and remember the operand.
6971       if (parseOperand(Operands, Mnemonic)) {
6972         return true;
6973       }
6974     }
6975   }
6976 
6977   if (parseToken(AsmToken::EndOfStatement, "unexpected token in argument list"))
6978     return true;
6979 
6980   tryConvertingToTwoOperandForm(Mnemonic, CarrySetting, Operands);
6981 
6982   // Some instructions, mostly Thumb, have forms for the same mnemonic that
6983   // do and don't have a cc_out optional-def operand. With some spot-checks
6984   // of the operand list, we can figure out which variant we're trying to
6985   // parse and adjust accordingly before actually matching. We shouldn't ever
6986   // try to remove a cc_out operand that was explicitly set on the
6987   // mnemonic, of course (CarrySetting == true). Reason number #317 the
6988   // table driven matcher doesn't fit well with the ARM instruction set.
6989   if (!CarrySetting && shouldOmitCCOutOperand(Mnemonic, Operands))
6990     Operands.erase(Operands.begin() + 1);
6991 
6992   // Some instructions have the same mnemonic, but don't always
6993   // have a predicate. Distinguish them here and delete the
6994   // appropriate predicate if needed.  This could be either the scalar
6995   // predication code or the vector predication code.
6996   if (PredicationCode == ARMCC::AL &&
6997       shouldOmitPredicateOperand(Mnemonic, Operands))
6998     Operands.erase(Operands.begin() + 1);
6999 
7000 
7001   if (hasMVE()) {
7002     if (!shouldOmitVectorPredicateOperand(Mnemonic, Operands) &&
7003         Mnemonic == "vmov" && PredicationCode == ARMCC::LT) {
7004       // Very nasty hack to deal with the vector predicated variant of vmovlt
7005       // the scalar predicated vmov with condition 'lt'.  We can not tell them
7006       // apart until we have parsed their operands.
7007       Operands.erase(Operands.begin() + 1);
7008       Operands.erase(Operands.begin());
7009       SMLoc MLoc = SMLoc::getFromPointer(NameLoc.getPointer());
7010       SMLoc PLoc = SMLoc::getFromPointer(NameLoc.getPointer() +
7011                                          Mnemonic.size() - 1 + CarrySetting);
7012       Operands.insert(Operands.begin(),
7013                       ARMOperand::CreateVPTPred(ARMVCC::None, PLoc));
7014       Operands.insert(Operands.begin(),
7015                       ARMOperand::CreateToken(StringRef("vmovlt"), MLoc));
7016     } else if (Mnemonic == "vcvt" && PredicationCode == ARMCC::NE &&
7017                !shouldOmitVectorPredicateOperand(Mnemonic, Operands)) {
7018       // Another nasty hack to deal with the ambiguity between vcvt with scalar
7019       // predication 'ne' and vcvtn with vector predication 'e'.  As above we
7020       // can only distinguish between the two after we have parsed their
7021       // operands.
7022       Operands.erase(Operands.begin() + 1);
7023       Operands.erase(Operands.begin());
7024       SMLoc MLoc = SMLoc::getFromPointer(NameLoc.getPointer());
7025       SMLoc PLoc = SMLoc::getFromPointer(NameLoc.getPointer() +
7026                                          Mnemonic.size() - 1 + CarrySetting);
7027       Operands.insert(Operands.begin(),
7028                       ARMOperand::CreateVPTPred(ARMVCC::Else, PLoc));
7029       Operands.insert(Operands.begin(),
7030                       ARMOperand::CreateToken(StringRef("vcvtn"), MLoc));
7031     } else if (Mnemonic == "vmul" && PredicationCode == ARMCC::LT &&
7032                !shouldOmitVectorPredicateOperand(Mnemonic, Operands)) {
7033       // Another hack, this time to distinguish between scalar predicated vmul
7034       // with 'lt' predication code and the vector instruction vmullt with
7035       // vector predication code "none"
7036       Operands.erase(Operands.begin() + 1);
7037       Operands.erase(Operands.begin());
7038       SMLoc MLoc = SMLoc::getFromPointer(NameLoc.getPointer());
7039       Operands.insert(Operands.begin(),
7040                       ARMOperand::CreateToken(StringRef("vmullt"), MLoc));
7041     }
7042     // For vmov and vcmp, as mentioned earlier, we did not add the vector
7043     // predication code, since these may contain operands that require
7044     // special parsing.  So now we have to see if they require vector
7045     // predication and replace the scalar one with the vector predication
7046     // operand if that is the case.
7047     else if (Mnemonic == "vmov" || Mnemonic.startswith("vcmp") ||
7048              (Mnemonic.startswith("vcvt") && !Mnemonic.startswith("vcvta") &&
7049               !Mnemonic.startswith("vcvtn") && !Mnemonic.startswith("vcvtp") &&
7050               !Mnemonic.startswith("vcvtm"))) {
7051       if (!shouldOmitVectorPredicateOperand(Mnemonic, Operands)) {
7052         // We could not split the vector predicate off vcvt because it might
7053         // have been the scalar vcvtt instruction.  Now we know its a vector
7054         // instruction, we still need to check whether its the vector
7055         // predicated vcvt with 'Then' predication or the vector vcvtt.  We can
7056         // distinguish the two based on the suffixes, if it is any of
7057         // ".f16.f32", ".f32.f16", ".f16.f64" or ".f64.f16" then it is the vcvtt.
7058         if (Mnemonic.startswith("vcvtt") && Operands.size() >= 4) {
7059           auto Sz1 = static_cast<ARMOperand &>(*Operands[2]);
7060           auto Sz2 = static_cast<ARMOperand &>(*Operands[3]);
7061           if (!(Sz1.isToken() && Sz1.getToken().startswith(".f") &&
7062               Sz2.isToken() && Sz2.getToken().startswith(".f"))) {
7063             Operands.erase(Operands.begin());
7064             SMLoc MLoc = SMLoc::getFromPointer(NameLoc.getPointer());
7065             VPTPredicationCode = ARMVCC::Then;
7066 
7067             Mnemonic = Mnemonic.substr(0, 4);
7068             Operands.insert(Operands.begin(),
7069                             ARMOperand::CreateToken(Mnemonic, MLoc));
7070           }
7071         }
7072         Operands.erase(Operands.begin() + 1);
7073         SMLoc PLoc = SMLoc::getFromPointer(NameLoc.getPointer() +
7074                                           Mnemonic.size() + CarrySetting);
7075         Operands.insert(Operands.begin() + 1,
7076                         ARMOperand::CreateVPTPred(
7077                             ARMVCC::VPTCodes(VPTPredicationCode), PLoc));
7078       }
7079     } else if (CanAcceptVPTPredicationCode) {
7080       // For all other instructions, make sure only one of the two
7081       // predication operands is left behind, depending on whether we should
7082       // use the vector predication.
7083       if (shouldOmitVectorPredicateOperand(Mnemonic, Operands)) {
7084         if (CanAcceptPredicationCode)
7085           Operands.erase(Operands.begin() + 2);
7086         else
7087           Operands.erase(Operands.begin() + 1);
7088       } else if (CanAcceptPredicationCode && PredicationCode == ARMCC::AL) {
7089         Operands.erase(Operands.begin() + 1);
7090       }
7091     }
7092   }
7093 
7094   if (VPTPredicationCode != ARMVCC::None) {
7095     bool usedVPTPredicationCode = false;
7096     for (unsigned I = 1; I < Operands.size(); ++I)
7097       if (static_cast<ARMOperand &>(*Operands[I]).isVPTPred())
7098         usedVPTPredicationCode = true;
7099     if (!usedVPTPredicationCode) {
7100       // If we have a VPT predication code and we haven't just turned it
7101       // into an operand, then it was a mistake for splitMnemonic to
7102       // separate it from the rest of the mnemonic in the first place,
7103       // and this may lead to wrong disassembly (e.g. scalar floating
7104       // point VCMPE is actually a different instruction from VCMP, so
7105       // we mustn't treat them the same). In that situation, glue it
7106       // back on.
7107       Mnemonic = Name.slice(0, Mnemonic.size() + 1);
7108       Operands.erase(Operands.begin());
7109       Operands.insert(Operands.begin(),
7110                       ARMOperand::CreateToken(Mnemonic, NameLoc));
7111     }
7112   }
7113 
7114     // ARM mode 'blx' need special handling, as the register operand version
7115     // is predicable, but the label operand version is not. So, we can't rely
7116     // on the Mnemonic based checking to correctly figure out when to put
7117     // a k_CondCode operand in the list. If we're trying to match the label
7118     // version, remove the k_CondCode operand here.
7119     if (!isThumb() && Mnemonic == "blx" && Operands.size() == 3 &&
7120         static_cast<ARMOperand &>(*Operands[2]).isImm())
7121       Operands.erase(Operands.begin() + 1);
7122 
7123     // Adjust operands of ldrexd/strexd to MCK_GPRPair.
7124     // ldrexd/strexd require even/odd GPR pair. To enforce this constraint,
7125     // a single GPRPair reg operand is used in the .td file to replace the two
7126     // GPRs. However, when parsing from asm, the two GRPs cannot be
7127     // automatically
7128     // expressed as a GPRPair, so we have to manually merge them.
7129     // FIXME: We would really like to be able to tablegen'erate this.
7130     if (!isThumb() && Operands.size() > 4 &&
7131         (Mnemonic == "ldrexd" || Mnemonic == "strexd" || Mnemonic == "ldaexd" ||
7132          Mnemonic == "stlexd")) {
7133       bool isLoad = (Mnemonic == "ldrexd" || Mnemonic == "ldaexd");
7134       unsigned Idx = isLoad ? 2 : 3;
7135       ARMOperand &Op1 = static_cast<ARMOperand &>(*Operands[Idx]);
7136       ARMOperand &Op2 = static_cast<ARMOperand &>(*Operands[Idx + 1]);
7137 
7138       const MCRegisterClass &MRC = MRI->getRegClass(ARM::GPRRegClassID);
7139       // Adjust only if Op1 and Op2 are GPRs.
7140       if (Op1.isReg() && Op2.isReg() && MRC.contains(Op1.getReg()) &&
7141           MRC.contains(Op2.getReg())) {
7142         unsigned Reg1 = Op1.getReg();
7143         unsigned Reg2 = Op2.getReg();
7144         unsigned Rt = MRI->getEncodingValue(Reg1);
7145         unsigned Rt2 = MRI->getEncodingValue(Reg2);
7146 
7147         // Rt2 must be Rt + 1 and Rt must be even.
7148         if (Rt + 1 != Rt2 || (Rt & 1)) {
7149           return Error(Op2.getStartLoc(),
7150                        isLoad ? "destination operands must be sequential"
7151                               : "source operands must be sequential");
7152         }
7153         unsigned NewReg = MRI->getMatchingSuperReg(
7154             Reg1, ARM::gsub_0, &(MRI->getRegClass(ARM::GPRPairRegClassID)));
7155         Operands[Idx] =
7156             ARMOperand::CreateReg(NewReg, Op1.getStartLoc(), Op2.getEndLoc());
7157         Operands.erase(Operands.begin() + Idx + 1);
7158       }
7159   }
7160 
7161   // GNU Assembler extension (compatibility).
7162   fixupGNULDRDAlias(Mnemonic, Operands);
7163 
7164   // FIXME: As said above, this is all a pretty gross hack.  This instruction
7165   // does not fit with other "subs" and tblgen.
7166   // Adjust operands of B9.3.19 SUBS PC, LR, #imm (Thumb2) system instruction
7167   // so the Mnemonic is the original name "subs" and delete the predicate
7168   // operand so it will match the table entry.
7169   if (isThumbTwo() && Mnemonic == "sub" && Operands.size() == 6 &&
7170       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
7171       static_cast<ARMOperand &>(*Operands[3]).getReg() == ARM::PC &&
7172       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
7173       static_cast<ARMOperand &>(*Operands[4]).getReg() == ARM::LR &&
7174       static_cast<ARMOperand &>(*Operands[5]).isImm()) {
7175     Operands.front() = ARMOperand::CreateToken(Name, NameLoc);
7176     Operands.erase(Operands.begin() + 1);
7177   }
7178   return false;
7179 }
7180 
7181 // Validate context-sensitive operand constraints.
7182 
7183 // return 'true' if register list contains non-low GPR registers,
7184 // 'false' otherwise. If Reg is in the register list or is HiReg, set
7185 // 'containsReg' to true.
7186 static bool checkLowRegisterList(const MCInst &Inst, unsigned OpNo,
7187                                  unsigned Reg, unsigned HiReg,
7188                                  bool &containsReg) {
7189   containsReg = false;
7190   for (unsigned i = OpNo; i < Inst.getNumOperands(); ++i) {
7191     unsigned OpReg = Inst.getOperand(i).getReg();
7192     if (OpReg == Reg)
7193       containsReg = true;
7194     // Anything other than a low register isn't legal here.
7195     if (!isARMLowRegister(OpReg) && (!HiReg || OpReg != HiReg))
7196       return true;
7197   }
7198   return false;
7199 }
7200 
7201 // Check if the specified regisgter is in the register list of the inst,
7202 // starting at the indicated operand number.
7203 static bool listContainsReg(const MCInst &Inst, unsigned OpNo, unsigned Reg) {
7204   for (unsigned i = OpNo, e = Inst.getNumOperands(); i < e; ++i) {
7205     unsigned OpReg = Inst.getOperand(i).getReg();
7206     if (OpReg == Reg)
7207       return true;
7208   }
7209   return false;
7210 }
7211 
7212 // Return true if instruction has the interesting property of being
7213 // allowed in IT blocks, but not being predicable.
7214 static bool instIsBreakpoint(const MCInst &Inst) {
7215     return Inst.getOpcode() == ARM::tBKPT ||
7216            Inst.getOpcode() == ARM::BKPT ||
7217            Inst.getOpcode() == ARM::tHLT ||
7218            Inst.getOpcode() == ARM::HLT;
7219 }
7220 
7221 bool ARMAsmParser::validatetLDMRegList(const MCInst &Inst,
7222                                        const OperandVector &Operands,
7223                                        unsigned ListNo, bool IsARPop) {
7224   const ARMOperand &Op = static_cast<const ARMOperand &>(*Operands[ListNo]);
7225   bool HasWritebackToken = Op.isToken() && Op.getToken() == "!";
7226 
7227   bool ListContainsSP = listContainsReg(Inst, ListNo, ARM::SP);
7228   bool ListContainsLR = listContainsReg(Inst, ListNo, ARM::LR);
7229   bool ListContainsPC = listContainsReg(Inst, ListNo, ARM::PC);
7230 
7231   if (!IsARPop && ListContainsSP)
7232     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
7233                  "SP may not be in the register list");
7234   else if (ListContainsPC && ListContainsLR)
7235     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
7236                  "PC and LR may not be in the register list simultaneously");
7237   return false;
7238 }
7239 
7240 bool ARMAsmParser::validatetSTMRegList(const MCInst &Inst,
7241                                        const OperandVector &Operands,
7242                                        unsigned ListNo) {
7243   const ARMOperand &Op = static_cast<const ARMOperand &>(*Operands[ListNo]);
7244   bool HasWritebackToken = Op.isToken() && Op.getToken() == "!";
7245 
7246   bool ListContainsSP = listContainsReg(Inst, ListNo, ARM::SP);
7247   bool ListContainsPC = listContainsReg(Inst, ListNo, ARM::PC);
7248 
7249   if (ListContainsSP && ListContainsPC)
7250     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
7251                  "SP and PC may not be in the register list");
7252   else if (ListContainsSP)
7253     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
7254                  "SP may not be in the register list");
7255   else if (ListContainsPC)
7256     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
7257                  "PC may not be in the register list");
7258   return false;
7259 }
7260 
7261 bool ARMAsmParser::validateLDRDSTRD(MCInst &Inst,
7262                                     const OperandVector &Operands,
7263                                     bool Load, bool ARMMode, bool Writeback) {
7264   unsigned RtIndex = Load || !Writeback ? 0 : 1;
7265   unsigned Rt = MRI->getEncodingValue(Inst.getOperand(RtIndex).getReg());
7266   unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(RtIndex + 1).getReg());
7267 
7268   if (ARMMode) {
7269     // Rt can't be R14.
7270     if (Rt == 14)
7271       return Error(Operands[3]->getStartLoc(),
7272                   "Rt can't be R14");
7273 
7274     // Rt must be even-numbered.
7275     if ((Rt & 1) == 1)
7276       return Error(Operands[3]->getStartLoc(),
7277                    "Rt must be even-numbered");
7278 
7279     // Rt2 must be Rt + 1.
7280     if (Rt2 != Rt + 1) {
7281       if (Load)
7282         return Error(Operands[3]->getStartLoc(),
7283                      "destination operands must be sequential");
7284       else
7285         return Error(Operands[3]->getStartLoc(),
7286                      "source operands must be sequential");
7287     }
7288 
7289     // FIXME: Diagnose m == 15
7290     // FIXME: Diagnose ldrd with m == t || m == t2.
7291   }
7292 
7293   if (!ARMMode && Load) {
7294     if (Rt2 == Rt)
7295       return Error(Operands[3]->getStartLoc(),
7296                    "destination operands can't be identical");
7297   }
7298 
7299   if (Writeback) {
7300     unsigned Rn = MRI->getEncodingValue(Inst.getOperand(3).getReg());
7301 
7302     if (Rn == Rt || Rn == Rt2) {
7303       if (Load)
7304         return Error(Operands[3]->getStartLoc(),
7305                      "base register needs to be different from destination "
7306                      "registers");
7307       else
7308         return Error(Operands[3]->getStartLoc(),
7309                      "source register and base register can't be identical");
7310     }
7311 
7312     // FIXME: Diagnose ldrd/strd with writeback and n == 15.
7313     // (Except the immediate form of ldrd?)
7314   }
7315 
7316   return false;
7317 }
7318 
7319 static int findFirstVectorPredOperandIdx(const MCInstrDesc &MCID) {
7320   for (unsigned i = 0; i < MCID.NumOperands; ++i) {
7321     if (ARM::isVpred(MCID.OpInfo[i].OperandType))
7322       return i;
7323   }
7324   return -1;
7325 }
7326 
7327 static bool isVectorPredicable(const MCInstrDesc &MCID) {
7328   return findFirstVectorPredOperandIdx(MCID) != -1;
7329 }
7330 
7331 // FIXME: We would really like to be able to tablegen'erate this.
7332 bool ARMAsmParser::validateInstruction(MCInst &Inst,
7333                                        const OperandVector &Operands) {
7334   const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
7335   SMLoc Loc = Operands[0]->getStartLoc();
7336 
7337   // Check the IT block state first.
7338   // NOTE: BKPT and HLT instructions have the interesting property of being
7339   // allowed in IT blocks, but not being predicable. They just always execute.
7340   if (inITBlock() && !instIsBreakpoint(Inst)) {
7341     // The instruction must be predicable.
7342     if (!MCID.isPredicable())
7343       return Error(Loc, "instructions in IT block must be predicable");
7344     ARMCC::CondCodes Cond = ARMCC::CondCodes(
7345         Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm());
7346     if (Cond != currentITCond()) {
7347       // Find the condition code Operand to get its SMLoc information.
7348       SMLoc CondLoc;
7349       for (unsigned I = 1; I < Operands.size(); ++I)
7350         if (static_cast<ARMOperand &>(*Operands[I]).isCondCode())
7351           CondLoc = Operands[I]->getStartLoc();
7352       return Error(CondLoc, "incorrect condition in IT block; got '" +
7353                                 StringRef(ARMCondCodeToString(Cond)) +
7354                                 "', but expected '" +
7355                                 ARMCondCodeToString(currentITCond()) + "'");
7356     }
7357   // Check for non-'al' condition codes outside of the IT block.
7358   } else if (isThumbTwo() && MCID.isPredicable() &&
7359              Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm() !=
7360              ARMCC::AL && Inst.getOpcode() != ARM::tBcc &&
7361              Inst.getOpcode() != ARM::t2Bcc &&
7362              Inst.getOpcode() != ARM::t2BFic) {
7363     return Error(Loc, "predicated instructions must be in IT block");
7364   } else if (!isThumb() && !useImplicitITARM() && MCID.isPredicable() &&
7365              Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm() !=
7366                  ARMCC::AL) {
7367     return Warning(Loc, "predicated instructions should be in IT block");
7368   } else if (!MCID.isPredicable()) {
7369     // Check the instruction doesn't have a predicate operand anyway
7370     // that it's not allowed to use. Sometimes this happens in order
7371     // to keep instructions the same shape even though one cannot
7372     // legally be predicated, e.g. vmul.f16 vs vmul.f32.
7373     for (unsigned i = 0, e = MCID.getNumOperands(); i != e; ++i) {
7374       if (MCID.OpInfo[i].isPredicate()) {
7375         if (Inst.getOperand(i).getImm() != ARMCC::AL)
7376           return Error(Loc, "instruction is not predicable");
7377         break;
7378       }
7379     }
7380   }
7381 
7382   // PC-setting instructions in an IT block, but not the last instruction of
7383   // the block, are UNPREDICTABLE.
7384   if (inExplicitITBlock() && !lastInITBlock() && isITBlockTerminator(Inst)) {
7385     return Error(Loc, "instruction must be outside of IT block or the last instruction in an IT block");
7386   }
7387 
7388   if (inVPTBlock() && !instIsBreakpoint(Inst)) {
7389     unsigned Bit = extractITMaskBit(VPTState.Mask, VPTState.CurPosition);
7390     if (!isVectorPredicable(MCID))
7391       return Error(Loc, "instruction in VPT block must be predicable");
7392     unsigned Pred = Inst.getOperand(findFirstVectorPredOperandIdx(MCID)).getImm();
7393     unsigned VPTPred = Bit ? ARMVCC::Else : ARMVCC::Then;
7394     if (Pred != VPTPred) {
7395       SMLoc PredLoc;
7396       for (unsigned I = 1; I < Operands.size(); ++I)
7397         if (static_cast<ARMOperand &>(*Operands[I]).isVPTPred())
7398           PredLoc = Operands[I]->getStartLoc();
7399       return Error(PredLoc, "incorrect predication in VPT block; got '" +
7400                    StringRef(ARMVPTPredToString(ARMVCC::VPTCodes(Pred))) +
7401                    "', but expected '" +
7402                    ARMVPTPredToString(ARMVCC::VPTCodes(VPTPred)) + "'");
7403     }
7404   }
7405   else if (isVectorPredicable(MCID) &&
7406            Inst.getOperand(findFirstVectorPredOperandIdx(MCID)).getImm() !=
7407            ARMVCC::None)
7408     return Error(Loc, "VPT predicated instructions must be in VPT block");
7409 
7410   const unsigned Opcode = Inst.getOpcode();
7411   switch (Opcode) {
7412   case ARM::t2IT: {
7413     // Encoding is unpredictable if it ever results in a notional 'NV'
7414     // predicate. Since we don't parse 'NV' directly this means an 'AL'
7415     // predicate with an "else" mask bit.
7416     unsigned Cond = Inst.getOperand(0).getImm();
7417     unsigned Mask = Inst.getOperand(1).getImm();
7418 
7419     // Conditions only allowing a 't' are those with no set bit except
7420     // the lowest-order one that indicates the end of the sequence. In
7421     // other words, powers of 2.
7422     if (Cond == ARMCC::AL && countPopulation(Mask) != 1)
7423       return Error(Loc, "unpredictable IT predicate sequence");
7424     break;
7425   }
7426   case ARM::LDRD:
7427     if (validateLDRDSTRD(Inst, Operands, /*Load*/true, /*ARMMode*/true,
7428                          /*Writeback*/false))
7429       return true;
7430     break;
7431   case ARM::LDRD_PRE:
7432   case ARM::LDRD_POST:
7433     if (validateLDRDSTRD(Inst, Operands, /*Load*/true, /*ARMMode*/true,
7434                          /*Writeback*/true))
7435       return true;
7436     break;
7437   case ARM::t2LDRDi8:
7438     if (validateLDRDSTRD(Inst, Operands, /*Load*/true, /*ARMMode*/false,
7439                          /*Writeback*/false))
7440       return true;
7441     break;
7442   case ARM::t2LDRD_PRE:
7443   case ARM::t2LDRD_POST:
7444     if (validateLDRDSTRD(Inst, Operands, /*Load*/true, /*ARMMode*/false,
7445                          /*Writeback*/true))
7446       return true;
7447     break;
7448   case ARM::t2BXJ: {
7449     const unsigned RmReg = Inst.getOperand(0).getReg();
7450     // Rm = SP is no longer unpredictable in v8-A
7451     if (RmReg == ARM::SP && !hasV8Ops())
7452       return Error(Operands[2]->getStartLoc(),
7453                    "r13 (SP) is an unpredictable operand to BXJ");
7454     return false;
7455   }
7456   case ARM::STRD:
7457     if (validateLDRDSTRD(Inst, Operands, /*Load*/false, /*ARMMode*/true,
7458                          /*Writeback*/false))
7459       return true;
7460     break;
7461   case ARM::STRD_PRE:
7462   case ARM::STRD_POST:
7463     if (validateLDRDSTRD(Inst, Operands, /*Load*/false, /*ARMMode*/true,
7464                          /*Writeback*/true))
7465       return true;
7466     break;
7467   case ARM::t2STRD_PRE:
7468   case ARM::t2STRD_POST:
7469     if (validateLDRDSTRD(Inst, Operands, /*Load*/false, /*ARMMode*/false,
7470                          /*Writeback*/true))
7471       return true;
7472     break;
7473   case ARM::STR_PRE_IMM:
7474   case ARM::STR_PRE_REG:
7475   case ARM::t2STR_PRE:
7476   case ARM::STR_POST_IMM:
7477   case ARM::STR_POST_REG:
7478   case ARM::t2STR_POST:
7479   case ARM::STRH_PRE:
7480   case ARM::t2STRH_PRE:
7481   case ARM::STRH_POST:
7482   case ARM::t2STRH_POST:
7483   case ARM::STRB_PRE_IMM:
7484   case ARM::STRB_PRE_REG:
7485   case ARM::t2STRB_PRE:
7486   case ARM::STRB_POST_IMM:
7487   case ARM::STRB_POST_REG:
7488   case ARM::t2STRB_POST: {
7489     // Rt must be different from Rn.
7490     const unsigned Rt = MRI->getEncodingValue(Inst.getOperand(1).getReg());
7491     const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(2).getReg());
7492 
7493     if (Rt == Rn)
7494       return Error(Operands[3]->getStartLoc(),
7495                    "source register and base register can't be identical");
7496     return false;
7497   }
7498   case ARM::LDR_PRE_IMM:
7499   case ARM::LDR_PRE_REG:
7500   case ARM::t2LDR_PRE:
7501   case ARM::LDR_POST_IMM:
7502   case ARM::LDR_POST_REG:
7503   case ARM::t2LDR_POST:
7504   case ARM::LDRH_PRE:
7505   case ARM::t2LDRH_PRE:
7506   case ARM::LDRH_POST:
7507   case ARM::t2LDRH_POST:
7508   case ARM::LDRSH_PRE:
7509   case ARM::t2LDRSH_PRE:
7510   case ARM::LDRSH_POST:
7511   case ARM::t2LDRSH_POST:
7512   case ARM::LDRB_PRE_IMM:
7513   case ARM::LDRB_PRE_REG:
7514   case ARM::t2LDRB_PRE:
7515   case ARM::LDRB_POST_IMM:
7516   case ARM::LDRB_POST_REG:
7517   case ARM::t2LDRB_POST:
7518   case ARM::LDRSB_PRE:
7519   case ARM::t2LDRSB_PRE:
7520   case ARM::LDRSB_POST:
7521   case ARM::t2LDRSB_POST: {
7522     // Rt must be different from Rn.
7523     const unsigned Rt = MRI->getEncodingValue(Inst.getOperand(0).getReg());
7524     const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(2).getReg());
7525 
7526     if (Rt == Rn)
7527       return Error(Operands[3]->getStartLoc(),
7528                    "destination register and base register can't be identical");
7529     return false;
7530   }
7531 
7532   case ARM::MVE_VLDRBU8_rq:
7533   case ARM::MVE_VLDRBU16_rq:
7534   case ARM::MVE_VLDRBS16_rq:
7535   case ARM::MVE_VLDRBU32_rq:
7536   case ARM::MVE_VLDRBS32_rq:
7537   case ARM::MVE_VLDRHU16_rq:
7538   case ARM::MVE_VLDRHU16_rq_u:
7539   case ARM::MVE_VLDRHU32_rq:
7540   case ARM::MVE_VLDRHU32_rq_u:
7541   case ARM::MVE_VLDRHS32_rq:
7542   case ARM::MVE_VLDRHS32_rq_u:
7543   case ARM::MVE_VLDRWU32_rq:
7544   case ARM::MVE_VLDRWU32_rq_u:
7545   case ARM::MVE_VLDRDU64_rq:
7546   case ARM::MVE_VLDRDU64_rq_u:
7547   case ARM::MVE_VLDRWU32_qi:
7548   case ARM::MVE_VLDRWU32_qi_pre:
7549   case ARM::MVE_VLDRDU64_qi:
7550   case ARM::MVE_VLDRDU64_qi_pre: {
7551     // Qd must be different from Qm.
7552     unsigned QdIdx = 0, QmIdx = 2;
7553     bool QmIsPointer = false;
7554     switch (Opcode) {
7555     case ARM::MVE_VLDRWU32_qi:
7556     case ARM::MVE_VLDRDU64_qi:
7557       QmIdx = 1;
7558       QmIsPointer = true;
7559       break;
7560     case ARM::MVE_VLDRWU32_qi_pre:
7561     case ARM::MVE_VLDRDU64_qi_pre:
7562       QdIdx = 1;
7563       QmIsPointer = true;
7564       break;
7565     }
7566 
7567     const unsigned Qd = MRI->getEncodingValue(Inst.getOperand(QdIdx).getReg());
7568     const unsigned Qm = MRI->getEncodingValue(Inst.getOperand(QmIdx).getReg());
7569 
7570     if (Qd == Qm) {
7571       return Error(Operands[3]->getStartLoc(),
7572                    Twine("destination vector register and vector ") +
7573                    (QmIsPointer ? "pointer" : "offset") +
7574                    " register can't be identical");
7575     }
7576     return false;
7577   }
7578 
7579   case ARM::SBFX:
7580   case ARM::t2SBFX:
7581   case ARM::UBFX:
7582   case ARM::t2UBFX: {
7583     // Width must be in range [1, 32-lsb].
7584     unsigned LSB = Inst.getOperand(2).getImm();
7585     unsigned Widthm1 = Inst.getOperand(3).getImm();
7586     if (Widthm1 >= 32 - LSB)
7587       return Error(Operands[5]->getStartLoc(),
7588                    "bitfield width must be in range [1,32-lsb]");
7589     return false;
7590   }
7591   // Notionally handles ARM::tLDMIA_UPD too.
7592   case ARM::tLDMIA: {
7593     // If we're parsing Thumb2, the .w variant is available and handles
7594     // most cases that are normally illegal for a Thumb1 LDM instruction.
7595     // We'll make the transformation in processInstruction() if necessary.
7596     //
7597     // Thumb LDM instructions are writeback iff the base register is not
7598     // in the register list.
7599     unsigned Rn = Inst.getOperand(0).getReg();
7600     bool HasWritebackToken =
7601         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
7602          static_cast<ARMOperand &>(*Operands[3]).getToken() == "!");
7603     bool ListContainsBase;
7604     if (checkLowRegisterList(Inst, 3, Rn, 0, ListContainsBase) && !isThumbTwo())
7605       return Error(Operands[3 + HasWritebackToken]->getStartLoc(),
7606                    "registers must be in range r0-r7");
7607     // If we should have writeback, then there should be a '!' token.
7608     if (!ListContainsBase && !HasWritebackToken && !isThumbTwo())
7609       return Error(Operands[2]->getStartLoc(),
7610                    "writeback operator '!' expected");
7611     // If we should not have writeback, there must not be a '!'. This is
7612     // true even for the 32-bit wide encodings.
7613     if (ListContainsBase && HasWritebackToken)
7614       return Error(Operands[3]->getStartLoc(),
7615                    "writeback operator '!' not allowed when base register "
7616                    "in register list");
7617 
7618     if (validatetLDMRegList(Inst, Operands, 3))
7619       return true;
7620     break;
7621   }
7622   case ARM::LDMIA_UPD:
7623   case ARM::LDMDB_UPD:
7624   case ARM::LDMIB_UPD:
7625   case ARM::LDMDA_UPD:
7626     // ARM variants loading and updating the same register are only officially
7627     // UNPREDICTABLE on v7 upwards. Goodness knows what they did before.
7628     if (!hasV7Ops())
7629       break;
7630     if (listContainsReg(Inst, 3, Inst.getOperand(0).getReg()))
7631       return Error(Operands.back()->getStartLoc(),
7632                    "writeback register not allowed in register list");
7633     break;
7634   case ARM::t2LDMIA:
7635   case ARM::t2LDMDB:
7636     if (validatetLDMRegList(Inst, Operands, 3))
7637       return true;
7638     break;
7639   case ARM::t2STMIA:
7640   case ARM::t2STMDB:
7641     if (validatetSTMRegList(Inst, Operands, 3))
7642       return true;
7643     break;
7644   case ARM::t2LDMIA_UPD:
7645   case ARM::t2LDMDB_UPD:
7646   case ARM::t2STMIA_UPD:
7647   case ARM::t2STMDB_UPD:
7648     if (listContainsReg(Inst, 3, Inst.getOperand(0).getReg()))
7649       return Error(Operands.back()->getStartLoc(),
7650                    "writeback register not allowed in register list");
7651 
7652     if (Opcode == ARM::t2LDMIA_UPD || Opcode == ARM::t2LDMDB_UPD) {
7653       if (validatetLDMRegList(Inst, Operands, 3))
7654         return true;
7655     } else {
7656       if (validatetSTMRegList(Inst, Operands, 3))
7657         return true;
7658     }
7659     break;
7660 
7661   case ARM::sysLDMIA_UPD:
7662   case ARM::sysLDMDA_UPD:
7663   case ARM::sysLDMDB_UPD:
7664   case ARM::sysLDMIB_UPD:
7665     if (!listContainsReg(Inst, 3, ARM::PC))
7666       return Error(Operands[4]->getStartLoc(),
7667                    "writeback register only allowed on system LDM "
7668                    "if PC in register-list");
7669     break;
7670   case ARM::sysSTMIA_UPD:
7671   case ARM::sysSTMDA_UPD:
7672   case ARM::sysSTMDB_UPD:
7673   case ARM::sysSTMIB_UPD:
7674     return Error(Operands[2]->getStartLoc(),
7675                  "system STM cannot have writeback register");
7676   case ARM::tMUL:
7677     // The second source operand must be the same register as the destination
7678     // operand.
7679     //
7680     // In this case, we must directly check the parsed operands because the
7681     // cvtThumbMultiply() function is written in such a way that it guarantees
7682     // this first statement is always true for the new Inst.  Essentially, the
7683     // destination is unconditionally copied into the second source operand
7684     // without checking to see if it matches what we actually parsed.
7685     if (Operands.size() == 6 && (((ARMOperand &)*Operands[3]).getReg() !=
7686                                  ((ARMOperand &)*Operands[5]).getReg()) &&
7687         (((ARMOperand &)*Operands[3]).getReg() !=
7688          ((ARMOperand &)*Operands[4]).getReg())) {
7689       return Error(Operands[3]->getStartLoc(),
7690                    "destination register must match source register");
7691     }
7692     break;
7693 
7694   // Like for ldm/stm, push and pop have hi-reg handling version in Thumb2,
7695   // so only issue a diagnostic for thumb1. The instructions will be
7696   // switched to the t2 encodings in processInstruction() if necessary.
7697   case ARM::tPOP: {
7698     bool ListContainsBase;
7699     if (checkLowRegisterList(Inst, 2, 0, ARM::PC, ListContainsBase) &&
7700         !isThumbTwo())
7701       return Error(Operands[2]->getStartLoc(),
7702                    "registers must be in range r0-r7 or pc");
7703     if (validatetLDMRegList(Inst, Operands, 2, !isMClass()))
7704       return true;
7705     break;
7706   }
7707   case ARM::tPUSH: {
7708     bool ListContainsBase;
7709     if (checkLowRegisterList(Inst, 2, 0, ARM::LR, ListContainsBase) &&
7710         !isThumbTwo())
7711       return Error(Operands[2]->getStartLoc(),
7712                    "registers must be in range r0-r7 or lr");
7713     if (validatetSTMRegList(Inst, Operands, 2))
7714       return true;
7715     break;
7716   }
7717   case ARM::tSTMIA_UPD: {
7718     bool ListContainsBase, InvalidLowList;
7719     InvalidLowList = checkLowRegisterList(Inst, 4, Inst.getOperand(0).getReg(),
7720                                           0, ListContainsBase);
7721     if (InvalidLowList && !isThumbTwo())
7722       return Error(Operands[4]->getStartLoc(),
7723                    "registers must be in range r0-r7");
7724 
7725     // This would be converted to a 32-bit stm, but that's not valid if the
7726     // writeback register is in the list.
7727     if (InvalidLowList && ListContainsBase)
7728       return Error(Operands[4]->getStartLoc(),
7729                    "writeback operator '!' not allowed when base register "
7730                    "in register list");
7731 
7732     if (validatetSTMRegList(Inst, Operands, 4))
7733       return true;
7734     break;
7735   }
7736   case ARM::tADDrSP:
7737     // If the non-SP source operand and the destination operand are not the
7738     // same, we need thumb2 (for the wide encoding), or we have an error.
7739     if (!isThumbTwo() &&
7740         Inst.getOperand(0).getReg() != Inst.getOperand(2).getReg()) {
7741       return Error(Operands[4]->getStartLoc(),
7742                    "source register must be the same as destination");
7743     }
7744     break;
7745 
7746   case ARM::t2ADDrr:
7747   case ARM::t2ADDrs:
7748   case ARM::t2SUBrr:
7749   case ARM::t2SUBrs:
7750     if (Inst.getOperand(0).getReg() == ARM::SP &&
7751         Inst.getOperand(1).getReg() != ARM::SP)
7752       return Error(Operands[4]->getStartLoc(),
7753                    "source register must be sp if destination is sp");
7754     break;
7755 
7756   // Final range checking for Thumb unconditional branch instructions.
7757   case ARM::tB:
7758     if (!(static_cast<ARMOperand &>(*Operands[2])).isSignedOffset<11, 1>())
7759       return Error(Operands[2]->getStartLoc(), "branch target out of range");
7760     break;
7761   case ARM::t2B: {
7762     int op = (Operands[2]->isImm()) ? 2 : 3;
7763     if (!static_cast<ARMOperand &>(*Operands[op]).isSignedOffset<24, 1>())
7764       return Error(Operands[op]->getStartLoc(), "branch target out of range");
7765     break;
7766   }
7767   // Final range checking for Thumb conditional branch instructions.
7768   case ARM::tBcc:
7769     if (!static_cast<ARMOperand &>(*Operands[2]).isSignedOffset<8, 1>())
7770       return Error(Operands[2]->getStartLoc(), "branch target out of range");
7771     break;
7772   case ARM::t2Bcc: {
7773     int Op = (Operands[2]->isImm()) ? 2 : 3;
7774     if (!static_cast<ARMOperand &>(*Operands[Op]).isSignedOffset<20, 1>())
7775       return Error(Operands[Op]->getStartLoc(), "branch target out of range");
7776     break;
7777   }
7778   case ARM::tCBZ:
7779   case ARM::tCBNZ: {
7780     if (!static_cast<ARMOperand &>(*Operands[2]).isUnsignedOffset<6, 1>())
7781       return Error(Operands[2]->getStartLoc(), "branch target out of range");
7782     break;
7783   }
7784   case ARM::MOVi16:
7785   case ARM::MOVTi16:
7786   case ARM::t2MOVi16:
7787   case ARM::t2MOVTi16:
7788     {
7789     // We want to avoid misleadingly allowing something like "mov r0, <symbol>"
7790     // especially when we turn it into a movw and the expression <symbol> does
7791     // not have a :lower16: or :upper16 as part of the expression.  We don't
7792     // want the behavior of silently truncating, which can be unexpected and
7793     // lead to bugs that are difficult to find since this is an easy mistake
7794     // to make.
7795     int i = (Operands[3]->isImm()) ? 3 : 4;
7796     ARMOperand &Op = static_cast<ARMOperand &>(*Operands[i]);
7797     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm());
7798     if (CE) break;
7799     const MCExpr *E = dyn_cast<MCExpr>(Op.getImm());
7800     if (!E) break;
7801     const ARMMCExpr *ARM16Expr = dyn_cast<ARMMCExpr>(E);
7802     if (!ARM16Expr || (ARM16Expr->getKind() != ARMMCExpr::VK_ARM_HI16 &&
7803                        ARM16Expr->getKind() != ARMMCExpr::VK_ARM_LO16))
7804       return Error(
7805           Op.getStartLoc(),
7806           "immediate expression for mov requires :lower16: or :upper16");
7807     break;
7808   }
7809   case ARM::HINT:
7810   case ARM::t2HINT: {
7811     unsigned Imm8 = Inst.getOperand(0).getImm();
7812     unsigned Pred = Inst.getOperand(1).getImm();
7813     // ESB is not predicable (pred must be AL). Without the RAS extension, this
7814     // behaves as any other unallocated hint.
7815     if (Imm8 == 0x10 && Pred != ARMCC::AL && hasRAS())
7816       return Error(Operands[1]->getStartLoc(), "instruction 'esb' is not "
7817                                                "predicable, but condition "
7818                                                "code specified");
7819     if (Imm8 == 0x14 && Pred != ARMCC::AL)
7820       return Error(Operands[1]->getStartLoc(), "instruction 'csdb' is not "
7821                                                "predicable, but condition "
7822                                                "code specified");
7823     break;
7824   }
7825   case ARM::t2BFi:
7826   case ARM::t2BFr:
7827   case ARM::t2BFLi:
7828   case ARM::t2BFLr: {
7829     if (!static_cast<ARMOperand &>(*Operands[2]).isUnsignedOffset<4, 1>() ||
7830         (Inst.getOperand(0).isImm() && Inst.getOperand(0).getImm() == 0))
7831       return Error(Operands[2]->getStartLoc(),
7832                    "branch location out of range or not a multiple of 2");
7833 
7834     if (Opcode == ARM::t2BFi) {
7835       if (!static_cast<ARMOperand &>(*Operands[3]).isSignedOffset<16, 1>())
7836         return Error(Operands[3]->getStartLoc(),
7837                      "branch target out of range or not a multiple of 2");
7838     } else if (Opcode == ARM::t2BFLi) {
7839       if (!static_cast<ARMOperand &>(*Operands[3]).isSignedOffset<18, 1>())
7840         return Error(Operands[3]->getStartLoc(),
7841                      "branch target out of range or not a multiple of 2");
7842     }
7843     break;
7844   }
7845   case ARM::t2BFic: {
7846     if (!static_cast<ARMOperand &>(*Operands[1]).isUnsignedOffset<4, 1>() ||
7847         (Inst.getOperand(0).isImm() && Inst.getOperand(0).getImm() == 0))
7848       return Error(Operands[1]->getStartLoc(),
7849                    "branch location out of range or not a multiple of 2");
7850 
7851     if (!static_cast<ARMOperand &>(*Operands[2]).isSignedOffset<16, 1>())
7852       return Error(Operands[2]->getStartLoc(),
7853                    "branch target out of range or not a multiple of 2");
7854 
7855     assert(Inst.getOperand(0).isImm() == Inst.getOperand(2).isImm() &&
7856            "branch location and else branch target should either both be "
7857            "immediates or both labels");
7858 
7859     if (Inst.getOperand(0).isImm() && Inst.getOperand(2).isImm()) {
7860       int Diff = Inst.getOperand(2).getImm() - Inst.getOperand(0).getImm();
7861       if (Diff != 4 && Diff != 2)
7862         return Error(
7863             Operands[3]->getStartLoc(),
7864             "else branch target must be 2 or 4 greater than the branch location");
7865     }
7866     break;
7867   }
7868   case ARM::t2CLRM: {
7869     for (unsigned i = 2; i < Inst.getNumOperands(); i++) {
7870       if (Inst.getOperand(i).isReg() &&
7871           !ARMMCRegisterClasses[ARM::GPRwithAPSRnospRegClassID].contains(
7872               Inst.getOperand(i).getReg())) {
7873         return Error(Operands[2]->getStartLoc(),
7874                      "invalid register in register list. Valid registers are "
7875                      "r0-r12, lr/r14 and APSR.");
7876       }
7877     }
7878     break;
7879   }
7880   case ARM::DSB:
7881   case ARM::t2DSB: {
7882 
7883     if (Inst.getNumOperands() < 2)
7884       break;
7885 
7886     unsigned Option = Inst.getOperand(0).getImm();
7887     unsigned Pred = Inst.getOperand(1).getImm();
7888 
7889     // SSBB and PSSBB (DSB #0|#4) are not predicable (pred must be AL).
7890     if (Option == 0 && Pred != ARMCC::AL)
7891       return Error(Operands[1]->getStartLoc(),
7892                    "instruction 'ssbb' is not predicable, but condition code "
7893                    "specified");
7894     if (Option == 4 && Pred != ARMCC::AL)
7895       return Error(Operands[1]->getStartLoc(),
7896                    "instruction 'pssbb' is not predicable, but condition code "
7897                    "specified");
7898     break;
7899   }
7900   case ARM::VMOVRRS: {
7901     // Source registers must be sequential.
7902     const unsigned Sm = MRI->getEncodingValue(Inst.getOperand(2).getReg());
7903     const unsigned Sm1 = MRI->getEncodingValue(Inst.getOperand(3).getReg());
7904     if (Sm1 != Sm + 1)
7905       return Error(Operands[5]->getStartLoc(),
7906                    "source operands must be sequential");
7907     break;
7908   }
7909   case ARM::VMOVSRR: {
7910     // Destination registers must be sequential.
7911     const unsigned Sm = MRI->getEncodingValue(Inst.getOperand(0).getReg());
7912     const unsigned Sm1 = MRI->getEncodingValue(Inst.getOperand(1).getReg());
7913     if (Sm1 != Sm + 1)
7914       return Error(Operands[3]->getStartLoc(),
7915                    "destination operands must be sequential");
7916     break;
7917   }
7918   case ARM::VLDMDIA:
7919   case ARM::VSTMDIA: {
7920     ARMOperand &Op = static_cast<ARMOperand&>(*Operands[3]);
7921     auto &RegList = Op.getRegList();
7922     if (RegList.size() < 1 || RegList.size() > 16)
7923       return Error(Operands[3]->getStartLoc(),
7924                    "list of registers must be at least 1 and at most 16");
7925     break;
7926   }
7927   case ARM::MVE_VQDMULLs32bh:
7928   case ARM::MVE_VQDMULLs32th:
7929   case ARM::MVE_VCMULf32:
7930   case ARM::MVE_VMULLBs32:
7931   case ARM::MVE_VMULLTs32:
7932   case ARM::MVE_VMULLBu32:
7933   case ARM::MVE_VMULLTu32: {
7934     if (Operands[3]->getReg() == Operands[4]->getReg()) {
7935       return Error (Operands[3]->getStartLoc(),
7936                     "Qd register and Qn register can't be identical");
7937     }
7938     if (Operands[3]->getReg() == Operands[5]->getReg()) {
7939       return Error (Operands[3]->getStartLoc(),
7940                     "Qd register and Qm register can't be identical");
7941     }
7942     break;
7943   }
7944   case ARM::MVE_VMOV_rr_q: {
7945     if (Operands[4]->getReg() != Operands[6]->getReg())
7946       return Error (Operands[4]->getStartLoc(), "Q-registers must be the same");
7947     if (static_cast<ARMOperand &>(*Operands[5]).getVectorIndex() !=
7948         static_cast<ARMOperand &>(*Operands[7]).getVectorIndex() + 2)
7949       return Error (Operands[5]->getStartLoc(), "Q-register indexes must be 2 and 0 or 3 and 1");
7950     break;
7951   }
7952   case ARM::MVE_VMOV_q_rr: {
7953     if (Operands[2]->getReg() != Operands[4]->getReg())
7954       return Error (Operands[2]->getStartLoc(), "Q-registers must be the same");
7955     if (static_cast<ARMOperand &>(*Operands[3]).getVectorIndex() !=
7956         static_cast<ARMOperand &>(*Operands[5]).getVectorIndex() + 2)
7957       return Error (Operands[3]->getStartLoc(), "Q-register indexes must be 2 and 0 or 3 and 1");
7958     break;
7959   }
7960   case ARM::UMAAL:
7961   case ARM::UMLAL:
7962   case ARM::UMULL:
7963   case ARM::t2UMAAL:
7964   case ARM::t2UMLAL:
7965   case ARM::t2UMULL:
7966   case ARM::SMLAL:
7967   case ARM::SMLALBB:
7968   case ARM::SMLALBT:
7969   case ARM::SMLALD:
7970   case ARM::SMLALDX:
7971   case ARM::SMLALTB:
7972   case ARM::SMLALTT:
7973   case ARM::SMLSLD:
7974   case ARM::SMLSLDX:
7975   case ARM::SMULL:
7976   case ARM::t2SMLAL:
7977   case ARM::t2SMLALBB:
7978   case ARM::t2SMLALBT:
7979   case ARM::t2SMLALD:
7980   case ARM::t2SMLALDX:
7981   case ARM::t2SMLALTB:
7982   case ARM::t2SMLALTT:
7983   case ARM::t2SMLSLD:
7984   case ARM::t2SMLSLDX:
7985   case ARM::t2SMULL: {
7986     unsigned RdHi = Inst.getOperand(0).getReg();
7987     unsigned RdLo = Inst.getOperand(1).getReg();
7988     if(RdHi == RdLo) {
7989       return Error(Loc,
7990                    "unpredictable instruction, RdHi and RdLo must be different");
7991     }
7992     break;
7993   }
7994   }
7995 
7996   return false;
7997 }
7998 
7999 static unsigned getRealVSTOpcode(unsigned Opc, unsigned &Spacing) {
8000   switch(Opc) {
8001   default: llvm_unreachable("unexpected opcode!");
8002   // VST1LN
8003   case ARM::VST1LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST1LNd8_UPD;
8004   case ARM::VST1LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST1LNd16_UPD;
8005   case ARM::VST1LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST1LNd32_UPD;
8006   case ARM::VST1LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST1LNd8_UPD;
8007   case ARM::VST1LNdWB_register_Asm_16: Spacing = 1; return ARM::VST1LNd16_UPD;
8008   case ARM::VST1LNdWB_register_Asm_32: Spacing = 1; return ARM::VST1LNd32_UPD;
8009   case ARM::VST1LNdAsm_8:  Spacing = 1; return ARM::VST1LNd8;
8010   case ARM::VST1LNdAsm_16: Spacing = 1; return ARM::VST1LNd16;
8011   case ARM::VST1LNdAsm_32: Spacing = 1; return ARM::VST1LNd32;
8012 
8013   // VST2LN
8014   case ARM::VST2LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST2LNd8_UPD;
8015   case ARM::VST2LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST2LNd16_UPD;
8016   case ARM::VST2LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST2LNd32_UPD;
8017   case ARM::VST2LNqWB_fixed_Asm_16: Spacing = 2; return ARM::VST2LNq16_UPD;
8018   case ARM::VST2LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST2LNq32_UPD;
8019 
8020   case ARM::VST2LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST2LNd8_UPD;
8021   case ARM::VST2LNdWB_register_Asm_16: Spacing = 1; return ARM::VST2LNd16_UPD;
8022   case ARM::VST2LNdWB_register_Asm_32: Spacing = 1; return ARM::VST2LNd32_UPD;
8023   case ARM::VST2LNqWB_register_Asm_16: Spacing = 2; return ARM::VST2LNq16_UPD;
8024   case ARM::VST2LNqWB_register_Asm_32: Spacing = 2; return ARM::VST2LNq32_UPD;
8025 
8026   case ARM::VST2LNdAsm_8:  Spacing = 1; return ARM::VST2LNd8;
8027   case ARM::VST2LNdAsm_16: Spacing = 1; return ARM::VST2LNd16;
8028   case ARM::VST2LNdAsm_32: Spacing = 1; return ARM::VST2LNd32;
8029   case ARM::VST2LNqAsm_16: Spacing = 2; return ARM::VST2LNq16;
8030   case ARM::VST2LNqAsm_32: Spacing = 2; return ARM::VST2LNq32;
8031 
8032   // VST3LN
8033   case ARM::VST3LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST3LNd8_UPD;
8034   case ARM::VST3LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST3LNd16_UPD;
8035   case ARM::VST3LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST3LNd32_UPD;
8036   case ARM::VST3LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VST3LNq16_UPD;
8037   case ARM::VST3LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST3LNq32_UPD;
8038   case ARM::VST3LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST3LNd8_UPD;
8039   case ARM::VST3LNdWB_register_Asm_16: Spacing = 1; return ARM::VST3LNd16_UPD;
8040   case ARM::VST3LNdWB_register_Asm_32: Spacing = 1; return ARM::VST3LNd32_UPD;
8041   case ARM::VST3LNqWB_register_Asm_16: Spacing = 2; return ARM::VST3LNq16_UPD;
8042   case ARM::VST3LNqWB_register_Asm_32: Spacing = 2; return ARM::VST3LNq32_UPD;
8043   case ARM::VST3LNdAsm_8:  Spacing = 1; return ARM::VST3LNd8;
8044   case ARM::VST3LNdAsm_16: Spacing = 1; return ARM::VST3LNd16;
8045   case ARM::VST3LNdAsm_32: Spacing = 1; return ARM::VST3LNd32;
8046   case ARM::VST3LNqAsm_16: Spacing = 2; return ARM::VST3LNq16;
8047   case ARM::VST3LNqAsm_32: Spacing = 2; return ARM::VST3LNq32;
8048 
8049   // VST3
8050   case ARM::VST3dWB_fixed_Asm_8:  Spacing = 1; return ARM::VST3d8_UPD;
8051   case ARM::VST3dWB_fixed_Asm_16: Spacing = 1; return ARM::VST3d16_UPD;
8052   case ARM::VST3dWB_fixed_Asm_32: Spacing = 1; return ARM::VST3d32_UPD;
8053   case ARM::VST3qWB_fixed_Asm_8:  Spacing = 2; return ARM::VST3q8_UPD;
8054   case ARM::VST3qWB_fixed_Asm_16: Spacing = 2; return ARM::VST3q16_UPD;
8055   case ARM::VST3qWB_fixed_Asm_32: Spacing = 2; return ARM::VST3q32_UPD;
8056   case ARM::VST3dWB_register_Asm_8:  Spacing = 1; return ARM::VST3d8_UPD;
8057   case ARM::VST3dWB_register_Asm_16: Spacing = 1; return ARM::VST3d16_UPD;
8058   case ARM::VST3dWB_register_Asm_32: Spacing = 1; return ARM::VST3d32_UPD;
8059   case ARM::VST3qWB_register_Asm_8:  Spacing = 2; return ARM::VST3q8_UPD;
8060   case ARM::VST3qWB_register_Asm_16: Spacing = 2; return ARM::VST3q16_UPD;
8061   case ARM::VST3qWB_register_Asm_32: Spacing = 2; return ARM::VST3q32_UPD;
8062   case ARM::VST3dAsm_8:  Spacing = 1; return ARM::VST3d8;
8063   case ARM::VST3dAsm_16: Spacing = 1; return ARM::VST3d16;
8064   case ARM::VST3dAsm_32: Spacing = 1; return ARM::VST3d32;
8065   case ARM::VST3qAsm_8:  Spacing = 2; return ARM::VST3q8;
8066   case ARM::VST3qAsm_16: Spacing = 2; return ARM::VST3q16;
8067   case ARM::VST3qAsm_32: Spacing = 2; return ARM::VST3q32;
8068 
8069   // VST4LN
8070   case ARM::VST4LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST4LNd8_UPD;
8071   case ARM::VST4LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST4LNd16_UPD;
8072   case ARM::VST4LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST4LNd32_UPD;
8073   case ARM::VST4LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VST4LNq16_UPD;
8074   case ARM::VST4LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST4LNq32_UPD;
8075   case ARM::VST4LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST4LNd8_UPD;
8076   case ARM::VST4LNdWB_register_Asm_16: Spacing = 1; return ARM::VST4LNd16_UPD;
8077   case ARM::VST4LNdWB_register_Asm_32: Spacing = 1; return ARM::VST4LNd32_UPD;
8078   case ARM::VST4LNqWB_register_Asm_16: Spacing = 2; return ARM::VST4LNq16_UPD;
8079   case ARM::VST4LNqWB_register_Asm_32: Spacing = 2; return ARM::VST4LNq32_UPD;
8080   case ARM::VST4LNdAsm_8:  Spacing = 1; return ARM::VST4LNd8;
8081   case ARM::VST4LNdAsm_16: Spacing = 1; return ARM::VST4LNd16;
8082   case ARM::VST4LNdAsm_32: Spacing = 1; return ARM::VST4LNd32;
8083   case ARM::VST4LNqAsm_16: Spacing = 2; return ARM::VST4LNq16;
8084   case ARM::VST4LNqAsm_32: Spacing = 2; return ARM::VST4LNq32;
8085 
8086   // VST4
8087   case ARM::VST4dWB_fixed_Asm_8:  Spacing = 1; return ARM::VST4d8_UPD;
8088   case ARM::VST4dWB_fixed_Asm_16: Spacing = 1; return ARM::VST4d16_UPD;
8089   case ARM::VST4dWB_fixed_Asm_32: Spacing = 1; return ARM::VST4d32_UPD;
8090   case ARM::VST4qWB_fixed_Asm_8:  Spacing = 2; return ARM::VST4q8_UPD;
8091   case ARM::VST4qWB_fixed_Asm_16: Spacing = 2; return ARM::VST4q16_UPD;
8092   case ARM::VST4qWB_fixed_Asm_32: Spacing = 2; return ARM::VST4q32_UPD;
8093   case ARM::VST4dWB_register_Asm_8:  Spacing = 1; return ARM::VST4d8_UPD;
8094   case ARM::VST4dWB_register_Asm_16: Spacing = 1; return ARM::VST4d16_UPD;
8095   case ARM::VST4dWB_register_Asm_32: Spacing = 1; return ARM::VST4d32_UPD;
8096   case ARM::VST4qWB_register_Asm_8:  Spacing = 2; return ARM::VST4q8_UPD;
8097   case ARM::VST4qWB_register_Asm_16: Spacing = 2; return ARM::VST4q16_UPD;
8098   case ARM::VST4qWB_register_Asm_32: Spacing = 2; return ARM::VST4q32_UPD;
8099   case ARM::VST4dAsm_8:  Spacing = 1; return ARM::VST4d8;
8100   case ARM::VST4dAsm_16: Spacing = 1; return ARM::VST4d16;
8101   case ARM::VST4dAsm_32: Spacing = 1; return ARM::VST4d32;
8102   case ARM::VST4qAsm_8:  Spacing = 2; return ARM::VST4q8;
8103   case ARM::VST4qAsm_16: Spacing = 2; return ARM::VST4q16;
8104   case ARM::VST4qAsm_32: Spacing = 2; return ARM::VST4q32;
8105   }
8106 }
8107 
8108 static unsigned getRealVLDOpcode(unsigned Opc, unsigned &Spacing) {
8109   switch(Opc) {
8110   default: llvm_unreachable("unexpected opcode!");
8111   // VLD1LN
8112   case ARM::VLD1LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD1LNd8_UPD;
8113   case ARM::VLD1LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD1LNd16_UPD;
8114   case ARM::VLD1LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD1LNd32_UPD;
8115   case ARM::VLD1LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD1LNd8_UPD;
8116   case ARM::VLD1LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD1LNd16_UPD;
8117   case ARM::VLD1LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD1LNd32_UPD;
8118   case ARM::VLD1LNdAsm_8:  Spacing = 1; return ARM::VLD1LNd8;
8119   case ARM::VLD1LNdAsm_16: Spacing = 1; return ARM::VLD1LNd16;
8120   case ARM::VLD1LNdAsm_32: Spacing = 1; return ARM::VLD1LNd32;
8121 
8122   // VLD2LN
8123   case ARM::VLD2LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD2LNd8_UPD;
8124   case ARM::VLD2LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD2LNd16_UPD;
8125   case ARM::VLD2LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD2LNd32_UPD;
8126   case ARM::VLD2LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD2LNq16_UPD;
8127   case ARM::VLD2LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD2LNq32_UPD;
8128   case ARM::VLD2LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD2LNd8_UPD;
8129   case ARM::VLD2LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD2LNd16_UPD;
8130   case ARM::VLD2LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD2LNd32_UPD;
8131   case ARM::VLD2LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD2LNq16_UPD;
8132   case ARM::VLD2LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD2LNq32_UPD;
8133   case ARM::VLD2LNdAsm_8:  Spacing = 1; return ARM::VLD2LNd8;
8134   case ARM::VLD2LNdAsm_16: Spacing = 1; return ARM::VLD2LNd16;
8135   case ARM::VLD2LNdAsm_32: Spacing = 1; return ARM::VLD2LNd32;
8136   case ARM::VLD2LNqAsm_16: Spacing = 2; return ARM::VLD2LNq16;
8137   case ARM::VLD2LNqAsm_32: Spacing = 2; return ARM::VLD2LNq32;
8138 
8139   // VLD3DUP
8140   case ARM::VLD3DUPdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3DUPd8_UPD;
8141   case ARM::VLD3DUPdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3DUPd16_UPD;
8142   case ARM::VLD3DUPdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3DUPd32_UPD;
8143   case ARM::VLD3DUPqWB_fixed_Asm_8: Spacing = 1; return ARM::VLD3DUPq8_UPD;
8144   case ARM::VLD3DUPqWB_fixed_Asm_16: Spacing = 2; return ARM::VLD3DUPq16_UPD;
8145   case ARM::VLD3DUPqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3DUPq32_UPD;
8146   case ARM::VLD3DUPdWB_register_Asm_8:  Spacing = 1; return ARM::VLD3DUPd8_UPD;
8147   case ARM::VLD3DUPdWB_register_Asm_16: Spacing = 1; return ARM::VLD3DUPd16_UPD;
8148   case ARM::VLD3DUPdWB_register_Asm_32: Spacing = 1; return ARM::VLD3DUPd32_UPD;
8149   case ARM::VLD3DUPqWB_register_Asm_8: Spacing = 2; return ARM::VLD3DUPq8_UPD;
8150   case ARM::VLD3DUPqWB_register_Asm_16: Spacing = 2; return ARM::VLD3DUPq16_UPD;
8151   case ARM::VLD3DUPqWB_register_Asm_32: Spacing = 2; return ARM::VLD3DUPq32_UPD;
8152   case ARM::VLD3DUPdAsm_8:  Spacing = 1; return ARM::VLD3DUPd8;
8153   case ARM::VLD3DUPdAsm_16: Spacing = 1; return ARM::VLD3DUPd16;
8154   case ARM::VLD3DUPdAsm_32: Spacing = 1; return ARM::VLD3DUPd32;
8155   case ARM::VLD3DUPqAsm_8: Spacing = 2; return ARM::VLD3DUPq8;
8156   case ARM::VLD3DUPqAsm_16: Spacing = 2; return ARM::VLD3DUPq16;
8157   case ARM::VLD3DUPqAsm_32: Spacing = 2; return ARM::VLD3DUPq32;
8158 
8159   // VLD3LN
8160   case ARM::VLD3LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3LNd8_UPD;
8161   case ARM::VLD3LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3LNd16_UPD;
8162   case ARM::VLD3LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3LNd32_UPD;
8163   case ARM::VLD3LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3LNq16_UPD;
8164   case ARM::VLD3LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3LNq32_UPD;
8165   case ARM::VLD3LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD3LNd8_UPD;
8166   case ARM::VLD3LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD3LNd16_UPD;
8167   case ARM::VLD3LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD3LNd32_UPD;
8168   case ARM::VLD3LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD3LNq16_UPD;
8169   case ARM::VLD3LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD3LNq32_UPD;
8170   case ARM::VLD3LNdAsm_8:  Spacing = 1; return ARM::VLD3LNd8;
8171   case ARM::VLD3LNdAsm_16: Spacing = 1; return ARM::VLD3LNd16;
8172   case ARM::VLD3LNdAsm_32: Spacing = 1; return ARM::VLD3LNd32;
8173   case ARM::VLD3LNqAsm_16: Spacing = 2; return ARM::VLD3LNq16;
8174   case ARM::VLD3LNqAsm_32: Spacing = 2; return ARM::VLD3LNq32;
8175 
8176   // VLD3
8177   case ARM::VLD3dWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3d8_UPD;
8178   case ARM::VLD3dWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3d16_UPD;
8179   case ARM::VLD3dWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3d32_UPD;
8180   case ARM::VLD3qWB_fixed_Asm_8:  Spacing = 2; return ARM::VLD3q8_UPD;
8181   case ARM::VLD3qWB_fixed_Asm_16: Spacing = 2; return ARM::VLD3q16_UPD;
8182   case ARM::VLD3qWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3q32_UPD;
8183   case ARM::VLD3dWB_register_Asm_8:  Spacing = 1; return ARM::VLD3d8_UPD;
8184   case ARM::VLD3dWB_register_Asm_16: Spacing = 1; return ARM::VLD3d16_UPD;
8185   case ARM::VLD3dWB_register_Asm_32: Spacing = 1; return ARM::VLD3d32_UPD;
8186   case ARM::VLD3qWB_register_Asm_8:  Spacing = 2; return ARM::VLD3q8_UPD;
8187   case ARM::VLD3qWB_register_Asm_16: Spacing = 2; return ARM::VLD3q16_UPD;
8188   case ARM::VLD3qWB_register_Asm_32: Spacing = 2; return ARM::VLD3q32_UPD;
8189   case ARM::VLD3dAsm_8:  Spacing = 1; return ARM::VLD3d8;
8190   case ARM::VLD3dAsm_16: Spacing = 1; return ARM::VLD3d16;
8191   case ARM::VLD3dAsm_32: Spacing = 1; return ARM::VLD3d32;
8192   case ARM::VLD3qAsm_8:  Spacing = 2; return ARM::VLD3q8;
8193   case ARM::VLD3qAsm_16: Spacing = 2; return ARM::VLD3q16;
8194   case ARM::VLD3qAsm_32: Spacing = 2; return ARM::VLD3q32;
8195 
8196   // VLD4LN
8197   case ARM::VLD4LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4LNd8_UPD;
8198   case ARM::VLD4LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4LNd16_UPD;
8199   case ARM::VLD4LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4LNd32_UPD;
8200   case ARM::VLD4LNqWB_fixed_Asm_16: Spacing = 2; return ARM::VLD4LNq16_UPD;
8201   case ARM::VLD4LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4LNq32_UPD;
8202   case ARM::VLD4LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD4LNd8_UPD;
8203   case ARM::VLD4LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD4LNd16_UPD;
8204   case ARM::VLD4LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD4LNd32_UPD;
8205   case ARM::VLD4LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD4LNq16_UPD;
8206   case ARM::VLD4LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD4LNq32_UPD;
8207   case ARM::VLD4LNdAsm_8:  Spacing = 1; return ARM::VLD4LNd8;
8208   case ARM::VLD4LNdAsm_16: Spacing = 1; return ARM::VLD4LNd16;
8209   case ARM::VLD4LNdAsm_32: Spacing = 1; return ARM::VLD4LNd32;
8210   case ARM::VLD4LNqAsm_16: Spacing = 2; return ARM::VLD4LNq16;
8211   case ARM::VLD4LNqAsm_32: Spacing = 2; return ARM::VLD4LNq32;
8212 
8213   // VLD4DUP
8214   case ARM::VLD4DUPdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4DUPd8_UPD;
8215   case ARM::VLD4DUPdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4DUPd16_UPD;
8216   case ARM::VLD4DUPdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4DUPd32_UPD;
8217   case ARM::VLD4DUPqWB_fixed_Asm_8: Spacing = 1; return ARM::VLD4DUPq8_UPD;
8218   case ARM::VLD4DUPqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4DUPq16_UPD;
8219   case ARM::VLD4DUPqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4DUPq32_UPD;
8220   case ARM::VLD4DUPdWB_register_Asm_8:  Spacing = 1; return ARM::VLD4DUPd8_UPD;
8221   case ARM::VLD4DUPdWB_register_Asm_16: Spacing = 1; return ARM::VLD4DUPd16_UPD;
8222   case ARM::VLD4DUPdWB_register_Asm_32: Spacing = 1; return ARM::VLD4DUPd32_UPD;
8223   case ARM::VLD4DUPqWB_register_Asm_8: Spacing = 2; return ARM::VLD4DUPq8_UPD;
8224   case ARM::VLD4DUPqWB_register_Asm_16: Spacing = 2; return ARM::VLD4DUPq16_UPD;
8225   case ARM::VLD4DUPqWB_register_Asm_32: Spacing = 2; return ARM::VLD4DUPq32_UPD;
8226   case ARM::VLD4DUPdAsm_8:  Spacing = 1; return ARM::VLD4DUPd8;
8227   case ARM::VLD4DUPdAsm_16: Spacing = 1; return ARM::VLD4DUPd16;
8228   case ARM::VLD4DUPdAsm_32: Spacing = 1; return ARM::VLD4DUPd32;
8229   case ARM::VLD4DUPqAsm_8: Spacing = 2; return ARM::VLD4DUPq8;
8230   case ARM::VLD4DUPqAsm_16: Spacing = 2; return ARM::VLD4DUPq16;
8231   case ARM::VLD4DUPqAsm_32: Spacing = 2; return ARM::VLD4DUPq32;
8232 
8233   // VLD4
8234   case ARM::VLD4dWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4d8_UPD;
8235   case ARM::VLD4dWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4d16_UPD;
8236   case ARM::VLD4dWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4d32_UPD;
8237   case ARM::VLD4qWB_fixed_Asm_8:  Spacing = 2; return ARM::VLD4q8_UPD;
8238   case ARM::VLD4qWB_fixed_Asm_16: Spacing = 2; return ARM::VLD4q16_UPD;
8239   case ARM::VLD4qWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4q32_UPD;
8240   case ARM::VLD4dWB_register_Asm_8:  Spacing = 1; return ARM::VLD4d8_UPD;
8241   case ARM::VLD4dWB_register_Asm_16: Spacing = 1; return ARM::VLD4d16_UPD;
8242   case ARM::VLD4dWB_register_Asm_32: Spacing = 1; return ARM::VLD4d32_UPD;
8243   case ARM::VLD4qWB_register_Asm_8:  Spacing = 2; return ARM::VLD4q8_UPD;
8244   case ARM::VLD4qWB_register_Asm_16: Spacing = 2; return ARM::VLD4q16_UPD;
8245   case ARM::VLD4qWB_register_Asm_32: Spacing = 2; return ARM::VLD4q32_UPD;
8246   case ARM::VLD4dAsm_8:  Spacing = 1; return ARM::VLD4d8;
8247   case ARM::VLD4dAsm_16: Spacing = 1; return ARM::VLD4d16;
8248   case ARM::VLD4dAsm_32: Spacing = 1; return ARM::VLD4d32;
8249   case ARM::VLD4qAsm_8:  Spacing = 2; return ARM::VLD4q8;
8250   case ARM::VLD4qAsm_16: Spacing = 2; return ARM::VLD4q16;
8251   case ARM::VLD4qAsm_32: Spacing = 2; return ARM::VLD4q32;
8252   }
8253 }
8254 
8255 bool ARMAsmParser::processInstruction(MCInst &Inst,
8256                                       const OperandVector &Operands,
8257                                       MCStreamer &Out) {
8258   // Check if we have the wide qualifier, because if it's present we
8259   // must avoid selecting a 16-bit thumb instruction.
8260   bool HasWideQualifier = false;
8261   for (auto &Op : Operands) {
8262     ARMOperand &ARMOp = static_cast<ARMOperand&>(*Op);
8263     if (ARMOp.isToken() && ARMOp.getToken() == ".w") {
8264       HasWideQualifier = true;
8265       break;
8266     }
8267   }
8268 
8269   switch (Inst.getOpcode()) {
8270   // Alias for alternate form of 'ldr{,b}t Rt, [Rn], #imm' instruction.
8271   case ARM::LDRT_POST:
8272   case ARM::LDRBT_POST: {
8273     const unsigned Opcode =
8274       (Inst.getOpcode() == ARM::LDRT_POST) ? ARM::LDRT_POST_IMM
8275                                            : ARM::LDRBT_POST_IMM;
8276     MCInst TmpInst;
8277     TmpInst.setOpcode(Opcode);
8278     TmpInst.addOperand(Inst.getOperand(0));
8279     TmpInst.addOperand(Inst.getOperand(1));
8280     TmpInst.addOperand(Inst.getOperand(1));
8281     TmpInst.addOperand(MCOperand::createReg(0));
8282     TmpInst.addOperand(MCOperand::createImm(0));
8283     TmpInst.addOperand(Inst.getOperand(2));
8284     TmpInst.addOperand(Inst.getOperand(3));
8285     Inst = TmpInst;
8286     return true;
8287   }
8288   // Alias for alternate form of 'str{,b}t Rt, [Rn], #imm' instruction.
8289   case ARM::STRT_POST:
8290   case ARM::STRBT_POST: {
8291     const unsigned Opcode =
8292       (Inst.getOpcode() == ARM::STRT_POST) ? ARM::STRT_POST_IMM
8293                                            : ARM::STRBT_POST_IMM;
8294     MCInst TmpInst;
8295     TmpInst.setOpcode(Opcode);
8296     TmpInst.addOperand(Inst.getOperand(1));
8297     TmpInst.addOperand(Inst.getOperand(0));
8298     TmpInst.addOperand(Inst.getOperand(1));
8299     TmpInst.addOperand(MCOperand::createReg(0));
8300     TmpInst.addOperand(MCOperand::createImm(0));
8301     TmpInst.addOperand(Inst.getOperand(2));
8302     TmpInst.addOperand(Inst.getOperand(3));
8303     Inst = TmpInst;
8304     return true;
8305   }
8306   // Alias for alternate form of 'ADR Rd, #imm' instruction.
8307   case ARM::ADDri: {
8308     if (Inst.getOperand(1).getReg() != ARM::PC ||
8309         Inst.getOperand(5).getReg() != 0 ||
8310         !(Inst.getOperand(2).isExpr() || Inst.getOperand(2).isImm()))
8311       return false;
8312     MCInst TmpInst;
8313     TmpInst.setOpcode(ARM::ADR);
8314     TmpInst.addOperand(Inst.getOperand(0));
8315     if (Inst.getOperand(2).isImm()) {
8316       // Immediate (mod_imm) will be in its encoded form, we must unencode it
8317       // before passing it to the ADR instruction.
8318       unsigned Enc = Inst.getOperand(2).getImm();
8319       TmpInst.addOperand(MCOperand::createImm(
8320         ARM_AM::rotr32(Enc & 0xFF, (Enc & 0xF00) >> 7)));
8321     } else {
8322       // Turn PC-relative expression into absolute expression.
8323       // Reading PC provides the start of the current instruction + 8 and
8324       // the transform to adr is biased by that.
8325       MCSymbol *Dot = getContext().createTempSymbol();
8326       Out.emitLabel(Dot);
8327       const MCExpr *OpExpr = Inst.getOperand(2).getExpr();
8328       const MCExpr *InstPC = MCSymbolRefExpr::create(Dot,
8329                                                      MCSymbolRefExpr::VK_None,
8330                                                      getContext());
8331       const MCExpr *Const8 = MCConstantExpr::create(8, getContext());
8332       const MCExpr *ReadPC = MCBinaryExpr::createAdd(InstPC, Const8,
8333                                                      getContext());
8334       const MCExpr *FixupAddr = MCBinaryExpr::createAdd(ReadPC, OpExpr,
8335                                                         getContext());
8336       TmpInst.addOperand(MCOperand::createExpr(FixupAddr));
8337     }
8338     TmpInst.addOperand(Inst.getOperand(3));
8339     TmpInst.addOperand(Inst.getOperand(4));
8340     Inst = TmpInst;
8341     return true;
8342   }
8343   // Aliases for alternate PC+imm syntax of LDR instructions.
8344   case ARM::t2LDRpcrel:
8345     // Select the narrow version if the immediate will fit.
8346     if (Inst.getOperand(1).getImm() > 0 &&
8347         Inst.getOperand(1).getImm() <= 0xff &&
8348         !HasWideQualifier)
8349       Inst.setOpcode(ARM::tLDRpci);
8350     else
8351       Inst.setOpcode(ARM::t2LDRpci);
8352     return true;
8353   case ARM::t2LDRBpcrel:
8354     Inst.setOpcode(ARM::t2LDRBpci);
8355     return true;
8356   case ARM::t2LDRHpcrel:
8357     Inst.setOpcode(ARM::t2LDRHpci);
8358     return true;
8359   case ARM::t2LDRSBpcrel:
8360     Inst.setOpcode(ARM::t2LDRSBpci);
8361     return true;
8362   case ARM::t2LDRSHpcrel:
8363     Inst.setOpcode(ARM::t2LDRSHpci);
8364     return true;
8365   case ARM::LDRConstPool:
8366   case ARM::tLDRConstPool:
8367   case ARM::t2LDRConstPool: {
8368     // Pseudo instruction ldr rt, =immediate is converted to a
8369     // MOV rt, immediate if immediate is known and representable
8370     // otherwise we create a constant pool entry that we load from.
8371     MCInst TmpInst;
8372     if (Inst.getOpcode() == ARM::LDRConstPool)
8373       TmpInst.setOpcode(ARM::LDRi12);
8374     else if (Inst.getOpcode() == ARM::tLDRConstPool)
8375       TmpInst.setOpcode(ARM::tLDRpci);
8376     else if (Inst.getOpcode() == ARM::t2LDRConstPool)
8377       TmpInst.setOpcode(ARM::t2LDRpci);
8378     const ARMOperand &PoolOperand =
8379       (HasWideQualifier ?
8380        static_cast<ARMOperand &>(*Operands[4]) :
8381        static_cast<ARMOperand &>(*Operands[3]));
8382     const MCExpr *SubExprVal = PoolOperand.getConstantPoolImm();
8383     // If SubExprVal is a constant we may be able to use a MOV
8384     if (isa<MCConstantExpr>(SubExprVal) &&
8385         Inst.getOperand(0).getReg() != ARM::PC &&
8386         Inst.getOperand(0).getReg() != ARM::SP) {
8387       int64_t Value =
8388         (int64_t) (cast<MCConstantExpr>(SubExprVal))->getValue();
8389       bool UseMov  = true;
8390       bool MovHasS = true;
8391       if (Inst.getOpcode() == ARM::LDRConstPool) {
8392         // ARM Constant
8393         if (ARM_AM::getSOImmVal(Value) != -1) {
8394           Value = ARM_AM::getSOImmVal(Value);
8395           TmpInst.setOpcode(ARM::MOVi);
8396         }
8397         else if (ARM_AM::getSOImmVal(~Value) != -1) {
8398           Value = ARM_AM::getSOImmVal(~Value);
8399           TmpInst.setOpcode(ARM::MVNi);
8400         }
8401         else if (hasV6T2Ops() &&
8402                  Value >=0 && Value < 65536) {
8403           TmpInst.setOpcode(ARM::MOVi16);
8404           MovHasS = false;
8405         }
8406         else
8407           UseMov = false;
8408       }
8409       else {
8410         // Thumb/Thumb2 Constant
8411         if (hasThumb2() &&
8412             ARM_AM::getT2SOImmVal(Value) != -1)
8413           TmpInst.setOpcode(ARM::t2MOVi);
8414         else if (hasThumb2() &&
8415                  ARM_AM::getT2SOImmVal(~Value) != -1) {
8416           TmpInst.setOpcode(ARM::t2MVNi);
8417           Value = ~Value;
8418         }
8419         else if (hasV8MBaseline() &&
8420                  Value >=0 && Value < 65536) {
8421           TmpInst.setOpcode(ARM::t2MOVi16);
8422           MovHasS = false;
8423         }
8424         else
8425           UseMov = false;
8426       }
8427       if (UseMov) {
8428         TmpInst.addOperand(Inst.getOperand(0));           // Rt
8429         TmpInst.addOperand(MCOperand::createImm(Value));  // Immediate
8430         TmpInst.addOperand(Inst.getOperand(2));           // CondCode
8431         TmpInst.addOperand(Inst.getOperand(3));           // CondCode
8432         if (MovHasS)
8433           TmpInst.addOperand(MCOperand::createReg(0));    // S
8434         Inst = TmpInst;
8435         return true;
8436       }
8437     }
8438     // No opportunity to use MOV/MVN create constant pool
8439     const MCExpr *CPLoc =
8440       getTargetStreamer().addConstantPoolEntry(SubExprVal,
8441                                                PoolOperand.getStartLoc());
8442     TmpInst.addOperand(Inst.getOperand(0));           // Rt
8443     TmpInst.addOperand(MCOperand::createExpr(CPLoc)); // offset to constpool
8444     if (TmpInst.getOpcode() == ARM::LDRi12)
8445       TmpInst.addOperand(MCOperand::createImm(0));    // unused offset
8446     TmpInst.addOperand(Inst.getOperand(2));           // CondCode
8447     TmpInst.addOperand(Inst.getOperand(3));           // CondCode
8448     Inst = TmpInst;
8449     return true;
8450   }
8451   // Handle NEON VST complex aliases.
8452   case ARM::VST1LNdWB_register_Asm_8:
8453   case ARM::VST1LNdWB_register_Asm_16:
8454   case ARM::VST1LNdWB_register_Asm_32: {
8455     MCInst TmpInst;
8456     // Shuffle the operands around so the lane index operand is in the
8457     // right place.
8458     unsigned Spacing;
8459     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8460     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8461     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8462     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8463     TmpInst.addOperand(Inst.getOperand(4)); // Rm
8464     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8465     TmpInst.addOperand(Inst.getOperand(1)); // lane
8466     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
8467     TmpInst.addOperand(Inst.getOperand(6));
8468     Inst = TmpInst;
8469     return true;
8470   }
8471 
8472   case ARM::VST2LNdWB_register_Asm_8:
8473   case ARM::VST2LNdWB_register_Asm_16:
8474   case ARM::VST2LNdWB_register_Asm_32:
8475   case ARM::VST2LNqWB_register_Asm_16:
8476   case ARM::VST2LNqWB_register_Asm_32: {
8477     MCInst TmpInst;
8478     // Shuffle the operands around so the lane index operand is in the
8479     // right place.
8480     unsigned Spacing;
8481     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8482     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8483     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8484     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8485     TmpInst.addOperand(Inst.getOperand(4)); // Rm
8486     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8487     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8488                                             Spacing));
8489     TmpInst.addOperand(Inst.getOperand(1)); // lane
8490     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
8491     TmpInst.addOperand(Inst.getOperand(6));
8492     Inst = TmpInst;
8493     return true;
8494   }
8495 
8496   case ARM::VST3LNdWB_register_Asm_8:
8497   case ARM::VST3LNdWB_register_Asm_16:
8498   case ARM::VST3LNdWB_register_Asm_32:
8499   case ARM::VST3LNqWB_register_Asm_16:
8500   case ARM::VST3LNqWB_register_Asm_32: {
8501     MCInst TmpInst;
8502     // Shuffle the operands around so the lane index operand is in the
8503     // right place.
8504     unsigned Spacing;
8505     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8506     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8507     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8508     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8509     TmpInst.addOperand(Inst.getOperand(4)); // Rm
8510     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8511     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8512                                             Spacing));
8513     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8514                                             Spacing * 2));
8515     TmpInst.addOperand(Inst.getOperand(1)); // lane
8516     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
8517     TmpInst.addOperand(Inst.getOperand(6));
8518     Inst = TmpInst;
8519     return true;
8520   }
8521 
8522   case ARM::VST4LNdWB_register_Asm_8:
8523   case ARM::VST4LNdWB_register_Asm_16:
8524   case ARM::VST4LNdWB_register_Asm_32:
8525   case ARM::VST4LNqWB_register_Asm_16:
8526   case ARM::VST4LNqWB_register_Asm_32: {
8527     MCInst TmpInst;
8528     // Shuffle the operands around so the lane index operand is in the
8529     // right place.
8530     unsigned Spacing;
8531     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8532     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8533     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8534     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8535     TmpInst.addOperand(Inst.getOperand(4)); // Rm
8536     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8537     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8538                                             Spacing));
8539     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8540                                             Spacing * 2));
8541     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8542                                             Spacing * 3));
8543     TmpInst.addOperand(Inst.getOperand(1)); // lane
8544     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
8545     TmpInst.addOperand(Inst.getOperand(6));
8546     Inst = TmpInst;
8547     return true;
8548   }
8549 
8550   case ARM::VST1LNdWB_fixed_Asm_8:
8551   case ARM::VST1LNdWB_fixed_Asm_16:
8552   case ARM::VST1LNdWB_fixed_Asm_32: {
8553     MCInst TmpInst;
8554     // Shuffle the operands around so the lane index operand is in the
8555     // right place.
8556     unsigned Spacing;
8557     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8558     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8559     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8560     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8561     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8562     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8563     TmpInst.addOperand(Inst.getOperand(1)); // lane
8564     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8565     TmpInst.addOperand(Inst.getOperand(5));
8566     Inst = TmpInst;
8567     return true;
8568   }
8569 
8570   case ARM::VST2LNdWB_fixed_Asm_8:
8571   case ARM::VST2LNdWB_fixed_Asm_16:
8572   case ARM::VST2LNdWB_fixed_Asm_32:
8573   case ARM::VST2LNqWB_fixed_Asm_16:
8574   case ARM::VST2LNqWB_fixed_Asm_32: {
8575     MCInst TmpInst;
8576     // Shuffle the operands around so the lane index operand is in the
8577     // right place.
8578     unsigned Spacing;
8579     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8580     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8581     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8582     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8583     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8584     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8585     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8586                                             Spacing));
8587     TmpInst.addOperand(Inst.getOperand(1)); // lane
8588     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8589     TmpInst.addOperand(Inst.getOperand(5));
8590     Inst = TmpInst;
8591     return true;
8592   }
8593 
8594   case ARM::VST3LNdWB_fixed_Asm_8:
8595   case ARM::VST3LNdWB_fixed_Asm_16:
8596   case ARM::VST3LNdWB_fixed_Asm_32:
8597   case ARM::VST3LNqWB_fixed_Asm_16:
8598   case ARM::VST3LNqWB_fixed_Asm_32: {
8599     MCInst TmpInst;
8600     // Shuffle the operands around so the lane index operand is in the
8601     // right place.
8602     unsigned Spacing;
8603     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8604     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8605     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8606     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8607     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8608     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8609     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8610                                             Spacing));
8611     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8612                                             Spacing * 2));
8613     TmpInst.addOperand(Inst.getOperand(1)); // lane
8614     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8615     TmpInst.addOperand(Inst.getOperand(5));
8616     Inst = TmpInst;
8617     return true;
8618   }
8619 
8620   case ARM::VST4LNdWB_fixed_Asm_8:
8621   case ARM::VST4LNdWB_fixed_Asm_16:
8622   case ARM::VST4LNdWB_fixed_Asm_32:
8623   case ARM::VST4LNqWB_fixed_Asm_16:
8624   case ARM::VST4LNqWB_fixed_Asm_32: {
8625     MCInst TmpInst;
8626     // Shuffle the operands around so the lane index operand is in the
8627     // right place.
8628     unsigned Spacing;
8629     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8630     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8631     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8632     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8633     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8634     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8635     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8636                                             Spacing));
8637     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8638                                             Spacing * 2));
8639     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8640                                             Spacing * 3));
8641     TmpInst.addOperand(Inst.getOperand(1)); // lane
8642     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8643     TmpInst.addOperand(Inst.getOperand(5));
8644     Inst = TmpInst;
8645     return true;
8646   }
8647 
8648   case ARM::VST1LNdAsm_8:
8649   case ARM::VST1LNdAsm_16:
8650   case ARM::VST1LNdAsm_32: {
8651     MCInst TmpInst;
8652     // Shuffle the operands around so the lane index operand is in the
8653     // right place.
8654     unsigned Spacing;
8655     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8656     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8657     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8658     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8659     TmpInst.addOperand(Inst.getOperand(1)); // lane
8660     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8661     TmpInst.addOperand(Inst.getOperand(5));
8662     Inst = TmpInst;
8663     return true;
8664   }
8665 
8666   case ARM::VST2LNdAsm_8:
8667   case ARM::VST2LNdAsm_16:
8668   case ARM::VST2LNdAsm_32:
8669   case ARM::VST2LNqAsm_16:
8670   case ARM::VST2LNqAsm_32: {
8671     MCInst TmpInst;
8672     // Shuffle the operands around so the lane index operand is in the
8673     // right place.
8674     unsigned Spacing;
8675     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8676     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8677     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8678     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8679     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8680                                             Spacing));
8681     TmpInst.addOperand(Inst.getOperand(1)); // lane
8682     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8683     TmpInst.addOperand(Inst.getOperand(5));
8684     Inst = TmpInst;
8685     return true;
8686   }
8687 
8688   case ARM::VST3LNdAsm_8:
8689   case ARM::VST3LNdAsm_16:
8690   case ARM::VST3LNdAsm_32:
8691   case ARM::VST3LNqAsm_16:
8692   case ARM::VST3LNqAsm_32: {
8693     MCInst TmpInst;
8694     // Shuffle the operands around so the lane index operand is in the
8695     // right place.
8696     unsigned Spacing;
8697     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8698     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8699     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8700     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8701     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8702                                             Spacing));
8703     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8704                                             Spacing * 2));
8705     TmpInst.addOperand(Inst.getOperand(1)); // lane
8706     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8707     TmpInst.addOperand(Inst.getOperand(5));
8708     Inst = TmpInst;
8709     return true;
8710   }
8711 
8712   case ARM::VST4LNdAsm_8:
8713   case ARM::VST4LNdAsm_16:
8714   case ARM::VST4LNdAsm_32:
8715   case ARM::VST4LNqAsm_16:
8716   case ARM::VST4LNqAsm_32: {
8717     MCInst TmpInst;
8718     // Shuffle the operands around so the lane index operand is in the
8719     // right place.
8720     unsigned Spacing;
8721     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8722     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8723     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8724     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8725     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8726                                             Spacing));
8727     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8728                                             Spacing * 2));
8729     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8730                                             Spacing * 3));
8731     TmpInst.addOperand(Inst.getOperand(1)); // lane
8732     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8733     TmpInst.addOperand(Inst.getOperand(5));
8734     Inst = TmpInst;
8735     return true;
8736   }
8737 
8738   // Handle NEON VLD complex aliases.
8739   case ARM::VLD1LNdWB_register_Asm_8:
8740   case ARM::VLD1LNdWB_register_Asm_16:
8741   case ARM::VLD1LNdWB_register_Asm_32: {
8742     MCInst TmpInst;
8743     // Shuffle the operands around so the lane index operand is in the
8744     // right place.
8745     unsigned Spacing;
8746     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8747     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8748     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8749     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8750     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8751     TmpInst.addOperand(Inst.getOperand(4)); // Rm
8752     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
8753     TmpInst.addOperand(Inst.getOperand(1)); // lane
8754     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
8755     TmpInst.addOperand(Inst.getOperand(6));
8756     Inst = TmpInst;
8757     return true;
8758   }
8759 
8760   case ARM::VLD2LNdWB_register_Asm_8:
8761   case ARM::VLD2LNdWB_register_Asm_16:
8762   case ARM::VLD2LNdWB_register_Asm_32:
8763   case ARM::VLD2LNqWB_register_Asm_16:
8764   case ARM::VLD2LNqWB_register_Asm_32: {
8765     MCInst TmpInst;
8766     // Shuffle the operands around so the lane index operand is in the
8767     // right place.
8768     unsigned Spacing;
8769     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8770     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8771     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8772                                             Spacing));
8773     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8774     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8775     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8776     TmpInst.addOperand(Inst.getOperand(4)); // Rm
8777     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
8778     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8779                                             Spacing));
8780     TmpInst.addOperand(Inst.getOperand(1)); // lane
8781     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
8782     TmpInst.addOperand(Inst.getOperand(6));
8783     Inst = TmpInst;
8784     return true;
8785   }
8786 
8787   case ARM::VLD3LNdWB_register_Asm_8:
8788   case ARM::VLD3LNdWB_register_Asm_16:
8789   case ARM::VLD3LNdWB_register_Asm_32:
8790   case ARM::VLD3LNqWB_register_Asm_16:
8791   case ARM::VLD3LNqWB_register_Asm_32: {
8792     MCInst TmpInst;
8793     // Shuffle the operands around so the lane index operand is in the
8794     // right place.
8795     unsigned Spacing;
8796     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8797     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8798     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8799                                             Spacing));
8800     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8801                                             Spacing * 2));
8802     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8803     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8804     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8805     TmpInst.addOperand(Inst.getOperand(4)); // Rm
8806     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
8807     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8808                                             Spacing));
8809     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8810                                             Spacing * 2));
8811     TmpInst.addOperand(Inst.getOperand(1)); // lane
8812     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
8813     TmpInst.addOperand(Inst.getOperand(6));
8814     Inst = TmpInst;
8815     return true;
8816   }
8817 
8818   case ARM::VLD4LNdWB_register_Asm_8:
8819   case ARM::VLD4LNdWB_register_Asm_16:
8820   case ARM::VLD4LNdWB_register_Asm_32:
8821   case ARM::VLD4LNqWB_register_Asm_16:
8822   case ARM::VLD4LNqWB_register_Asm_32: {
8823     MCInst TmpInst;
8824     // Shuffle the operands around so the lane index operand is in the
8825     // right place.
8826     unsigned Spacing;
8827     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8828     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8829     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8830                                             Spacing));
8831     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8832                                             Spacing * 2));
8833     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8834                                             Spacing * 3));
8835     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8836     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8837     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8838     TmpInst.addOperand(Inst.getOperand(4)); // Rm
8839     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
8840     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8841                                             Spacing));
8842     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8843                                             Spacing * 2));
8844     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8845                                             Spacing * 3));
8846     TmpInst.addOperand(Inst.getOperand(1)); // lane
8847     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
8848     TmpInst.addOperand(Inst.getOperand(6));
8849     Inst = TmpInst;
8850     return true;
8851   }
8852 
8853   case ARM::VLD1LNdWB_fixed_Asm_8:
8854   case ARM::VLD1LNdWB_fixed_Asm_16:
8855   case ARM::VLD1LNdWB_fixed_Asm_32: {
8856     MCInst TmpInst;
8857     // Shuffle the operands around so the lane index operand is in the
8858     // right place.
8859     unsigned Spacing;
8860     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8861     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8862     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8863     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8864     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8865     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8866     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
8867     TmpInst.addOperand(Inst.getOperand(1)); // lane
8868     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8869     TmpInst.addOperand(Inst.getOperand(5));
8870     Inst = TmpInst;
8871     return true;
8872   }
8873 
8874   case ARM::VLD2LNdWB_fixed_Asm_8:
8875   case ARM::VLD2LNdWB_fixed_Asm_16:
8876   case ARM::VLD2LNdWB_fixed_Asm_32:
8877   case ARM::VLD2LNqWB_fixed_Asm_16:
8878   case ARM::VLD2LNqWB_fixed_Asm_32: {
8879     MCInst TmpInst;
8880     // Shuffle the operands around so the lane index operand is in the
8881     // right place.
8882     unsigned Spacing;
8883     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8884     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8885     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8886                                             Spacing));
8887     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8888     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8889     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8890     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8891     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
8892     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8893                                             Spacing));
8894     TmpInst.addOperand(Inst.getOperand(1)); // lane
8895     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8896     TmpInst.addOperand(Inst.getOperand(5));
8897     Inst = TmpInst;
8898     return true;
8899   }
8900 
8901   case ARM::VLD3LNdWB_fixed_Asm_8:
8902   case ARM::VLD3LNdWB_fixed_Asm_16:
8903   case ARM::VLD3LNdWB_fixed_Asm_32:
8904   case ARM::VLD3LNqWB_fixed_Asm_16:
8905   case ARM::VLD3LNqWB_fixed_Asm_32: {
8906     MCInst TmpInst;
8907     // Shuffle the operands around so the lane index operand is in the
8908     // right place.
8909     unsigned Spacing;
8910     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8911     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8912     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8913                                             Spacing));
8914     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8915                                             Spacing * 2));
8916     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8917     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8918     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8919     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8920     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
8921     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8922                                             Spacing));
8923     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8924                                             Spacing * 2));
8925     TmpInst.addOperand(Inst.getOperand(1)); // lane
8926     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8927     TmpInst.addOperand(Inst.getOperand(5));
8928     Inst = TmpInst;
8929     return true;
8930   }
8931 
8932   case ARM::VLD4LNdWB_fixed_Asm_8:
8933   case ARM::VLD4LNdWB_fixed_Asm_16:
8934   case ARM::VLD4LNdWB_fixed_Asm_32:
8935   case ARM::VLD4LNqWB_fixed_Asm_16:
8936   case ARM::VLD4LNqWB_fixed_Asm_32: {
8937     MCInst TmpInst;
8938     // Shuffle the operands around so the lane index operand is in the
8939     // right place.
8940     unsigned Spacing;
8941     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8942     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8943     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8944                                             Spacing));
8945     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8946                                             Spacing * 2));
8947     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8948                                             Spacing * 3));
8949     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
8950     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8951     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8952     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8953     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
8954     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8955                                             Spacing));
8956     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8957                                             Spacing * 2));
8958     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8959                                             Spacing * 3));
8960     TmpInst.addOperand(Inst.getOperand(1)); // lane
8961     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8962     TmpInst.addOperand(Inst.getOperand(5));
8963     Inst = TmpInst;
8964     return true;
8965   }
8966 
8967   case ARM::VLD1LNdAsm_8:
8968   case ARM::VLD1LNdAsm_16:
8969   case ARM::VLD1LNdAsm_32: {
8970     MCInst TmpInst;
8971     // Shuffle the operands around so the lane index operand is in the
8972     // right place.
8973     unsigned Spacing;
8974     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8975     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8976     TmpInst.addOperand(Inst.getOperand(2)); // Rn
8977     TmpInst.addOperand(Inst.getOperand(3)); // alignment
8978     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
8979     TmpInst.addOperand(Inst.getOperand(1)); // lane
8980     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8981     TmpInst.addOperand(Inst.getOperand(5));
8982     Inst = TmpInst;
8983     return true;
8984   }
8985 
8986   case ARM::VLD2LNdAsm_8:
8987   case ARM::VLD2LNdAsm_16:
8988   case ARM::VLD2LNdAsm_32:
8989   case ARM::VLD2LNqAsm_16:
8990   case ARM::VLD2LNqAsm_32: {
8991     MCInst TmpInst;
8992     // Shuffle the operands around so the lane index operand is in the
8993     // right place.
8994     unsigned Spacing;
8995     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8996     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8997     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8998                                             Spacing));
8999     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9000     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9001     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
9002     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9003                                             Spacing));
9004     TmpInst.addOperand(Inst.getOperand(1)); // lane
9005     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9006     TmpInst.addOperand(Inst.getOperand(5));
9007     Inst = TmpInst;
9008     return true;
9009   }
9010 
9011   case ARM::VLD3LNdAsm_8:
9012   case ARM::VLD3LNdAsm_16:
9013   case ARM::VLD3LNdAsm_32:
9014   case ARM::VLD3LNqAsm_16:
9015   case ARM::VLD3LNqAsm_32: {
9016     MCInst TmpInst;
9017     // Shuffle the operands around so the lane index operand is in the
9018     // right place.
9019     unsigned Spacing;
9020     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9021     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9022     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9023                                             Spacing));
9024     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9025                                             Spacing * 2));
9026     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9027     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9028     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
9029     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9030                                             Spacing));
9031     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9032                                             Spacing * 2));
9033     TmpInst.addOperand(Inst.getOperand(1)); // lane
9034     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9035     TmpInst.addOperand(Inst.getOperand(5));
9036     Inst = TmpInst;
9037     return true;
9038   }
9039 
9040   case ARM::VLD4LNdAsm_8:
9041   case ARM::VLD4LNdAsm_16:
9042   case ARM::VLD4LNdAsm_32:
9043   case ARM::VLD4LNqAsm_16:
9044   case ARM::VLD4LNqAsm_32: {
9045     MCInst TmpInst;
9046     // Shuffle the operands around so the lane index operand is in the
9047     // right place.
9048     unsigned Spacing;
9049     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9050     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9051     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9052                                             Spacing));
9053     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9054                                             Spacing * 2));
9055     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9056                                             Spacing * 3));
9057     TmpInst.addOperand(Inst.getOperand(2)); // Rn
9058     TmpInst.addOperand(Inst.getOperand(3)); // alignment
9059     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
9060     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9061                                             Spacing));
9062     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9063                                             Spacing * 2));
9064     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9065                                             Spacing * 3));
9066     TmpInst.addOperand(Inst.getOperand(1)); // lane
9067     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9068     TmpInst.addOperand(Inst.getOperand(5));
9069     Inst = TmpInst;
9070     return true;
9071   }
9072 
9073   // VLD3DUP single 3-element structure to all lanes instructions.
9074   case ARM::VLD3DUPdAsm_8:
9075   case ARM::VLD3DUPdAsm_16:
9076   case ARM::VLD3DUPdAsm_32:
9077   case ARM::VLD3DUPqAsm_8:
9078   case ARM::VLD3DUPqAsm_16:
9079   case ARM::VLD3DUPqAsm_32: {
9080     MCInst TmpInst;
9081     unsigned Spacing;
9082     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9083     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9084     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9085                                             Spacing));
9086     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9087                                             Spacing * 2));
9088     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9089     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9090     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9091     TmpInst.addOperand(Inst.getOperand(4));
9092     Inst = TmpInst;
9093     return true;
9094   }
9095 
9096   case ARM::VLD3DUPdWB_fixed_Asm_8:
9097   case ARM::VLD3DUPdWB_fixed_Asm_16:
9098   case ARM::VLD3DUPdWB_fixed_Asm_32:
9099   case ARM::VLD3DUPqWB_fixed_Asm_8:
9100   case ARM::VLD3DUPqWB_fixed_Asm_16:
9101   case ARM::VLD3DUPqWB_fixed_Asm_32: {
9102     MCInst TmpInst;
9103     unsigned Spacing;
9104     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9105     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9106     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9107                                             Spacing));
9108     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9109                                             Spacing * 2));
9110     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9111     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9112     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9113     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9114     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9115     TmpInst.addOperand(Inst.getOperand(4));
9116     Inst = TmpInst;
9117     return true;
9118   }
9119 
9120   case ARM::VLD3DUPdWB_register_Asm_8:
9121   case ARM::VLD3DUPdWB_register_Asm_16:
9122   case ARM::VLD3DUPdWB_register_Asm_32:
9123   case ARM::VLD3DUPqWB_register_Asm_8:
9124   case ARM::VLD3DUPqWB_register_Asm_16:
9125   case ARM::VLD3DUPqWB_register_Asm_32: {
9126     MCInst TmpInst;
9127     unsigned Spacing;
9128     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9129     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9130     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9131                                             Spacing));
9132     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9133                                             Spacing * 2));
9134     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9135     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9136     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9137     TmpInst.addOperand(Inst.getOperand(3)); // Rm
9138     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9139     TmpInst.addOperand(Inst.getOperand(5));
9140     Inst = TmpInst;
9141     return true;
9142   }
9143 
9144   // VLD3 multiple 3-element structure instructions.
9145   case ARM::VLD3dAsm_8:
9146   case ARM::VLD3dAsm_16:
9147   case ARM::VLD3dAsm_32:
9148   case ARM::VLD3qAsm_8:
9149   case ARM::VLD3qAsm_16:
9150   case ARM::VLD3qAsm_32: {
9151     MCInst TmpInst;
9152     unsigned Spacing;
9153     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9154     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9155     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9156                                             Spacing));
9157     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9158                                             Spacing * 2));
9159     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9160     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9161     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9162     TmpInst.addOperand(Inst.getOperand(4));
9163     Inst = TmpInst;
9164     return true;
9165   }
9166 
9167   case ARM::VLD3dWB_fixed_Asm_8:
9168   case ARM::VLD3dWB_fixed_Asm_16:
9169   case ARM::VLD3dWB_fixed_Asm_32:
9170   case ARM::VLD3qWB_fixed_Asm_8:
9171   case ARM::VLD3qWB_fixed_Asm_16:
9172   case ARM::VLD3qWB_fixed_Asm_32: {
9173     MCInst TmpInst;
9174     unsigned Spacing;
9175     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
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(Inst.getOperand(1)); // Rn
9182     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9183     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9184     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9185     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9186     TmpInst.addOperand(Inst.getOperand(4));
9187     Inst = TmpInst;
9188     return true;
9189   }
9190 
9191   case ARM::VLD3dWB_register_Asm_8:
9192   case ARM::VLD3dWB_register_Asm_16:
9193   case ARM::VLD3dWB_register_Asm_32:
9194   case ARM::VLD3qWB_register_Asm_8:
9195   case ARM::VLD3qWB_register_Asm_16:
9196   case ARM::VLD3qWB_register_Asm_32: {
9197     MCInst TmpInst;
9198     unsigned Spacing;
9199     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9200     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9201     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9202                                             Spacing));
9203     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9204                                             Spacing * 2));
9205     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9206     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9207     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9208     TmpInst.addOperand(Inst.getOperand(3)); // Rm
9209     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9210     TmpInst.addOperand(Inst.getOperand(5));
9211     Inst = TmpInst;
9212     return true;
9213   }
9214 
9215   // VLD4DUP single 3-element structure to all lanes instructions.
9216   case ARM::VLD4DUPdAsm_8:
9217   case ARM::VLD4DUPdAsm_16:
9218   case ARM::VLD4DUPdAsm_32:
9219   case ARM::VLD4DUPqAsm_8:
9220   case ARM::VLD4DUPqAsm_16:
9221   case ARM::VLD4DUPqAsm_32: {
9222     MCInst TmpInst;
9223     unsigned Spacing;
9224     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9225     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9226     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9227                                             Spacing));
9228     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9229                                             Spacing * 2));
9230     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9231                                             Spacing * 3));
9232     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9233     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9234     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9235     TmpInst.addOperand(Inst.getOperand(4));
9236     Inst = TmpInst;
9237     return true;
9238   }
9239 
9240   case ARM::VLD4DUPdWB_fixed_Asm_8:
9241   case ARM::VLD4DUPdWB_fixed_Asm_16:
9242   case ARM::VLD4DUPdWB_fixed_Asm_32:
9243   case ARM::VLD4DUPqWB_fixed_Asm_8:
9244   case ARM::VLD4DUPqWB_fixed_Asm_16:
9245   case ARM::VLD4DUPqWB_fixed_Asm_32: {
9246     MCInst TmpInst;
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(MCOperand::createReg(Inst.getOperand(0).getReg() +
9255                                             Spacing * 3));
9256     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9257     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9258     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9259     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9260     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9261     TmpInst.addOperand(Inst.getOperand(4));
9262     Inst = TmpInst;
9263     return true;
9264   }
9265 
9266   case ARM::VLD4DUPdWB_register_Asm_8:
9267   case ARM::VLD4DUPdWB_register_Asm_16:
9268   case ARM::VLD4DUPdWB_register_Asm_32:
9269   case ARM::VLD4DUPqWB_register_Asm_8:
9270   case ARM::VLD4DUPqWB_register_Asm_16:
9271   case ARM::VLD4DUPqWB_register_Asm_32: {
9272     MCInst TmpInst;
9273     unsigned Spacing;
9274     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9275     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9276     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9277                                             Spacing));
9278     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9279                                             Spacing * 2));
9280     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9281                                             Spacing * 3));
9282     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9283     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9284     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9285     TmpInst.addOperand(Inst.getOperand(3)); // Rm
9286     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9287     TmpInst.addOperand(Inst.getOperand(5));
9288     Inst = TmpInst;
9289     return true;
9290   }
9291 
9292   // VLD4 multiple 4-element structure instructions.
9293   case ARM::VLD4dAsm_8:
9294   case ARM::VLD4dAsm_16:
9295   case ARM::VLD4dAsm_32:
9296   case ARM::VLD4qAsm_8:
9297   case ARM::VLD4qAsm_16:
9298   case ARM::VLD4qAsm_32: {
9299     MCInst TmpInst;
9300     unsigned Spacing;
9301     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9302     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9303     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9304                                             Spacing));
9305     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9306                                             Spacing * 2));
9307     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9308                                             Spacing * 3));
9309     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9310     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9311     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9312     TmpInst.addOperand(Inst.getOperand(4));
9313     Inst = TmpInst;
9314     return true;
9315   }
9316 
9317   case ARM::VLD4dWB_fixed_Asm_8:
9318   case ARM::VLD4dWB_fixed_Asm_16:
9319   case ARM::VLD4dWB_fixed_Asm_32:
9320   case ARM::VLD4qWB_fixed_Asm_8:
9321   case ARM::VLD4qWB_fixed_Asm_16:
9322   case ARM::VLD4qWB_fixed_Asm_32: {
9323     MCInst TmpInst;
9324     unsigned Spacing;
9325     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9326     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9327     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9328                                             Spacing));
9329     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9330                                             Spacing * 2));
9331     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9332                                             Spacing * 3));
9333     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9334     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9335     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9336     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9337     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9338     TmpInst.addOperand(Inst.getOperand(4));
9339     Inst = TmpInst;
9340     return true;
9341   }
9342 
9343   case ARM::VLD4dWB_register_Asm_8:
9344   case ARM::VLD4dWB_register_Asm_16:
9345   case ARM::VLD4dWB_register_Asm_32:
9346   case ARM::VLD4qWB_register_Asm_8:
9347   case ARM::VLD4qWB_register_Asm_16:
9348   case ARM::VLD4qWB_register_Asm_32: {
9349     MCInst TmpInst;
9350     unsigned Spacing;
9351     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
9352     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9353     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9354                                             Spacing));
9355     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9356                                             Spacing * 2));
9357     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9358                                             Spacing * 3));
9359     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9360     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9361     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9362     TmpInst.addOperand(Inst.getOperand(3)); // Rm
9363     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9364     TmpInst.addOperand(Inst.getOperand(5));
9365     Inst = TmpInst;
9366     return true;
9367   }
9368 
9369   // VST3 multiple 3-element structure instructions.
9370   case ARM::VST3dAsm_8:
9371   case ARM::VST3dAsm_16:
9372   case ARM::VST3dAsm_32:
9373   case ARM::VST3qAsm_8:
9374   case ARM::VST3qAsm_16:
9375   case ARM::VST3qAsm_32: {
9376     MCInst TmpInst;
9377     unsigned Spacing;
9378     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9379     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9380     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9381     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9382     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9383                                             Spacing));
9384     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9385                                             Spacing * 2));
9386     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9387     TmpInst.addOperand(Inst.getOperand(4));
9388     Inst = TmpInst;
9389     return true;
9390   }
9391 
9392   case ARM::VST3dWB_fixed_Asm_8:
9393   case ARM::VST3dWB_fixed_Asm_16:
9394   case ARM::VST3dWB_fixed_Asm_32:
9395   case ARM::VST3qWB_fixed_Asm_8:
9396   case ARM::VST3qWB_fixed_Asm_16:
9397   case ARM::VST3qWB_fixed_Asm_32: {
9398     MCInst TmpInst;
9399     unsigned Spacing;
9400     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9401     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9402     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9403     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9404     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9405     TmpInst.addOperand(Inst.getOperand(0)); // 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(Inst.getOperand(3)); // CondCode
9411     TmpInst.addOperand(Inst.getOperand(4));
9412     Inst = TmpInst;
9413     return true;
9414   }
9415 
9416   case ARM::VST3dWB_register_Asm_8:
9417   case ARM::VST3dWB_register_Asm_16:
9418   case ARM::VST3dWB_register_Asm_32:
9419   case ARM::VST3qWB_register_Asm_8:
9420   case ARM::VST3qWB_register_Asm_16:
9421   case ARM::VST3qWB_register_Asm_32: {
9422     MCInst TmpInst;
9423     unsigned Spacing;
9424     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9425     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9426     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9427     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9428     TmpInst.addOperand(Inst.getOperand(3)); // Rm
9429     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9430     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9431                                             Spacing));
9432     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9433                                             Spacing * 2));
9434     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9435     TmpInst.addOperand(Inst.getOperand(5));
9436     Inst = TmpInst;
9437     return true;
9438   }
9439 
9440   // VST4 multiple 3-element structure instructions.
9441   case ARM::VST4dAsm_8:
9442   case ARM::VST4dAsm_16:
9443   case ARM::VST4dAsm_32:
9444   case ARM::VST4qAsm_8:
9445   case ARM::VST4qAsm_16:
9446   case ARM::VST4qAsm_32: {
9447     MCInst TmpInst;
9448     unsigned Spacing;
9449     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9450     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9451     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9452     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9453     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9454                                             Spacing));
9455     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9456                                             Spacing * 2));
9457     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9458                                             Spacing * 3));
9459     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9460     TmpInst.addOperand(Inst.getOperand(4));
9461     Inst = TmpInst;
9462     return true;
9463   }
9464 
9465   case ARM::VST4dWB_fixed_Asm_8:
9466   case ARM::VST4dWB_fixed_Asm_16:
9467   case ARM::VST4dWB_fixed_Asm_32:
9468   case ARM::VST4qWB_fixed_Asm_8:
9469   case ARM::VST4qWB_fixed_Asm_16:
9470   case ARM::VST4qWB_fixed_Asm_32: {
9471     MCInst TmpInst;
9472     unsigned Spacing;
9473     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9474     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9475     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9476     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9477     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
9478     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9479     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9480                                             Spacing));
9481     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9482                                             Spacing * 2));
9483     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9484                                             Spacing * 3));
9485     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9486     TmpInst.addOperand(Inst.getOperand(4));
9487     Inst = TmpInst;
9488     return true;
9489   }
9490 
9491   case ARM::VST4dWB_register_Asm_8:
9492   case ARM::VST4dWB_register_Asm_16:
9493   case ARM::VST4dWB_register_Asm_32:
9494   case ARM::VST4qWB_register_Asm_8:
9495   case ARM::VST4qWB_register_Asm_16:
9496   case ARM::VST4qWB_register_Asm_32: {
9497     MCInst TmpInst;
9498     unsigned Spacing;
9499     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
9500     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9501     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
9502     TmpInst.addOperand(Inst.getOperand(2)); // alignment
9503     TmpInst.addOperand(Inst.getOperand(3)); // Rm
9504     TmpInst.addOperand(Inst.getOperand(0)); // Vd
9505     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9506                                             Spacing));
9507     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9508                                             Spacing * 2));
9509     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
9510                                             Spacing * 3));
9511     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9512     TmpInst.addOperand(Inst.getOperand(5));
9513     Inst = TmpInst;
9514     return true;
9515   }
9516 
9517   // Handle encoding choice for the shift-immediate instructions.
9518   case ARM::t2LSLri:
9519   case ARM::t2LSRri:
9520   case ARM::t2ASRri:
9521     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
9522         isARMLowRegister(Inst.getOperand(1).getReg()) &&
9523         Inst.getOperand(5).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
9524         !HasWideQualifier) {
9525       unsigned NewOpc;
9526       switch (Inst.getOpcode()) {
9527       default: llvm_unreachable("unexpected opcode");
9528       case ARM::t2LSLri: NewOpc = ARM::tLSLri; break;
9529       case ARM::t2LSRri: NewOpc = ARM::tLSRri; break;
9530       case ARM::t2ASRri: NewOpc = ARM::tASRri; break;
9531       }
9532       // The Thumb1 operands aren't in the same order. Awesome, eh?
9533       MCInst TmpInst;
9534       TmpInst.setOpcode(NewOpc);
9535       TmpInst.addOperand(Inst.getOperand(0));
9536       TmpInst.addOperand(Inst.getOperand(5));
9537       TmpInst.addOperand(Inst.getOperand(1));
9538       TmpInst.addOperand(Inst.getOperand(2));
9539       TmpInst.addOperand(Inst.getOperand(3));
9540       TmpInst.addOperand(Inst.getOperand(4));
9541       Inst = TmpInst;
9542       return true;
9543     }
9544     return false;
9545 
9546   // Handle the Thumb2 mode MOV complex aliases.
9547   case ARM::t2MOVsr:
9548   case ARM::t2MOVSsr: {
9549     // Which instruction to expand to depends on the CCOut operand and
9550     // whether we're in an IT block if the register operands are low
9551     // registers.
9552     bool isNarrow = false;
9553     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
9554         isARMLowRegister(Inst.getOperand(1).getReg()) &&
9555         isARMLowRegister(Inst.getOperand(2).getReg()) &&
9556         Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() &&
9557         inITBlock() == (Inst.getOpcode() == ARM::t2MOVsr) &&
9558         !HasWideQualifier)
9559       isNarrow = true;
9560     MCInst TmpInst;
9561     unsigned newOpc;
9562     switch(ARM_AM::getSORegShOp(Inst.getOperand(3).getImm())) {
9563     default: llvm_unreachable("unexpected opcode!");
9564     case ARM_AM::asr: newOpc = isNarrow ? ARM::tASRrr : ARM::t2ASRrr; break;
9565     case ARM_AM::lsr: newOpc = isNarrow ? ARM::tLSRrr : ARM::t2LSRrr; break;
9566     case ARM_AM::lsl: newOpc = isNarrow ? ARM::tLSLrr : ARM::t2LSLrr; break;
9567     case ARM_AM::ror: newOpc = isNarrow ? ARM::tROR   : ARM::t2RORrr; break;
9568     }
9569     TmpInst.setOpcode(newOpc);
9570     TmpInst.addOperand(Inst.getOperand(0)); // Rd
9571     if (isNarrow)
9572       TmpInst.addOperand(MCOperand::createReg(
9573           Inst.getOpcode() == ARM::t2MOVSsr ? ARM::CPSR : 0));
9574     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9575     TmpInst.addOperand(Inst.getOperand(2)); // Rm
9576     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
9577     TmpInst.addOperand(Inst.getOperand(5));
9578     if (!isNarrow)
9579       TmpInst.addOperand(MCOperand::createReg(
9580           Inst.getOpcode() == ARM::t2MOVSsr ? ARM::CPSR : 0));
9581     Inst = TmpInst;
9582     return true;
9583   }
9584   case ARM::t2MOVsi:
9585   case ARM::t2MOVSsi: {
9586     // Which instruction to expand to depends on the CCOut operand and
9587     // whether we're in an IT block if the register operands are low
9588     // registers.
9589     bool isNarrow = false;
9590     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
9591         isARMLowRegister(Inst.getOperand(1).getReg()) &&
9592         inITBlock() == (Inst.getOpcode() == ARM::t2MOVsi) &&
9593         !HasWideQualifier)
9594       isNarrow = true;
9595     MCInst TmpInst;
9596     unsigned newOpc;
9597     unsigned Shift = ARM_AM::getSORegShOp(Inst.getOperand(2).getImm());
9598     unsigned Amount = ARM_AM::getSORegOffset(Inst.getOperand(2).getImm());
9599     bool isMov = false;
9600     // MOV rd, rm, LSL #0 is actually a MOV instruction
9601     if (Shift == ARM_AM::lsl && Amount == 0) {
9602       isMov = true;
9603       // The 16-bit encoding of MOV rd, rm, LSL #N is explicitly encoding T2 of
9604       // MOV (register) in the ARMv8-A and ARMv8-M manuals, and immediate 0 is
9605       // unpredictable in an IT block so the 32-bit encoding T3 has to be used
9606       // instead.
9607       if (inITBlock()) {
9608         isNarrow = false;
9609       }
9610       newOpc = isNarrow ? ARM::tMOVSr : ARM::t2MOVr;
9611     } else {
9612       switch(Shift) {
9613       default: llvm_unreachable("unexpected opcode!");
9614       case ARM_AM::asr: newOpc = isNarrow ? ARM::tASRri : ARM::t2ASRri; break;
9615       case ARM_AM::lsr: newOpc = isNarrow ? ARM::tLSRri : ARM::t2LSRri; break;
9616       case ARM_AM::lsl: newOpc = isNarrow ? ARM::tLSLri : ARM::t2LSLri; break;
9617       case ARM_AM::ror: newOpc = ARM::t2RORri; isNarrow = false; break;
9618       case ARM_AM::rrx: isNarrow = false; newOpc = ARM::t2RRX; break;
9619       }
9620     }
9621     if (Amount == 32) Amount = 0;
9622     TmpInst.setOpcode(newOpc);
9623     TmpInst.addOperand(Inst.getOperand(0)); // Rd
9624     if (isNarrow && !isMov)
9625       TmpInst.addOperand(MCOperand::createReg(
9626           Inst.getOpcode() == ARM::t2MOVSsi ? ARM::CPSR : 0));
9627     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9628     if (newOpc != ARM::t2RRX && !isMov)
9629       TmpInst.addOperand(MCOperand::createImm(Amount));
9630     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9631     TmpInst.addOperand(Inst.getOperand(4));
9632     if (!isNarrow)
9633       TmpInst.addOperand(MCOperand::createReg(
9634           Inst.getOpcode() == ARM::t2MOVSsi ? ARM::CPSR : 0));
9635     Inst = TmpInst;
9636     return true;
9637   }
9638   // Handle the ARM mode MOV complex aliases.
9639   case ARM::ASRr:
9640   case ARM::LSRr:
9641   case ARM::LSLr:
9642   case ARM::RORr: {
9643     ARM_AM::ShiftOpc ShiftTy;
9644     switch(Inst.getOpcode()) {
9645     default: llvm_unreachable("unexpected opcode!");
9646     case ARM::ASRr: ShiftTy = ARM_AM::asr; break;
9647     case ARM::LSRr: ShiftTy = ARM_AM::lsr; break;
9648     case ARM::LSLr: ShiftTy = ARM_AM::lsl; break;
9649     case ARM::RORr: ShiftTy = ARM_AM::ror; break;
9650     }
9651     unsigned Shifter = ARM_AM::getSORegOpc(ShiftTy, 0);
9652     MCInst TmpInst;
9653     TmpInst.setOpcode(ARM::MOVsr);
9654     TmpInst.addOperand(Inst.getOperand(0)); // Rd
9655     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9656     TmpInst.addOperand(Inst.getOperand(2)); // Rm
9657     TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
9658     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9659     TmpInst.addOperand(Inst.getOperand(4));
9660     TmpInst.addOperand(Inst.getOperand(5)); // cc_out
9661     Inst = TmpInst;
9662     return true;
9663   }
9664   case ARM::ASRi:
9665   case ARM::LSRi:
9666   case ARM::LSLi:
9667   case ARM::RORi: {
9668     ARM_AM::ShiftOpc ShiftTy;
9669     switch(Inst.getOpcode()) {
9670     default: llvm_unreachable("unexpected opcode!");
9671     case ARM::ASRi: ShiftTy = ARM_AM::asr; break;
9672     case ARM::LSRi: ShiftTy = ARM_AM::lsr; break;
9673     case ARM::LSLi: ShiftTy = ARM_AM::lsl; break;
9674     case ARM::RORi: ShiftTy = ARM_AM::ror; break;
9675     }
9676     // A shift by zero is a plain MOVr, not a MOVsi.
9677     unsigned Amt = Inst.getOperand(2).getImm();
9678     unsigned Opc = Amt == 0 ? ARM::MOVr : ARM::MOVsi;
9679     // A shift by 32 should be encoded as 0 when permitted
9680     if (Amt == 32 && (ShiftTy == ARM_AM::lsr || ShiftTy == ARM_AM::asr))
9681       Amt = 0;
9682     unsigned Shifter = ARM_AM::getSORegOpc(ShiftTy, Amt);
9683     MCInst TmpInst;
9684     TmpInst.setOpcode(Opc);
9685     TmpInst.addOperand(Inst.getOperand(0)); // Rd
9686     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9687     if (Opc == ARM::MOVsi)
9688       TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
9689     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
9690     TmpInst.addOperand(Inst.getOperand(4));
9691     TmpInst.addOperand(Inst.getOperand(5)); // cc_out
9692     Inst = TmpInst;
9693     return true;
9694   }
9695   case ARM::RRXi: {
9696     unsigned Shifter = ARM_AM::getSORegOpc(ARM_AM::rrx, 0);
9697     MCInst TmpInst;
9698     TmpInst.setOpcode(ARM::MOVsi);
9699     TmpInst.addOperand(Inst.getOperand(0)); // Rd
9700     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9701     TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
9702     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
9703     TmpInst.addOperand(Inst.getOperand(3));
9704     TmpInst.addOperand(Inst.getOperand(4)); // cc_out
9705     Inst = TmpInst;
9706     return true;
9707   }
9708   case ARM::t2LDMIA_UPD: {
9709     // If this is a load of a single register, then we should use
9710     // a post-indexed LDR instruction instead, per the ARM ARM.
9711     if (Inst.getNumOperands() != 5)
9712       return false;
9713     MCInst TmpInst;
9714     TmpInst.setOpcode(ARM::t2LDR_POST);
9715     TmpInst.addOperand(Inst.getOperand(4)); // Rt
9716     TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
9717     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9718     TmpInst.addOperand(MCOperand::createImm(4));
9719     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
9720     TmpInst.addOperand(Inst.getOperand(3));
9721     Inst = TmpInst;
9722     return true;
9723   }
9724   case ARM::t2STMDB_UPD: {
9725     // If this is a store of a single register, then we should use
9726     // a pre-indexed STR instruction instead, per the ARM ARM.
9727     if (Inst.getNumOperands() != 5)
9728       return false;
9729     MCInst TmpInst;
9730     TmpInst.setOpcode(ARM::t2STR_PRE);
9731     TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
9732     TmpInst.addOperand(Inst.getOperand(4)); // Rt
9733     TmpInst.addOperand(Inst.getOperand(1)); // Rn
9734     TmpInst.addOperand(MCOperand::createImm(-4));
9735     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
9736     TmpInst.addOperand(Inst.getOperand(3));
9737     Inst = TmpInst;
9738     return true;
9739   }
9740   case ARM::LDMIA_UPD:
9741     // If this is a load of a single register via a 'pop', then we should use
9742     // a post-indexed LDR instruction instead, per the ARM ARM.
9743     if (static_cast<ARMOperand &>(*Operands[0]).getToken() == "pop" &&
9744         Inst.getNumOperands() == 5) {
9745       MCInst TmpInst;
9746       TmpInst.setOpcode(ARM::LDR_POST_IMM);
9747       TmpInst.addOperand(Inst.getOperand(4)); // Rt
9748       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
9749       TmpInst.addOperand(Inst.getOperand(1)); // Rn
9750       TmpInst.addOperand(MCOperand::createReg(0));  // am2offset
9751       TmpInst.addOperand(MCOperand::createImm(4));
9752       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
9753       TmpInst.addOperand(Inst.getOperand(3));
9754       Inst = TmpInst;
9755       return true;
9756     }
9757     break;
9758   case ARM::STMDB_UPD:
9759     // If this is a store of a single register via a 'push', then we should use
9760     // a pre-indexed STR instruction instead, per the ARM ARM.
9761     if (static_cast<ARMOperand &>(*Operands[0]).getToken() == "push" &&
9762         Inst.getNumOperands() == 5) {
9763       MCInst TmpInst;
9764       TmpInst.setOpcode(ARM::STR_PRE_IMM);
9765       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
9766       TmpInst.addOperand(Inst.getOperand(4)); // Rt
9767       TmpInst.addOperand(Inst.getOperand(1)); // addrmode_imm12
9768       TmpInst.addOperand(MCOperand::createImm(-4));
9769       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
9770       TmpInst.addOperand(Inst.getOperand(3));
9771       Inst = TmpInst;
9772     }
9773     break;
9774   case ARM::t2ADDri12:
9775   case ARM::t2SUBri12:
9776   case ARM::t2ADDspImm12:
9777   case ARM::t2SUBspImm12: {
9778     // If the immediate fits for encoding T3 and the generic
9779     // mnemonic was used, encoding T3 is preferred.
9780     const StringRef Token = static_cast<ARMOperand &>(*Operands[0]).getToken();
9781     if ((Token != "add" && Token != "sub") ||
9782         ARM_AM::getT2SOImmVal(Inst.getOperand(2).getImm()) == -1)
9783       break;
9784     switch (Inst.getOpcode()) {
9785     case ARM::t2ADDri12:
9786       Inst.setOpcode(ARM::t2ADDri);
9787       break;
9788     case ARM::t2SUBri12:
9789       Inst.setOpcode(ARM::t2SUBri);
9790       break;
9791     case ARM::t2ADDspImm12:
9792       Inst.setOpcode(ARM::t2ADDspImm);
9793       break;
9794     case ARM::t2SUBspImm12:
9795       Inst.setOpcode(ARM::t2SUBspImm);
9796       break;
9797     }
9798 
9799     Inst.addOperand(MCOperand::createReg(0)); // cc_out
9800     return true;
9801   }
9802   case ARM::tADDi8:
9803     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
9804     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
9805     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
9806     // to encoding T1 if <Rd> is omitted."
9807     if ((unsigned)Inst.getOperand(3).getImm() < 8 && Operands.size() == 6) {
9808       Inst.setOpcode(ARM::tADDi3);
9809       return true;
9810     }
9811     break;
9812   case ARM::tSUBi8:
9813     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
9814     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
9815     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
9816     // to encoding T1 if <Rd> is omitted."
9817     if ((unsigned)Inst.getOperand(3).getImm() < 8 && Operands.size() == 6) {
9818       Inst.setOpcode(ARM::tSUBi3);
9819       return true;
9820     }
9821     break;
9822   case ARM::t2ADDri:
9823   case ARM::t2SUBri: {
9824     // If the destination and first source operand are the same, and
9825     // the flags are compatible with the current IT status, use encoding T2
9826     // instead of T3. For compatibility with the system 'as'. Make sure the
9827     // wide encoding wasn't explicit.
9828     if (Inst.getOperand(0).getReg() != Inst.getOperand(1).getReg() ||
9829         !isARMLowRegister(Inst.getOperand(0).getReg()) ||
9830         (Inst.getOperand(2).isImm() &&
9831          (unsigned)Inst.getOperand(2).getImm() > 255) ||
9832         Inst.getOperand(5).getReg() != (inITBlock() ? 0 : ARM::CPSR) ||
9833         HasWideQualifier)
9834       break;
9835     MCInst TmpInst;
9836     TmpInst.setOpcode(Inst.getOpcode() == ARM::t2ADDri ?
9837                       ARM::tADDi8 : ARM::tSUBi8);
9838     TmpInst.addOperand(Inst.getOperand(0));
9839     TmpInst.addOperand(Inst.getOperand(5));
9840     TmpInst.addOperand(Inst.getOperand(0));
9841     TmpInst.addOperand(Inst.getOperand(2));
9842     TmpInst.addOperand(Inst.getOperand(3));
9843     TmpInst.addOperand(Inst.getOperand(4));
9844     Inst = TmpInst;
9845     return true;
9846   }
9847   case ARM::t2ADDspImm:
9848   case ARM::t2SUBspImm: {
9849     // Prefer T1 encoding if possible
9850     if (Inst.getOperand(5).getReg() != 0 || HasWideQualifier)
9851       break;
9852     unsigned V = Inst.getOperand(2).getImm();
9853     if (V & 3 || V > ((1 << 7) - 1) << 2)
9854       break;
9855     MCInst TmpInst;
9856     TmpInst.setOpcode(Inst.getOpcode() == ARM::t2ADDspImm ? ARM::tADDspi
9857                                                           : ARM::tSUBspi);
9858     TmpInst.addOperand(MCOperand::createReg(ARM::SP)); // destination reg
9859     TmpInst.addOperand(MCOperand::createReg(ARM::SP)); // source reg
9860     TmpInst.addOperand(MCOperand::createImm(V / 4));   // immediate
9861     TmpInst.addOperand(Inst.getOperand(3));            // pred
9862     TmpInst.addOperand(Inst.getOperand(4));
9863     Inst = TmpInst;
9864     return true;
9865   }
9866   case ARM::t2ADDrr: {
9867     // If the destination and first source operand are the same, and
9868     // there's no setting of the flags, use encoding T2 instead of T3.
9869     // Note that this is only for ADD, not SUB. This mirrors the system
9870     // 'as' behaviour.  Also take advantage of ADD being commutative.
9871     // Make sure the wide encoding wasn't explicit.
9872     bool Swap = false;
9873     auto DestReg = Inst.getOperand(0).getReg();
9874     bool Transform = DestReg == Inst.getOperand(1).getReg();
9875     if (!Transform && DestReg == Inst.getOperand(2).getReg()) {
9876       Transform = true;
9877       Swap = true;
9878     }
9879     if (!Transform ||
9880         Inst.getOperand(5).getReg() != 0 ||
9881         HasWideQualifier)
9882       break;
9883     MCInst TmpInst;
9884     TmpInst.setOpcode(ARM::tADDhirr);
9885     TmpInst.addOperand(Inst.getOperand(0));
9886     TmpInst.addOperand(Inst.getOperand(0));
9887     TmpInst.addOperand(Inst.getOperand(Swap ? 1 : 2));
9888     TmpInst.addOperand(Inst.getOperand(3));
9889     TmpInst.addOperand(Inst.getOperand(4));
9890     Inst = TmpInst;
9891     return true;
9892   }
9893   case ARM::tADDrSP:
9894     // If the non-SP source operand and the destination operand are not the
9895     // same, we need to use the 32-bit encoding if it's available.
9896     if (Inst.getOperand(0).getReg() != Inst.getOperand(2).getReg()) {
9897       Inst.setOpcode(ARM::t2ADDrr);
9898       Inst.addOperand(MCOperand::createReg(0)); // cc_out
9899       return true;
9900     }
9901     break;
9902   case ARM::tB:
9903     // A Thumb conditional branch outside of an IT block is a tBcc.
9904     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock()) {
9905       Inst.setOpcode(ARM::tBcc);
9906       return true;
9907     }
9908     break;
9909   case ARM::t2B:
9910     // A Thumb2 conditional branch outside of an IT block is a t2Bcc.
9911     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock()){
9912       Inst.setOpcode(ARM::t2Bcc);
9913       return true;
9914     }
9915     break;
9916   case ARM::t2Bcc:
9917     // If the conditional is AL or we're in an IT block, we really want t2B.
9918     if (Inst.getOperand(1).getImm() == ARMCC::AL || inITBlock()) {
9919       Inst.setOpcode(ARM::t2B);
9920       return true;
9921     }
9922     break;
9923   case ARM::tBcc:
9924     // If the conditional is AL, we really want tB.
9925     if (Inst.getOperand(1).getImm() == ARMCC::AL) {
9926       Inst.setOpcode(ARM::tB);
9927       return true;
9928     }
9929     break;
9930   case ARM::tLDMIA: {
9931     // If the register list contains any high registers, or if the writeback
9932     // doesn't match what tLDMIA can do, we need to use the 32-bit encoding
9933     // instead if we're in Thumb2. Otherwise, this should have generated
9934     // an error in validateInstruction().
9935     unsigned Rn = Inst.getOperand(0).getReg();
9936     bool hasWritebackToken =
9937         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
9938          static_cast<ARMOperand &>(*Operands[3]).getToken() == "!");
9939     bool listContainsBase;
9940     if (checkLowRegisterList(Inst, 3, Rn, 0, listContainsBase) ||
9941         (!listContainsBase && !hasWritebackToken) ||
9942         (listContainsBase && hasWritebackToken)) {
9943       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
9944       assert(isThumbTwo());
9945       Inst.setOpcode(hasWritebackToken ? ARM::t2LDMIA_UPD : ARM::t2LDMIA);
9946       // If we're switching to the updating version, we need to insert
9947       // the writeback tied operand.
9948       if (hasWritebackToken)
9949         Inst.insert(Inst.begin(),
9950                     MCOperand::createReg(Inst.getOperand(0).getReg()));
9951       return true;
9952     }
9953     break;
9954   }
9955   case ARM::tSTMIA_UPD: {
9956     // If the register list contains any high registers, we need to use
9957     // the 32-bit encoding instead if we're in Thumb2. Otherwise, this
9958     // should have generated an error in validateInstruction().
9959     unsigned Rn = Inst.getOperand(0).getReg();
9960     bool listContainsBase;
9961     if (checkLowRegisterList(Inst, 4, Rn, 0, listContainsBase)) {
9962       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
9963       assert(isThumbTwo());
9964       Inst.setOpcode(ARM::t2STMIA_UPD);
9965       return true;
9966     }
9967     break;
9968   }
9969   case ARM::tPOP: {
9970     bool listContainsBase;
9971     // If the register list contains any high registers, we need to use
9972     // the 32-bit encoding instead if we're in Thumb2. Otherwise, this
9973     // should have generated an error in validateInstruction().
9974     if (!checkLowRegisterList(Inst, 2, 0, ARM::PC, listContainsBase))
9975       return false;
9976     assert(isThumbTwo());
9977     Inst.setOpcode(ARM::t2LDMIA_UPD);
9978     // Add the base register and writeback operands.
9979     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
9980     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
9981     return true;
9982   }
9983   case ARM::tPUSH: {
9984     bool listContainsBase;
9985     if (!checkLowRegisterList(Inst, 2, 0, ARM::LR, listContainsBase))
9986       return false;
9987     assert(isThumbTwo());
9988     Inst.setOpcode(ARM::t2STMDB_UPD);
9989     // Add the base register and writeback operands.
9990     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
9991     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
9992     return true;
9993   }
9994   case ARM::t2MOVi:
9995     // If we can use the 16-bit encoding and the user didn't explicitly
9996     // request the 32-bit variant, transform it here.
9997     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
9998         (Inst.getOperand(1).isImm() &&
9999          (unsigned)Inst.getOperand(1).getImm() <= 255) &&
10000         Inst.getOperand(4).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
10001         !HasWideQualifier) {
10002       // The operands aren't in the same order for tMOVi8...
10003       MCInst TmpInst;
10004       TmpInst.setOpcode(ARM::tMOVi8);
10005       TmpInst.addOperand(Inst.getOperand(0));
10006       TmpInst.addOperand(Inst.getOperand(4));
10007       TmpInst.addOperand(Inst.getOperand(1));
10008       TmpInst.addOperand(Inst.getOperand(2));
10009       TmpInst.addOperand(Inst.getOperand(3));
10010       Inst = TmpInst;
10011       return true;
10012     }
10013     break;
10014 
10015   case ARM::t2MOVr:
10016     // If we can use the 16-bit encoding and the user didn't explicitly
10017     // request the 32-bit variant, transform it here.
10018     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
10019         isARMLowRegister(Inst.getOperand(1).getReg()) &&
10020         Inst.getOperand(2).getImm() == ARMCC::AL &&
10021         Inst.getOperand(4).getReg() == ARM::CPSR &&
10022         !HasWideQualifier) {
10023       // The operands aren't the same for tMOV[S]r... (no cc_out)
10024       MCInst TmpInst;
10025       TmpInst.setOpcode(Inst.getOperand(4).getReg() ? ARM::tMOVSr : ARM::tMOVr);
10026       TmpInst.addOperand(Inst.getOperand(0));
10027       TmpInst.addOperand(Inst.getOperand(1));
10028       TmpInst.addOperand(Inst.getOperand(2));
10029       TmpInst.addOperand(Inst.getOperand(3));
10030       Inst = TmpInst;
10031       return true;
10032     }
10033     break;
10034 
10035   case ARM::t2SXTH:
10036   case ARM::t2SXTB:
10037   case ARM::t2UXTH:
10038   case ARM::t2UXTB:
10039     // If we can use the 16-bit encoding and the user didn't explicitly
10040     // request the 32-bit variant, transform it here.
10041     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
10042         isARMLowRegister(Inst.getOperand(1).getReg()) &&
10043         Inst.getOperand(2).getImm() == 0 &&
10044         !HasWideQualifier) {
10045       unsigned NewOpc;
10046       switch (Inst.getOpcode()) {
10047       default: llvm_unreachable("Illegal opcode!");
10048       case ARM::t2SXTH: NewOpc = ARM::tSXTH; break;
10049       case ARM::t2SXTB: NewOpc = ARM::tSXTB; break;
10050       case ARM::t2UXTH: NewOpc = ARM::tUXTH; break;
10051       case ARM::t2UXTB: NewOpc = ARM::tUXTB; break;
10052       }
10053       // The operands aren't the same for thumb1 (no rotate operand).
10054       MCInst TmpInst;
10055       TmpInst.setOpcode(NewOpc);
10056       TmpInst.addOperand(Inst.getOperand(0));
10057       TmpInst.addOperand(Inst.getOperand(1));
10058       TmpInst.addOperand(Inst.getOperand(3));
10059       TmpInst.addOperand(Inst.getOperand(4));
10060       Inst = TmpInst;
10061       return true;
10062     }
10063     break;
10064 
10065   case ARM::MOVsi: {
10066     ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(Inst.getOperand(2).getImm());
10067     // rrx shifts and asr/lsr of #32 is encoded as 0
10068     if (SOpc == ARM_AM::rrx || SOpc == ARM_AM::asr || SOpc == ARM_AM::lsr)
10069       return false;
10070     if (ARM_AM::getSORegOffset(Inst.getOperand(2).getImm()) == 0) {
10071       // Shifting by zero is accepted as a vanilla 'MOVr'
10072       MCInst TmpInst;
10073       TmpInst.setOpcode(ARM::MOVr);
10074       TmpInst.addOperand(Inst.getOperand(0));
10075       TmpInst.addOperand(Inst.getOperand(1));
10076       TmpInst.addOperand(Inst.getOperand(3));
10077       TmpInst.addOperand(Inst.getOperand(4));
10078       TmpInst.addOperand(Inst.getOperand(5));
10079       Inst = TmpInst;
10080       return true;
10081     }
10082     return false;
10083   }
10084   case ARM::ANDrsi:
10085   case ARM::ORRrsi:
10086   case ARM::EORrsi:
10087   case ARM::BICrsi:
10088   case ARM::SUBrsi:
10089   case ARM::ADDrsi: {
10090     unsigned newOpc;
10091     ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(Inst.getOperand(3).getImm());
10092     if (SOpc == ARM_AM::rrx) return false;
10093     switch (Inst.getOpcode()) {
10094     default: llvm_unreachable("unexpected opcode!");
10095     case ARM::ANDrsi: newOpc = ARM::ANDrr; break;
10096     case ARM::ORRrsi: newOpc = ARM::ORRrr; break;
10097     case ARM::EORrsi: newOpc = ARM::EORrr; break;
10098     case ARM::BICrsi: newOpc = ARM::BICrr; break;
10099     case ARM::SUBrsi: newOpc = ARM::SUBrr; break;
10100     case ARM::ADDrsi: newOpc = ARM::ADDrr; break;
10101     }
10102     // If the shift is by zero, use the non-shifted instruction definition.
10103     // The exception is for right shifts, where 0 == 32
10104     if (ARM_AM::getSORegOffset(Inst.getOperand(3).getImm()) == 0 &&
10105         !(SOpc == ARM_AM::lsr || SOpc == ARM_AM::asr)) {
10106       MCInst TmpInst;
10107       TmpInst.setOpcode(newOpc);
10108       TmpInst.addOperand(Inst.getOperand(0));
10109       TmpInst.addOperand(Inst.getOperand(1));
10110       TmpInst.addOperand(Inst.getOperand(2));
10111       TmpInst.addOperand(Inst.getOperand(4));
10112       TmpInst.addOperand(Inst.getOperand(5));
10113       TmpInst.addOperand(Inst.getOperand(6));
10114       Inst = TmpInst;
10115       return true;
10116     }
10117     return false;
10118   }
10119   case ARM::ITasm:
10120   case ARM::t2IT: {
10121     // Set up the IT block state according to the IT instruction we just
10122     // matched.
10123     assert(!inITBlock() && "nested IT blocks?!");
10124     startExplicitITBlock(ARMCC::CondCodes(Inst.getOperand(0).getImm()),
10125                          Inst.getOperand(1).getImm());
10126     break;
10127   }
10128   case ARM::t2LSLrr:
10129   case ARM::t2LSRrr:
10130   case ARM::t2ASRrr:
10131   case ARM::t2SBCrr:
10132   case ARM::t2RORrr:
10133   case ARM::t2BICrr:
10134     // Assemblers should use the narrow encodings of these instructions when permissible.
10135     if ((isARMLowRegister(Inst.getOperand(1).getReg()) &&
10136          isARMLowRegister(Inst.getOperand(2).getReg())) &&
10137         Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() &&
10138         Inst.getOperand(5).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
10139         !HasWideQualifier) {
10140       unsigned NewOpc;
10141       switch (Inst.getOpcode()) {
10142         default: llvm_unreachable("unexpected opcode");
10143         case ARM::t2LSLrr: NewOpc = ARM::tLSLrr; break;
10144         case ARM::t2LSRrr: NewOpc = ARM::tLSRrr; break;
10145         case ARM::t2ASRrr: NewOpc = ARM::tASRrr; break;
10146         case ARM::t2SBCrr: NewOpc = ARM::tSBC; break;
10147         case ARM::t2RORrr: NewOpc = ARM::tROR; break;
10148         case ARM::t2BICrr: NewOpc = ARM::tBIC; break;
10149       }
10150       MCInst TmpInst;
10151       TmpInst.setOpcode(NewOpc);
10152       TmpInst.addOperand(Inst.getOperand(0));
10153       TmpInst.addOperand(Inst.getOperand(5));
10154       TmpInst.addOperand(Inst.getOperand(1));
10155       TmpInst.addOperand(Inst.getOperand(2));
10156       TmpInst.addOperand(Inst.getOperand(3));
10157       TmpInst.addOperand(Inst.getOperand(4));
10158       Inst = TmpInst;
10159       return true;
10160     }
10161     return false;
10162 
10163   case ARM::t2ANDrr:
10164   case ARM::t2EORrr:
10165   case ARM::t2ADCrr:
10166   case ARM::t2ORRrr:
10167     // Assemblers should use the narrow encodings of these instructions when permissible.
10168     // These instructions are special in that they are commutable, so shorter encodings
10169     // are available more often.
10170     if ((isARMLowRegister(Inst.getOperand(1).getReg()) &&
10171          isARMLowRegister(Inst.getOperand(2).getReg())) &&
10172         (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() ||
10173          Inst.getOperand(0).getReg() == Inst.getOperand(2).getReg()) &&
10174         Inst.getOperand(5).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
10175         !HasWideQualifier) {
10176       unsigned NewOpc;
10177       switch (Inst.getOpcode()) {
10178         default: llvm_unreachable("unexpected opcode");
10179         case ARM::t2ADCrr: NewOpc = ARM::tADC; break;
10180         case ARM::t2ANDrr: NewOpc = ARM::tAND; break;
10181         case ARM::t2EORrr: NewOpc = ARM::tEOR; break;
10182         case ARM::t2ORRrr: NewOpc = ARM::tORR; break;
10183       }
10184       MCInst TmpInst;
10185       TmpInst.setOpcode(NewOpc);
10186       TmpInst.addOperand(Inst.getOperand(0));
10187       TmpInst.addOperand(Inst.getOperand(5));
10188       if (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg()) {
10189         TmpInst.addOperand(Inst.getOperand(1));
10190         TmpInst.addOperand(Inst.getOperand(2));
10191       } else {
10192         TmpInst.addOperand(Inst.getOperand(2));
10193         TmpInst.addOperand(Inst.getOperand(1));
10194       }
10195       TmpInst.addOperand(Inst.getOperand(3));
10196       TmpInst.addOperand(Inst.getOperand(4));
10197       Inst = TmpInst;
10198       return true;
10199     }
10200     return false;
10201   case ARM::MVE_VPST:
10202   case ARM::MVE_VPTv16i8:
10203   case ARM::MVE_VPTv8i16:
10204   case ARM::MVE_VPTv4i32:
10205   case ARM::MVE_VPTv16u8:
10206   case ARM::MVE_VPTv8u16:
10207   case ARM::MVE_VPTv4u32:
10208   case ARM::MVE_VPTv16s8:
10209   case ARM::MVE_VPTv8s16:
10210   case ARM::MVE_VPTv4s32:
10211   case ARM::MVE_VPTv4f32:
10212   case ARM::MVE_VPTv8f16:
10213   case ARM::MVE_VPTv16i8r:
10214   case ARM::MVE_VPTv8i16r:
10215   case ARM::MVE_VPTv4i32r:
10216   case ARM::MVE_VPTv16u8r:
10217   case ARM::MVE_VPTv8u16r:
10218   case ARM::MVE_VPTv4u32r:
10219   case ARM::MVE_VPTv16s8r:
10220   case ARM::MVE_VPTv8s16r:
10221   case ARM::MVE_VPTv4s32r:
10222   case ARM::MVE_VPTv4f32r:
10223   case ARM::MVE_VPTv8f16r: {
10224     assert(!inVPTBlock() && "Nested VPT blocks are not allowed");
10225     MCOperand &MO = Inst.getOperand(0);
10226     VPTState.Mask = MO.getImm();
10227     VPTState.CurPosition = 0;
10228     break;
10229   }
10230   }
10231   return false;
10232 }
10233 
10234 unsigned ARMAsmParser::checkTargetMatchPredicate(MCInst &Inst) {
10235   // 16-bit thumb arithmetic instructions either require or preclude the 'S'
10236   // suffix depending on whether they're in an IT block or not.
10237   unsigned Opc = Inst.getOpcode();
10238   const MCInstrDesc &MCID = MII.get(Opc);
10239   if (MCID.TSFlags & ARMII::ThumbArithFlagSetting) {
10240     assert(MCID.hasOptionalDef() &&
10241            "optionally flag setting instruction missing optional def operand");
10242     assert(MCID.NumOperands == Inst.getNumOperands() &&
10243            "operand count mismatch!");
10244     // Find the optional-def operand (cc_out).
10245     unsigned OpNo;
10246     for (OpNo = 0;
10247          !MCID.OpInfo[OpNo].isOptionalDef() && OpNo < MCID.NumOperands;
10248          ++OpNo)
10249       ;
10250     // If we're parsing Thumb1, reject it completely.
10251     if (isThumbOne() && Inst.getOperand(OpNo).getReg() != ARM::CPSR)
10252       return Match_RequiresFlagSetting;
10253     // If we're parsing Thumb2, which form is legal depends on whether we're
10254     // in an IT block.
10255     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() != ARM::CPSR &&
10256         !inITBlock())
10257       return Match_RequiresITBlock;
10258     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() == ARM::CPSR &&
10259         inITBlock())
10260       return Match_RequiresNotITBlock;
10261     // LSL with zero immediate is not allowed in an IT block
10262     if (Opc == ARM::tLSLri && Inst.getOperand(3).getImm() == 0 && inITBlock())
10263       return Match_RequiresNotITBlock;
10264   } else if (isThumbOne()) {
10265     // Some high-register supporting Thumb1 encodings only allow both registers
10266     // to be from r0-r7 when in Thumb2.
10267     if (Opc == ARM::tADDhirr && !hasV6MOps() &&
10268         isARMLowRegister(Inst.getOperand(1).getReg()) &&
10269         isARMLowRegister(Inst.getOperand(2).getReg()))
10270       return Match_RequiresThumb2;
10271     // Others only require ARMv6 or later.
10272     else if (Opc == ARM::tMOVr && !hasV6Ops() &&
10273              isARMLowRegister(Inst.getOperand(0).getReg()) &&
10274              isARMLowRegister(Inst.getOperand(1).getReg()))
10275       return Match_RequiresV6;
10276   }
10277 
10278   // Before ARMv8 the rules for when SP is allowed in t2MOVr are more complex
10279   // than the loop below can handle, so it uses the GPRnopc register class and
10280   // we do SP handling here.
10281   if (Opc == ARM::t2MOVr && !hasV8Ops())
10282   {
10283     // SP as both source and destination is not allowed
10284     if (Inst.getOperand(0).getReg() == ARM::SP &&
10285         Inst.getOperand(1).getReg() == ARM::SP)
10286       return Match_RequiresV8;
10287     // When flags-setting SP as either source or destination is not allowed
10288     if (Inst.getOperand(4).getReg() == ARM::CPSR &&
10289         (Inst.getOperand(0).getReg() == ARM::SP ||
10290          Inst.getOperand(1).getReg() == ARM::SP))
10291       return Match_RequiresV8;
10292   }
10293 
10294   switch (Inst.getOpcode()) {
10295   case ARM::VMRS:
10296   case ARM::VMSR:
10297   case ARM::VMRS_FPCXTS:
10298   case ARM::VMRS_FPCXTNS:
10299   case ARM::VMSR_FPCXTS:
10300   case ARM::VMSR_FPCXTNS:
10301   case ARM::VMRS_FPSCR_NZCVQC:
10302   case ARM::VMSR_FPSCR_NZCVQC:
10303   case ARM::FMSTAT:
10304   case ARM::VMRS_VPR:
10305   case ARM::VMRS_P0:
10306   case ARM::VMSR_VPR:
10307   case ARM::VMSR_P0:
10308     // Use of SP for VMRS/VMSR is only allowed in ARM mode with the exception of
10309     // ARMv8-A.
10310     if (Inst.getOperand(0).isReg() && Inst.getOperand(0).getReg() == ARM::SP &&
10311         (isThumb() && !hasV8Ops()))
10312       return Match_InvalidOperand;
10313     break;
10314   default:
10315     break;
10316   }
10317 
10318   for (unsigned I = 0; I < MCID.NumOperands; ++I)
10319     if (MCID.OpInfo[I].RegClass == ARM::rGPRRegClassID) {
10320       // rGPRRegClass excludes PC, and also excluded SP before ARMv8
10321       const auto &Op = Inst.getOperand(I);
10322       if (!Op.isReg()) {
10323         // This can happen in awkward cases with tied operands, e.g. a
10324         // writeback load/store with a complex addressing mode in
10325         // which there's an output operand corresponding to the
10326         // updated written-back base register: the Tablegen-generated
10327         // AsmMatcher will have written a placeholder operand to that
10328         // slot in the form of an immediate 0, because it can't
10329         // generate the register part of the complex addressing-mode
10330         // operand ahead of time.
10331         continue;
10332       }
10333 
10334       unsigned Reg = Op.getReg();
10335       if ((Reg == ARM::SP) && !hasV8Ops())
10336         return Match_RequiresV8;
10337       else if (Reg == ARM::PC)
10338         return Match_InvalidOperand;
10339     }
10340 
10341   return Match_Success;
10342 }
10343 
10344 namespace llvm {
10345 
10346 template <> inline bool IsCPSRDead<MCInst>(const MCInst *Instr) {
10347   return true; // In an assembly source, no need to second-guess
10348 }
10349 
10350 } // end namespace llvm
10351 
10352 // Returns true if Inst is unpredictable if it is in and IT block, but is not
10353 // the last instruction in the block.
10354 bool ARMAsmParser::isITBlockTerminator(MCInst &Inst) const {
10355   const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
10356 
10357   // All branch & call instructions terminate IT blocks with the exception of
10358   // SVC.
10359   if (MCID.isTerminator() || (MCID.isCall() && Inst.getOpcode() != ARM::tSVC) ||
10360       MCID.isReturn() || MCID.isBranch() || MCID.isIndirectBranch())
10361     return true;
10362 
10363   // Any arithmetic instruction which writes to the PC also terminates the IT
10364   // block.
10365   if (MCID.hasDefOfPhysReg(Inst, ARM::PC, *MRI))
10366     return true;
10367 
10368   return false;
10369 }
10370 
10371 unsigned ARMAsmParser::MatchInstruction(OperandVector &Operands, MCInst &Inst,
10372                                           SmallVectorImpl<NearMissInfo> &NearMisses,
10373                                           bool MatchingInlineAsm,
10374                                           bool &EmitInITBlock,
10375                                           MCStreamer &Out) {
10376   // If we can't use an implicit IT block here, just match as normal.
10377   if (inExplicitITBlock() || !isThumbTwo() || !useImplicitITThumb())
10378     return MatchInstructionImpl(Operands, Inst, &NearMisses, MatchingInlineAsm);
10379 
10380   // Try to match the instruction in an extension of the current IT block (if
10381   // there is one).
10382   if (inImplicitITBlock()) {
10383     extendImplicitITBlock(ITState.Cond);
10384     if (MatchInstructionImpl(Operands, Inst, nullptr, MatchingInlineAsm) ==
10385             Match_Success) {
10386       // The match succeded, but we still have to check that the instruction is
10387       // valid in this implicit IT block.
10388       const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
10389       if (MCID.isPredicable()) {
10390         ARMCC::CondCodes InstCond =
10391             (ARMCC::CondCodes)Inst.getOperand(MCID.findFirstPredOperandIdx())
10392                 .getImm();
10393         ARMCC::CondCodes ITCond = currentITCond();
10394         if (InstCond == ITCond) {
10395           EmitInITBlock = true;
10396           return Match_Success;
10397         } else if (InstCond == ARMCC::getOppositeCondition(ITCond)) {
10398           invertCurrentITCondition();
10399           EmitInITBlock = true;
10400           return Match_Success;
10401         }
10402       }
10403     }
10404     rewindImplicitITPosition();
10405   }
10406 
10407   // Finish the current IT block, and try to match outside any IT block.
10408   flushPendingInstructions(Out);
10409   unsigned PlainMatchResult =
10410       MatchInstructionImpl(Operands, Inst, &NearMisses, MatchingInlineAsm);
10411   if (PlainMatchResult == Match_Success) {
10412     const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
10413     if (MCID.isPredicable()) {
10414       ARMCC::CondCodes InstCond =
10415           (ARMCC::CondCodes)Inst.getOperand(MCID.findFirstPredOperandIdx())
10416               .getImm();
10417       // Some forms of the branch instruction have their own condition code
10418       // fields, so can be conditionally executed without an IT block.
10419       if (Inst.getOpcode() == ARM::tBcc || Inst.getOpcode() == ARM::t2Bcc) {
10420         EmitInITBlock = false;
10421         return Match_Success;
10422       }
10423       if (InstCond == ARMCC::AL) {
10424         EmitInITBlock = false;
10425         return Match_Success;
10426       }
10427     } else {
10428       EmitInITBlock = false;
10429       return Match_Success;
10430     }
10431   }
10432 
10433   // Try to match in a new IT block. The matcher doesn't check the actual
10434   // condition, so we create an IT block with a dummy condition, and fix it up
10435   // once we know the actual condition.
10436   startImplicitITBlock();
10437   if (MatchInstructionImpl(Operands, Inst, nullptr, MatchingInlineAsm) ==
10438       Match_Success) {
10439     const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
10440     if (MCID.isPredicable()) {
10441       ITState.Cond =
10442           (ARMCC::CondCodes)Inst.getOperand(MCID.findFirstPredOperandIdx())
10443               .getImm();
10444       EmitInITBlock = true;
10445       return Match_Success;
10446     }
10447   }
10448   discardImplicitITBlock();
10449 
10450   // If none of these succeed, return the error we got when trying to match
10451   // outside any IT blocks.
10452   EmitInITBlock = false;
10453   return PlainMatchResult;
10454 }
10455 
10456 static std::string ARMMnemonicSpellCheck(StringRef S, const FeatureBitset &FBS,
10457                                          unsigned VariantID = 0);
10458 
10459 static const char *getSubtargetFeatureName(uint64_t Val);
10460 bool ARMAsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
10461                                            OperandVector &Operands,
10462                                            MCStreamer &Out, uint64_t &ErrorInfo,
10463                                            bool MatchingInlineAsm) {
10464   MCInst Inst;
10465   unsigned MatchResult;
10466   bool PendConditionalInstruction = false;
10467 
10468   SmallVector<NearMissInfo, 4> NearMisses;
10469   MatchResult = MatchInstruction(Operands, Inst, NearMisses, MatchingInlineAsm,
10470                                  PendConditionalInstruction, Out);
10471 
10472   switch (MatchResult) {
10473   case Match_Success:
10474     LLVM_DEBUG(dbgs() << "Parsed as: ";
10475                Inst.dump_pretty(dbgs(), MII.getName(Inst.getOpcode()));
10476                dbgs() << "\n");
10477 
10478     // Context sensitive operand constraints aren't handled by the matcher,
10479     // so check them here.
10480     if (validateInstruction(Inst, Operands)) {
10481       // Still progress the IT block, otherwise one wrong condition causes
10482       // nasty cascading errors.
10483       forwardITPosition();
10484       forwardVPTPosition();
10485       return true;
10486     }
10487 
10488     { // processInstruction() updates inITBlock state, we need to save it away
10489       bool wasInITBlock = inITBlock();
10490 
10491       // Some instructions need post-processing to, for example, tweak which
10492       // encoding is selected. Loop on it while changes happen so the
10493       // individual transformations can chain off each other. E.g.,
10494       // tPOP(r8)->t2LDMIA_UPD(sp,r8)->t2STR_POST(sp,r8)
10495       while (processInstruction(Inst, Operands, Out))
10496         LLVM_DEBUG(dbgs() << "Changed to: ";
10497                    Inst.dump_pretty(dbgs(), MII.getName(Inst.getOpcode()));
10498                    dbgs() << "\n");
10499 
10500       // Only after the instruction is fully processed, we can validate it
10501       if (wasInITBlock && hasV8Ops() && isThumb() &&
10502           !isV8EligibleForIT(&Inst)) {
10503         Warning(IDLoc, "deprecated instruction in IT block");
10504       }
10505     }
10506 
10507     // Only move forward at the very end so that everything in validate
10508     // and process gets a consistent answer about whether we're in an IT
10509     // block.
10510     forwardITPosition();
10511     forwardVPTPosition();
10512 
10513     // ITasm is an ARM mode pseudo-instruction that just sets the ITblock and
10514     // doesn't actually encode.
10515     if (Inst.getOpcode() == ARM::ITasm)
10516       return false;
10517 
10518     Inst.setLoc(IDLoc);
10519     if (PendConditionalInstruction) {
10520       PendingConditionalInsts.push_back(Inst);
10521       if (isITBlockFull() || isITBlockTerminator(Inst))
10522         flushPendingInstructions(Out);
10523     } else {
10524       Out.emitInstruction(Inst, getSTI());
10525     }
10526     return false;
10527   case Match_NearMisses:
10528     ReportNearMisses(NearMisses, IDLoc, Operands);
10529     return true;
10530   case Match_MnemonicFail: {
10531     FeatureBitset FBS = ComputeAvailableFeatures(getSTI().getFeatureBits());
10532     std::string Suggestion = ARMMnemonicSpellCheck(
10533       ((ARMOperand &)*Operands[0]).getToken(), FBS);
10534     return Error(IDLoc, "invalid instruction" + Suggestion,
10535                  ((ARMOperand &)*Operands[0]).getLocRange());
10536   }
10537   }
10538 
10539   llvm_unreachable("Implement any new match types added!");
10540 }
10541 
10542 /// parseDirective parses the arm specific directives
10543 bool ARMAsmParser::ParseDirective(AsmToken DirectiveID) {
10544   const MCObjectFileInfo::Environment Format =
10545     getContext().getObjectFileInfo()->getObjectFileType();
10546   bool IsMachO = Format == MCObjectFileInfo::IsMachO;
10547   bool IsCOFF = Format == MCObjectFileInfo::IsCOFF;
10548 
10549   std::string IDVal = DirectiveID.getIdentifier().lower();
10550   if (IDVal == ".word")
10551     parseLiteralValues(4, DirectiveID.getLoc());
10552   else if (IDVal == ".short" || IDVal == ".hword")
10553     parseLiteralValues(2, DirectiveID.getLoc());
10554   else if (IDVal == ".thumb")
10555     parseDirectiveThumb(DirectiveID.getLoc());
10556   else if (IDVal == ".arm")
10557     parseDirectiveARM(DirectiveID.getLoc());
10558   else if (IDVal == ".thumb_func")
10559     parseDirectiveThumbFunc(DirectiveID.getLoc());
10560   else if (IDVal == ".code")
10561     parseDirectiveCode(DirectiveID.getLoc());
10562   else if (IDVal == ".syntax")
10563     parseDirectiveSyntax(DirectiveID.getLoc());
10564   else if (IDVal == ".unreq")
10565     parseDirectiveUnreq(DirectiveID.getLoc());
10566   else if (IDVal == ".fnend")
10567     parseDirectiveFnEnd(DirectiveID.getLoc());
10568   else if (IDVal == ".cantunwind")
10569     parseDirectiveCantUnwind(DirectiveID.getLoc());
10570   else if (IDVal == ".personality")
10571     parseDirectivePersonality(DirectiveID.getLoc());
10572   else if (IDVal == ".handlerdata")
10573     parseDirectiveHandlerData(DirectiveID.getLoc());
10574   else if (IDVal == ".setfp")
10575     parseDirectiveSetFP(DirectiveID.getLoc());
10576   else if (IDVal == ".pad")
10577     parseDirectivePad(DirectiveID.getLoc());
10578   else if (IDVal == ".save")
10579     parseDirectiveRegSave(DirectiveID.getLoc(), false);
10580   else if (IDVal == ".vsave")
10581     parseDirectiveRegSave(DirectiveID.getLoc(), true);
10582   else if (IDVal == ".ltorg" || IDVal == ".pool")
10583     parseDirectiveLtorg(DirectiveID.getLoc());
10584   else if (IDVal == ".even")
10585     parseDirectiveEven(DirectiveID.getLoc());
10586   else if (IDVal == ".personalityindex")
10587     parseDirectivePersonalityIndex(DirectiveID.getLoc());
10588   else if (IDVal == ".unwind_raw")
10589     parseDirectiveUnwindRaw(DirectiveID.getLoc());
10590   else if (IDVal == ".movsp")
10591     parseDirectiveMovSP(DirectiveID.getLoc());
10592   else if (IDVal == ".arch_extension")
10593     parseDirectiveArchExtension(DirectiveID.getLoc());
10594   else if (IDVal == ".align")
10595     return parseDirectiveAlign(DirectiveID.getLoc()); // Use Generic on failure.
10596   else if (IDVal == ".thumb_set")
10597     parseDirectiveThumbSet(DirectiveID.getLoc());
10598   else if (IDVal == ".inst")
10599     parseDirectiveInst(DirectiveID.getLoc());
10600   else if (IDVal == ".inst.n")
10601     parseDirectiveInst(DirectiveID.getLoc(), 'n');
10602   else if (IDVal == ".inst.w")
10603     parseDirectiveInst(DirectiveID.getLoc(), 'w');
10604   else if (!IsMachO && !IsCOFF) {
10605     if (IDVal == ".arch")
10606       parseDirectiveArch(DirectiveID.getLoc());
10607     else if (IDVal == ".cpu")
10608       parseDirectiveCPU(DirectiveID.getLoc());
10609     else if (IDVal == ".eabi_attribute")
10610       parseDirectiveEabiAttr(DirectiveID.getLoc());
10611     else if (IDVal == ".fpu")
10612       parseDirectiveFPU(DirectiveID.getLoc());
10613     else if (IDVal == ".fnstart")
10614       parseDirectiveFnStart(DirectiveID.getLoc());
10615     else if (IDVal == ".object_arch")
10616       parseDirectiveObjectArch(DirectiveID.getLoc());
10617     else if (IDVal == ".tlsdescseq")
10618       parseDirectiveTLSDescSeq(DirectiveID.getLoc());
10619     else
10620       return true;
10621   } else
10622     return true;
10623   return false;
10624 }
10625 
10626 /// parseLiteralValues
10627 ///  ::= .hword expression [, expression]*
10628 ///  ::= .short expression [, expression]*
10629 ///  ::= .word expression [, expression]*
10630 bool ARMAsmParser::parseLiteralValues(unsigned Size, SMLoc L) {
10631   auto parseOne = [&]() -> bool {
10632     const MCExpr *Value;
10633     if (getParser().parseExpression(Value))
10634       return true;
10635     getParser().getStreamer().emitValue(Value, Size, L);
10636     return false;
10637   };
10638   return (parseMany(parseOne));
10639 }
10640 
10641 /// parseDirectiveThumb
10642 ///  ::= .thumb
10643 bool ARMAsmParser::parseDirectiveThumb(SMLoc L) {
10644   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive") ||
10645       check(!hasThumb(), L, "target does not support Thumb mode"))
10646     return true;
10647 
10648   if (!isThumb())
10649     SwitchMode();
10650 
10651   getParser().getStreamer().emitAssemblerFlag(MCAF_Code16);
10652   return false;
10653 }
10654 
10655 /// parseDirectiveARM
10656 ///  ::= .arm
10657 bool ARMAsmParser::parseDirectiveARM(SMLoc L) {
10658   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive") ||
10659       check(!hasARM(), L, "target does not support ARM mode"))
10660     return true;
10661 
10662   if (isThumb())
10663     SwitchMode();
10664   getParser().getStreamer().emitAssemblerFlag(MCAF_Code32);
10665   return false;
10666 }
10667 
10668 void ARMAsmParser::doBeforeLabelEmit(MCSymbol *Symbol) {
10669   // We need to flush the current implicit IT block on a label, because it is
10670   // not legal to branch into an IT block.
10671   flushPendingInstructions(getStreamer());
10672 }
10673 
10674 void ARMAsmParser::onLabelParsed(MCSymbol *Symbol) {
10675   if (NextSymbolIsThumb) {
10676     getParser().getStreamer().emitThumbFunc(Symbol);
10677     NextSymbolIsThumb = false;
10678   }
10679 }
10680 
10681 /// parseDirectiveThumbFunc
10682 ///  ::= .thumbfunc symbol_name
10683 bool ARMAsmParser::parseDirectiveThumbFunc(SMLoc L) {
10684   MCAsmParser &Parser = getParser();
10685   const auto Format = getContext().getObjectFileInfo()->getObjectFileType();
10686   bool IsMachO = Format == MCObjectFileInfo::IsMachO;
10687 
10688   // Darwin asm has (optionally) function name after .thumb_func direction
10689   // ELF doesn't
10690 
10691   if (IsMachO) {
10692     if (Parser.getTok().is(AsmToken::Identifier) ||
10693         Parser.getTok().is(AsmToken::String)) {
10694       MCSymbol *Func = getParser().getContext().getOrCreateSymbol(
10695           Parser.getTok().getIdentifier());
10696       getParser().getStreamer().emitThumbFunc(Func);
10697       Parser.Lex();
10698       if (parseToken(AsmToken::EndOfStatement,
10699                      "unexpected token in '.thumb_func' directive"))
10700         return true;
10701       return false;
10702     }
10703   }
10704 
10705   if (parseToken(AsmToken::EndOfStatement,
10706                  "unexpected token in '.thumb_func' directive"))
10707     return true;
10708 
10709   NextSymbolIsThumb = true;
10710   return false;
10711 }
10712 
10713 /// parseDirectiveSyntax
10714 ///  ::= .syntax unified | divided
10715 bool ARMAsmParser::parseDirectiveSyntax(SMLoc L) {
10716   MCAsmParser &Parser = getParser();
10717   const AsmToken &Tok = Parser.getTok();
10718   if (Tok.isNot(AsmToken::Identifier)) {
10719     Error(L, "unexpected token in .syntax directive");
10720     return false;
10721   }
10722 
10723   StringRef Mode = Tok.getString();
10724   Parser.Lex();
10725   if (check(Mode == "divided" || Mode == "DIVIDED", L,
10726             "'.syntax divided' arm assembly not supported") ||
10727       check(Mode != "unified" && Mode != "UNIFIED", L,
10728             "unrecognized syntax mode in .syntax directive") ||
10729       parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
10730     return true;
10731 
10732   // TODO tell the MC streamer the mode
10733   // getParser().getStreamer().Emit???();
10734   return false;
10735 }
10736 
10737 /// parseDirectiveCode
10738 ///  ::= .code 16 | 32
10739 bool ARMAsmParser::parseDirectiveCode(SMLoc L) {
10740   MCAsmParser &Parser = getParser();
10741   const AsmToken &Tok = Parser.getTok();
10742   if (Tok.isNot(AsmToken::Integer))
10743     return Error(L, "unexpected token in .code directive");
10744   int64_t Val = Parser.getTok().getIntVal();
10745   if (Val != 16 && Val != 32) {
10746     Error(L, "invalid operand to .code directive");
10747     return false;
10748   }
10749   Parser.Lex();
10750 
10751   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
10752     return true;
10753 
10754   if (Val == 16) {
10755     if (!hasThumb())
10756       return Error(L, "target does not support Thumb mode");
10757 
10758     if (!isThumb())
10759       SwitchMode();
10760     getParser().getStreamer().emitAssemblerFlag(MCAF_Code16);
10761   } else {
10762     if (!hasARM())
10763       return Error(L, "target does not support ARM mode");
10764 
10765     if (isThumb())
10766       SwitchMode();
10767     getParser().getStreamer().emitAssemblerFlag(MCAF_Code32);
10768   }
10769 
10770   return false;
10771 }
10772 
10773 /// parseDirectiveReq
10774 ///  ::= name .req registername
10775 bool ARMAsmParser::parseDirectiveReq(StringRef Name, SMLoc L) {
10776   MCAsmParser &Parser = getParser();
10777   Parser.Lex(); // Eat the '.req' token.
10778   unsigned Reg;
10779   SMLoc SRegLoc, ERegLoc;
10780   if (check(ParseRegister(Reg, SRegLoc, ERegLoc), SRegLoc,
10781             "register name expected") ||
10782       parseToken(AsmToken::EndOfStatement,
10783                  "unexpected input in .req directive."))
10784     return true;
10785 
10786   if (RegisterReqs.insert(std::make_pair(Name, Reg)).first->second != Reg)
10787     return Error(SRegLoc,
10788                  "redefinition of '" + Name + "' does not match original.");
10789 
10790   return false;
10791 }
10792 
10793 /// parseDirectiveUneq
10794 ///  ::= .unreq registername
10795 bool ARMAsmParser::parseDirectiveUnreq(SMLoc L) {
10796   MCAsmParser &Parser = getParser();
10797   if (Parser.getTok().isNot(AsmToken::Identifier))
10798     return Error(L, "unexpected input in .unreq directive.");
10799   RegisterReqs.erase(Parser.getTok().getIdentifier().lower());
10800   Parser.Lex(); // Eat the identifier.
10801   if (parseToken(AsmToken::EndOfStatement,
10802                  "unexpected input in '.unreq' directive"))
10803     return true;
10804   return false;
10805 }
10806 
10807 // After changing arch/CPU, try to put the ARM/Thumb mode back to what it was
10808 // before, if supported by the new target, or emit mapping symbols for the mode
10809 // switch.
10810 void ARMAsmParser::FixModeAfterArchChange(bool WasThumb, SMLoc Loc) {
10811   if (WasThumb != isThumb()) {
10812     if (WasThumb && hasThumb()) {
10813       // Stay in Thumb mode
10814       SwitchMode();
10815     } else if (!WasThumb && hasARM()) {
10816       // Stay in ARM mode
10817       SwitchMode();
10818     } else {
10819       // Mode switch forced, because the new arch doesn't support the old mode.
10820       getParser().getStreamer().emitAssemblerFlag(isThumb() ? MCAF_Code16
10821                                                             : MCAF_Code32);
10822       // Warn about the implcit mode switch. GAS does not switch modes here,
10823       // but instead stays in the old mode, reporting an error on any following
10824       // instructions as the mode does not exist on the target.
10825       Warning(Loc, Twine("new target does not support ") +
10826                        (WasThumb ? "thumb" : "arm") + " mode, switching to " +
10827                        (!WasThumb ? "thumb" : "arm") + " mode");
10828     }
10829   }
10830 }
10831 
10832 /// parseDirectiveArch
10833 ///  ::= .arch token
10834 bool ARMAsmParser::parseDirectiveArch(SMLoc L) {
10835   StringRef Arch = getParser().parseStringToEndOfStatement().trim();
10836   ARM::ArchKind ID = ARM::parseArch(Arch);
10837 
10838   if (ID == ARM::ArchKind::INVALID)
10839     return Error(L, "Unknown arch name");
10840 
10841   bool WasThumb = isThumb();
10842   Triple T;
10843   MCSubtargetInfo &STI = copySTI();
10844   STI.setDefaultFeatures("", ("+" + ARM::getArchName(ID)).str());
10845   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
10846   FixModeAfterArchChange(WasThumb, L);
10847 
10848   getTargetStreamer().emitArch(ID);
10849   return false;
10850 }
10851 
10852 /// parseDirectiveEabiAttr
10853 ///  ::= .eabi_attribute int, int [, "str"]
10854 ///  ::= .eabi_attribute Tag_name, int [, "str"]
10855 bool ARMAsmParser::parseDirectiveEabiAttr(SMLoc L) {
10856   MCAsmParser &Parser = getParser();
10857   int64_t Tag;
10858   SMLoc TagLoc;
10859   TagLoc = Parser.getTok().getLoc();
10860   if (Parser.getTok().is(AsmToken::Identifier)) {
10861     StringRef Name = Parser.getTok().getIdentifier();
10862     Tag = ARMBuildAttrs::AttrTypeFromString(Name);
10863     if (Tag == -1) {
10864       Error(TagLoc, "attribute name not recognised: " + Name);
10865       return false;
10866     }
10867     Parser.Lex();
10868   } else {
10869     const MCExpr *AttrExpr;
10870 
10871     TagLoc = Parser.getTok().getLoc();
10872     if (Parser.parseExpression(AttrExpr))
10873       return true;
10874 
10875     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(AttrExpr);
10876     if (check(!CE, TagLoc, "expected numeric constant"))
10877       return true;
10878 
10879     Tag = CE->getValue();
10880   }
10881 
10882   if (Parser.parseToken(AsmToken::Comma, "comma expected"))
10883     return true;
10884 
10885   StringRef StringValue = "";
10886   bool IsStringValue = false;
10887 
10888   int64_t IntegerValue = 0;
10889   bool IsIntegerValue = false;
10890 
10891   if (Tag == ARMBuildAttrs::CPU_raw_name || Tag == ARMBuildAttrs::CPU_name)
10892     IsStringValue = true;
10893   else if (Tag == ARMBuildAttrs::compatibility) {
10894     IsStringValue = true;
10895     IsIntegerValue = true;
10896   } else if (Tag < 32 || Tag % 2 == 0)
10897     IsIntegerValue = true;
10898   else if (Tag % 2 == 1)
10899     IsStringValue = true;
10900   else
10901     llvm_unreachable("invalid tag type");
10902 
10903   if (IsIntegerValue) {
10904     const MCExpr *ValueExpr;
10905     SMLoc ValueExprLoc = Parser.getTok().getLoc();
10906     if (Parser.parseExpression(ValueExpr))
10907       return true;
10908 
10909     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ValueExpr);
10910     if (!CE)
10911       return Error(ValueExprLoc, "expected numeric constant");
10912     IntegerValue = CE->getValue();
10913   }
10914 
10915   if (Tag == ARMBuildAttrs::compatibility) {
10916     if (Parser.parseToken(AsmToken::Comma, "comma expected"))
10917       return true;
10918   }
10919 
10920   if (IsStringValue) {
10921     if (Parser.getTok().isNot(AsmToken::String))
10922       return Error(Parser.getTok().getLoc(), "bad string constant");
10923 
10924     StringValue = Parser.getTok().getStringContents();
10925     Parser.Lex();
10926   }
10927 
10928   if (Parser.parseToken(AsmToken::EndOfStatement,
10929                         "unexpected token in '.eabi_attribute' directive"))
10930     return true;
10931 
10932   if (IsIntegerValue && IsStringValue) {
10933     assert(Tag == ARMBuildAttrs::compatibility);
10934     getTargetStreamer().emitIntTextAttribute(Tag, IntegerValue, StringValue);
10935   } else if (IsIntegerValue)
10936     getTargetStreamer().emitAttribute(Tag, IntegerValue);
10937   else if (IsStringValue)
10938     getTargetStreamer().emitTextAttribute(Tag, StringValue);
10939   return false;
10940 }
10941 
10942 /// parseDirectiveCPU
10943 ///  ::= .cpu str
10944 bool ARMAsmParser::parseDirectiveCPU(SMLoc L) {
10945   StringRef CPU = getParser().parseStringToEndOfStatement().trim();
10946   getTargetStreamer().emitTextAttribute(ARMBuildAttrs::CPU_name, CPU);
10947 
10948   // FIXME: This is using table-gen data, but should be moved to
10949   // ARMTargetParser once that is table-gen'd.
10950   if (!getSTI().isCPUStringValid(CPU))
10951     return Error(L, "Unknown CPU name");
10952 
10953   bool WasThumb = isThumb();
10954   MCSubtargetInfo &STI = copySTI();
10955   STI.setDefaultFeatures(CPU, "");
10956   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
10957   FixModeAfterArchChange(WasThumb, L);
10958 
10959   return false;
10960 }
10961 
10962 /// parseDirectiveFPU
10963 ///  ::= .fpu str
10964 bool ARMAsmParser::parseDirectiveFPU(SMLoc L) {
10965   SMLoc FPUNameLoc = getTok().getLoc();
10966   StringRef FPU = getParser().parseStringToEndOfStatement().trim();
10967 
10968   unsigned ID = ARM::parseFPU(FPU);
10969   std::vector<StringRef> Features;
10970   if (!ARM::getFPUFeatures(ID, Features))
10971     return Error(FPUNameLoc, "Unknown FPU name");
10972 
10973   MCSubtargetInfo &STI = copySTI();
10974   for (auto Feature : Features)
10975     STI.ApplyFeatureFlag(Feature);
10976   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
10977 
10978   getTargetStreamer().emitFPU(ID);
10979   return false;
10980 }
10981 
10982 /// parseDirectiveFnStart
10983 ///  ::= .fnstart
10984 bool ARMAsmParser::parseDirectiveFnStart(SMLoc L) {
10985   if (parseToken(AsmToken::EndOfStatement,
10986                  "unexpected token in '.fnstart' directive"))
10987     return true;
10988 
10989   if (UC.hasFnStart()) {
10990     Error(L, ".fnstart starts before the end of previous one");
10991     UC.emitFnStartLocNotes();
10992     return true;
10993   }
10994 
10995   // Reset the unwind directives parser state
10996   UC.reset();
10997 
10998   getTargetStreamer().emitFnStart();
10999 
11000   UC.recordFnStart(L);
11001   return false;
11002 }
11003 
11004 /// parseDirectiveFnEnd
11005 ///  ::= .fnend
11006 bool ARMAsmParser::parseDirectiveFnEnd(SMLoc L) {
11007   if (parseToken(AsmToken::EndOfStatement,
11008                  "unexpected token in '.fnend' directive"))
11009     return true;
11010   // Check the ordering of unwind directives
11011   if (!UC.hasFnStart())
11012     return Error(L, ".fnstart must precede .fnend directive");
11013 
11014   // Reset the unwind directives parser state
11015   getTargetStreamer().emitFnEnd();
11016 
11017   UC.reset();
11018   return false;
11019 }
11020 
11021 /// parseDirectiveCantUnwind
11022 ///  ::= .cantunwind
11023 bool ARMAsmParser::parseDirectiveCantUnwind(SMLoc L) {
11024   if (parseToken(AsmToken::EndOfStatement,
11025                  "unexpected token in '.cantunwind' directive"))
11026     return true;
11027 
11028   UC.recordCantUnwind(L);
11029   // Check the ordering of unwind directives
11030   if (check(!UC.hasFnStart(), L, ".fnstart must precede .cantunwind directive"))
11031     return true;
11032 
11033   if (UC.hasHandlerData()) {
11034     Error(L, ".cantunwind can't be used with .handlerdata directive");
11035     UC.emitHandlerDataLocNotes();
11036     return true;
11037   }
11038   if (UC.hasPersonality()) {
11039     Error(L, ".cantunwind can't be used with .personality directive");
11040     UC.emitPersonalityLocNotes();
11041     return true;
11042   }
11043 
11044   getTargetStreamer().emitCantUnwind();
11045   return false;
11046 }
11047 
11048 /// parseDirectivePersonality
11049 ///  ::= .personality name
11050 bool ARMAsmParser::parseDirectivePersonality(SMLoc L) {
11051   MCAsmParser &Parser = getParser();
11052   bool HasExistingPersonality = UC.hasPersonality();
11053 
11054   // Parse the name of the personality routine
11055   if (Parser.getTok().isNot(AsmToken::Identifier))
11056     return Error(L, "unexpected input in .personality directive.");
11057   StringRef Name(Parser.getTok().getIdentifier());
11058   Parser.Lex();
11059 
11060   if (parseToken(AsmToken::EndOfStatement,
11061                  "unexpected token in '.personality' directive"))
11062     return true;
11063 
11064   UC.recordPersonality(L);
11065 
11066   // Check the ordering of unwind directives
11067   if (!UC.hasFnStart())
11068     return Error(L, ".fnstart must precede .personality directive");
11069   if (UC.cantUnwind()) {
11070     Error(L, ".personality can't be used with .cantunwind directive");
11071     UC.emitCantUnwindLocNotes();
11072     return true;
11073   }
11074   if (UC.hasHandlerData()) {
11075     Error(L, ".personality must precede .handlerdata directive");
11076     UC.emitHandlerDataLocNotes();
11077     return true;
11078   }
11079   if (HasExistingPersonality) {
11080     Error(L, "multiple personality directives");
11081     UC.emitPersonalityLocNotes();
11082     return true;
11083   }
11084 
11085   MCSymbol *PR = getParser().getContext().getOrCreateSymbol(Name);
11086   getTargetStreamer().emitPersonality(PR);
11087   return false;
11088 }
11089 
11090 /// parseDirectiveHandlerData
11091 ///  ::= .handlerdata
11092 bool ARMAsmParser::parseDirectiveHandlerData(SMLoc L) {
11093   if (parseToken(AsmToken::EndOfStatement,
11094                  "unexpected token in '.handlerdata' directive"))
11095     return true;
11096 
11097   UC.recordHandlerData(L);
11098   // Check the ordering of unwind directives
11099   if (!UC.hasFnStart())
11100     return Error(L, ".fnstart must precede .personality directive");
11101   if (UC.cantUnwind()) {
11102     Error(L, ".handlerdata can't be used with .cantunwind directive");
11103     UC.emitCantUnwindLocNotes();
11104     return true;
11105   }
11106 
11107   getTargetStreamer().emitHandlerData();
11108   return false;
11109 }
11110 
11111 /// parseDirectiveSetFP
11112 ///  ::= .setfp fpreg, spreg [, offset]
11113 bool ARMAsmParser::parseDirectiveSetFP(SMLoc L) {
11114   MCAsmParser &Parser = getParser();
11115   // Check the ordering of unwind directives
11116   if (check(!UC.hasFnStart(), L, ".fnstart must precede .setfp directive") ||
11117       check(UC.hasHandlerData(), L,
11118             ".setfp must precede .handlerdata directive"))
11119     return true;
11120 
11121   // Parse fpreg
11122   SMLoc FPRegLoc = Parser.getTok().getLoc();
11123   int FPReg = tryParseRegister();
11124 
11125   if (check(FPReg == -1, FPRegLoc, "frame pointer register expected") ||
11126       Parser.parseToken(AsmToken::Comma, "comma expected"))
11127     return true;
11128 
11129   // Parse spreg
11130   SMLoc SPRegLoc = Parser.getTok().getLoc();
11131   int SPReg = tryParseRegister();
11132   if (check(SPReg == -1, SPRegLoc, "stack pointer register expected") ||
11133       check(SPReg != ARM::SP && SPReg != UC.getFPReg(), SPRegLoc,
11134             "register should be either $sp or the latest fp register"))
11135     return true;
11136 
11137   // Update the frame pointer register
11138   UC.saveFPReg(FPReg);
11139 
11140   // Parse offset
11141   int64_t Offset = 0;
11142   if (Parser.parseOptionalToken(AsmToken::Comma)) {
11143     if (Parser.getTok().isNot(AsmToken::Hash) &&
11144         Parser.getTok().isNot(AsmToken::Dollar))
11145       return Error(Parser.getTok().getLoc(), "'#' expected");
11146     Parser.Lex(); // skip hash token.
11147 
11148     const MCExpr *OffsetExpr;
11149     SMLoc ExLoc = Parser.getTok().getLoc();
11150     SMLoc EndLoc;
11151     if (getParser().parseExpression(OffsetExpr, EndLoc))
11152       return Error(ExLoc, "malformed setfp offset");
11153     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
11154     if (check(!CE, ExLoc, "setfp offset must be an immediate"))
11155       return true;
11156     Offset = CE->getValue();
11157   }
11158 
11159   if (Parser.parseToken(AsmToken::EndOfStatement))
11160     return true;
11161 
11162   getTargetStreamer().emitSetFP(static_cast<unsigned>(FPReg),
11163                                 static_cast<unsigned>(SPReg), Offset);
11164   return false;
11165 }
11166 
11167 /// parseDirective
11168 ///  ::= .pad offset
11169 bool ARMAsmParser::parseDirectivePad(SMLoc L) {
11170   MCAsmParser &Parser = getParser();
11171   // Check the ordering of unwind directives
11172   if (!UC.hasFnStart())
11173     return Error(L, ".fnstart must precede .pad directive");
11174   if (UC.hasHandlerData())
11175     return Error(L, ".pad must precede .handlerdata directive");
11176 
11177   // Parse the offset
11178   if (Parser.getTok().isNot(AsmToken::Hash) &&
11179       Parser.getTok().isNot(AsmToken::Dollar))
11180     return Error(Parser.getTok().getLoc(), "'#' expected");
11181   Parser.Lex(); // skip hash token.
11182 
11183   const MCExpr *OffsetExpr;
11184   SMLoc ExLoc = Parser.getTok().getLoc();
11185   SMLoc EndLoc;
11186   if (getParser().parseExpression(OffsetExpr, EndLoc))
11187     return Error(ExLoc, "malformed pad offset");
11188   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
11189   if (!CE)
11190     return Error(ExLoc, "pad offset must be an immediate");
11191 
11192   if (parseToken(AsmToken::EndOfStatement,
11193                  "unexpected token in '.pad' directive"))
11194     return true;
11195 
11196   getTargetStreamer().emitPad(CE->getValue());
11197   return false;
11198 }
11199 
11200 /// parseDirectiveRegSave
11201 ///  ::= .save  { registers }
11202 ///  ::= .vsave { registers }
11203 bool ARMAsmParser::parseDirectiveRegSave(SMLoc L, bool IsVector) {
11204   // Check the ordering of unwind directives
11205   if (!UC.hasFnStart())
11206     return Error(L, ".fnstart must precede .save or .vsave directives");
11207   if (UC.hasHandlerData())
11208     return Error(L, ".save or .vsave must precede .handlerdata directive");
11209 
11210   // RAII object to make sure parsed operands are deleted.
11211   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> Operands;
11212 
11213   // Parse the register list
11214   if (parseRegisterList(Operands) ||
11215       parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
11216     return true;
11217   ARMOperand &Op = (ARMOperand &)*Operands[0];
11218   if (!IsVector && !Op.isRegList())
11219     return Error(L, ".save expects GPR registers");
11220   if (IsVector && !Op.isDPRRegList())
11221     return Error(L, ".vsave expects DPR registers");
11222 
11223   getTargetStreamer().emitRegSave(Op.getRegList(), IsVector);
11224   return false;
11225 }
11226 
11227 /// parseDirectiveInst
11228 ///  ::= .inst opcode [, ...]
11229 ///  ::= .inst.n opcode [, ...]
11230 ///  ::= .inst.w opcode [, ...]
11231 bool ARMAsmParser::parseDirectiveInst(SMLoc Loc, char Suffix) {
11232   int Width = 4;
11233 
11234   if (isThumb()) {
11235     switch (Suffix) {
11236     case 'n':
11237       Width = 2;
11238       break;
11239     case 'w':
11240       break;
11241     default:
11242       Width = 0;
11243       break;
11244     }
11245   } else {
11246     if (Suffix)
11247       return Error(Loc, "width suffixes are invalid in ARM mode");
11248   }
11249 
11250   auto parseOne = [&]() -> bool {
11251     const MCExpr *Expr;
11252     if (getParser().parseExpression(Expr))
11253       return true;
11254     const MCConstantExpr *Value = dyn_cast_or_null<MCConstantExpr>(Expr);
11255     if (!Value) {
11256       return Error(Loc, "expected constant expression");
11257     }
11258 
11259     char CurSuffix = Suffix;
11260     switch (Width) {
11261     case 2:
11262       if (Value->getValue() > 0xffff)
11263         return Error(Loc, "inst.n operand is too big, use inst.w instead");
11264       break;
11265     case 4:
11266       if (Value->getValue() > 0xffffffff)
11267         return Error(Loc, StringRef(Suffix ? "inst.w" : "inst") +
11268                               " operand is too big");
11269       break;
11270     case 0:
11271       // Thumb mode, no width indicated. Guess from the opcode, if possible.
11272       if (Value->getValue() < 0xe800)
11273         CurSuffix = 'n';
11274       else if (Value->getValue() >= 0xe8000000)
11275         CurSuffix = 'w';
11276       else
11277         return Error(Loc, "cannot determine Thumb instruction size, "
11278                           "use inst.n/inst.w instead");
11279       break;
11280     default:
11281       llvm_unreachable("only supported widths are 2 and 4");
11282     }
11283 
11284     getTargetStreamer().emitInst(Value->getValue(), CurSuffix);
11285     return false;
11286   };
11287 
11288   if (parseOptionalToken(AsmToken::EndOfStatement))
11289     return Error(Loc, "expected expression following directive");
11290   if (parseMany(parseOne))
11291     return true;
11292   return false;
11293 }
11294 
11295 /// parseDirectiveLtorg
11296 ///  ::= .ltorg | .pool
11297 bool ARMAsmParser::parseDirectiveLtorg(SMLoc L) {
11298   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
11299     return true;
11300   getTargetStreamer().emitCurrentConstantPool();
11301   return false;
11302 }
11303 
11304 bool ARMAsmParser::parseDirectiveEven(SMLoc L) {
11305   const MCSection *Section = getStreamer().getCurrentSectionOnly();
11306 
11307   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
11308     return true;
11309 
11310   if (!Section) {
11311     getStreamer().InitSections(false);
11312     Section = getStreamer().getCurrentSectionOnly();
11313   }
11314 
11315   assert(Section && "must have section to emit alignment");
11316   if (Section->UseCodeAlign())
11317     getStreamer().emitCodeAlignment(2);
11318   else
11319     getStreamer().emitValueToAlignment(2);
11320 
11321   return false;
11322 }
11323 
11324 /// parseDirectivePersonalityIndex
11325 ///   ::= .personalityindex index
11326 bool ARMAsmParser::parseDirectivePersonalityIndex(SMLoc L) {
11327   MCAsmParser &Parser = getParser();
11328   bool HasExistingPersonality = UC.hasPersonality();
11329 
11330   const MCExpr *IndexExpression;
11331   SMLoc IndexLoc = Parser.getTok().getLoc();
11332   if (Parser.parseExpression(IndexExpression) ||
11333       parseToken(AsmToken::EndOfStatement,
11334                  "unexpected token in '.personalityindex' directive")) {
11335     return true;
11336   }
11337 
11338   UC.recordPersonalityIndex(L);
11339 
11340   if (!UC.hasFnStart()) {
11341     return Error(L, ".fnstart must precede .personalityindex directive");
11342   }
11343   if (UC.cantUnwind()) {
11344     Error(L, ".personalityindex cannot be used with .cantunwind");
11345     UC.emitCantUnwindLocNotes();
11346     return true;
11347   }
11348   if (UC.hasHandlerData()) {
11349     Error(L, ".personalityindex must precede .handlerdata directive");
11350     UC.emitHandlerDataLocNotes();
11351     return true;
11352   }
11353   if (HasExistingPersonality) {
11354     Error(L, "multiple personality directives");
11355     UC.emitPersonalityLocNotes();
11356     return true;
11357   }
11358 
11359   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(IndexExpression);
11360   if (!CE)
11361     return Error(IndexLoc, "index must be a constant number");
11362   if (CE->getValue() < 0 || CE->getValue() >= ARM::EHABI::NUM_PERSONALITY_INDEX)
11363     return Error(IndexLoc,
11364                  "personality routine index should be in range [0-3]");
11365 
11366   getTargetStreamer().emitPersonalityIndex(CE->getValue());
11367   return false;
11368 }
11369 
11370 /// parseDirectiveUnwindRaw
11371 ///   ::= .unwind_raw offset, opcode [, opcode...]
11372 bool ARMAsmParser::parseDirectiveUnwindRaw(SMLoc L) {
11373   MCAsmParser &Parser = getParser();
11374   int64_t StackOffset;
11375   const MCExpr *OffsetExpr;
11376   SMLoc OffsetLoc = getLexer().getLoc();
11377 
11378   if (!UC.hasFnStart())
11379     return Error(L, ".fnstart must precede .unwind_raw directives");
11380   if (getParser().parseExpression(OffsetExpr))
11381     return Error(OffsetLoc, "expected expression");
11382 
11383   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
11384   if (!CE)
11385     return Error(OffsetLoc, "offset must be a constant");
11386 
11387   StackOffset = CE->getValue();
11388 
11389   if (Parser.parseToken(AsmToken::Comma, "expected comma"))
11390     return true;
11391 
11392   SmallVector<uint8_t, 16> Opcodes;
11393 
11394   auto parseOne = [&]() -> bool {
11395     const MCExpr *OE = nullptr;
11396     SMLoc OpcodeLoc = getLexer().getLoc();
11397     if (check(getLexer().is(AsmToken::EndOfStatement) ||
11398                   Parser.parseExpression(OE),
11399               OpcodeLoc, "expected opcode expression"))
11400       return true;
11401     const MCConstantExpr *OC = dyn_cast<MCConstantExpr>(OE);
11402     if (!OC)
11403       return Error(OpcodeLoc, "opcode value must be a constant");
11404     const int64_t Opcode = OC->getValue();
11405     if (Opcode & ~0xff)
11406       return Error(OpcodeLoc, "invalid opcode");
11407     Opcodes.push_back(uint8_t(Opcode));
11408     return false;
11409   };
11410 
11411   // Must have at least 1 element
11412   SMLoc OpcodeLoc = getLexer().getLoc();
11413   if (parseOptionalToken(AsmToken::EndOfStatement))
11414     return Error(OpcodeLoc, "expected opcode expression");
11415   if (parseMany(parseOne))
11416     return true;
11417 
11418   getTargetStreamer().emitUnwindRaw(StackOffset, Opcodes);
11419   return false;
11420 }
11421 
11422 /// parseDirectiveTLSDescSeq
11423 ///   ::= .tlsdescseq tls-variable
11424 bool ARMAsmParser::parseDirectiveTLSDescSeq(SMLoc L) {
11425   MCAsmParser &Parser = getParser();
11426 
11427   if (getLexer().isNot(AsmToken::Identifier))
11428     return TokError("expected variable after '.tlsdescseq' directive");
11429 
11430   const MCSymbolRefExpr *SRE =
11431     MCSymbolRefExpr::create(Parser.getTok().getIdentifier(),
11432                             MCSymbolRefExpr::VK_ARM_TLSDESCSEQ, getContext());
11433   Lex();
11434 
11435   if (parseToken(AsmToken::EndOfStatement,
11436                  "unexpected token in '.tlsdescseq' directive"))
11437     return true;
11438 
11439   getTargetStreamer().AnnotateTLSDescriptorSequence(SRE);
11440   return false;
11441 }
11442 
11443 /// parseDirectiveMovSP
11444 ///  ::= .movsp reg [, #offset]
11445 bool ARMAsmParser::parseDirectiveMovSP(SMLoc L) {
11446   MCAsmParser &Parser = getParser();
11447   if (!UC.hasFnStart())
11448     return Error(L, ".fnstart must precede .movsp directives");
11449   if (UC.getFPReg() != ARM::SP)
11450     return Error(L, "unexpected .movsp directive");
11451 
11452   SMLoc SPRegLoc = Parser.getTok().getLoc();
11453   int SPReg = tryParseRegister();
11454   if (SPReg == -1)
11455     return Error(SPRegLoc, "register expected");
11456   if (SPReg == ARM::SP || SPReg == ARM::PC)
11457     return Error(SPRegLoc, "sp and pc are not permitted in .movsp directive");
11458 
11459   int64_t Offset = 0;
11460   if (Parser.parseOptionalToken(AsmToken::Comma)) {
11461     if (Parser.parseToken(AsmToken::Hash, "expected #constant"))
11462       return true;
11463 
11464     const MCExpr *OffsetExpr;
11465     SMLoc OffsetLoc = Parser.getTok().getLoc();
11466 
11467     if (Parser.parseExpression(OffsetExpr))
11468       return Error(OffsetLoc, "malformed offset expression");
11469 
11470     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
11471     if (!CE)
11472       return Error(OffsetLoc, "offset must be an immediate constant");
11473 
11474     Offset = CE->getValue();
11475   }
11476 
11477   if (parseToken(AsmToken::EndOfStatement,
11478                  "unexpected token in '.movsp' directive"))
11479     return true;
11480 
11481   getTargetStreamer().emitMovSP(SPReg, Offset);
11482   UC.saveFPReg(SPReg);
11483 
11484   return false;
11485 }
11486 
11487 /// parseDirectiveObjectArch
11488 ///   ::= .object_arch name
11489 bool ARMAsmParser::parseDirectiveObjectArch(SMLoc L) {
11490   MCAsmParser &Parser = getParser();
11491   if (getLexer().isNot(AsmToken::Identifier))
11492     return Error(getLexer().getLoc(), "unexpected token");
11493 
11494   StringRef Arch = Parser.getTok().getString();
11495   SMLoc ArchLoc = Parser.getTok().getLoc();
11496   Lex();
11497 
11498   ARM::ArchKind ID = ARM::parseArch(Arch);
11499 
11500   if (ID == ARM::ArchKind::INVALID)
11501     return Error(ArchLoc, "unknown architecture '" + Arch + "'");
11502   if (parseToken(AsmToken::EndOfStatement))
11503     return true;
11504 
11505   getTargetStreamer().emitObjectArch(ID);
11506   return false;
11507 }
11508 
11509 /// parseDirectiveAlign
11510 ///   ::= .align
11511 bool ARMAsmParser::parseDirectiveAlign(SMLoc L) {
11512   // NOTE: if this is not the end of the statement, fall back to the target
11513   // agnostic handling for this directive which will correctly handle this.
11514   if (parseOptionalToken(AsmToken::EndOfStatement)) {
11515     // '.align' is target specifically handled to mean 2**2 byte alignment.
11516     const MCSection *Section = getStreamer().getCurrentSectionOnly();
11517     assert(Section && "must have section to emit alignment");
11518     if (Section->UseCodeAlign())
11519       getStreamer().emitCodeAlignment(4, 0);
11520     else
11521       getStreamer().emitValueToAlignment(4, 0, 1, 0);
11522     return false;
11523   }
11524   return true;
11525 }
11526 
11527 /// parseDirectiveThumbSet
11528 ///  ::= .thumb_set name, value
11529 bool ARMAsmParser::parseDirectiveThumbSet(SMLoc L) {
11530   MCAsmParser &Parser = getParser();
11531 
11532   StringRef Name;
11533   if (check(Parser.parseIdentifier(Name),
11534             "expected identifier after '.thumb_set'") ||
11535       parseToken(AsmToken::Comma, "expected comma after name '" + Name + "'"))
11536     return true;
11537 
11538   MCSymbol *Sym;
11539   const MCExpr *Value;
11540   if (MCParserUtils::parseAssignmentExpression(Name, /* allow_redef */ true,
11541                                                Parser, Sym, Value))
11542     return true;
11543 
11544   getTargetStreamer().emitThumbSet(Sym, Value);
11545   return false;
11546 }
11547 
11548 /// Force static initialization.
11549 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeARMAsmParser() {
11550   RegisterMCAsmParser<ARMAsmParser> X(getTheARMLETarget());
11551   RegisterMCAsmParser<ARMAsmParser> Y(getTheARMBETarget());
11552   RegisterMCAsmParser<ARMAsmParser> A(getTheThumbLETarget());
11553   RegisterMCAsmParser<ARMAsmParser> B(getTheThumbBETarget());
11554 }
11555 
11556 #define GET_REGISTER_MATCHER
11557 #define GET_SUBTARGET_FEATURE_NAME
11558 #define GET_MATCHER_IMPLEMENTATION
11559 #define GET_MNEMONIC_SPELL_CHECKER
11560 #include "ARMGenAsmMatcher.inc"
11561 
11562 // Some diagnostics need to vary with subtarget features, so they are handled
11563 // here. For example, the DPR class has either 16 or 32 registers, depending
11564 // on the FPU available.
11565 const char *
11566 ARMAsmParser::getCustomOperandDiag(ARMMatchResultTy MatchError) {
11567   switch (MatchError) {
11568   // rGPR contains sp starting with ARMv8.
11569   case Match_rGPR:
11570     return hasV8Ops() ? "operand must be a register in range [r0, r14]"
11571                       : "operand must be a register in range [r0, r12] or r14";
11572   // DPR contains 16 registers for some FPUs, and 32 for others.
11573   case Match_DPR:
11574     return hasD32() ? "operand must be a register in range [d0, d31]"
11575                     : "operand must be a register in range [d0, d15]";
11576   case Match_DPR_RegList:
11577     return hasD32() ? "operand must be a list of registers in range [d0, d31]"
11578                     : "operand must be a list of registers in range [d0, d15]";
11579 
11580   // For all other diags, use the static string from tablegen.
11581   default:
11582     return getMatchKindDiag(MatchError);
11583   }
11584 }
11585 
11586 // Process the list of near-misses, throwing away ones we don't want to report
11587 // to the user, and converting the rest to a source location and string that
11588 // should be reported.
11589 void
11590 ARMAsmParser::FilterNearMisses(SmallVectorImpl<NearMissInfo> &NearMissesIn,
11591                                SmallVectorImpl<NearMissMessage> &NearMissesOut,
11592                                SMLoc IDLoc, OperandVector &Operands) {
11593   // TODO: If operand didn't match, sub in a dummy one and run target
11594   // predicate, so that we can avoid reporting near-misses that are invalid?
11595   // TODO: Many operand types dont have SuperClasses set, so we report
11596   // redundant ones.
11597   // TODO: Some operands are superclasses of registers (e.g.
11598   // MCK_RegShiftedImm), we don't have any way to represent that currently.
11599   // TODO: This is not all ARM-specific, can some of it be factored out?
11600 
11601   // Record some information about near-misses that we have already seen, so
11602   // that we can avoid reporting redundant ones. For example, if there are
11603   // variants of an instruction that take 8- and 16-bit immediates, we want
11604   // to only report the widest one.
11605   std::multimap<unsigned, unsigned> OperandMissesSeen;
11606   SmallSet<FeatureBitset, 4> FeatureMissesSeen;
11607   bool ReportedTooFewOperands = false;
11608 
11609   // Process the near-misses in reverse order, so that we see more general ones
11610   // first, and so can avoid emitting more specific ones.
11611   for (NearMissInfo &I : reverse(NearMissesIn)) {
11612     switch (I.getKind()) {
11613     case NearMissInfo::NearMissOperand: {
11614       SMLoc OperandLoc =
11615           ((ARMOperand &)*Operands[I.getOperandIndex()]).getStartLoc();
11616       const char *OperandDiag =
11617           getCustomOperandDiag((ARMMatchResultTy)I.getOperandError());
11618 
11619       // If we have already emitted a message for a superclass, don't also report
11620       // the sub-class. We consider all operand classes that we don't have a
11621       // specialised diagnostic for to be equal for the propose of this check,
11622       // so that we don't report the generic error multiple times on the same
11623       // operand.
11624       unsigned DupCheckMatchClass = OperandDiag ? I.getOperandClass() : ~0U;
11625       auto PrevReports = OperandMissesSeen.equal_range(I.getOperandIndex());
11626       if (std::any_of(PrevReports.first, PrevReports.second,
11627                       [DupCheckMatchClass](
11628                           const std::pair<unsigned, unsigned> Pair) {
11629             if (DupCheckMatchClass == ~0U || Pair.second == ~0U)
11630               return Pair.second == DupCheckMatchClass;
11631             else
11632               return isSubclass((MatchClassKind)DupCheckMatchClass,
11633                                 (MatchClassKind)Pair.second);
11634           }))
11635         break;
11636       OperandMissesSeen.insert(
11637           std::make_pair(I.getOperandIndex(), DupCheckMatchClass));
11638 
11639       NearMissMessage Message;
11640       Message.Loc = OperandLoc;
11641       if (OperandDiag) {
11642         Message.Message = OperandDiag;
11643       } else if (I.getOperandClass() == InvalidMatchClass) {
11644         Message.Message = "too many operands for instruction";
11645       } else {
11646         Message.Message = "invalid operand for instruction";
11647         LLVM_DEBUG(
11648             dbgs() << "Missing diagnostic string for operand class "
11649                    << getMatchClassName((MatchClassKind)I.getOperandClass())
11650                    << I.getOperandClass() << ", error " << I.getOperandError()
11651                    << ", opcode " << MII.getName(I.getOpcode()) << "\n");
11652       }
11653       NearMissesOut.emplace_back(Message);
11654       break;
11655     }
11656     case NearMissInfo::NearMissFeature: {
11657       const FeatureBitset &MissingFeatures = I.getFeatures();
11658       // Don't report the same set of features twice.
11659       if (FeatureMissesSeen.count(MissingFeatures))
11660         break;
11661       FeatureMissesSeen.insert(MissingFeatures);
11662 
11663       // Special case: don't report a feature set which includes arm-mode for
11664       // targets that don't have ARM mode.
11665       if (MissingFeatures.test(Feature_IsARMBit) && !hasARM())
11666         break;
11667       // Don't report any near-misses that both require switching instruction
11668       // set, and adding other subtarget features.
11669       if (isThumb() && MissingFeatures.test(Feature_IsARMBit) &&
11670           MissingFeatures.count() > 1)
11671         break;
11672       if (!isThumb() && MissingFeatures.test(Feature_IsThumbBit) &&
11673           MissingFeatures.count() > 1)
11674         break;
11675       if (!isThumb() && MissingFeatures.test(Feature_IsThumb2Bit) &&
11676           (MissingFeatures & ~FeatureBitset({Feature_IsThumb2Bit,
11677                                              Feature_IsThumbBit})).any())
11678         break;
11679       if (isMClass() && MissingFeatures.test(Feature_HasNEONBit))
11680         break;
11681 
11682       NearMissMessage Message;
11683       Message.Loc = IDLoc;
11684       raw_svector_ostream OS(Message.Message);
11685 
11686       OS << "instruction requires:";
11687       for (unsigned i = 0, e = MissingFeatures.size(); i != e; ++i)
11688         if (MissingFeatures.test(i))
11689           OS << ' ' << getSubtargetFeatureName(i);
11690 
11691       NearMissesOut.emplace_back(Message);
11692 
11693       break;
11694     }
11695     case NearMissInfo::NearMissPredicate: {
11696       NearMissMessage Message;
11697       Message.Loc = IDLoc;
11698       switch (I.getPredicateError()) {
11699       case Match_RequiresNotITBlock:
11700         Message.Message = "flag setting instruction only valid outside IT block";
11701         break;
11702       case Match_RequiresITBlock:
11703         Message.Message = "instruction only valid inside IT block";
11704         break;
11705       case Match_RequiresV6:
11706         Message.Message = "instruction variant requires ARMv6 or later";
11707         break;
11708       case Match_RequiresThumb2:
11709         Message.Message = "instruction variant requires Thumb2";
11710         break;
11711       case Match_RequiresV8:
11712         Message.Message = "instruction variant requires ARMv8 or later";
11713         break;
11714       case Match_RequiresFlagSetting:
11715         Message.Message = "no flag-preserving variant of this instruction available";
11716         break;
11717       case Match_InvalidOperand:
11718         Message.Message = "invalid operand for instruction";
11719         break;
11720       default:
11721         llvm_unreachable("Unhandled target predicate error");
11722         break;
11723       }
11724       NearMissesOut.emplace_back(Message);
11725       break;
11726     }
11727     case NearMissInfo::NearMissTooFewOperands: {
11728       if (!ReportedTooFewOperands) {
11729         SMLoc EndLoc = ((ARMOperand &)*Operands.back()).getEndLoc();
11730         NearMissesOut.emplace_back(NearMissMessage{
11731             EndLoc, StringRef("too few operands for instruction")});
11732         ReportedTooFewOperands = true;
11733       }
11734       break;
11735     }
11736     case NearMissInfo::NoNearMiss:
11737       // This should never leave the matcher.
11738       llvm_unreachable("not a near-miss");
11739       break;
11740     }
11741   }
11742 }
11743 
11744 void ARMAsmParser::ReportNearMisses(SmallVectorImpl<NearMissInfo> &NearMisses,
11745                                     SMLoc IDLoc, OperandVector &Operands) {
11746   SmallVector<NearMissMessage, 4> Messages;
11747   FilterNearMisses(NearMisses, Messages, IDLoc, Operands);
11748 
11749   if (Messages.size() == 0) {
11750     // No near-misses were found, so the best we can do is "invalid
11751     // instruction".
11752     Error(IDLoc, "invalid instruction");
11753   } else if (Messages.size() == 1) {
11754     // One near miss was found, report it as the sole error.
11755     Error(Messages[0].Loc, Messages[0].Message);
11756   } else {
11757     // More than one near miss, so report a generic "invalid instruction"
11758     // error, followed by notes for each of the near-misses.
11759     Error(IDLoc, "invalid instruction, any one of the following would fix this:");
11760     for (auto &M : Messages) {
11761       Note(M.Loc, M.Message);
11762     }
11763   }
11764 }
11765 
11766 /// parseDirectiveArchExtension
11767 ///   ::= .arch_extension [no]feature
11768 bool ARMAsmParser::parseDirectiveArchExtension(SMLoc L) {
11769   // FIXME: This structure should be moved inside ARMTargetParser
11770   // when we start to table-generate them, and we can use the ARM
11771   // flags below, that were generated by table-gen.
11772   static const struct {
11773     const uint64_t Kind;
11774     const FeatureBitset ArchCheck;
11775     const FeatureBitset Features;
11776   } Extensions[] = {
11777     { ARM::AEK_CRC, {Feature_HasV8Bit}, {ARM::FeatureCRC} },
11778     { ARM::AEK_CRYPTO,  {Feature_HasV8Bit},
11779       {ARM::FeatureCrypto, ARM::FeatureNEON, ARM::FeatureFPARMv8} },
11780     { ARM::AEK_FP, {Feature_HasV8Bit},
11781       {ARM::FeatureVFP2_SP, ARM::FeatureFPARMv8} },
11782     { (ARM::AEK_HWDIVTHUMB | ARM::AEK_HWDIVARM),
11783       {Feature_HasV7Bit, Feature_IsNotMClassBit},
11784       {ARM::FeatureHWDivThumb, ARM::FeatureHWDivARM} },
11785     { ARM::AEK_MP, {Feature_HasV7Bit, Feature_IsNotMClassBit},
11786       {ARM::FeatureMP} },
11787     { ARM::AEK_SIMD, {Feature_HasV8Bit},
11788       {ARM::FeatureNEON, ARM::FeatureVFP2_SP, ARM::FeatureFPARMv8} },
11789     { ARM::AEK_SEC, {Feature_HasV6KBit}, {ARM::FeatureTrustZone} },
11790     // FIXME: Only available in A-class, isel not predicated
11791     { ARM::AEK_VIRT, {Feature_HasV7Bit}, {ARM::FeatureVirtualization} },
11792     { ARM::AEK_FP16, {Feature_HasV8_2aBit},
11793       {ARM::FeatureFPARMv8, ARM::FeatureFullFP16} },
11794     { ARM::AEK_RAS, {Feature_HasV8Bit}, {ARM::FeatureRAS} },
11795     { ARM::AEK_LOB, {Feature_HasV8_1MMainlineBit}, {ARM::FeatureLOB} },
11796     // FIXME: Unsupported extensions.
11797     { ARM::AEK_OS, {}, {} },
11798     { ARM::AEK_IWMMXT, {}, {} },
11799     { ARM::AEK_IWMMXT2, {}, {} },
11800     { ARM::AEK_MAVERICK, {}, {} },
11801     { ARM::AEK_XSCALE, {}, {} },
11802   };
11803 
11804   MCAsmParser &Parser = getParser();
11805 
11806   if (getLexer().isNot(AsmToken::Identifier))
11807     return Error(getLexer().getLoc(), "expected architecture extension name");
11808 
11809   StringRef Name = Parser.getTok().getString();
11810   SMLoc ExtLoc = Parser.getTok().getLoc();
11811   Lex();
11812 
11813   if (parseToken(AsmToken::EndOfStatement,
11814                  "unexpected token in '.arch_extension' directive"))
11815     return true;
11816 
11817   bool EnableFeature = true;
11818   if (Name.startswith_lower("no")) {
11819     EnableFeature = false;
11820     Name = Name.substr(2);
11821   }
11822   uint64_t FeatureKind = ARM::parseArchExt(Name);
11823   if (FeatureKind == ARM::AEK_INVALID)
11824     return Error(ExtLoc, "unknown architectural extension: " + Name);
11825 
11826   for (const auto &Extension : Extensions) {
11827     if (Extension.Kind != FeatureKind)
11828       continue;
11829 
11830     if (Extension.Features.none())
11831       return Error(ExtLoc, "unsupported architectural extension: " + Name);
11832 
11833     if ((getAvailableFeatures() & Extension.ArchCheck) != Extension.ArchCheck)
11834       return Error(ExtLoc, "architectural extension '" + Name +
11835                                "' is not "
11836                                "allowed for the current base architecture");
11837 
11838     MCSubtargetInfo &STI = copySTI();
11839     if (EnableFeature) {
11840       STI.SetFeatureBitsTransitively(Extension.Features);
11841     } else {
11842       STI.ClearFeatureBitsTransitively(Extension.Features);
11843     }
11844     FeatureBitset Features = ComputeAvailableFeatures(STI.getFeatureBits());
11845     setAvailableFeatures(Features);
11846     return false;
11847   }
11848 
11849   return Error(ExtLoc, "unknown architectural extension: " + Name);
11850 }
11851 
11852 // Define this matcher function after the auto-generated include so we
11853 // have the match class enum definitions.
11854 unsigned ARMAsmParser::validateTargetOperandClass(MCParsedAsmOperand &AsmOp,
11855                                                   unsigned Kind) {
11856   ARMOperand &Op = static_cast<ARMOperand &>(AsmOp);
11857   // If the kind is a token for a literal immediate, check if our asm
11858   // operand matches. This is for InstAliases which have a fixed-value
11859   // immediate in the syntax.
11860   switch (Kind) {
11861   default: break;
11862   case MCK__HASH_0:
11863     if (Op.isImm())
11864       if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm()))
11865         if (CE->getValue() == 0)
11866           return Match_Success;
11867     break;
11868   case MCK__HASH_8:
11869     if (Op.isImm())
11870       if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm()))
11871         if (CE->getValue() == 8)
11872           return Match_Success;
11873     break;
11874   case MCK__HASH_16:
11875     if (Op.isImm())
11876       if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm()))
11877         if (CE->getValue() == 16)
11878           return Match_Success;
11879     break;
11880   case MCK_ModImm:
11881     if (Op.isImm()) {
11882       const MCExpr *SOExpr = Op.getImm();
11883       int64_t Value;
11884       if (!SOExpr->evaluateAsAbsolute(Value))
11885         return Match_Success;
11886       assert((Value >= std::numeric_limits<int32_t>::min() &&
11887               Value <= std::numeric_limits<uint32_t>::max()) &&
11888              "expression value must be representable in 32 bits");
11889     }
11890     break;
11891   case MCK_rGPR:
11892     if (hasV8Ops() && Op.isReg() && Op.getReg() == ARM::SP)
11893       return Match_Success;
11894     return Match_rGPR;
11895   case MCK_GPRPair:
11896     if (Op.isReg() &&
11897         MRI->getRegClass(ARM::GPRRegClassID).contains(Op.getReg()))
11898       return Match_Success;
11899     break;
11900   }
11901   return Match_InvalidOperand;
11902 }
11903 
11904 bool ARMAsmParser::isMnemonicVPTPredicable(StringRef Mnemonic,
11905                                            StringRef ExtraToken) {
11906   if (!hasMVE())
11907     return false;
11908 
11909   return Mnemonic.startswith("vabav") || Mnemonic.startswith("vaddv") ||
11910          Mnemonic.startswith("vaddlv") || Mnemonic.startswith("vminnmv") ||
11911          Mnemonic.startswith("vminnmav") || Mnemonic.startswith("vminv") ||
11912          Mnemonic.startswith("vminav") || Mnemonic.startswith("vmaxnmv") ||
11913          Mnemonic.startswith("vmaxnmav") || Mnemonic.startswith("vmaxv") ||
11914          Mnemonic.startswith("vmaxav") || Mnemonic.startswith("vmladav") ||
11915          Mnemonic.startswith("vrmlaldavh") || Mnemonic.startswith("vrmlalvh") ||
11916          Mnemonic.startswith("vmlsdav") || Mnemonic.startswith("vmlav") ||
11917          Mnemonic.startswith("vmlaldav") || Mnemonic.startswith("vmlalv") ||
11918          Mnemonic.startswith("vmaxnm") || Mnemonic.startswith("vminnm") ||
11919          Mnemonic.startswith("vmax") || Mnemonic.startswith("vmin") ||
11920          Mnemonic.startswith("vshlc") || Mnemonic.startswith("vmovlt") ||
11921          Mnemonic.startswith("vmovlb") || Mnemonic.startswith("vshll") ||
11922          Mnemonic.startswith("vrshrn") || Mnemonic.startswith("vshrn") ||
11923          Mnemonic.startswith("vqrshrun") || Mnemonic.startswith("vqshrun") ||
11924          Mnemonic.startswith("vqrshrn") || Mnemonic.startswith("vqshrn") ||
11925          Mnemonic.startswith("vbic") || Mnemonic.startswith("vrev64") ||
11926          Mnemonic.startswith("vrev32") || Mnemonic.startswith("vrev16") ||
11927          Mnemonic.startswith("vmvn") || Mnemonic.startswith("veor") ||
11928          Mnemonic.startswith("vorn") || Mnemonic.startswith("vorr") ||
11929          Mnemonic.startswith("vand") || Mnemonic.startswith("vmul") ||
11930          Mnemonic.startswith("vqrdmulh") || Mnemonic.startswith("vqdmulh") ||
11931          Mnemonic.startswith("vsub") || Mnemonic.startswith("vadd") ||
11932          Mnemonic.startswith("vqsub") || Mnemonic.startswith("vqadd") ||
11933          Mnemonic.startswith("vabd") || Mnemonic.startswith("vrhadd") ||
11934          Mnemonic.startswith("vhsub") || Mnemonic.startswith("vhadd") ||
11935          Mnemonic.startswith("vdup") || Mnemonic.startswith("vcls") ||
11936          Mnemonic.startswith("vclz") || Mnemonic.startswith("vneg") ||
11937          Mnemonic.startswith("vabs") || Mnemonic.startswith("vqneg") ||
11938          Mnemonic.startswith("vqabs") ||
11939          (Mnemonic.startswith("vrint") && Mnemonic != "vrintr") ||
11940          Mnemonic.startswith("vcmla") || Mnemonic.startswith("vfma") ||
11941          Mnemonic.startswith("vfms") || Mnemonic.startswith("vcadd") ||
11942          Mnemonic.startswith("vadd") || Mnemonic.startswith("vsub") ||
11943          Mnemonic.startswith("vshl") || Mnemonic.startswith("vqshl") ||
11944          Mnemonic.startswith("vqrshl") || Mnemonic.startswith("vrshl") ||
11945          Mnemonic.startswith("vsri") || Mnemonic.startswith("vsli") ||
11946          Mnemonic.startswith("vrshr") || Mnemonic.startswith("vshr") ||
11947          Mnemonic.startswith("vpsel") || Mnemonic.startswith("vcmp") ||
11948          Mnemonic.startswith("vqdmladh") || Mnemonic.startswith("vqrdmladh") ||
11949          Mnemonic.startswith("vqdmlsdh") || Mnemonic.startswith("vqrdmlsdh") ||
11950          Mnemonic.startswith("vcmul") || Mnemonic.startswith("vrmulh") ||
11951          Mnemonic.startswith("vqmovn") || Mnemonic.startswith("vqmovun") ||
11952          Mnemonic.startswith("vmovnt") || Mnemonic.startswith("vmovnb") ||
11953          Mnemonic.startswith("vmaxa") || Mnemonic.startswith("vmaxnma") ||
11954          Mnemonic.startswith("vhcadd") || Mnemonic.startswith("vadc") ||
11955          Mnemonic.startswith("vsbc") || Mnemonic.startswith("vrshr") ||
11956          Mnemonic.startswith("vshr") || Mnemonic.startswith("vstrb") ||
11957          Mnemonic.startswith("vldrb") ||
11958          (Mnemonic.startswith("vstrh") && Mnemonic != "vstrhi") ||
11959          (Mnemonic.startswith("vldrh") && Mnemonic != "vldrhi") ||
11960          Mnemonic.startswith("vstrw") || Mnemonic.startswith("vldrw") ||
11961          Mnemonic.startswith("vldrd") || Mnemonic.startswith("vstrd") ||
11962          Mnemonic.startswith("vqdmull") || Mnemonic.startswith("vbrsr") ||
11963          Mnemonic.startswith("vfmas") || Mnemonic.startswith("vmlas") ||
11964          Mnemonic.startswith("vmla") || Mnemonic.startswith("vqdmlash") ||
11965          Mnemonic.startswith("vqdmlah") || Mnemonic.startswith("vqrdmlash") ||
11966          Mnemonic.startswith("vqrdmlah") || Mnemonic.startswith("viwdup") ||
11967          Mnemonic.startswith("vdwdup") || Mnemonic.startswith("vidup") ||
11968          Mnemonic.startswith("vddup") || Mnemonic.startswith("vctp") ||
11969          Mnemonic.startswith("vpnot") || Mnemonic.startswith("vbic") ||
11970          Mnemonic.startswith("vrmlsldavh") || Mnemonic.startswith("vmlsldav") ||
11971          Mnemonic.startswith("vcvt") ||
11972          (Mnemonic.startswith("vmov") &&
11973           !(ExtraToken == ".f16" || ExtraToken == ".32" ||
11974             ExtraToken == ".16" || ExtraToken == ".8"));
11975 }
11976