1 //===- ARMAsmParser.cpp - Parse ARM assembly to MCInst instructions -------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "ARMFeatures.h"
11 #include "Utils/ARMBaseInfo.h"
12 #include "MCTargetDesc/ARMAddressingModes.h"
13 #include "MCTargetDesc/ARMBaseInfo.h"
14 #include "MCTargetDesc/ARMMCExpr.h"
15 #include "MCTargetDesc/ARMMCTargetDesc.h"
16 #include "llvm/ADT/APFloat.h"
17 #include "llvm/ADT/APInt.h"
18 #include "llvm/ADT/None.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SmallSet.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/StringMap.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/ADT/StringSwitch.h"
25 #include "llvm/ADT/Triple.h"
26 #include "llvm/ADT/Twine.h"
27 #include "llvm/MC/MCContext.h"
28 #include "llvm/MC/MCExpr.h"
29 #include "llvm/MC/MCInst.h"
30 #include "llvm/MC/MCInstrDesc.h"
31 #include "llvm/MC/MCInstrInfo.h"
32 #include "llvm/MC/MCObjectFileInfo.h"
33 #include "llvm/MC/MCParser/MCAsmLexer.h"
34 #include "llvm/MC/MCParser/MCAsmParser.h"
35 #include "llvm/MC/MCParser/MCAsmParserExtension.h"
36 #include "llvm/MC/MCParser/MCAsmParserUtils.h"
37 #include "llvm/MC/MCParser/MCParsedAsmOperand.h"
38 #include "llvm/MC/MCParser/MCTargetAsmParser.h"
39 #include "llvm/MC/MCRegisterInfo.h"
40 #include "llvm/MC/MCSection.h"
41 #include "llvm/MC/MCStreamer.h"
42 #include "llvm/MC/MCSubtargetInfo.h"
43 #include "llvm/MC/MCSymbol.h"
44 #include "llvm/MC/SubtargetFeature.h"
45 #include "llvm/Support/ARMBuildAttributes.h"
46 #include "llvm/Support/ARMEHABI.h"
47 #include "llvm/Support/Casting.h"
48 #include "llvm/Support/CommandLine.h"
49 #include "llvm/Support/Compiler.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Support/SMLoc.h"
53 #include "llvm/Support/TargetParser.h"
54 #include "llvm/Support/TargetRegistry.h"
55 #include "llvm/Support/raw_ostream.h"
56 #include <algorithm>
57 #include <cassert>
58 #include <cstddef>
59 #include <cstdint>
60 #include <iterator>
61 #include <limits>
62 #include <memory>
63 #include <string>
64 #include <utility>
65 #include <vector>
66 
67 #define DEBUG_TYPE "asm-parser"
68 
69 using namespace llvm;
70 
71 namespace {
72 
73 enum class ImplicitItModeTy { Always, Never, ARMOnly, ThumbOnly };
74 
75 static cl::opt<ImplicitItModeTy> ImplicitItMode(
76     "arm-implicit-it", cl::init(ImplicitItModeTy::ARMOnly),
77     cl::desc("Allow conditional instructions outdside of an IT block"),
78     cl::values(clEnumValN(ImplicitItModeTy::Always, "always",
79                           "Accept in both ISAs, emit implicit ITs in Thumb"),
80                clEnumValN(ImplicitItModeTy::Never, "never",
81                           "Warn in ARM, reject in Thumb"),
82                clEnumValN(ImplicitItModeTy::ARMOnly, "arm",
83                           "Accept in ARM, reject in Thumb"),
84                clEnumValN(ImplicitItModeTy::ThumbOnly, "thumb",
85                           "Warn in ARM, emit implicit ITs in Thumb")));
86 
87 static cl::opt<bool> AddBuildAttributes("arm-add-build-attributes",
88                                         cl::init(false));
89 
90 enum VectorLaneTy { NoLanes, AllLanes, IndexedLane };
91 
92 class UnwindContext {
93   using Locs = SmallVector<SMLoc, 4>;
94 
95   MCAsmParser &Parser;
96   Locs FnStartLocs;
97   Locs CantUnwindLocs;
98   Locs PersonalityLocs;
99   Locs PersonalityIndexLocs;
100   Locs HandlerDataLocs;
101   int FPReg;
102 
103 public:
104   UnwindContext(MCAsmParser &P) : Parser(P), FPReg(ARM::SP) {}
105 
106   bool hasFnStart() const { return !FnStartLocs.empty(); }
107   bool cantUnwind() const { return !CantUnwindLocs.empty(); }
108   bool hasHandlerData() const { return !HandlerDataLocs.empty(); }
109 
110   bool hasPersonality() const {
111     return !(PersonalityLocs.empty() && PersonalityIndexLocs.empty());
112   }
113 
114   void recordFnStart(SMLoc L) { FnStartLocs.push_back(L); }
115   void recordCantUnwind(SMLoc L) { CantUnwindLocs.push_back(L); }
116   void recordPersonality(SMLoc L) { PersonalityLocs.push_back(L); }
117   void recordHandlerData(SMLoc L) { HandlerDataLocs.push_back(L); }
118   void recordPersonalityIndex(SMLoc L) { PersonalityIndexLocs.push_back(L); }
119 
120   void saveFPReg(int Reg) { FPReg = Reg; }
121   int getFPReg() const { return FPReg; }
122 
123   void emitFnStartLocNotes() const {
124     for (Locs::const_iterator FI = FnStartLocs.begin(), FE = FnStartLocs.end();
125          FI != FE; ++FI)
126       Parser.Note(*FI, ".fnstart was specified here");
127   }
128 
129   void emitCantUnwindLocNotes() const {
130     for (Locs::const_iterator UI = CantUnwindLocs.begin(),
131                               UE = CantUnwindLocs.end(); UI != UE; ++UI)
132       Parser.Note(*UI, ".cantunwind was specified here");
133   }
134 
135   void emitHandlerDataLocNotes() const {
136     for (Locs::const_iterator HI = HandlerDataLocs.begin(),
137                               HE = HandlerDataLocs.end(); HI != HE; ++HI)
138       Parser.Note(*HI, ".handlerdata was specified here");
139   }
140 
141   void emitPersonalityLocNotes() const {
142     for (Locs::const_iterator PI = PersonalityLocs.begin(),
143                               PE = PersonalityLocs.end(),
144                               PII = PersonalityIndexLocs.begin(),
145                               PIE = PersonalityIndexLocs.end();
146          PI != PE || PII != PIE;) {
147       if (PI != PE && (PII == PIE || PI->getPointer() < PII->getPointer()))
148         Parser.Note(*PI++, ".personality was specified here");
149       else if (PII != PIE && (PI == PE || PII->getPointer() < PI->getPointer()))
150         Parser.Note(*PII++, ".personalityindex was specified here");
151       else
152         llvm_unreachable(".personality and .personalityindex cannot be "
153                          "at the same location");
154     }
155   }
156 
157   void reset() {
158     FnStartLocs = Locs();
159     CantUnwindLocs = Locs();
160     PersonalityLocs = Locs();
161     HandlerDataLocs = Locs();
162     PersonalityIndexLocs = Locs();
163     FPReg = ARM::SP;
164   }
165 };
166 
167 class ARMAsmParser : public MCTargetAsmParser {
168   const MCRegisterInfo *MRI;
169   UnwindContext UC;
170 
171   ARMTargetStreamer &getTargetStreamer() {
172     assert(getParser().getStreamer().getTargetStreamer() &&
173            "do not have a target streamer");
174     MCTargetStreamer &TS = *getParser().getStreamer().getTargetStreamer();
175     return static_cast<ARMTargetStreamer &>(TS);
176   }
177 
178   // Map of register aliases registers via the .req directive.
179   StringMap<unsigned> RegisterReqs;
180 
181   bool NextSymbolIsThumb;
182 
183   bool useImplicitITThumb() const {
184     return ImplicitItMode == ImplicitItModeTy::Always ||
185            ImplicitItMode == ImplicitItModeTy::ThumbOnly;
186   }
187 
188   bool useImplicitITARM() const {
189     return ImplicitItMode == ImplicitItModeTy::Always ||
190            ImplicitItMode == ImplicitItModeTy::ARMOnly;
191   }
192 
193   struct {
194     ARMCC::CondCodes Cond;    // Condition for IT block.
195     unsigned Mask:4;          // Condition mask for instructions.
196                               // Starting at first 1 (from lsb).
197                               //   '1'  condition as indicated in IT.
198                               //   '0'  inverse of condition (else).
199                               // Count of instructions in IT block is
200                               // 4 - trailingzeroes(mask)
201                               // Note that this does not have the same encoding
202                               // as in the IT instruction, which also depends
203                               // on the low bit of the condition code.
204 
205     unsigned CurPosition;     // Current position in parsing of IT
206                               // block. In range [0,4], with 0 being the IT
207                               // instruction itself. Initialized according to
208                               // count of instructions in block.  ~0U if no
209                               // active IT block.
210 
211     bool IsExplicit;          // true  - The IT instruction was present in the
212                               //         input, we should not modify it.
213                               // false - The IT instruction was added
214                               //         implicitly, we can extend it if that
215                               //         would be legal.
216   } ITState;
217 
218   SmallVector<MCInst, 4> PendingConditionalInsts;
219 
220   void flushPendingInstructions(MCStreamer &Out) override {
221     if (!inImplicitITBlock()) {
222       assert(PendingConditionalInsts.size() == 0);
223       return;
224     }
225 
226     // Emit the IT instruction
227     unsigned Mask = getITMaskEncoding();
228     MCInst ITInst;
229     ITInst.setOpcode(ARM::t2IT);
230     ITInst.addOperand(MCOperand::createImm(ITState.Cond));
231     ITInst.addOperand(MCOperand::createImm(Mask));
232     Out.EmitInstruction(ITInst, getSTI());
233 
234     // Emit the conditonal instructions
235     assert(PendingConditionalInsts.size() <= 4);
236     for (const MCInst &Inst : PendingConditionalInsts) {
237       Out.EmitInstruction(Inst, getSTI());
238     }
239     PendingConditionalInsts.clear();
240 
241     // Clear the IT state
242     ITState.Mask = 0;
243     ITState.CurPosition = ~0U;
244   }
245 
246   bool inITBlock() { return ITState.CurPosition != ~0U; }
247   bool inExplicitITBlock() { return inITBlock() && ITState.IsExplicit; }
248   bool inImplicitITBlock() { return inITBlock() && !ITState.IsExplicit; }
249 
250   bool lastInITBlock() {
251     return ITState.CurPosition == 4 - countTrailingZeros(ITState.Mask);
252   }
253 
254   void forwardITPosition() {
255     if (!inITBlock()) return;
256     // Move to the next instruction in the IT block, if there is one. If not,
257     // mark the block as done, except for implicit IT blocks, which we leave
258     // open until we find an instruction that can't be added to it.
259     unsigned TZ = countTrailingZeros(ITState.Mask);
260     if (++ITState.CurPosition == 5 - TZ && ITState.IsExplicit)
261       ITState.CurPosition = ~0U; // Done with the IT block after this.
262   }
263 
264   // Rewind the state of the current IT block, removing the last slot from it.
265   void rewindImplicitITPosition() {
266     assert(inImplicitITBlock());
267     assert(ITState.CurPosition > 1);
268     ITState.CurPosition--;
269     unsigned TZ = countTrailingZeros(ITState.Mask);
270     unsigned NewMask = 0;
271     NewMask |= ITState.Mask & (0xC << TZ);
272     NewMask |= 0x2 << TZ;
273     ITState.Mask = NewMask;
274   }
275 
276   // Rewind the state of the current IT block, removing the last slot from it.
277   // If we were at the first slot, this closes the IT block.
278   void discardImplicitITBlock() {
279     assert(inImplicitITBlock());
280     assert(ITState.CurPosition == 1);
281     ITState.CurPosition = ~0U;
282   }
283 
284   // Return the low-subreg of a given Q register.
285   unsigned getDRegFromQReg(unsigned QReg) const {
286     return MRI->getSubReg(QReg, ARM::dsub_0);
287   }
288 
289   // Get the encoding of the IT mask, as it will appear in an IT instruction.
290   unsigned getITMaskEncoding() {
291     assert(inITBlock());
292     unsigned Mask = ITState.Mask;
293     unsigned TZ = countTrailingZeros(Mask);
294     if ((ITState.Cond & 1) == 0) {
295       assert(Mask && TZ <= 3 && "illegal IT mask value!");
296       Mask ^= (0xE << TZ) & 0xF;
297     }
298     return Mask;
299   }
300 
301   // Get the condition code corresponding to the current IT block slot.
302   ARMCC::CondCodes currentITCond() {
303     unsigned MaskBit;
304     if (ITState.CurPosition == 1)
305       MaskBit = 1;
306     else
307       MaskBit = (ITState.Mask >> (5 - ITState.CurPosition)) & 1;
308 
309     return MaskBit ? ITState.Cond : ARMCC::getOppositeCondition(ITState.Cond);
310   }
311 
312   // Invert the condition of the current IT block slot without changing any
313   // other slots in the same block.
314   void invertCurrentITCondition() {
315     if (ITState.CurPosition == 1) {
316       ITState.Cond = ARMCC::getOppositeCondition(ITState.Cond);
317     } else {
318       ITState.Mask ^= 1 << (5 - ITState.CurPosition);
319     }
320   }
321 
322   // Returns true if the current IT block is full (all 4 slots used).
323   bool isITBlockFull() {
324     return inITBlock() && (ITState.Mask & 1);
325   }
326 
327   // Extend the current implicit IT block to have one more slot with the given
328   // condition code.
329   void extendImplicitITBlock(ARMCC::CondCodes Cond) {
330     assert(inImplicitITBlock());
331     assert(!isITBlockFull());
332     assert(Cond == ITState.Cond ||
333            Cond == ARMCC::getOppositeCondition(ITState.Cond));
334     unsigned TZ = countTrailingZeros(ITState.Mask);
335     unsigned NewMask = 0;
336     // Keep any existing condition bits.
337     NewMask |= ITState.Mask & (0xE << TZ);
338     // Insert the new condition bit.
339     NewMask |= (Cond == ITState.Cond) << TZ;
340     // Move the trailing 1 down one bit.
341     NewMask |= 1 << (TZ - 1);
342     ITState.Mask = NewMask;
343   }
344 
345   // Create a new implicit IT block with a dummy condition code.
346   void startImplicitITBlock() {
347     assert(!inITBlock());
348     ITState.Cond = ARMCC::AL;
349     ITState.Mask = 8;
350     ITState.CurPosition = 1;
351     ITState.IsExplicit = false;
352   }
353 
354   // Create a new explicit IT block with the given condition and mask. The mask
355   // should be in the parsed format, with a 1 implying 't', regardless of the
356   // low bit of 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   void Note(SMLoc L, const Twine &Msg, SMRange Range = None) {
366     return getParser().Note(L, Msg, Range);
367   }
368 
369   bool Warning(SMLoc L, const Twine &Msg, SMRange Range = None) {
370     return getParser().Warning(L, Msg, Range);
371   }
372 
373   bool Error(SMLoc L, const Twine &Msg, SMRange Range = None) {
374     return getParser().Error(L, Msg, Range);
375   }
376 
377   bool validatetLDMRegList(const MCInst &Inst, const OperandVector &Operands,
378                            unsigned ListNo, bool IsARPop = false);
379   bool validatetSTMRegList(const MCInst &Inst, const OperandVector &Operands,
380                            unsigned ListNo);
381 
382   int tryParseRegister();
383   bool tryParseRegisterWithWriteBack(OperandVector &);
384   int tryParseShiftRegister(OperandVector &);
385   bool parseRegisterList(OperandVector &);
386   bool parseMemory(OperandVector &);
387   bool parseOperand(OperandVector &, StringRef Mnemonic);
388   bool parsePrefix(ARMMCExpr::VariantKind &RefKind);
389   bool parseMemRegOffsetShift(ARM_AM::ShiftOpc &ShiftType,
390                               unsigned &ShiftAmount);
391   bool parseLiteralValues(unsigned Size, SMLoc L);
392   bool parseDirectiveThumb(SMLoc L);
393   bool parseDirectiveARM(SMLoc L);
394   bool parseDirectiveThumbFunc(SMLoc L);
395   bool parseDirectiveCode(SMLoc L);
396   bool parseDirectiveSyntax(SMLoc L);
397   bool parseDirectiveReq(StringRef Name, SMLoc L);
398   bool parseDirectiveUnreq(SMLoc L);
399   bool parseDirectiveArch(SMLoc L);
400   bool parseDirectiveEabiAttr(SMLoc L);
401   bool parseDirectiveCPU(SMLoc L);
402   bool parseDirectiveFPU(SMLoc L);
403   bool parseDirectiveFnStart(SMLoc L);
404   bool parseDirectiveFnEnd(SMLoc L);
405   bool parseDirectiveCantUnwind(SMLoc L);
406   bool parseDirectivePersonality(SMLoc L);
407   bool parseDirectiveHandlerData(SMLoc L);
408   bool parseDirectiveSetFP(SMLoc L);
409   bool parseDirectivePad(SMLoc L);
410   bool parseDirectiveRegSave(SMLoc L, bool IsVector);
411   bool parseDirectiveInst(SMLoc L, char Suffix = '\0');
412   bool parseDirectiveLtorg(SMLoc L);
413   bool parseDirectiveEven(SMLoc L);
414   bool parseDirectivePersonalityIndex(SMLoc L);
415   bool parseDirectiveUnwindRaw(SMLoc L);
416   bool parseDirectiveTLSDescSeq(SMLoc L);
417   bool parseDirectiveMovSP(SMLoc L);
418   bool parseDirectiveObjectArch(SMLoc L);
419   bool parseDirectiveArchExtension(SMLoc L);
420   bool parseDirectiveAlign(SMLoc L);
421   bool parseDirectiveThumbSet(SMLoc L);
422 
423   StringRef splitMnemonic(StringRef Mnemonic, unsigned &PredicationCode,
424                           bool &CarrySetting, unsigned &ProcessorIMod,
425                           StringRef &ITMask);
426   void getMnemonicAcceptInfo(StringRef Mnemonic, StringRef FullInst,
427                              bool &CanAcceptCarrySet,
428                              bool &CanAcceptPredicationCode);
429 
430   void tryConvertingToTwoOperandForm(StringRef Mnemonic, bool CarrySetting,
431                                      OperandVector &Operands);
432   bool isThumb() const {
433     // FIXME: Can tablegen auto-generate this?
434     return getSTI().getFeatureBits()[ARM::ModeThumb];
435   }
436 
437   bool isThumbOne() const {
438     return isThumb() && !getSTI().getFeatureBits()[ARM::FeatureThumb2];
439   }
440 
441   bool isThumbTwo() const {
442     return isThumb() && getSTI().getFeatureBits()[ARM::FeatureThumb2];
443   }
444 
445   bool hasThumb() const {
446     return getSTI().getFeatureBits()[ARM::HasV4TOps];
447   }
448 
449   bool hasThumb2() const {
450     return getSTI().getFeatureBits()[ARM::FeatureThumb2];
451   }
452 
453   bool hasV6Ops() const {
454     return getSTI().getFeatureBits()[ARM::HasV6Ops];
455   }
456 
457   bool hasV6T2Ops() const {
458     return getSTI().getFeatureBits()[ARM::HasV6T2Ops];
459   }
460 
461   bool hasV6MOps() const {
462     return getSTI().getFeatureBits()[ARM::HasV6MOps];
463   }
464 
465   bool hasV7Ops() const {
466     return getSTI().getFeatureBits()[ARM::HasV7Ops];
467   }
468 
469   bool hasV8Ops() const {
470     return getSTI().getFeatureBits()[ARM::HasV8Ops];
471   }
472 
473   bool hasV8MBaseline() const {
474     return getSTI().getFeatureBits()[ARM::HasV8MBaselineOps];
475   }
476 
477   bool hasV8MMainline() const {
478     return getSTI().getFeatureBits()[ARM::HasV8MMainlineOps];
479   }
480 
481   bool has8MSecExt() const {
482     return getSTI().getFeatureBits()[ARM::Feature8MSecExt];
483   }
484 
485   bool hasARM() const {
486     return !getSTI().getFeatureBits()[ARM::FeatureNoARM];
487   }
488 
489   bool hasDSP() const {
490     return getSTI().getFeatureBits()[ARM::FeatureDSP];
491   }
492 
493   bool hasD16() const {
494     return getSTI().getFeatureBits()[ARM::FeatureD16];
495   }
496 
497   bool hasV8_1aOps() const {
498     return getSTI().getFeatureBits()[ARM::HasV8_1aOps];
499   }
500 
501   bool hasRAS() const {
502     return getSTI().getFeatureBits()[ARM::FeatureRAS];
503   }
504 
505   void SwitchMode() {
506     MCSubtargetInfo &STI = copySTI();
507     uint64_t FB = ComputeAvailableFeatures(STI.ToggleFeature(ARM::ModeThumb));
508     setAvailableFeatures(FB);
509   }
510 
511   void FixModeAfterArchChange(bool WasThumb, SMLoc Loc);
512 
513   bool isMClass() const {
514     return getSTI().getFeatureBits()[ARM::FeatureMClass];
515   }
516 
517   /// @name Auto-generated Match Functions
518   /// {
519 
520 #define GET_ASSEMBLER_HEADER
521 #include "ARMGenAsmMatcher.inc"
522 
523   /// }
524 
525   OperandMatchResultTy parseITCondCode(OperandVector &);
526   OperandMatchResultTy parseCoprocNumOperand(OperandVector &);
527   OperandMatchResultTy parseCoprocRegOperand(OperandVector &);
528   OperandMatchResultTy parseCoprocOptionOperand(OperandVector &);
529   OperandMatchResultTy parseMemBarrierOptOperand(OperandVector &);
530   OperandMatchResultTy parseInstSyncBarrierOptOperand(OperandVector &);
531   OperandMatchResultTy parseProcIFlagsOperand(OperandVector &);
532   OperandMatchResultTy parseMSRMaskOperand(OperandVector &);
533   OperandMatchResultTy parseBankedRegOperand(OperandVector &);
534   OperandMatchResultTy parsePKHImm(OperandVector &O, StringRef Op, int Low,
535                                    int High);
536   OperandMatchResultTy parsePKHLSLImm(OperandVector &O) {
537     return parsePKHImm(O, "lsl", 0, 31);
538   }
539   OperandMatchResultTy parsePKHASRImm(OperandVector &O) {
540     return parsePKHImm(O, "asr", 1, 32);
541   }
542   OperandMatchResultTy parseSetEndImm(OperandVector &);
543   OperandMatchResultTy parseShifterImm(OperandVector &);
544   OperandMatchResultTy parseRotImm(OperandVector &);
545   OperandMatchResultTy parseModImm(OperandVector &);
546   OperandMatchResultTy parseBitfield(OperandVector &);
547   OperandMatchResultTy parsePostIdxReg(OperandVector &);
548   OperandMatchResultTy parseAM3Offset(OperandVector &);
549   OperandMatchResultTy parseFPImm(OperandVector &);
550   OperandMatchResultTy parseVectorList(OperandVector &);
551   OperandMatchResultTy parseVectorLane(VectorLaneTy &LaneKind, unsigned &Index,
552                                        SMLoc &EndLoc);
553 
554   // Asm Match Converter Methods
555   void cvtThumbMultiply(MCInst &Inst, const OperandVector &);
556   void cvtThumbBranches(MCInst &Inst, const OperandVector &);
557 
558   bool validateInstruction(MCInst &Inst, const OperandVector &Ops);
559   bool processInstruction(MCInst &Inst, const OperandVector &Ops, MCStreamer &Out);
560   bool shouldOmitCCOutOperand(StringRef Mnemonic, OperandVector &Operands);
561   bool shouldOmitPredicateOperand(StringRef Mnemonic, OperandVector &Operands);
562   bool isITBlockTerminator(MCInst &Inst) const;
563   void fixupGNULDRDAlias(StringRef Mnemonic, OperandVector &Operands);
564 
565 public:
566   enum ARMMatchResultTy {
567     Match_RequiresITBlock = FIRST_TARGET_MATCH_RESULT_TY,
568     Match_RequiresNotITBlock,
569     Match_RequiresV6,
570     Match_RequiresThumb2,
571     Match_RequiresV8,
572     Match_RequiresFlagSetting,
573 #define GET_OPERAND_DIAGNOSTIC_TYPES
574 #include "ARMGenAsmMatcher.inc"
575 
576   };
577 
578   ARMAsmParser(const MCSubtargetInfo &STI, MCAsmParser &Parser,
579                const MCInstrInfo &MII, const MCTargetOptions &Options)
580     : MCTargetAsmParser(Options, STI, MII), UC(Parser) {
581     MCAsmParserExtension::Initialize(Parser);
582 
583     // Cache the MCRegisterInfo.
584     MRI = getContext().getRegisterInfo();
585 
586     // Initialize the set of available features.
587     setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
588 
589     // Add build attributes based on the selected target.
590     if (AddBuildAttributes)
591       getTargetStreamer().emitTargetAttributes(STI);
592 
593     // Not in an ITBlock to start with.
594     ITState.CurPosition = ~0U;
595 
596     NextSymbolIsThumb = false;
597   }
598 
599   // Implementation of the MCTargetAsmParser interface:
600   bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc) override;
601   bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
602                         SMLoc NameLoc, OperandVector &Operands) override;
603   bool ParseDirective(AsmToken DirectiveID) override;
604 
605   unsigned validateTargetOperandClass(MCParsedAsmOperand &Op,
606                                       unsigned Kind) override;
607   unsigned checkTargetMatchPredicate(MCInst &Inst) override;
608 
609   bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
610                                OperandVector &Operands, MCStreamer &Out,
611                                uint64_t &ErrorInfo,
612                                bool MatchingInlineAsm) override;
613   unsigned MatchInstruction(OperandVector &Operands, MCInst &Inst,
614                             SmallVectorImpl<NearMissInfo> &NearMisses,
615                             bool MatchingInlineAsm, bool &EmitInITBlock,
616                             MCStreamer &Out);
617 
618   struct NearMissMessage {
619     SMLoc Loc;
620     SmallString<128> Message;
621   };
622 
623   const char *getCustomOperandDiag(ARMMatchResultTy MatchError);
624 
625   void FilterNearMisses(SmallVectorImpl<NearMissInfo> &NearMissesIn,
626                         SmallVectorImpl<NearMissMessage> &NearMissesOut,
627                         SMLoc IDLoc, OperandVector &Operands);
628   void ReportNearMisses(SmallVectorImpl<NearMissInfo> &NearMisses, SMLoc IDLoc,
629                         OperandVector &Operands);
630 
631   void onLabelParsed(MCSymbol *Symbol) override;
632 };
633 
634 /// ARMOperand - Instances of this class represent a parsed ARM machine
635 /// operand.
636 class ARMOperand : public MCParsedAsmOperand {
637   enum KindTy {
638     k_CondCode,
639     k_CCOut,
640     k_ITCondMask,
641     k_CoprocNum,
642     k_CoprocReg,
643     k_CoprocOption,
644     k_Immediate,
645     k_MemBarrierOpt,
646     k_InstSyncBarrierOpt,
647     k_Memory,
648     k_PostIndexRegister,
649     k_MSRMask,
650     k_BankedReg,
651     k_ProcIFlags,
652     k_VectorIndex,
653     k_Register,
654     k_RegisterList,
655     k_DPRRegisterList,
656     k_SPRRegisterList,
657     k_VectorList,
658     k_VectorListAllLanes,
659     k_VectorListIndexed,
660     k_ShiftedRegister,
661     k_ShiftedImmediate,
662     k_ShifterImmediate,
663     k_RotateImmediate,
664     k_ModifiedImmediate,
665     k_ConstantPoolImmediate,
666     k_BitfieldDescriptor,
667     k_Token,
668   } Kind;
669 
670   SMLoc StartLoc, EndLoc, AlignmentLoc;
671   SmallVector<unsigned, 8> Registers;
672 
673   struct CCOp {
674     ARMCC::CondCodes Val;
675   };
676 
677   struct CopOp {
678     unsigned Val;
679   };
680 
681   struct CoprocOptionOp {
682     unsigned Val;
683   };
684 
685   struct ITMaskOp {
686     unsigned Mask:4;
687   };
688 
689   struct MBOptOp {
690     ARM_MB::MemBOpt Val;
691   };
692 
693   struct ISBOptOp {
694     ARM_ISB::InstSyncBOpt Val;
695   };
696 
697   struct IFlagsOp {
698     ARM_PROC::IFlags Val;
699   };
700 
701   struct MMaskOp {
702     unsigned Val;
703   };
704 
705   struct BankedRegOp {
706     unsigned Val;
707   };
708 
709   struct TokOp {
710     const char *Data;
711     unsigned Length;
712   };
713 
714   struct RegOp {
715     unsigned RegNum;
716   };
717 
718   // A vector register list is a sequential list of 1 to 4 registers.
719   struct VectorListOp {
720     unsigned RegNum;
721     unsigned Count;
722     unsigned LaneIndex;
723     bool isDoubleSpaced;
724   };
725 
726   struct VectorIndexOp {
727     unsigned Val;
728   };
729 
730   struct ImmOp {
731     const MCExpr *Val;
732   };
733 
734   /// Combined record for all forms of ARM address expressions.
735   struct MemoryOp {
736     unsigned BaseRegNum;
737     // Offset is in OffsetReg or OffsetImm. If both are zero, no offset
738     // was specified.
739     const MCConstantExpr *OffsetImm;  // Offset immediate value
740     unsigned OffsetRegNum;    // Offset register num, when OffsetImm == NULL
741     ARM_AM::ShiftOpc ShiftType; // Shift type for OffsetReg
742     unsigned ShiftImm;        // shift for OffsetReg.
743     unsigned Alignment;       // 0 = no alignment specified
744     // n = alignment in bytes (2, 4, 8, 16, or 32)
745     unsigned isNegative : 1;  // Negated OffsetReg? (~'U' bit)
746   };
747 
748   struct PostIdxRegOp {
749     unsigned RegNum;
750     bool isAdd;
751     ARM_AM::ShiftOpc ShiftTy;
752     unsigned ShiftImm;
753   };
754 
755   struct ShifterImmOp {
756     bool isASR;
757     unsigned Imm;
758   };
759 
760   struct RegShiftedRegOp {
761     ARM_AM::ShiftOpc ShiftTy;
762     unsigned SrcReg;
763     unsigned ShiftReg;
764     unsigned ShiftImm;
765   };
766 
767   struct RegShiftedImmOp {
768     ARM_AM::ShiftOpc ShiftTy;
769     unsigned SrcReg;
770     unsigned ShiftImm;
771   };
772 
773   struct RotImmOp {
774     unsigned Imm;
775   };
776 
777   struct ModImmOp {
778     unsigned Bits;
779     unsigned Rot;
780   };
781 
782   struct BitfieldOp {
783     unsigned LSB;
784     unsigned Width;
785   };
786 
787   union {
788     struct CCOp CC;
789     struct CopOp Cop;
790     struct CoprocOptionOp CoprocOption;
791     struct MBOptOp MBOpt;
792     struct ISBOptOp ISBOpt;
793     struct ITMaskOp ITMask;
794     struct IFlagsOp IFlags;
795     struct MMaskOp MMask;
796     struct BankedRegOp BankedReg;
797     struct TokOp Tok;
798     struct RegOp Reg;
799     struct VectorListOp VectorList;
800     struct VectorIndexOp VectorIndex;
801     struct ImmOp Imm;
802     struct MemoryOp Memory;
803     struct PostIdxRegOp PostIdxReg;
804     struct ShifterImmOp ShifterImm;
805     struct RegShiftedRegOp RegShiftedReg;
806     struct RegShiftedImmOp RegShiftedImm;
807     struct RotImmOp RotImm;
808     struct ModImmOp ModImm;
809     struct BitfieldOp Bitfield;
810   };
811 
812 public:
813   ARMOperand(KindTy K) : MCParsedAsmOperand(), Kind(K) {}
814 
815   /// getStartLoc - Get the location of the first token of this operand.
816   SMLoc getStartLoc() const override { return StartLoc; }
817 
818   /// getEndLoc - Get the location of the last token of this operand.
819   SMLoc getEndLoc() const override { return EndLoc; }
820 
821   /// getLocRange - Get the range between the first and last token of this
822   /// operand.
823   SMRange getLocRange() const { return SMRange(StartLoc, EndLoc); }
824 
825   /// getAlignmentLoc - Get the location of the Alignment token of this operand.
826   SMLoc getAlignmentLoc() const {
827     assert(Kind == k_Memory && "Invalid access!");
828     return AlignmentLoc;
829   }
830 
831   ARMCC::CondCodes getCondCode() const {
832     assert(Kind == k_CondCode && "Invalid access!");
833     return CC.Val;
834   }
835 
836   unsigned getCoproc() const {
837     assert((Kind == k_CoprocNum || Kind == k_CoprocReg) && "Invalid access!");
838     return Cop.Val;
839   }
840 
841   StringRef getToken() const {
842     assert(Kind == k_Token && "Invalid access!");
843     return StringRef(Tok.Data, Tok.Length);
844   }
845 
846   unsigned getReg() const override {
847     assert((Kind == k_Register || Kind == k_CCOut) && "Invalid access!");
848     return Reg.RegNum;
849   }
850 
851   const SmallVectorImpl<unsigned> &getRegList() const {
852     assert((Kind == k_RegisterList || Kind == k_DPRRegisterList ||
853             Kind == k_SPRRegisterList) && "Invalid access!");
854     return Registers;
855   }
856 
857   const MCExpr *getImm() const {
858     assert(isImm() && "Invalid access!");
859     return Imm.Val;
860   }
861 
862   const MCExpr *getConstantPoolImm() const {
863     assert(isConstantPoolImm() && "Invalid access!");
864     return Imm.Val;
865   }
866 
867   unsigned getVectorIndex() const {
868     assert(Kind == k_VectorIndex && "Invalid access!");
869     return VectorIndex.Val;
870   }
871 
872   ARM_MB::MemBOpt getMemBarrierOpt() const {
873     assert(Kind == k_MemBarrierOpt && "Invalid access!");
874     return MBOpt.Val;
875   }
876 
877   ARM_ISB::InstSyncBOpt getInstSyncBarrierOpt() const {
878     assert(Kind == k_InstSyncBarrierOpt && "Invalid access!");
879     return ISBOpt.Val;
880   }
881 
882   ARM_PROC::IFlags getProcIFlags() const {
883     assert(Kind == k_ProcIFlags && "Invalid access!");
884     return IFlags.Val;
885   }
886 
887   unsigned getMSRMask() const {
888     assert(Kind == k_MSRMask && "Invalid access!");
889     return MMask.Val;
890   }
891 
892   unsigned getBankedReg() const {
893     assert(Kind == k_BankedReg && "Invalid access!");
894     return BankedReg.Val;
895   }
896 
897   bool isCoprocNum() const { return Kind == k_CoprocNum; }
898   bool isCoprocReg() const { return Kind == k_CoprocReg; }
899   bool isCoprocOption() const { return Kind == k_CoprocOption; }
900   bool isCondCode() const { return Kind == k_CondCode; }
901   bool isCCOut() const { return Kind == k_CCOut; }
902   bool isITMask() const { return Kind == k_ITCondMask; }
903   bool isITCondCode() const { return Kind == k_CondCode; }
904   bool isImm() const override {
905     return Kind == k_Immediate;
906   }
907 
908   bool isARMBranchTarget() const {
909     if (!isImm()) return false;
910 
911     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm()))
912       return CE->getValue() % 4 == 0;
913     return true;
914   }
915 
916 
917   bool isThumbBranchTarget() const {
918     if (!isImm()) return false;
919 
920     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm()))
921       return CE->getValue() % 2 == 0;
922     return true;
923   }
924 
925   // checks whether this operand is an unsigned offset which fits is a field
926   // of specified width and scaled by a specific number of bits
927   template<unsigned width, unsigned scale>
928   bool isUnsignedOffset() const {
929     if (!isImm()) return false;
930     if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
931     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val)) {
932       int64_t Val = CE->getValue();
933       int64_t Align = 1LL << scale;
934       int64_t Max = Align * ((1LL << width) - 1);
935       return ((Val % Align) == 0) && (Val >= 0) && (Val <= Max);
936     }
937     return false;
938   }
939 
940   // checks whether this operand is an signed offset which fits is a field
941   // of specified width and scaled by a specific number of bits
942   template<unsigned width, unsigned scale>
943   bool isSignedOffset() const {
944     if (!isImm()) return false;
945     if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
946     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val)) {
947       int64_t Val = CE->getValue();
948       int64_t Align = 1LL << scale;
949       int64_t Max = Align * ((1LL << (width-1)) - 1);
950       int64_t Min = -Align * (1LL << (width-1));
951       return ((Val % Align) == 0) && (Val >= Min) && (Val <= Max);
952     }
953     return false;
954   }
955 
956   // checks whether this operand is a memory operand computed as an offset
957   // applied to PC. the offset may have 8 bits of magnitude and is represented
958   // with two bits of shift. textually it may be either [pc, #imm], #imm or
959   // relocable expression...
960   bool isThumbMemPC() const {
961     int64_t Val = 0;
962     if (isImm()) {
963       if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
964       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val);
965       if (!CE) return false;
966       Val = CE->getValue();
967     }
968     else if (isMem()) {
969       if(!Memory.OffsetImm || Memory.OffsetRegNum) return false;
970       if(Memory.BaseRegNum != ARM::PC) return false;
971       Val = Memory.OffsetImm->getValue();
972     }
973     else return false;
974     return ((Val % 4) == 0) && (Val >= 0) && (Val <= 1020);
975   }
976 
977   bool isFPImm() const {
978     if (!isImm()) return false;
979     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
980     if (!CE) return false;
981     int Val = ARM_AM::getFP32Imm(APInt(32, CE->getValue()));
982     return Val != -1;
983   }
984 
985   template<int64_t N, int64_t M>
986   bool isImmediate() const {
987     if (!isImm()) return false;
988     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
989     if (!CE) return false;
990     int64_t Value = CE->getValue();
991     return Value >= N && Value <= M;
992   }
993 
994   template<int64_t N, int64_t M>
995   bool isImmediateS4() const {
996     if (!isImm()) return false;
997     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
998     if (!CE) return false;
999     int64_t Value = CE->getValue();
1000     return ((Value & 3) == 0) && Value >= N && Value <= M;
1001   }
1002 
1003   bool isFBits16() const {
1004     return isImmediate<0, 17>();
1005   }
1006   bool isFBits32() const {
1007     return isImmediate<1, 33>();
1008   }
1009   bool isImm8s4() const {
1010     return isImmediateS4<-1020, 1020>();
1011   }
1012   bool isImm0_1020s4() const {
1013     return isImmediateS4<0, 1020>();
1014   }
1015   bool isImm0_508s4() const {
1016     return isImmediateS4<0, 508>();
1017   }
1018   bool isImm0_508s4Neg() const {
1019     if (!isImm()) return false;
1020     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1021     if (!CE) return false;
1022     int64_t Value = -CE->getValue();
1023     // explicitly exclude zero. we want that to use the normal 0_508 version.
1024     return ((Value & 3) == 0) && Value > 0 && Value <= 508;
1025   }
1026 
1027   bool isImm0_4095Neg() const {
1028     if (!isImm()) return false;
1029     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1030     if (!CE) return false;
1031     int64_t Value = -CE->getValue();
1032     return Value > 0 && Value < 4096;
1033   }
1034 
1035   bool isImm0_7() const {
1036     return isImmediate<0, 7>();
1037   }
1038 
1039   bool isImm1_16() const {
1040     return isImmediate<1, 16>();
1041   }
1042 
1043   bool isImm1_32() const {
1044     return isImmediate<1, 32>();
1045   }
1046 
1047   bool isImm8_255() const {
1048     return isImmediate<8, 255>();
1049   }
1050 
1051   bool isImm256_65535Expr() const {
1052     if (!isImm()) return false;
1053     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1054     // If it's not a constant expression, it'll generate a fixup and be
1055     // handled later.
1056     if (!CE) return true;
1057     int64_t Value = CE->getValue();
1058     return Value >= 256 && Value < 65536;
1059   }
1060 
1061   bool isImm0_65535Expr() const {
1062     if (!isImm()) return false;
1063     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1064     // If it's not a constant expression, it'll generate a fixup and be
1065     // handled later.
1066     if (!CE) return true;
1067     int64_t Value = CE->getValue();
1068     return Value >= 0 && Value < 65536;
1069   }
1070 
1071   bool isImm24bit() const {
1072     return isImmediate<0, 0xffffff + 1>();
1073   }
1074 
1075   bool isImmThumbSR() const {
1076     return isImmediate<1, 33>();
1077   }
1078 
1079   bool isPKHLSLImm() const {
1080     return isImmediate<0, 32>();
1081   }
1082 
1083   bool isPKHASRImm() const {
1084     return isImmediate<0, 33>();
1085   }
1086 
1087   bool isAdrLabel() const {
1088     // If we have an immediate that's not a constant, treat it as a label
1089     // reference needing a fixup.
1090     if (isImm() && !isa<MCConstantExpr>(getImm()))
1091       return true;
1092 
1093     // If it is a constant, it must fit into a modified immediate encoding.
1094     if (!isImm()) return false;
1095     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1096     if (!CE) return false;
1097     int64_t Value = CE->getValue();
1098     return (ARM_AM::getSOImmVal(Value) != -1 ||
1099             ARM_AM::getSOImmVal(-Value) != -1);
1100   }
1101 
1102   bool isT2SOImm() const {
1103     // If we have an immediate that's not a constant, treat it as an expression
1104     // needing a fixup.
1105     if (isImm() && !isa<MCConstantExpr>(getImm())) {
1106       // We want to avoid matching :upper16: and :lower16: as we want these
1107       // expressions to match in isImm0_65535Expr()
1108       const ARMMCExpr *ARM16Expr = dyn_cast<ARMMCExpr>(getImm());
1109       return (!ARM16Expr || (ARM16Expr->getKind() != ARMMCExpr::VK_ARM_HI16 &&
1110                              ARM16Expr->getKind() != ARMMCExpr::VK_ARM_LO16));
1111     }
1112     if (!isImm()) return false;
1113     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1114     if (!CE) return false;
1115     int64_t Value = CE->getValue();
1116     return ARM_AM::getT2SOImmVal(Value) != -1;
1117   }
1118 
1119   bool isT2SOImmNot() const {
1120     if (!isImm()) return false;
1121     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1122     if (!CE) return false;
1123     int64_t Value = CE->getValue();
1124     return ARM_AM::getT2SOImmVal(Value) == -1 &&
1125       ARM_AM::getT2SOImmVal(~Value) != -1;
1126   }
1127 
1128   bool isT2SOImmNeg() const {
1129     if (!isImm()) return false;
1130     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1131     if (!CE) return false;
1132     int64_t Value = CE->getValue();
1133     // Only use this when not representable as a plain so_imm.
1134     return ARM_AM::getT2SOImmVal(Value) == -1 &&
1135       ARM_AM::getT2SOImmVal(-Value) != -1;
1136   }
1137 
1138   bool isSetEndImm() const {
1139     if (!isImm()) return false;
1140     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1141     if (!CE) return false;
1142     int64_t Value = CE->getValue();
1143     return Value == 1 || Value == 0;
1144   }
1145 
1146   bool isReg() const override { return Kind == k_Register; }
1147   bool isRegList() const { return Kind == k_RegisterList; }
1148   bool isDPRRegList() const { return Kind == k_DPRRegisterList; }
1149   bool isSPRRegList() const { return Kind == k_SPRRegisterList; }
1150   bool isToken() const override { return Kind == k_Token; }
1151   bool isMemBarrierOpt() const { return Kind == k_MemBarrierOpt; }
1152   bool isInstSyncBarrierOpt() const { return Kind == k_InstSyncBarrierOpt; }
1153   bool isMem() const override {
1154     if (Kind != k_Memory)
1155       return false;
1156     if (Memory.BaseRegNum &&
1157         !ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Memory.BaseRegNum))
1158       return false;
1159     if (Memory.OffsetRegNum &&
1160         !ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Memory.OffsetRegNum))
1161       return false;
1162     return true;
1163   }
1164   bool isShifterImm() const { return Kind == k_ShifterImmediate; }
1165   bool isRegShiftedReg() const {
1166     return Kind == k_ShiftedRegister &&
1167            ARMMCRegisterClasses[ARM::GPRRegClassID].contains(
1168                RegShiftedReg.SrcReg) &&
1169            ARMMCRegisterClasses[ARM::GPRRegClassID].contains(
1170                RegShiftedReg.ShiftReg);
1171   }
1172   bool isRegShiftedImm() const {
1173     return Kind == k_ShiftedImmediate &&
1174            ARMMCRegisterClasses[ARM::GPRRegClassID].contains(
1175                RegShiftedImm.SrcReg);
1176   }
1177   bool isRotImm() const { return Kind == k_RotateImmediate; }
1178   bool isModImm() const { return Kind == k_ModifiedImmediate; }
1179 
1180   bool isModImmNot() const {
1181     if (!isImm()) return false;
1182     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1183     if (!CE) return false;
1184     int64_t Value = CE->getValue();
1185     return ARM_AM::getSOImmVal(~Value) != -1;
1186   }
1187 
1188   bool isModImmNeg() const {
1189     if (!isImm()) return false;
1190     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1191     if (!CE) return false;
1192     int64_t Value = CE->getValue();
1193     return ARM_AM::getSOImmVal(Value) == -1 &&
1194       ARM_AM::getSOImmVal(-Value) != -1;
1195   }
1196 
1197   bool isThumbModImmNeg1_7() const {
1198     if (!isImm()) return false;
1199     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1200     if (!CE) return false;
1201     int32_t Value = -(int32_t)CE->getValue();
1202     return 0 < Value && Value < 8;
1203   }
1204 
1205   bool isThumbModImmNeg8_255() const {
1206     if (!isImm()) return false;
1207     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1208     if (!CE) return false;
1209     int32_t Value = -(int32_t)CE->getValue();
1210     return 7 < Value && Value < 256;
1211   }
1212 
1213   bool isConstantPoolImm() const { return Kind == k_ConstantPoolImmediate; }
1214   bool isBitfield() const { return Kind == k_BitfieldDescriptor; }
1215   bool isPostIdxRegShifted() const {
1216     return Kind == k_PostIndexRegister &&
1217            ARMMCRegisterClasses[ARM::GPRRegClassID].contains(PostIdxReg.RegNum);
1218   }
1219   bool isPostIdxReg() const {
1220     return isPostIdxRegShifted() && PostIdxReg.ShiftTy == ARM_AM::no_shift;
1221   }
1222   bool isMemNoOffset(bool alignOK = false, unsigned Alignment = 0) const {
1223     if (!isMem())
1224       return false;
1225     // No offset of any kind.
1226     return Memory.OffsetRegNum == 0 && Memory.OffsetImm == nullptr &&
1227      (alignOK || Memory.Alignment == Alignment);
1228   }
1229   bool isMemPCRelImm12() const {
1230     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1231       return false;
1232     // Base register must be PC.
1233     if (Memory.BaseRegNum != ARM::PC)
1234       return false;
1235     // Immediate offset in range [-4095, 4095].
1236     if (!Memory.OffsetImm) return true;
1237     int64_t Val = Memory.OffsetImm->getValue();
1238     return (Val > -4096 && Val < 4096) ||
1239            (Val == std::numeric_limits<int32_t>::min());
1240   }
1241 
1242   bool isAlignedMemory() const {
1243     return isMemNoOffset(true);
1244   }
1245 
1246   bool isAlignedMemoryNone() const {
1247     return isMemNoOffset(false, 0);
1248   }
1249 
1250   bool isDupAlignedMemoryNone() const {
1251     return isMemNoOffset(false, 0);
1252   }
1253 
1254   bool isAlignedMemory16() const {
1255     if (isMemNoOffset(false, 2)) // alignment in bytes for 16-bits is 2.
1256       return true;
1257     return isMemNoOffset(false, 0);
1258   }
1259 
1260   bool isDupAlignedMemory16() const {
1261     if (isMemNoOffset(false, 2)) // alignment in bytes for 16-bits is 2.
1262       return true;
1263     return isMemNoOffset(false, 0);
1264   }
1265 
1266   bool isAlignedMemory32() const {
1267     if (isMemNoOffset(false, 4)) // alignment in bytes for 32-bits is 4.
1268       return true;
1269     return isMemNoOffset(false, 0);
1270   }
1271 
1272   bool isDupAlignedMemory32() const {
1273     if (isMemNoOffset(false, 4)) // alignment in bytes for 32-bits is 4.
1274       return true;
1275     return isMemNoOffset(false, 0);
1276   }
1277 
1278   bool isAlignedMemory64() const {
1279     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1280       return true;
1281     return isMemNoOffset(false, 0);
1282   }
1283 
1284   bool isDupAlignedMemory64() const {
1285     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1286       return true;
1287     return isMemNoOffset(false, 0);
1288   }
1289 
1290   bool isAlignedMemory64or128() const {
1291     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1292       return true;
1293     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1294       return true;
1295     return isMemNoOffset(false, 0);
1296   }
1297 
1298   bool isDupAlignedMemory64or128() const {
1299     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1300       return true;
1301     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1302       return true;
1303     return isMemNoOffset(false, 0);
1304   }
1305 
1306   bool isAlignedMemory64or128or256() const {
1307     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1308       return true;
1309     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1310       return true;
1311     if (isMemNoOffset(false, 32)) // alignment in bytes for 256-bits is 32.
1312       return true;
1313     return isMemNoOffset(false, 0);
1314   }
1315 
1316   bool isAddrMode2() const {
1317     if (!isMem() || Memory.Alignment != 0) return false;
1318     // Check for register offset.
1319     if (Memory.OffsetRegNum) return true;
1320     // Immediate offset in range [-4095, 4095].
1321     if (!Memory.OffsetImm) return true;
1322     int64_t Val = Memory.OffsetImm->getValue();
1323     return Val > -4096 && Val < 4096;
1324   }
1325 
1326   bool isAM2OffsetImm() const {
1327     if (!isImm()) return false;
1328     // Immediate offset in range [-4095, 4095].
1329     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1330     if (!CE) return false;
1331     int64_t Val = CE->getValue();
1332     return (Val == std::numeric_limits<int32_t>::min()) ||
1333            (Val > -4096 && Val < 4096);
1334   }
1335 
1336   bool isAddrMode3() const {
1337     // If we have an immediate that's not a constant, treat it as a label
1338     // reference needing a fixup. If it is a constant, it's something else
1339     // and we reject it.
1340     if (isImm() && !isa<MCConstantExpr>(getImm()))
1341       return true;
1342     if (!isMem() || Memory.Alignment != 0) return false;
1343     // No shifts are legal for AM3.
1344     if (Memory.ShiftType != ARM_AM::no_shift) return false;
1345     // Check for register offset.
1346     if (Memory.OffsetRegNum) return true;
1347     // Immediate offset in range [-255, 255].
1348     if (!Memory.OffsetImm) return true;
1349     int64_t Val = Memory.OffsetImm->getValue();
1350     // The #-0 offset is encoded as std::numeric_limits<int32_t>::min(), and we
1351     // have to check for this too.
1352     return (Val > -256 && Val < 256) ||
1353            Val == std::numeric_limits<int32_t>::min();
1354   }
1355 
1356   bool isAM3Offset() const {
1357     if (isPostIdxReg())
1358       return true;
1359     if (!isImm())
1360       return false;
1361     // Immediate offset in range [-255, 255].
1362     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1363     if (!CE) return false;
1364     int64_t Val = CE->getValue();
1365     // Special case, #-0 is std::numeric_limits<int32_t>::min().
1366     return (Val > -256 && Val < 256) ||
1367            Val == std::numeric_limits<int32_t>::min();
1368   }
1369 
1370   bool isAddrMode5() const {
1371     // If we have an immediate that's not a constant, treat it as a label
1372     // reference needing a fixup. If it is a constant, it's something else
1373     // and we reject it.
1374     if (isImm() && !isa<MCConstantExpr>(getImm()))
1375       return true;
1376     if (!isMem() || Memory.Alignment != 0) return false;
1377     // Check for register offset.
1378     if (Memory.OffsetRegNum) return false;
1379     // Immediate offset in range [-1020, 1020] and a multiple of 4.
1380     if (!Memory.OffsetImm) return true;
1381     int64_t Val = Memory.OffsetImm->getValue();
1382     return (Val >= -1020 && Val <= 1020 && ((Val & 3) == 0)) ||
1383       Val == std::numeric_limits<int32_t>::min();
1384   }
1385 
1386   bool isAddrMode5FP16() const {
1387     // If we have an immediate that's not a constant, treat it as a label
1388     // reference needing a fixup. If it is a constant, it's something else
1389     // and we reject it.
1390     if (isImm() && !isa<MCConstantExpr>(getImm()))
1391       return true;
1392     if (!isMem() || Memory.Alignment != 0) return false;
1393     // Check for register offset.
1394     if (Memory.OffsetRegNum) return false;
1395     // Immediate offset in range [-510, 510] and a multiple of 2.
1396     if (!Memory.OffsetImm) return true;
1397     int64_t Val = Memory.OffsetImm->getValue();
1398     return (Val >= -510 && Val <= 510 && ((Val & 1) == 0)) ||
1399            Val == std::numeric_limits<int32_t>::min();
1400   }
1401 
1402   bool isMemTBB() const {
1403     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1404         Memory.ShiftType != ARM_AM::no_shift || Memory.Alignment != 0)
1405       return false;
1406     return true;
1407   }
1408 
1409   bool isMemTBH() const {
1410     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1411         Memory.ShiftType != ARM_AM::lsl || Memory.ShiftImm != 1 ||
1412         Memory.Alignment != 0 )
1413       return false;
1414     return true;
1415   }
1416 
1417   bool isMemRegOffset() const {
1418     if (!isMem() || !Memory.OffsetRegNum || Memory.Alignment != 0)
1419       return false;
1420     return true;
1421   }
1422 
1423   bool isT2MemRegOffset() const {
1424     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1425         Memory.Alignment != 0 || Memory.BaseRegNum == ARM::PC)
1426       return false;
1427     // Only lsl #{0, 1, 2, 3} allowed.
1428     if (Memory.ShiftType == ARM_AM::no_shift)
1429       return true;
1430     if (Memory.ShiftType != ARM_AM::lsl || Memory.ShiftImm > 3)
1431       return false;
1432     return true;
1433   }
1434 
1435   bool isMemThumbRR() const {
1436     // Thumb reg+reg addressing is simple. Just two registers, a base and
1437     // an offset. No shifts, negations or any other complicating factors.
1438     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1439         Memory.ShiftType != ARM_AM::no_shift || Memory.Alignment != 0)
1440       return false;
1441     return isARMLowRegister(Memory.BaseRegNum) &&
1442       (!Memory.OffsetRegNum || isARMLowRegister(Memory.OffsetRegNum));
1443   }
1444 
1445   bool isMemThumbRIs4() const {
1446     if (!isMem() || Memory.OffsetRegNum != 0 ||
1447         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1448       return false;
1449     // Immediate offset, multiple of 4 in range [0, 124].
1450     if (!Memory.OffsetImm) return true;
1451     int64_t Val = Memory.OffsetImm->getValue();
1452     return Val >= 0 && Val <= 124 && (Val % 4) == 0;
1453   }
1454 
1455   bool isMemThumbRIs2() const {
1456     if (!isMem() || Memory.OffsetRegNum != 0 ||
1457         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1458       return false;
1459     // Immediate offset, multiple of 4 in range [0, 62].
1460     if (!Memory.OffsetImm) return true;
1461     int64_t Val = Memory.OffsetImm->getValue();
1462     return Val >= 0 && Val <= 62 && (Val % 2) == 0;
1463   }
1464 
1465   bool isMemThumbRIs1() const {
1466     if (!isMem() || Memory.OffsetRegNum != 0 ||
1467         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1468       return false;
1469     // Immediate offset in range [0, 31].
1470     if (!Memory.OffsetImm) return true;
1471     int64_t Val = Memory.OffsetImm->getValue();
1472     return Val >= 0 && Val <= 31;
1473   }
1474 
1475   bool isMemThumbSPI() const {
1476     if (!isMem() || Memory.OffsetRegNum != 0 ||
1477         Memory.BaseRegNum != ARM::SP || Memory.Alignment != 0)
1478       return false;
1479     // Immediate offset, multiple of 4 in range [0, 1020].
1480     if (!Memory.OffsetImm) return true;
1481     int64_t Val = Memory.OffsetImm->getValue();
1482     return Val >= 0 && Val <= 1020 && (Val % 4) == 0;
1483   }
1484 
1485   bool isMemImm8s4Offset() const {
1486     // If we have an immediate that's not a constant, treat it as a label
1487     // reference needing a fixup. If it is a constant, it's something else
1488     // and we reject it.
1489     if (isImm() && !isa<MCConstantExpr>(getImm()))
1490       return true;
1491     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1492       return false;
1493     // Immediate offset a multiple of 4 in range [-1020, 1020].
1494     if (!Memory.OffsetImm) return true;
1495     int64_t Val = Memory.OffsetImm->getValue();
1496     // Special case, #-0 is std::numeric_limits<int32_t>::min().
1497     return (Val >= -1020 && Val <= 1020 && (Val & 3) == 0) ||
1498            Val == std::numeric_limits<int32_t>::min();
1499   }
1500 
1501   bool isMemImm0_1020s4Offset() const {
1502     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1503       return false;
1504     // Immediate offset a multiple of 4 in range [0, 1020].
1505     if (!Memory.OffsetImm) return true;
1506     int64_t Val = Memory.OffsetImm->getValue();
1507     return Val >= 0 && Val <= 1020 && (Val & 3) == 0;
1508   }
1509 
1510   bool isMemImm8Offset() const {
1511     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1512       return false;
1513     // Base reg of PC isn't allowed for these encodings.
1514     if (Memory.BaseRegNum == ARM::PC) return false;
1515     // Immediate offset in range [-255, 255].
1516     if (!Memory.OffsetImm) return true;
1517     int64_t Val = Memory.OffsetImm->getValue();
1518     return (Val == std::numeric_limits<int32_t>::min()) ||
1519            (Val > -256 && Val < 256);
1520   }
1521 
1522   bool isMemPosImm8Offset() const {
1523     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1524       return false;
1525     // Immediate offset in range [0, 255].
1526     if (!Memory.OffsetImm) return true;
1527     int64_t Val = Memory.OffsetImm->getValue();
1528     return Val >= 0 && Val < 256;
1529   }
1530 
1531   bool isMemNegImm8Offset() const {
1532     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1533       return false;
1534     // Base reg of PC isn't allowed for these encodings.
1535     if (Memory.BaseRegNum == ARM::PC) return false;
1536     // Immediate offset in range [-255, -1].
1537     if (!Memory.OffsetImm) return false;
1538     int64_t Val = Memory.OffsetImm->getValue();
1539     return (Val == std::numeric_limits<int32_t>::min()) ||
1540            (Val > -256 && Val < 0);
1541   }
1542 
1543   bool isMemUImm12Offset() const {
1544     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1545       return false;
1546     // Immediate offset in range [0, 4095].
1547     if (!Memory.OffsetImm) return true;
1548     int64_t Val = Memory.OffsetImm->getValue();
1549     return (Val >= 0 && Val < 4096);
1550   }
1551 
1552   bool isMemImm12Offset() const {
1553     // If we have an immediate that's not a constant, treat it as a label
1554     // reference needing a fixup. If it is a constant, it's something else
1555     // and we reject it.
1556 
1557     if (isImm() && !isa<MCConstantExpr>(getImm()))
1558       return true;
1559 
1560     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1561       return false;
1562     // Immediate offset in range [-4095, 4095].
1563     if (!Memory.OffsetImm) return true;
1564     int64_t Val = Memory.OffsetImm->getValue();
1565     return (Val > -4096 && Val < 4096) ||
1566            (Val == std::numeric_limits<int32_t>::min());
1567   }
1568 
1569   bool isConstPoolAsmImm() const {
1570     // Delay processing of Constant Pool Immediate, this will turn into
1571     // a constant. Match no other operand
1572     return (isConstantPoolImm());
1573   }
1574 
1575   bool isPostIdxImm8() const {
1576     if (!isImm()) return false;
1577     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1578     if (!CE) return false;
1579     int64_t Val = CE->getValue();
1580     return (Val > -256 && Val < 256) ||
1581            (Val == std::numeric_limits<int32_t>::min());
1582   }
1583 
1584   bool isPostIdxImm8s4() const {
1585     if (!isImm()) return false;
1586     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1587     if (!CE) return false;
1588     int64_t Val = CE->getValue();
1589     return ((Val & 3) == 0 && Val >= -1020 && Val <= 1020) ||
1590            (Val == std::numeric_limits<int32_t>::min());
1591   }
1592 
1593   bool isMSRMask() const { return Kind == k_MSRMask; }
1594   bool isBankedReg() const { return Kind == k_BankedReg; }
1595   bool isProcIFlags() const { return Kind == k_ProcIFlags; }
1596 
1597   // NEON operands.
1598   bool isSingleSpacedVectorList() const {
1599     return Kind == k_VectorList && !VectorList.isDoubleSpaced;
1600   }
1601 
1602   bool isDoubleSpacedVectorList() const {
1603     return Kind == k_VectorList && VectorList.isDoubleSpaced;
1604   }
1605 
1606   bool isVecListOneD() const {
1607     if (!isSingleSpacedVectorList()) return false;
1608     return VectorList.Count == 1;
1609   }
1610 
1611   bool isVecListDPair() const {
1612     if (!isSingleSpacedVectorList()) return false;
1613     return (ARMMCRegisterClasses[ARM::DPairRegClassID]
1614               .contains(VectorList.RegNum));
1615   }
1616 
1617   bool isVecListThreeD() const {
1618     if (!isSingleSpacedVectorList()) return false;
1619     return VectorList.Count == 3;
1620   }
1621 
1622   bool isVecListFourD() const {
1623     if (!isSingleSpacedVectorList()) return false;
1624     return VectorList.Count == 4;
1625   }
1626 
1627   bool isVecListDPairSpaced() const {
1628     if (Kind != k_VectorList) return false;
1629     if (isSingleSpacedVectorList()) return false;
1630     return (ARMMCRegisterClasses[ARM::DPairSpcRegClassID]
1631               .contains(VectorList.RegNum));
1632   }
1633 
1634   bool isVecListThreeQ() const {
1635     if (!isDoubleSpacedVectorList()) return false;
1636     return VectorList.Count == 3;
1637   }
1638 
1639   bool isVecListFourQ() const {
1640     if (!isDoubleSpacedVectorList()) return false;
1641     return VectorList.Count == 4;
1642   }
1643 
1644   bool isSingleSpacedVectorAllLanes() const {
1645     return Kind == k_VectorListAllLanes && !VectorList.isDoubleSpaced;
1646   }
1647 
1648   bool isDoubleSpacedVectorAllLanes() const {
1649     return Kind == k_VectorListAllLanes && VectorList.isDoubleSpaced;
1650   }
1651 
1652   bool isVecListOneDAllLanes() const {
1653     if (!isSingleSpacedVectorAllLanes()) return false;
1654     return VectorList.Count == 1;
1655   }
1656 
1657   bool isVecListDPairAllLanes() const {
1658     if (!isSingleSpacedVectorAllLanes()) return false;
1659     return (ARMMCRegisterClasses[ARM::DPairRegClassID]
1660               .contains(VectorList.RegNum));
1661   }
1662 
1663   bool isVecListDPairSpacedAllLanes() const {
1664     if (!isDoubleSpacedVectorAllLanes()) return false;
1665     return VectorList.Count == 2;
1666   }
1667 
1668   bool isVecListThreeDAllLanes() const {
1669     if (!isSingleSpacedVectorAllLanes()) return false;
1670     return VectorList.Count == 3;
1671   }
1672 
1673   bool isVecListThreeQAllLanes() const {
1674     if (!isDoubleSpacedVectorAllLanes()) return false;
1675     return VectorList.Count == 3;
1676   }
1677 
1678   bool isVecListFourDAllLanes() const {
1679     if (!isSingleSpacedVectorAllLanes()) return false;
1680     return VectorList.Count == 4;
1681   }
1682 
1683   bool isVecListFourQAllLanes() const {
1684     if (!isDoubleSpacedVectorAllLanes()) return false;
1685     return VectorList.Count == 4;
1686   }
1687 
1688   bool isSingleSpacedVectorIndexed() const {
1689     return Kind == k_VectorListIndexed && !VectorList.isDoubleSpaced;
1690   }
1691 
1692   bool isDoubleSpacedVectorIndexed() const {
1693     return Kind == k_VectorListIndexed && VectorList.isDoubleSpaced;
1694   }
1695 
1696   bool isVecListOneDByteIndexed() const {
1697     if (!isSingleSpacedVectorIndexed()) return false;
1698     return VectorList.Count == 1 && VectorList.LaneIndex <= 7;
1699   }
1700 
1701   bool isVecListOneDHWordIndexed() const {
1702     if (!isSingleSpacedVectorIndexed()) return false;
1703     return VectorList.Count == 1 && VectorList.LaneIndex <= 3;
1704   }
1705 
1706   bool isVecListOneDWordIndexed() const {
1707     if (!isSingleSpacedVectorIndexed()) return false;
1708     return VectorList.Count == 1 && VectorList.LaneIndex <= 1;
1709   }
1710 
1711   bool isVecListTwoDByteIndexed() const {
1712     if (!isSingleSpacedVectorIndexed()) return false;
1713     return VectorList.Count == 2 && VectorList.LaneIndex <= 7;
1714   }
1715 
1716   bool isVecListTwoDHWordIndexed() const {
1717     if (!isSingleSpacedVectorIndexed()) return false;
1718     return VectorList.Count == 2 && VectorList.LaneIndex <= 3;
1719   }
1720 
1721   bool isVecListTwoQWordIndexed() const {
1722     if (!isDoubleSpacedVectorIndexed()) return false;
1723     return VectorList.Count == 2 && VectorList.LaneIndex <= 1;
1724   }
1725 
1726   bool isVecListTwoQHWordIndexed() const {
1727     if (!isDoubleSpacedVectorIndexed()) return false;
1728     return VectorList.Count == 2 && VectorList.LaneIndex <= 3;
1729   }
1730 
1731   bool isVecListTwoDWordIndexed() const {
1732     if (!isSingleSpacedVectorIndexed()) return false;
1733     return VectorList.Count == 2 && VectorList.LaneIndex <= 1;
1734   }
1735 
1736   bool isVecListThreeDByteIndexed() const {
1737     if (!isSingleSpacedVectorIndexed()) return false;
1738     return VectorList.Count == 3 && VectorList.LaneIndex <= 7;
1739   }
1740 
1741   bool isVecListThreeDHWordIndexed() const {
1742     if (!isSingleSpacedVectorIndexed()) return false;
1743     return VectorList.Count == 3 && VectorList.LaneIndex <= 3;
1744   }
1745 
1746   bool isVecListThreeQWordIndexed() const {
1747     if (!isDoubleSpacedVectorIndexed()) return false;
1748     return VectorList.Count == 3 && VectorList.LaneIndex <= 1;
1749   }
1750 
1751   bool isVecListThreeQHWordIndexed() const {
1752     if (!isDoubleSpacedVectorIndexed()) return false;
1753     return VectorList.Count == 3 && VectorList.LaneIndex <= 3;
1754   }
1755 
1756   bool isVecListThreeDWordIndexed() const {
1757     if (!isSingleSpacedVectorIndexed()) return false;
1758     return VectorList.Count == 3 && VectorList.LaneIndex <= 1;
1759   }
1760 
1761   bool isVecListFourDByteIndexed() const {
1762     if (!isSingleSpacedVectorIndexed()) return false;
1763     return VectorList.Count == 4 && VectorList.LaneIndex <= 7;
1764   }
1765 
1766   bool isVecListFourDHWordIndexed() const {
1767     if (!isSingleSpacedVectorIndexed()) return false;
1768     return VectorList.Count == 4 && VectorList.LaneIndex <= 3;
1769   }
1770 
1771   bool isVecListFourQWordIndexed() const {
1772     if (!isDoubleSpacedVectorIndexed()) return false;
1773     return VectorList.Count == 4 && VectorList.LaneIndex <= 1;
1774   }
1775 
1776   bool isVecListFourQHWordIndexed() const {
1777     if (!isDoubleSpacedVectorIndexed()) return false;
1778     return VectorList.Count == 4 && VectorList.LaneIndex <= 3;
1779   }
1780 
1781   bool isVecListFourDWordIndexed() const {
1782     if (!isSingleSpacedVectorIndexed()) return false;
1783     return VectorList.Count == 4 && VectorList.LaneIndex <= 1;
1784   }
1785 
1786   bool isVectorIndex8() const {
1787     if (Kind != k_VectorIndex) return false;
1788     return VectorIndex.Val < 8;
1789   }
1790 
1791   bool isVectorIndex16() const {
1792     if (Kind != k_VectorIndex) return false;
1793     return VectorIndex.Val < 4;
1794   }
1795 
1796   bool isVectorIndex32() const {
1797     if (Kind != k_VectorIndex) return false;
1798     return VectorIndex.Val < 2;
1799   }
1800   bool isVectorIndex64() const {
1801     if (Kind != k_VectorIndex) return false;
1802     return VectorIndex.Val < 1;
1803   }
1804 
1805   bool isNEONi8splat() const {
1806     if (!isImm()) return false;
1807     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1808     // Must be a constant.
1809     if (!CE) return false;
1810     int64_t Value = CE->getValue();
1811     // i8 value splatted across 8 bytes. The immediate is just the 8 byte
1812     // value.
1813     return Value >= 0 && Value < 256;
1814   }
1815 
1816   bool isNEONi16splat() const {
1817     if (isNEONByteReplicate(2))
1818       return false; // Leave that for bytes replication and forbid by default.
1819     if (!isImm())
1820       return false;
1821     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1822     // Must be a constant.
1823     if (!CE) return false;
1824     unsigned Value = CE->getValue();
1825     return ARM_AM::isNEONi16splat(Value);
1826   }
1827 
1828   bool isNEONi16splatNot() const {
1829     if (!isImm())
1830       return false;
1831     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1832     // Must be a constant.
1833     if (!CE) return false;
1834     unsigned Value = CE->getValue();
1835     return ARM_AM::isNEONi16splat(~Value & 0xffff);
1836   }
1837 
1838   bool isNEONi32splat() const {
1839     if (isNEONByteReplicate(4))
1840       return false; // Leave that for bytes replication and forbid by default.
1841     if (!isImm())
1842       return false;
1843     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1844     // Must be a constant.
1845     if (!CE) return false;
1846     unsigned Value = CE->getValue();
1847     return ARM_AM::isNEONi32splat(Value);
1848   }
1849 
1850   bool isNEONi32splatNot() const {
1851     if (!isImm())
1852       return false;
1853     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1854     // Must be a constant.
1855     if (!CE) return false;
1856     unsigned Value = CE->getValue();
1857     return ARM_AM::isNEONi32splat(~Value);
1858   }
1859 
1860   bool isNEONByteReplicate(unsigned NumBytes) const {
1861     if (!isImm())
1862       return false;
1863     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1864     // Must be a constant.
1865     if (!CE)
1866       return false;
1867     int64_t Value = CE->getValue();
1868     if (!Value)
1869       return false; // Don't bother with zero.
1870 
1871     unsigned char B = Value & 0xff;
1872     for (unsigned i = 1; i < NumBytes; ++i) {
1873       Value >>= 8;
1874       if ((Value & 0xff) != B)
1875         return false;
1876     }
1877     return true;
1878   }
1879 
1880   bool isNEONi16ByteReplicate() const { return isNEONByteReplicate(2); }
1881   bool isNEONi32ByteReplicate() const { return isNEONByteReplicate(4); }
1882 
1883   bool isNEONi32vmov() const {
1884     if (isNEONByteReplicate(4))
1885       return false; // Let it to be classified as byte-replicate case.
1886     if (!isImm())
1887       return false;
1888     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1889     // Must be a constant.
1890     if (!CE)
1891       return false;
1892     int64_t Value = CE->getValue();
1893     // i32 value with set bits only in one byte X000, 0X00, 00X0, or 000X,
1894     // for VMOV/VMVN only, 00Xf or 0Xff are also accepted.
1895     // FIXME: This is probably wrong and a copy and paste from previous example
1896     return (Value >= 0 && Value < 256) ||
1897       (Value >= 0x0100 && Value <= 0xff00) ||
1898       (Value >= 0x010000 && Value <= 0xff0000) ||
1899       (Value >= 0x01000000 && Value <= 0xff000000) ||
1900       (Value >= 0x01ff && Value <= 0xffff && (Value & 0xff) == 0xff) ||
1901       (Value >= 0x01ffff && Value <= 0xffffff && (Value & 0xffff) == 0xffff);
1902   }
1903 
1904   bool isNEONi32vmovNeg() const {
1905     if (!isImm()) return false;
1906     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1907     // Must be a constant.
1908     if (!CE) return false;
1909     int64_t Value = ~CE->getValue();
1910     // i32 value with set bits only in one byte X000, 0X00, 00X0, or 000X,
1911     // for VMOV/VMVN only, 00Xf or 0Xff are also accepted.
1912     // FIXME: This is probably wrong and a copy and paste from previous example
1913     return (Value >= 0 && Value < 256) ||
1914       (Value >= 0x0100 && Value <= 0xff00) ||
1915       (Value >= 0x010000 && Value <= 0xff0000) ||
1916       (Value >= 0x01000000 && Value <= 0xff000000) ||
1917       (Value >= 0x01ff && Value <= 0xffff && (Value & 0xff) == 0xff) ||
1918       (Value >= 0x01ffff && Value <= 0xffffff && (Value & 0xffff) == 0xffff);
1919   }
1920 
1921   bool isNEONi64splat() const {
1922     if (!isImm()) return false;
1923     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1924     // Must be a constant.
1925     if (!CE) return false;
1926     uint64_t Value = CE->getValue();
1927     // i64 value with each byte being either 0 or 0xff.
1928     for (unsigned i = 0; i < 8; ++i, Value >>= 8)
1929       if ((Value & 0xff) != 0 && (Value & 0xff) != 0xff) return false;
1930     return true;
1931   }
1932 
1933   template<int64_t Angle, int64_t Remainder>
1934   bool isComplexRotation() const {
1935     if (!isImm()) return false;
1936 
1937     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1938     if (!CE) return false;
1939     uint64_t Value = CE->getValue();
1940 
1941     return (Value % Angle == Remainder && Value <= 270);
1942   }
1943 
1944   void addExpr(MCInst &Inst, const MCExpr *Expr) const {
1945     // Add as immediates when possible.  Null MCExpr = 0.
1946     if (!Expr)
1947       Inst.addOperand(MCOperand::createImm(0));
1948     else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
1949       Inst.addOperand(MCOperand::createImm(CE->getValue()));
1950     else
1951       Inst.addOperand(MCOperand::createExpr(Expr));
1952   }
1953 
1954   void addARMBranchTargetOperands(MCInst &Inst, unsigned N) const {
1955     assert(N == 1 && "Invalid number of operands!");
1956     addExpr(Inst, getImm());
1957   }
1958 
1959   void addThumbBranchTargetOperands(MCInst &Inst, unsigned N) const {
1960     assert(N == 1 && "Invalid number of operands!");
1961     addExpr(Inst, getImm());
1962   }
1963 
1964   void addCondCodeOperands(MCInst &Inst, unsigned N) const {
1965     assert(N == 2 && "Invalid number of operands!");
1966     Inst.addOperand(MCOperand::createImm(unsigned(getCondCode())));
1967     unsigned RegNum = getCondCode() == ARMCC::AL ? 0: ARM::CPSR;
1968     Inst.addOperand(MCOperand::createReg(RegNum));
1969   }
1970 
1971   void addCoprocNumOperands(MCInst &Inst, unsigned N) const {
1972     assert(N == 1 && "Invalid number of operands!");
1973     Inst.addOperand(MCOperand::createImm(getCoproc()));
1974   }
1975 
1976   void addCoprocRegOperands(MCInst &Inst, unsigned N) const {
1977     assert(N == 1 && "Invalid number of operands!");
1978     Inst.addOperand(MCOperand::createImm(getCoproc()));
1979   }
1980 
1981   void addCoprocOptionOperands(MCInst &Inst, unsigned N) const {
1982     assert(N == 1 && "Invalid number of operands!");
1983     Inst.addOperand(MCOperand::createImm(CoprocOption.Val));
1984   }
1985 
1986   void addITMaskOperands(MCInst &Inst, unsigned N) const {
1987     assert(N == 1 && "Invalid number of operands!");
1988     Inst.addOperand(MCOperand::createImm(ITMask.Mask));
1989   }
1990 
1991   void addITCondCodeOperands(MCInst &Inst, unsigned N) const {
1992     assert(N == 1 && "Invalid number of operands!");
1993     Inst.addOperand(MCOperand::createImm(unsigned(getCondCode())));
1994   }
1995 
1996   void addCCOutOperands(MCInst &Inst, unsigned N) const {
1997     assert(N == 1 && "Invalid number of operands!");
1998     Inst.addOperand(MCOperand::createReg(getReg()));
1999   }
2000 
2001   void addRegOperands(MCInst &Inst, unsigned N) const {
2002     assert(N == 1 && "Invalid number of operands!");
2003     Inst.addOperand(MCOperand::createReg(getReg()));
2004   }
2005 
2006   void addRegShiftedRegOperands(MCInst &Inst, unsigned N) const {
2007     assert(N == 3 && "Invalid number of operands!");
2008     assert(isRegShiftedReg() &&
2009            "addRegShiftedRegOperands() on non-RegShiftedReg!");
2010     Inst.addOperand(MCOperand::createReg(RegShiftedReg.SrcReg));
2011     Inst.addOperand(MCOperand::createReg(RegShiftedReg.ShiftReg));
2012     Inst.addOperand(MCOperand::createImm(
2013       ARM_AM::getSORegOpc(RegShiftedReg.ShiftTy, RegShiftedReg.ShiftImm)));
2014   }
2015 
2016   void addRegShiftedImmOperands(MCInst &Inst, unsigned N) const {
2017     assert(N == 2 && "Invalid number of operands!");
2018     assert(isRegShiftedImm() &&
2019            "addRegShiftedImmOperands() on non-RegShiftedImm!");
2020     Inst.addOperand(MCOperand::createReg(RegShiftedImm.SrcReg));
2021     // Shift of #32 is encoded as 0 where permitted
2022     unsigned Imm = (RegShiftedImm.ShiftImm == 32 ? 0 : RegShiftedImm.ShiftImm);
2023     Inst.addOperand(MCOperand::createImm(
2024       ARM_AM::getSORegOpc(RegShiftedImm.ShiftTy, Imm)));
2025   }
2026 
2027   void addShifterImmOperands(MCInst &Inst, unsigned N) const {
2028     assert(N == 1 && "Invalid number of operands!");
2029     Inst.addOperand(MCOperand::createImm((ShifterImm.isASR << 5) |
2030                                          ShifterImm.Imm));
2031   }
2032 
2033   void addRegListOperands(MCInst &Inst, unsigned N) const {
2034     assert(N == 1 && "Invalid number of operands!");
2035     const SmallVectorImpl<unsigned> &RegList = getRegList();
2036     for (SmallVectorImpl<unsigned>::const_iterator
2037            I = RegList.begin(), E = RegList.end(); I != E; ++I)
2038       Inst.addOperand(MCOperand::createReg(*I));
2039   }
2040 
2041   void addDPRRegListOperands(MCInst &Inst, unsigned N) const {
2042     addRegListOperands(Inst, N);
2043   }
2044 
2045   void addSPRRegListOperands(MCInst &Inst, unsigned N) const {
2046     addRegListOperands(Inst, N);
2047   }
2048 
2049   void addRotImmOperands(MCInst &Inst, unsigned N) const {
2050     assert(N == 1 && "Invalid number of operands!");
2051     // Encoded as val>>3. The printer handles display as 8, 16, 24.
2052     Inst.addOperand(MCOperand::createImm(RotImm.Imm >> 3));
2053   }
2054 
2055   void addModImmOperands(MCInst &Inst, unsigned N) const {
2056     assert(N == 1 && "Invalid number of operands!");
2057 
2058     // Support for fixups (MCFixup)
2059     if (isImm())
2060       return addImmOperands(Inst, N);
2061 
2062     Inst.addOperand(MCOperand::createImm(ModImm.Bits | (ModImm.Rot << 7)));
2063   }
2064 
2065   void addModImmNotOperands(MCInst &Inst, unsigned N) const {
2066     assert(N == 1 && "Invalid number of operands!");
2067     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2068     uint32_t Enc = ARM_AM::getSOImmVal(~CE->getValue());
2069     Inst.addOperand(MCOperand::createImm(Enc));
2070   }
2071 
2072   void addModImmNegOperands(MCInst &Inst, unsigned N) const {
2073     assert(N == 1 && "Invalid number of operands!");
2074     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2075     uint32_t Enc = ARM_AM::getSOImmVal(-CE->getValue());
2076     Inst.addOperand(MCOperand::createImm(Enc));
2077   }
2078 
2079   void addThumbModImmNeg8_255Operands(MCInst &Inst, unsigned N) const {
2080     assert(N == 1 && "Invalid number of operands!");
2081     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2082     uint32_t Val = -CE->getValue();
2083     Inst.addOperand(MCOperand::createImm(Val));
2084   }
2085 
2086   void addThumbModImmNeg1_7Operands(MCInst &Inst, unsigned N) const {
2087     assert(N == 1 && "Invalid number of operands!");
2088     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2089     uint32_t Val = -CE->getValue();
2090     Inst.addOperand(MCOperand::createImm(Val));
2091   }
2092 
2093   void addBitfieldOperands(MCInst &Inst, unsigned N) const {
2094     assert(N == 1 && "Invalid number of operands!");
2095     // Munge the lsb/width into a bitfield mask.
2096     unsigned lsb = Bitfield.LSB;
2097     unsigned width = Bitfield.Width;
2098     // Make a 32-bit mask w/ the referenced bits clear and all other bits set.
2099     uint32_t Mask = ~(((uint32_t)0xffffffff >> lsb) << (32 - width) >>
2100                       (32 - (lsb + width)));
2101     Inst.addOperand(MCOperand::createImm(Mask));
2102   }
2103 
2104   void addImmOperands(MCInst &Inst, unsigned N) const {
2105     assert(N == 1 && "Invalid number of operands!");
2106     addExpr(Inst, getImm());
2107   }
2108 
2109   void addFBits16Operands(MCInst &Inst, unsigned N) const {
2110     assert(N == 1 && "Invalid number of operands!");
2111     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2112     Inst.addOperand(MCOperand::createImm(16 - CE->getValue()));
2113   }
2114 
2115   void addFBits32Operands(MCInst &Inst, unsigned N) const {
2116     assert(N == 1 && "Invalid number of operands!");
2117     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2118     Inst.addOperand(MCOperand::createImm(32 - CE->getValue()));
2119   }
2120 
2121   void addFPImmOperands(MCInst &Inst, unsigned N) const {
2122     assert(N == 1 && "Invalid number of operands!");
2123     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2124     int Val = ARM_AM::getFP32Imm(APInt(32, CE->getValue()));
2125     Inst.addOperand(MCOperand::createImm(Val));
2126   }
2127 
2128   void addImm8s4Operands(MCInst &Inst, unsigned N) const {
2129     assert(N == 1 && "Invalid number of operands!");
2130     // FIXME: We really want to scale the value here, but the LDRD/STRD
2131     // instruction don't encode operands that way yet.
2132     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2133     Inst.addOperand(MCOperand::createImm(CE->getValue()));
2134   }
2135 
2136   void addImm0_1020s4Operands(MCInst &Inst, unsigned N) const {
2137     assert(N == 1 && "Invalid number of operands!");
2138     // The immediate is scaled by four in the encoding and is stored
2139     // in the MCInst as such. Lop off the low two bits here.
2140     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2141     Inst.addOperand(MCOperand::createImm(CE->getValue() / 4));
2142   }
2143 
2144   void addImm0_508s4NegOperands(MCInst &Inst, unsigned N) const {
2145     assert(N == 1 && "Invalid number of operands!");
2146     // The immediate is scaled by four in the encoding and is stored
2147     // in the MCInst as such. Lop off the low two bits here.
2148     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2149     Inst.addOperand(MCOperand::createImm(-(CE->getValue() / 4)));
2150   }
2151 
2152   void addImm0_508s4Operands(MCInst &Inst, unsigned N) const {
2153     assert(N == 1 && "Invalid number of operands!");
2154     // The immediate is scaled by four in the encoding and is stored
2155     // in the MCInst as such. Lop off the low two bits here.
2156     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2157     Inst.addOperand(MCOperand::createImm(CE->getValue() / 4));
2158   }
2159 
2160   void addImm1_16Operands(MCInst &Inst, unsigned N) const {
2161     assert(N == 1 && "Invalid number of operands!");
2162     // The constant encodes as the immediate-1, and we store in the instruction
2163     // the bits as encoded, so subtract off one here.
2164     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2165     Inst.addOperand(MCOperand::createImm(CE->getValue() - 1));
2166   }
2167 
2168   void addImm1_32Operands(MCInst &Inst, unsigned N) const {
2169     assert(N == 1 && "Invalid number of operands!");
2170     // The constant encodes as the immediate-1, and we store in the instruction
2171     // the bits as encoded, so subtract off one here.
2172     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2173     Inst.addOperand(MCOperand::createImm(CE->getValue() - 1));
2174   }
2175 
2176   void addImmThumbSROperands(MCInst &Inst, unsigned N) const {
2177     assert(N == 1 && "Invalid number of operands!");
2178     // The constant encodes as the immediate, except for 32, which encodes as
2179     // zero.
2180     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2181     unsigned Imm = CE->getValue();
2182     Inst.addOperand(MCOperand::createImm((Imm == 32 ? 0 : Imm)));
2183   }
2184 
2185   void addPKHASRImmOperands(MCInst &Inst, unsigned N) const {
2186     assert(N == 1 && "Invalid number of operands!");
2187     // An ASR value of 32 encodes as 0, so that's how we want to add it to
2188     // the instruction as well.
2189     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2190     int Val = CE->getValue();
2191     Inst.addOperand(MCOperand::createImm(Val == 32 ? 0 : Val));
2192   }
2193 
2194   void addT2SOImmNotOperands(MCInst &Inst, unsigned N) const {
2195     assert(N == 1 && "Invalid number of operands!");
2196     // The operand is actually a t2_so_imm, but we have its bitwise
2197     // negation in the assembly source, so twiddle it here.
2198     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2199     Inst.addOperand(MCOperand::createImm(~(uint32_t)CE->getValue()));
2200   }
2201 
2202   void addT2SOImmNegOperands(MCInst &Inst, unsigned N) const {
2203     assert(N == 1 && "Invalid number of operands!");
2204     // The operand is actually a t2_so_imm, but we have its
2205     // negation in the assembly source, so twiddle it here.
2206     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2207     Inst.addOperand(MCOperand::createImm(-(uint32_t)CE->getValue()));
2208   }
2209 
2210   void addImm0_4095NegOperands(MCInst &Inst, unsigned N) const {
2211     assert(N == 1 && "Invalid number of operands!");
2212     // The operand is actually an imm0_4095, but we have its
2213     // negation in the assembly source, so twiddle it here.
2214     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2215     Inst.addOperand(MCOperand::createImm(-CE->getValue()));
2216   }
2217 
2218   void addUnsignedOffset_b8s2Operands(MCInst &Inst, unsigned N) const {
2219     if(const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm())) {
2220       Inst.addOperand(MCOperand::createImm(CE->getValue() >> 2));
2221       return;
2222     }
2223 
2224     const MCSymbolRefExpr *SR = dyn_cast<MCSymbolRefExpr>(Imm.Val);
2225     assert(SR && "Unknown value type!");
2226     Inst.addOperand(MCOperand::createExpr(SR));
2227   }
2228 
2229   void addThumbMemPCOperands(MCInst &Inst, unsigned N) const {
2230     assert(N == 1 && "Invalid number of operands!");
2231     if (isImm()) {
2232       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2233       if (CE) {
2234         Inst.addOperand(MCOperand::createImm(CE->getValue()));
2235         return;
2236       }
2237 
2238       const MCSymbolRefExpr *SR = dyn_cast<MCSymbolRefExpr>(Imm.Val);
2239 
2240       assert(SR && "Unknown value type!");
2241       Inst.addOperand(MCOperand::createExpr(SR));
2242       return;
2243     }
2244 
2245     assert(isMem()  && "Unknown value type!");
2246     assert(isa<MCConstantExpr>(Memory.OffsetImm) && "Unknown value type!");
2247     Inst.addOperand(MCOperand::createImm(Memory.OffsetImm->getValue()));
2248   }
2249 
2250   void addMemBarrierOptOperands(MCInst &Inst, unsigned N) const {
2251     assert(N == 1 && "Invalid number of operands!");
2252     Inst.addOperand(MCOperand::createImm(unsigned(getMemBarrierOpt())));
2253   }
2254 
2255   void addInstSyncBarrierOptOperands(MCInst &Inst, unsigned N) const {
2256     assert(N == 1 && "Invalid number of operands!");
2257     Inst.addOperand(MCOperand::createImm(unsigned(getInstSyncBarrierOpt())));
2258   }
2259 
2260   void addMemNoOffsetOperands(MCInst &Inst, unsigned N) const {
2261     assert(N == 1 && "Invalid number of operands!");
2262     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2263   }
2264 
2265   void addMemPCRelImm12Operands(MCInst &Inst, unsigned N) const {
2266     assert(N == 1 && "Invalid number of operands!");
2267     int32_t Imm = Memory.OffsetImm->getValue();
2268     Inst.addOperand(MCOperand::createImm(Imm));
2269   }
2270 
2271   void addAdrLabelOperands(MCInst &Inst, unsigned N) const {
2272     assert(N == 1 && "Invalid number of operands!");
2273     assert(isImm() && "Not an immediate!");
2274 
2275     // If we have an immediate that's not a constant, treat it as a label
2276     // reference needing a fixup.
2277     if (!isa<MCConstantExpr>(getImm())) {
2278       Inst.addOperand(MCOperand::createExpr(getImm()));
2279       return;
2280     }
2281 
2282     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2283     int Val = CE->getValue();
2284     Inst.addOperand(MCOperand::createImm(Val));
2285   }
2286 
2287   void addAlignedMemoryOperands(MCInst &Inst, unsigned N) const {
2288     assert(N == 2 && "Invalid number of operands!");
2289     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2290     Inst.addOperand(MCOperand::createImm(Memory.Alignment));
2291   }
2292 
2293   void addDupAlignedMemoryNoneOperands(MCInst &Inst, unsigned N) const {
2294     addAlignedMemoryOperands(Inst, N);
2295   }
2296 
2297   void addAlignedMemoryNoneOperands(MCInst &Inst, unsigned N) const {
2298     addAlignedMemoryOperands(Inst, N);
2299   }
2300 
2301   void addAlignedMemory16Operands(MCInst &Inst, unsigned N) const {
2302     addAlignedMemoryOperands(Inst, N);
2303   }
2304 
2305   void addDupAlignedMemory16Operands(MCInst &Inst, unsigned N) const {
2306     addAlignedMemoryOperands(Inst, N);
2307   }
2308 
2309   void addAlignedMemory32Operands(MCInst &Inst, unsigned N) const {
2310     addAlignedMemoryOperands(Inst, N);
2311   }
2312 
2313   void addDupAlignedMemory32Operands(MCInst &Inst, unsigned N) const {
2314     addAlignedMemoryOperands(Inst, N);
2315   }
2316 
2317   void addAlignedMemory64Operands(MCInst &Inst, unsigned N) const {
2318     addAlignedMemoryOperands(Inst, N);
2319   }
2320 
2321   void addDupAlignedMemory64Operands(MCInst &Inst, unsigned N) const {
2322     addAlignedMemoryOperands(Inst, N);
2323   }
2324 
2325   void addAlignedMemory64or128Operands(MCInst &Inst, unsigned N) const {
2326     addAlignedMemoryOperands(Inst, N);
2327   }
2328 
2329   void addDupAlignedMemory64or128Operands(MCInst &Inst, unsigned N) const {
2330     addAlignedMemoryOperands(Inst, N);
2331   }
2332 
2333   void addAlignedMemory64or128or256Operands(MCInst &Inst, unsigned N) const {
2334     addAlignedMemoryOperands(Inst, N);
2335   }
2336 
2337   void addAddrMode2Operands(MCInst &Inst, unsigned N) const {
2338     assert(N == 3 && "Invalid number of operands!");
2339     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2340     if (!Memory.OffsetRegNum) {
2341       ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2342       // Special case for #-0
2343       if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2344       if (Val < 0) Val = -Val;
2345       Val = ARM_AM::getAM2Opc(AddSub, Val, ARM_AM::no_shift);
2346     } else {
2347       // For register offset, we encode the shift type and negation flag
2348       // here.
2349       Val = ARM_AM::getAM2Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add,
2350                               Memory.ShiftImm, Memory.ShiftType);
2351     }
2352     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2353     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2354     Inst.addOperand(MCOperand::createImm(Val));
2355   }
2356 
2357   void addAM2OffsetImmOperands(MCInst &Inst, unsigned N) const {
2358     assert(N == 2 && "Invalid number of operands!");
2359     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2360     assert(CE && "non-constant AM2OffsetImm operand!");
2361     int32_t Val = CE->getValue();
2362     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2363     // Special case for #-0
2364     if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2365     if (Val < 0) Val = -Val;
2366     Val = ARM_AM::getAM2Opc(AddSub, Val, ARM_AM::no_shift);
2367     Inst.addOperand(MCOperand::createReg(0));
2368     Inst.addOperand(MCOperand::createImm(Val));
2369   }
2370 
2371   void addAddrMode3Operands(MCInst &Inst, unsigned N) const {
2372     assert(N == 3 && "Invalid number of operands!");
2373     // If we have an immediate that's not a constant, treat it as a label
2374     // reference needing a fixup. If it is a constant, it's something else
2375     // and we reject it.
2376     if (isImm()) {
2377       Inst.addOperand(MCOperand::createExpr(getImm()));
2378       Inst.addOperand(MCOperand::createReg(0));
2379       Inst.addOperand(MCOperand::createImm(0));
2380       return;
2381     }
2382 
2383     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2384     if (!Memory.OffsetRegNum) {
2385       ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2386       // Special case for #-0
2387       if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2388       if (Val < 0) Val = -Val;
2389       Val = ARM_AM::getAM3Opc(AddSub, Val);
2390     } else {
2391       // For register offset, we encode the shift type and negation flag
2392       // here.
2393       Val = ARM_AM::getAM3Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add, 0);
2394     }
2395     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2396     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2397     Inst.addOperand(MCOperand::createImm(Val));
2398   }
2399 
2400   void addAM3OffsetOperands(MCInst &Inst, unsigned N) const {
2401     assert(N == 2 && "Invalid number of operands!");
2402     if (Kind == k_PostIndexRegister) {
2403       int32_t Val =
2404         ARM_AM::getAM3Opc(PostIdxReg.isAdd ? ARM_AM::add : ARM_AM::sub, 0);
2405       Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
2406       Inst.addOperand(MCOperand::createImm(Val));
2407       return;
2408     }
2409 
2410     // Constant offset.
2411     const MCConstantExpr *CE = static_cast<const MCConstantExpr*>(getImm());
2412     int32_t Val = CE->getValue();
2413     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2414     // Special case for #-0
2415     if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2416     if (Val < 0) Val = -Val;
2417     Val = ARM_AM::getAM3Opc(AddSub, Val);
2418     Inst.addOperand(MCOperand::createReg(0));
2419     Inst.addOperand(MCOperand::createImm(Val));
2420   }
2421 
2422   void addAddrMode5Operands(MCInst &Inst, unsigned N) const {
2423     assert(N == 2 && "Invalid number of operands!");
2424     // If we have an immediate that's not a constant, treat it as a label
2425     // reference needing a fixup. If it is a constant, it's something else
2426     // and we reject it.
2427     if (isImm()) {
2428       Inst.addOperand(MCOperand::createExpr(getImm()));
2429       Inst.addOperand(MCOperand::createImm(0));
2430       return;
2431     }
2432 
2433     // The lower two bits are always zero and as such are not encoded.
2434     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 4 : 0;
2435     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2436     // Special case for #-0
2437     if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2438     if (Val < 0) Val = -Val;
2439     Val = ARM_AM::getAM5Opc(AddSub, Val);
2440     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2441     Inst.addOperand(MCOperand::createImm(Val));
2442   }
2443 
2444   void addAddrMode5FP16Operands(MCInst &Inst, unsigned N) const {
2445     assert(N == 2 && "Invalid number of operands!");
2446     // If we have an immediate that's not a constant, treat it as a label
2447     // reference needing a fixup. If it is a constant, it's something else
2448     // and we reject it.
2449     if (isImm()) {
2450       Inst.addOperand(MCOperand::createExpr(getImm()));
2451       Inst.addOperand(MCOperand::createImm(0));
2452       return;
2453     }
2454 
2455     // The lower bit is always zero and as such is not encoded.
2456     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 2 : 0;
2457     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2458     // Special case for #-0
2459     if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2460     if (Val < 0) Val = -Val;
2461     Val = ARM_AM::getAM5FP16Opc(AddSub, Val);
2462     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2463     Inst.addOperand(MCOperand::createImm(Val));
2464   }
2465 
2466   void addMemImm8s4OffsetOperands(MCInst &Inst, unsigned N) const {
2467     assert(N == 2 && "Invalid number of operands!");
2468     // If we have an immediate that's not a constant, treat it as a label
2469     // reference needing a fixup. If it is a constant, it's something else
2470     // and we reject it.
2471     if (isImm()) {
2472       Inst.addOperand(MCOperand::createExpr(getImm()));
2473       Inst.addOperand(MCOperand::createImm(0));
2474       return;
2475     }
2476 
2477     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2478     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2479     Inst.addOperand(MCOperand::createImm(Val));
2480   }
2481 
2482   void addMemImm0_1020s4OffsetOperands(MCInst &Inst, unsigned N) const {
2483     assert(N == 2 && "Invalid number of operands!");
2484     // The lower two bits are always zero and as such are not encoded.
2485     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 4 : 0;
2486     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2487     Inst.addOperand(MCOperand::createImm(Val));
2488   }
2489 
2490   void addMemImm8OffsetOperands(MCInst &Inst, unsigned N) const {
2491     assert(N == 2 && "Invalid number of operands!");
2492     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2493     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2494     Inst.addOperand(MCOperand::createImm(Val));
2495   }
2496 
2497   void addMemPosImm8OffsetOperands(MCInst &Inst, unsigned N) const {
2498     addMemImm8OffsetOperands(Inst, N);
2499   }
2500 
2501   void addMemNegImm8OffsetOperands(MCInst &Inst, unsigned N) const {
2502     addMemImm8OffsetOperands(Inst, N);
2503   }
2504 
2505   void addMemUImm12OffsetOperands(MCInst &Inst, unsigned N) const {
2506     assert(N == 2 && "Invalid number of operands!");
2507     // If this is an immediate, it's a label reference.
2508     if (isImm()) {
2509       addExpr(Inst, getImm());
2510       Inst.addOperand(MCOperand::createImm(0));
2511       return;
2512     }
2513 
2514     // Otherwise, it's a normal memory reg+offset.
2515     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2516     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2517     Inst.addOperand(MCOperand::createImm(Val));
2518   }
2519 
2520   void addMemImm12OffsetOperands(MCInst &Inst, unsigned N) const {
2521     assert(N == 2 && "Invalid number of operands!");
2522     // If this is an immediate, it's a label reference.
2523     if (isImm()) {
2524       addExpr(Inst, getImm());
2525       Inst.addOperand(MCOperand::createImm(0));
2526       return;
2527     }
2528 
2529     // Otherwise, it's a normal memory reg+offset.
2530     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2531     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2532     Inst.addOperand(MCOperand::createImm(Val));
2533   }
2534 
2535   void addConstPoolAsmImmOperands(MCInst &Inst, unsigned N) const {
2536     assert(N == 1 && "Invalid number of operands!");
2537     // This is container for the immediate that we will create the constant
2538     // pool from
2539     addExpr(Inst, getConstantPoolImm());
2540     return;
2541   }
2542 
2543   void addMemTBBOperands(MCInst &Inst, unsigned N) const {
2544     assert(N == 2 && "Invalid number of operands!");
2545     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2546     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2547   }
2548 
2549   void addMemTBHOperands(MCInst &Inst, unsigned N) const {
2550     assert(N == 2 && "Invalid number of operands!");
2551     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2552     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2553   }
2554 
2555   void addMemRegOffsetOperands(MCInst &Inst, unsigned N) const {
2556     assert(N == 3 && "Invalid number of operands!");
2557     unsigned Val =
2558       ARM_AM::getAM2Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add,
2559                         Memory.ShiftImm, Memory.ShiftType);
2560     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2561     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2562     Inst.addOperand(MCOperand::createImm(Val));
2563   }
2564 
2565   void addT2MemRegOffsetOperands(MCInst &Inst, unsigned N) const {
2566     assert(N == 3 && "Invalid number of operands!");
2567     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2568     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2569     Inst.addOperand(MCOperand::createImm(Memory.ShiftImm));
2570   }
2571 
2572   void addMemThumbRROperands(MCInst &Inst, unsigned N) const {
2573     assert(N == 2 && "Invalid number of operands!");
2574     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2575     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2576   }
2577 
2578   void addMemThumbRIs4Operands(MCInst &Inst, unsigned N) const {
2579     assert(N == 2 && "Invalid number of operands!");
2580     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 4) : 0;
2581     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2582     Inst.addOperand(MCOperand::createImm(Val));
2583   }
2584 
2585   void addMemThumbRIs2Operands(MCInst &Inst, unsigned N) const {
2586     assert(N == 2 && "Invalid number of operands!");
2587     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 2) : 0;
2588     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2589     Inst.addOperand(MCOperand::createImm(Val));
2590   }
2591 
2592   void addMemThumbRIs1Operands(MCInst &Inst, unsigned N) const {
2593     assert(N == 2 && "Invalid number of operands!");
2594     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue()) : 0;
2595     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2596     Inst.addOperand(MCOperand::createImm(Val));
2597   }
2598 
2599   void addMemThumbSPIOperands(MCInst &Inst, unsigned N) const {
2600     assert(N == 2 && "Invalid number of operands!");
2601     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 4) : 0;
2602     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2603     Inst.addOperand(MCOperand::createImm(Val));
2604   }
2605 
2606   void addPostIdxImm8Operands(MCInst &Inst, unsigned N) const {
2607     assert(N == 1 && "Invalid number of operands!");
2608     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2609     assert(CE && "non-constant post-idx-imm8 operand!");
2610     int Imm = CE->getValue();
2611     bool isAdd = Imm >= 0;
2612     if (Imm == std::numeric_limits<int32_t>::min()) Imm = 0;
2613     Imm = (Imm < 0 ? -Imm : Imm) | (int)isAdd << 8;
2614     Inst.addOperand(MCOperand::createImm(Imm));
2615   }
2616 
2617   void addPostIdxImm8s4Operands(MCInst &Inst, unsigned N) const {
2618     assert(N == 1 && "Invalid number of operands!");
2619     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2620     assert(CE && "non-constant post-idx-imm8s4 operand!");
2621     int Imm = CE->getValue();
2622     bool isAdd = Imm >= 0;
2623     if (Imm == std::numeric_limits<int32_t>::min()) Imm = 0;
2624     // Immediate is scaled by 4.
2625     Imm = ((Imm < 0 ? -Imm : Imm) / 4) | (int)isAdd << 8;
2626     Inst.addOperand(MCOperand::createImm(Imm));
2627   }
2628 
2629   void addPostIdxRegOperands(MCInst &Inst, unsigned N) const {
2630     assert(N == 2 && "Invalid number of operands!");
2631     Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
2632     Inst.addOperand(MCOperand::createImm(PostIdxReg.isAdd));
2633   }
2634 
2635   void addPostIdxRegShiftedOperands(MCInst &Inst, unsigned N) const {
2636     assert(N == 2 && "Invalid number of operands!");
2637     Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
2638     // The sign, shift type, and shift amount are encoded in a single operand
2639     // using the AM2 encoding helpers.
2640     ARM_AM::AddrOpc opc = PostIdxReg.isAdd ? ARM_AM::add : ARM_AM::sub;
2641     unsigned Imm = ARM_AM::getAM2Opc(opc, PostIdxReg.ShiftImm,
2642                                      PostIdxReg.ShiftTy);
2643     Inst.addOperand(MCOperand::createImm(Imm));
2644   }
2645 
2646   void addMSRMaskOperands(MCInst &Inst, unsigned N) const {
2647     assert(N == 1 && "Invalid number of operands!");
2648     Inst.addOperand(MCOperand::createImm(unsigned(getMSRMask())));
2649   }
2650 
2651   void addBankedRegOperands(MCInst &Inst, unsigned N) const {
2652     assert(N == 1 && "Invalid number of operands!");
2653     Inst.addOperand(MCOperand::createImm(unsigned(getBankedReg())));
2654   }
2655 
2656   void addProcIFlagsOperands(MCInst &Inst, unsigned N) const {
2657     assert(N == 1 && "Invalid number of operands!");
2658     Inst.addOperand(MCOperand::createImm(unsigned(getProcIFlags())));
2659   }
2660 
2661   void addVecListOperands(MCInst &Inst, unsigned N) const {
2662     assert(N == 1 && "Invalid number of operands!");
2663     Inst.addOperand(MCOperand::createReg(VectorList.RegNum));
2664   }
2665 
2666   void addVecListIndexedOperands(MCInst &Inst, unsigned N) const {
2667     assert(N == 2 && "Invalid number of operands!");
2668     Inst.addOperand(MCOperand::createReg(VectorList.RegNum));
2669     Inst.addOperand(MCOperand::createImm(VectorList.LaneIndex));
2670   }
2671 
2672   void addVectorIndex8Operands(MCInst &Inst, unsigned N) const {
2673     assert(N == 1 && "Invalid number of operands!");
2674     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
2675   }
2676 
2677   void addVectorIndex16Operands(MCInst &Inst, unsigned N) const {
2678     assert(N == 1 && "Invalid number of operands!");
2679     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
2680   }
2681 
2682   void addVectorIndex32Operands(MCInst &Inst, unsigned N) const {
2683     assert(N == 1 && "Invalid number of operands!");
2684     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
2685   }
2686 
2687   void addVectorIndex64Operands(MCInst &Inst, unsigned N) const {
2688     assert(N == 1 && "Invalid number of operands!");
2689     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
2690   }
2691 
2692   void addNEONi8splatOperands(MCInst &Inst, unsigned N) const {
2693     assert(N == 1 && "Invalid number of operands!");
2694     // The immediate encodes the type of constant as well as the value.
2695     // Mask in that this is an i8 splat.
2696     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2697     Inst.addOperand(MCOperand::createImm(CE->getValue() | 0xe00));
2698   }
2699 
2700   void addNEONi16splatOperands(MCInst &Inst, unsigned N) const {
2701     assert(N == 1 && "Invalid number of operands!");
2702     // The immediate encodes the type of constant as well as the value.
2703     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2704     unsigned Value = CE->getValue();
2705     Value = ARM_AM::encodeNEONi16splat(Value);
2706     Inst.addOperand(MCOperand::createImm(Value));
2707   }
2708 
2709   void addNEONi16splatNotOperands(MCInst &Inst, unsigned N) const {
2710     assert(N == 1 && "Invalid number of operands!");
2711     // The immediate encodes the type of constant as well as the value.
2712     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2713     unsigned Value = CE->getValue();
2714     Value = ARM_AM::encodeNEONi16splat(~Value & 0xffff);
2715     Inst.addOperand(MCOperand::createImm(Value));
2716   }
2717 
2718   void addNEONi32splatOperands(MCInst &Inst, unsigned N) const {
2719     assert(N == 1 && "Invalid number of operands!");
2720     // The immediate encodes the type of constant as well as the value.
2721     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2722     unsigned Value = CE->getValue();
2723     Value = ARM_AM::encodeNEONi32splat(Value);
2724     Inst.addOperand(MCOperand::createImm(Value));
2725   }
2726 
2727   void addNEONi32splatNotOperands(MCInst &Inst, unsigned N) const {
2728     assert(N == 1 && "Invalid number of operands!");
2729     // The immediate encodes the type of constant as well as the value.
2730     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2731     unsigned Value = CE->getValue();
2732     Value = ARM_AM::encodeNEONi32splat(~Value);
2733     Inst.addOperand(MCOperand::createImm(Value));
2734   }
2735 
2736   void addNEONinvByteReplicateOperands(MCInst &Inst, unsigned N) const {
2737     assert(N == 1 && "Invalid number of operands!");
2738     // The immediate encodes the type of constant as well as the value.
2739     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2740     unsigned Value = CE->getValue();
2741     assert((Inst.getOpcode() == ARM::VMOVv8i8 ||
2742             Inst.getOpcode() == ARM::VMOVv16i8) &&
2743            "All vmvn instructions that wants to replicate non-zero byte "
2744            "always must be replaced with VMOVv8i8 or VMOVv16i8.");
2745     unsigned B = ((~Value) & 0xff);
2746     B |= 0xe00; // cmode = 0b1110
2747     Inst.addOperand(MCOperand::createImm(B));
2748   }
2749 
2750   void addNEONi32vmovOperands(MCInst &Inst, unsigned N) const {
2751     assert(N == 1 && "Invalid number of operands!");
2752     // The immediate encodes the type of constant as well as the value.
2753     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2754     unsigned Value = CE->getValue();
2755     if (Value >= 256 && Value <= 0xffff)
2756       Value = (Value >> 8) | ((Value & 0xff) ? 0xc00 : 0x200);
2757     else if (Value > 0xffff && Value <= 0xffffff)
2758       Value = (Value >> 16) | ((Value & 0xff) ? 0xd00 : 0x400);
2759     else if (Value > 0xffffff)
2760       Value = (Value >> 24) | 0x600;
2761     Inst.addOperand(MCOperand::createImm(Value));
2762   }
2763 
2764   void addNEONvmovByteReplicateOperands(MCInst &Inst, unsigned N) const {
2765     assert(N == 1 && "Invalid number of operands!");
2766     // The immediate encodes the type of constant as well as the value.
2767     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2768     unsigned Value = CE->getValue();
2769     assert((Inst.getOpcode() == ARM::VMOVv8i8 ||
2770             Inst.getOpcode() == ARM::VMOVv16i8) &&
2771            "All instructions that wants to replicate non-zero byte "
2772            "always must be replaced with VMOVv8i8 or VMOVv16i8.");
2773     unsigned B = Value & 0xff;
2774     B |= 0xe00; // cmode = 0b1110
2775     Inst.addOperand(MCOperand::createImm(B));
2776   }
2777 
2778   void addNEONi32vmovNegOperands(MCInst &Inst, unsigned N) const {
2779     assert(N == 1 && "Invalid number of operands!");
2780     // The immediate encodes the type of constant as well as the value.
2781     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2782     unsigned Value = ~CE->getValue();
2783     if (Value >= 256 && Value <= 0xffff)
2784       Value = (Value >> 8) | ((Value & 0xff) ? 0xc00 : 0x200);
2785     else if (Value > 0xffff && Value <= 0xffffff)
2786       Value = (Value >> 16) | ((Value & 0xff) ? 0xd00 : 0x400);
2787     else if (Value > 0xffffff)
2788       Value = (Value >> 24) | 0x600;
2789     Inst.addOperand(MCOperand::createImm(Value));
2790   }
2791 
2792   void addNEONi64splatOperands(MCInst &Inst, unsigned N) const {
2793     assert(N == 1 && "Invalid number of operands!");
2794     // The immediate encodes the type of constant as well as the value.
2795     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2796     uint64_t Value = CE->getValue();
2797     unsigned Imm = 0;
2798     for (unsigned i = 0; i < 8; ++i, Value >>= 8) {
2799       Imm |= (Value & 1) << i;
2800     }
2801     Inst.addOperand(MCOperand::createImm(Imm | 0x1e00));
2802   }
2803 
2804   void addComplexRotationEvenOperands(MCInst &Inst, unsigned N) const {
2805     assert(N == 1 && "Invalid number of operands!");
2806     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2807     Inst.addOperand(MCOperand::createImm(CE->getValue() / 90));
2808   }
2809 
2810   void addComplexRotationOddOperands(MCInst &Inst, unsigned N) const {
2811     assert(N == 1 && "Invalid number of operands!");
2812     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2813     Inst.addOperand(MCOperand::createImm((CE->getValue() - 90) / 180));
2814   }
2815 
2816   void print(raw_ostream &OS) const override;
2817 
2818   static std::unique_ptr<ARMOperand> CreateITMask(unsigned Mask, SMLoc S) {
2819     auto Op = make_unique<ARMOperand>(k_ITCondMask);
2820     Op->ITMask.Mask = Mask;
2821     Op->StartLoc = S;
2822     Op->EndLoc = S;
2823     return Op;
2824   }
2825 
2826   static std::unique_ptr<ARMOperand> CreateCondCode(ARMCC::CondCodes CC,
2827                                                     SMLoc S) {
2828     auto Op = make_unique<ARMOperand>(k_CondCode);
2829     Op->CC.Val = CC;
2830     Op->StartLoc = S;
2831     Op->EndLoc = S;
2832     return Op;
2833   }
2834 
2835   static std::unique_ptr<ARMOperand> CreateCoprocNum(unsigned CopVal, SMLoc S) {
2836     auto Op = make_unique<ARMOperand>(k_CoprocNum);
2837     Op->Cop.Val = CopVal;
2838     Op->StartLoc = S;
2839     Op->EndLoc = S;
2840     return Op;
2841   }
2842 
2843   static std::unique_ptr<ARMOperand> CreateCoprocReg(unsigned CopVal, SMLoc S) {
2844     auto Op = make_unique<ARMOperand>(k_CoprocReg);
2845     Op->Cop.Val = CopVal;
2846     Op->StartLoc = S;
2847     Op->EndLoc = S;
2848     return Op;
2849   }
2850 
2851   static std::unique_ptr<ARMOperand> CreateCoprocOption(unsigned Val, SMLoc S,
2852                                                         SMLoc E) {
2853     auto Op = make_unique<ARMOperand>(k_CoprocOption);
2854     Op->Cop.Val = Val;
2855     Op->StartLoc = S;
2856     Op->EndLoc = E;
2857     return Op;
2858   }
2859 
2860   static std::unique_ptr<ARMOperand> CreateCCOut(unsigned RegNum, SMLoc S) {
2861     auto Op = make_unique<ARMOperand>(k_CCOut);
2862     Op->Reg.RegNum = RegNum;
2863     Op->StartLoc = S;
2864     Op->EndLoc = S;
2865     return Op;
2866   }
2867 
2868   static std::unique_ptr<ARMOperand> CreateToken(StringRef Str, SMLoc S) {
2869     auto Op = make_unique<ARMOperand>(k_Token);
2870     Op->Tok.Data = Str.data();
2871     Op->Tok.Length = Str.size();
2872     Op->StartLoc = S;
2873     Op->EndLoc = S;
2874     return Op;
2875   }
2876 
2877   static std::unique_ptr<ARMOperand> CreateReg(unsigned RegNum, SMLoc S,
2878                                                SMLoc E) {
2879     auto Op = make_unique<ARMOperand>(k_Register);
2880     Op->Reg.RegNum = RegNum;
2881     Op->StartLoc = S;
2882     Op->EndLoc = E;
2883     return Op;
2884   }
2885 
2886   static std::unique_ptr<ARMOperand>
2887   CreateShiftedRegister(ARM_AM::ShiftOpc ShTy, unsigned SrcReg,
2888                         unsigned ShiftReg, unsigned ShiftImm, SMLoc S,
2889                         SMLoc E) {
2890     auto Op = make_unique<ARMOperand>(k_ShiftedRegister);
2891     Op->RegShiftedReg.ShiftTy = ShTy;
2892     Op->RegShiftedReg.SrcReg = SrcReg;
2893     Op->RegShiftedReg.ShiftReg = ShiftReg;
2894     Op->RegShiftedReg.ShiftImm = ShiftImm;
2895     Op->StartLoc = S;
2896     Op->EndLoc = E;
2897     return Op;
2898   }
2899 
2900   static std::unique_ptr<ARMOperand>
2901   CreateShiftedImmediate(ARM_AM::ShiftOpc ShTy, unsigned SrcReg,
2902                          unsigned ShiftImm, SMLoc S, SMLoc E) {
2903     auto Op = make_unique<ARMOperand>(k_ShiftedImmediate);
2904     Op->RegShiftedImm.ShiftTy = ShTy;
2905     Op->RegShiftedImm.SrcReg = SrcReg;
2906     Op->RegShiftedImm.ShiftImm = ShiftImm;
2907     Op->StartLoc = S;
2908     Op->EndLoc = E;
2909     return Op;
2910   }
2911 
2912   static std::unique_ptr<ARMOperand> CreateShifterImm(bool isASR, unsigned Imm,
2913                                                       SMLoc S, SMLoc E) {
2914     auto Op = make_unique<ARMOperand>(k_ShifterImmediate);
2915     Op->ShifterImm.isASR = isASR;
2916     Op->ShifterImm.Imm = Imm;
2917     Op->StartLoc = S;
2918     Op->EndLoc = E;
2919     return Op;
2920   }
2921 
2922   static std::unique_ptr<ARMOperand> CreateRotImm(unsigned Imm, SMLoc S,
2923                                                   SMLoc E) {
2924     auto Op = make_unique<ARMOperand>(k_RotateImmediate);
2925     Op->RotImm.Imm = Imm;
2926     Op->StartLoc = S;
2927     Op->EndLoc = E;
2928     return Op;
2929   }
2930 
2931   static std::unique_ptr<ARMOperand> CreateModImm(unsigned Bits, unsigned Rot,
2932                                                   SMLoc S, SMLoc E) {
2933     auto Op = make_unique<ARMOperand>(k_ModifiedImmediate);
2934     Op->ModImm.Bits = Bits;
2935     Op->ModImm.Rot = Rot;
2936     Op->StartLoc = S;
2937     Op->EndLoc = E;
2938     return Op;
2939   }
2940 
2941   static std::unique_ptr<ARMOperand>
2942   CreateConstantPoolImm(const MCExpr *Val, SMLoc S, SMLoc E) {
2943     auto Op = make_unique<ARMOperand>(k_ConstantPoolImmediate);
2944     Op->Imm.Val = Val;
2945     Op->StartLoc = S;
2946     Op->EndLoc = E;
2947     return Op;
2948   }
2949 
2950   static std::unique_ptr<ARMOperand>
2951   CreateBitfield(unsigned LSB, unsigned Width, SMLoc S, SMLoc E) {
2952     auto Op = make_unique<ARMOperand>(k_BitfieldDescriptor);
2953     Op->Bitfield.LSB = LSB;
2954     Op->Bitfield.Width = Width;
2955     Op->StartLoc = S;
2956     Op->EndLoc = E;
2957     return Op;
2958   }
2959 
2960   static std::unique_ptr<ARMOperand>
2961   CreateRegList(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs,
2962                 SMLoc StartLoc, SMLoc EndLoc) {
2963     assert(Regs.size() > 0 && "RegList contains no registers?");
2964     KindTy Kind = k_RegisterList;
2965 
2966     if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Regs.front().second))
2967       Kind = k_DPRRegisterList;
2968     else if (ARMMCRegisterClasses[ARM::SPRRegClassID].
2969              contains(Regs.front().second))
2970       Kind = k_SPRRegisterList;
2971 
2972     // Sort based on the register encoding values.
2973     array_pod_sort(Regs.begin(), Regs.end());
2974 
2975     auto Op = make_unique<ARMOperand>(Kind);
2976     for (SmallVectorImpl<std::pair<unsigned, unsigned>>::const_iterator
2977            I = Regs.begin(), E = Regs.end(); I != E; ++I)
2978       Op->Registers.push_back(I->second);
2979     Op->StartLoc = StartLoc;
2980     Op->EndLoc = EndLoc;
2981     return Op;
2982   }
2983 
2984   static std::unique_ptr<ARMOperand> CreateVectorList(unsigned RegNum,
2985                                                       unsigned Count,
2986                                                       bool isDoubleSpaced,
2987                                                       SMLoc S, SMLoc E) {
2988     auto Op = make_unique<ARMOperand>(k_VectorList);
2989     Op->VectorList.RegNum = RegNum;
2990     Op->VectorList.Count = Count;
2991     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
2992     Op->StartLoc = S;
2993     Op->EndLoc = E;
2994     return Op;
2995   }
2996 
2997   static std::unique_ptr<ARMOperand>
2998   CreateVectorListAllLanes(unsigned RegNum, unsigned Count, bool isDoubleSpaced,
2999                            SMLoc S, SMLoc E) {
3000     auto Op = make_unique<ARMOperand>(k_VectorListAllLanes);
3001     Op->VectorList.RegNum = RegNum;
3002     Op->VectorList.Count = Count;
3003     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
3004     Op->StartLoc = S;
3005     Op->EndLoc = E;
3006     return Op;
3007   }
3008 
3009   static std::unique_ptr<ARMOperand>
3010   CreateVectorListIndexed(unsigned RegNum, unsigned Count, unsigned Index,
3011                           bool isDoubleSpaced, SMLoc S, SMLoc E) {
3012     auto Op = make_unique<ARMOperand>(k_VectorListIndexed);
3013     Op->VectorList.RegNum = RegNum;
3014     Op->VectorList.Count = Count;
3015     Op->VectorList.LaneIndex = Index;
3016     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
3017     Op->StartLoc = S;
3018     Op->EndLoc = E;
3019     return Op;
3020   }
3021 
3022   static std::unique_ptr<ARMOperand>
3023   CreateVectorIndex(unsigned Idx, SMLoc S, SMLoc E, MCContext &Ctx) {
3024     auto Op = make_unique<ARMOperand>(k_VectorIndex);
3025     Op->VectorIndex.Val = Idx;
3026     Op->StartLoc = S;
3027     Op->EndLoc = E;
3028     return Op;
3029   }
3030 
3031   static std::unique_ptr<ARMOperand> CreateImm(const MCExpr *Val, SMLoc S,
3032                                                SMLoc E) {
3033     auto Op = make_unique<ARMOperand>(k_Immediate);
3034     Op->Imm.Val = Val;
3035     Op->StartLoc = S;
3036     Op->EndLoc = E;
3037     return Op;
3038   }
3039 
3040   static std::unique_ptr<ARMOperand>
3041   CreateMem(unsigned BaseRegNum, const MCConstantExpr *OffsetImm,
3042             unsigned OffsetRegNum, ARM_AM::ShiftOpc ShiftType,
3043             unsigned ShiftImm, unsigned Alignment, bool isNegative, SMLoc S,
3044             SMLoc E, SMLoc AlignmentLoc = SMLoc()) {
3045     auto Op = make_unique<ARMOperand>(k_Memory);
3046     Op->Memory.BaseRegNum = BaseRegNum;
3047     Op->Memory.OffsetImm = OffsetImm;
3048     Op->Memory.OffsetRegNum = OffsetRegNum;
3049     Op->Memory.ShiftType = ShiftType;
3050     Op->Memory.ShiftImm = ShiftImm;
3051     Op->Memory.Alignment = Alignment;
3052     Op->Memory.isNegative = isNegative;
3053     Op->StartLoc = S;
3054     Op->EndLoc = E;
3055     Op->AlignmentLoc = AlignmentLoc;
3056     return Op;
3057   }
3058 
3059   static std::unique_ptr<ARMOperand>
3060   CreatePostIdxReg(unsigned RegNum, bool isAdd, ARM_AM::ShiftOpc ShiftTy,
3061                    unsigned ShiftImm, SMLoc S, SMLoc E) {
3062     auto Op = make_unique<ARMOperand>(k_PostIndexRegister);
3063     Op->PostIdxReg.RegNum = RegNum;
3064     Op->PostIdxReg.isAdd = isAdd;
3065     Op->PostIdxReg.ShiftTy = ShiftTy;
3066     Op->PostIdxReg.ShiftImm = ShiftImm;
3067     Op->StartLoc = S;
3068     Op->EndLoc = E;
3069     return Op;
3070   }
3071 
3072   static std::unique_ptr<ARMOperand> CreateMemBarrierOpt(ARM_MB::MemBOpt Opt,
3073                                                          SMLoc S) {
3074     auto Op = make_unique<ARMOperand>(k_MemBarrierOpt);
3075     Op->MBOpt.Val = Opt;
3076     Op->StartLoc = S;
3077     Op->EndLoc = S;
3078     return Op;
3079   }
3080 
3081   static std::unique_ptr<ARMOperand>
3082   CreateInstSyncBarrierOpt(ARM_ISB::InstSyncBOpt Opt, SMLoc S) {
3083     auto Op = make_unique<ARMOperand>(k_InstSyncBarrierOpt);
3084     Op->ISBOpt.Val = Opt;
3085     Op->StartLoc = S;
3086     Op->EndLoc = S;
3087     return Op;
3088   }
3089 
3090   static std::unique_ptr<ARMOperand> CreateProcIFlags(ARM_PROC::IFlags IFlags,
3091                                                       SMLoc S) {
3092     auto Op = make_unique<ARMOperand>(k_ProcIFlags);
3093     Op->IFlags.Val = IFlags;
3094     Op->StartLoc = S;
3095     Op->EndLoc = S;
3096     return Op;
3097   }
3098 
3099   static std::unique_ptr<ARMOperand> CreateMSRMask(unsigned MMask, SMLoc S) {
3100     auto Op = make_unique<ARMOperand>(k_MSRMask);
3101     Op->MMask.Val = MMask;
3102     Op->StartLoc = S;
3103     Op->EndLoc = S;
3104     return Op;
3105   }
3106 
3107   static std::unique_ptr<ARMOperand> CreateBankedReg(unsigned Reg, SMLoc S) {
3108     auto Op = make_unique<ARMOperand>(k_BankedReg);
3109     Op->BankedReg.Val = Reg;
3110     Op->StartLoc = S;
3111     Op->EndLoc = S;
3112     return Op;
3113   }
3114 };
3115 
3116 } // end anonymous namespace.
3117 
3118 void ARMOperand::print(raw_ostream &OS) const {
3119   switch (Kind) {
3120   case k_CondCode:
3121     OS << "<ARMCC::" << ARMCondCodeToString(getCondCode()) << ">";
3122     break;
3123   case k_CCOut:
3124     OS << "<ccout " << getReg() << ">";
3125     break;
3126   case k_ITCondMask: {
3127     static const char *const MaskStr[] = {
3128       "()", "(t)", "(e)", "(tt)", "(et)", "(te)", "(ee)", "(ttt)", "(ett)",
3129       "(tet)", "(eet)", "(tte)", "(ete)", "(tee)", "(eee)"
3130     };
3131     assert((ITMask.Mask & 0xf) == ITMask.Mask);
3132     OS << "<it-mask " << MaskStr[ITMask.Mask] << ">";
3133     break;
3134   }
3135   case k_CoprocNum:
3136     OS << "<coprocessor number: " << getCoproc() << ">";
3137     break;
3138   case k_CoprocReg:
3139     OS << "<coprocessor register: " << getCoproc() << ">";
3140     break;
3141   case k_CoprocOption:
3142     OS << "<coprocessor option: " << CoprocOption.Val << ">";
3143     break;
3144   case k_MSRMask:
3145     OS << "<mask: " << getMSRMask() << ">";
3146     break;
3147   case k_BankedReg:
3148     OS << "<banked reg: " << getBankedReg() << ">";
3149     break;
3150   case k_Immediate:
3151     OS << *getImm();
3152     break;
3153   case k_MemBarrierOpt:
3154     OS << "<ARM_MB::" << MemBOptToString(getMemBarrierOpt(), false) << ">";
3155     break;
3156   case k_InstSyncBarrierOpt:
3157     OS << "<ARM_ISB::" << InstSyncBOptToString(getInstSyncBarrierOpt()) << ">";
3158     break;
3159   case k_Memory:
3160     OS << "<memory "
3161        << " base:" << Memory.BaseRegNum;
3162     OS << ">";
3163     break;
3164   case k_PostIndexRegister:
3165     OS << "post-idx register " << (PostIdxReg.isAdd ? "" : "-")
3166        << PostIdxReg.RegNum;
3167     if (PostIdxReg.ShiftTy != ARM_AM::no_shift)
3168       OS << ARM_AM::getShiftOpcStr(PostIdxReg.ShiftTy) << " "
3169          << PostIdxReg.ShiftImm;
3170     OS << ">";
3171     break;
3172   case k_ProcIFlags: {
3173     OS << "<ARM_PROC::";
3174     unsigned IFlags = getProcIFlags();
3175     for (int i=2; i >= 0; --i)
3176       if (IFlags & (1 << i))
3177         OS << ARM_PROC::IFlagsToString(1 << i);
3178     OS << ">";
3179     break;
3180   }
3181   case k_Register:
3182     OS << "<register " << getReg() << ">";
3183     break;
3184   case k_ShifterImmediate:
3185     OS << "<shift " << (ShifterImm.isASR ? "asr" : "lsl")
3186        << " #" << ShifterImm.Imm << ">";
3187     break;
3188   case k_ShiftedRegister:
3189     OS << "<so_reg_reg "
3190        << RegShiftedReg.SrcReg << " "
3191        << ARM_AM::getShiftOpcStr(RegShiftedReg.ShiftTy)
3192        << " " << RegShiftedReg.ShiftReg << ">";
3193     break;
3194   case k_ShiftedImmediate:
3195     OS << "<so_reg_imm "
3196        << RegShiftedImm.SrcReg << " "
3197        << ARM_AM::getShiftOpcStr(RegShiftedImm.ShiftTy)
3198        << " #" << RegShiftedImm.ShiftImm << ">";
3199     break;
3200   case k_RotateImmediate:
3201     OS << "<ror " << " #" << (RotImm.Imm * 8) << ">";
3202     break;
3203   case k_ModifiedImmediate:
3204     OS << "<mod_imm #" << ModImm.Bits << ", #"
3205        <<  ModImm.Rot << ")>";
3206     break;
3207   case k_ConstantPoolImmediate:
3208     OS << "<constant_pool_imm #" << *getConstantPoolImm();
3209     break;
3210   case k_BitfieldDescriptor:
3211     OS << "<bitfield " << "lsb: " << Bitfield.LSB
3212        << ", width: " << Bitfield.Width << ">";
3213     break;
3214   case k_RegisterList:
3215   case k_DPRRegisterList:
3216   case k_SPRRegisterList: {
3217     OS << "<register_list ";
3218 
3219     const SmallVectorImpl<unsigned> &RegList = getRegList();
3220     for (SmallVectorImpl<unsigned>::const_iterator
3221            I = RegList.begin(), E = RegList.end(); I != E; ) {
3222       OS << *I;
3223       if (++I < E) OS << ", ";
3224     }
3225 
3226     OS << ">";
3227     break;
3228   }
3229   case k_VectorList:
3230     OS << "<vector_list " << VectorList.Count << " * "
3231        << VectorList.RegNum << ">";
3232     break;
3233   case k_VectorListAllLanes:
3234     OS << "<vector_list(all lanes) " << VectorList.Count << " * "
3235        << VectorList.RegNum << ">";
3236     break;
3237   case k_VectorListIndexed:
3238     OS << "<vector_list(lane " << VectorList.LaneIndex << ") "
3239        << VectorList.Count << " * " << VectorList.RegNum << ">";
3240     break;
3241   case k_Token:
3242     OS << "'" << getToken() << "'";
3243     break;
3244   case k_VectorIndex:
3245     OS << "<vectorindex " << getVectorIndex() << ">";
3246     break;
3247   }
3248 }
3249 
3250 /// @name Auto-generated Match Functions
3251 /// {
3252 
3253 static unsigned MatchRegisterName(StringRef Name);
3254 
3255 /// }
3256 
3257 bool ARMAsmParser::ParseRegister(unsigned &RegNo,
3258                                  SMLoc &StartLoc, SMLoc &EndLoc) {
3259   const AsmToken &Tok = getParser().getTok();
3260   StartLoc = Tok.getLoc();
3261   EndLoc = Tok.getEndLoc();
3262   RegNo = tryParseRegister();
3263 
3264   return (RegNo == (unsigned)-1);
3265 }
3266 
3267 /// Try to parse a register name.  The token must be an Identifier when called,
3268 /// and if it is a register name the token is eaten and the register number is
3269 /// returned.  Otherwise return -1.
3270 int ARMAsmParser::tryParseRegister() {
3271   MCAsmParser &Parser = getParser();
3272   const AsmToken &Tok = Parser.getTok();
3273   if (Tok.isNot(AsmToken::Identifier)) return -1;
3274 
3275   std::string lowerCase = Tok.getString().lower();
3276   unsigned RegNum = MatchRegisterName(lowerCase);
3277   if (!RegNum) {
3278     RegNum = StringSwitch<unsigned>(lowerCase)
3279       .Case("r13", ARM::SP)
3280       .Case("r14", ARM::LR)
3281       .Case("r15", ARM::PC)
3282       .Case("ip", ARM::R12)
3283       // Additional register name aliases for 'gas' compatibility.
3284       .Case("a1", ARM::R0)
3285       .Case("a2", ARM::R1)
3286       .Case("a3", ARM::R2)
3287       .Case("a4", ARM::R3)
3288       .Case("v1", ARM::R4)
3289       .Case("v2", ARM::R5)
3290       .Case("v3", ARM::R6)
3291       .Case("v4", ARM::R7)
3292       .Case("v5", ARM::R8)
3293       .Case("v6", ARM::R9)
3294       .Case("v7", ARM::R10)
3295       .Case("v8", ARM::R11)
3296       .Case("sb", ARM::R9)
3297       .Case("sl", ARM::R10)
3298       .Case("fp", ARM::R11)
3299       .Default(0);
3300   }
3301   if (!RegNum) {
3302     // Check for aliases registered via .req. Canonicalize to lower case.
3303     // That's more consistent since register names are case insensitive, and
3304     // it's how the original entry was passed in from MC/MCParser/AsmParser.
3305     StringMap<unsigned>::const_iterator Entry = RegisterReqs.find(lowerCase);
3306     // If no match, return failure.
3307     if (Entry == RegisterReqs.end())
3308       return -1;
3309     Parser.Lex(); // Eat identifier token.
3310     return Entry->getValue();
3311   }
3312 
3313   // Some FPUs only have 16 D registers, so D16-D31 are invalid
3314   if (hasD16() && RegNum >= ARM::D16 && RegNum <= ARM::D31)
3315     return -1;
3316 
3317   Parser.Lex(); // Eat identifier token.
3318 
3319   return RegNum;
3320 }
3321 
3322 // Try to parse a shifter  (e.g., "lsl <amt>"). On success, return 0.
3323 // If a recoverable error occurs, return 1. If an irrecoverable error
3324 // occurs, return -1. An irrecoverable error is one where tokens have been
3325 // consumed in the process of trying to parse the shifter (i.e., when it is
3326 // indeed a shifter operand, but malformed).
3327 int ARMAsmParser::tryParseShiftRegister(OperandVector &Operands) {
3328   MCAsmParser &Parser = getParser();
3329   SMLoc S = Parser.getTok().getLoc();
3330   const AsmToken &Tok = Parser.getTok();
3331   if (Tok.isNot(AsmToken::Identifier))
3332     return -1;
3333 
3334   std::string lowerCase = Tok.getString().lower();
3335   ARM_AM::ShiftOpc ShiftTy = StringSwitch<ARM_AM::ShiftOpc>(lowerCase)
3336       .Case("asl", ARM_AM::lsl)
3337       .Case("lsl", ARM_AM::lsl)
3338       .Case("lsr", ARM_AM::lsr)
3339       .Case("asr", ARM_AM::asr)
3340       .Case("ror", ARM_AM::ror)
3341       .Case("rrx", ARM_AM::rrx)
3342       .Default(ARM_AM::no_shift);
3343 
3344   if (ShiftTy == ARM_AM::no_shift)
3345     return 1;
3346 
3347   Parser.Lex(); // Eat the operator.
3348 
3349   // The source register for the shift has already been added to the
3350   // operand list, so we need to pop it off and combine it into the shifted
3351   // register operand instead.
3352   std::unique_ptr<ARMOperand> PrevOp(
3353       (ARMOperand *)Operands.pop_back_val().release());
3354   if (!PrevOp->isReg())
3355     return Error(PrevOp->getStartLoc(), "shift must be of a register");
3356   int SrcReg = PrevOp->getReg();
3357 
3358   SMLoc EndLoc;
3359   int64_t Imm = 0;
3360   int ShiftReg = 0;
3361   if (ShiftTy == ARM_AM::rrx) {
3362     // RRX Doesn't have an explicit shift amount. The encoder expects
3363     // the shift register to be the same as the source register. Seems odd,
3364     // but OK.
3365     ShiftReg = SrcReg;
3366   } else {
3367     // Figure out if this is shifted by a constant or a register (for non-RRX).
3368     if (Parser.getTok().is(AsmToken::Hash) ||
3369         Parser.getTok().is(AsmToken::Dollar)) {
3370       Parser.Lex(); // Eat hash.
3371       SMLoc ImmLoc = Parser.getTok().getLoc();
3372       const MCExpr *ShiftExpr = nullptr;
3373       if (getParser().parseExpression(ShiftExpr, EndLoc)) {
3374         Error(ImmLoc, "invalid immediate shift value");
3375         return -1;
3376       }
3377       // The expression must be evaluatable as an immediate.
3378       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftExpr);
3379       if (!CE) {
3380         Error(ImmLoc, "invalid immediate shift value");
3381         return -1;
3382       }
3383       // Range check the immediate.
3384       // lsl, ror: 0 <= imm <= 31
3385       // lsr, asr: 0 <= imm <= 32
3386       Imm = CE->getValue();
3387       if (Imm < 0 ||
3388           ((ShiftTy == ARM_AM::lsl || ShiftTy == ARM_AM::ror) && Imm > 31) ||
3389           ((ShiftTy == ARM_AM::lsr || ShiftTy == ARM_AM::asr) && Imm > 32)) {
3390         Error(ImmLoc, "immediate shift value out of range");
3391         return -1;
3392       }
3393       // shift by zero is a nop. Always send it through as lsl.
3394       // ('as' compatibility)
3395       if (Imm == 0)
3396         ShiftTy = ARM_AM::lsl;
3397     } else if (Parser.getTok().is(AsmToken::Identifier)) {
3398       SMLoc L = Parser.getTok().getLoc();
3399       EndLoc = Parser.getTok().getEndLoc();
3400       ShiftReg = tryParseRegister();
3401       if (ShiftReg == -1) {
3402         Error(L, "expected immediate or register in shift operand");
3403         return -1;
3404       }
3405     } else {
3406       Error(Parser.getTok().getLoc(),
3407             "expected immediate or register in shift operand");
3408       return -1;
3409     }
3410   }
3411 
3412   if (ShiftReg && ShiftTy != ARM_AM::rrx)
3413     Operands.push_back(ARMOperand::CreateShiftedRegister(ShiftTy, SrcReg,
3414                                                          ShiftReg, Imm,
3415                                                          S, EndLoc));
3416   else
3417     Operands.push_back(ARMOperand::CreateShiftedImmediate(ShiftTy, SrcReg, Imm,
3418                                                           S, EndLoc));
3419 
3420   return 0;
3421 }
3422 
3423 /// Try to parse a register name.  The token must be an Identifier when called.
3424 /// If it's a register, an AsmOperand is created. Another AsmOperand is created
3425 /// if there is a "writeback". 'true' if it's not a register.
3426 ///
3427 /// TODO this is likely to change to allow different register types and or to
3428 /// parse for a specific register type.
3429 bool ARMAsmParser::tryParseRegisterWithWriteBack(OperandVector &Operands) {
3430   MCAsmParser &Parser = getParser();
3431   SMLoc RegStartLoc = Parser.getTok().getLoc();
3432   SMLoc RegEndLoc = Parser.getTok().getEndLoc();
3433   int RegNo = tryParseRegister();
3434   if (RegNo == -1)
3435     return true;
3436 
3437   Operands.push_back(ARMOperand::CreateReg(RegNo, RegStartLoc, RegEndLoc));
3438 
3439   const AsmToken &ExclaimTok = Parser.getTok();
3440   if (ExclaimTok.is(AsmToken::Exclaim)) {
3441     Operands.push_back(ARMOperand::CreateToken(ExclaimTok.getString(),
3442                                                ExclaimTok.getLoc()));
3443     Parser.Lex(); // Eat exclaim token
3444     return false;
3445   }
3446 
3447   // Also check for an index operand. This is only legal for vector registers,
3448   // but that'll get caught OK in operand matching, so we don't need to
3449   // explicitly filter everything else out here.
3450   if (Parser.getTok().is(AsmToken::LBrac)) {
3451     SMLoc SIdx = Parser.getTok().getLoc();
3452     Parser.Lex(); // Eat left bracket token.
3453 
3454     const MCExpr *ImmVal;
3455     if (getParser().parseExpression(ImmVal))
3456       return true;
3457     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(ImmVal);
3458     if (!MCE)
3459       return TokError("immediate value expected for vector index");
3460 
3461     if (Parser.getTok().isNot(AsmToken::RBrac))
3462       return Error(Parser.getTok().getLoc(), "']' expected");
3463 
3464     SMLoc E = Parser.getTok().getEndLoc();
3465     Parser.Lex(); // Eat right bracket token.
3466 
3467     Operands.push_back(ARMOperand::CreateVectorIndex(MCE->getValue(),
3468                                                      SIdx, E,
3469                                                      getContext()));
3470   }
3471 
3472   return false;
3473 }
3474 
3475 /// MatchCoprocessorOperandName - Try to parse an coprocessor related
3476 /// instruction with a symbolic operand name.
3477 /// We accept "crN" syntax for GAS compatibility.
3478 /// <operand-name> ::= <prefix><number>
3479 /// If CoprocOp is 'c', then:
3480 ///   <prefix> ::= c | cr
3481 /// If CoprocOp is 'p', then :
3482 ///   <prefix> ::= p
3483 /// <number> ::= integer in range [0, 15]
3484 static int MatchCoprocessorOperandName(StringRef Name, char CoprocOp) {
3485   // Use the same layout as the tablegen'erated register name matcher. Ugly,
3486   // but efficient.
3487   if (Name.size() < 2 || Name[0] != CoprocOp)
3488     return -1;
3489   Name = (Name[1] == 'r') ? Name.drop_front(2) : Name.drop_front();
3490 
3491   switch (Name.size()) {
3492   default: return -1;
3493   case 1:
3494     switch (Name[0]) {
3495     default:  return -1;
3496     case '0': return 0;
3497     case '1': return 1;
3498     case '2': return 2;
3499     case '3': return 3;
3500     case '4': return 4;
3501     case '5': return 5;
3502     case '6': return 6;
3503     case '7': return 7;
3504     case '8': return 8;
3505     case '9': return 9;
3506     }
3507   case 2:
3508     if (Name[0] != '1')
3509       return -1;
3510     switch (Name[1]) {
3511     default:  return -1;
3512     // CP10 and CP11 are VFP/NEON and so vector instructions should be used.
3513     // However, old cores (v5/v6) did use them in that way.
3514     case '0': return 10;
3515     case '1': return 11;
3516     case '2': return 12;
3517     case '3': return 13;
3518     case '4': return 14;
3519     case '5': return 15;
3520     }
3521   }
3522 }
3523 
3524 /// parseITCondCode - Try to parse a condition code for an IT instruction.
3525 OperandMatchResultTy
3526 ARMAsmParser::parseITCondCode(OperandVector &Operands) {
3527   MCAsmParser &Parser = getParser();
3528   SMLoc S = Parser.getTok().getLoc();
3529   const AsmToken &Tok = Parser.getTok();
3530   if (!Tok.is(AsmToken::Identifier))
3531     return MatchOperand_NoMatch;
3532   unsigned CC = ARMCondCodeFromString(Tok.getString());
3533   if (CC == ~0U)
3534     return MatchOperand_NoMatch;
3535   Parser.Lex(); // Eat the token.
3536 
3537   Operands.push_back(ARMOperand::CreateCondCode(ARMCC::CondCodes(CC), S));
3538 
3539   return MatchOperand_Success;
3540 }
3541 
3542 /// parseCoprocNumOperand - Try to parse an coprocessor number operand. The
3543 /// token must be an Identifier when called, and if it is a coprocessor
3544 /// number, the token is eaten and the operand is added to the operand list.
3545 OperandMatchResultTy
3546 ARMAsmParser::parseCoprocNumOperand(OperandVector &Operands) {
3547   MCAsmParser &Parser = getParser();
3548   SMLoc S = Parser.getTok().getLoc();
3549   const AsmToken &Tok = Parser.getTok();
3550   if (Tok.isNot(AsmToken::Identifier))
3551     return MatchOperand_NoMatch;
3552 
3553   int Num = MatchCoprocessorOperandName(Tok.getString(), 'p');
3554   if (Num == -1)
3555     return MatchOperand_NoMatch;
3556   // ARMv7 and v8 don't allow cp10/cp11 due to VFP/NEON specific instructions
3557   if ((hasV7Ops() || hasV8Ops()) && (Num == 10 || Num == 11))
3558     return MatchOperand_NoMatch;
3559 
3560   Parser.Lex(); // Eat identifier token.
3561   Operands.push_back(ARMOperand::CreateCoprocNum(Num, S));
3562   return MatchOperand_Success;
3563 }
3564 
3565 /// parseCoprocRegOperand - Try to parse an coprocessor register operand. The
3566 /// token must be an Identifier when called, and if it is a coprocessor
3567 /// number, the token is eaten and the operand is added to the operand list.
3568 OperandMatchResultTy
3569 ARMAsmParser::parseCoprocRegOperand(OperandVector &Operands) {
3570   MCAsmParser &Parser = getParser();
3571   SMLoc S = Parser.getTok().getLoc();
3572   const AsmToken &Tok = Parser.getTok();
3573   if (Tok.isNot(AsmToken::Identifier))
3574     return MatchOperand_NoMatch;
3575 
3576   int Reg = MatchCoprocessorOperandName(Tok.getString(), 'c');
3577   if (Reg == -1)
3578     return MatchOperand_NoMatch;
3579 
3580   Parser.Lex(); // Eat identifier token.
3581   Operands.push_back(ARMOperand::CreateCoprocReg(Reg, S));
3582   return MatchOperand_Success;
3583 }
3584 
3585 /// parseCoprocOptionOperand - Try to parse an coprocessor option operand.
3586 /// coproc_option : '{' imm0_255 '}'
3587 OperandMatchResultTy
3588 ARMAsmParser::parseCoprocOptionOperand(OperandVector &Operands) {
3589   MCAsmParser &Parser = getParser();
3590   SMLoc S = Parser.getTok().getLoc();
3591 
3592   // If this isn't a '{', this isn't a coprocessor immediate operand.
3593   if (Parser.getTok().isNot(AsmToken::LCurly))
3594     return MatchOperand_NoMatch;
3595   Parser.Lex(); // Eat the '{'
3596 
3597   const MCExpr *Expr;
3598   SMLoc Loc = Parser.getTok().getLoc();
3599   if (getParser().parseExpression(Expr)) {
3600     Error(Loc, "illegal expression");
3601     return MatchOperand_ParseFail;
3602   }
3603   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
3604   if (!CE || CE->getValue() < 0 || CE->getValue() > 255) {
3605     Error(Loc, "coprocessor option must be an immediate in range [0, 255]");
3606     return MatchOperand_ParseFail;
3607   }
3608   int Val = CE->getValue();
3609 
3610   // Check for and consume the closing '}'
3611   if (Parser.getTok().isNot(AsmToken::RCurly))
3612     return MatchOperand_ParseFail;
3613   SMLoc E = Parser.getTok().getEndLoc();
3614   Parser.Lex(); // Eat the '}'
3615 
3616   Operands.push_back(ARMOperand::CreateCoprocOption(Val, S, E));
3617   return MatchOperand_Success;
3618 }
3619 
3620 // For register list parsing, we need to map from raw GPR register numbering
3621 // to the enumeration values. The enumeration values aren't sorted by
3622 // register number due to our using "sp", "lr" and "pc" as canonical names.
3623 static unsigned getNextRegister(unsigned Reg) {
3624   // If this is a GPR, we need to do it manually, otherwise we can rely
3625   // on the sort ordering of the enumeration since the other reg-classes
3626   // are sane.
3627   if (!ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
3628     return Reg + 1;
3629   switch(Reg) {
3630   default: llvm_unreachable("Invalid GPR number!");
3631   case ARM::R0:  return ARM::R1;  case ARM::R1:  return ARM::R2;
3632   case ARM::R2:  return ARM::R3;  case ARM::R3:  return ARM::R4;
3633   case ARM::R4:  return ARM::R5;  case ARM::R5:  return ARM::R6;
3634   case ARM::R6:  return ARM::R7;  case ARM::R7:  return ARM::R8;
3635   case ARM::R8:  return ARM::R9;  case ARM::R9:  return ARM::R10;
3636   case ARM::R10: return ARM::R11; case ARM::R11: return ARM::R12;
3637   case ARM::R12: return ARM::SP;  case ARM::SP:  return ARM::LR;
3638   case ARM::LR:  return ARM::PC;  case ARM::PC:  return ARM::R0;
3639   }
3640 }
3641 
3642 /// Parse a register list.
3643 bool ARMAsmParser::parseRegisterList(OperandVector &Operands) {
3644   MCAsmParser &Parser = getParser();
3645   if (Parser.getTok().isNot(AsmToken::LCurly))
3646     return TokError("Token is not a Left Curly Brace");
3647   SMLoc S = Parser.getTok().getLoc();
3648   Parser.Lex(); // Eat '{' token.
3649   SMLoc RegLoc = Parser.getTok().getLoc();
3650 
3651   // Check the first register in the list to see what register class
3652   // this is a list of.
3653   int Reg = tryParseRegister();
3654   if (Reg == -1)
3655     return Error(RegLoc, "register expected");
3656 
3657   // The reglist instructions have at most 16 registers, so reserve
3658   // space for that many.
3659   int EReg = 0;
3660   SmallVector<std::pair<unsigned, unsigned>, 16> Registers;
3661 
3662   // Allow Q regs and just interpret them as the two D sub-registers.
3663   if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3664     Reg = getDRegFromQReg(Reg);
3665     EReg = MRI->getEncodingValue(Reg);
3666     Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3667     ++Reg;
3668   }
3669   const MCRegisterClass *RC;
3670   if (ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
3671     RC = &ARMMCRegisterClasses[ARM::GPRRegClassID];
3672   else if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Reg))
3673     RC = &ARMMCRegisterClasses[ARM::DPRRegClassID];
3674   else if (ARMMCRegisterClasses[ARM::SPRRegClassID].contains(Reg))
3675     RC = &ARMMCRegisterClasses[ARM::SPRRegClassID];
3676   else
3677     return Error(RegLoc, "invalid register in register list");
3678 
3679   // Store the register.
3680   EReg = MRI->getEncodingValue(Reg);
3681   Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3682 
3683   // This starts immediately after the first register token in the list,
3684   // so we can see either a comma or a minus (range separator) as a legal
3685   // next token.
3686   while (Parser.getTok().is(AsmToken::Comma) ||
3687          Parser.getTok().is(AsmToken::Minus)) {
3688     if (Parser.getTok().is(AsmToken::Minus)) {
3689       Parser.Lex(); // Eat the minus.
3690       SMLoc AfterMinusLoc = Parser.getTok().getLoc();
3691       int EndReg = tryParseRegister();
3692       if (EndReg == -1)
3693         return Error(AfterMinusLoc, "register expected");
3694       // Allow Q regs and just interpret them as the two D sub-registers.
3695       if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(EndReg))
3696         EndReg = getDRegFromQReg(EndReg) + 1;
3697       // If the register is the same as the start reg, there's nothing
3698       // more to do.
3699       if (Reg == EndReg)
3700         continue;
3701       // The register must be in the same register class as the first.
3702       if (!RC->contains(EndReg))
3703         return Error(AfterMinusLoc, "invalid register in register list");
3704       // Ranges must go from low to high.
3705       if (MRI->getEncodingValue(Reg) > MRI->getEncodingValue(EndReg))
3706         return Error(AfterMinusLoc, "bad range in register list");
3707 
3708       // Add all the registers in the range to the register list.
3709       while (Reg != EndReg) {
3710         Reg = getNextRegister(Reg);
3711         EReg = MRI->getEncodingValue(Reg);
3712         Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3713       }
3714       continue;
3715     }
3716     Parser.Lex(); // Eat the comma.
3717     RegLoc = Parser.getTok().getLoc();
3718     int OldReg = Reg;
3719     const AsmToken RegTok = Parser.getTok();
3720     Reg = tryParseRegister();
3721     if (Reg == -1)
3722       return Error(RegLoc, "register expected");
3723     // Allow Q regs and just interpret them as the two D sub-registers.
3724     bool isQReg = false;
3725     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3726       Reg = getDRegFromQReg(Reg);
3727       isQReg = true;
3728     }
3729     // The register must be in the same register class as the first.
3730     if (!RC->contains(Reg))
3731       return Error(RegLoc, "invalid register in register list");
3732     // List must be monotonically increasing.
3733     if (MRI->getEncodingValue(Reg) < MRI->getEncodingValue(OldReg)) {
3734       if (ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
3735         Warning(RegLoc, "register list not in ascending order");
3736       else
3737         return Error(RegLoc, "register list not in ascending order");
3738     }
3739     if (MRI->getEncodingValue(Reg) == MRI->getEncodingValue(OldReg)) {
3740       Warning(RegLoc, "duplicated register (" + RegTok.getString() +
3741               ") in register list");
3742       continue;
3743     }
3744     // VFP register lists must also be contiguous.
3745     if (RC != &ARMMCRegisterClasses[ARM::GPRRegClassID] &&
3746         Reg != OldReg + 1)
3747       return Error(RegLoc, "non-contiguous register range");
3748     EReg = MRI->getEncodingValue(Reg);
3749     Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3750     if (isQReg) {
3751       EReg = MRI->getEncodingValue(++Reg);
3752       Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3753     }
3754   }
3755 
3756   if (Parser.getTok().isNot(AsmToken::RCurly))
3757     return Error(Parser.getTok().getLoc(), "'}' expected");
3758   SMLoc E = Parser.getTok().getEndLoc();
3759   Parser.Lex(); // Eat '}' token.
3760 
3761   // Push the register list operand.
3762   Operands.push_back(ARMOperand::CreateRegList(Registers, S, E));
3763 
3764   // The ARM system instruction variants for LDM/STM have a '^' token here.
3765   if (Parser.getTok().is(AsmToken::Caret)) {
3766     Operands.push_back(ARMOperand::CreateToken("^",Parser.getTok().getLoc()));
3767     Parser.Lex(); // Eat '^' token.
3768   }
3769 
3770   return false;
3771 }
3772 
3773 // Helper function to parse the lane index for vector lists.
3774 OperandMatchResultTy ARMAsmParser::
3775 parseVectorLane(VectorLaneTy &LaneKind, unsigned &Index, SMLoc &EndLoc) {
3776   MCAsmParser &Parser = getParser();
3777   Index = 0; // Always return a defined index value.
3778   if (Parser.getTok().is(AsmToken::LBrac)) {
3779     Parser.Lex(); // Eat the '['.
3780     if (Parser.getTok().is(AsmToken::RBrac)) {
3781       // "Dn[]" is the 'all lanes' syntax.
3782       LaneKind = AllLanes;
3783       EndLoc = Parser.getTok().getEndLoc();
3784       Parser.Lex(); // Eat the ']'.
3785       return MatchOperand_Success;
3786     }
3787 
3788     // There's an optional '#' token here. Normally there wouldn't be, but
3789     // inline assemble puts one in, and it's friendly to accept that.
3790     if (Parser.getTok().is(AsmToken::Hash))
3791       Parser.Lex(); // Eat '#' or '$'.
3792 
3793     const MCExpr *LaneIndex;
3794     SMLoc Loc = Parser.getTok().getLoc();
3795     if (getParser().parseExpression(LaneIndex)) {
3796       Error(Loc, "illegal expression");
3797       return MatchOperand_ParseFail;
3798     }
3799     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(LaneIndex);
3800     if (!CE) {
3801       Error(Loc, "lane index must be empty or an integer");
3802       return MatchOperand_ParseFail;
3803     }
3804     if (Parser.getTok().isNot(AsmToken::RBrac)) {
3805       Error(Parser.getTok().getLoc(), "']' expected");
3806       return MatchOperand_ParseFail;
3807     }
3808     EndLoc = Parser.getTok().getEndLoc();
3809     Parser.Lex(); // Eat the ']'.
3810     int64_t Val = CE->getValue();
3811 
3812     // FIXME: Make this range check context sensitive for .8, .16, .32.
3813     if (Val < 0 || Val > 7) {
3814       Error(Parser.getTok().getLoc(), "lane index out of range");
3815       return MatchOperand_ParseFail;
3816     }
3817     Index = Val;
3818     LaneKind = IndexedLane;
3819     return MatchOperand_Success;
3820   }
3821   LaneKind = NoLanes;
3822   return MatchOperand_Success;
3823 }
3824 
3825 // parse a vector register list
3826 OperandMatchResultTy
3827 ARMAsmParser::parseVectorList(OperandVector &Operands) {
3828   MCAsmParser &Parser = getParser();
3829   VectorLaneTy LaneKind;
3830   unsigned LaneIndex;
3831   SMLoc S = Parser.getTok().getLoc();
3832   // As an extension (to match gas), support a plain D register or Q register
3833   // (without encosing curly braces) as a single or double entry list,
3834   // respectively.
3835   if (Parser.getTok().is(AsmToken::Identifier)) {
3836     SMLoc E = Parser.getTok().getEndLoc();
3837     int Reg = tryParseRegister();
3838     if (Reg == -1)
3839       return MatchOperand_NoMatch;
3840     if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Reg)) {
3841       OperandMatchResultTy Res = parseVectorLane(LaneKind, LaneIndex, E);
3842       if (Res != MatchOperand_Success)
3843         return Res;
3844       switch (LaneKind) {
3845       case NoLanes:
3846         Operands.push_back(ARMOperand::CreateVectorList(Reg, 1, false, S, E));
3847         break;
3848       case AllLanes:
3849         Operands.push_back(ARMOperand::CreateVectorListAllLanes(Reg, 1, false,
3850                                                                 S, E));
3851         break;
3852       case IndexedLane:
3853         Operands.push_back(ARMOperand::CreateVectorListIndexed(Reg, 1,
3854                                                                LaneIndex,
3855                                                                false, S, E));
3856         break;
3857       }
3858       return MatchOperand_Success;
3859     }
3860     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3861       Reg = getDRegFromQReg(Reg);
3862       OperandMatchResultTy Res = parseVectorLane(LaneKind, LaneIndex, E);
3863       if (Res != MatchOperand_Success)
3864         return Res;
3865       switch (LaneKind) {
3866       case NoLanes:
3867         Reg = MRI->getMatchingSuperReg(Reg, ARM::dsub_0,
3868                                    &ARMMCRegisterClasses[ARM::DPairRegClassID]);
3869         Operands.push_back(ARMOperand::CreateVectorList(Reg, 2, false, S, E));
3870         break;
3871       case AllLanes:
3872         Reg = MRI->getMatchingSuperReg(Reg, ARM::dsub_0,
3873                                    &ARMMCRegisterClasses[ARM::DPairRegClassID]);
3874         Operands.push_back(ARMOperand::CreateVectorListAllLanes(Reg, 2, false,
3875                                                                 S, E));
3876         break;
3877       case IndexedLane:
3878         Operands.push_back(ARMOperand::CreateVectorListIndexed(Reg, 2,
3879                                                                LaneIndex,
3880                                                                false, S, E));
3881         break;
3882       }
3883       return MatchOperand_Success;
3884     }
3885     Error(S, "vector register expected");
3886     return MatchOperand_ParseFail;
3887   }
3888 
3889   if (Parser.getTok().isNot(AsmToken::LCurly))
3890     return MatchOperand_NoMatch;
3891 
3892   Parser.Lex(); // Eat '{' token.
3893   SMLoc RegLoc = Parser.getTok().getLoc();
3894 
3895   int Reg = tryParseRegister();
3896   if (Reg == -1) {
3897     Error(RegLoc, "register expected");
3898     return MatchOperand_ParseFail;
3899   }
3900   unsigned Count = 1;
3901   int Spacing = 0;
3902   unsigned FirstReg = Reg;
3903   // The list is of D registers, but we also allow Q regs and just interpret
3904   // them as the two D sub-registers.
3905   if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3906     FirstReg = Reg = getDRegFromQReg(Reg);
3907     Spacing = 1; // double-spacing requires explicit D registers, otherwise
3908                  // it's ambiguous with four-register single spaced.
3909     ++Reg;
3910     ++Count;
3911   }
3912 
3913   SMLoc E;
3914   if (parseVectorLane(LaneKind, LaneIndex, E) != MatchOperand_Success)
3915     return MatchOperand_ParseFail;
3916 
3917   while (Parser.getTok().is(AsmToken::Comma) ||
3918          Parser.getTok().is(AsmToken::Minus)) {
3919     if (Parser.getTok().is(AsmToken::Minus)) {
3920       if (!Spacing)
3921         Spacing = 1; // Register range implies a single spaced list.
3922       else if (Spacing == 2) {
3923         Error(Parser.getTok().getLoc(),
3924               "sequential registers in double spaced list");
3925         return MatchOperand_ParseFail;
3926       }
3927       Parser.Lex(); // Eat the minus.
3928       SMLoc AfterMinusLoc = Parser.getTok().getLoc();
3929       int EndReg = tryParseRegister();
3930       if (EndReg == -1) {
3931         Error(AfterMinusLoc, "register expected");
3932         return MatchOperand_ParseFail;
3933       }
3934       // Allow Q regs and just interpret them as the two D sub-registers.
3935       if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(EndReg))
3936         EndReg = getDRegFromQReg(EndReg) + 1;
3937       // If the register is the same as the start reg, there's nothing
3938       // more to do.
3939       if (Reg == EndReg)
3940         continue;
3941       // The register must be in the same register class as the first.
3942       if (!ARMMCRegisterClasses[ARM::DPRRegClassID].contains(EndReg)) {
3943         Error(AfterMinusLoc, "invalid register in register list");
3944         return MatchOperand_ParseFail;
3945       }
3946       // Ranges must go from low to high.
3947       if (Reg > EndReg) {
3948         Error(AfterMinusLoc, "bad range in register list");
3949         return MatchOperand_ParseFail;
3950       }
3951       // Parse the lane specifier if present.
3952       VectorLaneTy NextLaneKind;
3953       unsigned NextLaneIndex;
3954       if (parseVectorLane(NextLaneKind, NextLaneIndex, E) !=
3955           MatchOperand_Success)
3956         return MatchOperand_ParseFail;
3957       if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
3958         Error(AfterMinusLoc, "mismatched lane index in register list");
3959         return MatchOperand_ParseFail;
3960       }
3961 
3962       // Add all the registers in the range to the register list.
3963       Count += EndReg - Reg;
3964       Reg = EndReg;
3965       continue;
3966     }
3967     Parser.Lex(); // Eat the comma.
3968     RegLoc = Parser.getTok().getLoc();
3969     int OldReg = Reg;
3970     Reg = tryParseRegister();
3971     if (Reg == -1) {
3972       Error(RegLoc, "register expected");
3973       return MatchOperand_ParseFail;
3974     }
3975     // vector register lists must be contiguous.
3976     // It's OK to use the enumeration values directly here rather, as the
3977     // VFP register classes have the enum sorted properly.
3978     //
3979     // The list is of D registers, but we also allow Q regs and just interpret
3980     // them as the two D sub-registers.
3981     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3982       if (!Spacing)
3983         Spacing = 1; // Register range implies a single spaced list.
3984       else if (Spacing == 2) {
3985         Error(RegLoc,
3986               "invalid register in double-spaced list (must be 'D' register')");
3987         return MatchOperand_ParseFail;
3988       }
3989       Reg = getDRegFromQReg(Reg);
3990       if (Reg != OldReg + 1) {
3991         Error(RegLoc, "non-contiguous register range");
3992         return MatchOperand_ParseFail;
3993       }
3994       ++Reg;
3995       Count += 2;
3996       // Parse the lane specifier if present.
3997       VectorLaneTy NextLaneKind;
3998       unsigned NextLaneIndex;
3999       SMLoc LaneLoc = Parser.getTok().getLoc();
4000       if (parseVectorLane(NextLaneKind, NextLaneIndex, E) !=
4001           MatchOperand_Success)
4002         return MatchOperand_ParseFail;
4003       if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
4004         Error(LaneLoc, "mismatched lane index in register list");
4005         return MatchOperand_ParseFail;
4006       }
4007       continue;
4008     }
4009     // Normal D register.
4010     // Figure out the register spacing (single or double) of the list if
4011     // we don't know it already.
4012     if (!Spacing)
4013       Spacing = 1 + (Reg == OldReg + 2);
4014 
4015     // Just check that it's contiguous and keep going.
4016     if (Reg != OldReg + Spacing) {
4017       Error(RegLoc, "non-contiguous register range");
4018       return MatchOperand_ParseFail;
4019     }
4020     ++Count;
4021     // Parse the lane specifier if present.
4022     VectorLaneTy NextLaneKind;
4023     unsigned NextLaneIndex;
4024     SMLoc EndLoc = Parser.getTok().getLoc();
4025     if (parseVectorLane(NextLaneKind, NextLaneIndex, E) != MatchOperand_Success)
4026       return MatchOperand_ParseFail;
4027     if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
4028       Error(EndLoc, "mismatched lane index in register list");
4029       return MatchOperand_ParseFail;
4030     }
4031   }
4032 
4033   if (Parser.getTok().isNot(AsmToken::RCurly)) {
4034     Error(Parser.getTok().getLoc(), "'}' expected");
4035     return MatchOperand_ParseFail;
4036   }
4037   E = Parser.getTok().getEndLoc();
4038   Parser.Lex(); // Eat '}' token.
4039 
4040   switch (LaneKind) {
4041   case NoLanes:
4042     // Two-register operands have been converted to the
4043     // composite register classes.
4044     if (Count == 2) {
4045       const MCRegisterClass *RC = (Spacing == 1) ?
4046         &ARMMCRegisterClasses[ARM::DPairRegClassID] :
4047         &ARMMCRegisterClasses[ARM::DPairSpcRegClassID];
4048       FirstReg = MRI->getMatchingSuperReg(FirstReg, ARM::dsub_0, RC);
4049     }
4050     Operands.push_back(ARMOperand::CreateVectorList(FirstReg, Count,
4051                                                     (Spacing == 2), S, E));
4052     break;
4053   case AllLanes:
4054     // Two-register operands have been converted to the
4055     // composite register classes.
4056     if (Count == 2) {
4057       const MCRegisterClass *RC = (Spacing == 1) ?
4058         &ARMMCRegisterClasses[ARM::DPairRegClassID] :
4059         &ARMMCRegisterClasses[ARM::DPairSpcRegClassID];
4060       FirstReg = MRI->getMatchingSuperReg(FirstReg, ARM::dsub_0, RC);
4061     }
4062     Operands.push_back(ARMOperand::CreateVectorListAllLanes(FirstReg, Count,
4063                                                             (Spacing == 2),
4064                                                             S, E));
4065     break;
4066   case IndexedLane:
4067     Operands.push_back(ARMOperand::CreateVectorListIndexed(FirstReg, Count,
4068                                                            LaneIndex,
4069                                                            (Spacing == 2),
4070                                                            S, E));
4071     break;
4072   }
4073   return MatchOperand_Success;
4074 }
4075 
4076 /// parseMemBarrierOptOperand - Try to parse DSB/DMB data barrier options.
4077 OperandMatchResultTy
4078 ARMAsmParser::parseMemBarrierOptOperand(OperandVector &Operands) {
4079   MCAsmParser &Parser = getParser();
4080   SMLoc S = Parser.getTok().getLoc();
4081   const AsmToken &Tok = Parser.getTok();
4082   unsigned Opt;
4083 
4084   if (Tok.is(AsmToken::Identifier)) {
4085     StringRef OptStr = Tok.getString();
4086 
4087     Opt = StringSwitch<unsigned>(OptStr.slice(0, OptStr.size()).lower())
4088       .Case("sy",    ARM_MB::SY)
4089       .Case("st",    ARM_MB::ST)
4090       .Case("ld",    ARM_MB::LD)
4091       .Case("sh",    ARM_MB::ISH)
4092       .Case("ish",   ARM_MB::ISH)
4093       .Case("shst",  ARM_MB::ISHST)
4094       .Case("ishst", ARM_MB::ISHST)
4095       .Case("ishld", ARM_MB::ISHLD)
4096       .Case("nsh",   ARM_MB::NSH)
4097       .Case("un",    ARM_MB::NSH)
4098       .Case("nshst", ARM_MB::NSHST)
4099       .Case("nshld", ARM_MB::NSHLD)
4100       .Case("unst",  ARM_MB::NSHST)
4101       .Case("osh",   ARM_MB::OSH)
4102       .Case("oshst", ARM_MB::OSHST)
4103       .Case("oshld", ARM_MB::OSHLD)
4104       .Default(~0U);
4105 
4106     // ishld, oshld, nshld and ld are only available from ARMv8.
4107     if (!hasV8Ops() && (Opt == ARM_MB::ISHLD || Opt == ARM_MB::OSHLD ||
4108                         Opt == ARM_MB::NSHLD || Opt == ARM_MB::LD))
4109       Opt = ~0U;
4110 
4111     if (Opt == ~0U)
4112       return MatchOperand_NoMatch;
4113 
4114     Parser.Lex(); // Eat identifier token.
4115   } else if (Tok.is(AsmToken::Hash) ||
4116              Tok.is(AsmToken::Dollar) ||
4117              Tok.is(AsmToken::Integer)) {
4118     if (Parser.getTok().isNot(AsmToken::Integer))
4119       Parser.Lex(); // Eat '#' or '$'.
4120     SMLoc Loc = Parser.getTok().getLoc();
4121 
4122     const MCExpr *MemBarrierID;
4123     if (getParser().parseExpression(MemBarrierID)) {
4124       Error(Loc, "illegal expression");
4125       return MatchOperand_ParseFail;
4126     }
4127 
4128     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(MemBarrierID);
4129     if (!CE) {
4130       Error(Loc, "constant expression expected");
4131       return MatchOperand_ParseFail;
4132     }
4133 
4134     int Val = CE->getValue();
4135     if (Val & ~0xf) {
4136       Error(Loc, "immediate value out of range");
4137       return MatchOperand_ParseFail;
4138     }
4139 
4140     Opt = ARM_MB::RESERVED_0 + Val;
4141   } else
4142     return MatchOperand_ParseFail;
4143 
4144   Operands.push_back(ARMOperand::CreateMemBarrierOpt((ARM_MB::MemBOpt)Opt, S));
4145   return MatchOperand_Success;
4146 }
4147 
4148 /// parseInstSyncBarrierOptOperand - Try to parse ISB inst sync barrier options.
4149 OperandMatchResultTy
4150 ARMAsmParser::parseInstSyncBarrierOptOperand(OperandVector &Operands) {
4151   MCAsmParser &Parser = getParser();
4152   SMLoc S = Parser.getTok().getLoc();
4153   const AsmToken &Tok = Parser.getTok();
4154   unsigned Opt;
4155 
4156   if (Tok.is(AsmToken::Identifier)) {
4157     StringRef OptStr = Tok.getString();
4158 
4159     if (OptStr.equals_lower("sy"))
4160       Opt = ARM_ISB::SY;
4161     else
4162       return MatchOperand_NoMatch;
4163 
4164     Parser.Lex(); // Eat identifier token.
4165   } else if (Tok.is(AsmToken::Hash) ||
4166              Tok.is(AsmToken::Dollar) ||
4167              Tok.is(AsmToken::Integer)) {
4168     if (Parser.getTok().isNot(AsmToken::Integer))
4169       Parser.Lex(); // Eat '#' or '$'.
4170     SMLoc Loc = Parser.getTok().getLoc();
4171 
4172     const MCExpr *ISBarrierID;
4173     if (getParser().parseExpression(ISBarrierID)) {
4174       Error(Loc, "illegal expression");
4175       return MatchOperand_ParseFail;
4176     }
4177 
4178     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ISBarrierID);
4179     if (!CE) {
4180       Error(Loc, "constant expression expected");
4181       return MatchOperand_ParseFail;
4182     }
4183 
4184     int Val = CE->getValue();
4185     if (Val & ~0xf) {
4186       Error(Loc, "immediate value out of range");
4187       return MatchOperand_ParseFail;
4188     }
4189 
4190     Opt = ARM_ISB::RESERVED_0 + Val;
4191   } else
4192     return MatchOperand_ParseFail;
4193 
4194   Operands.push_back(ARMOperand::CreateInstSyncBarrierOpt(
4195           (ARM_ISB::InstSyncBOpt)Opt, S));
4196   return MatchOperand_Success;
4197 }
4198 
4199 
4200 /// parseProcIFlagsOperand - Try to parse iflags from CPS instruction.
4201 OperandMatchResultTy
4202 ARMAsmParser::parseProcIFlagsOperand(OperandVector &Operands) {
4203   MCAsmParser &Parser = getParser();
4204   SMLoc S = Parser.getTok().getLoc();
4205   const AsmToken &Tok = Parser.getTok();
4206   if (!Tok.is(AsmToken::Identifier))
4207     return MatchOperand_NoMatch;
4208   StringRef IFlagsStr = Tok.getString();
4209 
4210   // An iflags string of "none" is interpreted to mean that none of the AIF
4211   // bits are set.  Not a terribly useful instruction, but a valid encoding.
4212   unsigned IFlags = 0;
4213   if (IFlagsStr != "none") {
4214         for (int i = 0, e = IFlagsStr.size(); i != e; ++i) {
4215       unsigned Flag = StringSwitch<unsigned>(IFlagsStr.substr(i, 1).lower())
4216         .Case("a", ARM_PROC::A)
4217         .Case("i", ARM_PROC::I)
4218         .Case("f", ARM_PROC::F)
4219         .Default(~0U);
4220 
4221       // If some specific iflag is already set, it means that some letter is
4222       // present more than once, this is not acceptable.
4223       if (Flag == ~0U || (IFlags & Flag))
4224         return MatchOperand_NoMatch;
4225 
4226       IFlags |= Flag;
4227     }
4228   }
4229 
4230   Parser.Lex(); // Eat identifier token.
4231   Operands.push_back(ARMOperand::CreateProcIFlags((ARM_PROC::IFlags)IFlags, S));
4232   return MatchOperand_Success;
4233 }
4234 
4235 /// parseMSRMaskOperand - Try to parse mask flags from MSR instruction.
4236 OperandMatchResultTy
4237 ARMAsmParser::parseMSRMaskOperand(OperandVector &Operands) {
4238   MCAsmParser &Parser = getParser();
4239   SMLoc S = Parser.getTok().getLoc();
4240   const AsmToken &Tok = Parser.getTok();
4241   if (!Tok.is(AsmToken::Identifier))
4242     return MatchOperand_NoMatch;
4243   StringRef Mask = Tok.getString();
4244 
4245   if (isMClass()) {
4246     auto TheReg = ARMSysReg::lookupMClassSysRegByName(Mask.lower());
4247     if (!TheReg || !TheReg->hasRequiredFeatures(getSTI().getFeatureBits()))
4248       return MatchOperand_NoMatch;
4249 
4250     unsigned SYSmvalue = TheReg->Encoding & 0xFFF;
4251 
4252     Parser.Lex(); // Eat identifier token.
4253     Operands.push_back(ARMOperand::CreateMSRMask(SYSmvalue, S));
4254     return MatchOperand_Success;
4255   }
4256 
4257   // Split spec_reg from flag, example: CPSR_sxf => "CPSR" and "sxf"
4258   size_t Start = 0, Next = Mask.find('_');
4259   StringRef Flags = "";
4260   std::string SpecReg = Mask.slice(Start, Next).lower();
4261   if (Next != StringRef::npos)
4262     Flags = Mask.slice(Next+1, Mask.size());
4263 
4264   // FlagsVal contains the complete mask:
4265   // 3-0: Mask
4266   // 4: Special Reg (cpsr, apsr => 0; spsr => 1)
4267   unsigned FlagsVal = 0;
4268 
4269   if (SpecReg == "apsr") {
4270     FlagsVal = StringSwitch<unsigned>(Flags)
4271     .Case("nzcvq",  0x8) // same as CPSR_f
4272     .Case("g",      0x4) // same as CPSR_s
4273     .Case("nzcvqg", 0xc) // same as CPSR_fs
4274     .Default(~0U);
4275 
4276     if (FlagsVal == ~0U) {
4277       if (!Flags.empty())
4278         return MatchOperand_NoMatch;
4279       else
4280         FlagsVal = 8; // No flag
4281     }
4282   } else if (SpecReg == "cpsr" || SpecReg == "spsr") {
4283     // cpsr_all is an alias for cpsr_fc, as is plain cpsr.
4284     if (Flags == "all" || Flags == "")
4285       Flags = "fc";
4286     for (int i = 0, e = Flags.size(); i != e; ++i) {
4287       unsigned Flag = StringSwitch<unsigned>(Flags.substr(i, 1))
4288       .Case("c", 1)
4289       .Case("x", 2)
4290       .Case("s", 4)
4291       .Case("f", 8)
4292       .Default(~0U);
4293 
4294       // If some specific flag is already set, it means that some letter is
4295       // present more than once, this is not acceptable.
4296       if (Flag == ~0U || (FlagsVal & Flag))
4297         return MatchOperand_NoMatch;
4298       FlagsVal |= Flag;
4299     }
4300   } else // No match for special register.
4301     return MatchOperand_NoMatch;
4302 
4303   // Special register without flags is NOT equivalent to "fc" flags.
4304   // NOTE: This is a divergence from gas' behavior.  Uncommenting the following
4305   // two lines would enable gas compatibility at the expense of breaking
4306   // round-tripping.
4307   //
4308   // if (!FlagsVal)
4309   //  FlagsVal = 0x9;
4310 
4311   // Bit 4: Special Reg (cpsr, apsr => 0; spsr => 1)
4312   if (SpecReg == "spsr")
4313     FlagsVal |= 16;
4314 
4315   Parser.Lex(); // Eat identifier token.
4316   Operands.push_back(ARMOperand::CreateMSRMask(FlagsVal, S));
4317   return MatchOperand_Success;
4318 }
4319 
4320 /// parseBankedRegOperand - Try to parse a banked register (e.g. "lr_irq") for
4321 /// use in the MRS/MSR instructions added to support virtualization.
4322 OperandMatchResultTy
4323 ARMAsmParser::parseBankedRegOperand(OperandVector &Operands) {
4324   MCAsmParser &Parser = getParser();
4325   SMLoc S = Parser.getTok().getLoc();
4326   const AsmToken &Tok = Parser.getTok();
4327   if (!Tok.is(AsmToken::Identifier))
4328     return MatchOperand_NoMatch;
4329   StringRef RegName = Tok.getString();
4330 
4331   auto TheReg = ARMBankedReg::lookupBankedRegByName(RegName.lower());
4332   if (!TheReg)
4333     return MatchOperand_NoMatch;
4334   unsigned Encoding = TheReg->Encoding;
4335 
4336   Parser.Lex(); // Eat identifier token.
4337   Operands.push_back(ARMOperand::CreateBankedReg(Encoding, S));
4338   return MatchOperand_Success;
4339 }
4340 
4341 OperandMatchResultTy
4342 ARMAsmParser::parsePKHImm(OperandVector &Operands, StringRef Op, int Low,
4343                           int High) {
4344   MCAsmParser &Parser = getParser();
4345   const AsmToken &Tok = Parser.getTok();
4346   if (Tok.isNot(AsmToken::Identifier)) {
4347     Error(Parser.getTok().getLoc(), Op + " operand expected.");
4348     return MatchOperand_ParseFail;
4349   }
4350   StringRef ShiftName = Tok.getString();
4351   std::string LowerOp = Op.lower();
4352   std::string UpperOp = Op.upper();
4353   if (ShiftName != LowerOp && ShiftName != UpperOp) {
4354     Error(Parser.getTok().getLoc(), Op + " operand expected.");
4355     return MatchOperand_ParseFail;
4356   }
4357   Parser.Lex(); // Eat shift type token.
4358 
4359   // There must be a '#' and a shift amount.
4360   if (Parser.getTok().isNot(AsmToken::Hash) &&
4361       Parser.getTok().isNot(AsmToken::Dollar)) {
4362     Error(Parser.getTok().getLoc(), "'#' expected");
4363     return MatchOperand_ParseFail;
4364   }
4365   Parser.Lex(); // Eat hash token.
4366 
4367   const MCExpr *ShiftAmount;
4368   SMLoc Loc = Parser.getTok().getLoc();
4369   SMLoc EndLoc;
4370   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
4371     Error(Loc, "illegal expression");
4372     return MatchOperand_ParseFail;
4373   }
4374   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
4375   if (!CE) {
4376     Error(Loc, "constant expression expected");
4377     return MatchOperand_ParseFail;
4378   }
4379   int Val = CE->getValue();
4380   if (Val < Low || Val > High) {
4381     Error(Loc, "immediate value out of range");
4382     return MatchOperand_ParseFail;
4383   }
4384 
4385   Operands.push_back(ARMOperand::CreateImm(CE, Loc, EndLoc));
4386 
4387   return MatchOperand_Success;
4388 }
4389 
4390 OperandMatchResultTy
4391 ARMAsmParser::parseSetEndImm(OperandVector &Operands) {
4392   MCAsmParser &Parser = getParser();
4393   const AsmToken &Tok = Parser.getTok();
4394   SMLoc S = Tok.getLoc();
4395   if (Tok.isNot(AsmToken::Identifier)) {
4396     Error(S, "'be' or 'le' operand expected");
4397     return MatchOperand_ParseFail;
4398   }
4399   int Val = StringSwitch<int>(Tok.getString().lower())
4400     .Case("be", 1)
4401     .Case("le", 0)
4402     .Default(-1);
4403   Parser.Lex(); // Eat the token.
4404 
4405   if (Val == -1) {
4406     Error(S, "'be' or 'le' operand expected");
4407     return MatchOperand_ParseFail;
4408   }
4409   Operands.push_back(ARMOperand::CreateImm(MCConstantExpr::create(Val,
4410                                                                   getContext()),
4411                                            S, Tok.getEndLoc()));
4412   return MatchOperand_Success;
4413 }
4414 
4415 /// parseShifterImm - Parse the shifter immediate operand for SSAT/USAT
4416 /// instructions. Legal values are:
4417 ///     lsl #n  'n' in [0,31]
4418 ///     asr #n  'n' in [1,32]
4419 ///             n == 32 encoded as n == 0.
4420 OperandMatchResultTy
4421 ARMAsmParser::parseShifterImm(OperandVector &Operands) {
4422   MCAsmParser &Parser = getParser();
4423   const AsmToken &Tok = Parser.getTok();
4424   SMLoc S = Tok.getLoc();
4425   if (Tok.isNot(AsmToken::Identifier)) {
4426     Error(S, "shift operator 'asr' or 'lsl' expected");
4427     return MatchOperand_ParseFail;
4428   }
4429   StringRef ShiftName = Tok.getString();
4430   bool isASR;
4431   if (ShiftName == "lsl" || ShiftName == "LSL")
4432     isASR = false;
4433   else if (ShiftName == "asr" || ShiftName == "ASR")
4434     isASR = true;
4435   else {
4436     Error(S, "shift operator 'asr' or 'lsl' expected");
4437     return MatchOperand_ParseFail;
4438   }
4439   Parser.Lex(); // Eat the operator.
4440 
4441   // A '#' and a shift amount.
4442   if (Parser.getTok().isNot(AsmToken::Hash) &&
4443       Parser.getTok().isNot(AsmToken::Dollar)) {
4444     Error(Parser.getTok().getLoc(), "'#' expected");
4445     return MatchOperand_ParseFail;
4446   }
4447   Parser.Lex(); // Eat hash token.
4448   SMLoc ExLoc = Parser.getTok().getLoc();
4449 
4450   const MCExpr *ShiftAmount;
4451   SMLoc EndLoc;
4452   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
4453     Error(ExLoc, "malformed shift expression");
4454     return MatchOperand_ParseFail;
4455   }
4456   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
4457   if (!CE) {
4458     Error(ExLoc, "shift amount must be an immediate");
4459     return MatchOperand_ParseFail;
4460   }
4461 
4462   int64_t Val = CE->getValue();
4463   if (isASR) {
4464     // Shift amount must be in [1,32]
4465     if (Val < 1 || Val > 32) {
4466       Error(ExLoc, "'asr' shift amount must be in range [1,32]");
4467       return MatchOperand_ParseFail;
4468     }
4469     // asr #32 encoded as asr #0, but is not allowed in Thumb2 mode.
4470     if (isThumb() && Val == 32) {
4471       Error(ExLoc, "'asr #32' shift amount not allowed in Thumb mode");
4472       return MatchOperand_ParseFail;
4473     }
4474     if (Val == 32) Val = 0;
4475   } else {
4476     // Shift amount must be in [1,32]
4477     if (Val < 0 || Val > 31) {
4478       Error(ExLoc, "'lsr' shift amount must be in range [0,31]");
4479       return MatchOperand_ParseFail;
4480     }
4481   }
4482 
4483   Operands.push_back(ARMOperand::CreateShifterImm(isASR, Val, S, EndLoc));
4484 
4485   return MatchOperand_Success;
4486 }
4487 
4488 /// parseRotImm - Parse the shifter immediate operand for SXTB/UXTB family
4489 /// of instructions. Legal values are:
4490 ///     ror #n  'n' in {0, 8, 16, 24}
4491 OperandMatchResultTy
4492 ARMAsmParser::parseRotImm(OperandVector &Operands) {
4493   MCAsmParser &Parser = getParser();
4494   const AsmToken &Tok = Parser.getTok();
4495   SMLoc S = Tok.getLoc();
4496   if (Tok.isNot(AsmToken::Identifier))
4497     return MatchOperand_NoMatch;
4498   StringRef ShiftName = Tok.getString();
4499   if (ShiftName != "ror" && ShiftName != "ROR")
4500     return MatchOperand_NoMatch;
4501   Parser.Lex(); // Eat the operator.
4502 
4503   // A '#' and a rotate amount.
4504   if (Parser.getTok().isNot(AsmToken::Hash) &&
4505       Parser.getTok().isNot(AsmToken::Dollar)) {
4506     Error(Parser.getTok().getLoc(), "'#' expected");
4507     return MatchOperand_ParseFail;
4508   }
4509   Parser.Lex(); // Eat hash token.
4510   SMLoc ExLoc = Parser.getTok().getLoc();
4511 
4512   const MCExpr *ShiftAmount;
4513   SMLoc EndLoc;
4514   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
4515     Error(ExLoc, "malformed rotate expression");
4516     return MatchOperand_ParseFail;
4517   }
4518   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
4519   if (!CE) {
4520     Error(ExLoc, "rotate amount must be an immediate");
4521     return MatchOperand_ParseFail;
4522   }
4523 
4524   int64_t Val = CE->getValue();
4525   // Shift amount must be in {0, 8, 16, 24} (0 is undocumented extension)
4526   // normally, zero is represented in asm by omitting the rotate operand
4527   // entirely.
4528   if (Val != 8 && Val != 16 && Val != 24 && Val != 0) {
4529     Error(ExLoc, "'ror' rotate amount must be 8, 16, or 24");
4530     return MatchOperand_ParseFail;
4531   }
4532 
4533   Operands.push_back(ARMOperand::CreateRotImm(Val, S, EndLoc));
4534 
4535   return MatchOperand_Success;
4536 }
4537 
4538 OperandMatchResultTy
4539 ARMAsmParser::parseModImm(OperandVector &Operands) {
4540   MCAsmParser &Parser = getParser();
4541   MCAsmLexer &Lexer = getLexer();
4542   int64_t Imm1, Imm2;
4543 
4544   SMLoc S = Parser.getTok().getLoc();
4545 
4546   // 1) A mod_imm operand can appear in the place of a register name:
4547   //   add r0, #mod_imm
4548   //   add r0, r0, #mod_imm
4549   // to correctly handle the latter, we bail out as soon as we see an
4550   // identifier.
4551   //
4552   // 2) Similarly, we do not want to parse into complex operands:
4553   //   mov r0, #mod_imm
4554   //   mov r0, :lower16:(_foo)
4555   if (Parser.getTok().is(AsmToken::Identifier) ||
4556       Parser.getTok().is(AsmToken::Colon))
4557     return MatchOperand_NoMatch;
4558 
4559   // Hash (dollar) is optional as per the ARMARM
4560   if (Parser.getTok().is(AsmToken::Hash) ||
4561       Parser.getTok().is(AsmToken::Dollar)) {
4562     // Avoid parsing into complex operands (#:)
4563     if (Lexer.peekTok().is(AsmToken::Colon))
4564       return MatchOperand_NoMatch;
4565 
4566     // Eat the hash (dollar)
4567     Parser.Lex();
4568   }
4569 
4570   SMLoc Sx1, Ex1;
4571   Sx1 = Parser.getTok().getLoc();
4572   const MCExpr *Imm1Exp;
4573   if (getParser().parseExpression(Imm1Exp, Ex1)) {
4574     Error(Sx1, "malformed expression");
4575     return MatchOperand_ParseFail;
4576   }
4577 
4578   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm1Exp);
4579 
4580   if (CE) {
4581     // Immediate must fit within 32-bits
4582     Imm1 = CE->getValue();
4583     int Enc = ARM_AM::getSOImmVal(Imm1);
4584     if (Enc != -1 && Parser.getTok().is(AsmToken::EndOfStatement)) {
4585       // We have a match!
4586       Operands.push_back(ARMOperand::CreateModImm((Enc & 0xFF),
4587                                                   (Enc & 0xF00) >> 7,
4588                                                   Sx1, Ex1));
4589       return MatchOperand_Success;
4590     }
4591 
4592     // We have parsed an immediate which is not for us, fallback to a plain
4593     // immediate. This can happen for instruction aliases. For an example,
4594     // ARMInstrInfo.td defines the alias [mov <-> mvn] which can transform
4595     // a mov (mvn) with a mod_imm_neg/mod_imm_not operand into the opposite
4596     // instruction with a mod_imm operand. The alias is defined such that the
4597     // parser method is shared, that's why we have to do this here.
4598     if (Parser.getTok().is(AsmToken::EndOfStatement)) {
4599       Operands.push_back(ARMOperand::CreateImm(Imm1Exp, Sx1, Ex1));
4600       return MatchOperand_Success;
4601     }
4602   } else {
4603     // Operands like #(l1 - l2) can only be evaluated at a later stage (via an
4604     // MCFixup). Fallback to a plain immediate.
4605     Operands.push_back(ARMOperand::CreateImm(Imm1Exp, Sx1, Ex1));
4606     return MatchOperand_Success;
4607   }
4608 
4609   // From this point onward, we expect the input to be a (#bits, #rot) pair
4610   if (Parser.getTok().isNot(AsmToken::Comma)) {
4611     Error(Sx1, "expected modified immediate operand: #[0, 255], #even[0-30]");
4612     return MatchOperand_ParseFail;
4613   }
4614 
4615   if (Imm1 & ~0xFF) {
4616     Error(Sx1, "immediate operand must a number in the range [0, 255]");
4617     return MatchOperand_ParseFail;
4618   }
4619 
4620   // Eat the comma
4621   Parser.Lex();
4622 
4623   // Repeat for #rot
4624   SMLoc Sx2, Ex2;
4625   Sx2 = Parser.getTok().getLoc();
4626 
4627   // Eat the optional hash (dollar)
4628   if (Parser.getTok().is(AsmToken::Hash) ||
4629       Parser.getTok().is(AsmToken::Dollar))
4630     Parser.Lex();
4631 
4632   const MCExpr *Imm2Exp;
4633   if (getParser().parseExpression(Imm2Exp, Ex2)) {
4634     Error(Sx2, "malformed expression");
4635     return MatchOperand_ParseFail;
4636   }
4637 
4638   CE = dyn_cast<MCConstantExpr>(Imm2Exp);
4639 
4640   if (CE) {
4641     Imm2 = CE->getValue();
4642     if (!(Imm2 & ~0x1E)) {
4643       // We have a match!
4644       Operands.push_back(ARMOperand::CreateModImm(Imm1, Imm2, S, Ex2));
4645       return MatchOperand_Success;
4646     }
4647     Error(Sx2, "immediate operand must an even number in the range [0, 30]");
4648     return MatchOperand_ParseFail;
4649   } else {
4650     Error(Sx2, "constant expression expected");
4651     return MatchOperand_ParseFail;
4652   }
4653 }
4654 
4655 OperandMatchResultTy
4656 ARMAsmParser::parseBitfield(OperandVector &Operands) {
4657   MCAsmParser &Parser = getParser();
4658   SMLoc S = Parser.getTok().getLoc();
4659   // The bitfield descriptor is really two operands, the LSB and the width.
4660   if (Parser.getTok().isNot(AsmToken::Hash) &&
4661       Parser.getTok().isNot(AsmToken::Dollar)) {
4662     Error(Parser.getTok().getLoc(), "'#' expected");
4663     return MatchOperand_ParseFail;
4664   }
4665   Parser.Lex(); // Eat hash token.
4666 
4667   const MCExpr *LSBExpr;
4668   SMLoc E = Parser.getTok().getLoc();
4669   if (getParser().parseExpression(LSBExpr)) {
4670     Error(E, "malformed immediate expression");
4671     return MatchOperand_ParseFail;
4672   }
4673   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(LSBExpr);
4674   if (!CE) {
4675     Error(E, "'lsb' operand must be an immediate");
4676     return MatchOperand_ParseFail;
4677   }
4678 
4679   int64_t LSB = CE->getValue();
4680   // The LSB must be in the range [0,31]
4681   if (LSB < 0 || LSB > 31) {
4682     Error(E, "'lsb' operand must be in the range [0,31]");
4683     return MatchOperand_ParseFail;
4684   }
4685   E = Parser.getTok().getLoc();
4686 
4687   // Expect another immediate operand.
4688   if (Parser.getTok().isNot(AsmToken::Comma)) {
4689     Error(Parser.getTok().getLoc(), "too few operands");
4690     return MatchOperand_ParseFail;
4691   }
4692   Parser.Lex(); // Eat hash token.
4693   if (Parser.getTok().isNot(AsmToken::Hash) &&
4694       Parser.getTok().isNot(AsmToken::Dollar)) {
4695     Error(Parser.getTok().getLoc(), "'#' expected");
4696     return MatchOperand_ParseFail;
4697   }
4698   Parser.Lex(); // Eat hash token.
4699 
4700   const MCExpr *WidthExpr;
4701   SMLoc EndLoc;
4702   if (getParser().parseExpression(WidthExpr, EndLoc)) {
4703     Error(E, "malformed immediate expression");
4704     return MatchOperand_ParseFail;
4705   }
4706   CE = dyn_cast<MCConstantExpr>(WidthExpr);
4707   if (!CE) {
4708     Error(E, "'width' operand must be an immediate");
4709     return MatchOperand_ParseFail;
4710   }
4711 
4712   int64_t Width = CE->getValue();
4713   // The LSB must be in the range [1,32-lsb]
4714   if (Width < 1 || Width > 32 - LSB) {
4715     Error(E, "'width' operand must be in the range [1,32-lsb]");
4716     return MatchOperand_ParseFail;
4717   }
4718 
4719   Operands.push_back(ARMOperand::CreateBitfield(LSB, Width, S, EndLoc));
4720 
4721   return MatchOperand_Success;
4722 }
4723 
4724 OperandMatchResultTy
4725 ARMAsmParser::parsePostIdxReg(OperandVector &Operands) {
4726   // Check for a post-index addressing register operand. Specifically:
4727   // postidx_reg := '+' register {, shift}
4728   //              | '-' register {, shift}
4729   //              | register {, shift}
4730 
4731   // This method must return MatchOperand_NoMatch without consuming any tokens
4732   // in the case where there is no match, as other alternatives take other
4733   // parse methods.
4734   MCAsmParser &Parser = getParser();
4735   AsmToken Tok = Parser.getTok();
4736   SMLoc S = Tok.getLoc();
4737   bool haveEaten = false;
4738   bool isAdd = true;
4739   if (Tok.is(AsmToken::Plus)) {
4740     Parser.Lex(); // Eat the '+' token.
4741     haveEaten = true;
4742   } else if (Tok.is(AsmToken::Minus)) {
4743     Parser.Lex(); // Eat the '-' token.
4744     isAdd = false;
4745     haveEaten = true;
4746   }
4747 
4748   SMLoc E = Parser.getTok().getEndLoc();
4749   int Reg = tryParseRegister();
4750   if (Reg == -1) {
4751     if (!haveEaten)
4752       return MatchOperand_NoMatch;
4753     Error(Parser.getTok().getLoc(), "register expected");
4754     return MatchOperand_ParseFail;
4755   }
4756 
4757   ARM_AM::ShiftOpc ShiftTy = ARM_AM::no_shift;
4758   unsigned ShiftImm = 0;
4759   if (Parser.getTok().is(AsmToken::Comma)) {
4760     Parser.Lex(); // Eat the ','.
4761     if (parseMemRegOffsetShift(ShiftTy, ShiftImm))
4762       return MatchOperand_ParseFail;
4763 
4764     // FIXME: Only approximates end...may include intervening whitespace.
4765     E = Parser.getTok().getLoc();
4766   }
4767 
4768   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ShiftTy,
4769                                                   ShiftImm, S, E));
4770 
4771   return MatchOperand_Success;
4772 }
4773 
4774 OperandMatchResultTy
4775 ARMAsmParser::parseAM3Offset(OperandVector &Operands) {
4776   // Check for a post-index addressing register operand. Specifically:
4777   // am3offset := '+' register
4778   //              | '-' register
4779   //              | register
4780   //              | # imm
4781   //              | # + imm
4782   //              | # - imm
4783 
4784   // This method must return MatchOperand_NoMatch without consuming any tokens
4785   // in the case where there is no match, as other alternatives take other
4786   // parse methods.
4787   MCAsmParser &Parser = getParser();
4788   AsmToken Tok = Parser.getTok();
4789   SMLoc S = Tok.getLoc();
4790 
4791   // Do immediates first, as we always parse those if we have a '#'.
4792   if (Parser.getTok().is(AsmToken::Hash) ||
4793       Parser.getTok().is(AsmToken::Dollar)) {
4794     Parser.Lex(); // Eat '#' or '$'.
4795     // Explicitly look for a '-', as we need to encode negative zero
4796     // differently.
4797     bool isNegative = Parser.getTok().is(AsmToken::Minus);
4798     const MCExpr *Offset;
4799     SMLoc E;
4800     if (getParser().parseExpression(Offset, E))
4801       return MatchOperand_ParseFail;
4802     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
4803     if (!CE) {
4804       Error(S, "constant expression expected");
4805       return MatchOperand_ParseFail;
4806     }
4807     // Negative zero is encoded as the flag value
4808     // std::numeric_limits<int32_t>::min().
4809     int32_t Val = CE->getValue();
4810     if (isNegative && Val == 0)
4811       Val = std::numeric_limits<int32_t>::min();
4812 
4813     Operands.push_back(
4814       ARMOperand::CreateImm(MCConstantExpr::create(Val, getContext()), S, E));
4815 
4816     return MatchOperand_Success;
4817   }
4818 
4819   bool haveEaten = false;
4820   bool isAdd = true;
4821   if (Tok.is(AsmToken::Plus)) {
4822     Parser.Lex(); // Eat the '+' token.
4823     haveEaten = true;
4824   } else if (Tok.is(AsmToken::Minus)) {
4825     Parser.Lex(); // Eat the '-' token.
4826     isAdd = false;
4827     haveEaten = true;
4828   }
4829 
4830   Tok = Parser.getTok();
4831   int Reg = tryParseRegister();
4832   if (Reg == -1) {
4833     if (!haveEaten)
4834       return MatchOperand_NoMatch;
4835     Error(Tok.getLoc(), "register expected");
4836     return MatchOperand_ParseFail;
4837   }
4838 
4839   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ARM_AM::no_shift,
4840                                                   0, S, Tok.getEndLoc()));
4841 
4842   return MatchOperand_Success;
4843 }
4844 
4845 /// Convert parsed operands to MCInst.  Needed here because this instruction
4846 /// only has two register operands, but multiplication is commutative so
4847 /// assemblers should accept both "mul rD, rN, rD" and "mul rD, rD, rN".
4848 void ARMAsmParser::cvtThumbMultiply(MCInst &Inst,
4849                                     const OperandVector &Operands) {
4850   ((ARMOperand &)*Operands[3]).addRegOperands(Inst, 1);
4851   ((ARMOperand &)*Operands[1]).addCCOutOperands(Inst, 1);
4852   // If we have a three-operand form, make sure to set Rn to be the operand
4853   // that isn't the same as Rd.
4854   unsigned RegOp = 4;
4855   if (Operands.size() == 6 &&
4856       ((ARMOperand &)*Operands[4]).getReg() ==
4857           ((ARMOperand &)*Operands[3]).getReg())
4858     RegOp = 5;
4859   ((ARMOperand &)*Operands[RegOp]).addRegOperands(Inst, 1);
4860   Inst.addOperand(Inst.getOperand(0));
4861   ((ARMOperand &)*Operands[2]).addCondCodeOperands(Inst, 2);
4862 }
4863 
4864 void ARMAsmParser::cvtThumbBranches(MCInst &Inst,
4865                                     const OperandVector &Operands) {
4866   int CondOp = -1, ImmOp = -1;
4867   switch(Inst.getOpcode()) {
4868     case ARM::tB:
4869     case ARM::tBcc:  CondOp = 1; ImmOp = 2; break;
4870 
4871     case ARM::t2B:
4872     case ARM::t2Bcc: CondOp = 1; ImmOp = 3; break;
4873 
4874     default: llvm_unreachable("Unexpected instruction in cvtThumbBranches");
4875   }
4876   // first decide whether or not the branch should be conditional
4877   // by looking at it's location relative to an IT block
4878   if(inITBlock()) {
4879     // inside an IT block we cannot have any conditional branches. any
4880     // such instructions needs to be converted to unconditional form
4881     switch(Inst.getOpcode()) {
4882       case ARM::tBcc: Inst.setOpcode(ARM::tB); break;
4883       case ARM::t2Bcc: Inst.setOpcode(ARM::t2B); break;
4884     }
4885   } else {
4886     // outside IT blocks we can only have unconditional branches with AL
4887     // condition code or conditional branches with non-AL condition code
4888     unsigned Cond = static_cast<ARMOperand &>(*Operands[CondOp]).getCondCode();
4889     switch(Inst.getOpcode()) {
4890       case ARM::tB:
4891       case ARM::tBcc:
4892         Inst.setOpcode(Cond == ARMCC::AL ? ARM::tB : ARM::tBcc);
4893         break;
4894       case ARM::t2B:
4895       case ARM::t2Bcc:
4896         Inst.setOpcode(Cond == ARMCC::AL ? ARM::t2B : ARM::t2Bcc);
4897         break;
4898     }
4899   }
4900 
4901   // now decide on encoding size based on branch target range
4902   switch(Inst.getOpcode()) {
4903     // classify tB as either t2B or t1B based on range of immediate operand
4904     case ARM::tB: {
4905       ARMOperand &op = static_cast<ARMOperand &>(*Operands[ImmOp]);
4906       if (!op.isSignedOffset<11, 1>() && isThumb() && hasV8MBaseline())
4907         Inst.setOpcode(ARM::t2B);
4908       break;
4909     }
4910     // classify tBcc as either t2Bcc or t1Bcc based on range of immediate operand
4911     case ARM::tBcc: {
4912       ARMOperand &op = static_cast<ARMOperand &>(*Operands[ImmOp]);
4913       if (!op.isSignedOffset<8, 1>() && isThumb() && hasV8MBaseline())
4914         Inst.setOpcode(ARM::t2Bcc);
4915       break;
4916     }
4917   }
4918   ((ARMOperand &)*Operands[ImmOp]).addImmOperands(Inst, 1);
4919   ((ARMOperand &)*Operands[CondOp]).addCondCodeOperands(Inst, 2);
4920 }
4921 
4922 /// Parse an ARM memory expression, return false if successful else return true
4923 /// or an error.  The first token must be a '[' when called.
4924 bool ARMAsmParser::parseMemory(OperandVector &Operands) {
4925   MCAsmParser &Parser = getParser();
4926   SMLoc S, E;
4927   if (Parser.getTok().isNot(AsmToken::LBrac))
4928     return TokError("Token is not a Left Bracket");
4929   S = Parser.getTok().getLoc();
4930   Parser.Lex(); // Eat left bracket token.
4931 
4932   const AsmToken &BaseRegTok = Parser.getTok();
4933   int BaseRegNum = tryParseRegister();
4934   if (BaseRegNum == -1)
4935     return Error(BaseRegTok.getLoc(), "register expected");
4936 
4937   // The next token must either be a comma, a colon or a closing bracket.
4938   const AsmToken &Tok = Parser.getTok();
4939   if (!Tok.is(AsmToken::Colon) && !Tok.is(AsmToken::Comma) &&
4940       !Tok.is(AsmToken::RBrac))
4941     return Error(Tok.getLoc(), "malformed memory operand");
4942 
4943   if (Tok.is(AsmToken::RBrac)) {
4944     E = Tok.getEndLoc();
4945     Parser.Lex(); // Eat right bracket token.
4946 
4947     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, 0,
4948                                              ARM_AM::no_shift, 0, 0, false,
4949                                              S, E));
4950 
4951     // If there's a pre-indexing writeback marker, '!', just add it as a token
4952     // operand. It's rather odd, but syntactically valid.
4953     if (Parser.getTok().is(AsmToken::Exclaim)) {
4954       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
4955       Parser.Lex(); // Eat the '!'.
4956     }
4957 
4958     return false;
4959   }
4960 
4961   assert((Tok.is(AsmToken::Colon) || Tok.is(AsmToken::Comma)) &&
4962          "Lost colon or comma in memory operand?!");
4963   if (Tok.is(AsmToken::Comma)) {
4964     Parser.Lex(); // Eat the comma.
4965   }
4966 
4967   // If we have a ':', it's an alignment specifier.
4968   if (Parser.getTok().is(AsmToken::Colon)) {
4969     Parser.Lex(); // Eat the ':'.
4970     E = Parser.getTok().getLoc();
4971     SMLoc AlignmentLoc = Tok.getLoc();
4972 
4973     const MCExpr *Expr;
4974     if (getParser().parseExpression(Expr))
4975      return true;
4976 
4977     // The expression has to be a constant. Memory references with relocations
4978     // don't come through here, as they use the <label> forms of the relevant
4979     // instructions.
4980     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
4981     if (!CE)
4982       return Error (E, "constant expression expected");
4983 
4984     unsigned Align = 0;
4985     switch (CE->getValue()) {
4986     default:
4987       return Error(E,
4988                    "alignment specifier must be 16, 32, 64, 128, or 256 bits");
4989     case 16:  Align = 2; break;
4990     case 32:  Align = 4; break;
4991     case 64:  Align = 8; break;
4992     case 128: Align = 16; break;
4993     case 256: Align = 32; break;
4994     }
4995 
4996     // Now we should have the closing ']'
4997     if (Parser.getTok().isNot(AsmToken::RBrac))
4998       return Error(Parser.getTok().getLoc(), "']' expected");
4999     E = Parser.getTok().getEndLoc();
5000     Parser.Lex(); // Eat right bracket token.
5001 
5002     // Don't worry about range checking the value here. That's handled by
5003     // the is*() predicates.
5004     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, 0,
5005                                              ARM_AM::no_shift, 0, Align,
5006                                              false, S, E, AlignmentLoc));
5007 
5008     // If there's a pre-indexing writeback marker, '!', just add it as a token
5009     // operand.
5010     if (Parser.getTok().is(AsmToken::Exclaim)) {
5011       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
5012       Parser.Lex(); // Eat the '!'.
5013     }
5014 
5015     return false;
5016   }
5017 
5018   // If we have a '#', it's an immediate offset, else assume it's a register
5019   // offset. Be friendly and also accept a plain integer (without a leading
5020   // hash) for gas compatibility.
5021   if (Parser.getTok().is(AsmToken::Hash) ||
5022       Parser.getTok().is(AsmToken::Dollar) ||
5023       Parser.getTok().is(AsmToken::Integer)) {
5024     if (Parser.getTok().isNot(AsmToken::Integer))
5025       Parser.Lex(); // Eat '#' or '$'.
5026     E = Parser.getTok().getLoc();
5027 
5028     bool isNegative = getParser().getTok().is(AsmToken::Minus);
5029     const MCExpr *Offset;
5030     if (getParser().parseExpression(Offset))
5031      return true;
5032 
5033     // The expression has to be a constant. Memory references with relocations
5034     // don't come through here, as they use the <label> forms of the relevant
5035     // instructions.
5036     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
5037     if (!CE)
5038       return Error (E, "constant expression expected");
5039 
5040     // If the constant was #-0, represent it as
5041     // std::numeric_limits<int32_t>::min().
5042     int32_t Val = CE->getValue();
5043     if (isNegative && Val == 0)
5044       CE = MCConstantExpr::create(std::numeric_limits<int32_t>::min(),
5045                                   getContext());
5046 
5047     // Now we should have the closing ']'
5048     if (Parser.getTok().isNot(AsmToken::RBrac))
5049       return Error(Parser.getTok().getLoc(), "']' expected");
5050     E = Parser.getTok().getEndLoc();
5051     Parser.Lex(); // Eat right bracket token.
5052 
5053     // Don't worry about range checking the value here. That's handled by
5054     // the is*() predicates.
5055     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, CE, 0,
5056                                              ARM_AM::no_shift, 0, 0,
5057                                              false, S, E));
5058 
5059     // If there's a pre-indexing writeback marker, '!', just add it as a token
5060     // operand.
5061     if (Parser.getTok().is(AsmToken::Exclaim)) {
5062       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
5063       Parser.Lex(); // Eat the '!'.
5064     }
5065 
5066     return false;
5067   }
5068 
5069   // The register offset is optionally preceded by a '+' or '-'
5070   bool isNegative = false;
5071   if (Parser.getTok().is(AsmToken::Minus)) {
5072     isNegative = true;
5073     Parser.Lex(); // Eat the '-'.
5074   } else if (Parser.getTok().is(AsmToken::Plus)) {
5075     // Nothing to do.
5076     Parser.Lex(); // Eat the '+'.
5077   }
5078 
5079   E = Parser.getTok().getLoc();
5080   int OffsetRegNum = tryParseRegister();
5081   if (OffsetRegNum == -1)
5082     return Error(E, "register expected");
5083 
5084   // If there's a shift operator, handle it.
5085   ARM_AM::ShiftOpc ShiftType = ARM_AM::no_shift;
5086   unsigned ShiftImm = 0;
5087   if (Parser.getTok().is(AsmToken::Comma)) {
5088     Parser.Lex(); // Eat the ','.
5089     if (parseMemRegOffsetShift(ShiftType, ShiftImm))
5090       return true;
5091   }
5092 
5093   // Now we should have the closing ']'
5094   if (Parser.getTok().isNot(AsmToken::RBrac))
5095     return Error(Parser.getTok().getLoc(), "']' expected");
5096   E = Parser.getTok().getEndLoc();
5097   Parser.Lex(); // Eat right bracket token.
5098 
5099   Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, OffsetRegNum,
5100                                            ShiftType, ShiftImm, 0, isNegative,
5101                                            S, E));
5102 
5103   // If there's a pre-indexing writeback marker, '!', just add it as a token
5104   // operand.
5105   if (Parser.getTok().is(AsmToken::Exclaim)) {
5106     Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
5107     Parser.Lex(); // Eat the '!'.
5108   }
5109 
5110   return false;
5111 }
5112 
5113 /// parseMemRegOffsetShift - one of these two:
5114 ///   ( lsl | lsr | asr | ror ) , # shift_amount
5115 ///   rrx
5116 /// return true if it parses a shift otherwise it returns false.
5117 bool ARMAsmParser::parseMemRegOffsetShift(ARM_AM::ShiftOpc &St,
5118                                           unsigned &Amount) {
5119   MCAsmParser &Parser = getParser();
5120   SMLoc Loc = Parser.getTok().getLoc();
5121   const AsmToken &Tok = Parser.getTok();
5122   if (Tok.isNot(AsmToken::Identifier))
5123     return Error(Loc, "illegal shift operator");
5124   StringRef ShiftName = Tok.getString();
5125   if (ShiftName == "lsl" || ShiftName == "LSL" ||
5126       ShiftName == "asl" || ShiftName == "ASL")
5127     St = ARM_AM::lsl;
5128   else if (ShiftName == "lsr" || ShiftName == "LSR")
5129     St = ARM_AM::lsr;
5130   else if (ShiftName == "asr" || ShiftName == "ASR")
5131     St = ARM_AM::asr;
5132   else if (ShiftName == "ror" || ShiftName == "ROR")
5133     St = ARM_AM::ror;
5134   else if (ShiftName == "rrx" || ShiftName == "RRX")
5135     St = ARM_AM::rrx;
5136   else
5137     return Error(Loc, "illegal shift operator");
5138   Parser.Lex(); // Eat shift type token.
5139 
5140   // rrx stands alone.
5141   Amount = 0;
5142   if (St != ARM_AM::rrx) {
5143     Loc = Parser.getTok().getLoc();
5144     // A '#' and a shift amount.
5145     const AsmToken &HashTok = Parser.getTok();
5146     if (HashTok.isNot(AsmToken::Hash) &&
5147         HashTok.isNot(AsmToken::Dollar))
5148       return Error(HashTok.getLoc(), "'#' expected");
5149     Parser.Lex(); // Eat hash token.
5150 
5151     const MCExpr *Expr;
5152     if (getParser().parseExpression(Expr))
5153       return true;
5154     // Range check the immediate.
5155     // lsl, ror: 0 <= imm <= 31
5156     // lsr, asr: 0 <= imm <= 32
5157     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
5158     if (!CE)
5159       return Error(Loc, "shift amount must be an immediate");
5160     int64_t Imm = CE->getValue();
5161     if (Imm < 0 ||
5162         ((St == ARM_AM::lsl || St == ARM_AM::ror) && Imm > 31) ||
5163         ((St == ARM_AM::lsr || St == ARM_AM::asr) && Imm > 32))
5164       return Error(Loc, "immediate shift value out of range");
5165     // If <ShiftTy> #0, turn it into a no_shift.
5166     if (Imm == 0)
5167       St = ARM_AM::lsl;
5168     // For consistency, treat lsr #32 and asr #32 as having immediate value 0.
5169     if (Imm == 32)
5170       Imm = 0;
5171     Amount = Imm;
5172   }
5173 
5174   return false;
5175 }
5176 
5177 /// parseFPImm - A floating point immediate expression operand.
5178 OperandMatchResultTy
5179 ARMAsmParser::parseFPImm(OperandVector &Operands) {
5180   MCAsmParser &Parser = getParser();
5181   // Anything that can accept a floating point constant as an operand
5182   // needs to go through here, as the regular parseExpression is
5183   // integer only.
5184   //
5185   // This routine still creates a generic Immediate operand, containing
5186   // a bitcast of the 64-bit floating point value. The various operands
5187   // that accept floats can check whether the value is valid for them
5188   // via the standard is*() predicates.
5189 
5190   SMLoc S = Parser.getTok().getLoc();
5191 
5192   if (Parser.getTok().isNot(AsmToken::Hash) &&
5193       Parser.getTok().isNot(AsmToken::Dollar))
5194     return MatchOperand_NoMatch;
5195 
5196   // Disambiguate the VMOV forms that can accept an FP immediate.
5197   // vmov.f32 <sreg>, #imm
5198   // vmov.f64 <dreg>, #imm
5199   // vmov.f32 <dreg>, #imm  @ vector f32x2
5200   // vmov.f32 <qreg>, #imm  @ vector f32x4
5201   //
5202   // There are also the NEON VMOV instructions which expect an
5203   // integer constant. Make sure we don't try to parse an FPImm
5204   // for these:
5205   // vmov.i{8|16|32|64} <dreg|qreg>, #imm
5206   ARMOperand &TyOp = static_cast<ARMOperand &>(*Operands[2]);
5207   bool isVmovf = TyOp.isToken() &&
5208                  (TyOp.getToken() == ".f32" || TyOp.getToken() == ".f64" ||
5209                   TyOp.getToken() == ".f16");
5210   ARMOperand &Mnemonic = static_cast<ARMOperand &>(*Operands[0]);
5211   bool isFconst = Mnemonic.isToken() && (Mnemonic.getToken() == "fconstd" ||
5212                                          Mnemonic.getToken() == "fconsts");
5213   if (!(isVmovf || isFconst))
5214     return MatchOperand_NoMatch;
5215 
5216   Parser.Lex(); // Eat '#' or '$'.
5217 
5218   // Handle negation, as that still comes through as a separate token.
5219   bool isNegative = false;
5220   if (Parser.getTok().is(AsmToken::Minus)) {
5221     isNegative = true;
5222     Parser.Lex();
5223   }
5224   const AsmToken &Tok = Parser.getTok();
5225   SMLoc Loc = Tok.getLoc();
5226   if (Tok.is(AsmToken::Real) && isVmovf) {
5227     APFloat RealVal(APFloat::IEEEsingle(), Tok.getString());
5228     uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
5229     // If we had a '-' in front, toggle the sign bit.
5230     IntVal ^= (uint64_t)isNegative << 31;
5231     Parser.Lex(); // Eat the token.
5232     Operands.push_back(ARMOperand::CreateImm(
5233           MCConstantExpr::create(IntVal, getContext()),
5234           S, Parser.getTok().getLoc()));
5235     return MatchOperand_Success;
5236   }
5237   // Also handle plain integers. Instructions which allow floating point
5238   // immediates also allow a raw encoded 8-bit value.
5239   if (Tok.is(AsmToken::Integer) && isFconst) {
5240     int64_t Val = Tok.getIntVal();
5241     Parser.Lex(); // Eat the token.
5242     if (Val > 255 || Val < 0) {
5243       Error(Loc, "encoded floating point value out of range");
5244       return MatchOperand_ParseFail;
5245     }
5246     float RealVal = ARM_AM::getFPImmFloat(Val);
5247     Val = APFloat(RealVal).bitcastToAPInt().getZExtValue();
5248 
5249     Operands.push_back(ARMOperand::CreateImm(
5250         MCConstantExpr::create(Val, getContext()), S,
5251         Parser.getTok().getLoc()));
5252     return MatchOperand_Success;
5253   }
5254 
5255   Error(Loc, "invalid floating point immediate");
5256   return MatchOperand_ParseFail;
5257 }
5258 
5259 /// Parse a arm instruction operand.  For now this parses the operand regardless
5260 /// of the mnemonic.
5261 bool ARMAsmParser::parseOperand(OperandVector &Operands, StringRef Mnemonic) {
5262   MCAsmParser &Parser = getParser();
5263   SMLoc S, E;
5264 
5265   // Check if the current operand has a custom associated parser, if so, try to
5266   // custom parse the operand, or fallback to the general approach.
5267   OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
5268   if (ResTy == MatchOperand_Success)
5269     return false;
5270   // If there wasn't a custom match, try the generic matcher below. Otherwise,
5271   // there was a match, but an error occurred, in which case, just return that
5272   // the operand parsing failed.
5273   if (ResTy == MatchOperand_ParseFail)
5274     return true;
5275 
5276   switch (getLexer().getKind()) {
5277   default:
5278     Error(Parser.getTok().getLoc(), "unexpected token in operand");
5279     return true;
5280   case AsmToken::Identifier: {
5281     // If we've seen a branch mnemonic, the next operand must be a label.  This
5282     // is true even if the label is a register name.  So "br r1" means branch to
5283     // label "r1".
5284     bool ExpectLabel = Mnemonic == "b" || Mnemonic == "bl";
5285     if (!ExpectLabel) {
5286       if (!tryParseRegisterWithWriteBack(Operands))
5287         return false;
5288       int Res = tryParseShiftRegister(Operands);
5289       if (Res == 0) // success
5290         return false;
5291       else if (Res == -1) // irrecoverable error
5292         return true;
5293       // If this is VMRS, check for the apsr_nzcv operand.
5294       if (Mnemonic == "vmrs" &&
5295           Parser.getTok().getString().equals_lower("apsr_nzcv")) {
5296         S = Parser.getTok().getLoc();
5297         Parser.Lex();
5298         Operands.push_back(ARMOperand::CreateToken("APSR_nzcv", S));
5299         return false;
5300       }
5301     }
5302 
5303     // Fall though for the Identifier case that is not a register or a
5304     // special name.
5305     LLVM_FALLTHROUGH;
5306   }
5307   case AsmToken::LParen:  // parenthesized expressions like (_strcmp-4)
5308   case AsmToken::Integer: // things like 1f and 2b as a branch targets
5309   case AsmToken::String:  // quoted label names.
5310   case AsmToken::Dot: {   // . as a branch target
5311     // This was not a register so parse other operands that start with an
5312     // identifier (like labels) as expressions and create them as immediates.
5313     const MCExpr *IdVal;
5314     S = Parser.getTok().getLoc();
5315     if (getParser().parseExpression(IdVal))
5316       return true;
5317     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5318     Operands.push_back(ARMOperand::CreateImm(IdVal, S, E));
5319     return false;
5320   }
5321   case AsmToken::LBrac:
5322     return parseMemory(Operands);
5323   case AsmToken::LCurly:
5324     return parseRegisterList(Operands);
5325   case AsmToken::Dollar:
5326   case AsmToken::Hash:
5327     // #42 -> immediate.
5328     S = Parser.getTok().getLoc();
5329     Parser.Lex();
5330 
5331     if (Parser.getTok().isNot(AsmToken::Colon)) {
5332       bool isNegative = Parser.getTok().is(AsmToken::Minus);
5333       const MCExpr *ImmVal;
5334       if (getParser().parseExpression(ImmVal))
5335         return true;
5336       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ImmVal);
5337       if (CE) {
5338         int32_t Val = CE->getValue();
5339         if (isNegative && Val == 0)
5340           ImmVal = MCConstantExpr::create(std::numeric_limits<int32_t>::min(),
5341                                           getContext());
5342       }
5343       E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5344       Operands.push_back(ARMOperand::CreateImm(ImmVal, S, E));
5345 
5346       // There can be a trailing '!' on operands that we want as a separate
5347       // '!' Token operand. Handle that here. For example, the compatibility
5348       // alias for 'srsdb sp!, #imm' is 'srsdb #imm!'.
5349       if (Parser.getTok().is(AsmToken::Exclaim)) {
5350         Operands.push_back(ARMOperand::CreateToken(Parser.getTok().getString(),
5351                                                    Parser.getTok().getLoc()));
5352         Parser.Lex(); // Eat exclaim token
5353       }
5354       return false;
5355     }
5356     // w/ a ':' after the '#', it's just like a plain ':'.
5357     LLVM_FALLTHROUGH;
5358 
5359   case AsmToken::Colon: {
5360     S = Parser.getTok().getLoc();
5361     // ":lower16:" and ":upper16:" expression prefixes
5362     // FIXME: Check it's an expression prefix,
5363     // e.g. (FOO - :lower16:BAR) isn't legal.
5364     ARMMCExpr::VariantKind RefKind;
5365     if (parsePrefix(RefKind))
5366       return true;
5367 
5368     const MCExpr *SubExprVal;
5369     if (getParser().parseExpression(SubExprVal))
5370       return true;
5371 
5372     const MCExpr *ExprVal = ARMMCExpr::create(RefKind, SubExprVal,
5373                                               getContext());
5374     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5375     Operands.push_back(ARMOperand::CreateImm(ExprVal, S, E));
5376     return false;
5377   }
5378   case AsmToken::Equal: {
5379     S = Parser.getTok().getLoc();
5380     if (Mnemonic != "ldr") // only parse for ldr pseudo (e.g. ldr r0, =val)
5381       return Error(S, "unexpected token in operand");
5382     Parser.Lex(); // Eat '='
5383     const MCExpr *SubExprVal;
5384     if (getParser().parseExpression(SubExprVal))
5385       return true;
5386     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5387 
5388     // execute-only: we assume that assembly programmers know what they are
5389     // doing and allow literal pool creation here
5390     Operands.push_back(ARMOperand::CreateConstantPoolImm(SubExprVal, S, E));
5391     return false;
5392   }
5393   }
5394 }
5395 
5396 // parsePrefix - Parse ARM 16-bit relocations expression prefix, i.e.
5397 //  :lower16: and :upper16:.
5398 bool ARMAsmParser::parsePrefix(ARMMCExpr::VariantKind &RefKind) {
5399   MCAsmParser &Parser = getParser();
5400   RefKind = ARMMCExpr::VK_ARM_None;
5401 
5402   // consume an optional '#' (GNU compatibility)
5403   if (getLexer().is(AsmToken::Hash))
5404     Parser.Lex();
5405 
5406   // :lower16: and :upper16: modifiers
5407   assert(getLexer().is(AsmToken::Colon) && "expected a :");
5408   Parser.Lex(); // Eat ':'
5409 
5410   if (getLexer().isNot(AsmToken::Identifier)) {
5411     Error(Parser.getTok().getLoc(), "expected prefix identifier in operand");
5412     return true;
5413   }
5414 
5415   enum {
5416     COFF = (1 << MCObjectFileInfo::IsCOFF),
5417     ELF = (1 << MCObjectFileInfo::IsELF),
5418     MACHO = (1 << MCObjectFileInfo::IsMachO),
5419     WASM = (1 << MCObjectFileInfo::IsWasm),
5420   };
5421   static const struct PrefixEntry {
5422     const char *Spelling;
5423     ARMMCExpr::VariantKind VariantKind;
5424     uint8_t SupportedFormats;
5425   } PrefixEntries[] = {
5426     { "lower16", ARMMCExpr::VK_ARM_LO16, COFF | ELF | MACHO },
5427     { "upper16", ARMMCExpr::VK_ARM_HI16, COFF | ELF | MACHO },
5428   };
5429 
5430   StringRef IDVal = Parser.getTok().getIdentifier();
5431 
5432   const auto &Prefix =
5433       std::find_if(std::begin(PrefixEntries), std::end(PrefixEntries),
5434                    [&IDVal](const PrefixEntry &PE) {
5435                       return PE.Spelling == IDVal;
5436                    });
5437   if (Prefix == std::end(PrefixEntries)) {
5438     Error(Parser.getTok().getLoc(), "unexpected prefix in operand");
5439     return true;
5440   }
5441 
5442   uint8_t CurrentFormat;
5443   switch (getContext().getObjectFileInfo()->getObjectFileType()) {
5444   case MCObjectFileInfo::IsMachO:
5445     CurrentFormat = MACHO;
5446     break;
5447   case MCObjectFileInfo::IsELF:
5448     CurrentFormat = ELF;
5449     break;
5450   case MCObjectFileInfo::IsCOFF:
5451     CurrentFormat = COFF;
5452     break;
5453   case MCObjectFileInfo::IsWasm:
5454     CurrentFormat = WASM;
5455     break;
5456   }
5457 
5458   if (~Prefix->SupportedFormats & CurrentFormat) {
5459     Error(Parser.getTok().getLoc(),
5460           "cannot represent relocation in the current file format");
5461     return true;
5462   }
5463 
5464   RefKind = Prefix->VariantKind;
5465   Parser.Lex();
5466 
5467   if (getLexer().isNot(AsmToken::Colon)) {
5468     Error(Parser.getTok().getLoc(), "unexpected token after prefix");
5469     return true;
5470   }
5471   Parser.Lex(); // Eat the last ':'
5472 
5473   return false;
5474 }
5475 
5476 /// \brief Given a mnemonic, split out possible predication code and carry
5477 /// setting letters to form a canonical mnemonic and flags.
5478 //
5479 // FIXME: Would be nice to autogen this.
5480 // FIXME: This is a bit of a maze of special cases.
5481 StringRef ARMAsmParser::splitMnemonic(StringRef Mnemonic,
5482                                       unsigned &PredicationCode,
5483                                       bool &CarrySetting,
5484                                       unsigned &ProcessorIMod,
5485                                       StringRef &ITMask) {
5486   PredicationCode = ARMCC::AL;
5487   CarrySetting = false;
5488   ProcessorIMod = 0;
5489 
5490   // Ignore some mnemonics we know aren't predicated forms.
5491   //
5492   // FIXME: Would be nice to autogen this.
5493   if ((Mnemonic == "movs" && isThumb()) ||
5494       Mnemonic == "teq"   || Mnemonic == "vceq"   || Mnemonic == "svc"   ||
5495       Mnemonic == "mls"   || Mnemonic == "smmls"  || Mnemonic == "vcls"  ||
5496       Mnemonic == "vmls"  || Mnemonic == "vnmls"  || Mnemonic == "vacge" ||
5497       Mnemonic == "vcge"  || Mnemonic == "vclt"   || Mnemonic == "vacgt" ||
5498       Mnemonic == "vaclt" || Mnemonic == "vacle"  || Mnemonic == "hlt" ||
5499       Mnemonic == "vcgt"  || Mnemonic == "vcle"   || Mnemonic == "smlal" ||
5500       Mnemonic == "umaal" || Mnemonic == "umlal"  || Mnemonic == "vabal" ||
5501       Mnemonic == "vmlal" || Mnemonic == "vpadal" || Mnemonic == "vqdmlal" ||
5502       Mnemonic == "fmuls" || Mnemonic == "vmaxnm" || Mnemonic == "vminnm" ||
5503       Mnemonic == "vcvta" || Mnemonic == "vcvtn"  || Mnemonic == "vcvtp" ||
5504       Mnemonic == "vcvtm" || Mnemonic == "vrinta" || Mnemonic == "vrintn" ||
5505       Mnemonic == "vrintp" || Mnemonic == "vrintm" || Mnemonic == "hvc" ||
5506       Mnemonic.startswith("vsel") || Mnemonic == "vins" || Mnemonic == "vmovx" ||
5507       Mnemonic == "bxns"  || Mnemonic == "blxns" ||
5508       Mnemonic == "vudot" || Mnemonic == "vsdot" ||
5509       Mnemonic == "vcmla" || Mnemonic == "vcadd")
5510     return Mnemonic;
5511 
5512   // First, split out any predication code. Ignore mnemonics we know aren't
5513   // predicated but do have a carry-set and so weren't caught above.
5514   if (Mnemonic != "adcs" && Mnemonic != "bics" && Mnemonic != "movs" &&
5515       Mnemonic != "muls" && Mnemonic != "smlals" && Mnemonic != "smulls" &&
5516       Mnemonic != "umlals" && Mnemonic != "umulls" && Mnemonic != "lsls" &&
5517       Mnemonic != "sbcs" && Mnemonic != "rscs") {
5518     unsigned CC = ARMCondCodeFromString(Mnemonic.substr(Mnemonic.size()-2));
5519     if (CC != ~0U) {
5520       Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 2);
5521       PredicationCode = CC;
5522     }
5523   }
5524 
5525   // Next, determine if we have a carry setting bit. We explicitly ignore all
5526   // the instructions we know end in 's'.
5527   if (Mnemonic.endswith("s") &&
5528       !(Mnemonic == "cps" || Mnemonic == "mls" ||
5529         Mnemonic == "mrs" || Mnemonic == "smmls" || Mnemonic == "vabs" ||
5530         Mnemonic == "vcls" || Mnemonic == "vmls" || Mnemonic == "vmrs" ||
5531         Mnemonic == "vnmls" || Mnemonic == "vqabs" || Mnemonic == "vrecps" ||
5532         Mnemonic == "vrsqrts" || Mnemonic == "srs" || Mnemonic == "flds" ||
5533         Mnemonic == "fmrs" || Mnemonic == "fsqrts" || Mnemonic == "fsubs" ||
5534         Mnemonic == "fsts" || Mnemonic == "fcpys" || Mnemonic == "fdivs" ||
5535         Mnemonic == "fmuls" || Mnemonic == "fcmps" || Mnemonic == "fcmpzs" ||
5536         Mnemonic == "vfms" || Mnemonic == "vfnms" || Mnemonic == "fconsts" ||
5537         Mnemonic == "bxns" || Mnemonic == "blxns" ||
5538         (Mnemonic == "movs" && isThumb()))) {
5539     Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 1);
5540     CarrySetting = true;
5541   }
5542 
5543   // The "cps" instruction can have a interrupt mode operand which is glued into
5544   // the mnemonic. Check if this is the case, split it and parse the imod op
5545   if (Mnemonic.startswith("cps")) {
5546     // Split out any imod code.
5547     unsigned IMod =
5548       StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2, 2))
5549       .Case("ie", ARM_PROC::IE)
5550       .Case("id", ARM_PROC::ID)
5551       .Default(~0U);
5552     if (IMod != ~0U) {
5553       Mnemonic = Mnemonic.slice(0, Mnemonic.size()-2);
5554       ProcessorIMod = IMod;
5555     }
5556   }
5557 
5558   // The "it" instruction has the condition mask on the end of the mnemonic.
5559   if (Mnemonic.startswith("it")) {
5560     ITMask = Mnemonic.slice(2, Mnemonic.size());
5561     Mnemonic = Mnemonic.slice(0, 2);
5562   }
5563 
5564   return Mnemonic;
5565 }
5566 
5567 /// \brief Given a canonical mnemonic, determine if the instruction ever allows
5568 /// inclusion of carry set or predication code operands.
5569 //
5570 // FIXME: It would be nice to autogen this.
5571 void ARMAsmParser::getMnemonicAcceptInfo(StringRef Mnemonic, StringRef FullInst,
5572                                          bool &CanAcceptCarrySet,
5573                                          bool &CanAcceptPredicationCode) {
5574   CanAcceptCarrySet =
5575       Mnemonic == "and" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
5576       Mnemonic == "rrx" || Mnemonic == "ror" || Mnemonic == "sub" ||
5577       Mnemonic == "add" || Mnemonic == "adc" || Mnemonic == "mul" ||
5578       Mnemonic == "bic" || Mnemonic == "asr" || Mnemonic == "orr" ||
5579       Mnemonic == "mvn" || Mnemonic == "rsb" || Mnemonic == "rsc" ||
5580       Mnemonic == "orn" || Mnemonic == "sbc" || Mnemonic == "eor" ||
5581       Mnemonic == "neg" || Mnemonic == "vfm" || Mnemonic == "vfnm" ||
5582       (!isThumb() &&
5583        (Mnemonic == "smull" || Mnemonic == "mov" || Mnemonic == "mla" ||
5584         Mnemonic == "smlal" || Mnemonic == "umlal" || Mnemonic == "umull"));
5585 
5586   if (Mnemonic == "bkpt" || Mnemonic == "cbnz" || Mnemonic == "setend" ||
5587       Mnemonic == "cps" || Mnemonic == "it" || Mnemonic == "cbz" ||
5588       Mnemonic == "trap" || Mnemonic == "hlt" || Mnemonic == "udf" ||
5589       Mnemonic.startswith("crc32") || Mnemonic.startswith("cps") ||
5590       Mnemonic.startswith("vsel") || Mnemonic == "vmaxnm" ||
5591       Mnemonic == "vminnm" || Mnemonic == "vcvta" || Mnemonic == "vcvtn" ||
5592       Mnemonic == "vcvtp" || Mnemonic == "vcvtm" || Mnemonic == "vrinta" ||
5593       Mnemonic == "vrintn" || Mnemonic == "vrintp" || Mnemonic == "vrintm" ||
5594       Mnemonic.startswith("aes") || Mnemonic == "hvc" || Mnemonic == "setpan" ||
5595       Mnemonic.startswith("sha1") || Mnemonic.startswith("sha256") ||
5596       (FullInst.startswith("vmull") && FullInst.endswith(".p64")) ||
5597       Mnemonic == "vmovx" || Mnemonic == "vins" ||
5598       Mnemonic == "vudot" || Mnemonic == "vsdot" ||
5599       Mnemonic == "vcmla" || Mnemonic == "vcadd") {
5600     // These mnemonics are never predicable
5601     CanAcceptPredicationCode = false;
5602   } else if (!isThumb()) {
5603     // Some instructions are only predicable in Thumb mode
5604     CanAcceptPredicationCode =
5605         Mnemonic != "cdp2" && Mnemonic != "clrex" && Mnemonic != "mcr2" &&
5606         Mnemonic != "mcrr2" && Mnemonic != "mrc2" && Mnemonic != "mrrc2" &&
5607         Mnemonic != "dmb" && Mnemonic != "dfb" && Mnemonic != "dsb" &&
5608         Mnemonic != "isb" && Mnemonic != "pld" && Mnemonic != "pli" &&
5609         Mnemonic != "pldw" && Mnemonic != "ldc2" && Mnemonic != "ldc2l" &&
5610         Mnemonic != "stc2" && Mnemonic != "stc2l" &&
5611         !Mnemonic.startswith("rfe") && !Mnemonic.startswith("srs");
5612   } else if (isThumbOne()) {
5613     if (hasV6MOps())
5614       CanAcceptPredicationCode = Mnemonic != "movs";
5615     else
5616       CanAcceptPredicationCode = Mnemonic != "nop" && Mnemonic != "movs";
5617   } else
5618     CanAcceptPredicationCode = true;
5619 }
5620 
5621 // \brief Some Thumb instructions have two operand forms that are not
5622 // available as three operand, convert to two operand form if possible.
5623 //
5624 // FIXME: We would really like to be able to tablegen'erate this.
5625 void ARMAsmParser::tryConvertingToTwoOperandForm(StringRef Mnemonic,
5626                                                  bool CarrySetting,
5627                                                  OperandVector &Operands) {
5628   if (Operands.size() != 6)
5629     return;
5630 
5631   const auto &Op3 = static_cast<ARMOperand &>(*Operands[3]);
5632         auto &Op4 = static_cast<ARMOperand &>(*Operands[4]);
5633   if (!Op3.isReg() || !Op4.isReg())
5634     return;
5635 
5636   auto Op3Reg = Op3.getReg();
5637   auto Op4Reg = Op4.getReg();
5638 
5639   // For most Thumb2 cases we just generate the 3 operand form and reduce
5640   // it in processInstruction(), but the 3 operand form of ADD (t2ADDrr)
5641   // won't accept SP or PC so we do the transformation here taking care
5642   // with immediate range in the 'add sp, sp #imm' case.
5643   auto &Op5 = static_cast<ARMOperand &>(*Operands[5]);
5644   if (isThumbTwo()) {
5645     if (Mnemonic != "add")
5646       return;
5647     bool TryTransform = Op3Reg == ARM::PC || Op4Reg == ARM::PC ||
5648                         (Op5.isReg() && Op5.getReg() == ARM::PC);
5649     if (!TryTransform) {
5650       TryTransform = (Op3Reg == ARM::SP || Op4Reg == ARM::SP ||
5651                       (Op5.isReg() && Op5.getReg() == ARM::SP)) &&
5652                      !(Op3Reg == ARM::SP && Op4Reg == ARM::SP &&
5653                        Op5.isImm() && !Op5.isImm0_508s4());
5654     }
5655     if (!TryTransform)
5656       return;
5657   } else if (!isThumbOne())
5658     return;
5659 
5660   if (!(Mnemonic == "add" || Mnemonic == "sub" || Mnemonic == "and" ||
5661         Mnemonic == "eor" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
5662         Mnemonic == "asr" || Mnemonic == "adc" || Mnemonic == "sbc" ||
5663         Mnemonic == "ror" || Mnemonic == "orr" || Mnemonic == "bic"))
5664     return;
5665 
5666   // If first 2 operands of a 3 operand instruction are the same
5667   // then transform to 2 operand version of the same instruction
5668   // e.g. 'adds r0, r0, #1' transforms to 'adds r0, #1'
5669   bool Transform = Op3Reg == Op4Reg;
5670 
5671   // For communtative operations, we might be able to transform if we swap
5672   // Op4 and Op5.  The 'ADD Rdm, SP, Rdm' form is already handled specially
5673   // as tADDrsp.
5674   const ARMOperand *LastOp = &Op5;
5675   bool Swap = false;
5676   if (!Transform && Op5.isReg() && Op3Reg == Op5.getReg() &&
5677       ((Mnemonic == "add" && Op4Reg != ARM::SP) ||
5678        Mnemonic == "and" || Mnemonic == "eor" ||
5679        Mnemonic == "adc" || Mnemonic == "orr")) {
5680     Swap = true;
5681     LastOp = &Op4;
5682     Transform = true;
5683   }
5684 
5685   // If both registers are the same then remove one of them from
5686   // the operand list, with certain exceptions.
5687   if (Transform) {
5688     // Don't transform 'adds Rd, Rd, Rm' or 'sub{s} Rd, Rd, Rm' because the
5689     // 2 operand forms don't exist.
5690     if (((Mnemonic == "add" && CarrySetting) || Mnemonic == "sub") &&
5691         LastOp->isReg())
5692       Transform = false;
5693 
5694     // Don't transform 'add/sub{s} Rd, Rd, #imm' if the immediate fits into
5695     // 3-bits because the ARMARM says not to.
5696     if ((Mnemonic == "add" || Mnemonic == "sub") && LastOp->isImm0_7())
5697       Transform = false;
5698   }
5699 
5700   if (Transform) {
5701     if (Swap)
5702       std::swap(Op4, Op5);
5703     Operands.erase(Operands.begin() + 3);
5704   }
5705 }
5706 
5707 bool ARMAsmParser::shouldOmitCCOutOperand(StringRef Mnemonic,
5708                                           OperandVector &Operands) {
5709   // FIXME: This is all horribly hacky. We really need a better way to deal
5710   // with optional operands like this in the matcher table.
5711 
5712   // The 'mov' mnemonic is special. One variant has a cc_out operand, while
5713   // another does not. Specifically, the MOVW instruction does not. So we
5714   // special case it here and remove the defaulted (non-setting) cc_out
5715   // operand if that's the instruction we're trying to match.
5716   //
5717   // We do this as post-processing of the explicit operands rather than just
5718   // conditionally adding the cc_out in the first place because we need
5719   // to check the type of the parsed immediate operand.
5720   if (Mnemonic == "mov" && Operands.size() > 4 && !isThumb() &&
5721       !static_cast<ARMOperand &>(*Operands[4]).isModImm() &&
5722       static_cast<ARMOperand &>(*Operands[4]).isImm0_65535Expr() &&
5723       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0)
5724     return true;
5725 
5726   // Register-register 'add' for thumb does not have a cc_out operand
5727   // when there are only two register operands.
5728   if (isThumb() && Mnemonic == "add" && Operands.size() == 5 &&
5729       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5730       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5731       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0)
5732     return true;
5733   // Register-register 'add' for thumb does not have a cc_out operand
5734   // when it's an ADD Rdm, SP, {Rdm|#imm0_255} instruction. We do
5735   // have to check the immediate range here since Thumb2 has a variant
5736   // that can handle a different range and has a cc_out operand.
5737   if (((isThumb() && Mnemonic == "add") ||
5738        (isThumbTwo() && Mnemonic == "sub")) &&
5739       Operands.size() == 6 && static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5740       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5741       static_cast<ARMOperand &>(*Operands[4]).getReg() == ARM::SP &&
5742       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5743       ((Mnemonic == "add" && static_cast<ARMOperand &>(*Operands[5]).isReg()) ||
5744        static_cast<ARMOperand &>(*Operands[5]).isImm0_1020s4()))
5745     return true;
5746   // For Thumb2, add/sub immediate does not have a cc_out operand for the
5747   // imm0_4095 variant. That's the least-preferred variant when
5748   // selecting via the generic "add" mnemonic, so to know that we
5749   // should remove the cc_out operand, we have to explicitly check that
5750   // it's not one of the other variants. Ugh.
5751   if (isThumbTwo() && (Mnemonic == "add" || Mnemonic == "sub") &&
5752       Operands.size() == 6 && static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5753       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5754       static_cast<ARMOperand &>(*Operands[5]).isImm()) {
5755     // Nest conditions rather than one big 'if' statement for readability.
5756     //
5757     // If both registers are low, we're in an IT block, and the immediate is
5758     // in range, we should use encoding T1 instead, which has a cc_out.
5759     if (inITBlock() &&
5760         isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) &&
5761         isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) &&
5762         static_cast<ARMOperand &>(*Operands[5]).isImm0_7())
5763       return false;
5764     // Check against T3. If the second register is the PC, this is an
5765     // alternate form of ADR, which uses encoding T4, so check for that too.
5766     if (static_cast<ARMOperand &>(*Operands[4]).getReg() != ARM::PC &&
5767         static_cast<ARMOperand &>(*Operands[5]).isT2SOImm())
5768       return false;
5769 
5770     // Otherwise, we use encoding T4, which does not have a cc_out
5771     // operand.
5772     return true;
5773   }
5774 
5775   // The thumb2 multiply instruction doesn't have a CCOut register, so
5776   // if we have a "mul" mnemonic in Thumb mode, check if we'll be able to
5777   // use the 16-bit encoding or not.
5778   if (isThumbTwo() && Mnemonic == "mul" && Operands.size() == 6 &&
5779       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5780       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5781       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5782       static_cast<ARMOperand &>(*Operands[5]).isReg() &&
5783       // If the registers aren't low regs, the destination reg isn't the
5784       // same as one of the source regs, or the cc_out operand is zero
5785       // outside of an IT block, we have to use the 32-bit encoding, so
5786       // remove the cc_out operand.
5787       (!isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) ||
5788        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) ||
5789        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[5]).getReg()) ||
5790        !inITBlock() || (static_cast<ARMOperand &>(*Operands[3]).getReg() !=
5791                             static_cast<ARMOperand &>(*Operands[5]).getReg() &&
5792                         static_cast<ARMOperand &>(*Operands[3]).getReg() !=
5793                             static_cast<ARMOperand &>(*Operands[4]).getReg())))
5794     return true;
5795 
5796   // Also check the 'mul' syntax variant that doesn't specify an explicit
5797   // destination register.
5798   if (isThumbTwo() && Mnemonic == "mul" && Operands.size() == 5 &&
5799       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5800       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5801       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5802       // If the registers aren't low regs  or the cc_out operand is zero
5803       // outside of an IT block, we have to use the 32-bit encoding, so
5804       // remove the cc_out operand.
5805       (!isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) ||
5806        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) ||
5807        !inITBlock()))
5808     return true;
5809 
5810   // Register-register 'add/sub' for thumb does not have a cc_out operand
5811   // when it's an ADD/SUB SP, #imm. Be lenient on count since there's also
5812   // the "add/sub SP, SP, #imm" version. If the follow-up operands aren't
5813   // right, this will result in better diagnostics (which operand is off)
5814   // anyway.
5815   if (isThumb() && (Mnemonic == "add" || Mnemonic == "sub") &&
5816       (Operands.size() == 5 || Operands.size() == 6) &&
5817       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5818       static_cast<ARMOperand &>(*Operands[3]).getReg() == ARM::SP &&
5819       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5820       (static_cast<ARMOperand &>(*Operands[4]).isImm() ||
5821        (Operands.size() == 6 &&
5822         static_cast<ARMOperand &>(*Operands[5]).isImm())))
5823     return true;
5824 
5825   return false;
5826 }
5827 
5828 bool ARMAsmParser::shouldOmitPredicateOperand(StringRef Mnemonic,
5829                                               OperandVector &Operands) {
5830   // VRINT{Z, X} have a predicate operand in VFP, but not in NEON
5831   unsigned RegIdx = 3;
5832   if ((Mnemonic == "vrintz" || Mnemonic == "vrintx") &&
5833       (static_cast<ARMOperand &>(*Operands[2]).getToken() == ".f32" ||
5834        static_cast<ARMOperand &>(*Operands[2]).getToken() == ".f16")) {
5835     if (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
5836         (static_cast<ARMOperand &>(*Operands[3]).getToken() == ".f32" ||
5837          static_cast<ARMOperand &>(*Operands[3]).getToken() == ".f16"))
5838       RegIdx = 4;
5839 
5840     if (static_cast<ARMOperand &>(*Operands[RegIdx]).isReg() &&
5841         (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(
5842              static_cast<ARMOperand &>(*Operands[RegIdx]).getReg()) ||
5843          ARMMCRegisterClasses[ARM::QPRRegClassID].contains(
5844              static_cast<ARMOperand &>(*Operands[RegIdx]).getReg())))
5845       return true;
5846   }
5847   return false;
5848 }
5849 
5850 static bool isDataTypeToken(StringRef Tok) {
5851   return Tok == ".8" || Tok == ".16" || Tok == ".32" || Tok == ".64" ||
5852     Tok == ".i8" || Tok == ".i16" || Tok == ".i32" || Tok == ".i64" ||
5853     Tok == ".u8" || Tok == ".u16" || Tok == ".u32" || Tok == ".u64" ||
5854     Tok == ".s8" || Tok == ".s16" || Tok == ".s32" || Tok == ".s64" ||
5855     Tok == ".p8" || Tok == ".p16" || Tok == ".f32" || Tok == ".f64" ||
5856     Tok == ".f" || Tok == ".d";
5857 }
5858 
5859 // FIXME: This bit should probably be handled via an explicit match class
5860 // in the .td files that matches the suffix instead of having it be
5861 // a literal string token the way it is now.
5862 static bool doesIgnoreDataTypeSuffix(StringRef Mnemonic, StringRef DT) {
5863   return Mnemonic.startswith("vldm") || Mnemonic.startswith("vstm");
5864 }
5865 
5866 static void applyMnemonicAliases(StringRef &Mnemonic, uint64_t Features,
5867                                  unsigned VariantID);
5868 
5869 // The GNU assembler has aliases of ldrd and strd with the second register
5870 // omitted. We don't have a way to do that in tablegen, so fix it up here.
5871 //
5872 // We have to be careful to not emit an invalid Rt2 here, because the rest of
5873 // the assmebly parser could then generate confusing diagnostics refering to
5874 // it. If we do find anything that prevents us from doing the transformation we
5875 // bail out, and let the assembly parser report an error on the instruction as
5876 // it is written.
5877 void ARMAsmParser::fixupGNULDRDAlias(StringRef Mnemonic,
5878                                      OperandVector &Operands) {
5879   if (Mnemonic != "ldrd" && Mnemonic != "strd")
5880     return;
5881   if (Operands.size() < 4)
5882     return;
5883 
5884   ARMOperand &Op2 = static_cast<ARMOperand &>(*Operands[2]);
5885   ARMOperand &Op3 = static_cast<ARMOperand &>(*Operands[3]);
5886 
5887   if (!Op2.isReg())
5888     return;
5889   if (!Op3.isMem())
5890     return;
5891 
5892   const MCRegisterClass &GPR = MRI->getRegClass(ARM::GPRRegClassID);
5893   if (!GPR.contains(Op2.getReg()))
5894     return;
5895 
5896   unsigned RtEncoding = MRI->getEncodingValue(Op2.getReg());
5897   if (!isThumb() && (RtEncoding & 1)) {
5898     // In ARM mode, the registers must be from an aligned pair, this
5899     // restriction does not apply in Thumb mode.
5900     return;
5901   }
5902   if (Op2.getReg() == ARM::PC)
5903     return;
5904   unsigned PairedReg = GPR.getRegister(RtEncoding + 1);
5905   if (!PairedReg || PairedReg == ARM::PC ||
5906       (PairedReg == ARM::SP && !hasV8Ops()))
5907     return;
5908 
5909   Operands.insert(
5910       Operands.begin() + 3,
5911       ARMOperand::CreateReg(PairedReg, Op2.getStartLoc(), Op2.getEndLoc()));
5912 }
5913 
5914 /// Parse an arm instruction mnemonic followed by its operands.
5915 bool ARMAsmParser::ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
5916                                     SMLoc NameLoc, OperandVector &Operands) {
5917   MCAsmParser &Parser = getParser();
5918 
5919   // Apply mnemonic aliases before doing anything else, as the destination
5920   // mnemonic may include suffices and we want to handle them normally.
5921   // The generic tblgen'erated code does this later, at the start of
5922   // MatchInstructionImpl(), but that's too late for aliases that include
5923   // any sort of suffix.
5924   uint64_t AvailableFeatures = getAvailableFeatures();
5925   unsigned AssemblerDialect = getParser().getAssemblerDialect();
5926   applyMnemonicAliases(Name, AvailableFeatures, AssemblerDialect);
5927 
5928   // First check for the ARM-specific .req directive.
5929   if (Parser.getTok().is(AsmToken::Identifier) &&
5930       Parser.getTok().getIdentifier() == ".req") {
5931     parseDirectiveReq(Name, NameLoc);
5932     // We always return 'error' for this, as we're done with this
5933     // statement and don't need to match the 'instruction."
5934     return true;
5935   }
5936 
5937   // Create the leading tokens for the mnemonic, split by '.' characters.
5938   size_t Start = 0, Next = Name.find('.');
5939   StringRef Mnemonic = Name.slice(Start, Next);
5940 
5941   // Split out the predication code and carry setting flag from the mnemonic.
5942   unsigned PredicationCode;
5943   unsigned ProcessorIMod;
5944   bool CarrySetting;
5945   StringRef ITMask;
5946   Mnemonic = splitMnemonic(Mnemonic, PredicationCode, CarrySetting,
5947                            ProcessorIMod, ITMask);
5948 
5949   // In Thumb1, only the branch (B) instruction can be predicated.
5950   if (isThumbOne() && PredicationCode != ARMCC::AL && Mnemonic != "b") {
5951     return Error(NameLoc, "conditional execution not supported in Thumb1");
5952   }
5953 
5954   Operands.push_back(ARMOperand::CreateToken(Mnemonic, NameLoc));
5955 
5956   // Handle the IT instruction ITMask. Convert it to a bitmask. This
5957   // is the mask as it will be for the IT encoding if the conditional
5958   // encoding has a '1' as it's bit0 (i.e. 't' ==> '1'). In the case
5959   // where the conditional bit0 is zero, the instruction post-processing
5960   // will adjust the mask accordingly.
5961   if (Mnemonic == "it") {
5962     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + 2);
5963     if (ITMask.size() > 3) {
5964       return Error(Loc, "too many conditions on IT instruction");
5965     }
5966     unsigned Mask = 8;
5967     for (unsigned i = ITMask.size(); i != 0; --i) {
5968       char pos = ITMask[i - 1];
5969       if (pos != 't' && pos != 'e') {
5970         return Error(Loc, "illegal IT block condition mask '" + ITMask + "'");
5971       }
5972       Mask >>= 1;
5973       if (ITMask[i - 1] == 't')
5974         Mask |= 8;
5975     }
5976     Operands.push_back(ARMOperand::CreateITMask(Mask, Loc));
5977   }
5978 
5979   // FIXME: This is all a pretty gross hack. We should automatically handle
5980   // optional operands like this via tblgen.
5981 
5982   // Next, add the CCOut and ConditionCode operands, if needed.
5983   //
5984   // For mnemonics which can ever incorporate a carry setting bit or predication
5985   // code, our matching model involves us always generating CCOut and
5986   // ConditionCode operands to match the mnemonic "as written" and then we let
5987   // the matcher deal with finding the right instruction or generating an
5988   // appropriate error.
5989   bool CanAcceptCarrySet, CanAcceptPredicationCode;
5990   getMnemonicAcceptInfo(Mnemonic, Name, CanAcceptCarrySet, CanAcceptPredicationCode);
5991 
5992   // If we had a carry-set on an instruction that can't do that, issue an
5993   // error.
5994   if (!CanAcceptCarrySet && CarrySetting) {
5995     return Error(NameLoc, "instruction '" + Mnemonic +
5996                  "' can not set flags, but 's' suffix specified");
5997   }
5998   // If we had a predication code on an instruction that can't do that, issue an
5999   // error.
6000   if (!CanAcceptPredicationCode && PredicationCode != ARMCC::AL) {
6001     return Error(NameLoc, "instruction '" + Mnemonic +
6002                  "' is not predicable, but condition code specified");
6003   }
6004 
6005   // Add the carry setting operand, if necessary.
6006   if (CanAcceptCarrySet) {
6007     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size());
6008     Operands.push_back(ARMOperand::CreateCCOut(CarrySetting ? ARM::CPSR : 0,
6009                                                Loc));
6010   }
6011 
6012   // Add the predication code operand, if necessary.
6013   if (CanAcceptPredicationCode) {
6014     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size() +
6015                                       CarrySetting);
6016     Operands.push_back(ARMOperand::CreateCondCode(
6017                          ARMCC::CondCodes(PredicationCode), Loc));
6018   }
6019 
6020   // Add the processor imod operand, if necessary.
6021   if (ProcessorIMod) {
6022     Operands.push_back(ARMOperand::CreateImm(
6023           MCConstantExpr::create(ProcessorIMod, getContext()),
6024                                  NameLoc, NameLoc));
6025   } else if (Mnemonic == "cps" && isMClass()) {
6026     return Error(NameLoc, "instruction 'cps' requires effect for M-class");
6027   }
6028 
6029   // Add the remaining tokens in the mnemonic.
6030   while (Next != StringRef::npos) {
6031     Start = Next;
6032     Next = Name.find('.', Start + 1);
6033     StringRef ExtraToken = Name.slice(Start, Next);
6034 
6035     // Some NEON instructions have an optional datatype suffix that is
6036     // completely ignored. Check for that.
6037     if (isDataTypeToken(ExtraToken) &&
6038         doesIgnoreDataTypeSuffix(Mnemonic, ExtraToken))
6039       continue;
6040 
6041     // For for ARM mode generate an error if the .n qualifier is used.
6042     if (ExtraToken == ".n" && !isThumb()) {
6043       SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Start);
6044       return Error(Loc, "instruction with .n (narrow) qualifier not allowed in "
6045                    "arm mode");
6046     }
6047 
6048     // The .n qualifier is always discarded as that is what the tables
6049     // and matcher expect.  In ARM mode the .w qualifier has no effect,
6050     // so discard it to avoid errors that can be caused by the matcher.
6051     if (ExtraToken != ".n" && (isThumb() || ExtraToken != ".w")) {
6052       SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Start);
6053       Operands.push_back(ARMOperand::CreateToken(ExtraToken, Loc));
6054     }
6055   }
6056 
6057   // Read the remaining operands.
6058   if (getLexer().isNot(AsmToken::EndOfStatement)) {
6059     // Read the first operand.
6060     if (parseOperand(Operands, Mnemonic)) {
6061       return true;
6062     }
6063 
6064     while (parseOptionalToken(AsmToken::Comma)) {
6065       // Parse and remember the operand.
6066       if (parseOperand(Operands, Mnemonic)) {
6067         return true;
6068       }
6069     }
6070   }
6071 
6072   if (parseToken(AsmToken::EndOfStatement, "unexpected token in argument list"))
6073     return true;
6074 
6075   tryConvertingToTwoOperandForm(Mnemonic, CarrySetting, Operands);
6076 
6077   // Some instructions, mostly Thumb, have forms for the same mnemonic that
6078   // do and don't have a cc_out optional-def operand. With some spot-checks
6079   // of the operand list, we can figure out which variant we're trying to
6080   // parse and adjust accordingly before actually matching. We shouldn't ever
6081   // try to remove a cc_out operand that was explicitly set on the
6082   // mnemonic, of course (CarrySetting == true). Reason number #317 the
6083   // table driven matcher doesn't fit well with the ARM instruction set.
6084   if (!CarrySetting && shouldOmitCCOutOperand(Mnemonic, Operands))
6085     Operands.erase(Operands.begin() + 1);
6086 
6087   // Some instructions have the same mnemonic, but don't always
6088   // have a predicate. Distinguish them here and delete the
6089   // predicate if needed.
6090   if (PredicationCode == ARMCC::AL &&
6091       shouldOmitPredicateOperand(Mnemonic, Operands))
6092     Operands.erase(Operands.begin() + 1);
6093 
6094   // ARM mode 'blx' need special handling, as the register operand version
6095   // is predicable, but the label operand version is not. So, we can't rely
6096   // on the Mnemonic based checking to correctly figure out when to put
6097   // a k_CondCode operand in the list. If we're trying to match the label
6098   // version, remove the k_CondCode operand here.
6099   if (!isThumb() && Mnemonic == "blx" && Operands.size() == 3 &&
6100       static_cast<ARMOperand &>(*Operands[2]).isImm())
6101     Operands.erase(Operands.begin() + 1);
6102 
6103   // Adjust operands of ldrexd/strexd to MCK_GPRPair.
6104   // ldrexd/strexd require even/odd GPR pair. To enforce this constraint,
6105   // a single GPRPair reg operand is used in the .td file to replace the two
6106   // GPRs. However, when parsing from asm, the two GRPs cannot be automatically
6107   // expressed as a GPRPair, so we have to manually merge them.
6108   // FIXME: We would really like to be able to tablegen'erate this.
6109   if (!isThumb() && Operands.size() > 4 &&
6110       (Mnemonic == "ldrexd" || Mnemonic == "strexd" || Mnemonic == "ldaexd" ||
6111        Mnemonic == "stlexd")) {
6112     bool isLoad = (Mnemonic == "ldrexd" || Mnemonic == "ldaexd");
6113     unsigned Idx = isLoad ? 2 : 3;
6114     ARMOperand &Op1 = static_cast<ARMOperand &>(*Operands[Idx]);
6115     ARMOperand &Op2 = static_cast<ARMOperand &>(*Operands[Idx + 1]);
6116 
6117     const MCRegisterClass& MRC = MRI->getRegClass(ARM::GPRRegClassID);
6118     // Adjust only if Op1 and Op2 are GPRs.
6119     if (Op1.isReg() && Op2.isReg() && MRC.contains(Op1.getReg()) &&
6120         MRC.contains(Op2.getReg())) {
6121       unsigned Reg1 = Op1.getReg();
6122       unsigned Reg2 = Op2.getReg();
6123       unsigned Rt = MRI->getEncodingValue(Reg1);
6124       unsigned Rt2 = MRI->getEncodingValue(Reg2);
6125 
6126       // Rt2 must be Rt + 1 and Rt must be even.
6127       if (Rt + 1 != Rt2 || (Rt & 1)) {
6128         return Error(Op2.getStartLoc(),
6129                      isLoad ? "destination operands must be sequential"
6130                             : "source operands must be sequential");
6131       }
6132       unsigned NewReg = MRI->getMatchingSuperReg(Reg1, ARM::gsub_0,
6133           &(MRI->getRegClass(ARM::GPRPairRegClassID)));
6134       Operands[Idx] =
6135           ARMOperand::CreateReg(NewReg, Op1.getStartLoc(), Op2.getEndLoc());
6136       Operands.erase(Operands.begin() + Idx + 1);
6137     }
6138   }
6139 
6140   // GNU Assembler extension (compatibility).
6141   fixupGNULDRDAlias(Mnemonic, Operands);
6142 
6143   // FIXME: As said above, this is all a pretty gross hack.  This instruction
6144   // does not fit with other "subs" and tblgen.
6145   // Adjust operands of B9.3.19 SUBS PC, LR, #imm (Thumb2) system instruction
6146   // so the Mnemonic is the original name "subs" and delete the predicate
6147   // operand so it will match the table entry.
6148   if (isThumbTwo() && Mnemonic == "sub" && Operands.size() == 6 &&
6149       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6150       static_cast<ARMOperand &>(*Operands[3]).getReg() == ARM::PC &&
6151       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
6152       static_cast<ARMOperand &>(*Operands[4]).getReg() == ARM::LR &&
6153       static_cast<ARMOperand &>(*Operands[5]).isImm()) {
6154     Operands.front() = ARMOperand::CreateToken(Name, NameLoc);
6155     Operands.erase(Operands.begin() + 1);
6156   }
6157   return false;
6158 }
6159 
6160 // Validate context-sensitive operand constraints.
6161 
6162 // return 'true' if register list contains non-low GPR registers,
6163 // 'false' otherwise. If Reg is in the register list or is HiReg, set
6164 // 'containsReg' to true.
6165 static bool checkLowRegisterList(const MCInst &Inst, unsigned OpNo,
6166                                  unsigned Reg, unsigned HiReg,
6167                                  bool &containsReg) {
6168   containsReg = false;
6169   for (unsigned i = OpNo; i < Inst.getNumOperands(); ++i) {
6170     unsigned OpReg = Inst.getOperand(i).getReg();
6171     if (OpReg == Reg)
6172       containsReg = true;
6173     // Anything other than a low register isn't legal here.
6174     if (!isARMLowRegister(OpReg) && (!HiReg || OpReg != HiReg))
6175       return true;
6176   }
6177   return false;
6178 }
6179 
6180 // Check if the specified regisgter is in the register list of the inst,
6181 // starting at the indicated operand number.
6182 static bool listContainsReg(const MCInst &Inst, unsigned OpNo, unsigned Reg) {
6183   for (unsigned i = OpNo, e = Inst.getNumOperands(); i < e; ++i) {
6184     unsigned OpReg = Inst.getOperand(i).getReg();
6185     if (OpReg == Reg)
6186       return true;
6187   }
6188   return false;
6189 }
6190 
6191 // Return true if instruction has the interesting property of being
6192 // allowed in IT blocks, but not being predicable.
6193 static bool instIsBreakpoint(const MCInst &Inst) {
6194     return Inst.getOpcode() == ARM::tBKPT ||
6195            Inst.getOpcode() == ARM::BKPT ||
6196            Inst.getOpcode() == ARM::tHLT ||
6197            Inst.getOpcode() == ARM::HLT;
6198 }
6199 
6200 bool ARMAsmParser::validatetLDMRegList(const MCInst &Inst,
6201                                        const OperandVector &Operands,
6202                                        unsigned ListNo, bool IsARPop) {
6203   const ARMOperand &Op = static_cast<const ARMOperand &>(*Operands[ListNo]);
6204   bool HasWritebackToken = Op.isToken() && Op.getToken() == "!";
6205 
6206   bool ListContainsSP = listContainsReg(Inst, ListNo, ARM::SP);
6207   bool ListContainsLR = listContainsReg(Inst, ListNo, ARM::LR);
6208   bool ListContainsPC = listContainsReg(Inst, ListNo, ARM::PC);
6209 
6210   if (!IsARPop && ListContainsSP)
6211     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6212                  "SP may not be in the register list");
6213   else if (ListContainsPC && ListContainsLR)
6214     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6215                  "PC and LR may not be in the register list simultaneously");
6216   return false;
6217 }
6218 
6219 bool ARMAsmParser::validatetSTMRegList(const MCInst &Inst,
6220                                        const OperandVector &Operands,
6221                                        unsigned ListNo) {
6222   const ARMOperand &Op = static_cast<const ARMOperand &>(*Operands[ListNo]);
6223   bool HasWritebackToken = Op.isToken() && Op.getToken() == "!";
6224 
6225   bool ListContainsSP = listContainsReg(Inst, ListNo, ARM::SP);
6226   bool ListContainsPC = listContainsReg(Inst, ListNo, ARM::PC);
6227 
6228   if (ListContainsSP && ListContainsPC)
6229     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6230                  "SP and PC may not be in the register list");
6231   else if (ListContainsSP)
6232     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6233                  "SP may not be in the register list");
6234   else if (ListContainsPC)
6235     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6236                  "PC may not be in the register list");
6237   return false;
6238 }
6239 
6240 // FIXME: We would really like to be able to tablegen'erate this.
6241 bool ARMAsmParser::validateInstruction(MCInst &Inst,
6242                                        const OperandVector &Operands) {
6243   const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
6244   SMLoc Loc = Operands[0]->getStartLoc();
6245 
6246   // Check the IT block state first.
6247   // NOTE: BKPT and HLT instructions have the interesting property of being
6248   // allowed in IT blocks, but not being predicable. They just always execute.
6249   if (inITBlock() && !instIsBreakpoint(Inst)) {
6250     // The instruction must be predicable.
6251     if (!MCID.isPredicable())
6252       return Error(Loc, "instructions in IT block must be predicable");
6253     ARMCC::CondCodes Cond = ARMCC::CondCodes(
6254         Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm());
6255     if (Cond != currentITCond()) {
6256       // Find the condition code Operand to get its SMLoc information.
6257       SMLoc CondLoc;
6258       for (unsigned I = 1; I < Operands.size(); ++I)
6259         if (static_cast<ARMOperand &>(*Operands[I]).isCondCode())
6260           CondLoc = Operands[I]->getStartLoc();
6261       return Error(CondLoc, "incorrect condition in IT block; got '" +
6262                                 StringRef(ARMCondCodeToString(Cond)) +
6263                                 "', but expected '" +
6264                                 ARMCondCodeToString(currentITCond()) + "'");
6265     }
6266   // Check for non-'al' condition codes outside of the IT block.
6267   } else if (isThumbTwo() && MCID.isPredicable() &&
6268              Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm() !=
6269              ARMCC::AL && Inst.getOpcode() != ARM::tBcc &&
6270              Inst.getOpcode() != ARM::t2Bcc) {
6271     return Error(Loc, "predicated instructions must be in IT block");
6272   } else if (!isThumb() && !useImplicitITARM() && MCID.isPredicable() &&
6273              Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm() !=
6274                  ARMCC::AL) {
6275     return Warning(Loc, "predicated instructions should be in IT block");
6276   }
6277 
6278   // PC-setting instructions in an IT block, but not the last instruction of
6279   // the block, are UNPREDICTABLE.
6280   if (inExplicitITBlock() && !lastInITBlock() && isITBlockTerminator(Inst)) {
6281     return Error(Loc, "instruction must be outside of IT block or the last instruction in an IT block");
6282   }
6283 
6284   const unsigned Opcode = Inst.getOpcode();
6285   switch (Opcode) {
6286   case ARM::LDRD:
6287   case ARM::LDRD_PRE:
6288   case ARM::LDRD_POST: {
6289     const unsigned RtReg = Inst.getOperand(0).getReg();
6290 
6291     // Rt can't be R14.
6292     if (RtReg == ARM::LR)
6293       return Error(Operands[3]->getStartLoc(),
6294                    "Rt can't be R14");
6295 
6296     const unsigned Rt = MRI->getEncodingValue(RtReg);
6297     // Rt must be even-numbered.
6298     if ((Rt & 1) == 1)
6299       return Error(Operands[3]->getStartLoc(),
6300                    "Rt must be even-numbered");
6301 
6302     // Rt2 must be Rt + 1.
6303     const unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6304     if (Rt2 != Rt + 1)
6305       return Error(Operands[3]->getStartLoc(),
6306                    "destination operands must be sequential");
6307 
6308     if (Opcode == ARM::LDRD_PRE || Opcode == ARM::LDRD_POST) {
6309       const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(3).getReg());
6310       // For addressing modes with writeback, the base register needs to be
6311       // different from the destination registers.
6312       if (Rn == Rt || Rn == Rt2)
6313         return Error(Operands[3]->getStartLoc(),
6314                      "base register needs to be different from destination "
6315                      "registers");
6316     }
6317 
6318     return false;
6319   }
6320   case ARM::t2LDRDi8:
6321   case ARM::t2LDRD_PRE:
6322   case ARM::t2LDRD_POST: {
6323     // Rt2 must be different from Rt.
6324     unsigned Rt = MRI->getEncodingValue(Inst.getOperand(0).getReg());
6325     unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6326     if (Rt2 == Rt)
6327       return Error(Operands[3]->getStartLoc(),
6328                    "destination operands can't be identical");
6329     return false;
6330   }
6331   case ARM::t2BXJ: {
6332     const unsigned RmReg = Inst.getOperand(0).getReg();
6333     // Rm = SP is no longer unpredictable in v8-A
6334     if (RmReg == ARM::SP && !hasV8Ops())
6335       return Error(Operands[2]->getStartLoc(),
6336                    "r13 (SP) is an unpredictable operand to BXJ");
6337     return false;
6338   }
6339   case ARM::STRD: {
6340     // Rt2 must be Rt + 1.
6341     unsigned Rt = MRI->getEncodingValue(Inst.getOperand(0).getReg());
6342     unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6343     if (Rt2 != Rt + 1)
6344       return Error(Operands[3]->getStartLoc(),
6345                    "source operands must be sequential");
6346     return false;
6347   }
6348   case ARM::STRD_PRE:
6349   case ARM::STRD_POST: {
6350     // Rt2 must be Rt + 1.
6351     unsigned Rt = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6352     unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(2).getReg());
6353     if (Rt2 != Rt + 1)
6354       return Error(Operands[3]->getStartLoc(),
6355                    "source operands must be sequential");
6356     return false;
6357   }
6358   case ARM::STR_PRE_IMM:
6359   case ARM::STR_PRE_REG:
6360   case ARM::STR_POST_IMM:
6361   case ARM::STR_POST_REG:
6362   case ARM::STRH_PRE:
6363   case ARM::STRH_POST:
6364   case ARM::STRB_PRE_IMM:
6365   case ARM::STRB_PRE_REG:
6366   case ARM::STRB_POST_IMM:
6367   case ARM::STRB_POST_REG: {
6368     // Rt must be different from Rn.
6369     const unsigned Rt = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6370     const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(2).getReg());
6371 
6372     if (Rt == Rn)
6373       return Error(Operands[3]->getStartLoc(),
6374                    "source register and base register can't be identical");
6375     return false;
6376   }
6377   case ARM::LDR_PRE_IMM:
6378   case ARM::LDR_PRE_REG:
6379   case ARM::LDR_POST_IMM:
6380   case ARM::LDR_POST_REG:
6381   case ARM::LDRH_PRE:
6382   case ARM::LDRH_POST:
6383   case ARM::LDRSH_PRE:
6384   case ARM::LDRSH_POST:
6385   case ARM::LDRB_PRE_IMM:
6386   case ARM::LDRB_PRE_REG:
6387   case ARM::LDRB_POST_IMM:
6388   case ARM::LDRB_POST_REG:
6389   case ARM::LDRSB_PRE:
6390   case ARM::LDRSB_POST: {
6391     // Rt must be different from Rn.
6392     const unsigned Rt = MRI->getEncodingValue(Inst.getOperand(0).getReg());
6393     const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(2).getReg());
6394 
6395     if (Rt == Rn)
6396       return Error(Operands[3]->getStartLoc(),
6397                    "destination register and base register can't be identical");
6398     return false;
6399   }
6400   case ARM::SBFX:
6401   case ARM::UBFX: {
6402     // Width must be in range [1, 32-lsb].
6403     unsigned LSB = Inst.getOperand(2).getImm();
6404     unsigned Widthm1 = Inst.getOperand(3).getImm();
6405     if (Widthm1 >= 32 - LSB)
6406       return Error(Operands[5]->getStartLoc(),
6407                    "bitfield width must be in range [1,32-lsb]");
6408     return false;
6409   }
6410   // Notionally handles ARM::tLDMIA_UPD too.
6411   case ARM::tLDMIA: {
6412     // If we're parsing Thumb2, the .w variant is available and handles
6413     // most cases that are normally illegal for a Thumb1 LDM instruction.
6414     // We'll make the transformation in processInstruction() if necessary.
6415     //
6416     // Thumb LDM instructions are writeback iff the base register is not
6417     // in the register list.
6418     unsigned Rn = Inst.getOperand(0).getReg();
6419     bool HasWritebackToken =
6420         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
6421          static_cast<ARMOperand &>(*Operands[3]).getToken() == "!");
6422     bool ListContainsBase;
6423     if (checkLowRegisterList(Inst, 3, Rn, 0, ListContainsBase) && !isThumbTwo())
6424       return Error(Operands[3 + HasWritebackToken]->getStartLoc(),
6425                    "registers must be in range r0-r7");
6426     // If we should have writeback, then there should be a '!' token.
6427     if (!ListContainsBase && !HasWritebackToken && !isThumbTwo())
6428       return Error(Operands[2]->getStartLoc(),
6429                    "writeback operator '!' expected");
6430     // If we should not have writeback, there must not be a '!'. This is
6431     // true even for the 32-bit wide encodings.
6432     if (ListContainsBase && HasWritebackToken)
6433       return Error(Operands[3]->getStartLoc(),
6434                    "writeback operator '!' not allowed when base register "
6435                    "in register list");
6436 
6437     if (validatetLDMRegList(Inst, Operands, 3))
6438       return true;
6439     break;
6440   }
6441   case ARM::LDMIA_UPD:
6442   case ARM::LDMDB_UPD:
6443   case ARM::LDMIB_UPD:
6444   case ARM::LDMDA_UPD:
6445     // ARM variants loading and updating the same register are only officially
6446     // UNPREDICTABLE on v7 upwards. Goodness knows what they did before.
6447     if (!hasV7Ops())
6448       break;
6449     if (listContainsReg(Inst, 3, Inst.getOperand(0).getReg()))
6450       return Error(Operands.back()->getStartLoc(),
6451                    "writeback register not allowed in register list");
6452     break;
6453   case ARM::t2LDMIA:
6454   case ARM::t2LDMDB:
6455     if (validatetLDMRegList(Inst, Operands, 3))
6456       return true;
6457     break;
6458   case ARM::t2STMIA:
6459   case ARM::t2STMDB:
6460     if (validatetSTMRegList(Inst, Operands, 3))
6461       return true;
6462     break;
6463   case ARM::t2LDMIA_UPD:
6464   case ARM::t2LDMDB_UPD:
6465   case ARM::t2STMIA_UPD:
6466   case ARM::t2STMDB_UPD:
6467     if (listContainsReg(Inst, 3, Inst.getOperand(0).getReg()))
6468       return Error(Operands.back()->getStartLoc(),
6469                    "writeback register not allowed in register list");
6470 
6471     if (Opcode == ARM::t2LDMIA_UPD || Opcode == ARM::t2LDMDB_UPD) {
6472       if (validatetLDMRegList(Inst, Operands, 3))
6473         return true;
6474     } else {
6475       if (validatetSTMRegList(Inst, Operands, 3))
6476         return true;
6477     }
6478     break;
6479 
6480   case ARM::sysLDMIA_UPD:
6481   case ARM::sysLDMDA_UPD:
6482   case ARM::sysLDMDB_UPD:
6483   case ARM::sysLDMIB_UPD:
6484     if (!listContainsReg(Inst, 3, ARM::PC))
6485       return Error(Operands[4]->getStartLoc(),
6486                    "writeback register only allowed on system LDM "
6487                    "if PC in register-list");
6488     break;
6489   case ARM::sysSTMIA_UPD:
6490   case ARM::sysSTMDA_UPD:
6491   case ARM::sysSTMDB_UPD:
6492   case ARM::sysSTMIB_UPD:
6493     return Error(Operands[2]->getStartLoc(),
6494                  "system STM cannot have writeback register");
6495   case ARM::tMUL:
6496     // The second source operand must be the same register as the destination
6497     // operand.
6498     //
6499     // In this case, we must directly check the parsed operands because the
6500     // cvtThumbMultiply() function is written in such a way that it guarantees
6501     // this first statement is always true for the new Inst.  Essentially, the
6502     // destination is unconditionally copied into the second source operand
6503     // without checking to see if it matches what we actually parsed.
6504     if (Operands.size() == 6 && (((ARMOperand &)*Operands[3]).getReg() !=
6505                                  ((ARMOperand &)*Operands[5]).getReg()) &&
6506         (((ARMOperand &)*Operands[3]).getReg() !=
6507          ((ARMOperand &)*Operands[4]).getReg())) {
6508       return Error(Operands[3]->getStartLoc(),
6509                    "destination register must match source register");
6510     }
6511     break;
6512 
6513   // Like for ldm/stm, push and pop have hi-reg handling version in Thumb2,
6514   // so only issue a diagnostic for thumb1. The instructions will be
6515   // switched to the t2 encodings in processInstruction() if necessary.
6516   case ARM::tPOP: {
6517     bool ListContainsBase;
6518     if (checkLowRegisterList(Inst, 2, 0, ARM::PC, ListContainsBase) &&
6519         !isThumbTwo())
6520       return Error(Operands[2]->getStartLoc(),
6521                    "registers must be in range r0-r7 or pc");
6522     if (validatetLDMRegList(Inst, Operands, 2, !isMClass()))
6523       return true;
6524     break;
6525   }
6526   case ARM::tPUSH: {
6527     bool ListContainsBase;
6528     if (checkLowRegisterList(Inst, 2, 0, ARM::LR, ListContainsBase) &&
6529         !isThumbTwo())
6530       return Error(Operands[2]->getStartLoc(),
6531                    "registers must be in range r0-r7 or lr");
6532     if (validatetSTMRegList(Inst, Operands, 2))
6533       return true;
6534     break;
6535   }
6536   case ARM::tSTMIA_UPD: {
6537     bool ListContainsBase, InvalidLowList;
6538     InvalidLowList = checkLowRegisterList(Inst, 4, Inst.getOperand(0).getReg(),
6539                                           0, ListContainsBase);
6540     if (InvalidLowList && !isThumbTwo())
6541       return Error(Operands[4]->getStartLoc(),
6542                    "registers must be in range r0-r7");
6543 
6544     // This would be converted to a 32-bit stm, but that's not valid if the
6545     // writeback register is in the list.
6546     if (InvalidLowList && ListContainsBase)
6547       return Error(Operands[4]->getStartLoc(),
6548                    "writeback operator '!' not allowed when base register "
6549                    "in register list");
6550 
6551     if (validatetSTMRegList(Inst, Operands, 4))
6552       return true;
6553     break;
6554   }
6555   case ARM::tADDrSP:
6556     // If the non-SP source operand and the destination operand are not the
6557     // same, we need thumb2 (for the wide encoding), or we have an error.
6558     if (!isThumbTwo() &&
6559         Inst.getOperand(0).getReg() != Inst.getOperand(2).getReg()) {
6560       return Error(Operands[4]->getStartLoc(),
6561                    "source register must be the same as destination");
6562     }
6563     break;
6564 
6565   // Final range checking for Thumb unconditional branch instructions.
6566   case ARM::tB:
6567     if (!(static_cast<ARMOperand &>(*Operands[2])).isSignedOffset<11, 1>())
6568       return Error(Operands[2]->getStartLoc(), "branch target out of range");
6569     break;
6570   case ARM::t2B: {
6571     int op = (Operands[2]->isImm()) ? 2 : 3;
6572     if (!static_cast<ARMOperand &>(*Operands[op]).isSignedOffset<24, 1>())
6573       return Error(Operands[op]->getStartLoc(), "branch target out of range");
6574     break;
6575   }
6576   // Final range checking for Thumb conditional branch instructions.
6577   case ARM::tBcc:
6578     if (!static_cast<ARMOperand &>(*Operands[2]).isSignedOffset<8, 1>())
6579       return Error(Operands[2]->getStartLoc(), "branch target out of range");
6580     break;
6581   case ARM::t2Bcc: {
6582     int Op = (Operands[2]->isImm()) ? 2 : 3;
6583     if (!static_cast<ARMOperand &>(*Operands[Op]).isSignedOffset<20, 1>())
6584       return Error(Operands[Op]->getStartLoc(), "branch target out of range");
6585     break;
6586   }
6587   case ARM::tCBZ:
6588   case ARM::tCBNZ: {
6589     if (!static_cast<ARMOperand &>(*Operands[2]).isUnsignedOffset<6, 1>())
6590       return Error(Operands[2]->getStartLoc(), "branch target out of range");
6591     break;
6592   }
6593   case ARM::MOVi16:
6594   case ARM::MOVTi16:
6595   case ARM::t2MOVi16:
6596   case ARM::t2MOVTi16:
6597     {
6598     // We want to avoid misleadingly allowing something like "mov r0, <symbol>"
6599     // especially when we turn it into a movw and the expression <symbol> does
6600     // not have a :lower16: or :upper16 as part of the expression.  We don't
6601     // want the behavior of silently truncating, which can be unexpected and
6602     // lead to bugs that are difficult to find since this is an easy mistake
6603     // to make.
6604     int i = (Operands[3]->isImm()) ? 3 : 4;
6605     ARMOperand &Op = static_cast<ARMOperand &>(*Operands[i]);
6606     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm());
6607     if (CE) break;
6608     const MCExpr *E = dyn_cast<MCExpr>(Op.getImm());
6609     if (!E) break;
6610     const ARMMCExpr *ARM16Expr = dyn_cast<ARMMCExpr>(E);
6611     if (!ARM16Expr || (ARM16Expr->getKind() != ARMMCExpr::VK_ARM_HI16 &&
6612                        ARM16Expr->getKind() != ARMMCExpr::VK_ARM_LO16))
6613       return Error(
6614           Op.getStartLoc(),
6615           "immediate expression for mov requires :lower16: or :upper16");
6616     break;
6617   }
6618   case ARM::HINT:
6619   case ARM::t2HINT:
6620     if (hasRAS()) {
6621       // ESB is not predicable (pred must be AL)
6622       unsigned Imm8 = Inst.getOperand(0).getImm();
6623       unsigned Pred = Inst.getOperand(1).getImm();
6624       if (Imm8 == 0x10 && Pred != ARMCC::AL)
6625         return Error(Operands[1]->getStartLoc(), "instruction 'esb' is not "
6626                                                  "predicable, but condition "
6627                                                  "code specified");
6628     }
6629     // Without the RAS extension, this behaves as any other unallocated hint.
6630     break;
6631   }
6632 
6633   return false;
6634 }
6635 
6636 static unsigned getRealVSTOpcode(unsigned Opc, unsigned &Spacing) {
6637   switch(Opc) {
6638   default: llvm_unreachable("unexpected opcode!");
6639   // VST1LN
6640   case ARM::VST1LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST1LNd8_UPD;
6641   case ARM::VST1LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST1LNd16_UPD;
6642   case ARM::VST1LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST1LNd32_UPD;
6643   case ARM::VST1LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST1LNd8_UPD;
6644   case ARM::VST1LNdWB_register_Asm_16: Spacing = 1; return ARM::VST1LNd16_UPD;
6645   case ARM::VST1LNdWB_register_Asm_32: Spacing = 1; return ARM::VST1LNd32_UPD;
6646   case ARM::VST1LNdAsm_8:  Spacing = 1; return ARM::VST1LNd8;
6647   case ARM::VST1LNdAsm_16: Spacing = 1; return ARM::VST1LNd16;
6648   case ARM::VST1LNdAsm_32: Spacing = 1; return ARM::VST1LNd32;
6649 
6650   // VST2LN
6651   case ARM::VST2LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST2LNd8_UPD;
6652   case ARM::VST2LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST2LNd16_UPD;
6653   case ARM::VST2LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST2LNd32_UPD;
6654   case ARM::VST2LNqWB_fixed_Asm_16: Spacing = 2; return ARM::VST2LNq16_UPD;
6655   case ARM::VST2LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST2LNq32_UPD;
6656 
6657   case ARM::VST2LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST2LNd8_UPD;
6658   case ARM::VST2LNdWB_register_Asm_16: Spacing = 1; return ARM::VST2LNd16_UPD;
6659   case ARM::VST2LNdWB_register_Asm_32: Spacing = 1; return ARM::VST2LNd32_UPD;
6660   case ARM::VST2LNqWB_register_Asm_16: Spacing = 2; return ARM::VST2LNq16_UPD;
6661   case ARM::VST2LNqWB_register_Asm_32: Spacing = 2; return ARM::VST2LNq32_UPD;
6662 
6663   case ARM::VST2LNdAsm_8:  Spacing = 1; return ARM::VST2LNd8;
6664   case ARM::VST2LNdAsm_16: Spacing = 1; return ARM::VST2LNd16;
6665   case ARM::VST2LNdAsm_32: Spacing = 1; return ARM::VST2LNd32;
6666   case ARM::VST2LNqAsm_16: Spacing = 2; return ARM::VST2LNq16;
6667   case ARM::VST2LNqAsm_32: Spacing = 2; return ARM::VST2LNq32;
6668 
6669   // VST3LN
6670   case ARM::VST3LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST3LNd8_UPD;
6671   case ARM::VST3LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST3LNd16_UPD;
6672   case ARM::VST3LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST3LNd32_UPD;
6673   case ARM::VST3LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VST3LNq16_UPD;
6674   case ARM::VST3LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST3LNq32_UPD;
6675   case ARM::VST3LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST3LNd8_UPD;
6676   case ARM::VST3LNdWB_register_Asm_16: Spacing = 1; return ARM::VST3LNd16_UPD;
6677   case ARM::VST3LNdWB_register_Asm_32: Spacing = 1; return ARM::VST3LNd32_UPD;
6678   case ARM::VST3LNqWB_register_Asm_16: Spacing = 2; return ARM::VST3LNq16_UPD;
6679   case ARM::VST3LNqWB_register_Asm_32: Spacing = 2; return ARM::VST3LNq32_UPD;
6680   case ARM::VST3LNdAsm_8:  Spacing = 1; return ARM::VST3LNd8;
6681   case ARM::VST3LNdAsm_16: Spacing = 1; return ARM::VST3LNd16;
6682   case ARM::VST3LNdAsm_32: Spacing = 1; return ARM::VST3LNd32;
6683   case ARM::VST3LNqAsm_16: Spacing = 2; return ARM::VST3LNq16;
6684   case ARM::VST3LNqAsm_32: Spacing = 2; return ARM::VST3LNq32;
6685 
6686   // VST3
6687   case ARM::VST3dWB_fixed_Asm_8:  Spacing = 1; return ARM::VST3d8_UPD;
6688   case ARM::VST3dWB_fixed_Asm_16: Spacing = 1; return ARM::VST3d16_UPD;
6689   case ARM::VST3dWB_fixed_Asm_32: Spacing = 1; return ARM::VST3d32_UPD;
6690   case ARM::VST3qWB_fixed_Asm_8:  Spacing = 2; return ARM::VST3q8_UPD;
6691   case ARM::VST3qWB_fixed_Asm_16: Spacing = 2; return ARM::VST3q16_UPD;
6692   case ARM::VST3qWB_fixed_Asm_32: Spacing = 2; return ARM::VST3q32_UPD;
6693   case ARM::VST3dWB_register_Asm_8:  Spacing = 1; return ARM::VST3d8_UPD;
6694   case ARM::VST3dWB_register_Asm_16: Spacing = 1; return ARM::VST3d16_UPD;
6695   case ARM::VST3dWB_register_Asm_32: Spacing = 1; return ARM::VST3d32_UPD;
6696   case ARM::VST3qWB_register_Asm_8:  Spacing = 2; return ARM::VST3q8_UPD;
6697   case ARM::VST3qWB_register_Asm_16: Spacing = 2; return ARM::VST3q16_UPD;
6698   case ARM::VST3qWB_register_Asm_32: Spacing = 2; return ARM::VST3q32_UPD;
6699   case ARM::VST3dAsm_8:  Spacing = 1; return ARM::VST3d8;
6700   case ARM::VST3dAsm_16: Spacing = 1; return ARM::VST3d16;
6701   case ARM::VST3dAsm_32: Spacing = 1; return ARM::VST3d32;
6702   case ARM::VST3qAsm_8:  Spacing = 2; return ARM::VST3q8;
6703   case ARM::VST3qAsm_16: Spacing = 2; return ARM::VST3q16;
6704   case ARM::VST3qAsm_32: Spacing = 2; return ARM::VST3q32;
6705 
6706   // VST4LN
6707   case ARM::VST4LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST4LNd8_UPD;
6708   case ARM::VST4LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST4LNd16_UPD;
6709   case ARM::VST4LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST4LNd32_UPD;
6710   case ARM::VST4LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VST4LNq16_UPD;
6711   case ARM::VST4LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST4LNq32_UPD;
6712   case ARM::VST4LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST4LNd8_UPD;
6713   case ARM::VST4LNdWB_register_Asm_16: Spacing = 1; return ARM::VST4LNd16_UPD;
6714   case ARM::VST4LNdWB_register_Asm_32: Spacing = 1; return ARM::VST4LNd32_UPD;
6715   case ARM::VST4LNqWB_register_Asm_16: Spacing = 2; return ARM::VST4LNq16_UPD;
6716   case ARM::VST4LNqWB_register_Asm_32: Spacing = 2; return ARM::VST4LNq32_UPD;
6717   case ARM::VST4LNdAsm_8:  Spacing = 1; return ARM::VST4LNd8;
6718   case ARM::VST4LNdAsm_16: Spacing = 1; return ARM::VST4LNd16;
6719   case ARM::VST4LNdAsm_32: Spacing = 1; return ARM::VST4LNd32;
6720   case ARM::VST4LNqAsm_16: Spacing = 2; return ARM::VST4LNq16;
6721   case ARM::VST4LNqAsm_32: Spacing = 2; return ARM::VST4LNq32;
6722 
6723   // VST4
6724   case ARM::VST4dWB_fixed_Asm_8:  Spacing = 1; return ARM::VST4d8_UPD;
6725   case ARM::VST4dWB_fixed_Asm_16: Spacing = 1; return ARM::VST4d16_UPD;
6726   case ARM::VST4dWB_fixed_Asm_32: Spacing = 1; return ARM::VST4d32_UPD;
6727   case ARM::VST4qWB_fixed_Asm_8:  Spacing = 2; return ARM::VST4q8_UPD;
6728   case ARM::VST4qWB_fixed_Asm_16: Spacing = 2; return ARM::VST4q16_UPD;
6729   case ARM::VST4qWB_fixed_Asm_32: Spacing = 2; return ARM::VST4q32_UPD;
6730   case ARM::VST4dWB_register_Asm_8:  Spacing = 1; return ARM::VST4d8_UPD;
6731   case ARM::VST4dWB_register_Asm_16: Spacing = 1; return ARM::VST4d16_UPD;
6732   case ARM::VST4dWB_register_Asm_32: Spacing = 1; return ARM::VST4d32_UPD;
6733   case ARM::VST4qWB_register_Asm_8:  Spacing = 2; return ARM::VST4q8_UPD;
6734   case ARM::VST4qWB_register_Asm_16: Spacing = 2; return ARM::VST4q16_UPD;
6735   case ARM::VST4qWB_register_Asm_32: Spacing = 2; return ARM::VST4q32_UPD;
6736   case ARM::VST4dAsm_8:  Spacing = 1; return ARM::VST4d8;
6737   case ARM::VST4dAsm_16: Spacing = 1; return ARM::VST4d16;
6738   case ARM::VST4dAsm_32: Spacing = 1; return ARM::VST4d32;
6739   case ARM::VST4qAsm_8:  Spacing = 2; return ARM::VST4q8;
6740   case ARM::VST4qAsm_16: Spacing = 2; return ARM::VST4q16;
6741   case ARM::VST4qAsm_32: Spacing = 2; return ARM::VST4q32;
6742   }
6743 }
6744 
6745 static unsigned getRealVLDOpcode(unsigned Opc, unsigned &Spacing) {
6746   switch(Opc) {
6747   default: llvm_unreachable("unexpected opcode!");
6748   // VLD1LN
6749   case ARM::VLD1LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD1LNd8_UPD;
6750   case ARM::VLD1LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD1LNd16_UPD;
6751   case ARM::VLD1LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD1LNd32_UPD;
6752   case ARM::VLD1LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD1LNd8_UPD;
6753   case ARM::VLD1LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD1LNd16_UPD;
6754   case ARM::VLD1LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD1LNd32_UPD;
6755   case ARM::VLD1LNdAsm_8:  Spacing = 1; return ARM::VLD1LNd8;
6756   case ARM::VLD1LNdAsm_16: Spacing = 1; return ARM::VLD1LNd16;
6757   case ARM::VLD1LNdAsm_32: Spacing = 1; return ARM::VLD1LNd32;
6758 
6759   // VLD2LN
6760   case ARM::VLD2LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD2LNd8_UPD;
6761   case ARM::VLD2LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD2LNd16_UPD;
6762   case ARM::VLD2LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD2LNd32_UPD;
6763   case ARM::VLD2LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD2LNq16_UPD;
6764   case ARM::VLD2LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD2LNq32_UPD;
6765   case ARM::VLD2LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD2LNd8_UPD;
6766   case ARM::VLD2LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD2LNd16_UPD;
6767   case ARM::VLD2LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD2LNd32_UPD;
6768   case ARM::VLD2LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD2LNq16_UPD;
6769   case ARM::VLD2LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD2LNq32_UPD;
6770   case ARM::VLD2LNdAsm_8:  Spacing = 1; return ARM::VLD2LNd8;
6771   case ARM::VLD2LNdAsm_16: Spacing = 1; return ARM::VLD2LNd16;
6772   case ARM::VLD2LNdAsm_32: Spacing = 1; return ARM::VLD2LNd32;
6773   case ARM::VLD2LNqAsm_16: Spacing = 2; return ARM::VLD2LNq16;
6774   case ARM::VLD2LNqAsm_32: Spacing = 2; return ARM::VLD2LNq32;
6775 
6776   // VLD3DUP
6777   case ARM::VLD3DUPdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3DUPd8_UPD;
6778   case ARM::VLD3DUPdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3DUPd16_UPD;
6779   case ARM::VLD3DUPdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3DUPd32_UPD;
6780   case ARM::VLD3DUPqWB_fixed_Asm_8: Spacing = 1; return ARM::VLD3DUPq8_UPD;
6781   case ARM::VLD3DUPqWB_fixed_Asm_16: Spacing = 2; return ARM::VLD3DUPq16_UPD;
6782   case ARM::VLD3DUPqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3DUPq32_UPD;
6783   case ARM::VLD3DUPdWB_register_Asm_8:  Spacing = 1; return ARM::VLD3DUPd8_UPD;
6784   case ARM::VLD3DUPdWB_register_Asm_16: Spacing = 1; return ARM::VLD3DUPd16_UPD;
6785   case ARM::VLD3DUPdWB_register_Asm_32: Spacing = 1; return ARM::VLD3DUPd32_UPD;
6786   case ARM::VLD3DUPqWB_register_Asm_8: Spacing = 2; return ARM::VLD3DUPq8_UPD;
6787   case ARM::VLD3DUPqWB_register_Asm_16: Spacing = 2; return ARM::VLD3DUPq16_UPD;
6788   case ARM::VLD3DUPqWB_register_Asm_32: Spacing = 2; return ARM::VLD3DUPq32_UPD;
6789   case ARM::VLD3DUPdAsm_8:  Spacing = 1; return ARM::VLD3DUPd8;
6790   case ARM::VLD3DUPdAsm_16: Spacing = 1; return ARM::VLD3DUPd16;
6791   case ARM::VLD3DUPdAsm_32: Spacing = 1; return ARM::VLD3DUPd32;
6792   case ARM::VLD3DUPqAsm_8: Spacing = 2; return ARM::VLD3DUPq8;
6793   case ARM::VLD3DUPqAsm_16: Spacing = 2; return ARM::VLD3DUPq16;
6794   case ARM::VLD3DUPqAsm_32: Spacing = 2; return ARM::VLD3DUPq32;
6795 
6796   // VLD3LN
6797   case ARM::VLD3LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3LNd8_UPD;
6798   case ARM::VLD3LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3LNd16_UPD;
6799   case ARM::VLD3LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3LNd32_UPD;
6800   case ARM::VLD3LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3LNq16_UPD;
6801   case ARM::VLD3LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3LNq32_UPD;
6802   case ARM::VLD3LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD3LNd8_UPD;
6803   case ARM::VLD3LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD3LNd16_UPD;
6804   case ARM::VLD3LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD3LNd32_UPD;
6805   case ARM::VLD3LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD3LNq16_UPD;
6806   case ARM::VLD3LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD3LNq32_UPD;
6807   case ARM::VLD3LNdAsm_8:  Spacing = 1; return ARM::VLD3LNd8;
6808   case ARM::VLD3LNdAsm_16: Spacing = 1; return ARM::VLD3LNd16;
6809   case ARM::VLD3LNdAsm_32: Spacing = 1; return ARM::VLD3LNd32;
6810   case ARM::VLD3LNqAsm_16: Spacing = 2; return ARM::VLD3LNq16;
6811   case ARM::VLD3LNqAsm_32: Spacing = 2; return ARM::VLD3LNq32;
6812 
6813   // VLD3
6814   case ARM::VLD3dWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3d8_UPD;
6815   case ARM::VLD3dWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3d16_UPD;
6816   case ARM::VLD3dWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3d32_UPD;
6817   case ARM::VLD3qWB_fixed_Asm_8:  Spacing = 2; return ARM::VLD3q8_UPD;
6818   case ARM::VLD3qWB_fixed_Asm_16: Spacing = 2; return ARM::VLD3q16_UPD;
6819   case ARM::VLD3qWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3q32_UPD;
6820   case ARM::VLD3dWB_register_Asm_8:  Spacing = 1; return ARM::VLD3d8_UPD;
6821   case ARM::VLD3dWB_register_Asm_16: Spacing = 1; return ARM::VLD3d16_UPD;
6822   case ARM::VLD3dWB_register_Asm_32: Spacing = 1; return ARM::VLD3d32_UPD;
6823   case ARM::VLD3qWB_register_Asm_8:  Spacing = 2; return ARM::VLD3q8_UPD;
6824   case ARM::VLD3qWB_register_Asm_16: Spacing = 2; return ARM::VLD3q16_UPD;
6825   case ARM::VLD3qWB_register_Asm_32: Spacing = 2; return ARM::VLD3q32_UPD;
6826   case ARM::VLD3dAsm_8:  Spacing = 1; return ARM::VLD3d8;
6827   case ARM::VLD3dAsm_16: Spacing = 1; return ARM::VLD3d16;
6828   case ARM::VLD3dAsm_32: Spacing = 1; return ARM::VLD3d32;
6829   case ARM::VLD3qAsm_8:  Spacing = 2; return ARM::VLD3q8;
6830   case ARM::VLD3qAsm_16: Spacing = 2; return ARM::VLD3q16;
6831   case ARM::VLD3qAsm_32: Spacing = 2; return ARM::VLD3q32;
6832 
6833   // VLD4LN
6834   case ARM::VLD4LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4LNd8_UPD;
6835   case ARM::VLD4LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4LNd16_UPD;
6836   case ARM::VLD4LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4LNd32_UPD;
6837   case ARM::VLD4LNqWB_fixed_Asm_16: Spacing = 2; return ARM::VLD4LNq16_UPD;
6838   case ARM::VLD4LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4LNq32_UPD;
6839   case ARM::VLD4LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD4LNd8_UPD;
6840   case ARM::VLD4LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD4LNd16_UPD;
6841   case ARM::VLD4LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD4LNd32_UPD;
6842   case ARM::VLD4LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD4LNq16_UPD;
6843   case ARM::VLD4LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD4LNq32_UPD;
6844   case ARM::VLD4LNdAsm_8:  Spacing = 1; return ARM::VLD4LNd8;
6845   case ARM::VLD4LNdAsm_16: Spacing = 1; return ARM::VLD4LNd16;
6846   case ARM::VLD4LNdAsm_32: Spacing = 1; return ARM::VLD4LNd32;
6847   case ARM::VLD4LNqAsm_16: Spacing = 2; return ARM::VLD4LNq16;
6848   case ARM::VLD4LNqAsm_32: Spacing = 2; return ARM::VLD4LNq32;
6849 
6850   // VLD4DUP
6851   case ARM::VLD4DUPdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4DUPd8_UPD;
6852   case ARM::VLD4DUPdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4DUPd16_UPD;
6853   case ARM::VLD4DUPdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4DUPd32_UPD;
6854   case ARM::VLD4DUPqWB_fixed_Asm_8: Spacing = 1; return ARM::VLD4DUPq8_UPD;
6855   case ARM::VLD4DUPqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4DUPq16_UPD;
6856   case ARM::VLD4DUPqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4DUPq32_UPD;
6857   case ARM::VLD4DUPdWB_register_Asm_8:  Spacing = 1; return ARM::VLD4DUPd8_UPD;
6858   case ARM::VLD4DUPdWB_register_Asm_16: Spacing = 1; return ARM::VLD4DUPd16_UPD;
6859   case ARM::VLD4DUPdWB_register_Asm_32: Spacing = 1; return ARM::VLD4DUPd32_UPD;
6860   case ARM::VLD4DUPqWB_register_Asm_8: Spacing = 2; return ARM::VLD4DUPq8_UPD;
6861   case ARM::VLD4DUPqWB_register_Asm_16: Spacing = 2; return ARM::VLD4DUPq16_UPD;
6862   case ARM::VLD4DUPqWB_register_Asm_32: Spacing = 2; return ARM::VLD4DUPq32_UPD;
6863   case ARM::VLD4DUPdAsm_8:  Spacing = 1; return ARM::VLD4DUPd8;
6864   case ARM::VLD4DUPdAsm_16: Spacing = 1; return ARM::VLD4DUPd16;
6865   case ARM::VLD4DUPdAsm_32: Spacing = 1; return ARM::VLD4DUPd32;
6866   case ARM::VLD4DUPqAsm_8: Spacing = 2; return ARM::VLD4DUPq8;
6867   case ARM::VLD4DUPqAsm_16: Spacing = 2; return ARM::VLD4DUPq16;
6868   case ARM::VLD4DUPqAsm_32: Spacing = 2; return ARM::VLD4DUPq32;
6869 
6870   // VLD4
6871   case ARM::VLD4dWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4d8_UPD;
6872   case ARM::VLD4dWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4d16_UPD;
6873   case ARM::VLD4dWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4d32_UPD;
6874   case ARM::VLD4qWB_fixed_Asm_8:  Spacing = 2; return ARM::VLD4q8_UPD;
6875   case ARM::VLD4qWB_fixed_Asm_16: Spacing = 2; return ARM::VLD4q16_UPD;
6876   case ARM::VLD4qWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4q32_UPD;
6877   case ARM::VLD4dWB_register_Asm_8:  Spacing = 1; return ARM::VLD4d8_UPD;
6878   case ARM::VLD4dWB_register_Asm_16: Spacing = 1; return ARM::VLD4d16_UPD;
6879   case ARM::VLD4dWB_register_Asm_32: Spacing = 1; return ARM::VLD4d32_UPD;
6880   case ARM::VLD4qWB_register_Asm_8:  Spacing = 2; return ARM::VLD4q8_UPD;
6881   case ARM::VLD4qWB_register_Asm_16: Spacing = 2; return ARM::VLD4q16_UPD;
6882   case ARM::VLD4qWB_register_Asm_32: Spacing = 2; return ARM::VLD4q32_UPD;
6883   case ARM::VLD4dAsm_8:  Spacing = 1; return ARM::VLD4d8;
6884   case ARM::VLD4dAsm_16: Spacing = 1; return ARM::VLD4d16;
6885   case ARM::VLD4dAsm_32: Spacing = 1; return ARM::VLD4d32;
6886   case ARM::VLD4qAsm_8:  Spacing = 2; return ARM::VLD4q8;
6887   case ARM::VLD4qAsm_16: Spacing = 2; return ARM::VLD4q16;
6888   case ARM::VLD4qAsm_32: Spacing = 2; return ARM::VLD4q32;
6889   }
6890 }
6891 
6892 bool ARMAsmParser::processInstruction(MCInst &Inst,
6893                                       const OperandVector &Operands,
6894                                       MCStreamer &Out) {
6895   // Check if we have the wide qualifier, because if it's present we
6896   // must avoid selecting a 16-bit thumb instruction.
6897   bool HasWideQualifier = false;
6898   for (auto &Op : Operands) {
6899     ARMOperand &ARMOp = static_cast<ARMOperand&>(*Op);
6900     if (ARMOp.isToken() && ARMOp.getToken() == ".w") {
6901       HasWideQualifier = true;
6902       break;
6903     }
6904   }
6905 
6906   switch (Inst.getOpcode()) {
6907   // Alias for alternate form of 'ldr{,b}t Rt, [Rn], #imm' instruction.
6908   case ARM::LDRT_POST:
6909   case ARM::LDRBT_POST: {
6910     const unsigned Opcode =
6911       (Inst.getOpcode() == ARM::LDRT_POST) ? ARM::LDRT_POST_IMM
6912                                            : ARM::LDRBT_POST_IMM;
6913     MCInst TmpInst;
6914     TmpInst.setOpcode(Opcode);
6915     TmpInst.addOperand(Inst.getOperand(0));
6916     TmpInst.addOperand(Inst.getOperand(1));
6917     TmpInst.addOperand(Inst.getOperand(1));
6918     TmpInst.addOperand(MCOperand::createReg(0));
6919     TmpInst.addOperand(MCOperand::createImm(0));
6920     TmpInst.addOperand(Inst.getOperand(2));
6921     TmpInst.addOperand(Inst.getOperand(3));
6922     Inst = TmpInst;
6923     return true;
6924   }
6925   // Alias for alternate form of 'str{,b}t Rt, [Rn], #imm' instruction.
6926   case ARM::STRT_POST:
6927   case ARM::STRBT_POST: {
6928     const unsigned Opcode =
6929       (Inst.getOpcode() == ARM::STRT_POST) ? ARM::STRT_POST_IMM
6930                                            : ARM::STRBT_POST_IMM;
6931     MCInst TmpInst;
6932     TmpInst.setOpcode(Opcode);
6933     TmpInst.addOperand(Inst.getOperand(1));
6934     TmpInst.addOperand(Inst.getOperand(0));
6935     TmpInst.addOperand(Inst.getOperand(1));
6936     TmpInst.addOperand(MCOperand::createReg(0));
6937     TmpInst.addOperand(MCOperand::createImm(0));
6938     TmpInst.addOperand(Inst.getOperand(2));
6939     TmpInst.addOperand(Inst.getOperand(3));
6940     Inst = TmpInst;
6941     return true;
6942   }
6943   // Alias for alternate form of 'ADR Rd, #imm' instruction.
6944   case ARM::ADDri: {
6945     if (Inst.getOperand(1).getReg() != ARM::PC ||
6946         Inst.getOperand(5).getReg() != 0 ||
6947         !(Inst.getOperand(2).isExpr() || Inst.getOperand(2).isImm()))
6948       return false;
6949     MCInst TmpInst;
6950     TmpInst.setOpcode(ARM::ADR);
6951     TmpInst.addOperand(Inst.getOperand(0));
6952     if (Inst.getOperand(2).isImm()) {
6953       // Immediate (mod_imm) will be in its encoded form, we must unencode it
6954       // before passing it to the ADR instruction.
6955       unsigned Enc = Inst.getOperand(2).getImm();
6956       TmpInst.addOperand(MCOperand::createImm(
6957         ARM_AM::rotr32(Enc & 0xFF, (Enc & 0xF00) >> 7)));
6958     } else {
6959       // Turn PC-relative expression into absolute expression.
6960       // Reading PC provides the start of the current instruction + 8 and
6961       // the transform to adr is biased by that.
6962       MCSymbol *Dot = getContext().createTempSymbol();
6963       Out.EmitLabel(Dot);
6964       const MCExpr *OpExpr = Inst.getOperand(2).getExpr();
6965       const MCExpr *InstPC = MCSymbolRefExpr::create(Dot,
6966                                                      MCSymbolRefExpr::VK_None,
6967                                                      getContext());
6968       const MCExpr *Const8 = MCConstantExpr::create(8, getContext());
6969       const MCExpr *ReadPC = MCBinaryExpr::createAdd(InstPC, Const8,
6970                                                      getContext());
6971       const MCExpr *FixupAddr = MCBinaryExpr::createAdd(ReadPC, OpExpr,
6972                                                         getContext());
6973       TmpInst.addOperand(MCOperand::createExpr(FixupAddr));
6974     }
6975     TmpInst.addOperand(Inst.getOperand(3));
6976     TmpInst.addOperand(Inst.getOperand(4));
6977     Inst = TmpInst;
6978     return true;
6979   }
6980   // Aliases for alternate PC+imm syntax of LDR instructions.
6981   case ARM::t2LDRpcrel:
6982     // Select the narrow version if the immediate will fit.
6983     if (Inst.getOperand(1).getImm() > 0 &&
6984         Inst.getOperand(1).getImm() <= 0xff &&
6985         !HasWideQualifier)
6986       Inst.setOpcode(ARM::tLDRpci);
6987     else
6988       Inst.setOpcode(ARM::t2LDRpci);
6989     return true;
6990   case ARM::t2LDRBpcrel:
6991     Inst.setOpcode(ARM::t2LDRBpci);
6992     return true;
6993   case ARM::t2LDRHpcrel:
6994     Inst.setOpcode(ARM::t2LDRHpci);
6995     return true;
6996   case ARM::t2LDRSBpcrel:
6997     Inst.setOpcode(ARM::t2LDRSBpci);
6998     return true;
6999   case ARM::t2LDRSHpcrel:
7000     Inst.setOpcode(ARM::t2LDRSHpci);
7001     return true;
7002   case ARM::LDRConstPool:
7003   case ARM::tLDRConstPool:
7004   case ARM::t2LDRConstPool: {
7005     // Pseudo instruction ldr rt, =immediate is converted to a
7006     // MOV rt, immediate if immediate is known and representable
7007     // otherwise we create a constant pool entry that we load from.
7008     MCInst TmpInst;
7009     if (Inst.getOpcode() == ARM::LDRConstPool)
7010       TmpInst.setOpcode(ARM::LDRi12);
7011     else if (Inst.getOpcode() == ARM::tLDRConstPool)
7012       TmpInst.setOpcode(ARM::tLDRpci);
7013     else if (Inst.getOpcode() == ARM::t2LDRConstPool)
7014       TmpInst.setOpcode(ARM::t2LDRpci);
7015     const ARMOperand &PoolOperand =
7016       (HasWideQualifier ?
7017        static_cast<ARMOperand &>(*Operands[4]) :
7018        static_cast<ARMOperand &>(*Operands[3]));
7019     const MCExpr *SubExprVal = PoolOperand.getConstantPoolImm();
7020     // If SubExprVal is a constant we may be able to use a MOV
7021     if (isa<MCConstantExpr>(SubExprVal) &&
7022         Inst.getOperand(0).getReg() != ARM::PC &&
7023         Inst.getOperand(0).getReg() != ARM::SP) {
7024       int64_t Value =
7025         (int64_t) (cast<MCConstantExpr>(SubExprVal))->getValue();
7026       bool UseMov  = true;
7027       bool MovHasS = true;
7028       if (Inst.getOpcode() == ARM::LDRConstPool) {
7029         // ARM Constant
7030         if (ARM_AM::getSOImmVal(Value) != -1) {
7031           Value = ARM_AM::getSOImmVal(Value);
7032           TmpInst.setOpcode(ARM::MOVi);
7033         }
7034         else if (ARM_AM::getSOImmVal(~Value) != -1) {
7035           Value = ARM_AM::getSOImmVal(~Value);
7036           TmpInst.setOpcode(ARM::MVNi);
7037         }
7038         else if (hasV6T2Ops() &&
7039                  Value >=0 && Value < 65536) {
7040           TmpInst.setOpcode(ARM::MOVi16);
7041           MovHasS = false;
7042         }
7043         else
7044           UseMov = false;
7045       }
7046       else {
7047         // Thumb/Thumb2 Constant
7048         if (hasThumb2() &&
7049             ARM_AM::getT2SOImmVal(Value) != -1)
7050           TmpInst.setOpcode(ARM::t2MOVi);
7051         else if (hasThumb2() &&
7052                  ARM_AM::getT2SOImmVal(~Value) != -1) {
7053           TmpInst.setOpcode(ARM::t2MVNi);
7054           Value = ~Value;
7055         }
7056         else if (hasV8MBaseline() &&
7057                  Value >=0 && Value < 65536) {
7058           TmpInst.setOpcode(ARM::t2MOVi16);
7059           MovHasS = false;
7060         }
7061         else
7062           UseMov = false;
7063       }
7064       if (UseMov) {
7065         TmpInst.addOperand(Inst.getOperand(0));           // Rt
7066         TmpInst.addOperand(MCOperand::createImm(Value));  // Immediate
7067         TmpInst.addOperand(Inst.getOperand(2));           // CondCode
7068         TmpInst.addOperand(Inst.getOperand(3));           // CondCode
7069         if (MovHasS)
7070           TmpInst.addOperand(MCOperand::createReg(0));    // S
7071         Inst = TmpInst;
7072         return true;
7073       }
7074     }
7075     // No opportunity to use MOV/MVN create constant pool
7076     const MCExpr *CPLoc =
7077       getTargetStreamer().addConstantPoolEntry(SubExprVal,
7078                                                PoolOperand.getStartLoc());
7079     TmpInst.addOperand(Inst.getOperand(0));           // Rt
7080     TmpInst.addOperand(MCOperand::createExpr(CPLoc)); // offset to constpool
7081     if (TmpInst.getOpcode() == ARM::LDRi12)
7082       TmpInst.addOperand(MCOperand::createImm(0));    // unused offset
7083     TmpInst.addOperand(Inst.getOperand(2));           // CondCode
7084     TmpInst.addOperand(Inst.getOperand(3));           // CondCode
7085     Inst = TmpInst;
7086     return true;
7087   }
7088   // Handle NEON VST complex aliases.
7089   case ARM::VST1LNdWB_register_Asm_8:
7090   case ARM::VST1LNdWB_register_Asm_16:
7091   case ARM::VST1LNdWB_register_Asm_32: {
7092     MCInst TmpInst;
7093     // Shuffle the operands around so the lane index operand is in the
7094     // right place.
7095     unsigned Spacing;
7096     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7097     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7098     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7099     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7100     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7101     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7102     TmpInst.addOperand(Inst.getOperand(1)); // lane
7103     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7104     TmpInst.addOperand(Inst.getOperand(6));
7105     Inst = TmpInst;
7106     return true;
7107   }
7108 
7109   case ARM::VST2LNdWB_register_Asm_8:
7110   case ARM::VST2LNdWB_register_Asm_16:
7111   case ARM::VST2LNdWB_register_Asm_32:
7112   case ARM::VST2LNqWB_register_Asm_16:
7113   case ARM::VST2LNqWB_register_Asm_32: {
7114     MCInst TmpInst;
7115     // Shuffle the operands around so the lane index operand is in the
7116     // right place.
7117     unsigned Spacing;
7118     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7119     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7120     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7121     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7122     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7123     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7124     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7125                                             Spacing));
7126     TmpInst.addOperand(Inst.getOperand(1)); // lane
7127     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7128     TmpInst.addOperand(Inst.getOperand(6));
7129     Inst = TmpInst;
7130     return true;
7131   }
7132 
7133   case ARM::VST3LNdWB_register_Asm_8:
7134   case ARM::VST3LNdWB_register_Asm_16:
7135   case ARM::VST3LNdWB_register_Asm_32:
7136   case ARM::VST3LNqWB_register_Asm_16:
7137   case ARM::VST3LNqWB_register_Asm_32: {
7138     MCInst TmpInst;
7139     // Shuffle the operands around so the lane index operand is in the
7140     // right place.
7141     unsigned Spacing;
7142     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7143     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7144     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7145     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7146     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7147     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7148     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7149                                             Spacing));
7150     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7151                                             Spacing * 2));
7152     TmpInst.addOperand(Inst.getOperand(1)); // lane
7153     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7154     TmpInst.addOperand(Inst.getOperand(6));
7155     Inst = TmpInst;
7156     return true;
7157   }
7158 
7159   case ARM::VST4LNdWB_register_Asm_8:
7160   case ARM::VST4LNdWB_register_Asm_16:
7161   case ARM::VST4LNdWB_register_Asm_32:
7162   case ARM::VST4LNqWB_register_Asm_16:
7163   case ARM::VST4LNqWB_register_Asm_32: {
7164     MCInst TmpInst;
7165     // Shuffle the operands around so the lane index operand is in the
7166     // right place.
7167     unsigned Spacing;
7168     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7169     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7170     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7171     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7172     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7173     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7174     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7175                                             Spacing));
7176     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7177                                             Spacing * 2));
7178     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7179                                             Spacing * 3));
7180     TmpInst.addOperand(Inst.getOperand(1)); // lane
7181     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7182     TmpInst.addOperand(Inst.getOperand(6));
7183     Inst = TmpInst;
7184     return true;
7185   }
7186 
7187   case ARM::VST1LNdWB_fixed_Asm_8:
7188   case ARM::VST1LNdWB_fixed_Asm_16:
7189   case ARM::VST1LNdWB_fixed_Asm_32: {
7190     MCInst TmpInst;
7191     // Shuffle the operands around so the lane index operand is in the
7192     // right place.
7193     unsigned Spacing;
7194     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7195     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7196     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7197     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7198     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7199     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7200     TmpInst.addOperand(Inst.getOperand(1)); // lane
7201     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7202     TmpInst.addOperand(Inst.getOperand(5));
7203     Inst = TmpInst;
7204     return true;
7205   }
7206 
7207   case ARM::VST2LNdWB_fixed_Asm_8:
7208   case ARM::VST2LNdWB_fixed_Asm_16:
7209   case ARM::VST2LNdWB_fixed_Asm_32:
7210   case ARM::VST2LNqWB_fixed_Asm_16:
7211   case ARM::VST2LNqWB_fixed_Asm_32: {
7212     MCInst TmpInst;
7213     // Shuffle the operands around so the lane index operand is in the
7214     // right place.
7215     unsigned Spacing;
7216     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7217     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7218     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7219     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7220     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7221     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7222     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7223                                             Spacing));
7224     TmpInst.addOperand(Inst.getOperand(1)); // lane
7225     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7226     TmpInst.addOperand(Inst.getOperand(5));
7227     Inst = TmpInst;
7228     return true;
7229   }
7230 
7231   case ARM::VST3LNdWB_fixed_Asm_8:
7232   case ARM::VST3LNdWB_fixed_Asm_16:
7233   case ARM::VST3LNdWB_fixed_Asm_32:
7234   case ARM::VST3LNqWB_fixed_Asm_16:
7235   case ARM::VST3LNqWB_fixed_Asm_32: {
7236     MCInst TmpInst;
7237     // Shuffle the operands around so the lane index operand is in the
7238     // right place.
7239     unsigned Spacing;
7240     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7241     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7242     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7243     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7244     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7245     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7246     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7247                                             Spacing));
7248     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7249                                             Spacing * 2));
7250     TmpInst.addOperand(Inst.getOperand(1)); // lane
7251     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7252     TmpInst.addOperand(Inst.getOperand(5));
7253     Inst = TmpInst;
7254     return true;
7255   }
7256 
7257   case ARM::VST4LNdWB_fixed_Asm_8:
7258   case ARM::VST4LNdWB_fixed_Asm_16:
7259   case ARM::VST4LNdWB_fixed_Asm_32:
7260   case ARM::VST4LNqWB_fixed_Asm_16:
7261   case ARM::VST4LNqWB_fixed_Asm_32: {
7262     MCInst TmpInst;
7263     // Shuffle the operands around so the lane index operand is in the
7264     // right place.
7265     unsigned Spacing;
7266     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7267     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7268     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7269     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7270     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7271     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7272     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7273                                             Spacing));
7274     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7275                                             Spacing * 2));
7276     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7277                                             Spacing * 3));
7278     TmpInst.addOperand(Inst.getOperand(1)); // lane
7279     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7280     TmpInst.addOperand(Inst.getOperand(5));
7281     Inst = TmpInst;
7282     return true;
7283   }
7284 
7285   case ARM::VST1LNdAsm_8:
7286   case ARM::VST1LNdAsm_16:
7287   case ARM::VST1LNdAsm_32: {
7288     MCInst TmpInst;
7289     // Shuffle the operands around so the lane index operand is in the
7290     // right place.
7291     unsigned Spacing;
7292     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7293     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7294     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7295     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7296     TmpInst.addOperand(Inst.getOperand(1)); // lane
7297     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7298     TmpInst.addOperand(Inst.getOperand(5));
7299     Inst = TmpInst;
7300     return true;
7301   }
7302 
7303   case ARM::VST2LNdAsm_8:
7304   case ARM::VST2LNdAsm_16:
7305   case ARM::VST2LNdAsm_32:
7306   case ARM::VST2LNqAsm_16:
7307   case ARM::VST2LNqAsm_32: {
7308     MCInst TmpInst;
7309     // Shuffle the operands around so the lane index operand is in the
7310     // right place.
7311     unsigned Spacing;
7312     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7313     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7314     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7315     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7316     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7317                                             Spacing));
7318     TmpInst.addOperand(Inst.getOperand(1)); // lane
7319     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7320     TmpInst.addOperand(Inst.getOperand(5));
7321     Inst = TmpInst;
7322     return true;
7323   }
7324 
7325   case ARM::VST3LNdAsm_8:
7326   case ARM::VST3LNdAsm_16:
7327   case ARM::VST3LNdAsm_32:
7328   case ARM::VST3LNqAsm_16:
7329   case ARM::VST3LNqAsm_32: {
7330     MCInst TmpInst;
7331     // Shuffle the operands around so the lane index operand is in the
7332     // right place.
7333     unsigned Spacing;
7334     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7335     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7336     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7337     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7338     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7339                                             Spacing));
7340     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7341                                             Spacing * 2));
7342     TmpInst.addOperand(Inst.getOperand(1)); // lane
7343     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7344     TmpInst.addOperand(Inst.getOperand(5));
7345     Inst = TmpInst;
7346     return true;
7347   }
7348 
7349   case ARM::VST4LNdAsm_8:
7350   case ARM::VST4LNdAsm_16:
7351   case ARM::VST4LNdAsm_32:
7352   case ARM::VST4LNqAsm_16:
7353   case ARM::VST4LNqAsm_32: {
7354     MCInst TmpInst;
7355     // Shuffle the operands around so the lane index operand is in the
7356     // right place.
7357     unsigned Spacing;
7358     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7359     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7360     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7361     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7362     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7363                                             Spacing));
7364     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7365                                             Spacing * 2));
7366     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7367                                             Spacing * 3));
7368     TmpInst.addOperand(Inst.getOperand(1)); // lane
7369     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7370     TmpInst.addOperand(Inst.getOperand(5));
7371     Inst = TmpInst;
7372     return true;
7373   }
7374 
7375   // Handle NEON VLD complex aliases.
7376   case ARM::VLD1LNdWB_register_Asm_8:
7377   case ARM::VLD1LNdWB_register_Asm_16:
7378   case ARM::VLD1LNdWB_register_Asm_32: {
7379     MCInst TmpInst;
7380     // Shuffle the operands around so the lane index operand is in the
7381     // right place.
7382     unsigned Spacing;
7383     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7384     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7385     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7386     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7387     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7388     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7389     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7390     TmpInst.addOperand(Inst.getOperand(1)); // lane
7391     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7392     TmpInst.addOperand(Inst.getOperand(6));
7393     Inst = TmpInst;
7394     return true;
7395   }
7396 
7397   case ARM::VLD2LNdWB_register_Asm_8:
7398   case ARM::VLD2LNdWB_register_Asm_16:
7399   case ARM::VLD2LNdWB_register_Asm_32:
7400   case ARM::VLD2LNqWB_register_Asm_16:
7401   case ARM::VLD2LNqWB_register_Asm_32: {
7402     MCInst TmpInst;
7403     // Shuffle the operands around so the lane index operand is in the
7404     // right place.
7405     unsigned Spacing;
7406     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7407     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7408     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7409                                             Spacing));
7410     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7411     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7412     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7413     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7414     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7415     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7416                                             Spacing));
7417     TmpInst.addOperand(Inst.getOperand(1)); // lane
7418     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7419     TmpInst.addOperand(Inst.getOperand(6));
7420     Inst = TmpInst;
7421     return true;
7422   }
7423 
7424   case ARM::VLD3LNdWB_register_Asm_8:
7425   case ARM::VLD3LNdWB_register_Asm_16:
7426   case ARM::VLD3LNdWB_register_Asm_32:
7427   case ARM::VLD3LNqWB_register_Asm_16:
7428   case ARM::VLD3LNqWB_register_Asm_32: {
7429     MCInst TmpInst;
7430     // Shuffle the operands around so the lane index operand is in the
7431     // right place.
7432     unsigned Spacing;
7433     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7434     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7435     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7436                                             Spacing));
7437     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7438                                             Spacing * 2));
7439     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7440     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7441     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7442     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7443     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7444     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7445                                             Spacing));
7446     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7447                                             Spacing * 2));
7448     TmpInst.addOperand(Inst.getOperand(1)); // lane
7449     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7450     TmpInst.addOperand(Inst.getOperand(6));
7451     Inst = TmpInst;
7452     return true;
7453   }
7454 
7455   case ARM::VLD4LNdWB_register_Asm_8:
7456   case ARM::VLD4LNdWB_register_Asm_16:
7457   case ARM::VLD4LNdWB_register_Asm_32:
7458   case ARM::VLD4LNqWB_register_Asm_16:
7459   case ARM::VLD4LNqWB_register_Asm_32: {
7460     MCInst TmpInst;
7461     // Shuffle the operands around so the lane index operand is in the
7462     // right place.
7463     unsigned Spacing;
7464     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7465     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7466     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7467                                             Spacing));
7468     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7469                                             Spacing * 2));
7470     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7471                                             Spacing * 3));
7472     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7473     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7474     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7475     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7476     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7477     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7478                                             Spacing));
7479     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7480                                             Spacing * 2));
7481     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7482                                             Spacing * 3));
7483     TmpInst.addOperand(Inst.getOperand(1)); // lane
7484     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7485     TmpInst.addOperand(Inst.getOperand(6));
7486     Inst = TmpInst;
7487     return true;
7488   }
7489 
7490   case ARM::VLD1LNdWB_fixed_Asm_8:
7491   case ARM::VLD1LNdWB_fixed_Asm_16:
7492   case ARM::VLD1LNdWB_fixed_Asm_32: {
7493     MCInst TmpInst;
7494     // Shuffle the operands around so the lane index operand is in the
7495     // right place.
7496     unsigned Spacing;
7497     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7498     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7499     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7500     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7501     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7502     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7503     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7504     TmpInst.addOperand(Inst.getOperand(1)); // lane
7505     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7506     TmpInst.addOperand(Inst.getOperand(5));
7507     Inst = TmpInst;
7508     return true;
7509   }
7510 
7511   case ARM::VLD2LNdWB_fixed_Asm_8:
7512   case ARM::VLD2LNdWB_fixed_Asm_16:
7513   case ARM::VLD2LNdWB_fixed_Asm_32:
7514   case ARM::VLD2LNqWB_fixed_Asm_16:
7515   case ARM::VLD2LNqWB_fixed_Asm_32: {
7516     MCInst TmpInst;
7517     // Shuffle the operands around so the lane index operand is in the
7518     // right place.
7519     unsigned Spacing;
7520     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7521     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7522     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7523                                             Spacing));
7524     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7525     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7526     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7527     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7528     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7529     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7530                                             Spacing));
7531     TmpInst.addOperand(Inst.getOperand(1)); // lane
7532     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7533     TmpInst.addOperand(Inst.getOperand(5));
7534     Inst = TmpInst;
7535     return true;
7536   }
7537 
7538   case ARM::VLD3LNdWB_fixed_Asm_8:
7539   case ARM::VLD3LNdWB_fixed_Asm_16:
7540   case ARM::VLD3LNdWB_fixed_Asm_32:
7541   case ARM::VLD3LNqWB_fixed_Asm_16:
7542   case ARM::VLD3LNqWB_fixed_Asm_32: {
7543     MCInst TmpInst;
7544     // Shuffle the operands around so the lane index operand is in the
7545     // right place.
7546     unsigned Spacing;
7547     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7548     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7549     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7550                                             Spacing));
7551     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7552                                             Spacing * 2));
7553     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7554     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7555     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7556     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7557     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7558     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7559                                             Spacing));
7560     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7561                                             Spacing * 2));
7562     TmpInst.addOperand(Inst.getOperand(1)); // lane
7563     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7564     TmpInst.addOperand(Inst.getOperand(5));
7565     Inst = TmpInst;
7566     return true;
7567   }
7568 
7569   case ARM::VLD4LNdWB_fixed_Asm_8:
7570   case ARM::VLD4LNdWB_fixed_Asm_16:
7571   case ARM::VLD4LNdWB_fixed_Asm_32:
7572   case ARM::VLD4LNqWB_fixed_Asm_16:
7573   case ARM::VLD4LNqWB_fixed_Asm_32: {
7574     MCInst TmpInst;
7575     // Shuffle the operands around so the lane index operand is in the
7576     // right place.
7577     unsigned Spacing;
7578     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7579     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7580     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7581                                             Spacing));
7582     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7583                                             Spacing * 2));
7584     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7585                                             Spacing * 3));
7586     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7587     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7588     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7589     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7590     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7591     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7592                                             Spacing));
7593     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7594                                             Spacing * 2));
7595     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7596                                             Spacing * 3));
7597     TmpInst.addOperand(Inst.getOperand(1)); // lane
7598     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7599     TmpInst.addOperand(Inst.getOperand(5));
7600     Inst = TmpInst;
7601     return true;
7602   }
7603 
7604   case ARM::VLD1LNdAsm_8:
7605   case ARM::VLD1LNdAsm_16:
7606   case ARM::VLD1LNdAsm_32: {
7607     MCInst TmpInst;
7608     // Shuffle the operands around so the lane index operand is in the
7609     // right place.
7610     unsigned Spacing;
7611     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7612     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7613     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7614     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7615     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7616     TmpInst.addOperand(Inst.getOperand(1)); // lane
7617     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7618     TmpInst.addOperand(Inst.getOperand(5));
7619     Inst = TmpInst;
7620     return true;
7621   }
7622 
7623   case ARM::VLD2LNdAsm_8:
7624   case ARM::VLD2LNdAsm_16:
7625   case ARM::VLD2LNdAsm_32:
7626   case ARM::VLD2LNqAsm_16:
7627   case ARM::VLD2LNqAsm_32: {
7628     MCInst TmpInst;
7629     // Shuffle the operands around so the lane index operand is in the
7630     // right place.
7631     unsigned Spacing;
7632     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7633     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7634     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7635                                             Spacing));
7636     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7637     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7638     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7639     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7640                                             Spacing));
7641     TmpInst.addOperand(Inst.getOperand(1)); // lane
7642     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7643     TmpInst.addOperand(Inst.getOperand(5));
7644     Inst = TmpInst;
7645     return true;
7646   }
7647 
7648   case ARM::VLD3LNdAsm_8:
7649   case ARM::VLD3LNdAsm_16:
7650   case ARM::VLD3LNdAsm_32:
7651   case ARM::VLD3LNqAsm_16:
7652   case ARM::VLD3LNqAsm_32: {
7653     MCInst TmpInst;
7654     // Shuffle the operands around so the lane index operand is in the
7655     // right place.
7656     unsigned Spacing;
7657     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7658     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7659     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7660                                             Spacing));
7661     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7662                                             Spacing * 2));
7663     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7664     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7665     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7666     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7667                                             Spacing));
7668     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7669                                             Spacing * 2));
7670     TmpInst.addOperand(Inst.getOperand(1)); // lane
7671     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7672     TmpInst.addOperand(Inst.getOperand(5));
7673     Inst = TmpInst;
7674     return true;
7675   }
7676 
7677   case ARM::VLD4LNdAsm_8:
7678   case ARM::VLD4LNdAsm_16:
7679   case ARM::VLD4LNdAsm_32:
7680   case ARM::VLD4LNqAsm_16:
7681   case ARM::VLD4LNqAsm_32: {
7682     MCInst TmpInst;
7683     // Shuffle the operands around so the lane index operand is in the
7684     // right place.
7685     unsigned Spacing;
7686     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7687     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7688     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7689                                             Spacing));
7690     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7691                                             Spacing * 2));
7692     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7693                                             Spacing * 3));
7694     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7695     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7696     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7697     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7698                                             Spacing));
7699     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7700                                             Spacing * 2));
7701     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7702                                             Spacing * 3));
7703     TmpInst.addOperand(Inst.getOperand(1)); // lane
7704     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7705     TmpInst.addOperand(Inst.getOperand(5));
7706     Inst = TmpInst;
7707     return true;
7708   }
7709 
7710   // VLD3DUP single 3-element structure to all lanes instructions.
7711   case ARM::VLD3DUPdAsm_8:
7712   case ARM::VLD3DUPdAsm_16:
7713   case ARM::VLD3DUPdAsm_32:
7714   case ARM::VLD3DUPqAsm_8:
7715   case ARM::VLD3DUPqAsm_16:
7716   case ARM::VLD3DUPqAsm_32: {
7717     MCInst TmpInst;
7718     unsigned Spacing;
7719     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7720     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7721     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7722                                             Spacing));
7723     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7724                                             Spacing * 2));
7725     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7726     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7727     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7728     TmpInst.addOperand(Inst.getOperand(4));
7729     Inst = TmpInst;
7730     return true;
7731   }
7732 
7733   case ARM::VLD3DUPdWB_fixed_Asm_8:
7734   case ARM::VLD3DUPdWB_fixed_Asm_16:
7735   case ARM::VLD3DUPdWB_fixed_Asm_32:
7736   case ARM::VLD3DUPqWB_fixed_Asm_8:
7737   case ARM::VLD3DUPqWB_fixed_Asm_16:
7738   case ARM::VLD3DUPqWB_fixed_Asm_32: {
7739     MCInst TmpInst;
7740     unsigned Spacing;
7741     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7742     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7743     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7744                                             Spacing));
7745     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7746                                             Spacing * 2));
7747     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7748     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7749     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7750     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7751     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7752     TmpInst.addOperand(Inst.getOperand(4));
7753     Inst = TmpInst;
7754     return true;
7755   }
7756 
7757   case ARM::VLD3DUPdWB_register_Asm_8:
7758   case ARM::VLD3DUPdWB_register_Asm_16:
7759   case ARM::VLD3DUPdWB_register_Asm_32:
7760   case ARM::VLD3DUPqWB_register_Asm_8:
7761   case ARM::VLD3DUPqWB_register_Asm_16:
7762   case ARM::VLD3DUPqWB_register_Asm_32: {
7763     MCInst TmpInst;
7764     unsigned Spacing;
7765     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7766     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7767     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7768                                             Spacing));
7769     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7770                                             Spacing * 2));
7771     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7772     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7773     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7774     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7775     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7776     TmpInst.addOperand(Inst.getOperand(5));
7777     Inst = TmpInst;
7778     return true;
7779   }
7780 
7781   // VLD3 multiple 3-element structure instructions.
7782   case ARM::VLD3dAsm_8:
7783   case ARM::VLD3dAsm_16:
7784   case ARM::VLD3dAsm_32:
7785   case ARM::VLD3qAsm_8:
7786   case ARM::VLD3qAsm_16:
7787   case ARM::VLD3qAsm_32: {
7788     MCInst TmpInst;
7789     unsigned Spacing;
7790     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7791     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7792     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7793                                             Spacing));
7794     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7795                                             Spacing * 2));
7796     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7797     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7798     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7799     TmpInst.addOperand(Inst.getOperand(4));
7800     Inst = TmpInst;
7801     return true;
7802   }
7803 
7804   case ARM::VLD3dWB_fixed_Asm_8:
7805   case ARM::VLD3dWB_fixed_Asm_16:
7806   case ARM::VLD3dWB_fixed_Asm_32:
7807   case ARM::VLD3qWB_fixed_Asm_8:
7808   case ARM::VLD3qWB_fixed_Asm_16:
7809   case ARM::VLD3qWB_fixed_Asm_32: {
7810     MCInst TmpInst;
7811     unsigned Spacing;
7812     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7813     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7814     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7815                                             Spacing));
7816     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7817                                             Spacing * 2));
7818     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7819     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7820     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7821     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7822     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7823     TmpInst.addOperand(Inst.getOperand(4));
7824     Inst = TmpInst;
7825     return true;
7826   }
7827 
7828   case ARM::VLD3dWB_register_Asm_8:
7829   case ARM::VLD3dWB_register_Asm_16:
7830   case ARM::VLD3dWB_register_Asm_32:
7831   case ARM::VLD3qWB_register_Asm_8:
7832   case ARM::VLD3qWB_register_Asm_16:
7833   case ARM::VLD3qWB_register_Asm_32: {
7834     MCInst TmpInst;
7835     unsigned Spacing;
7836     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7837     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7838     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7839                                             Spacing));
7840     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7841                                             Spacing * 2));
7842     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7843     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7844     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7845     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7846     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7847     TmpInst.addOperand(Inst.getOperand(5));
7848     Inst = TmpInst;
7849     return true;
7850   }
7851 
7852   // VLD4DUP single 3-element structure to all lanes instructions.
7853   case ARM::VLD4DUPdAsm_8:
7854   case ARM::VLD4DUPdAsm_16:
7855   case ARM::VLD4DUPdAsm_32:
7856   case ARM::VLD4DUPqAsm_8:
7857   case ARM::VLD4DUPqAsm_16:
7858   case ARM::VLD4DUPqAsm_32: {
7859     MCInst TmpInst;
7860     unsigned Spacing;
7861     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7862     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7863     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7864                                             Spacing));
7865     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7866                                             Spacing * 2));
7867     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7868                                             Spacing * 3));
7869     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7870     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7871     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7872     TmpInst.addOperand(Inst.getOperand(4));
7873     Inst = TmpInst;
7874     return true;
7875   }
7876 
7877   case ARM::VLD4DUPdWB_fixed_Asm_8:
7878   case ARM::VLD4DUPdWB_fixed_Asm_16:
7879   case ARM::VLD4DUPdWB_fixed_Asm_32:
7880   case ARM::VLD4DUPqWB_fixed_Asm_8:
7881   case ARM::VLD4DUPqWB_fixed_Asm_16:
7882   case ARM::VLD4DUPqWB_fixed_Asm_32: {
7883     MCInst TmpInst;
7884     unsigned Spacing;
7885     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7886     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7887     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7888                                             Spacing));
7889     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7890                                             Spacing * 2));
7891     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7892                                             Spacing * 3));
7893     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7894     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7895     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7896     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7897     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7898     TmpInst.addOperand(Inst.getOperand(4));
7899     Inst = TmpInst;
7900     return true;
7901   }
7902 
7903   case ARM::VLD4DUPdWB_register_Asm_8:
7904   case ARM::VLD4DUPdWB_register_Asm_16:
7905   case ARM::VLD4DUPdWB_register_Asm_32:
7906   case ARM::VLD4DUPqWB_register_Asm_8:
7907   case ARM::VLD4DUPqWB_register_Asm_16:
7908   case ARM::VLD4DUPqWB_register_Asm_32: {
7909     MCInst TmpInst;
7910     unsigned Spacing;
7911     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7912     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7913     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7914                                             Spacing));
7915     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7916                                             Spacing * 2));
7917     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7918                                             Spacing * 3));
7919     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7920     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7921     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7922     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7923     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7924     TmpInst.addOperand(Inst.getOperand(5));
7925     Inst = TmpInst;
7926     return true;
7927   }
7928 
7929   // VLD4 multiple 4-element structure instructions.
7930   case ARM::VLD4dAsm_8:
7931   case ARM::VLD4dAsm_16:
7932   case ARM::VLD4dAsm_32:
7933   case ARM::VLD4qAsm_8:
7934   case ARM::VLD4qAsm_16:
7935   case ARM::VLD4qAsm_32: {
7936     MCInst TmpInst;
7937     unsigned Spacing;
7938     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7939     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7940     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7941                                             Spacing));
7942     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7943                                             Spacing * 2));
7944     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7945                                             Spacing * 3));
7946     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7947     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7948     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7949     TmpInst.addOperand(Inst.getOperand(4));
7950     Inst = TmpInst;
7951     return true;
7952   }
7953 
7954   case ARM::VLD4dWB_fixed_Asm_8:
7955   case ARM::VLD4dWB_fixed_Asm_16:
7956   case ARM::VLD4dWB_fixed_Asm_32:
7957   case ARM::VLD4qWB_fixed_Asm_8:
7958   case ARM::VLD4qWB_fixed_Asm_16:
7959   case ARM::VLD4qWB_fixed_Asm_32: {
7960     MCInst TmpInst;
7961     unsigned Spacing;
7962     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7963     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7964     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7965                                             Spacing));
7966     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7967                                             Spacing * 2));
7968     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7969                                             Spacing * 3));
7970     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7971     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7972     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7973     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7974     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7975     TmpInst.addOperand(Inst.getOperand(4));
7976     Inst = TmpInst;
7977     return true;
7978   }
7979 
7980   case ARM::VLD4dWB_register_Asm_8:
7981   case ARM::VLD4dWB_register_Asm_16:
7982   case ARM::VLD4dWB_register_Asm_32:
7983   case ARM::VLD4qWB_register_Asm_8:
7984   case ARM::VLD4qWB_register_Asm_16:
7985   case ARM::VLD4qWB_register_Asm_32: {
7986     MCInst TmpInst;
7987     unsigned Spacing;
7988     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7989     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7990     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7991                                             Spacing));
7992     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7993                                             Spacing * 2));
7994     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7995                                             Spacing * 3));
7996     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7997     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7998     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7999     TmpInst.addOperand(Inst.getOperand(3)); // Rm
8000     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8001     TmpInst.addOperand(Inst.getOperand(5));
8002     Inst = TmpInst;
8003     return true;
8004   }
8005 
8006   // VST3 multiple 3-element structure instructions.
8007   case ARM::VST3dAsm_8:
8008   case ARM::VST3dAsm_16:
8009   case ARM::VST3dAsm_32:
8010   case ARM::VST3qAsm_8:
8011   case ARM::VST3qAsm_16:
8012   case ARM::VST3qAsm_32: {
8013     MCInst TmpInst;
8014     unsigned Spacing;
8015     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8016     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8017     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8018     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8019     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8020                                             Spacing));
8021     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8022                                             Spacing * 2));
8023     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8024     TmpInst.addOperand(Inst.getOperand(4));
8025     Inst = TmpInst;
8026     return true;
8027   }
8028 
8029   case ARM::VST3dWB_fixed_Asm_8:
8030   case ARM::VST3dWB_fixed_Asm_16:
8031   case ARM::VST3dWB_fixed_Asm_32:
8032   case ARM::VST3qWB_fixed_Asm_8:
8033   case ARM::VST3qWB_fixed_Asm_16:
8034   case ARM::VST3qWB_fixed_Asm_32: {
8035     MCInst TmpInst;
8036     unsigned Spacing;
8037     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8038     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8039     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8040     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8041     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8042     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8043     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8044                                             Spacing));
8045     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8046                                             Spacing * 2));
8047     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8048     TmpInst.addOperand(Inst.getOperand(4));
8049     Inst = TmpInst;
8050     return true;
8051   }
8052 
8053   case ARM::VST3dWB_register_Asm_8:
8054   case ARM::VST3dWB_register_Asm_16:
8055   case ARM::VST3dWB_register_Asm_32:
8056   case ARM::VST3qWB_register_Asm_8:
8057   case ARM::VST3qWB_register_Asm_16:
8058   case ARM::VST3qWB_register_Asm_32: {
8059     MCInst TmpInst;
8060     unsigned Spacing;
8061     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8062     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8063     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8064     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8065     TmpInst.addOperand(Inst.getOperand(3)); // Rm
8066     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8067     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8068                                             Spacing));
8069     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8070                                             Spacing * 2));
8071     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8072     TmpInst.addOperand(Inst.getOperand(5));
8073     Inst = TmpInst;
8074     return true;
8075   }
8076 
8077   // VST4 multiple 3-element structure instructions.
8078   case ARM::VST4dAsm_8:
8079   case ARM::VST4dAsm_16:
8080   case ARM::VST4dAsm_32:
8081   case ARM::VST4qAsm_8:
8082   case ARM::VST4qAsm_16:
8083   case ARM::VST4qAsm_32: {
8084     MCInst TmpInst;
8085     unsigned Spacing;
8086     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8087     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8088     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8089     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8090     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8091                                             Spacing));
8092     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8093                                             Spacing * 2));
8094     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8095                                             Spacing * 3));
8096     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8097     TmpInst.addOperand(Inst.getOperand(4));
8098     Inst = TmpInst;
8099     return true;
8100   }
8101 
8102   case ARM::VST4dWB_fixed_Asm_8:
8103   case ARM::VST4dWB_fixed_Asm_16:
8104   case ARM::VST4dWB_fixed_Asm_32:
8105   case ARM::VST4qWB_fixed_Asm_8:
8106   case ARM::VST4qWB_fixed_Asm_16:
8107   case ARM::VST4qWB_fixed_Asm_32: {
8108     MCInst TmpInst;
8109     unsigned Spacing;
8110     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8111     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8112     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8113     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8114     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8115     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8116     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8117                                             Spacing));
8118     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8119                                             Spacing * 2));
8120     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8121                                             Spacing * 3));
8122     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8123     TmpInst.addOperand(Inst.getOperand(4));
8124     Inst = TmpInst;
8125     return true;
8126   }
8127 
8128   case ARM::VST4dWB_register_Asm_8:
8129   case ARM::VST4dWB_register_Asm_16:
8130   case ARM::VST4dWB_register_Asm_32:
8131   case ARM::VST4qWB_register_Asm_8:
8132   case ARM::VST4qWB_register_Asm_16:
8133   case ARM::VST4qWB_register_Asm_32: {
8134     MCInst TmpInst;
8135     unsigned Spacing;
8136     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8137     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8138     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8139     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8140     TmpInst.addOperand(Inst.getOperand(3)); // Rm
8141     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8142     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8143                                             Spacing));
8144     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8145                                             Spacing * 2));
8146     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8147                                             Spacing * 3));
8148     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8149     TmpInst.addOperand(Inst.getOperand(5));
8150     Inst = TmpInst;
8151     return true;
8152   }
8153 
8154   // Handle encoding choice for the shift-immediate instructions.
8155   case ARM::t2LSLri:
8156   case ARM::t2LSRri:
8157   case ARM::t2ASRri:
8158     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8159         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8160         Inst.getOperand(5).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
8161         !HasWideQualifier) {
8162       unsigned NewOpc;
8163       switch (Inst.getOpcode()) {
8164       default: llvm_unreachable("unexpected opcode");
8165       case ARM::t2LSLri: NewOpc = ARM::tLSLri; break;
8166       case ARM::t2LSRri: NewOpc = ARM::tLSRri; break;
8167       case ARM::t2ASRri: NewOpc = ARM::tASRri; break;
8168       }
8169       // The Thumb1 operands aren't in the same order. Awesome, eh?
8170       MCInst TmpInst;
8171       TmpInst.setOpcode(NewOpc);
8172       TmpInst.addOperand(Inst.getOperand(0));
8173       TmpInst.addOperand(Inst.getOperand(5));
8174       TmpInst.addOperand(Inst.getOperand(1));
8175       TmpInst.addOperand(Inst.getOperand(2));
8176       TmpInst.addOperand(Inst.getOperand(3));
8177       TmpInst.addOperand(Inst.getOperand(4));
8178       Inst = TmpInst;
8179       return true;
8180     }
8181     return false;
8182 
8183   // Handle the Thumb2 mode MOV complex aliases.
8184   case ARM::t2MOVsr:
8185   case ARM::t2MOVSsr: {
8186     // Which instruction to expand to depends on the CCOut operand and
8187     // whether we're in an IT block if the register operands are low
8188     // registers.
8189     bool isNarrow = false;
8190     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8191         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8192         isARMLowRegister(Inst.getOperand(2).getReg()) &&
8193         Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() &&
8194         inITBlock() == (Inst.getOpcode() == ARM::t2MOVsr) &&
8195         !HasWideQualifier)
8196       isNarrow = true;
8197     MCInst TmpInst;
8198     unsigned newOpc;
8199     switch(ARM_AM::getSORegShOp(Inst.getOperand(3).getImm())) {
8200     default: llvm_unreachable("unexpected opcode!");
8201     case ARM_AM::asr: newOpc = isNarrow ? ARM::tASRrr : ARM::t2ASRrr; break;
8202     case ARM_AM::lsr: newOpc = isNarrow ? ARM::tLSRrr : ARM::t2LSRrr; break;
8203     case ARM_AM::lsl: newOpc = isNarrow ? ARM::tLSLrr : ARM::t2LSLrr; break;
8204     case ARM_AM::ror: newOpc = isNarrow ? ARM::tROR   : ARM::t2RORrr; break;
8205     }
8206     TmpInst.setOpcode(newOpc);
8207     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8208     if (isNarrow)
8209       TmpInst.addOperand(MCOperand::createReg(
8210           Inst.getOpcode() == ARM::t2MOVSsr ? ARM::CPSR : 0));
8211     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8212     TmpInst.addOperand(Inst.getOperand(2)); // Rm
8213     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8214     TmpInst.addOperand(Inst.getOperand(5));
8215     if (!isNarrow)
8216       TmpInst.addOperand(MCOperand::createReg(
8217           Inst.getOpcode() == ARM::t2MOVSsr ? ARM::CPSR : 0));
8218     Inst = TmpInst;
8219     return true;
8220   }
8221   case ARM::t2MOVsi:
8222   case ARM::t2MOVSsi: {
8223     // Which instruction to expand to depends on the CCOut operand and
8224     // whether we're in an IT block if the register operands are low
8225     // registers.
8226     bool isNarrow = false;
8227     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8228         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8229         inITBlock() == (Inst.getOpcode() == ARM::t2MOVsi) &&
8230         !HasWideQualifier)
8231       isNarrow = true;
8232     MCInst TmpInst;
8233     unsigned newOpc;
8234     unsigned Shift = ARM_AM::getSORegShOp(Inst.getOperand(2).getImm());
8235     unsigned Amount = ARM_AM::getSORegOffset(Inst.getOperand(2).getImm());
8236     bool isMov = false;
8237     // MOV rd, rm, LSL #0 is actually a MOV instruction
8238     if (Shift == ARM_AM::lsl && Amount == 0) {
8239       isMov = true;
8240       // The 16-bit encoding of MOV rd, rm, LSL #N is explicitly encoding T2 of
8241       // MOV (register) in the ARMv8-A and ARMv8-M manuals, and immediate 0 is
8242       // unpredictable in an IT block so the 32-bit encoding T3 has to be used
8243       // instead.
8244       if (inITBlock()) {
8245         isNarrow = false;
8246       }
8247       newOpc = isNarrow ? ARM::tMOVSr : ARM::t2MOVr;
8248     } else {
8249       switch(Shift) {
8250       default: llvm_unreachable("unexpected opcode!");
8251       case ARM_AM::asr: newOpc = isNarrow ? ARM::tASRri : ARM::t2ASRri; break;
8252       case ARM_AM::lsr: newOpc = isNarrow ? ARM::tLSRri : ARM::t2LSRri; break;
8253       case ARM_AM::lsl: newOpc = isNarrow ? ARM::tLSLri : ARM::t2LSLri; break;
8254       case ARM_AM::ror: newOpc = ARM::t2RORri; isNarrow = false; break;
8255       case ARM_AM::rrx: isNarrow = false; newOpc = ARM::t2RRX; break;
8256       }
8257     }
8258     if (Amount == 32) Amount = 0;
8259     TmpInst.setOpcode(newOpc);
8260     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8261     if (isNarrow && !isMov)
8262       TmpInst.addOperand(MCOperand::createReg(
8263           Inst.getOpcode() == ARM::t2MOVSsi ? ARM::CPSR : 0));
8264     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8265     if (newOpc != ARM::t2RRX && !isMov)
8266       TmpInst.addOperand(MCOperand::createImm(Amount));
8267     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8268     TmpInst.addOperand(Inst.getOperand(4));
8269     if (!isNarrow)
8270       TmpInst.addOperand(MCOperand::createReg(
8271           Inst.getOpcode() == ARM::t2MOVSsi ? ARM::CPSR : 0));
8272     Inst = TmpInst;
8273     return true;
8274   }
8275   // Handle the ARM mode MOV complex aliases.
8276   case ARM::ASRr:
8277   case ARM::LSRr:
8278   case ARM::LSLr:
8279   case ARM::RORr: {
8280     ARM_AM::ShiftOpc ShiftTy;
8281     switch(Inst.getOpcode()) {
8282     default: llvm_unreachable("unexpected opcode!");
8283     case ARM::ASRr: ShiftTy = ARM_AM::asr; break;
8284     case ARM::LSRr: ShiftTy = ARM_AM::lsr; break;
8285     case ARM::LSLr: ShiftTy = ARM_AM::lsl; break;
8286     case ARM::RORr: ShiftTy = ARM_AM::ror; break;
8287     }
8288     unsigned Shifter = ARM_AM::getSORegOpc(ShiftTy, 0);
8289     MCInst TmpInst;
8290     TmpInst.setOpcode(ARM::MOVsr);
8291     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8292     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8293     TmpInst.addOperand(Inst.getOperand(2)); // Rm
8294     TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
8295     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8296     TmpInst.addOperand(Inst.getOperand(4));
8297     TmpInst.addOperand(Inst.getOperand(5)); // cc_out
8298     Inst = TmpInst;
8299     return true;
8300   }
8301   case ARM::ASRi:
8302   case ARM::LSRi:
8303   case ARM::LSLi:
8304   case ARM::RORi: {
8305     ARM_AM::ShiftOpc ShiftTy;
8306     switch(Inst.getOpcode()) {
8307     default: llvm_unreachable("unexpected opcode!");
8308     case ARM::ASRi: ShiftTy = ARM_AM::asr; break;
8309     case ARM::LSRi: ShiftTy = ARM_AM::lsr; break;
8310     case ARM::LSLi: ShiftTy = ARM_AM::lsl; break;
8311     case ARM::RORi: ShiftTy = ARM_AM::ror; break;
8312     }
8313     // A shift by zero is a plain MOVr, not a MOVsi.
8314     unsigned Amt = Inst.getOperand(2).getImm();
8315     unsigned Opc = Amt == 0 ? ARM::MOVr : ARM::MOVsi;
8316     // A shift by 32 should be encoded as 0 when permitted
8317     if (Amt == 32 && (ShiftTy == ARM_AM::lsr || ShiftTy == ARM_AM::asr))
8318       Amt = 0;
8319     unsigned Shifter = ARM_AM::getSORegOpc(ShiftTy, Amt);
8320     MCInst TmpInst;
8321     TmpInst.setOpcode(Opc);
8322     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8323     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8324     if (Opc == ARM::MOVsi)
8325       TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
8326     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8327     TmpInst.addOperand(Inst.getOperand(4));
8328     TmpInst.addOperand(Inst.getOperand(5)); // cc_out
8329     Inst = TmpInst;
8330     return true;
8331   }
8332   case ARM::RRXi: {
8333     unsigned Shifter = ARM_AM::getSORegOpc(ARM_AM::rrx, 0);
8334     MCInst TmpInst;
8335     TmpInst.setOpcode(ARM::MOVsi);
8336     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8337     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8338     TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
8339     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8340     TmpInst.addOperand(Inst.getOperand(3));
8341     TmpInst.addOperand(Inst.getOperand(4)); // cc_out
8342     Inst = TmpInst;
8343     return true;
8344   }
8345   case ARM::t2LDMIA_UPD: {
8346     // If this is a load of a single register, then we should use
8347     // a post-indexed LDR instruction instead, per the ARM ARM.
8348     if (Inst.getNumOperands() != 5)
8349       return false;
8350     MCInst TmpInst;
8351     TmpInst.setOpcode(ARM::t2LDR_POST);
8352     TmpInst.addOperand(Inst.getOperand(4)); // Rt
8353     TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8354     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8355     TmpInst.addOperand(MCOperand::createImm(4));
8356     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8357     TmpInst.addOperand(Inst.getOperand(3));
8358     Inst = TmpInst;
8359     return true;
8360   }
8361   case ARM::t2STMDB_UPD: {
8362     // If this is a store of a single register, then we should use
8363     // a pre-indexed STR instruction instead, per the ARM ARM.
8364     if (Inst.getNumOperands() != 5)
8365       return false;
8366     MCInst TmpInst;
8367     TmpInst.setOpcode(ARM::t2STR_PRE);
8368     TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8369     TmpInst.addOperand(Inst.getOperand(4)); // Rt
8370     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8371     TmpInst.addOperand(MCOperand::createImm(-4));
8372     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8373     TmpInst.addOperand(Inst.getOperand(3));
8374     Inst = TmpInst;
8375     return true;
8376   }
8377   case ARM::LDMIA_UPD:
8378     // If this is a load of a single register via a 'pop', then we should use
8379     // a post-indexed LDR instruction instead, per the ARM ARM.
8380     if (static_cast<ARMOperand &>(*Operands[0]).getToken() == "pop" &&
8381         Inst.getNumOperands() == 5) {
8382       MCInst TmpInst;
8383       TmpInst.setOpcode(ARM::LDR_POST_IMM);
8384       TmpInst.addOperand(Inst.getOperand(4)); // Rt
8385       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8386       TmpInst.addOperand(Inst.getOperand(1)); // Rn
8387       TmpInst.addOperand(MCOperand::createReg(0));  // am2offset
8388       TmpInst.addOperand(MCOperand::createImm(4));
8389       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8390       TmpInst.addOperand(Inst.getOperand(3));
8391       Inst = TmpInst;
8392       return true;
8393     }
8394     break;
8395   case ARM::STMDB_UPD:
8396     // If this is a store of a single register via a 'push', then we should use
8397     // a pre-indexed STR instruction instead, per the ARM ARM.
8398     if (static_cast<ARMOperand &>(*Operands[0]).getToken() == "push" &&
8399         Inst.getNumOperands() == 5) {
8400       MCInst TmpInst;
8401       TmpInst.setOpcode(ARM::STR_PRE_IMM);
8402       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8403       TmpInst.addOperand(Inst.getOperand(4)); // Rt
8404       TmpInst.addOperand(Inst.getOperand(1)); // addrmode_imm12
8405       TmpInst.addOperand(MCOperand::createImm(-4));
8406       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8407       TmpInst.addOperand(Inst.getOperand(3));
8408       Inst = TmpInst;
8409     }
8410     break;
8411   case ARM::t2ADDri12:
8412     // If the immediate fits for encoding T3 (t2ADDri) and the generic "add"
8413     // mnemonic was used (not "addw"), encoding T3 is preferred.
8414     if (static_cast<ARMOperand &>(*Operands[0]).getToken() != "add" ||
8415         ARM_AM::getT2SOImmVal(Inst.getOperand(2).getImm()) == -1)
8416       break;
8417     Inst.setOpcode(ARM::t2ADDri);
8418     Inst.addOperand(MCOperand::createReg(0)); // cc_out
8419     break;
8420   case ARM::t2SUBri12:
8421     // If the immediate fits for encoding T3 (t2SUBri) and the generic "sub"
8422     // mnemonic was used (not "subw"), encoding T3 is preferred.
8423     if (static_cast<ARMOperand &>(*Operands[0]).getToken() != "sub" ||
8424         ARM_AM::getT2SOImmVal(Inst.getOperand(2).getImm()) == -1)
8425       break;
8426     Inst.setOpcode(ARM::t2SUBri);
8427     Inst.addOperand(MCOperand::createReg(0)); // cc_out
8428     break;
8429   case ARM::tADDi8:
8430     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
8431     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
8432     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
8433     // to encoding T1 if <Rd> is omitted."
8434     if ((unsigned)Inst.getOperand(3).getImm() < 8 && Operands.size() == 6) {
8435       Inst.setOpcode(ARM::tADDi3);
8436       return true;
8437     }
8438     break;
8439   case ARM::tSUBi8:
8440     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
8441     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
8442     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
8443     // to encoding T1 if <Rd> is omitted."
8444     if ((unsigned)Inst.getOperand(3).getImm() < 8 && Operands.size() == 6) {
8445       Inst.setOpcode(ARM::tSUBi3);
8446       return true;
8447     }
8448     break;
8449   case ARM::t2ADDri:
8450   case ARM::t2SUBri: {
8451     // If the destination and first source operand are the same, and
8452     // the flags are compatible with the current IT status, use encoding T2
8453     // instead of T3. For compatibility with the system 'as'. Make sure the
8454     // wide encoding wasn't explicit.
8455     if (Inst.getOperand(0).getReg() != Inst.getOperand(1).getReg() ||
8456         !isARMLowRegister(Inst.getOperand(0).getReg()) ||
8457         (Inst.getOperand(2).isImm() &&
8458          (unsigned)Inst.getOperand(2).getImm() > 255) ||
8459         Inst.getOperand(5).getReg() != (inITBlock() ? 0 : ARM::CPSR) ||
8460         HasWideQualifier)
8461       break;
8462     MCInst TmpInst;
8463     TmpInst.setOpcode(Inst.getOpcode() == ARM::t2ADDri ?
8464                       ARM::tADDi8 : ARM::tSUBi8);
8465     TmpInst.addOperand(Inst.getOperand(0));
8466     TmpInst.addOperand(Inst.getOperand(5));
8467     TmpInst.addOperand(Inst.getOperand(0));
8468     TmpInst.addOperand(Inst.getOperand(2));
8469     TmpInst.addOperand(Inst.getOperand(3));
8470     TmpInst.addOperand(Inst.getOperand(4));
8471     Inst = TmpInst;
8472     return true;
8473   }
8474   case ARM::t2ADDrr: {
8475     // If the destination and first source operand are the same, and
8476     // there's no setting of the flags, use encoding T2 instead of T3.
8477     // Note that this is only for ADD, not SUB. This mirrors the system
8478     // 'as' behaviour.  Also take advantage of ADD being commutative.
8479     // Make sure the wide encoding wasn't explicit.
8480     bool Swap = false;
8481     auto DestReg = Inst.getOperand(0).getReg();
8482     bool Transform = DestReg == Inst.getOperand(1).getReg();
8483     if (!Transform && DestReg == Inst.getOperand(2).getReg()) {
8484       Transform = true;
8485       Swap = true;
8486     }
8487     if (!Transform ||
8488         Inst.getOperand(5).getReg() != 0 ||
8489         HasWideQualifier)
8490       break;
8491     MCInst TmpInst;
8492     TmpInst.setOpcode(ARM::tADDhirr);
8493     TmpInst.addOperand(Inst.getOperand(0));
8494     TmpInst.addOperand(Inst.getOperand(0));
8495     TmpInst.addOperand(Inst.getOperand(Swap ? 1 : 2));
8496     TmpInst.addOperand(Inst.getOperand(3));
8497     TmpInst.addOperand(Inst.getOperand(4));
8498     Inst = TmpInst;
8499     return true;
8500   }
8501   case ARM::tADDrSP:
8502     // If the non-SP source operand and the destination operand are not the
8503     // same, we need to use the 32-bit encoding if it's available.
8504     if (Inst.getOperand(0).getReg() != Inst.getOperand(2).getReg()) {
8505       Inst.setOpcode(ARM::t2ADDrr);
8506       Inst.addOperand(MCOperand::createReg(0)); // cc_out
8507       return true;
8508     }
8509     break;
8510   case ARM::tB:
8511     // A Thumb conditional branch outside of an IT block is a tBcc.
8512     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock()) {
8513       Inst.setOpcode(ARM::tBcc);
8514       return true;
8515     }
8516     break;
8517   case ARM::t2B:
8518     // A Thumb2 conditional branch outside of an IT block is a t2Bcc.
8519     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock()){
8520       Inst.setOpcode(ARM::t2Bcc);
8521       return true;
8522     }
8523     break;
8524   case ARM::t2Bcc:
8525     // If the conditional is AL or we're in an IT block, we really want t2B.
8526     if (Inst.getOperand(1).getImm() == ARMCC::AL || inITBlock()) {
8527       Inst.setOpcode(ARM::t2B);
8528       return true;
8529     }
8530     break;
8531   case ARM::tBcc:
8532     // If the conditional is AL, we really want tB.
8533     if (Inst.getOperand(1).getImm() == ARMCC::AL) {
8534       Inst.setOpcode(ARM::tB);
8535       return true;
8536     }
8537     break;
8538   case ARM::tLDMIA: {
8539     // If the register list contains any high registers, or if the writeback
8540     // doesn't match what tLDMIA can do, we need to use the 32-bit encoding
8541     // instead if we're in Thumb2. Otherwise, this should have generated
8542     // an error in validateInstruction().
8543     unsigned Rn = Inst.getOperand(0).getReg();
8544     bool hasWritebackToken =
8545         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
8546          static_cast<ARMOperand &>(*Operands[3]).getToken() == "!");
8547     bool listContainsBase;
8548     if (checkLowRegisterList(Inst, 3, Rn, 0, listContainsBase) ||
8549         (!listContainsBase && !hasWritebackToken) ||
8550         (listContainsBase && hasWritebackToken)) {
8551       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
8552       assert(isThumbTwo());
8553       Inst.setOpcode(hasWritebackToken ? ARM::t2LDMIA_UPD : ARM::t2LDMIA);
8554       // If we're switching to the updating version, we need to insert
8555       // the writeback tied operand.
8556       if (hasWritebackToken)
8557         Inst.insert(Inst.begin(),
8558                     MCOperand::createReg(Inst.getOperand(0).getReg()));
8559       return true;
8560     }
8561     break;
8562   }
8563   case ARM::tSTMIA_UPD: {
8564     // If the register list contains any high registers, we need to use
8565     // the 32-bit encoding instead if we're in Thumb2. Otherwise, this
8566     // should have generated an error in validateInstruction().
8567     unsigned Rn = Inst.getOperand(0).getReg();
8568     bool listContainsBase;
8569     if (checkLowRegisterList(Inst, 4, Rn, 0, listContainsBase)) {
8570       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
8571       assert(isThumbTwo());
8572       Inst.setOpcode(ARM::t2STMIA_UPD);
8573       return true;
8574     }
8575     break;
8576   }
8577   case ARM::tPOP: {
8578     bool listContainsBase;
8579     // If the register list contains any high registers, we need to use
8580     // the 32-bit encoding instead if we're in Thumb2. Otherwise, this
8581     // should have generated an error in validateInstruction().
8582     if (!checkLowRegisterList(Inst, 2, 0, ARM::PC, listContainsBase))
8583       return false;
8584     assert(isThumbTwo());
8585     Inst.setOpcode(ARM::t2LDMIA_UPD);
8586     // Add the base register and writeback operands.
8587     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8588     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8589     return true;
8590   }
8591   case ARM::tPUSH: {
8592     bool listContainsBase;
8593     if (!checkLowRegisterList(Inst, 2, 0, ARM::LR, listContainsBase))
8594       return false;
8595     assert(isThumbTwo());
8596     Inst.setOpcode(ARM::t2STMDB_UPD);
8597     // Add the base register and writeback operands.
8598     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8599     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8600     return true;
8601   }
8602   case ARM::t2MOVi:
8603     // If we can use the 16-bit encoding and the user didn't explicitly
8604     // request the 32-bit variant, transform it here.
8605     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8606         (Inst.getOperand(1).isImm() &&
8607          (unsigned)Inst.getOperand(1).getImm() <= 255) &&
8608         Inst.getOperand(4).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
8609         !HasWideQualifier) {
8610       // The operands aren't in the same order for tMOVi8...
8611       MCInst TmpInst;
8612       TmpInst.setOpcode(ARM::tMOVi8);
8613       TmpInst.addOperand(Inst.getOperand(0));
8614       TmpInst.addOperand(Inst.getOperand(4));
8615       TmpInst.addOperand(Inst.getOperand(1));
8616       TmpInst.addOperand(Inst.getOperand(2));
8617       TmpInst.addOperand(Inst.getOperand(3));
8618       Inst = TmpInst;
8619       return true;
8620     }
8621     break;
8622 
8623   case ARM::t2MOVr:
8624     // If we can use the 16-bit encoding and the user didn't explicitly
8625     // request the 32-bit variant, transform it here.
8626     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8627         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8628         Inst.getOperand(2).getImm() == ARMCC::AL &&
8629         Inst.getOperand(4).getReg() == ARM::CPSR &&
8630         !HasWideQualifier) {
8631       // The operands aren't the same for tMOV[S]r... (no cc_out)
8632       MCInst TmpInst;
8633       TmpInst.setOpcode(Inst.getOperand(4).getReg() ? ARM::tMOVSr : ARM::tMOVr);
8634       TmpInst.addOperand(Inst.getOperand(0));
8635       TmpInst.addOperand(Inst.getOperand(1));
8636       TmpInst.addOperand(Inst.getOperand(2));
8637       TmpInst.addOperand(Inst.getOperand(3));
8638       Inst = TmpInst;
8639       return true;
8640     }
8641     break;
8642 
8643   case ARM::t2SXTH:
8644   case ARM::t2SXTB:
8645   case ARM::t2UXTH:
8646   case ARM::t2UXTB:
8647     // If we can use the 16-bit encoding and the user didn't explicitly
8648     // request the 32-bit variant, transform it here.
8649     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8650         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8651         Inst.getOperand(2).getImm() == 0 &&
8652         !HasWideQualifier) {
8653       unsigned NewOpc;
8654       switch (Inst.getOpcode()) {
8655       default: llvm_unreachable("Illegal opcode!");
8656       case ARM::t2SXTH: NewOpc = ARM::tSXTH; break;
8657       case ARM::t2SXTB: NewOpc = ARM::tSXTB; break;
8658       case ARM::t2UXTH: NewOpc = ARM::tUXTH; break;
8659       case ARM::t2UXTB: NewOpc = ARM::tUXTB; break;
8660       }
8661       // The operands aren't the same for thumb1 (no rotate operand).
8662       MCInst TmpInst;
8663       TmpInst.setOpcode(NewOpc);
8664       TmpInst.addOperand(Inst.getOperand(0));
8665       TmpInst.addOperand(Inst.getOperand(1));
8666       TmpInst.addOperand(Inst.getOperand(3));
8667       TmpInst.addOperand(Inst.getOperand(4));
8668       Inst = TmpInst;
8669       return true;
8670     }
8671     break;
8672 
8673   case ARM::MOVsi: {
8674     ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(Inst.getOperand(2).getImm());
8675     // rrx shifts and asr/lsr of #32 is encoded as 0
8676     if (SOpc == ARM_AM::rrx || SOpc == ARM_AM::asr || SOpc == ARM_AM::lsr)
8677       return false;
8678     if (ARM_AM::getSORegOffset(Inst.getOperand(2).getImm()) == 0) {
8679       // Shifting by zero is accepted as a vanilla 'MOVr'
8680       MCInst TmpInst;
8681       TmpInst.setOpcode(ARM::MOVr);
8682       TmpInst.addOperand(Inst.getOperand(0));
8683       TmpInst.addOperand(Inst.getOperand(1));
8684       TmpInst.addOperand(Inst.getOperand(3));
8685       TmpInst.addOperand(Inst.getOperand(4));
8686       TmpInst.addOperand(Inst.getOperand(5));
8687       Inst = TmpInst;
8688       return true;
8689     }
8690     return false;
8691   }
8692   case ARM::ANDrsi:
8693   case ARM::ORRrsi:
8694   case ARM::EORrsi:
8695   case ARM::BICrsi:
8696   case ARM::SUBrsi:
8697   case ARM::ADDrsi: {
8698     unsigned newOpc;
8699     ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(Inst.getOperand(3).getImm());
8700     if (SOpc == ARM_AM::rrx) return false;
8701     switch (Inst.getOpcode()) {
8702     default: llvm_unreachable("unexpected opcode!");
8703     case ARM::ANDrsi: newOpc = ARM::ANDrr; break;
8704     case ARM::ORRrsi: newOpc = ARM::ORRrr; break;
8705     case ARM::EORrsi: newOpc = ARM::EORrr; break;
8706     case ARM::BICrsi: newOpc = ARM::BICrr; break;
8707     case ARM::SUBrsi: newOpc = ARM::SUBrr; break;
8708     case ARM::ADDrsi: newOpc = ARM::ADDrr; break;
8709     }
8710     // If the shift is by zero, use the non-shifted instruction definition.
8711     // The exception is for right shifts, where 0 == 32
8712     if (ARM_AM::getSORegOffset(Inst.getOperand(3).getImm()) == 0 &&
8713         !(SOpc == ARM_AM::lsr || SOpc == ARM_AM::asr)) {
8714       MCInst TmpInst;
8715       TmpInst.setOpcode(newOpc);
8716       TmpInst.addOperand(Inst.getOperand(0));
8717       TmpInst.addOperand(Inst.getOperand(1));
8718       TmpInst.addOperand(Inst.getOperand(2));
8719       TmpInst.addOperand(Inst.getOperand(4));
8720       TmpInst.addOperand(Inst.getOperand(5));
8721       TmpInst.addOperand(Inst.getOperand(6));
8722       Inst = TmpInst;
8723       return true;
8724     }
8725     return false;
8726   }
8727   case ARM::ITasm:
8728   case ARM::t2IT: {
8729     MCOperand &MO = Inst.getOperand(1);
8730     unsigned Mask = MO.getImm();
8731     ARMCC::CondCodes Cond = ARMCC::CondCodes(Inst.getOperand(0).getImm());
8732 
8733     // Set up the IT block state according to the IT instruction we just
8734     // matched.
8735     assert(!inITBlock() && "nested IT blocks?!");
8736     startExplicitITBlock(Cond, Mask);
8737     MO.setImm(getITMaskEncoding());
8738     break;
8739   }
8740   case ARM::t2LSLrr:
8741   case ARM::t2LSRrr:
8742   case ARM::t2ASRrr:
8743   case ARM::t2SBCrr:
8744   case ARM::t2RORrr:
8745   case ARM::t2BICrr:
8746     // Assemblers should use the narrow encodings of these instructions when permissible.
8747     if ((isARMLowRegister(Inst.getOperand(1).getReg()) &&
8748          isARMLowRegister(Inst.getOperand(2).getReg())) &&
8749         Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() &&
8750         Inst.getOperand(5).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
8751         !HasWideQualifier) {
8752       unsigned NewOpc;
8753       switch (Inst.getOpcode()) {
8754         default: llvm_unreachable("unexpected opcode");
8755         case ARM::t2LSLrr: NewOpc = ARM::tLSLrr; break;
8756         case ARM::t2LSRrr: NewOpc = ARM::tLSRrr; break;
8757         case ARM::t2ASRrr: NewOpc = ARM::tASRrr; break;
8758         case ARM::t2SBCrr: NewOpc = ARM::tSBC; break;
8759         case ARM::t2RORrr: NewOpc = ARM::tROR; break;
8760         case ARM::t2BICrr: NewOpc = ARM::tBIC; break;
8761       }
8762       MCInst TmpInst;
8763       TmpInst.setOpcode(NewOpc);
8764       TmpInst.addOperand(Inst.getOperand(0));
8765       TmpInst.addOperand(Inst.getOperand(5));
8766       TmpInst.addOperand(Inst.getOperand(1));
8767       TmpInst.addOperand(Inst.getOperand(2));
8768       TmpInst.addOperand(Inst.getOperand(3));
8769       TmpInst.addOperand(Inst.getOperand(4));
8770       Inst = TmpInst;
8771       return true;
8772     }
8773     return false;
8774 
8775   case ARM::t2ANDrr:
8776   case ARM::t2EORrr:
8777   case ARM::t2ADCrr:
8778   case ARM::t2ORRrr:
8779     // Assemblers should use the narrow encodings of these instructions when permissible.
8780     // These instructions are special in that they are commutable, so shorter encodings
8781     // are available more often.
8782     if ((isARMLowRegister(Inst.getOperand(1).getReg()) &&
8783          isARMLowRegister(Inst.getOperand(2).getReg())) &&
8784         (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() ||
8785          Inst.getOperand(0).getReg() == Inst.getOperand(2).getReg()) &&
8786         Inst.getOperand(5).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
8787         !HasWideQualifier) {
8788       unsigned NewOpc;
8789       switch (Inst.getOpcode()) {
8790         default: llvm_unreachable("unexpected opcode");
8791         case ARM::t2ADCrr: NewOpc = ARM::tADC; break;
8792         case ARM::t2ANDrr: NewOpc = ARM::tAND; break;
8793         case ARM::t2EORrr: NewOpc = ARM::tEOR; break;
8794         case ARM::t2ORRrr: NewOpc = ARM::tORR; break;
8795       }
8796       MCInst TmpInst;
8797       TmpInst.setOpcode(NewOpc);
8798       TmpInst.addOperand(Inst.getOperand(0));
8799       TmpInst.addOperand(Inst.getOperand(5));
8800       if (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg()) {
8801         TmpInst.addOperand(Inst.getOperand(1));
8802         TmpInst.addOperand(Inst.getOperand(2));
8803       } else {
8804         TmpInst.addOperand(Inst.getOperand(2));
8805         TmpInst.addOperand(Inst.getOperand(1));
8806       }
8807       TmpInst.addOperand(Inst.getOperand(3));
8808       TmpInst.addOperand(Inst.getOperand(4));
8809       Inst = TmpInst;
8810       return true;
8811     }
8812     return false;
8813   }
8814   return false;
8815 }
8816 
8817 unsigned ARMAsmParser::checkTargetMatchPredicate(MCInst &Inst) {
8818   // 16-bit thumb arithmetic instructions either require or preclude the 'S'
8819   // suffix depending on whether they're in an IT block or not.
8820   unsigned Opc = Inst.getOpcode();
8821   const MCInstrDesc &MCID = MII.get(Opc);
8822   if (MCID.TSFlags & ARMII::ThumbArithFlagSetting) {
8823     assert(MCID.hasOptionalDef() &&
8824            "optionally flag setting instruction missing optional def operand");
8825     assert(MCID.NumOperands == Inst.getNumOperands() &&
8826            "operand count mismatch!");
8827     // Find the optional-def operand (cc_out).
8828     unsigned OpNo;
8829     for (OpNo = 0;
8830          !MCID.OpInfo[OpNo].isOptionalDef() && OpNo < MCID.NumOperands;
8831          ++OpNo)
8832       ;
8833     // If we're parsing Thumb1, reject it completely.
8834     if (isThumbOne() && Inst.getOperand(OpNo).getReg() != ARM::CPSR)
8835       return Match_RequiresFlagSetting;
8836     // If we're parsing Thumb2, which form is legal depends on whether we're
8837     // in an IT block.
8838     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() != ARM::CPSR &&
8839         !inITBlock())
8840       return Match_RequiresITBlock;
8841     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() == ARM::CPSR &&
8842         inITBlock())
8843       return Match_RequiresNotITBlock;
8844     // LSL with zero immediate is not allowed in an IT block
8845     if (Opc == ARM::tLSLri && Inst.getOperand(3).getImm() == 0 && inITBlock())
8846       return Match_RequiresNotITBlock;
8847   } else if (isThumbOne()) {
8848     // Some high-register supporting Thumb1 encodings only allow both registers
8849     // to be from r0-r7 when in Thumb2.
8850     if (Opc == ARM::tADDhirr && !hasV6MOps() &&
8851         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8852         isARMLowRegister(Inst.getOperand(2).getReg()))
8853       return Match_RequiresThumb2;
8854     // Others only require ARMv6 or later.
8855     else if (Opc == ARM::tMOVr && !hasV6Ops() &&
8856              isARMLowRegister(Inst.getOperand(0).getReg()) &&
8857              isARMLowRegister(Inst.getOperand(1).getReg()))
8858       return Match_RequiresV6;
8859   }
8860 
8861   // Before ARMv8 the rules for when SP is allowed in t2MOVr are more complex
8862   // than the loop below can handle, so it uses the GPRnopc register class and
8863   // we do SP handling here.
8864   if (Opc == ARM::t2MOVr && !hasV8Ops())
8865   {
8866     // SP as both source and destination is not allowed
8867     if (Inst.getOperand(0).getReg() == ARM::SP &&
8868         Inst.getOperand(1).getReg() == ARM::SP)
8869       return Match_RequiresV8;
8870     // When flags-setting SP as either source or destination is not allowed
8871     if (Inst.getOperand(4).getReg() == ARM::CPSR &&
8872         (Inst.getOperand(0).getReg() == ARM::SP ||
8873          Inst.getOperand(1).getReg() == ARM::SP))
8874       return Match_RequiresV8;
8875   }
8876 
8877   // Use of SP for VMRS/VMSR is only allowed in ARM mode with the exception of
8878   // ARMv8-A.
8879   if ((Inst.getOpcode() == ARM::VMRS || Inst.getOpcode() == ARM::VMSR) &&
8880       Inst.getOperand(0).getReg() == ARM::SP && (isThumb() && !hasV8Ops()))
8881     return Match_InvalidOperand;
8882 
8883   for (unsigned I = 0; I < MCID.NumOperands; ++I)
8884     if (MCID.OpInfo[I].RegClass == ARM::rGPRRegClassID) {
8885       // rGPRRegClass excludes PC, and also excluded SP before ARMv8
8886       if ((Inst.getOperand(I).getReg() == ARM::SP) && !hasV8Ops())
8887         return Match_RequiresV8;
8888       else if (Inst.getOperand(I).getReg() == ARM::PC)
8889         return Match_InvalidOperand;
8890     }
8891 
8892   return Match_Success;
8893 }
8894 
8895 namespace llvm {
8896 
8897 template <> inline bool IsCPSRDead<MCInst>(const MCInst *Instr) {
8898   return true; // In an assembly source, no need to second-guess
8899 }
8900 
8901 } // end namespace llvm
8902 
8903 // Returns true if Inst is unpredictable if it is in and IT block, but is not
8904 // the last instruction in the block.
8905 bool ARMAsmParser::isITBlockTerminator(MCInst &Inst) const {
8906   const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
8907 
8908   // All branch & call instructions terminate IT blocks with the exception of
8909   // SVC.
8910   if (MCID.isTerminator() || (MCID.isCall() && Inst.getOpcode() != ARM::tSVC) ||
8911       MCID.isReturn() || MCID.isBranch() || MCID.isIndirectBranch())
8912     return true;
8913 
8914   // Any arithmetic instruction which writes to the PC also terminates the IT
8915   // block.
8916   for (unsigned OpIdx = 0; OpIdx < MCID.getNumDefs(); ++OpIdx) {
8917     MCOperand &Op = Inst.getOperand(OpIdx);
8918     if (Op.isReg() && Op.getReg() == ARM::PC)
8919       return true;
8920   }
8921 
8922   if (MCID.hasImplicitDefOfPhysReg(ARM::PC, MRI))
8923     return true;
8924 
8925   // Instructions with variable operand lists, which write to the variable
8926   // operands. We only care about Thumb instructions here, as ARM instructions
8927   // obviously can't be in an IT block.
8928   switch (Inst.getOpcode()) {
8929   case ARM::tLDMIA:
8930   case ARM::t2LDMIA:
8931   case ARM::t2LDMIA_UPD:
8932   case ARM::t2LDMDB:
8933   case ARM::t2LDMDB_UPD:
8934     if (listContainsReg(Inst, 3, ARM::PC))
8935       return true;
8936     break;
8937   case ARM::tPOP:
8938     if (listContainsReg(Inst, 2, ARM::PC))
8939       return true;
8940     break;
8941   }
8942 
8943   return false;
8944 }
8945 
8946 unsigned ARMAsmParser::MatchInstruction(OperandVector &Operands, MCInst &Inst,
8947                                           SmallVectorImpl<NearMissInfo> &NearMisses,
8948                                           bool MatchingInlineAsm,
8949                                           bool &EmitInITBlock,
8950                                           MCStreamer &Out) {
8951   // If we can't use an implicit IT block here, just match as normal.
8952   if (inExplicitITBlock() || !isThumbTwo() || !useImplicitITThumb())
8953     return MatchInstructionImpl(Operands, Inst, &NearMisses, MatchingInlineAsm);
8954 
8955   // Try to match the instruction in an extension of the current IT block (if
8956   // there is one).
8957   if (inImplicitITBlock()) {
8958     extendImplicitITBlock(ITState.Cond);
8959     if (MatchInstructionImpl(Operands, Inst, nullptr, MatchingInlineAsm) ==
8960             Match_Success) {
8961       // The match succeded, but we still have to check that the instruction is
8962       // valid in this implicit IT block.
8963       const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
8964       if (MCID.isPredicable()) {
8965         ARMCC::CondCodes InstCond =
8966             (ARMCC::CondCodes)Inst.getOperand(MCID.findFirstPredOperandIdx())
8967                 .getImm();
8968         ARMCC::CondCodes ITCond = currentITCond();
8969         if (InstCond == ITCond) {
8970           EmitInITBlock = true;
8971           return Match_Success;
8972         } else if (InstCond == ARMCC::getOppositeCondition(ITCond)) {
8973           invertCurrentITCondition();
8974           EmitInITBlock = true;
8975           return Match_Success;
8976         }
8977       }
8978     }
8979     rewindImplicitITPosition();
8980   }
8981 
8982   // Finish the current IT block, and try to match outside any IT block.
8983   flushPendingInstructions(Out);
8984   unsigned PlainMatchResult =
8985       MatchInstructionImpl(Operands, Inst, &NearMisses, MatchingInlineAsm);
8986   if (PlainMatchResult == Match_Success) {
8987     const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
8988     if (MCID.isPredicable()) {
8989       ARMCC::CondCodes InstCond =
8990           (ARMCC::CondCodes)Inst.getOperand(MCID.findFirstPredOperandIdx())
8991               .getImm();
8992       // Some forms of the branch instruction have their own condition code
8993       // fields, so can be conditionally executed without an IT block.
8994       if (Inst.getOpcode() == ARM::tBcc || Inst.getOpcode() == ARM::t2Bcc) {
8995         EmitInITBlock = false;
8996         return Match_Success;
8997       }
8998       if (InstCond == ARMCC::AL) {
8999         EmitInITBlock = false;
9000         return Match_Success;
9001       }
9002     } else {
9003       EmitInITBlock = false;
9004       return Match_Success;
9005     }
9006   }
9007 
9008   // Try to match in a new IT block. The matcher doesn't check the actual
9009   // condition, so we create an IT block with a dummy condition, and fix it up
9010   // once we know the actual condition.
9011   startImplicitITBlock();
9012   if (MatchInstructionImpl(Operands, Inst, nullptr, MatchingInlineAsm) ==
9013       Match_Success) {
9014     const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
9015     if (MCID.isPredicable()) {
9016       ITState.Cond =
9017           (ARMCC::CondCodes)Inst.getOperand(MCID.findFirstPredOperandIdx())
9018               .getImm();
9019       EmitInITBlock = true;
9020       return Match_Success;
9021     }
9022   }
9023   discardImplicitITBlock();
9024 
9025   // If none of these succeed, return the error we got when trying to match
9026   // outside any IT blocks.
9027   EmitInITBlock = false;
9028   return PlainMatchResult;
9029 }
9030 
9031 static std::string ARMMnemonicSpellCheck(StringRef S, uint64_t FBS,
9032                                          unsigned VariantID = 0);
9033 
9034 static const char *getSubtargetFeatureName(uint64_t Val);
9035 bool ARMAsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
9036                                            OperandVector &Operands,
9037                                            MCStreamer &Out, uint64_t &ErrorInfo,
9038                                            bool MatchingInlineAsm) {
9039   MCInst Inst;
9040   unsigned MatchResult;
9041   bool PendConditionalInstruction = false;
9042 
9043   SmallVector<NearMissInfo, 4> NearMisses;
9044   MatchResult = MatchInstruction(Operands, Inst, NearMisses, MatchingInlineAsm,
9045                                  PendConditionalInstruction, Out);
9046 
9047   switch (MatchResult) {
9048   case Match_Success:
9049     // Context sensitive operand constraints aren't handled by the matcher,
9050     // so check them here.
9051     if (validateInstruction(Inst, Operands)) {
9052       // Still progress the IT block, otherwise one wrong condition causes
9053       // nasty cascading errors.
9054       forwardITPosition();
9055       return true;
9056     }
9057 
9058     { // processInstruction() updates inITBlock state, we need to save it away
9059       bool wasInITBlock = inITBlock();
9060 
9061       // Some instructions need post-processing to, for example, tweak which
9062       // encoding is selected. Loop on it while changes happen so the
9063       // individual transformations can chain off each other. E.g.,
9064       // tPOP(r8)->t2LDMIA_UPD(sp,r8)->t2STR_POST(sp,r8)
9065       while (processInstruction(Inst, Operands, Out))
9066         ;
9067 
9068       // Only after the instruction is fully processed, we can validate it
9069       if (wasInITBlock && hasV8Ops() && isThumb() &&
9070           !isV8EligibleForIT(&Inst)) {
9071         Warning(IDLoc, "deprecated instruction in IT block");
9072       }
9073     }
9074 
9075     // Only move forward at the very end so that everything in validate
9076     // and process gets a consistent answer about whether we're in an IT
9077     // block.
9078     forwardITPosition();
9079 
9080     // ITasm is an ARM mode pseudo-instruction that just sets the ITblock and
9081     // doesn't actually encode.
9082     if (Inst.getOpcode() == ARM::ITasm)
9083       return false;
9084 
9085     Inst.setLoc(IDLoc);
9086     if (PendConditionalInstruction) {
9087       PendingConditionalInsts.push_back(Inst);
9088       if (isITBlockFull() || isITBlockTerminator(Inst))
9089         flushPendingInstructions(Out);
9090     } else {
9091       Out.EmitInstruction(Inst, getSTI());
9092     }
9093     return false;
9094   case Match_NearMisses:
9095     ReportNearMisses(NearMisses, IDLoc, Operands);
9096     return true;
9097   case Match_MnemonicFail: {
9098     uint64_t FBS = ComputeAvailableFeatures(getSTI().getFeatureBits());
9099     std::string Suggestion = ARMMnemonicSpellCheck(
9100       ((ARMOperand &)*Operands[0]).getToken(), FBS);
9101     return Error(IDLoc, "invalid instruction" + Suggestion,
9102                  ((ARMOperand &)*Operands[0]).getLocRange());
9103   }
9104   }
9105 
9106   llvm_unreachable("Implement any new match types added!");
9107 }
9108 
9109 /// parseDirective parses the arm specific directives
9110 bool ARMAsmParser::ParseDirective(AsmToken DirectiveID) {
9111   const MCObjectFileInfo::Environment Format =
9112     getContext().getObjectFileInfo()->getObjectFileType();
9113   bool IsMachO = Format == MCObjectFileInfo::IsMachO;
9114   bool IsCOFF = Format == MCObjectFileInfo::IsCOFF;
9115 
9116   StringRef IDVal = DirectiveID.getIdentifier();
9117   if (IDVal == ".word")
9118     parseLiteralValues(4, DirectiveID.getLoc());
9119   else if (IDVal == ".short" || IDVal == ".hword")
9120     parseLiteralValues(2, DirectiveID.getLoc());
9121   else if (IDVal == ".thumb")
9122     parseDirectiveThumb(DirectiveID.getLoc());
9123   else if (IDVal == ".arm")
9124     parseDirectiveARM(DirectiveID.getLoc());
9125   else if (IDVal == ".thumb_func")
9126     parseDirectiveThumbFunc(DirectiveID.getLoc());
9127   else if (IDVal == ".code")
9128     parseDirectiveCode(DirectiveID.getLoc());
9129   else if (IDVal == ".syntax")
9130     parseDirectiveSyntax(DirectiveID.getLoc());
9131   else if (IDVal == ".unreq")
9132     parseDirectiveUnreq(DirectiveID.getLoc());
9133   else if (IDVal == ".fnend")
9134     parseDirectiveFnEnd(DirectiveID.getLoc());
9135   else if (IDVal == ".cantunwind")
9136     parseDirectiveCantUnwind(DirectiveID.getLoc());
9137   else if (IDVal == ".personality")
9138     parseDirectivePersonality(DirectiveID.getLoc());
9139   else if (IDVal == ".handlerdata")
9140     parseDirectiveHandlerData(DirectiveID.getLoc());
9141   else if (IDVal == ".setfp")
9142     parseDirectiveSetFP(DirectiveID.getLoc());
9143   else if (IDVal == ".pad")
9144     parseDirectivePad(DirectiveID.getLoc());
9145   else if (IDVal == ".save")
9146     parseDirectiveRegSave(DirectiveID.getLoc(), false);
9147   else if (IDVal == ".vsave")
9148     parseDirectiveRegSave(DirectiveID.getLoc(), true);
9149   else if (IDVal == ".ltorg" || IDVal == ".pool")
9150     parseDirectiveLtorg(DirectiveID.getLoc());
9151   else if (IDVal == ".even")
9152     parseDirectiveEven(DirectiveID.getLoc());
9153   else if (IDVal == ".personalityindex")
9154     parseDirectivePersonalityIndex(DirectiveID.getLoc());
9155   else if (IDVal == ".unwind_raw")
9156     parseDirectiveUnwindRaw(DirectiveID.getLoc());
9157   else if (IDVal == ".movsp")
9158     parseDirectiveMovSP(DirectiveID.getLoc());
9159   else if (IDVal == ".arch_extension")
9160     parseDirectiveArchExtension(DirectiveID.getLoc());
9161   else if (IDVal == ".align")
9162     return parseDirectiveAlign(DirectiveID.getLoc()); // Use Generic on failure.
9163   else if (IDVal == ".thumb_set")
9164     parseDirectiveThumbSet(DirectiveID.getLoc());
9165   else if (!IsMachO && !IsCOFF) {
9166     if (IDVal == ".arch")
9167       parseDirectiveArch(DirectiveID.getLoc());
9168     else if (IDVal == ".cpu")
9169       parseDirectiveCPU(DirectiveID.getLoc());
9170     else if (IDVal == ".eabi_attribute")
9171       parseDirectiveEabiAttr(DirectiveID.getLoc());
9172     else if (IDVal == ".fpu")
9173       parseDirectiveFPU(DirectiveID.getLoc());
9174     else if (IDVal == ".fnstart")
9175       parseDirectiveFnStart(DirectiveID.getLoc());
9176     else if (IDVal == ".inst")
9177       parseDirectiveInst(DirectiveID.getLoc());
9178     else if (IDVal == ".inst.n")
9179       parseDirectiveInst(DirectiveID.getLoc(), 'n');
9180     else if (IDVal == ".inst.w")
9181       parseDirectiveInst(DirectiveID.getLoc(), 'w');
9182     else if (IDVal == ".object_arch")
9183       parseDirectiveObjectArch(DirectiveID.getLoc());
9184     else if (IDVal == ".tlsdescseq")
9185       parseDirectiveTLSDescSeq(DirectiveID.getLoc());
9186     else
9187       return true;
9188   } else
9189     return true;
9190   return false;
9191 }
9192 
9193 /// parseLiteralValues
9194 ///  ::= .hword expression [, expression]*
9195 ///  ::= .short expression [, expression]*
9196 ///  ::= .word expression [, expression]*
9197 bool ARMAsmParser::parseLiteralValues(unsigned Size, SMLoc L) {
9198   auto parseOne = [&]() -> bool {
9199     const MCExpr *Value;
9200     if (getParser().parseExpression(Value))
9201       return true;
9202     getParser().getStreamer().EmitValue(Value, Size, L);
9203     return false;
9204   };
9205   return (parseMany(parseOne));
9206 }
9207 
9208 /// parseDirectiveThumb
9209 ///  ::= .thumb
9210 bool ARMAsmParser::parseDirectiveThumb(SMLoc L) {
9211   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive") ||
9212       check(!hasThumb(), L, "target does not support Thumb mode"))
9213     return true;
9214 
9215   if (!isThumb())
9216     SwitchMode();
9217 
9218   getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
9219   return false;
9220 }
9221 
9222 /// parseDirectiveARM
9223 ///  ::= .arm
9224 bool ARMAsmParser::parseDirectiveARM(SMLoc L) {
9225   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive") ||
9226       check(!hasARM(), L, "target does not support ARM mode"))
9227     return true;
9228 
9229   if (isThumb())
9230     SwitchMode();
9231   getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
9232   return false;
9233 }
9234 
9235 void ARMAsmParser::onLabelParsed(MCSymbol *Symbol) {
9236   // We need to flush the current implicit IT block on a label, because it is
9237   // not legal to branch into an IT block.
9238   flushPendingInstructions(getStreamer());
9239   if (NextSymbolIsThumb) {
9240     getParser().getStreamer().EmitThumbFunc(Symbol);
9241     NextSymbolIsThumb = false;
9242   }
9243 }
9244 
9245 /// parseDirectiveThumbFunc
9246 ///  ::= .thumbfunc symbol_name
9247 bool ARMAsmParser::parseDirectiveThumbFunc(SMLoc L) {
9248   MCAsmParser &Parser = getParser();
9249   const auto Format = getContext().getObjectFileInfo()->getObjectFileType();
9250   bool IsMachO = Format == MCObjectFileInfo::IsMachO;
9251 
9252   // Darwin asm has (optionally) function name after .thumb_func direction
9253   // ELF doesn't
9254 
9255   if (IsMachO) {
9256     if (Parser.getTok().is(AsmToken::Identifier) ||
9257         Parser.getTok().is(AsmToken::String)) {
9258       MCSymbol *Func = getParser().getContext().getOrCreateSymbol(
9259           Parser.getTok().getIdentifier());
9260       getParser().getStreamer().EmitThumbFunc(Func);
9261       Parser.Lex();
9262       if (parseToken(AsmToken::EndOfStatement,
9263                      "unexpected token in '.thumb_func' directive"))
9264         return true;
9265       return false;
9266     }
9267   }
9268 
9269   if (parseToken(AsmToken::EndOfStatement,
9270                  "unexpected token in '.thumb_func' directive"))
9271     return true;
9272 
9273   NextSymbolIsThumb = true;
9274   return false;
9275 }
9276 
9277 /// parseDirectiveSyntax
9278 ///  ::= .syntax unified | divided
9279 bool ARMAsmParser::parseDirectiveSyntax(SMLoc L) {
9280   MCAsmParser &Parser = getParser();
9281   const AsmToken &Tok = Parser.getTok();
9282   if (Tok.isNot(AsmToken::Identifier)) {
9283     Error(L, "unexpected token in .syntax directive");
9284     return false;
9285   }
9286 
9287   StringRef Mode = Tok.getString();
9288   Parser.Lex();
9289   if (check(Mode == "divided" || Mode == "DIVIDED", L,
9290             "'.syntax divided' arm assembly not supported") ||
9291       check(Mode != "unified" && Mode != "UNIFIED", L,
9292             "unrecognized syntax mode in .syntax directive") ||
9293       parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
9294     return true;
9295 
9296   // TODO tell the MC streamer the mode
9297   // getParser().getStreamer().Emit???();
9298   return false;
9299 }
9300 
9301 /// parseDirectiveCode
9302 ///  ::= .code 16 | 32
9303 bool ARMAsmParser::parseDirectiveCode(SMLoc L) {
9304   MCAsmParser &Parser = getParser();
9305   const AsmToken &Tok = Parser.getTok();
9306   if (Tok.isNot(AsmToken::Integer))
9307     return Error(L, "unexpected token in .code directive");
9308   int64_t Val = Parser.getTok().getIntVal();
9309   if (Val != 16 && Val != 32) {
9310     Error(L, "invalid operand to .code directive");
9311     return false;
9312   }
9313   Parser.Lex();
9314 
9315   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
9316     return true;
9317 
9318   if (Val == 16) {
9319     if (!hasThumb())
9320       return Error(L, "target does not support Thumb mode");
9321 
9322     if (!isThumb())
9323       SwitchMode();
9324     getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
9325   } else {
9326     if (!hasARM())
9327       return Error(L, "target does not support ARM mode");
9328 
9329     if (isThumb())
9330       SwitchMode();
9331     getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
9332   }
9333 
9334   return false;
9335 }
9336 
9337 /// parseDirectiveReq
9338 ///  ::= name .req registername
9339 bool ARMAsmParser::parseDirectiveReq(StringRef Name, SMLoc L) {
9340   MCAsmParser &Parser = getParser();
9341   Parser.Lex(); // Eat the '.req' token.
9342   unsigned Reg;
9343   SMLoc SRegLoc, ERegLoc;
9344   if (check(ParseRegister(Reg, SRegLoc, ERegLoc), SRegLoc,
9345             "register name expected") ||
9346       parseToken(AsmToken::EndOfStatement,
9347                  "unexpected input in .req directive."))
9348     return true;
9349 
9350   if (RegisterReqs.insert(std::make_pair(Name, Reg)).first->second != Reg)
9351     return Error(SRegLoc,
9352                  "redefinition of '" + Name + "' does not match original.");
9353 
9354   return false;
9355 }
9356 
9357 /// parseDirectiveUneq
9358 ///  ::= .unreq registername
9359 bool ARMAsmParser::parseDirectiveUnreq(SMLoc L) {
9360   MCAsmParser &Parser = getParser();
9361   if (Parser.getTok().isNot(AsmToken::Identifier))
9362     return Error(L, "unexpected input in .unreq directive.");
9363   RegisterReqs.erase(Parser.getTok().getIdentifier().lower());
9364   Parser.Lex(); // Eat the identifier.
9365   if (parseToken(AsmToken::EndOfStatement,
9366                  "unexpected input in '.unreq' directive"))
9367     return true;
9368   return false;
9369 }
9370 
9371 // After changing arch/CPU, try to put the ARM/Thumb mode back to what it was
9372 // before, if supported by the new target, or emit mapping symbols for the mode
9373 // switch.
9374 void ARMAsmParser::FixModeAfterArchChange(bool WasThumb, SMLoc Loc) {
9375   if (WasThumb != isThumb()) {
9376     if (WasThumb && hasThumb()) {
9377       // Stay in Thumb mode
9378       SwitchMode();
9379     } else if (!WasThumb && hasARM()) {
9380       // Stay in ARM mode
9381       SwitchMode();
9382     } else {
9383       // Mode switch forced, because the new arch doesn't support the old mode.
9384       getParser().getStreamer().EmitAssemblerFlag(isThumb() ? MCAF_Code16
9385                                                             : MCAF_Code32);
9386       // Warn about the implcit mode switch. GAS does not switch modes here,
9387       // but instead stays in the old mode, reporting an error on any following
9388       // instructions as the mode does not exist on the target.
9389       Warning(Loc, Twine("new target does not support ") +
9390                        (WasThumb ? "thumb" : "arm") + " mode, switching to " +
9391                        (!WasThumb ? "thumb" : "arm") + " mode");
9392     }
9393   }
9394 }
9395 
9396 /// parseDirectiveArch
9397 ///  ::= .arch token
9398 bool ARMAsmParser::parseDirectiveArch(SMLoc L) {
9399   StringRef Arch = getParser().parseStringToEndOfStatement().trim();
9400   ARM::ArchKind ID = ARM::parseArch(Arch);
9401 
9402   if (ID == ARM::ArchKind::INVALID)
9403     return Error(L, "Unknown arch name");
9404 
9405   bool WasThumb = isThumb();
9406   Triple T;
9407   MCSubtargetInfo &STI = copySTI();
9408   STI.setDefaultFeatures("", ("+" + ARM::getArchName(ID)).str());
9409   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
9410   FixModeAfterArchChange(WasThumb, L);
9411 
9412   getTargetStreamer().emitArch(ID);
9413   return false;
9414 }
9415 
9416 /// parseDirectiveEabiAttr
9417 ///  ::= .eabi_attribute int, int [, "str"]
9418 ///  ::= .eabi_attribute Tag_name, int [, "str"]
9419 bool ARMAsmParser::parseDirectiveEabiAttr(SMLoc L) {
9420   MCAsmParser &Parser = getParser();
9421   int64_t Tag;
9422   SMLoc TagLoc;
9423   TagLoc = Parser.getTok().getLoc();
9424   if (Parser.getTok().is(AsmToken::Identifier)) {
9425     StringRef Name = Parser.getTok().getIdentifier();
9426     Tag = ARMBuildAttrs::AttrTypeFromString(Name);
9427     if (Tag == -1) {
9428       Error(TagLoc, "attribute name not recognised: " + Name);
9429       return false;
9430     }
9431     Parser.Lex();
9432   } else {
9433     const MCExpr *AttrExpr;
9434 
9435     TagLoc = Parser.getTok().getLoc();
9436     if (Parser.parseExpression(AttrExpr))
9437       return true;
9438 
9439     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(AttrExpr);
9440     if (check(!CE, TagLoc, "expected numeric constant"))
9441       return true;
9442 
9443     Tag = CE->getValue();
9444   }
9445 
9446   if (Parser.parseToken(AsmToken::Comma, "comma expected"))
9447     return true;
9448 
9449   StringRef StringValue = "";
9450   bool IsStringValue = false;
9451 
9452   int64_t IntegerValue = 0;
9453   bool IsIntegerValue = false;
9454 
9455   if (Tag == ARMBuildAttrs::CPU_raw_name || Tag == ARMBuildAttrs::CPU_name)
9456     IsStringValue = true;
9457   else if (Tag == ARMBuildAttrs::compatibility) {
9458     IsStringValue = true;
9459     IsIntegerValue = true;
9460   } else if (Tag < 32 || Tag % 2 == 0)
9461     IsIntegerValue = true;
9462   else if (Tag % 2 == 1)
9463     IsStringValue = true;
9464   else
9465     llvm_unreachable("invalid tag type");
9466 
9467   if (IsIntegerValue) {
9468     const MCExpr *ValueExpr;
9469     SMLoc ValueExprLoc = Parser.getTok().getLoc();
9470     if (Parser.parseExpression(ValueExpr))
9471       return true;
9472 
9473     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ValueExpr);
9474     if (!CE)
9475       return Error(ValueExprLoc, "expected numeric constant");
9476     IntegerValue = CE->getValue();
9477   }
9478 
9479   if (Tag == ARMBuildAttrs::compatibility) {
9480     if (Parser.parseToken(AsmToken::Comma, "comma expected"))
9481       return true;
9482   }
9483 
9484   if (IsStringValue) {
9485     if (Parser.getTok().isNot(AsmToken::String))
9486       return Error(Parser.getTok().getLoc(), "bad string constant");
9487 
9488     StringValue = Parser.getTok().getStringContents();
9489     Parser.Lex();
9490   }
9491 
9492   if (Parser.parseToken(AsmToken::EndOfStatement,
9493                         "unexpected token in '.eabi_attribute' directive"))
9494     return true;
9495 
9496   if (IsIntegerValue && IsStringValue) {
9497     assert(Tag == ARMBuildAttrs::compatibility);
9498     getTargetStreamer().emitIntTextAttribute(Tag, IntegerValue, StringValue);
9499   } else if (IsIntegerValue)
9500     getTargetStreamer().emitAttribute(Tag, IntegerValue);
9501   else if (IsStringValue)
9502     getTargetStreamer().emitTextAttribute(Tag, StringValue);
9503   return false;
9504 }
9505 
9506 /// parseDirectiveCPU
9507 ///  ::= .cpu str
9508 bool ARMAsmParser::parseDirectiveCPU(SMLoc L) {
9509   StringRef CPU = getParser().parseStringToEndOfStatement().trim();
9510   getTargetStreamer().emitTextAttribute(ARMBuildAttrs::CPU_name, CPU);
9511 
9512   // FIXME: This is using table-gen data, but should be moved to
9513   // ARMTargetParser once that is table-gen'd.
9514   if (!getSTI().isCPUStringValid(CPU))
9515     return Error(L, "Unknown CPU name");
9516 
9517   bool WasThumb = isThumb();
9518   MCSubtargetInfo &STI = copySTI();
9519   STI.setDefaultFeatures(CPU, "");
9520   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
9521   FixModeAfterArchChange(WasThumb, L);
9522 
9523   return false;
9524 }
9525 
9526 /// parseDirectiveFPU
9527 ///  ::= .fpu str
9528 bool ARMAsmParser::parseDirectiveFPU(SMLoc L) {
9529   SMLoc FPUNameLoc = getTok().getLoc();
9530   StringRef FPU = getParser().parseStringToEndOfStatement().trim();
9531 
9532   unsigned ID = ARM::parseFPU(FPU);
9533   std::vector<StringRef> Features;
9534   if (!ARM::getFPUFeatures(ID, Features))
9535     return Error(FPUNameLoc, "Unknown FPU name");
9536 
9537   MCSubtargetInfo &STI = copySTI();
9538   for (auto Feature : Features)
9539     STI.ApplyFeatureFlag(Feature);
9540   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
9541 
9542   getTargetStreamer().emitFPU(ID);
9543   return false;
9544 }
9545 
9546 /// parseDirectiveFnStart
9547 ///  ::= .fnstart
9548 bool ARMAsmParser::parseDirectiveFnStart(SMLoc L) {
9549   if (parseToken(AsmToken::EndOfStatement,
9550                  "unexpected token in '.fnstart' directive"))
9551     return true;
9552 
9553   if (UC.hasFnStart()) {
9554     Error(L, ".fnstart starts before the end of previous one");
9555     UC.emitFnStartLocNotes();
9556     return true;
9557   }
9558 
9559   // Reset the unwind directives parser state
9560   UC.reset();
9561 
9562   getTargetStreamer().emitFnStart();
9563 
9564   UC.recordFnStart(L);
9565   return false;
9566 }
9567 
9568 /// parseDirectiveFnEnd
9569 ///  ::= .fnend
9570 bool ARMAsmParser::parseDirectiveFnEnd(SMLoc L) {
9571   if (parseToken(AsmToken::EndOfStatement,
9572                  "unexpected token in '.fnend' directive"))
9573     return true;
9574   // Check the ordering of unwind directives
9575   if (!UC.hasFnStart())
9576     return Error(L, ".fnstart must precede .fnend directive");
9577 
9578   // Reset the unwind directives parser state
9579   getTargetStreamer().emitFnEnd();
9580 
9581   UC.reset();
9582   return false;
9583 }
9584 
9585 /// parseDirectiveCantUnwind
9586 ///  ::= .cantunwind
9587 bool ARMAsmParser::parseDirectiveCantUnwind(SMLoc L) {
9588   if (parseToken(AsmToken::EndOfStatement,
9589                  "unexpected token in '.cantunwind' directive"))
9590     return true;
9591 
9592   UC.recordCantUnwind(L);
9593   // Check the ordering of unwind directives
9594   if (check(!UC.hasFnStart(), L, ".fnstart must precede .cantunwind directive"))
9595     return true;
9596 
9597   if (UC.hasHandlerData()) {
9598     Error(L, ".cantunwind can't be used with .handlerdata directive");
9599     UC.emitHandlerDataLocNotes();
9600     return true;
9601   }
9602   if (UC.hasPersonality()) {
9603     Error(L, ".cantunwind can't be used with .personality directive");
9604     UC.emitPersonalityLocNotes();
9605     return true;
9606   }
9607 
9608   getTargetStreamer().emitCantUnwind();
9609   return false;
9610 }
9611 
9612 /// parseDirectivePersonality
9613 ///  ::= .personality name
9614 bool ARMAsmParser::parseDirectivePersonality(SMLoc L) {
9615   MCAsmParser &Parser = getParser();
9616   bool HasExistingPersonality = UC.hasPersonality();
9617 
9618   // Parse the name of the personality routine
9619   if (Parser.getTok().isNot(AsmToken::Identifier))
9620     return Error(L, "unexpected input in .personality directive.");
9621   StringRef Name(Parser.getTok().getIdentifier());
9622   Parser.Lex();
9623 
9624   if (parseToken(AsmToken::EndOfStatement,
9625                  "unexpected token in '.personality' directive"))
9626     return true;
9627 
9628   UC.recordPersonality(L);
9629 
9630   // Check the ordering of unwind directives
9631   if (!UC.hasFnStart())
9632     return Error(L, ".fnstart must precede .personality directive");
9633   if (UC.cantUnwind()) {
9634     Error(L, ".personality can't be used with .cantunwind directive");
9635     UC.emitCantUnwindLocNotes();
9636     return true;
9637   }
9638   if (UC.hasHandlerData()) {
9639     Error(L, ".personality must precede .handlerdata directive");
9640     UC.emitHandlerDataLocNotes();
9641     return true;
9642   }
9643   if (HasExistingPersonality) {
9644     Error(L, "multiple personality directives");
9645     UC.emitPersonalityLocNotes();
9646     return true;
9647   }
9648 
9649   MCSymbol *PR = getParser().getContext().getOrCreateSymbol(Name);
9650   getTargetStreamer().emitPersonality(PR);
9651   return false;
9652 }
9653 
9654 /// parseDirectiveHandlerData
9655 ///  ::= .handlerdata
9656 bool ARMAsmParser::parseDirectiveHandlerData(SMLoc L) {
9657   if (parseToken(AsmToken::EndOfStatement,
9658                  "unexpected token in '.handlerdata' directive"))
9659     return true;
9660 
9661   UC.recordHandlerData(L);
9662   // Check the ordering of unwind directives
9663   if (!UC.hasFnStart())
9664     return Error(L, ".fnstart must precede .personality directive");
9665   if (UC.cantUnwind()) {
9666     Error(L, ".handlerdata can't be used with .cantunwind directive");
9667     UC.emitCantUnwindLocNotes();
9668     return true;
9669   }
9670 
9671   getTargetStreamer().emitHandlerData();
9672   return false;
9673 }
9674 
9675 /// parseDirectiveSetFP
9676 ///  ::= .setfp fpreg, spreg [, offset]
9677 bool ARMAsmParser::parseDirectiveSetFP(SMLoc L) {
9678   MCAsmParser &Parser = getParser();
9679   // Check the ordering of unwind directives
9680   if (check(!UC.hasFnStart(), L, ".fnstart must precede .setfp directive") ||
9681       check(UC.hasHandlerData(), L,
9682             ".setfp must precede .handlerdata directive"))
9683     return true;
9684 
9685   // Parse fpreg
9686   SMLoc FPRegLoc = Parser.getTok().getLoc();
9687   int FPReg = tryParseRegister();
9688 
9689   if (check(FPReg == -1, FPRegLoc, "frame pointer register expected") ||
9690       Parser.parseToken(AsmToken::Comma, "comma expected"))
9691     return true;
9692 
9693   // Parse spreg
9694   SMLoc SPRegLoc = Parser.getTok().getLoc();
9695   int SPReg = tryParseRegister();
9696   if (check(SPReg == -1, SPRegLoc, "stack pointer register expected") ||
9697       check(SPReg != ARM::SP && SPReg != UC.getFPReg(), SPRegLoc,
9698             "register should be either $sp or the latest fp register"))
9699     return true;
9700 
9701   // Update the frame pointer register
9702   UC.saveFPReg(FPReg);
9703 
9704   // Parse offset
9705   int64_t Offset = 0;
9706   if (Parser.parseOptionalToken(AsmToken::Comma)) {
9707     if (Parser.getTok().isNot(AsmToken::Hash) &&
9708         Parser.getTok().isNot(AsmToken::Dollar))
9709       return Error(Parser.getTok().getLoc(), "'#' expected");
9710     Parser.Lex(); // skip hash token.
9711 
9712     const MCExpr *OffsetExpr;
9713     SMLoc ExLoc = Parser.getTok().getLoc();
9714     SMLoc EndLoc;
9715     if (getParser().parseExpression(OffsetExpr, EndLoc))
9716       return Error(ExLoc, "malformed setfp offset");
9717     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
9718     if (check(!CE, ExLoc, "setfp offset must be an immediate"))
9719       return true;
9720     Offset = CE->getValue();
9721   }
9722 
9723   if (Parser.parseToken(AsmToken::EndOfStatement))
9724     return true;
9725 
9726   getTargetStreamer().emitSetFP(static_cast<unsigned>(FPReg),
9727                                 static_cast<unsigned>(SPReg), Offset);
9728   return false;
9729 }
9730 
9731 /// parseDirective
9732 ///  ::= .pad offset
9733 bool ARMAsmParser::parseDirectivePad(SMLoc L) {
9734   MCAsmParser &Parser = getParser();
9735   // Check the ordering of unwind directives
9736   if (!UC.hasFnStart())
9737     return Error(L, ".fnstart must precede .pad directive");
9738   if (UC.hasHandlerData())
9739     return Error(L, ".pad must precede .handlerdata directive");
9740 
9741   // Parse the offset
9742   if (Parser.getTok().isNot(AsmToken::Hash) &&
9743       Parser.getTok().isNot(AsmToken::Dollar))
9744     return Error(Parser.getTok().getLoc(), "'#' expected");
9745   Parser.Lex(); // skip hash token.
9746 
9747   const MCExpr *OffsetExpr;
9748   SMLoc ExLoc = Parser.getTok().getLoc();
9749   SMLoc EndLoc;
9750   if (getParser().parseExpression(OffsetExpr, EndLoc))
9751     return Error(ExLoc, "malformed pad offset");
9752   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
9753   if (!CE)
9754     return Error(ExLoc, "pad offset must be an immediate");
9755 
9756   if (parseToken(AsmToken::EndOfStatement,
9757                  "unexpected token in '.pad' directive"))
9758     return true;
9759 
9760   getTargetStreamer().emitPad(CE->getValue());
9761   return false;
9762 }
9763 
9764 /// parseDirectiveRegSave
9765 ///  ::= .save  { registers }
9766 ///  ::= .vsave { registers }
9767 bool ARMAsmParser::parseDirectiveRegSave(SMLoc L, bool IsVector) {
9768   // Check the ordering of unwind directives
9769   if (!UC.hasFnStart())
9770     return Error(L, ".fnstart must precede .save or .vsave directives");
9771   if (UC.hasHandlerData())
9772     return Error(L, ".save or .vsave must precede .handlerdata directive");
9773 
9774   // RAII object to make sure parsed operands are deleted.
9775   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> Operands;
9776 
9777   // Parse the register list
9778   if (parseRegisterList(Operands) ||
9779       parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
9780     return true;
9781   ARMOperand &Op = (ARMOperand &)*Operands[0];
9782   if (!IsVector && !Op.isRegList())
9783     return Error(L, ".save expects GPR registers");
9784   if (IsVector && !Op.isDPRRegList())
9785     return Error(L, ".vsave expects DPR registers");
9786 
9787   getTargetStreamer().emitRegSave(Op.getRegList(), IsVector);
9788   return false;
9789 }
9790 
9791 /// parseDirectiveInst
9792 ///  ::= .inst opcode [, ...]
9793 ///  ::= .inst.n opcode [, ...]
9794 ///  ::= .inst.w opcode [, ...]
9795 bool ARMAsmParser::parseDirectiveInst(SMLoc Loc, char Suffix) {
9796   int Width = 4;
9797 
9798   if (isThumb()) {
9799     switch (Suffix) {
9800     case 'n':
9801       Width = 2;
9802       break;
9803     case 'w':
9804       break;
9805     default:
9806       return Error(Loc, "cannot determine Thumb instruction size, "
9807                         "use inst.n/inst.w instead");
9808     }
9809   } else {
9810     if (Suffix)
9811       return Error(Loc, "width suffixes are invalid in ARM mode");
9812   }
9813 
9814   auto parseOne = [&]() -> bool {
9815     const MCExpr *Expr;
9816     if (getParser().parseExpression(Expr))
9817       return true;
9818     const MCConstantExpr *Value = dyn_cast_or_null<MCConstantExpr>(Expr);
9819     if (!Value) {
9820       return Error(Loc, "expected constant expression");
9821     }
9822 
9823     switch (Width) {
9824     case 2:
9825       if (Value->getValue() > 0xffff)
9826         return Error(Loc, "inst.n operand is too big, use inst.w instead");
9827       break;
9828     case 4:
9829       if (Value->getValue() > 0xffffffff)
9830         return Error(Loc, StringRef(Suffix ? "inst.w" : "inst") +
9831                               " operand is too big");
9832       break;
9833     default:
9834       llvm_unreachable("only supported widths are 2 and 4");
9835     }
9836 
9837     getTargetStreamer().emitInst(Value->getValue(), Suffix);
9838     return false;
9839   };
9840 
9841   if (parseOptionalToken(AsmToken::EndOfStatement))
9842     return Error(Loc, "expected expression following directive");
9843   if (parseMany(parseOne))
9844     return true;
9845   return false;
9846 }
9847 
9848 /// parseDirectiveLtorg
9849 ///  ::= .ltorg | .pool
9850 bool ARMAsmParser::parseDirectiveLtorg(SMLoc L) {
9851   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
9852     return true;
9853   getTargetStreamer().emitCurrentConstantPool();
9854   return false;
9855 }
9856 
9857 bool ARMAsmParser::parseDirectiveEven(SMLoc L) {
9858   const MCSection *Section = getStreamer().getCurrentSectionOnly();
9859 
9860   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
9861     return true;
9862 
9863   if (!Section) {
9864     getStreamer().InitSections(false);
9865     Section = getStreamer().getCurrentSectionOnly();
9866   }
9867 
9868   assert(Section && "must have section to emit alignment");
9869   if (Section->UseCodeAlign())
9870     getStreamer().EmitCodeAlignment(2);
9871   else
9872     getStreamer().EmitValueToAlignment(2);
9873 
9874   return false;
9875 }
9876 
9877 /// parseDirectivePersonalityIndex
9878 ///   ::= .personalityindex index
9879 bool ARMAsmParser::parseDirectivePersonalityIndex(SMLoc L) {
9880   MCAsmParser &Parser = getParser();
9881   bool HasExistingPersonality = UC.hasPersonality();
9882 
9883   const MCExpr *IndexExpression;
9884   SMLoc IndexLoc = Parser.getTok().getLoc();
9885   if (Parser.parseExpression(IndexExpression) ||
9886       parseToken(AsmToken::EndOfStatement,
9887                  "unexpected token in '.personalityindex' directive")) {
9888     return true;
9889   }
9890 
9891   UC.recordPersonalityIndex(L);
9892 
9893   if (!UC.hasFnStart()) {
9894     return Error(L, ".fnstart must precede .personalityindex directive");
9895   }
9896   if (UC.cantUnwind()) {
9897     Error(L, ".personalityindex cannot be used with .cantunwind");
9898     UC.emitCantUnwindLocNotes();
9899     return true;
9900   }
9901   if (UC.hasHandlerData()) {
9902     Error(L, ".personalityindex must precede .handlerdata directive");
9903     UC.emitHandlerDataLocNotes();
9904     return true;
9905   }
9906   if (HasExistingPersonality) {
9907     Error(L, "multiple personality directives");
9908     UC.emitPersonalityLocNotes();
9909     return true;
9910   }
9911 
9912   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(IndexExpression);
9913   if (!CE)
9914     return Error(IndexLoc, "index must be a constant number");
9915   if (CE->getValue() < 0 || CE->getValue() >= ARM::EHABI::NUM_PERSONALITY_INDEX)
9916     return Error(IndexLoc,
9917                  "personality routine index should be in range [0-3]");
9918 
9919   getTargetStreamer().emitPersonalityIndex(CE->getValue());
9920   return false;
9921 }
9922 
9923 /// parseDirectiveUnwindRaw
9924 ///   ::= .unwind_raw offset, opcode [, opcode...]
9925 bool ARMAsmParser::parseDirectiveUnwindRaw(SMLoc L) {
9926   MCAsmParser &Parser = getParser();
9927   int64_t StackOffset;
9928   const MCExpr *OffsetExpr;
9929   SMLoc OffsetLoc = getLexer().getLoc();
9930 
9931   if (!UC.hasFnStart())
9932     return Error(L, ".fnstart must precede .unwind_raw directives");
9933   if (getParser().parseExpression(OffsetExpr))
9934     return Error(OffsetLoc, "expected expression");
9935 
9936   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
9937   if (!CE)
9938     return Error(OffsetLoc, "offset must be a constant");
9939 
9940   StackOffset = CE->getValue();
9941 
9942   if (Parser.parseToken(AsmToken::Comma, "expected comma"))
9943     return true;
9944 
9945   SmallVector<uint8_t, 16> Opcodes;
9946 
9947   auto parseOne = [&]() -> bool {
9948     const MCExpr *OE;
9949     SMLoc OpcodeLoc = getLexer().getLoc();
9950     if (check(getLexer().is(AsmToken::EndOfStatement) ||
9951                   Parser.parseExpression(OE),
9952               OpcodeLoc, "expected opcode expression"))
9953       return true;
9954     const MCConstantExpr *OC = dyn_cast<MCConstantExpr>(OE);
9955     if (!OC)
9956       return Error(OpcodeLoc, "opcode value must be a constant");
9957     const int64_t Opcode = OC->getValue();
9958     if (Opcode & ~0xff)
9959       return Error(OpcodeLoc, "invalid opcode");
9960     Opcodes.push_back(uint8_t(Opcode));
9961     return false;
9962   };
9963 
9964   // Must have at least 1 element
9965   SMLoc OpcodeLoc = getLexer().getLoc();
9966   if (parseOptionalToken(AsmToken::EndOfStatement))
9967     return Error(OpcodeLoc, "expected opcode expression");
9968   if (parseMany(parseOne))
9969     return true;
9970 
9971   getTargetStreamer().emitUnwindRaw(StackOffset, Opcodes);
9972   return false;
9973 }
9974 
9975 /// parseDirectiveTLSDescSeq
9976 ///   ::= .tlsdescseq tls-variable
9977 bool ARMAsmParser::parseDirectiveTLSDescSeq(SMLoc L) {
9978   MCAsmParser &Parser = getParser();
9979 
9980   if (getLexer().isNot(AsmToken::Identifier))
9981     return TokError("expected variable after '.tlsdescseq' directive");
9982 
9983   const MCSymbolRefExpr *SRE =
9984     MCSymbolRefExpr::create(Parser.getTok().getIdentifier(),
9985                             MCSymbolRefExpr::VK_ARM_TLSDESCSEQ, getContext());
9986   Lex();
9987 
9988   if (parseToken(AsmToken::EndOfStatement,
9989                  "unexpected token in '.tlsdescseq' directive"))
9990     return true;
9991 
9992   getTargetStreamer().AnnotateTLSDescriptorSequence(SRE);
9993   return false;
9994 }
9995 
9996 /// parseDirectiveMovSP
9997 ///  ::= .movsp reg [, #offset]
9998 bool ARMAsmParser::parseDirectiveMovSP(SMLoc L) {
9999   MCAsmParser &Parser = getParser();
10000   if (!UC.hasFnStart())
10001     return Error(L, ".fnstart must precede .movsp directives");
10002   if (UC.getFPReg() != ARM::SP)
10003     return Error(L, "unexpected .movsp directive");
10004 
10005   SMLoc SPRegLoc = Parser.getTok().getLoc();
10006   int SPReg = tryParseRegister();
10007   if (SPReg == -1)
10008     return Error(SPRegLoc, "register expected");
10009   if (SPReg == ARM::SP || SPReg == ARM::PC)
10010     return Error(SPRegLoc, "sp and pc are not permitted in .movsp directive");
10011 
10012   int64_t Offset = 0;
10013   if (Parser.parseOptionalToken(AsmToken::Comma)) {
10014     if (Parser.parseToken(AsmToken::Hash, "expected #constant"))
10015       return true;
10016 
10017     const MCExpr *OffsetExpr;
10018     SMLoc OffsetLoc = Parser.getTok().getLoc();
10019 
10020     if (Parser.parseExpression(OffsetExpr))
10021       return Error(OffsetLoc, "malformed offset expression");
10022 
10023     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
10024     if (!CE)
10025       return Error(OffsetLoc, "offset must be an immediate constant");
10026 
10027     Offset = CE->getValue();
10028   }
10029 
10030   if (parseToken(AsmToken::EndOfStatement,
10031                  "unexpected token in '.movsp' directive"))
10032     return true;
10033 
10034   getTargetStreamer().emitMovSP(SPReg, Offset);
10035   UC.saveFPReg(SPReg);
10036 
10037   return false;
10038 }
10039 
10040 /// parseDirectiveObjectArch
10041 ///   ::= .object_arch name
10042 bool ARMAsmParser::parseDirectiveObjectArch(SMLoc L) {
10043   MCAsmParser &Parser = getParser();
10044   if (getLexer().isNot(AsmToken::Identifier))
10045     return Error(getLexer().getLoc(), "unexpected token");
10046 
10047   StringRef Arch = Parser.getTok().getString();
10048   SMLoc ArchLoc = Parser.getTok().getLoc();
10049   Lex();
10050 
10051   ARM::ArchKind ID = ARM::parseArch(Arch);
10052 
10053   if (ID == ARM::ArchKind::INVALID)
10054     return Error(ArchLoc, "unknown architecture '" + Arch + "'");
10055   if (parseToken(AsmToken::EndOfStatement))
10056     return true;
10057 
10058   getTargetStreamer().emitObjectArch(ID);
10059   return false;
10060 }
10061 
10062 /// parseDirectiveAlign
10063 ///   ::= .align
10064 bool ARMAsmParser::parseDirectiveAlign(SMLoc L) {
10065   // NOTE: if this is not the end of the statement, fall back to the target
10066   // agnostic handling for this directive which will correctly handle this.
10067   if (parseOptionalToken(AsmToken::EndOfStatement)) {
10068     // '.align' is target specifically handled to mean 2**2 byte alignment.
10069     const MCSection *Section = getStreamer().getCurrentSectionOnly();
10070     assert(Section && "must have section to emit alignment");
10071     if (Section->UseCodeAlign())
10072       getStreamer().EmitCodeAlignment(4, 0);
10073     else
10074       getStreamer().EmitValueToAlignment(4, 0, 1, 0);
10075     return false;
10076   }
10077   return true;
10078 }
10079 
10080 /// parseDirectiveThumbSet
10081 ///  ::= .thumb_set name, value
10082 bool ARMAsmParser::parseDirectiveThumbSet(SMLoc L) {
10083   MCAsmParser &Parser = getParser();
10084 
10085   StringRef Name;
10086   if (check(Parser.parseIdentifier(Name),
10087             "expected identifier after '.thumb_set'") ||
10088       parseToken(AsmToken::Comma, "expected comma after name '" + Name + "'"))
10089     return true;
10090 
10091   MCSymbol *Sym;
10092   const MCExpr *Value;
10093   if (MCParserUtils::parseAssignmentExpression(Name, /* allow_redef */ true,
10094                                                Parser, Sym, Value))
10095     return true;
10096 
10097   getTargetStreamer().emitThumbSet(Sym, Value);
10098   return false;
10099 }
10100 
10101 /// Force static initialization.
10102 extern "C" void LLVMInitializeARMAsmParser() {
10103   RegisterMCAsmParser<ARMAsmParser> X(getTheARMLETarget());
10104   RegisterMCAsmParser<ARMAsmParser> Y(getTheARMBETarget());
10105   RegisterMCAsmParser<ARMAsmParser> A(getTheThumbLETarget());
10106   RegisterMCAsmParser<ARMAsmParser> B(getTheThumbBETarget());
10107 }
10108 
10109 #define GET_REGISTER_MATCHER
10110 #define GET_SUBTARGET_FEATURE_NAME
10111 #define GET_MATCHER_IMPLEMENTATION
10112 #define GET_MNEMONIC_SPELL_CHECKER
10113 #include "ARMGenAsmMatcher.inc"
10114 
10115 // Some diagnostics need to vary with subtarget features, so they are handled
10116 // here. For example, the DPR class has either 16 or 32 registers, depending
10117 // on the FPU available.
10118 const char *
10119 ARMAsmParser::getCustomOperandDiag(ARMMatchResultTy MatchError) {
10120   switch (MatchError) {
10121   // rGPR contains sp starting with ARMv8.
10122   case Match_rGPR:
10123     return hasV8Ops() ? "operand must be a register in range [r0, r14]"
10124                       : "operand must be a register in range [r0, r12] or r14";
10125   // DPR contains 16 registers for some FPUs, and 32 for others.
10126   case Match_DPR:
10127     return hasD16() ? "operand must be a register in range [d0, d15]"
10128                     : "operand must be a register in range [d0, d31]";
10129   case Match_DPR_RegList:
10130     return hasD16() ? "operand must be a list of registers in range [d0, d15]"
10131                     : "operand must be a list of registers in range [d0, d31]";
10132 
10133   // For all other diags, use the static string from tablegen.
10134   default:
10135     return getMatchKindDiag(MatchError);
10136   }
10137 }
10138 
10139 // Process the list of near-misses, throwing away ones we don't want to report
10140 // to the user, and converting the rest to a source location and string that
10141 // should be reported.
10142 void
10143 ARMAsmParser::FilterNearMisses(SmallVectorImpl<NearMissInfo> &NearMissesIn,
10144                                SmallVectorImpl<NearMissMessage> &NearMissesOut,
10145                                SMLoc IDLoc, OperandVector &Operands) {
10146   // TODO: If operand didn't match, sub in a dummy one and run target
10147   // predicate, so that we can avoid reporting near-misses that are invalid?
10148   // TODO: Many operand types dont have SuperClasses set, so we report
10149   // redundant ones.
10150   // TODO: Some operands are superclasses of registers (e.g.
10151   // MCK_RegShiftedImm), we don't have any way to represent that currently.
10152   // TODO: This is not all ARM-specific, can some of it be factored out?
10153 
10154   // Record some information about near-misses that we have already seen, so
10155   // that we can avoid reporting redundant ones. For example, if there are
10156   // variants of an instruction that take 8- and 16-bit immediates, we want
10157   // to only report the widest one.
10158   std::multimap<unsigned, unsigned> OperandMissesSeen;
10159   SmallSet<uint64_t, 4> FeatureMissesSeen;
10160   bool ReportedTooFewOperands = false;
10161 
10162   // Process the near-misses in reverse order, so that we see more general ones
10163   // first, and so can avoid emitting more specific ones.
10164   for (NearMissInfo &I : reverse(NearMissesIn)) {
10165     switch (I.getKind()) {
10166     case NearMissInfo::NearMissOperand: {
10167       SMLoc OperandLoc =
10168           ((ARMOperand &)*Operands[I.getOperandIndex()]).getStartLoc();
10169       const char *OperandDiag =
10170           getCustomOperandDiag((ARMMatchResultTy)I.getOperandError());
10171 
10172       // If we have already emitted a message for a superclass, don't also report
10173       // the sub-class. We consider all operand classes that we don't have a
10174       // specialised diagnostic for to be equal for the propose of this check,
10175       // so that we don't report the generic error multiple times on the same
10176       // operand.
10177       unsigned DupCheckMatchClass = OperandDiag ? I.getOperandClass() : ~0U;
10178       auto PrevReports = OperandMissesSeen.equal_range(I.getOperandIndex());
10179       if (std::any_of(PrevReports.first, PrevReports.second,
10180                       [DupCheckMatchClass](
10181                           const std::pair<unsigned, unsigned> Pair) {
10182             if (DupCheckMatchClass == ~0U || Pair.second == ~0U)
10183               return Pair.second == DupCheckMatchClass;
10184             else
10185               return isSubclass((MatchClassKind)DupCheckMatchClass,
10186                                 (MatchClassKind)Pair.second);
10187           }))
10188         break;
10189       OperandMissesSeen.insert(
10190           std::make_pair(I.getOperandIndex(), DupCheckMatchClass));
10191 
10192       NearMissMessage Message;
10193       Message.Loc = OperandLoc;
10194       if (OperandDiag) {
10195         Message.Message = OperandDiag;
10196       } else if (I.getOperandClass() == InvalidMatchClass) {
10197         Message.Message = "too many operands for instruction";
10198       } else {
10199         Message.Message = "invalid operand for instruction";
10200         DEBUG(dbgs() << "Missing diagnostic string for operand class " <<
10201               getMatchClassName((MatchClassKind)I.getOperandClass())
10202               << I.getOperandClass() << ", error " << I.getOperandError()
10203               << ", opcode " << MII.getName(I.getOpcode()) << "\n");
10204       }
10205       NearMissesOut.emplace_back(Message);
10206       break;
10207     }
10208     case NearMissInfo::NearMissFeature: {
10209       uint64_t MissingFeatures = I.getFeatures();
10210       // Don't report the same set of features twice.
10211       if (FeatureMissesSeen.count(MissingFeatures))
10212         break;
10213       FeatureMissesSeen.insert(MissingFeatures);
10214 
10215       // Special case: don't report a feature set which includes arm-mode for
10216       // targets that don't have ARM mode.
10217       if ((MissingFeatures & Feature_IsARM) && !hasARM())
10218         break;
10219       // Don't report any near-misses that both require switching instruction
10220       // set, and adding other subtarget features.
10221       if (isThumb() && (MissingFeatures & Feature_IsARM) &&
10222           (MissingFeatures & ~Feature_IsARM))
10223         break;
10224       if (!isThumb() && (MissingFeatures & Feature_IsThumb) &&
10225           (MissingFeatures & ~Feature_IsThumb))
10226         break;
10227       if (!isThumb() && (MissingFeatures & Feature_IsThumb2) &&
10228           (MissingFeatures & ~(Feature_IsThumb2 | Feature_IsThumb)))
10229         break;
10230 
10231       NearMissMessage Message;
10232       Message.Loc = IDLoc;
10233       raw_svector_ostream OS(Message.Message);
10234 
10235       OS << "instruction requires:";
10236       uint64_t Mask = 1;
10237       for (unsigned MaskPos = 0; MaskPos < (sizeof(MissingFeatures) * 8 - 1);
10238            ++MaskPos) {
10239         if (MissingFeatures & Mask) {
10240           OS << " " << getSubtargetFeatureName(MissingFeatures & Mask);
10241         }
10242         Mask <<= 1;
10243       }
10244       NearMissesOut.emplace_back(Message);
10245 
10246       break;
10247     }
10248     case NearMissInfo::NearMissPredicate: {
10249       NearMissMessage Message;
10250       Message.Loc = IDLoc;
10251       switch (I.getPredicateError()) {
10252       case Match_RequiresNotITBlock:
10253         Message.Message = "flag setting instruction only valid outside IT block";
10254         break;
10255       case Match_RequiresITBlock:
10256         Message.Message = "instruction only valid inside IT block";
10257         break;
10258       case Match_RequiresV6:
10259         Message.Message = "instruction variant requires ARMv6 or later";
10260         break;
10261       case Match_RequiresThumb2:
10262         Message.Message = "instruction variant requires Thumb2";
10263         break;
10264       case Match_RequiresV8:
10265         Message.Message = "instruction variant requires ARMv8 or later";
10266         break;
10267       case Match_RequiresFlagSetting:
10268         Message.Message = "no flag-preserving variant of this instruction available";
10269         break;
10270       case Match_InvalidOperand:
10271         Message.Message = "invalid operand for instruction";
10272         break;
10273       default:
10274         llvm_unreachable("Unhandled target predicate error");
10275         break;
10276       }
10277       NearMissesOut.emplace_back(Message);
10278       break;
10279     }
10280     case NearMissInfo::NearMissTooFewOperands: {
10281       if (!ReportedTooFewOperands) {
10282         SMLoc EndLoc = ((ARMOperand &)*Operands.back()).getEndLoc();
10283         NearMissesOut.emplace_back(NearMissMessage{
10284             EndLoc, StringRef("too few operands for instruction")});
10285         ReportedTooFewOperands = true;
10286       }
10287       break;
10288     }
10289     case NearMissInfo::NoNearMiss:
10290       // This should never leave the matcher.
10291       llvm_unreachable("not a near-miss");
10292       break;
10293     }
10294   }
10295 }
10296 
10297 void ARMAsmParser::ReportNearMisses(SmallVectorImpl<NearMissInfo> &NearMisses,
10298                                     SMLoc IDLoc, OperandVector &Operands) {
10299   SmallVector<NearMissMessage, 4> Messages;
10300   FilterNearMisses(NearMisses, Messages, IDLoc, Operands);
10301 
10302   if (Messages.size() == 0) {
10303     // No near-misses were found, so the best we can do is "invalid
10304     // instruction".
10305     Error(IDLoc, "invalid instruction");
10306   } else if (Messages.size() == 1) {
10307     // One near miss was found, report it as the sole error.
10308     Error(Messages[0].Loc, Messages[0].Message);
10309   } else {
10310     // More than one near miss, so report a generic "invalid instruction"
10311     // error, followed by notes for each of the near-misses.
10312     Error(IDLoc, "invalid instruction, any one of the following would fix this:");
10313     for (auto &M : Messages) {
10314       Note(M.Loc, M.Message);
10315     }
10316   }
10317 }
10318 
10319 // FIXME: This structure should be moved inside ARMTargetParser
10320 // when we start to table-generate them, and we can use the ARM
10321 // flags below, that were generated by table-gen.
10322 static const struct {
10323   const unsigned Kind;
10324   const uint64_t ArchCheck;
10325   const FeatureBitset Features;
10326 } Extensions[] = {
10327   { ARM::AEK_CRC, Feature_HasV8, {ARM::FeatureCRC} },
10328   { ARM::AEK_CRYPTO,  Feature_HasV8,
10329     {ARM::FeatureCrypto, ARM::FeatureNEON, ARM::FeatureFPARMv8} },
10330   { ARM::AEK_FP, Feature_HasV8, {ARM::FeatureFPARMv8} },
10331   { (ARM::AEK_HWDIVTHUMB | ARM::AEK_HWDIVARM), Feature_HasV7 | Feature_IsNotMClass,
10332     {ARM::FeatureHWDivThumb, ARM::FeatureHWDivARM} },
10333   { ARM::AEK_MP, Feature_HasV7 | Feature_IsNotMClass, {ARM::FeatureMP} },
10334   { ARM::AEK_SIMD, Feature_HasV8, {ARM::FeatureNEON, ARM::FeatureFPARMv8} },
10335   { ARM::AEK_SEC, Feature_HasV6K, {ARM::FeatureTrustZone} },
10336   // FIXME: Only available in A-class, isel not predicated
10337   { ARM::AEK_VIRT, Feature_HasV7, {ARM::FeatureVirtualization} },
10338   { ARM::AEK_FP16, Feature_HasV8_2a, {ARM::FeatureFPARMv8, ARM::FeatureFullFP16} },
10339   { ARM::AEK_RAS, Feature_HasV8, {ARM::FeatureRAS} },
10340   // FIXME: Unsupported extensions.
10341   { ARM::AEK_OS, Feature_None, {} },
10342   { ARM::AEK_IWMMXT, Feature_None, {} },
10343   { ARM::AEK_IWMMXT2, Feature_None, {} },
10344   { ARM::AEK_MAVERICK, Feature_None, {} },
10345   { ARM::AEK_XSCALE, Feature_None, {} },
10346 };
10347 
10348 /// parseDirectiveArchExtension
10349 ///   ::= .arch_extension [no]feature
10350 bool ARMAsmParser::parseDirectiveArchExtension(SMLoc L) {
10351   MCAsmParser &Parser = getParser();
10352 
10353   if (getLexer().isNot(AsmToken::Identifier))
10354     return Error(getLexer().getLoc(), "expected architecture extension name");
10355 
10356   StringRef Name = Parser.getTok().getString();
10357   SMLoc ExtLoc = Parser.getTok().getLoc();
10358   Lex();
10359 
10360   if (parseToken(AsmToken::EndOfStatement,
10361                  "unexpected token in '.arch_extension' directive"))
10362     return true;
10363 
10364   bool EnableFeature = true;
10365   if (Name.startswith_lower("no")) {
10366     EnableFeature = false;
10367     Name = Name.substr(2);
10368   }
10369   unsigned FeatureKind = ARM::parseArchExt(Name);
10370   if (FeatureKind == ARM::AEK_INVALID)
10371     return Error(ExtLoc, "unknown architectural extension: " + Name);
10372 
10373   for (const auto &Extension : Extensions) {
10374     if (Extension.Kind != FeatureKind)
10375       continue;
10376 
10377     if (Extension.Features.none())
10378       return Error(ExtLoc, "unsupported architectural extension: " + Name);
10379 
10380     if ((getAvailableFeatures() & Extension.ArchCheck) != Extension.ArchCheck)
10381       return Error(ExtLoc, "architectural extension '" + Name +
10382                                "' is not "
10383                                "allowed for the current base architecture");
10384 
10385     MCSubtargetInfo &STI = copySTI();
10386     FeatureBitset ToggleFeatures = EnableFeature
10387       ? (~STI.getFeatureBits() & Extension.Features)
10388       : ( STI.getFeatureBits() & Extension.Features);
10389 
10390     uint64_t Features =
10391         ComputeAvailableFeatures(STI.ToggleFeature(ToggleFeatures));
10392     setAvailableFeatures(Features);
10393     return false;
10394   }
10395 
10396   return Error(ExtLoc, "unknown architectural extension: " + Name);
10397 }
10398 
10399 // Define this matcher function after the auto-generated include so we
10400 // have the match class enum definitions.
10401 unsigned ARMAsmParser::validateTargetOperandClass(MCParsedAsmOperand &AsmOp,
10402                                                   unsigned Kind) {
10403   ARMOperand &Op = static_cast<ARMOperand &>(AsmOp);
10404   // If the kind is a token for a literal immediate, check if our asm
10405   // operand matches. This is for InstAliases which have a fixed-value
10406   // immediate in the syntax.
10407   switch (Kind) {
10408   default: break;
10409   case MCK__35_0:
10410     if (Op.isImm())
10411       if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm()))
10412         if (CE->getValue() == 0)
10413           return Match_Success;
10414     break;
10415   case MCK_ModImm:
10416     if (Op.isImm()) {
10417       const MCExpr *SOExpr = Op.getImm();
10418       int64_t Value;
10419       if (!SOExpr->evaluateAsAbsolute(Value))
10420         return Match_Success;
10421       assert((Value >= std::numeric_limits<int32_t>::min() &&
10422               Value <= std::numeric_limits<uint32_t>::max()) &&
10423              "expression value must be representable in 32 bits");
10424     }
10425     break;
10426   case MCK_rGPR:
10427     if (hasV8Ops() && Op.isReg() && Op.getReg() == ARM::SP)
10428       return Match_Success;
10429     return Match_rGPR;
10430   case MCK_GPRPair:
10431     if (Op.isReg() &&
10432         MRI->getRegClass(ARM::GPRRegClassID).contains(Op.getReg()))
10433       return Match_Success;
10434     break;
10435   }
10436   return Match_InvalidOperand;
10437 }
10438