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 
4242   if (Tok.is(AsmToken::Integer)) {
4243     int64_t Val = Tok.getIntVal();
4244     if (Val > 255 || Val < 0) {
4245       return MatchOperand_NoMatch;
4246     }
4247     unsigned SYSmvalue = Val & 0xFF;
4248     Parser.Lex();
4249     Operands.push_back(ARMOperand::CreateMSRMask(SYSmvalue, S));
4250     return MatchOperand_Success;
4251   }
4252 
4253   if (!Tok.is(AsmToken::Identifier))
4254     return MatchOperand_NoMatch;
4255   StringRef Mask = Tok.getString();
4256 
4257   if (isMClass()) {
4258     auto TheReg = ARMSysReg::lookupMClassSysRegByName(Mask.lower());
4259     if (!TheReg || !TheReg->hasRequiredFeatures(getSTI().getFeatureBits()))
4260       return MatchOperand_NoMatch;
4261 
4262     unsigned SYSmvalue = TheReg->Encoding & 0xFFF;
4263 
4264     Parser.Lex(); // Eat identifier token.
4265     Operands.push_back(ARMOperand::CreateMSRMask(SYSmvalue, S));
4266     return MatchOperand_Success;
4267   }
4268 
4269   // Split spec_reg from flag, example: CPSR_sxf => "CPSR" and "sxf"
4270   size_t Start = 0, Next = Mask.find('_');
4271   StringRef Flags = "";
4272   std::string SpecReg = Mask.slice(Start, Next).lower();
4273   if (Next != StringRef::npos)
4274     Flags = Mask.slice(Next+1, Mask.size());
4275 
4276   // FlagsVal contains the complete mask:
4277   // 3-0: Mask
4278   // 4: Special Reg (cpsr, apsr => 0; spsr => 1)
4279   unsigned FlagsVal = 0;
4280 
4281   if (SpecReg == "apsr") {
4282     FlagsVal = StringSwitch<unsigned>(Flags)
4283     .Case("nzcvq",  0x8) // same as CPSR_f
4284     .Case("g",      0x4) // same as CPSR_s
4285     .Case("nzcvqg", 0xc) // same as CPSR_fs
4286     .Default(~0U);
4287 
4288     if (FlagsVal == ~0U) {
4289       if (!Flags.empty())
4290         return MatchOperand_NoMatch;
4291       else
4292         FlagsVal = 8; // No flag
4293     }
4294   } else if (SpecReg == "cpsr" || SpecReg == "spsr") {
4295     // cpsr_all is an alias for cpsr_fc, as is plain cpsr.
4296     if (Flags == "all" || Flags == "")
4297       Flags = "fc";
4298     for (int i = 0, e = Flags.size(); i != e; ++i) {
4299       unsigned Flag = StringSwitch<unsigned>(Flags.substr(i, 1))
4300       .Case("c", 1)
4301       .Case("x", 2)
4302       .Case("s", 4)
4303       .Case("f", 8)
4304       .Default(~0U);
4305 
4306       // If some specific flag is already set, it means that some letter is
4307       // present more than once, this is not acceptable.
4308       if (Flag == ~0U || (FlagsVal & Flag))
4309         return MatchOperand_NoMatch;
4310       FlagsVal |= Flag;
4311     }
4312   } else // No match for special register.
4313     return MatchOperand_NoMatch;
4314 
4315   // Special register without flags is NOT equivalent to "fc" flags.
4316   // NOTE: This is a divergence from gas' behavior.  Uncommenting the following
4317   // two lines would enable gas compatibility at the expense of breaking
4318   // round-tripping.
4319   //
4320   // if (!FlagsVal)
4321   //  FlagsVal = 0x9;
4322 
4323   // Bit 4: Special Reg (cpsr, apsr => 0; spsr => 1)
4324   if (SpecReg == "spsr")
4325     FlagsVal |= 16;
4326 
4327   Parser.Lex(); // Eat identifier token.
4328   Operands.push_back(ARMOperand::CreateMSRMask(FlagsVal, S));
4329   return MatchOperand_Success;
4330 }
4331 
4332 /// parseBankedRegOperand - Try to parse a banked register (e.g. "lr_irq") for
4333 /// use in the MRS/MSR instructions added to support virtualization.
4334 OperandMatchResultTy
4335 ARMAsmParser::parseBankedRegOperand(OperandVector &Operands) {
4336   MCAsmParser &Parser = getParser();
4337   SMLoc S = Parser.getTok().getLoc();
4338   const AsmToken &Tok = Parser.getTok();
4339   if (!Tok.is(AsmToken::Identifier))
4340     return MatchOperand_NoMatch;
4341   StringRef RegName = Tok.getString();
4342 
4343   auto TheReg = ARMBankedReg::lookupBankedRegByName(RegName.lower());
4344   if (!TheReg)
4345     return MatchOperand_NoMatch;
4346   unsigned Encoding = TheReg->Encoding;
4347 
4348   Parser.Lex(); // Eat identifier token.
4349   Operands.push_back(ARMOperand::CreateBankedReg(Encoding, S));
4350   return MatchOperand_Success;
4351 }
4352 
4353 OperandMatchResultTy
4354 ARMAsmParser::parsePKHImm(OperandVector &Operands, StringRef Op, int Low,
4355                           int High) {
4356   MCAsmParser &Parser = getParser();
4357   const AsmToken &Tok = Parser.getTok();
4358   if (Tok.isNot(AsmToken::Identifier)) {
4359     Error(Parser.getTok().getLoc(), Op + " operand expected.");
4360     return MatchOperand_ParseFail;
4361   }
4362   StringRef ShiftName = Tok.getString();
4363   std::string LowerOp = Op.lower();
4364   std::string UpperOp = Op.upper();
4365   if (ShiftName != LowerOp && ShiftName != UpperOp) {
4366     Error(Parser.getTok().getLoc(), Op + " operand expected.");
4367     return MatchOperand_ParseFail;
4368   }
4369   Parser.Lex(); // Eat shift type token.
4370 
4371   // There must be a '#' and a shift amount.
4372   if (Parser.getTok().isNot(AsmToken::Hash) &&
4373       Parser.getTok().isNot(AsmToken::Dollar)) {
4374     Error(Parser.getTok().getLoc(), "'#' expected");
4375     return MatchOperand_ParseFail;
4376   }
4377   Parser.Lex(); // Eat hash token.
4378 
4379   const MCExpr *ShiftAmount;
4380   SMLoc Loc = Parser.getTok().getLoc();
4381   SMLoc EndLoc;
4382   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
4383     Error(Loc, "illegal expression");
4384     return MatchOperand_ParseFail;
4385   }
4386   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
4387   if (!CE) {
4388     Error(Loc, "constant expression expected");
4389     return MatchOperand_ParseFail;
4390   }
4391   int Val = CE->getValue();
4392   if (Val < Low || Val > High) {
4393     Error(Loc, "immediate value out of range");
4394     return MatchOperand_ParseFail;
4395   }
4396 
4397   Operands.push_back(ARMOperand::CreateImm(CE, Loc, EndLoc));
4398 
4399   return MatchOperand_Success;
4400 }
4401 
4402 OperandMatchResultTy
4403 ARMAsmParser::parseSetEndImm(OperandVector &Operands) {
4404   MCAsmParser &Parser = getParser();
4405   const AsmToken &Tok = Parser.getTok();
4406   SMLoc S = Tok.getLoc();
4407   if (Tok.isNot(AsmToken::Identifier)) {
4408     Error(S, "'be' or 'le' operand expected");
4409     return MatchOperand_ParseFail;
4410   }
4411   int Val = StringSwitch<int>(Tok.getString().lower())
4412     .Case("be", 1)
4413     .Case("le", 0)
4414     .Default(-1);
4415   Parser.Lex(); // Eat the token.
4416 
4417   if (Val == -1) {
4418     Error(S, "'be' or 'le' operand expected");
4419     return MatchOperand_ParseFail;
4420   }
4421   Operands.push_back(ARMOperand::CreateImm(MCConstantExpr::create(Val,
4422                                                                   getContext()),
4423                                            S, Tok.getEndLoc()));
4424   return MatchOperand_Success;
4425 }
4426 
4427 /// parseShifterImm - Parse the shifter immediate operand for SSAT/USAT
4428 /// instructions. Legal values are:
4429 ///     lsl #n  'n' in [0,31]
4430 ///     asr #n  'n' in [1,32]
4431 ///             n == 32 encoded as n == 0.
4432 OperandMatchResultTy
4433 ARMAsmParser::parseShifterImm(OperandVector &Operands) {
4434   MCAsmParser &Parser = getParser();
4435   const AsmToken &Tok = Parser.getTok();
4436   SMLoc S = Tok.getLoc();
4437   if (Tok.isNot(AsmToken::Identifier)) {
4438     Error(S, "shift operator 'asr' or 'lsl' expected");
4439     return MatchOperand_ParseFail;
4440   }
4441   StringRef ShiftName = Tok.getString();
4442   bool isASR;
4443   if (ShiftName == "lsl" || ShiftName == "LSL")
4444     isASR = false;
4445   else if (ShiftName == "asr" || ShiftName == "ASR")
4446     isASR = true;
4447   else {
4448     Error(S, "shift operator 'asr' or 'lsl' expected");
4449     return MatchOperand_ParseFail;
4450   }
4451   Parser.Lex(); // Eat the operator.
4452 
4453   // A '#' and a shift amount.
4454   if (Parser.getTok().isNot(AsmToken::Hash) &&
4455       Parser.getTok().isNot(AsmToken::Dollar)) {
4456     Error(Parser.getTok().getLoc(), "'#' expected");
4457     return MatchOperand_ParseFail;
4458   }
4459   Parser.Lex(); // Eat hash token.
4460   SMLoc ExLoc = Parser.getTok().getLoc();
4461 
4462   const MCExpr *ShiftAmount;
4463   SMLoc EndLoc;
4464   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
4465     Error(ExLoc, "malformed shift expression");
4466     return MatchOperand_ParseFail;
4467   }
4468   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
4469   if (!CE) {
4470     Error(ExLoc, "shift amount must be an immediate");
4471     return MatchOperand_ParseFail;
4472   }
4473 
4474   int64_t Val = CE->getValue();
4475   if (isASR) {
4476     // Shift amount must be in [1,32]
4477     if (Val < 1 || Val > 32) {
4478       Error(ExLoc, "'asr' shift amount must be in range [1,32]");
4479       return MatchOperand_ParseFail;
4480     }
4481     // asr #32 encoded as asr #0, but is not allowed in Thumb2 mode.
4482     if (isThumb() && Val == 32) {
4483       Error(ExLoc, "'asr #32' shift amount not allowed in Thumb mode");
4484       return MatchOperand_ParseFail;
4485     }
4486     if (Val == 32) Val = 0;
4487   } else {
4488     // Shift amount must be in [1,32]
4489     if (Val < 0 || Val > 31) {
4490       Error(ExLoc, "'lsr' shift amount must be in range [0,31]");
4491       return MatchOperand_ParseFail;
4492     }
4493   }
4494 
4495   Operands.push_back(ARMOperand::CreateShifterImm(isASR, Val, S, EndLoc));
4496 
4497   return MatchOperand_Success;
4498 }
4499 
4500 /// parseRotImm - Parse the shifter immediate operand for SXTB/UXTB family
4501 /// of instructions. Legal values are:
4502 ///     ror #n  'n' in {0, 8, 16, 24}
4503 OperandMatchResultTy
4504 ARMAsmParser::parseRotImm(OperandVector &Operands) {
4505   MCAsmParser &Parser = getParser();
4506   const AsmToken &Tok = Parser.getTok();
4507   SMLoc S = Tok.getLoc();
4508   if (Tok.isNot(AsmToken::Identifier))
4509     return MatchOperand_NoMatch;
4510   StringRef ShiftName = Tok.getString();
4511   if (ShiftName != "ror" && ShiftName != "ROR")
4512     return MatchOperand_NoMatch;
4513   Parser.Lex(); // Eat the operator.
4514 
4515   // A '#' and a rotate amount.
4516   if (Parser.getTok().isNot(AsmToken::Hash) &&
4517       Parser.getTok().isNot(AsmToken::Dollar)) {
4518     Error(Parser.getTok().getLoc(), "'#' expected");
4519     return MatchOperand_ParseFail;
4520   }
4521   Parser.Lex(); // Eat hash token.
4522   SMLoc ExLoc = Parser.getTok().getLoc();
4523 
4524   const MCExpr *ShiftAmount;
4525   SMLoc EndLoc;
4526   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
4527     Error(ExLoc, "malformed rotate expression");
4528     return MatchOperand_ParseFail;
4529   }
4530   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
4531   if (!CE) {
4532     Error(ExLoc, "rotate amount must be an immediate");
4533     return MatchOperand_ParseFail;
4534   }
4535 
4536   int64_t Val = CE->getValue();
4537   // Shift amount must be in {0, 8, 16, 24} (0 is undocumented extension)
4538   // normally, zero is represented in asm by omitting the rotate operand
4539   // entirely.
4540   if (Val != 8 && Val != 16 && Val != 24 && Val != 0) {
4541     Error(ExLoc, "'ror' rotate amount must be 8, 16, or 24");
4542     return MatchOperand_ParseFail;
4543   }
4544 
4545   Operands.push_back(ARMOperand::CreateRotImm(Val, S, EndLoc));
4546 
4547   return MatchOperand_Success;
4548 }
4549 
4550 OperandMatchResultTy
4551 ARMAsmParser::parseModImm(OperandVector &Operands) {
4552   MCAsmParser &Parser = getParser();
4553   MCAsmLexer &Lexer = getLexer();
4554   int64_t Imm1, Imm2;
4555 
4556   SMLoc S = Parser.getTok().getLoc();
4557 
4558   // 1) A mod_imm operand can appear in the place of a register name:
4559   //   add r0, #mod_imm
4560   //   add r0, r0, #mod_imm
4561   // to correctly handle the latter, we bail out as soon as we see an
4562   // identifier.
4563   //
4564   // 2) Similarly, we do not want to parse into complex operands:
4565   //   mov r0, #mod_imm
4566   //   mov r0, :lower16:(_foo)
4567   if (Parser.getTok().is(AsmToken::Identifier) ||
4568       Parser.getTok().is(AsmToken::Colon))
4569     return MatchOperand_NoMatch;
4570 
4571   // Hash (dollar) is optional as per the ARMARM
4572   if (Parser.getTok().is(AsmToken::Hash) ||
4573       Parser.getTok().is(AsmToken::Dollar)) {
4574     // Avoid parsing into complex operands (#:)
4575     if (Lexer.peekTok().is(AsmToken::Colon))
4576       return MatchOperand_NoMatch;
4577 
4578     // Eat the hash (dollar)
4579     Parser.Lex();
4580   }
4581 
4582   SMLoc Sx1, Ex1;
4583   Sx1 = Parser.getTok().getLoc();
4584   const MCExpr *Imm1Exp;
4585   if (getParser().parseExpression(Imm1Exp, Ex1)) {
4586     Error(Sx1, "malformed expression");
4587     return MatchOperand_ParseFail;
4588   }
4589 
4590   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm1Exp);
4591 
4592   if (CE) {
4593     // Immediate must fit within 32-bits
4594     Imm1 = CE->getValue();
4595     int Enc = ARM_AM::getSOImmVal(Imm1);
4596     if (Enc != -1 && Parser.getTok().is(AsmToken::EndOfStatement)) {
4597       // We have a match!
4598       Operands.push_back(ARMOperand::CreateModImm((Enc & 0xFF),
4599                                                   (Enc & 0xF00) >> 7,
4600                                                   Sx1, Ex1));
4601       return MatchOperand_Success;
4602     }
4603 
4604     // We have parsed an immediate which is not for us, fallback to a plain
4605     // immediate. This can happen for instruction aliases. For an example,
4606     // ARMInstrInfo.td defines the alias [mov <-> mvn] which can transform
4607     // a mov (mvn) with a mod_imm_neg/mod_imm_not operand into the opposite
4608     // instruction with a mod_imm operand. The alias is defined such that the
4609     // parser method is shared, that's why we have to do this here.
4610     if (Parser.getTok().is(AsmToken::EndOfStatement)) {
4611       Operands.push_back(ARMOperand::CreateImm(Imm1Exp, Sx1, Ex1));
4612       return MatchOperand_Success;
4613     }
4614   } else {
4615     // Operands like #(l1 - l2) can only be evaluated at a later stage (via an
4616     // MCFixup). Fallback to a plain immediate.
4617     Operands.push_back(ARMOperand::CreateImm(Imm1Exp, Sx1, Ex1));
4618     return MatchOperand_Success;
4619   }
4620 
4621   // From this point onward, we expect the input to be a (#bits, #rot) pair
4622   if (Parser.getTok().isNot(AsmToken::Comma)) {
4623     Error(Sx1, "expected modified immediate operand: #[0, 255], #even[0-30]");
4624     return MatchOperand_ParseFail;
4625   }
4626 
4627   if (Imm1 & ~0xFF) {
4628     Error(Sx1, "immediate operand must a number in the range [0, 255]");
4629     return MatchOperand_ParseFail;
4630   }
4631 
4632   // Eat the comma
4633   Parser.Lex();
4634 
4635   // Repeat for #rot
4636   SMLoc Sx2, Ex2;
4637   Sx2 = Parser.getTok().getLoc();
4638 
4639   // Eat the optional hash (dollar)
4640   if (Parser.getTok().is(AsmToken::Hash) ||
4641       Parser.getTok().is(AsmToken::Dollar))
4642     Parser.Lex();
4643 
4644   const MCExpr *Imm2Exp;
4645   if (getParser().parseExpression(Imm2Exp, Ex2)) {
4646     Error(Sx2, "malformed expression");
4647     return MatchOperand_ParseFail;
4648   }
4649 
4650   CE = dyn_cast<MCConstantExpr>(Imm2Exp);
4651 
4652   if (CE) {
4653     Imm2 = CE->getValue();
4654     if (!(Imm2 & ~0x1E)) {
4655       // We have a match!
4656       Operands.push_back(ARMOperand::CreateModImm(Imm1, Imm2, S, Ex2));
4657       return MatchOperand_Success;
4658     }
4659     Error(Sx2, "immediate operand must an even number in the range [0, 30]");
4660     return MatchOperand_ParseFail;
4661   } else {
4662     Error(Sx2, "constant expression expected");
4663     return MatchOperand_ParseFail;
4664   }
4665 }
4666 
4667 OperandMatchResultTy
4668 ARMAsmParser::parseBitfield(OperandVector &Operands) {
4669   MCAsmParser &Parser = getParser();
4670   SMLoc S = Parser.getTok().getLoc();
4671   // The bitfield descriptor is really two operands, the LSB and the width.
4672   if (Parser.getTok().isNot(AsmToken::Hash) &&
4673       Parser.getTok().isNot(AsmToken::Dollar)) {
4674     Error(Parser.getTok().getLoc(), "'#' expected");
4675     return MatchOperand_ParseFail;
4676   }
4677   Parser.Lex(); // Eat hash token.
4678 
4679   const MCExpr *LSBExpr;
4680   SMLoc E = Parser.getTok().getLoc();
4681   if (getParser().parseExpression(LSBExpr)) {
4682     Error(E, "malformed immediate expression");
4683     return MatchOperand_ParseFail;
4684   }
4685   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(LSBExpr);
4686   if (!CE) {
4687     Error(E, "'lsb' operand must be an immediate");
4688     return MatchOperand_ParseFail;
4689   }
4690 
4691   int64_t LSB = CE->getValue();
4692   // The LSB must be in the range [0,31]
4693   if (LSB < 0 || LSB > 31) {
4694     Error(E, "'lsb' operand must be in the range [0,31]");
4695     return MatchOperand_ParseFail;
4696   }
4697   E = Parser.getTok().getLoc();
4698 
4699   // Expect another immediate operand.
4700   if (Parser.getTok().isNot(AsmToken::Comma)) {
4701     Error(Parser.getTok().getLoc(), "too few operands");
4702     return MatchOperand_ParseFail;
4703   }
4704   Parser.Lex(); // Eat hash token.
4705   if (Parser.getTok().isNot(AsmToken::Hash) &&
4706       Parser.getTok().isNot(AsmToken::Dollar)) {
4707     Error(Parser.getTok().getLoc(), "'#' expected");
4708     return MatchOperand_ParseFail;
4709   }
4710   Parser.Lex(); // Eat hash token.
4711 
4712   const MCExpr *WidthExpr;
4713   SMLoc EndLoc;
4714   if (getParser().parseExpression(WidthExpr, EndLoc)) {
4715     Error(E, "malformed immediate expression");
4716     return MatchOperand_ParseFail;
4717   }
4718   CE = dyn_cast<MCConstantExpr>(WidthExpr);
4719   if (!CE) {
4720     Error(E, "'width' operand must be an immediate");
4721     return MatchOperand_ParseFail;
4722   }
4723 
4724   int64_t Width = CE->getValue();
4725   // The LSB must be in the range [1,32-lsb]
4726   if (Width < 1 || Width > 32 - LSB) {
4727     Error(E, "'width' operand must be in the range [1,32-lsb]");
4728     return MatchOperand_ParseFail;
4729   }
4730 
4731   Operands.push_back(ARMOperand::CreateBitfield(LSB, Width, S, EndLoc));
4732 
4733   return MatchOperand_Success;
4734 }
4735 
4736 OperandMatchResultTy
4737 ARMAsmParser::parsePostIdxReg(OperandVector &Operands) {
4738   // Check for a post-index addressing register operand. Specifically:
4739   // postidx_reg := '+' register {, shift}
4740   //              | '-' register {, shift}
4741   //              | register {, shift}
4742 
4743   // This method must return MatchOperand_NoMatch without consuming any tokens
4744   // in the case where there is no match, as other alternatives take other
4745   // parse methods.
4746   MCAsmParser &Parser = getParser();
4747   AsmToken Tok = Parser.getTok();
4748   SMLoc S = Tok.getLoc();
4749   bool haveEaten = false;
4750   bool isAdd = true;
4751   if (Tok.is(AsmToken::Plus)) {
4752     Parser.Lex(); // Eat the '+' token.
4753     haveEaten = true;
4754   } else if (Tok.is(AsmToken::Minus)) {
4755     Parser.Lex(); // Eat the '-' token.
4756     isAdd = false;
4757     haveEaten = true;
4758   }
4759 
4760   SMLoc E = Parser.getTok().getEndLoc();
4761   int Reg = tryParseRegister();
4762   if (Reg == -1) {
4763     if (!haveEaten)
4764       return MatchOperand_NoMatch;
4765     Error(Parser.getTok().getLoc(), "register expected");
4766     return MatchOperand_ParseFail;
4767   }
4768 
4769   ARM_AM::ShiftOpc ShiftTy = ARM_AM::no_shift;
4770   unsigned ShiftImm = 0;
4771   if (Parser.getTok().is(AsmToken::Comma)) {
4772     Parser.Lex(); // Eat the ','.
4773     if (parseMemRegOffsetShift(ShiftTy, ShiftImm))
4774       return MatchOperand_ParseFail;
4775 
4776     // FIXME: Only approximates end...may include intervening whitespace.
4777     E = Parser.getTok().getLoc();
4778   }
4779 
4780   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ShiftTy,
4781                                                   ShiftImm, S, E));
4782 
4783   return MatchOperand_Success;
4784 }
4785 
4786 OperandMatchResultTy
4787 ARMAsmParser::parseAM3Offset(OperandVector &Operands) {
4788   // Check for a post-index addressing register operand. Specifically:
4789   // am3offset := '+' register
4790   //              | '-' register
4791   //              | register
4792   //              | # imm
4793   //              | # + imm
4794   //              | # - imm
4795 
4796   // This method must return MatchOperand_NoMatch without consuming any tokens
4797   // in the case where there is no match, as other alternatives take other
4798   // parse methods.
4799   MCAsmParser &Parser = getParser();
4800   AsmToken Tok = Parser.getTok();
4801   SMLoc S = Tok.getLoc();
4802 
4803   // Do immediates first, as we always parse those if we have a '#'.
4804   if (Parser.getTok().is(AsmToken::Hash) ||
4805       Parser.getTok().is(AsmToken::Dollar)) {
4806     Parser.Lex(); // Eat '#' or '$'.
4807     // Explicitly look for a '-', as we need to encode negative zero
4808     // differently.
4809     bool isNegative = Parser.getTok().is(AsmToken::Minus);
4810     const MCExpr *Offset;
4811     SMLoc E;
4812     if (getParser().parseExpression(Offset, E))
4813       return MatchOperand_ParseFail;
4814     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
4815     if (!CE) {
4816       Error(S, "constant expression expected");
4817       return MatchOperand_ParseFail;
4818     }
4819     // Negative zero is encoded as the flag value
4820     // std::numeric_limits<int32_t>::min().
4821     int32_t Val = CE->getValue();
4822     if (isNegative && Val == 0)
4823       Val = std::numeric_limits<int32_t>::min();
4824 
4825     Operands.push_back(
4826       ARMOperand::CreateImm(MCConstantExpr::create(Val, getContext()), S, E));
4827 
4828     return MatchOperand_Success;
4829   }
4830 
4831   bool haveEaten = false;
4832   bool isAdd = true;
4833   if (Tok.is(AsmToken::Plus)) {
4834     Parser.Lex(); // Eat the '+' token.
4835     haveEaten = true;
4836   } else if (Tok.is(AsmToken::Minus)) {
4837     Parser.Lex(); // Eat the '-' token.
4838     isAdd = false;
4839     haveEaten = true;
4840   }
4841 
4842   Tok = Parser.getTok();
4843   int Reg = tryParseRegister();
4844   if (Reg == -1) {
4845     if (!haveEaten)
4846       return MatchOperand_NoMatch;
4847     Error(Tok.getLoc(), "register expected");
4848     return MatchOperand_ParseFail;
4849   }
4850 
4851   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ARM_AM::no_shift,
4852                                                   0, S, Tok.getEndLoc()));
4853 
4854   return MatchOperand_Success;
4855 }
4856 
4857 /// Convert parsed operands to MCInst.  Needed here because this instruction
4858 /// only has two register operands, but multiplication is commutative so
4859 /// assemblers should accept both "mul rD, rN, rD" and "mul rD, rD, rN".
4860 void ARMAsmParser::cvtThumbMultiply(MCInst &Inst,
4861                                     const OperandVector &Operands) {
4862   ((ARMOperand &)*Operands[3]).addRegOperands(Inst, 1);
4863   ((ARMOperand &)*Operands[1]).addCCOutOperands(Inst, 1);
4864   // If we have a three-operand form, make sure to set Rn to be the operand
4865   // that isn't the same as Rd.
4866   unsigned RegOp = 4;
4867   if (Operands.size() == 6 &&
4868       ((ARMOperand &)*Operands[4]).getReg() ==
4869           ((ARMOperand &)*Operands[3]).getReg())
4870     RegOp = 5;
4871   ((ARMOperand &)*Operands[RegOp]).addRegOperands(Inst, 1);
4872   Inst.addOperand(Inst.getOperand(0));
4873   ((ARMOperand &)*Operands[2]).addCondCodeOperands(Inst, 2);
4874 }
4875 
4876 void ARMAsmParser::cvtThumbBranches(MCInst &Inst,
4877                                     const OperandVector &Operands) {
4878   int CondOp = -1, ImmOp = -1;
4879   switch(Inst.getOpcode()) {
4880     case ARM::tB:
4881     case ARM::tBcc:  CondOp = 1; ImmOp = 2; break;
4882 
4883     case ARM::t2B:
4884     case ARM::t2Bcc: CondOp = 1; ImmOp = 3; break;
4885 
4886     default: llvm_unreachable("Unexpected instruction in cvtThumbBranches");
4887   }
4888   // first decide whether or not the branch should be conditional
4889   // by looking at it's location relative to an IT block
4890   if(inITBlock()) {
4891     // inside an IT block we cannot have any conditional branches. any
4892     // such instructions needs to be converted to unconditional form
4893     switch(Inst.getOpcode()) {
4894       case ARM::tBcc: Inst.setOpcode(ARM::tB); break;
4895       case ARM::t2Bcc: Inst.setOpcode(ARM::t2B); break;
4896     }
4897   } else {
4898     // outside IT blocks we can only have unconditional branches with AL
4899     // condition code or conditional branches with non-AL condition code
4900     unsigned Cond = static_cast<ARMOperand &>(*Operands[CondOp]).getCondCode();
4901     switch(Inst.getOpcode()) {
4902       case ARM::tB:
4903       case ARM::tBcc:
4904         Inst.setOpcode(Cond == ARMCC::AL ? ARM::tB : ARM::tBcc);
4905         break;
4906       case ARM::t2B:
4907       case ARM::t2Bcc:
4908         Inst.setOpcode(Cond == ARMCC::AL ? ARM::t2B : ARM::t2Bcc);
4909         break;
4910     }
4911   }
4912 
4913   // now decide on encoding size based on branch target range
4914   switch(Inst.getOpcode()) {
4915     // classify tB as either t2B or t1B based on range of immediate operand
4916     case ARM::tB: {
4917       ARMOperand &op = static_cast<ARMOperand &>(*Operands[ImmOp]);
4918       if (!op.isSignedOffset<11, 1>() && isThumb() && hasV8MBaseline())
4919         Inst.setOpcode(ARM::t2B);
4920       break;
4921     }
4922     // classify tBcc as either t2Bcc or t1Bcc based on range of immediate operand
4923     case ARM::tBcc: {
4924       ARMOperand &op = static_cast<ARMOperand &>(*Operands[ImmOp]);
4925       if (!op.isSignedOffset<8, 1>() && isThumb() && hasV8MBaseline())
4926         Inst.setOpcode(ARM::t2Bcc);
4927       break;
4928     }
4929   }
4930   ((ARMOperand &)*Operands[ImmOp]).addImmOperands(Inst, 1);
4931   ((ARMOperand &)*Operands[CondOp]).addCondCodeOperands(Inst, 2);
4932 }
4933 
4934 /// Parse an ARM memory expression, return false if successful else return true
4935 /// or an error.  The first token must be a '[' when called.
4936 bool ARMAsmParser::parseMemory(OperandVector &Operands) {
4937   MCAsmParser &Parser = getParser();
4938   SMLoc S, E;
4939   if (Parser.getTok().isNot(AsmToken::LBrac))
4940     return TokError("Token is not a Left Bracket");
4941   S = Parser.getTok().getLoc();
4942   Parser.Lex(); // Eat left bracket token.
4943 
4944   const AsmToken &BaseRegTok = Parser.getTok();
4945   int BaseRegNum = tryParseRegister();
4946   if (BaseRegNum == -1)
4947     return Error(BaseRegTok.getLoc(), "register expected");
4948 
4949   // The next token must either be a comma, a colon or a closing bracket.
4950   const AsmToken &Tok = Parser.getTok();
4951   if (!Tok.is(AsmToken::Colon) && !Tok.is(AsmToken::Comma) &&
4952       !Tok.is(AsmToken::RBrac))
4953     return Error(Tok.getLoc(), "malformed memory operand");
4954 
4955   if (Tok.is(AsmToken::RBrac)) {
4956     E = Tok.getEndLoc();
4957     Parser.Lex(); // Eat right bracket token.
4958 
4959     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, 0,
4960                                              ARM_AM::no_shift, 0, 0, false,
4961                                              S, E));
4962 
4963     // If there's a pre-indexing writeback marker, '!', just add it as a token
4964     // operand. It's rather odd, but syntactically valid.
4965     if (Parser.getTok().is(AsmToken::Exclaim)) {
4966       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
4967       Parser.Lex(); // Eat the '!'.
4968     }
4969 
4970     return false;
4971   }
4972 
4973   assert((Tok.is(AsmToken::Colon) || Tok.is(AsmToken::Comma)) &&
4974          "Lost colon or comma in memory operand?!");
4975   if (Tok.is(AsmToken::Comma)) {
4976     Parser.Lex(); // Eat the comma.
4977   }
4978 
4979   // If we have a ':', it's an alignment specifier.
4980   if (Parser.getTok().is(AsmToken::Colon)) {
4981     Parser.Lex(); // Eat the ':'.
4982     E = Parser.getTok().getLoc();
4983     SMLoc AlignmentLoc = Tok.getLoc();
4984 
4985     const MCExpr *Expr;
4986     if (getParser().parseExpression(Expr))
4987      return true;
4988 
4989     // The expression has to be a constant. Memory references with relocations
4990     // don't come through here, as they use the <label> forms of the relevant
4991     // instructions.
4992     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
4993     if (!CE)
4994       return Error (E, "constant expression expected");
4995 
4996     unsigned Align = 0;
4997     switch (CE->getValue()) {
4998     default:
4999       return Error(E,
5000                    "alignment specifier must be 16, 32, 64, 128, or 256 bits");
5001     case 16:  Align = 2; break;
5002     case 32:  Align = 4; break;
5003     case 64:  Align = 8; break;
5004     case 128: Align = 16; break;
5005     case 256: Align = 32; break;
5006     }
5007 
5008     // Now we should have the closing ']'
5009     if (Parser.getTok().isNot(AsmToken::RBrac))
5010       return Error(Parser.getTok().getLoc(), "']' expected");
5011     E = Parser.getTok().getEndLoc();
5012     Parser.Lex(); // Eat right bracket token.
5013 
5014     // Don't worry about range checking the value here. That's handled by
5015     // the is*() predicates.
5016     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, 0,
5017                                              ARM_AM::no_shift, 0, Align,
5018                                              false, S, E, AlignmentLoc));
5019 
5020     // If there's a pre-indexing writeback marker, '!', just add it as a token
5021     // operand.
5022     if (Parser.getTok().is(AsmToken::Exclaim)) {
5023       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
5024       Parser.Lex(); // Eat the '!'.
5025     }
5026 
5027     return false;
5028   }
5029 
5030   // If we have a '#', it's an immediate offset, else assume it's a register
5031   // offset. Be friendly and also accept a plain integer (without a leading
5032   // hash) for gas compatibility.
5033   if (Parser.getTok().is(AsmToken::Hash) ||
5034       Parser.getTok().is(AsmToken::Dollar) ||
5035       Parser.getTok().is(AsmToken::Integer)) {
5036     if (Parser.getTok().isNot(AsmToken::Integer))
5037       Parser.Lex(); // Eat '#' or '$'.
5038     E = Parser.getTok().getLoc();
5039 
5040     bool isNegative = getParser().getTok().is(AsmToken::Minus);
5041     const MCExpr *Offset;
5042     if (getParser().parseExpression(Offset))
5043      return true;
5044 
5045     // The expression has to be a constant. Memory references with relocations
5046     // don't come through here, as they use the <label> forms of the relevant
5047     // instructions.
5048     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
5049     if (!CE)
5050       return Error (E, "constant expression expected");
5051 
5052     // If the constant was #-0, represent it as
5053     // std::numeric_limits<int32_t>::min().
5054     int32_t Val = CE->getValue();
5055     if (isNegative && Val == 0)
5056       CE = MCConstantExpr::create(std::numeric_limits<int32_t>::min(),
5057                                   getContext());
5058 
5059     // Now we should have the closing ']'
5060     if (Parser.getTok().isNot(AsmToken::RBrac))
5061       return Error(Parser.getTok().getLoc(), "']' expected");
5062     E = Parser.getTok().getEndLoc();
5063     Parser.Lex(); // Eat right bracket token.
5064 
5065     // Don't worry about range checking the value here. That's handled by
5066     // the is*() predicates.
5067     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, CE, 0,
5068                                              ARM_AM::no_shift, 0, 0,
5069                                              false, S, E));
5070 
5071     // If there's a pre-indexing writeback marker, '!', just add it as a token
5072     // operand.
5073     if (Parser.getTok().is(AsmToken::Exclaim)) {
5074       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
5075       Parser.Lex(); // Eat the '!'.
5076     }
5077 
5078     return false;
5079   }
5080 
5081   // The register offset is optionally preceded by a '+' or '-'
5082   bool isNegative = false;
5083   if (Parser.getTok().is(AsmToken::Minus)) {
5084     isNegative = true;
5085     Parser.Lex(); // Eat the '-'.
5086   } else if (Parser.getTok().is(AsmToken::Plus)) {
5087     // Nothing to do.
5088     Parser.Lex(); // Eat the '+'.
5089   }
5090 
5091   E = Parser.getTok().getLoc();
5092   int OffsetRegNum = tryParseRegister();
5093   if (OffsetRegNum == -1)
5094     return Error(E, "register expected");
5095 
5096   // If there's a shift operator, handle it.
5097   ARM_AM::ShiftOpc ShiftType = ARM_AM::no_shift;
5098   unsigned ShiftImm = 0;
5099   if (Parser.getTok().is(AsmToken::Comma)) {
5100     Parser.Lex(); // Eat the ','.
5101     if (parseMemRegOffsetShift(ShiftType, ShiftImm))
5102       return true;
5103   }
5104 
5105   // Now we should have the closing ']'
5106   if (Parser.getTok().isNot(AsmToken::RBrac))
5107     return Error(Parser.getTok().getLoc(), "']' expected");
5108   E = Parser.getTok().getEndLoc();
5109   Parser.Lex(); // Eat right bracket token.
5110 
5111   Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, OffsetRegNum,
5112                                            ShiftType, ShiftImm, 0, isNegative,
5113                                            S, E));
5114 
5115   // If there's a pre-indexing writeback marker, '!', just add it as a token
5116   // operand.
5117   if (Parser.getTok().is(AsmToken::Exclaim)) {
5118     Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
5119     Parser.Lex(); // Eat the '!'.
5120   }
5121 
5122   return false;
5123 }
5124 
5125 /// parseMemRegOffsetShift - one of these two:
5126 ///   ( lsl | lsr | asr | ror ) , # shift_amount
5127 ///   rrx
5128 /// return true if it parses a shift otherwise it returns false.
5129 bool ARMAsmParser::parseMemRegOffsetShift(ARM_AM::ShiftOpc &St,
5130                                           unsigned &Amount) {
5131   MCAsmParser &Parser = getParser();
5132   SMLoc Loc = Parser.getTok().getLoc();
5133   const AsmToken &Tok = Parser.getTok();
5134   if (Tok.isNot(AsmToken::Identifier))
5135     return Error(Loc, "illegal shift operator");
5136   StringRef ShiftName = Tok.getString();
5137   if (ShiftName == "lsl" || ShiftName == "LSL" ||
5138       ShiftName == "asl" || ShiftName == "ASL")
5139     St = ARM_AM::lsl;
5140   else if (ShiftName == "lsr" || ShiftName == "LSR")
5141     St = ARM_AM::lsr;
5142   else if (ShiftName == "asr" || ShiftName == "ASR")
5143     St = ARM_AM::asr;
5144   else if (ShiftName == "ror" || ShiftName == "ROR")
5145     St = ARM_AM::ror;
5146   else if (ShiftName == "rrx" || ShiftName == "RRX")
5147     St = ARM_AM::rrx;
5148   else
5149     return Error(Loc, "illegal shift operator");
5150   Parser.Lex(); // Eat shift type token.
5151 
5152   // rrx stands alone.
5153   Amount = 0;
5154   if (St != ARM_AM::rrx) {
5155     Loc = Parser.getTok().getLoc();
5156     // A '#' and a shift amount.
5157     const AsmToken &HashTok = Parser.getTok();
5158     if (HashTok.isNot(AsmToken::Hash) &&
5159         HashTok.isNot(AsmToken::Dollar))
5160       return Error(HashTok.getLoc(), "'#' expected");
5161     Parser.Lex(); // Eat hash token.
5162 
5163     const MCExpr *Expr;
5164     if (getParser().parseExpression(Expr))
5165       return true;
5166     // Range check the immediate.
5167     // lsl, ror: 0 <= imm <= 31
5168     // lsr, asr: 0 <= imm <= 32
5169     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
5170     if (!CE)
5171       return Error(Loc, "shift amount must be an immediate");
5172     int64_t Imm = CE->getValue();
5173     if (Imm < 0 ||
5174         ((St == ARM_AM::lsl || St == ARM_AM::ror) && Imm > 31) ||
5175         ((St == ARM_AM::lsr || St == ARM_AM::asr) && Imm > 32))
5176       return Error(Loc, "immediate shift value out of range");
5177     // If <ShiftTy> #0, turn it into a no_shift.
5178     if (Imm == 0)
5179       St = ARM_AM::lsl;
5180     // For consistency, treat lsr #32 and asr #32 as having immediate value 0.
5181     if (Imm == 32)
5182       Imm = 0;
5183     Amount = Imm;
5184   }
5185 
5186   return false;
5187 }
5188 
5189 /// parseFPImm - A floating point immediate expression operand.
5190 OperandMatchResultTy
5191 ARMAsmParser::parseFPImm(OperandVector &Operands) {
5192   MCAsmParser &Parser = getParser();
5193   // Anything that can accept a floating point constant as an operand
5194   // needs to go through here, as the regular parseExpression is
5195   // integer only.
5196   //
5197   // This routine still creates a generic Immediate operand, containing
5198   // a bitcast of the 64-bit floating point value. The various operands
5199   // that accept floats can check whether the value is valid for them
5200   // via the standard is*() predicates.
5201 
5202   SMLoc S = Parser.getTok().getLoc();
5203 
5204   if (Parser.getTok().isNot(AsmToken::Hash) &&
5205       Parser.getTok().isNot(AsmToken::Dollar))
5206     return MatchOperand_NoMatch;
5207 
5208   // Disambiguate the VMOV forms that can accept an FP immediate.
5209   // vmov.f32 <sreg>, #imm
5210   // vmov.f64 <dreg>, #imm
5211   // vmov.f32 <dreg>, #imm  @ vector f32x2
5212   // vmov.f32 <qreg>, #imm  @ vector f32x4
5213   //
5214   // There are also the NEON VMOV instructions which expect an
5215   // integer constant. Make sure we don't try to parse an FPImm
5216   // for these:
5217   // vmov.i{8|16|32|64} <dreg|qreg>, #imm
5218   ARMOperand &TyOp = static_cast<ARMOperand &>(*Operands[2]);
5219   bool isVmovf = TyOp.isToken() &&
5220                  (TyOp.getToken() == ".f32" || TyOp.getToken() == ".f64" ||
5221                   TyOp.getToken() == ".f16");
5222   ARMOperand &Mnemonic = static_cast<ARMOperand &>(*Operands[0]);
5223   bool isFconst = Mnemonic.isToken() && (Mnemonic.getToken() == "fconstd" ||
5224                                          Mnemonic.getToken() == "fconsts");
5225   if (!(isVmovf || isFconst))
5226     return MatchOperand_NoMatch;
5227 
5228   Parser.Lex(); // Eat '#' or '$'.
5229 
5230   // Handle negation, as that still comes through as a separate token.
5231   bool isNegative = false;
5232   if (Parser.getTok().is(AsmToken::Minus)) {
5233     isNegative = true;
5234     Parser.Lex();
5235   }
5236   const AsmToken &Tok = Parser.getTok();
5237   SMLoc Loc = Tok.getLoc();
5238   if (Tok.is(AsmToken::Real) && isVmovf) {
5239     APFloat RealVal(APFloat::IEEEsingle(), Tok.getString());
5240     uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
5241     // If we had a '-' in front, toggle the sign bit.
5242     IntVal ^= (uint64_t)isNegative << 31;
5243     Parser.Lex(); // Eat the token.
5244     Operands.push_back(ARMOperand::CreateImm(
5245           MCConstantExpr::create(IntVal, getContext()),
5246           S, Parser.getTok().getLoc()));
5247     return MatchOperand_Success;
5248   }
5249   // Also handle plain integers. Instructions which allow floating point
5250   // immediates also allow a raw encoded 8-bit value.
5251   if (Tok.is(AsmToken::Integer) && isFconst) {
5252     int64_t Val = Tok.getIntVal();
5253     Parser.Lex(); // Eat the token.
5254     if (Val > 255 || Val < 0) {
5255       Error(Loc, "encoded floating point value out of range");
5256       return MatchOperand_ParseFail;
5257     }
5258     float RealVal = ARM_AM::getFPImmFloat(Val);
5259     Val = APFloat(RealVal).bitcastToAPInt().getZExtValue();
5260 
5261     Operands.push_back(ARMOperand::CreateImm(
5262         MCConstantExpr::create(Val, getContext()), S,
5263         Parser.getTok().getLoc()));
5264     return MatchOperand_Success;
5265   }
5266 
5267   Error(Loc, "invalid floating point immediate");
5268   return MatchOperand_ParseFail;
5269 }
5270 
5271 /// Parse a arm instruction operand.  For now this parses the operand regardless
5272 /// of the mnemonic.
5273 bool ARMAsmParser::parseOperand(OperandVector &Operands, StringRef Mnemonic) {
5274   MCAsmParser &Parser = getParser();
5275   SMLoc S, E;
5276 
5277   // Check if the current operand has a custom associated parser, if so, try to
5278   // custom parse the operand, or fallback to the general approach.
5279   OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
5280   if (ResTy == MatchOperand_Success)
5281     return false;
5282   // If there wasn't a custom match, try the generic matcher below. Otherwise,
5283   // there was a match, but an error occurred, in which case, just return that
5284   // the operand parsing failed.
5285   if (ResTy == MatchOperand_ParseFail)
5286     return true;
5287 
5288   switch (getLexer().getKind()) {
5289   default:
5290     Error(Parser.getTok().getLoc(), "unexpected token in operand");
5291     return true;
5292   case AsmToken::Identifier: {
5293     // If we've seen a branch mnemonic, the next operand must be a label.  This
5294     // is true even if the label is a register name.  So "br r1" means branch to
5295     // label "r1".
5296     bool ExpectLabel = Mnemonic == "b" || Mnemonic == "bl";
5297     if (!ExpectLabel) {
5298       if (!tryParseRegisterWithWriteBack(Operands))
5299         return false;
5300       int Res = tryParseShiftRegister(Operands);
5301       if (Res == 0) // success
5302         return false;
5303       else if (Res == -1) // irrecoverable error
5304         return true;
5305       // If this is VMRS, check for the apsr_nzcv operand.
5306       if (Mnemonic == "vmrs" &&
5307           Parser.getTok().getString().equals_lower("apsr_nzcv")) {
5308         S = Parser.getTok().getLoc();
5309         Parser.Lex();
5310         Operands.push_back(ARMOperand::CreateToken("APSR_nzcv", S));
5311         return false;
5312       }
5313     }
5314 
5315     // Fall though for the Identifier case that is not a register or a
5316     // special name.
5317     LLVM_FALLTHROUGH;
5318   }
5319   case AsmToken::LParen:  // parenthesized expressions like (_strcmp-4)
5320   case AsmToken::Integer: // things like 1f and 2b as a branch targets
5321   case AsmToken::String:  // quoted label names.
5322   case AsmToken::Dot: {   // . as a branch target
5323     // This was not a register so parse other operands that start with an
5324     // identifier (like labels) as expressions and create them as immediates.
5325     const MCExpr *IdVal;
5326     S = Parser.getTok().getLoc();
5327     if (getParser().parseExpression(IdVal))
5328       return true;
5329     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5330     Operands.push_back(ARMOperand::CreateImm(IdVal, S, E));
5331     return false;
5332   }
5333   case AsmToken::LBrac:
5334     return parseMemory(Operands);
5335   case AsmToken::LCurly:
5336     return parseRegisterList(Operands);
5337   case AsmToken::Dollar:
5338   case AsmToken::Hash:
5339     // #42 -> immediate.
5340     S = Parser.getTok().getLoc();
5341     Parser.Lex();
5342 
5343     if (Parser.getTok().isNot(AsmToken::Colon)) {
5344       bool isNegative = Parser.getTok().is(AsmToken::Minus);
5345       const MCExpr *ImmVal;
5346       if (getParser().parseExpression(ImmVal))
5347         return true;
5348       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ImmVal);
5349       if (CE) {
5350         int32_t Val = CE->getValue();
5351         if (isNegative && Val == 0)
5352           ImmVal = MCConstantExpr::create(std::numeric_limits<int32_t>::min(),
5353                                           getContext());
5354       }
5355       E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5356       Operands.push_back(ARMOperand::CreateImm(ImmVal, S, E));
5357 
5358       // There can be a trailing '!' on operands that we want as a separate
5359       // '!' Token operand. Handle that here. For example, the compatibility
5360       // alias for 'srsdb sp!, #imm' is 'srsdb #imm!'.
5361       if (Parser.getTok().is(AsmToken::Exclaim)) {
5362         Operands.push_back(ARMOperand::CreateToken(Parser.getTok().getString(),
5363                                                    Parser.getTok().getLoc()));
5364         Parser.Lex(); // Eat exclaim token
5365       }
5366       return false;
5367     }
5368     // w/ a ':' after the '#', it's just like a plain ':'.
5369     LLVM_FALLTHROUGH;
5370 
5371   case AsmToken::Colon: {
5372     S = Parser.getTok().getLoc();
5373     // ":lower16:" and ":upper16:" expression prefixes
5374     // FIXME: Check it's an expression prefix,
5375     // e.g. (FOO - :lower16:BAR) isn't legal.
5376     ARMMCExpr::VariantKind RefKind;
5377     if (parsePrefix(RefKind))
5378       return true;
5379 
5380     const MCExpr *SubExprVal;
5381     if (getParser().parseExpression(SubExprVal))
5382       return true;
5383 
5384     const MCExpr *ExprVal = ARMMCExpr::create(RefKind, SubExprVal,
5385                                               getContext());
5386     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5387     Operands.push_back(ARMOperand::CreateImm(ExprVal, S, E));
5388     return false;
5389   }
5390   case AsmToken::Equal: {
5391     S = Parser.getTok().getLoc();
5392     if (Mnemonic != "ldr") // only parse for ldr pseudo (e.g. ldr r0, =val)
5393       return Error(S, "unexpected token in operand");
5394     Parser.Lex(); // Eat '='
5395     const MCExpr *SubExprVal;
5396     if (getParser().parseExpression(SubExprVal))
5397       return true;
5398     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5399 
5400     // execute-only: we assume that assembly programmers know what they are
5401     // doing and allow literal pool creation here
5402     Operands.push_back(ARMOperand::CreateConstantPoolImm(SubExprVal, S, E));
5403     return false;
5404   }
5405   }
5406 }
5407 
5408 // parsePrefix - Parse ARM 16-bit relocations expression prefix, i.e.
5409 //  :lower16: and :upper16:.
5410 bool ARMAsmParser::parsePrefix(ARMMCExpr::VariantKind &RefKind) {
5411   MCAsmParser &Parser = getParser();
5412   RefKind = ARMMCExpr::VK_ARM_None;
5413 
5414   // consume an optional '#' (GNU compatibility)
5415   if (getLexer().is(AsmToken::Hash))
5416     Parser.Lex();
5417 
5418   // :lower16: and :upper16: modifiers
5419   assert(getLexer().is(AsmToken::Colon) && "expected a :");
5420   Parser.Lex(); // Eat ':'
5421 
5422   if (getLexer().isNot(AsmToken::Identifier)) {
5423     Error(Parser.getTok().getLoc(), "expected prefix identifier in operand");
5424     return true;
5425   }
5426 
5427   enum {
5428     COFF = (1 << MCObjectFileInfo::IsCOFF),
5429     ELF = (1 << MCObjectFileInfo::IsELF),
5430     MACHO = (1 << MCObjectFileInfo::IsMachO),
5431     WASM = (1 << MCObjectFileInfo::IsWasm),
5432   };
5433   static const struct PrefixEntry {
5434     const char *Spelling;
5435     ARMMCExpr::VariantKind VariantKind;
5436     uint8_t SupportedFormats;
5437   } PrefixEntries[] = {
5438     { "lower16", ARMMCExpr::VK_ARM_LO16, COFF | ELF | MACHO },
5439     { "upper16", ARMMCExpr::VK_ARM_HI16, COFF | ELF | MACHO },
5440   };
5441 
5442   StringRef IDVal = Parser.getTok().getIdentifier();
5443 
5444   const auto &Prefix =
5445       std::find_if(std::begin(PrefixEntries), std::end(PrefixEntries),
5446                    [&IDVal](const PrefixEntry &PE) {
5447                       return PE.Spelling == IDVal;
5448                    });
5449   if (Prefix == std::end(PrefixEntries)) {
5450     Error(Parser.getTok().getLoc(), "unexpected prefix in operand");
5451     return true;
5452   }
5453 
5454   uint8_t CurrentFormat;
5455   switch (getContext().getObjectFileInfo()->getObjectFileType()) {
5456   case MCObjectFileInfo::IsMachO:
5457     CurrentFormat = MACHO;
5458     break;
5459   case MCObjectFileInfo::IsELF:
5460     CurrentFormat = ELF;
5461     break;
5462   case MCObjectFileInfo::IsCOFF:
5463     CurrentFormat = COFF;
5464     break;
5465   case MCObjectFileInfo::IsWasm:
5466     CurrentFormat = WASM;
5467     break;
5468   }
5469 
5470   if (~Prefix->SupportedFormats & CurrentFormat) {
5471     Error(Parser.getTok().getLoc(),
5472           "cannot represent relocation in the current file format");
5473     return true;
5474   }
5475 
5476   RefKind = Prefix->VariantKind;
5477   Parser.Lex();
5478 
5479   if (getLexer().isNot(AsmToken::Colon)) {
5480     Error(Parser.getTok().getLoc(), "unexpected token after prefix");
5481     return true;
5482   }
5483   Parser.Lex(); // Eat the last ':'
5484 
5485   return false;
5486 }
5487 
5488 /// \brief Given a mnemonic, split out possible predication code and carry
5489 /// setting letters to form a canonical mnemonic and flags.
5490 //
5491 // FIXME: Would be nice to autogen this.
5492 // FIXME: This is a bit of a maze of special cases.
5493 StringRef ARMAsmParser::splitMnemonic(StringRef Mnemonic,
5494                                       unsigned &PredicationCode,
5495                                       bool &CarrySetting,
5496                                       unsigned &ProcessorIMod,
5497                                       StringRef &ITMask) {
5498   PredicationCode = ARMCC::AL;
5499   CarrySetting = false;
5500   ProcessorIMod = 0;
5501 
5502   // Ignore some mnemonics we know aren't predicated forms.
5503   //
5504   // FIXME: Would be nice to autogen this.
5505   if ((Mnemonic == "movs" && isThumb()) ||
5506       Mnemonic == "teq"   || Mnemonic == "vceq"   || Mnemonic == "svc"   ||
5507       Mnemonic == "mls"   || Mnemonic == "smmls"  || Mnemonic == "vcls"  ||
5508       Mnemonic == "vmls"  || Mnemonic == "vnmls"  || Mnemonic == "vacge" ||
5509       Mnemonic == "vcge"  || Mnemonic == "vclt"   || Mnemonic == "vacgt" ||
5510       Mnemonic == "vaclt" || Mnemonic == "vacle"  || Mnemonic == "hlt" ||
5511       Mnemonic == "vcgt"  || Mnemonic == "vcle"   || Mnemonic == "smlal" ||
5512       Mnemonic == "umaal" || Mnemonic == "umlal"  || Mnemonic == "vabal" ||
5513       Mnemonic == "vmlal" || Mnemonic == "vpadal" || Mnemonic == "vqdmlal" ||
5514       Mnemonic == "fmuls" || Mnemonic == "vmaxnm" || Mnemonic == "vminnm" ||
5515       Mnemonic == "vcvta" || Mnemonic == "vcvtn"  || Mnemonic == "vcvtp" ||
5516       Mnemonic == "vcvtm" || Mnemonic == "vrinta" || Mnemonic == "vrintn" ||
5517       Mnemonic == "vrintp" || Mnemonic == "vrintm" || Mnemonic == "hvc" ||
5518       Mnemonic.startswith("vsel") || Mnemonic == "vins" || Mnemonic == "vmovx" ||
5519       Mnemonic == "bxns"  || Mnemonic == "blxns" ||
5520       Mnemonic == "vudot" || Mnemonic == "vsdot" ||
5521       Mnemonic == "vcmla" || Mnemonic == "vcadd")
5522     return Mnemonic;
5523 
5524   // First, split out any predication code. Ignore mnemonics we know aren't
5525   // predicated but do have a carry-set and so weren't caught above.
5526   if (Mnemonic != "adcs" && Mnemonic != "bics" && Mnemonic != "movs" &&
5527       Mnemonic != "muls" && Mnemonic != "smlals" && Mnemonic != "smulls" &&
5528       Mnemonic != "umlals" && Mnemonic != "umulls" && Mnemonic != "lsls" &&
5529       Mnemonic != "sbcs" && Mnemonic != "rscs") {
5530     unsigned CC = ARMCondCodeFromString(Mnemonic.substr(Mnemonic.size()-2));
5531     if (CC != ~0U) {
5532       Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 2);
5533       PredicationCode = CC;
5534     }
5535   }
5536 
5537   // Next, determine if we have a carry setting bit. We explicitly ignore all
5538   // the instructions we know end in 's'.
5539   if (Mnemonic.endswith("s") &&
5540       !(Mnemonic == "cps" || Mnemonic == "mls" ||
5541         Mnemonic == "mrs" || Mnemonic == "smmls" || Mnemonic == "vabs" ||
5542         Mnemonic == "vcls" || Mnemonic == "vmls" || Mnemonic == "vmrs" ||
5543         Mnemonic == "vnmls" || Mnemonic == "vqabs" || Mnemonic == "vrecps" ||
5544         Mnemonic == "vrsqrts" || Mnemonic == "srs" || Mnemonic == "flds" ||
5545         Mnemonic == "fmrs" || Mnemonic == "fsqrts" || Mnemonic == "fsubs" ||
5546         Mnemonic == "fsts" || Mnemonic == "fcpys" || Mnemonic == "fdivs" ||
5547         Mnemonic == "fmuls" || Mnemonic == "fcmps" || Mnemonic == "fcmpzs" ||
5548         Mnemonic == "vfms" || Mnemonic == "vfnms" || Mnemonic == "fconsts" ||
5549         Mnemonic == "bxns" || Mnemonic == "blxns" ||
5550         (Mnemonic == "movs" && isThumb()))) {
5551     Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 1);
5552     CarrySetting = true;
5553   }
5554 
5555   // The "cps" instruction can have a interrupt mode operand which is glued into
5556   // the mnemonic. Check if this is the case, split it and parse the imod op
5557   if (Mnemonic.startswith("cps")) {
5558     // Split out any imod code.
5559     unsigned IMod =
5560       StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2, 2))
5561       .Case("ie", ARM_PROC::IE)
5562       .Case("id", ARM_PROC::ID)
5563       .Default(~0U);
5564     if (IMod != ~0U) {
5565       Mnemonic = Mnemonic.slice(0, Mnemonic.size()-2);
5566       ProcessorIMod = IMod;
5567     }
5568   }
5569 
5570   // The "it" instruction has the condition mask on the end of the mnemonic.
5571   if (Mnemonic.startswith("it")) {
5572     ITMask = Mnemonic.slice(2, Mnemonic.size());
5573     Mnemonic = Mnemonic.slice(0, 2);
5574   }
5575 
5576   return Mnemonic;
5577 }
5578 
5579 /// \brief Given a canonical mnemonic, determine if the instruction ever allows
5580 /// inclusion of carry set or predication code operands.
5581 //
5582 // FIXME: It would be nice to autogen this.
5583 void ARMAsmParser::getMnemonicAcceptInfo(StringRef Mnemonic, StringRef FullInst,
5584                                          bool &CanAcceptCarrySet,
5585                                          bool &CanAcceptPredicationCode) {
5586   CanAcceptCarrySet =
5587       Mnemonic == "and" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
5588       Mnemonic == "rrx" || Mnemonic == "ror" || Mnemonic == "sub" ||
5589       Mnemonic == "add" || Mnemonic == "adc" || Mnemonic == "mul" ||
5590       Mnemonic == "bic" || Mnemonic == "asr" || Mnemonic == "orr" ||
5591       Mnemonic == "mvn" || Mnemonic == "rsb" || Mnemonic == "rsc" ||
5592       Mnemonic == "orn" || Mnemonic == "sbc" || Mnemonic == "eor" ||
5593       Mnemonic == "neg" || Mnemonic == "vfm" || Mnemonic == "vfnm" ||
5594       (!isThumb() &&
5595        (Mnemonic == "smull" || Mnemonic == "mov" || Mnemonic == "mla" ||
5596         Mnemonic == "smlal" || Mnemonic == "umlal" || Mnemonic == "umull"));
5597 
5598   if (Mnemonic == "bkpt" || Mnemonic == "cbnz" || Mnemonic == "setend" ||
5599       Mnemonic == "cps" || Mnemonic == "it" || Mnemonic == "cbz" ||
5600       Mnemonic == "trap" || Mnemonic == "hlt" || Mnemonic == "udf" ||
5601       Mnemonic.startswith("crc32") || Mnemonic.startswith("cps") ||
5602       Mnemonic.startswith("vsel") || Mnemonic == "vmaxnm" ||
5603       Mnemonic == "vminnm" || Mnemonic == "vcvta" || Mnemonic == "vcvtn" ||
5604       Mnemonic == "vcvtp" || Mnemonic == "vcvtm" || Mnemonic == "vrinta" ||
5605       Mnemonic == "vrintn" || Mnemonic == "vrintp" || Mnemonic == "vrintm" ||
5606       Mnemonic.startswith("aes") || Mnemonic == "hvc" || Mnemonic == "setpan" ||
5607       Mnemonic.startswith("sha1") || Mnemonic.startswith("sha256") ||
5608       (FullInst.startswith("vmull") && FullInst.endswith(".p64")) ||
5609       Mnemonic == "vmovx" || Mnemonic == "vins" ||
5610       Mnemonic == "vudot" || Mnemonic == "vsdot" ||
5611       Mnemonic == "vcmla" || Mnemonic == "vcadd") {
5612     // These mnemonics are never predicable
5613     CanAcceptPredicationCode = false;
5614   } else if (!isThumb()) {
5615     // Some instructions are only predicable in Thumb mode
5616     CanAcceptPredicationCode =
5617         Mnemonic != "cdp2" && Mnemonic != "clrex" && Mnemonic != "mcr2" &&
5618         Mnemonic != "mcrr2" && Mnemonic != "mrc2" && Mnemonic != "mrrc2" &&
5619         Mnemonic != "dmb" && Mnemonic != "dfb" && Mnemonic != "dsb" &&
5620         Mnemonic != "isb" && Mnemonic != "pld" && Mnemonic != "pli" &&
5621         Mnemonic != "pldw" && Mnemonic != "ldc2" && Mnemonic != "ldc2l" &&
5622         Mnemonic != "stc2" && Mnemonic != "stc2l" &&
5623         !Mnemonic.startswith("rfe") && !Mnemonic.startswith("srs");
5624   } else if (isThumbOne()) {
5625     if (hasV6MOps())
5626       CanAcceptPredicationCode = Mnemonic != "movs";
5627     else
5628       CanAcceptPredicationCode = Mnemonic != "nop" && Mnemonic != "movs";
5629   } else
5630     CanAcceptPredicationCode = true;
5631 }
5632 
5633 // \brief Some Thumb instructions have two operand forms that are not
5634 // available as three operand, convert to two operand form if possible.
5635 //
5636 // FIXME: We would really like to be able to tablegen'erate this.
5637 void ARMAsmParser::tryConvertingToTwoOperandForm(StringRef Mnemonic,
5638                                                  bool CarrySetting,
5639                                                  OperandVector &Operands) {
5640   if (Operands.size() != 6)
5641     return;
5642 
5643   const auto &Op3 = static_cast<ARMOperand &>(*Operands[3]);
5644         auto &Op4 = static_cast<ARMOperand &>(*Operands[4]);
5645   if (!Op3.isReg() || !Op4.isReg())
5646     return;
5647 
5648   auto Op3Reg = Op3.getReg();
5649   auto Op4Reg = Op4.getReg();
5650 
5651   // For most Thumb2 cases we just generate the 3 operand form and reduce
5652   // it in processInstruction(), but the 3 operand form of ADD (t2ADDrr)
5653   // won't accept SP or PC so we do the transformation here taking care
5654   // with immediate range in the 'add sp, sp #imm' case.
5655   auto &Op5 = static_cast<ARMOperand &>(*Operands[5]);
5656   if (isThumbTwo()) {
5657     if (Mnemonic != "add")
5658       return;
5659     bool TryTransform = Op3Reg == ARM::PC || Op4Reg == ARM::PC ||
5660                         (Op5.isReg() && Op5.getReg() == ARM::PC);
5661     if (!TryTransform) {
5662       TryTransform = (Op3Reg == ARM::SP || Op4Reg == ARM::SP ||
5663                       (Op5.isReg() && Op5.getReg() == ARM::SP)) &&
5664                      !(Op3Reg == ARM::SP && Op4Reg == ARM::SP &&
5665                        Op5.isImm() && !Op5.isImm0_508s4());
5666     }
5667     if (!TryTransform)
5668       return;
5669   } else if (!isThumbOne())
5670     return;
5671 
5672   if (!(Mnemonic == "add" || Mnemonic == "sub" || Mnemonic == "and" ||
5673         Mnemonic == "eor" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
5674         Mnemonic == "asr" || Mnemonic == "adc" || Mnemonic == "sbc" ||
5675         Mnemonic == "ror" || Mnemonic == "orr" || Mnemonic == "bic"))
5676     return;
5677 
5678   // If first 2 operands of a 3 operand instruction are the same
5679   // then transform to 2 operand version of the same instruction
5680   // e.g. 'adds r0, r0, #1' transforms to 'adds r0, #1'
5681   bool Transform = Op3Reg == Op4Reg;
5682 
5683   // For communtative operations, we might be able to transform if we swap
5684   // Op4 and Op5.  The 'ADD Rdm, SP, Rdm' form is already handled specially
5685   // as tADDrsp.
5686   const ARMOperand *LastOp = &Op5;
5687   bool Swap = false;
5688   if (!Transform && Op5.isReg() && Op3Reg == Op5.getReg() &&
5689       ((Mnemonic == "add" && Op4Reg != ARM::SP) ||
5690        Mnemonic == "and" || Mnemonic == "eor" ||
5691        Mnemonic == "adc" || Mnemonic == "orr")) {
5692     Swap = true;
5693     LastOp = &Op4;
5694     Transform = true;
5695   }
5696 
5697   // If both registers are the same then remove one of them from
5698   // the operand list, with certain exceptions.
5699   if (Transform) {
5700     // Don't transform 'adds Rd, Rd, Rm' or 'sub{s} Rd, Rd, Rm' because the
5701     // 2 operand forms don't exist.
5702     if (((Mnemonic == "add" && CarrySetting) || Mnemonic == "sub") &&
5703         LastOp->isReg())
5704       Transform = false;
5705 
5706     // Don't transform 'add/sub{s} Rd, Rd, #imm' if the immediate fits into
5707     // 3-bits because the ARMARM says not to.
5708     if ((Mnemonic == "add" || Mnemonic == "sub") && LastOp->isImm0_7())
5709       Transform = false;
5710   }
5711 
5712   if (Transform) {
5713     if (Swap)
5714       std::swap(Op4, Op5);
5715     Operands.erase(Operands.begin() + 3);
5716   }
5717 }
5718 
5719 bool ARMAsmParser::shouldOmitCCOutOperand(StringRef Mnemonic,
5720                                           OperandVector &Operands) {
5721   // FIXME: This is all horribly hacky. We really need a better way to deal
5722   // with optional operands like this in the matcher table.
5723 
5724   // The 'mov' mnemonic is special. One variant has a cc_out operand, while
5725   // another does not. Specifically, the MOVW instruction does not. So we
5726   // special case it here and remove the defaulted (non-setting) cc_out
5727   // operand if that's the instruction we're trying to match.
5728   //
5729   // We do this as post-processing of the explicit operands rather than just
5730   // conditionally adding the cc_out in the first place because we need
5731   // to check the type of the parsed immediate operand.
5732   if (Mnemonic == "mov" && Operands.size() > 4 && !isThumb() &&
5733       !static_cast<ARMOperand &>(*Operands[4]).isModImm() &&
5734       static_cast<ARMOperand &>(*Operands[4]).isImm0_65535Expr() &&
5735       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0)
5736     return true;
5737 
5738   // Register-register 'add' for thumb does not have a cc_out operand
5739   // when there are only two register operands.
5740   if (isThumb() && Mnemonic == "add" && Operands.size() == 5 &&
5741       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5742       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5743       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0)
5744     return true;
5745   // Register-register 'add' for thumb does not have a cc_out operand
5746   // when it's an ADD Rdm, SP, {Rdm|#imm0_255} instruction. We do
5747   // have to check the immediate range here since Thumb2 has a variant
5748   // that can handle a different range and has a cc_out operand.
5749   if (((isThumb() && Mnemonic == "add") ||
5750        (isThumbTwo() && Mnemonic == "sub")) &&
5751       Operands.size() == 6 && static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5752       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5753       static_cast<ARMOperand &>(*Operands[4]).getReg() == ARM::SP &&
5754       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5755       ((Mnemonic == "add" && static_cast<ARMOperand &>(*Operands[5]).isReg()) ||
5756        static_cast<ARMOperand &>(*Operands[5]).isImm0_1020s4()))
5757     return true;
5758   // For Thumb2, add/sub immediate does not have a cc_out operand for the
5759   // imm0_4095 variant. That's the least-preferred variant when
5760   // selecting via the generic "add" mnemonic, so to know that we
5761   // should remove the cc_out operand, we have to explicitly check that
5762   // it's not one of the other variants. Ugh.
5763   if (isThumbTwo() && (Mnemonic == "add" || Mnemonic == "sub") &&
5764       Operands.size() == 6 && static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5765       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5766       static_cast<ARMOperand &>(*Operands[5]).isImm()) {
5767     // Nest conditions rather than one big 'if' statement for readability.
5768     //
5769     // If both registers are low, we're in an IT block, and the immediate is
5770     // in range, we should use encoding T1 instead, which has a cc_out.
5771     if (inITBlock() &&
5772         isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) &&
5773         isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) &&
5774         static_cast<ARMOperand &>(*Operands[5]).isImm0_7())
5775       return false;
5776     // Check against T3. If the second register is the PC, this is an
5777     // alternate form of ADR, which uses encoding T4, so check for that too.
5778     if (static_cast<ARMOperand &>(*Operands[4]).getReg() != ARM::PC &&
5779         static_cast<ARMOperand &>(*Operands[5]).isT2SOImm())
5780       return false;
5781 
5782     // Otherwise, we use encoding T4, which does not have a cc_out
5783     // operand.
5784     return true;
5785   }
5786 
5787   // The thumb2 multiply instruction doesn't have a CCOut register, so
5788   // if we have a "mul" mnemonic in Thumb mode, check if we'll be able to
5789   // use the 16-bit encoding or not.
5790   if (isThumbTwo() && Mnemonic == "mul" && Operands.size() == 6 &&
5791       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5792       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5793       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5794       static_cast<ARMOperand &>(*Operands[5]).isReg() &&
5795       // If the registers aren't low regs, the destination reg isn't the
5796       // same as one of the source regs, or the cc_out operand is zero
5797       // outside of an IT block, we have to use the 32-bit encoding, so
5798       // remove the cc_out operand.
5799       (!isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) ||
5800        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) ||
5801        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[5]).getReg()) ||
5802        !inITBlock() || (static_cast<ARMOperand &>(*Operands[3]).getReg() !=
5803                             static_cast<ARMOperand &>(*Operands[5]).getReg() &&
5804                         static_cast<ARMOperand &>(*Operands[3]).getReg() !=
5805                             static_cast<ARMOperand &>(*Operands[4]).getReg())))
5806     return true;
5807 
5808   // Also check the 'mul' syntax variant that doesn't specify an explicit
5809   // destination register.
5810   if (isThumbTwo() && Mnemonic == "mul" && Operands.size() == 5 &&
5811       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5812       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5813       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5814       // If the registers aren't low regs  or the cc_out operand is zero
5815       // outside of an IT block, we have to use the 32-bit encoding, so
5816       // remove the cc_out operand.
5817       (!isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) ||
5818        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) ||
5819        !inITBlock()))
5820     return true;
5821 
5822   // Register-register 'add/sub' for thumb does not have a cc_out operand
5823   // when it's an ADD/SUB SP, #imm. Be lenient on count since there's also
5824   // the "add/sub SP, SP, #imm" version. If the follow-up operands aren't
5825   // right, this will result in better diagnostics (which operand is off)
5826   // anyway.
5827   if (isThumb() && (Mnemonic == "add" || Mnemonic == "sub") &&
5828       (Operands.size() == 5 || Operands.size() == 6) &&
5829       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5830       static_cast<ARMOperand &>(*Operands[3]).getReg() == ARM::SP &&
5831       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5832       (static_cast<ARMOperand &>(*Operands[4]).isImm() ||
5833        (Operands.size() == 6 &&
5834         static_cast<ARMOperand &>(*Operands[5]).isImm())))
5835     return true;
5836 
5837   return false;
5838 }
5839 
5840 bool ARMAsmParser::shouldOmitPredicateOperand(StringRef Mnemonic,
5841                                               OperandVector &Operands) {
5842   // VRINT{Z, X} have a predicate operand in VFP, but not in NEON
5843   unsigned RegIdx = 3;
5844   if ((Mnemonic == "vrintz" || Mnemonic == "vrintx") &&
5845       (static_cast<ARMOperand &>(*Operands[2]).getToken() == ".f32" ||
5846        static_cast<ARMOperand &>(*Operands[2]).getToken() == ".f16")) {
5847     if (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
5848         (static_cast<ARMOperand &>(*Operands[3]).getToken() == ".f32" ||
5849          static_cast<ARMOperand &>(*Operands[3]).getToken() == ".f16"))
5850       RegIdx = 4;
5851 
5852     if (static_cast<ARMOperand &>(*Operands[RegIdx]).isReg() &&
5853         (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(
5854              static_cast<ARMOperand &>(*Operands[RegIdx]).getReg()) ||
5855          ARMMCRegisterClasses[ARM::QPRRegClassID].contains(
5856              static_cast<ARMOperand &>(*Operands[RegIdx]).getReg())))
5857       return true;
5858   }
5859   return false;
5860 }
5861 
5862 static bool isDataTypeToken(StringRef Tok) {
5863   return Tok == ".8" || Tok == ".16" || Tok == ".32" || Tok == ".64" ||
5864     Tok == ".i8" || Tok == ".i16" || Tok == ".i32" || Tok == ".i64" ||
5865     Tok == ".u8" || Tok == ".u16" || Tok == ".u32" || Tok == ".u64" ||
5866     Tok == ".s8" || Tok == ".s16" || Tok == ".s32" || Tok == ".s64" ||
5867     Tok == ".p8" || Tok == ".p16" || Tok == ".f32" || Tok == ".f64" ||
5868     Tok == ".f" || Tok == ".d";
5869 }
5870 
5871 // FIXME: This bit should probably be handled via an explicit match class
5872 // in the .td files that matches the suffix instead of having it be
5873 // a literal string token the way it is now.
5874 static bool doesIgnoreDataTypeSuffix(StringRef Mnemonic, StringRef DT) {
5875   return Mnemonic.startswith("vldm") || Mnemonic.startswith("vstm");
5876 }
5877 
5878 static void applyMnemonicAliases(StringRef &Mnemonic, uint64_t Features,
5879                                  unsigned VariantID);
5880 
5881 // The GNU assembler has aliases of ldrd and strd with the second register
5882 // omitted. We don't have a way to do that in tablegen, so fix it up here.
5883 //
5884 // We have to be careful to not emit an invalid Rt2 here, because the rest of
5885 // the assmebly parser could then generate confusing diagnostics refering to
5886 // it. If we do find anything that prevents us from doing the transformation we
5887 // bail out, and let the assembly parser report an error on the instruction as
5888 // it is written.
5889 void ARMAsmParser::fixupGNULDRDAlias(StringRef Mnemonic,
5890                                      OperandVector &Operands) {
5891   if (Mnemonic != "ldrd" && Mnemonic != "strd")
5892     return;
5893   if (Operands.size() < 4)
5894     return;
5895 
5896   ARMOperand &Op2 = static_cast<ARMOperand &>(*Operands[2]);
5897   ARMOperand &Op3 = static_cast<ARMOperand &>(*Operands[3]);
5898 
5899   if (!Op2.isReg())
5900     return;
5901   if (!Op3.isMem())
5902     return;
5903 
5904   const MCRegisterClass &GPR = MRI->getRegClass(ARM::GPRRegClassID);
5905   if (!GPR.contains(Op2.getReg()))
5906     return;
5907 
5908   unsigned RtEncoding = MRI->getEncodingValue(Op2.getReg());
5909   if (!isThumb() && (RtEncoding & 1)) {
5910     // In ARM mode, the registers must be from an aligned pair, this
5911     // restriction does not apply in Thumb mode.
5912     return;
5913   }
5914   if (Op2.getReg() == ARM::PC)
5915     return;
5916   unsigned PairedReg = GPR.getRegister(RtEncoding + 1);
5917   if (!PairedReg || PairedReg == ARM::PC ||
5918       (PairedReg == ARM::SP && !hasV8Ops()))
5919     return;
5920 
5921   Operands.insert(
5922       Operands.begin() + 3,
5923       ARMOperand::CreateReg(PairedReg, Op2.getStartLoc(), Op2.getEndLoc()));
5924 }
5925 
5926 /// Parse an arm instruction mnemonic followed by its operands.
5927 bool ARMAsmParser::ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
5928                                     SMLoc NameLoc, OperandVector &Operands) {
5929   MCAsmParser &Parser = getParser();
5930 
5931   // Apply mnemonic aliases before doing anything else, as the destination
5932   // mnemonic may include suffices and we want to handle them normally.
5933   // The generic tblgen'erated code does this later, at the start of
5934   // MatchInstructionImpl(), but that's too late for aliases that include
5935   // any sort of suffix.
5936   uint64_t AvailableFeatures = getAvailableFeatures();
5937   unsigned AssemblerDialect = getParser().getAssemblerDialect();
5938   applyMnemonicAliases(Name, AvailableFeatures, AssemblerDialect);
5939 
5940   // First check for the ARM-specific .req directive.
5941   if (Parser.getTok().is(AsmToken::Identifier) &&
5942       Parser.getTok().getIdentifier() == ".req") {
5943     parseDirectiveReq(Name, NameLoc);
5944     // We always return 'error' for this, as we're done with this
5945     // statement and don't need to match the 'instruction."
5946     return true;
5947   }
5948 
5949   // Create the leading tokens for the mnemonic, split by '.' characters.
5950   size_t Start = 0, Next = Name.find('.');
5951   StringRef Mnemonic = Name.slice(Start, Next);
5952 
5953   // Split out the predication code and carry setting flag from the mnemonic.
5954   unsigned PredicationCode;
5955   unsigned ProcessorIMod;
5956   bool CarrySetting;
5957   StringRef ITMask;
5958   Mnemonic = splitMnemonic(Mnemonic, PredicationCode, CarrySetting,
5959                            ProcessorIMod, ITMask);
5960 
5961   // In Thumb1, only the branch (B) instruction can be predicated.
5962   if (isThumbOne() && PredicationCode != ARMCC::AL && Mnemonic != "b") {
5963     return Error(NameLoc, "conditional execution not supported in Thumb1");
5964   }
5965 
5966   Operands.push_back(ARMOperand::CreateToken(Mnemonic, NameLoc));
5967 
5968   // Handle the IT instruction ITMask. Convert it to a bitmask. This
5969   // is the mask as it will be for the IT encoding if the conditional
5970   // encoding has a '1' as it's bit0 (i.e. 't' ==> '1'). In the case
5971   // where the conditional bit0 is zero, the instruction post-processing
5972   // will adjust the mask accordingly.
5973   if (Mnemonic == "it") {
5974     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + 2);
5975     if (ITMask.size() > 3) {
5976       return Error(Loc, "too many conditions on IT instruction");
5977     }
5978     unsigned Mask = 8;
5979     for (unsigned i = ITMask.size(); i != 0; --i) {
5980       char pos = ITMask[i - 1];
5981       if (pos != 't' && pos != 'e') {
5982         return Error(Loc, "illegal IT block condition mask '" + ITMask + "'");
5983       }
5984       Mask >>= 1;
5985       if (ITMask[i - 1] == 't')
5986         Mask |= 8;
5987     }
5988     Operands.push_back(ARMOperand::CreateITMask(Mask, Loc));
5989   }
5990 
5991   // FIXME: This is all a pretty gross hack. We should automatically handle
5992   // optional operands like this via tblgen.
5993 
5994   // Next, add the CCOut and ConditionCode operands, if needed.
5995   //
5996   // For mnemonics which can ever incorporate a carry setting bit or predication
5997   // code, our matching model involves us always generating CCOut and
5998   // ConditionCode operands to match the mnemonic "as written" and then we let
5999   // the matcher deal with finding the right instruction or generating an
6000   // appropriate error.
6001   bool CanAcceptCarrySet, CanAcceptPredicationCode;
6002   getMnemonicAcceptInfo(Mnemonic, Name, CanAcceptCarrySet, CanAcceptPredicationCode);
6003 
6004   // If we had a carry-set on an instruction that can't do that, issue an
6005   // error.
6006   if (!CanAcceptCarrySet && CarrySetting) {
6007     return Error(NameLoc, "instruction '" + Mnemonic +
6008                  "' can not set flags, but 's' suffix specified");
6009   }
6010   // If we had a predication code on an instruction that can't do that, issue an
6011   // error.
6012   if (!CanAcceptPredicationCode && PredicationCode != ARMCC::AL) {
6013     return Error(NameLoc, "instruction '" + Mnemonic +
6014                  "' is not predicable, but condition code specified");
6015   }
6016 
6017   // Add the carry setting operand, if necessary.
6018   if (CanAcceptCarrySet) {
6019     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size());
6020     Operands.push_back(ARMOperand::CreateCCOut(CarrySetting ? ARM::CPSR : 0,
6021                                                Loc));
6022   }
6023 
6024   // Add the predication code operand, if necessary.
6025   if (CanAcceptPredicationCode) {
6026     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size() +
6027                                       CarrySetting);
6028     Operands.push_back(ARMOperand::CreateCondCode(
6029                          ARMCC::CondCodes(PredicationCode), Loc));
6030   }
6031 
6032   // Add the processor imod operand, if necessary.
6033   if (ProcessorIMod) {
6034     Operands.push_back(ARMOperand::CreateImm(
6035           MCConstantExpr::create(ProcessorIMod, getContext()),
6036                                  NameLoc, NameLoc));
6037   } else if (Mnemonic == "cps" && isMClass()) {
6038     return Error(NameLoc, "instruction 'cps' requires effect for M-class");
6039   }
6040 
6041   // Add the remaining tokens in the mnemonic.
6042   while (Next != StringRef::npos) {
6043     Start = Next;
6044     Next = Name.find('.', Start + 1);
6045     StringRef ExtraToken = Name.slice(Start, Next);
6046 
6047     // Some NEON instructions have an optional datatype suffix that is
6048     // completely ignored. Check for that.
6049     if (isDataTypeToken(ExtraToken) &&
6050         doesIgnoreDataTypeSuffix(Mnemonic, ExtraToken))
6051       continue;
6052 
6053     // For for ARM mode generate an error if the .n qualifier is used.
6054     if (ExtraToken == ".n" && !isThumb()) {
6055       SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Start);
6056       return Error(Loc, "instruction with .n (narrow) qualifier not allowed in "
6057                    "arm mode");
6058     }
6059 
6060     // The .n qualifier is always discarded as that is what the tables
6061     // and matcher expect.  In ARM mode the .w qualifier has no effect,
6062     // so discard it to avoid errors that can be caused by the matcher.
6063     if (ExtraToken != ".n" && (isThumb() || ExtraToken != ".w")) {
6064       SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Start);
6065       Operands.push_back(ARMOperand::CreateToken(ExtraToken, Loc));
6066     }
6067   }
6068 
6069   // Read the remaining operands.
6070   if (getLexer().isNot(AsmToken::EndOfStatement)) {
6071     // Read the first operand.
6072     if (parseOperand(Operands, Mnemonic)) {
6073       return true;
6074     }
6075 
6076     while (parseOptionalToken(AsmToken::Comma)) {
6077       // Parse and remember the operand.
6078       if (parseOperand(Operands, Mnemonic)) {
6079         return true;
6080       }
6081     }
6082   }
6083 
6084   if (parseToken(AsmToken::EndOfStatement, "unexpected token in argument list"))
6085     return true;
6086 
6087   tryConvertingToTwoOperandForm(Mnemonic, CarrySetting, Operands);
6088 
6089   // Some instructions, mostly Thumb, have forms for the same mnemonic that
6090   // do and don't have a cc_out optional-def operand. With some spot-checks
6091   // of the operand list, we can figure out which variant we're trying to
6092   // parse and adjust accordingly before actually matching. We shouldn't ever
6093   // try to remove a cc_out operand that was explicitly set on the
6094   // mnemonic, of course (CarrySetting == true). Reason number #317 the
6095   // table driven matcher doesn't fit well with the ARM instruction set.
6096   if (!CarrySetting && shouldOmitCCOutOperand(Mnemonic, Operands))
6097     Operands.erase(Operands.begin() + 1);
6098 
6099   // Some instructions have the same mnemonic, but don't always
6100   // have a predicate. Distinguish them here and delete the
6101   // predicate if needed.
6102   if (PredicationCode == ARMCC::AL &&
6103       shouldOmitPredicateOperand(Mnemonic, Operands))
6104     Operands.erase(Operands.begin() + 1);
6105 
6106   // ARM mode 'blx' need special handling, as the register operand version
6107   // is predicable, but the label operand version is not. So, we can't rely
6108   // on the Mnemonic based checking to correctly figure out when to put
6109   // a k_CondCode operand in the list. If we're trying to match the label
6110   // version, remove the k_CondCode operand here.
6111   if (!isThumb() && Mnemonic == "blx" && Operands.size() == 3 &&
6112       static_cast<ARMOperand &>(*Operands[2]).isImm())
6113     Operands.erase(Operands.begin() + 1);
6114 
6115   // Adjust operands of ldrexd/strexd to MCK_GPRPair.
6116   // ldrexd/strexd require even/odd GPR pair. To enforce this constraint,
6117   // a single GPRPair reg operand is used in the .td file to replace the two
6118   // GPRs. However, when parsing from asm, the two GRPs cannot be automatically
6119   // expressed as a GPRPair, so we have to manually merge them.
6120   // FIXME: We would really like to be able to tablegen'erate this.
6121   if (!isThumb() && Operands.size() > 4 &&
6122       (Mnemonic == "ldrexd" || Mnemonic == "strexd" || Mnemonic == "ldaexd" ||
6123        Mnemonic == "stlexd")) {
6124     bool isLoad = (Mnemonic == "ldrexd" || Mnemonic == "ldaexd");
6125     unsigned Idx = isLoad ? 2 : 3;
6126     ARMOperand &Op1 = static_cast<ARMOperand &>(*Operands[Idx]);
6127     ARMOperand &Op2 = static_cast<ARMOperand &>(*Operands[Idx + 1]);
6128 
6129     const MCRegisterClass& MRC = MRI->getRegClass(ARM::GPRRegClassID);
6130     // Adjust only if Op1 and Op2 are GPRs.
6131     if (Op1.isReg() && Op2.isReg() && MRC.contains(Op1.getReg()) &&
6132         MRC.contains(Op2.getReg())) {
6133       unsigned Reg1 = Op1.getReg();
6134       unsigned Reg2 = Op2.getReg();
6135       unsigned Rt = MRI->getEncodingValue(Reg1);
6136       unsigned Rt2 = MRI->getEncodingValue(Reg2);
6137 
6138       // Rt2 must be Rt + 1 and Rt must be even.
6139       if (Rt + 1 != Rt2 || (Rt & 1)) {
6140         return Error(Op2.getStartLoc(),
6141                      isLoad ? "destination operands must be sequential"
6142                             : "source operands must be sequential");
6143       }
6144       unsigned NewReg = MRI->getMatchingSuperReg(Reg1, ARM::gsub_0,
6145           &(MRI->getRegClass(ARM::GPRPairRegClassID)));
6146       Operands[Idx] =
6147           ARMOperand::CreateReg(NewReg, Op1.getStartLoc(), Op2.getEndLoc());
6148       Operands.erase(Operands.begin() + Idx + 1);
6149     }
6150   }
6151 
6152   // GNU Assembler extension (compatibility).
6153   fixupGNULDRDAlias(Mnemonic, Operands);
6154 
6155   // FIXME: As said above, this is all a pretty gross hack.  This instruction
6156   // does not fit with other "subs" and tblgen.
6157   // Adjust operands of B9.3.19 SUBS PC, LR, #imm (Thumb2) system instruction
6158   // so the Mnemonic is the original name "subs" and delete the predicate
6159   // operand so it will match the table entry.
6160   if (isThumbTwo() && Mnemonic == "sub" && Operands.size() == 6 &&
6161       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6162       static_cast<ARMOperand &>(*Operands[3]).getReg() == ARM::PC &&
6163       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
6164       static_cast<ARMOperand &>(*Operands[4]).getReg() == ARM::LR &&
6165       static_cast<ARMOperand &>(*Operands[5]).isImm()) {
6166     Operands.front() = ARMOperand::CreateToken(Name, NameLoc);
6167     Operands.erase(Operands.begin() + 1);
6168   }
6169   return false;
6170 }
6171 
6172 // Validate context-sensitive operand constraints.
6173 
6174 // return 'true' if register list contains non-low GPR registers,
6175 // 'false' otherwise. If Reg is in the register list or is HiReg, set
6176 // 'containsReg' to true.
6177 static bool checkLowRegisterList(const MCInst &Inst, unsigned OpNo,
6178                                  unsigned Reg, unsigned HiReg,
6179                                  bool &containsReg) {
6180   containsReg = false;
6181   for (unsigned i = OpNo; i < Inst.getNumOperands(); ++i) {
6182     unsigned OpReg = Inst.getOperand(i).getReg();
6183     if (OpReg == Reg)
6184       containsReg = true;
6185     // Anything other than a low register isn't legal here.
6186     if (!isARMLowRegister(OpReg) && (!HiReg || OpReg != HiReg))
6187       return true;
6188   }
6189   return false;
6190 }
6191 
6192 // Check if the specified regisgter is in the register list of the inst,
6193 // starting at the indicated operand number.
6194 static bool listContainsReg(const MCInst &Inst, unsigned OpNo, unsigned Reg) {
6195   for (unsigned i = OpNo, e = Inst.getNumOperands(); i < e; ++i) {
6196     unsigned OpReg = Inst.getOperand(i).getReg();
6197     if (OpReg == Reg)
6198       return true;
6199   }
6200   return false;
6201 }
6202 
6203 // Return true if instruction has the interesting property of being
6204 // allowed in IT blocks, but not being predicable.
6205 static bool instIsBreakpoint(const MCInst &Inst) {
6206     return Inst.getOpcode() == ARM::tBKPT ||
6207            Inst.getOpcode() == ARM::BKPT ||
6208            Inst.getOpcode() == ARM::tHLT ||
6209            Inst.getOpcode() == ARM::HLT;
6210 }
6211 
6212 bool ARMAsmParser::validatetLDMRegList(const MCInst &Inst,
6213                                        const OperandVector &Operands,
6214                                        unsigned ListNo, bool IsARPop) {
6215   const ARMOperand &Op = static_cast<const ARMOperand &>(*Operands[ListNo]);
6216   bool HasWritebackToken = Op.isToken() && Op.getToken() == "!";
6217 
6218   bool ListContainsSP = listContainsReg(Inst, ListNo, ARM::SP);
6219   bool ListContainsLR = listContainsReg(Inst, ListNo, ARM::LR);
6220   bool ListContainsPC = listContainsReg(Inst, ListNo, ARM::PC);
6221 
6222   if (!IsARPop && ListContainsSP)
6223     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6224                  "SP may not be in the register list");
6225   else if (ListContainsPC && ListContainsLR)
6226     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6227                  "PC and LR may not be in the register list simultaneously");
6228   return false;
6229 }
6230 
6231 bool ARMAsmParser::validatetSTMRegList(const MCInst &Inst,
6232                                        const OperandVector &Operands,
6233                                        unsigned ListNo) {
6234   const ARMOperand &Op = static_cast<const ARMOperand &>(*Operands[ListNo]);
6235   bool HasWritebackToken = Op.isToken() && Op.getToken() == "!";
6236 
6237   bool ListContainsSP = listContainsReg(Inst, ListNo, ARM::SP);
6238   bool ListContainsPC = listContainsReg(Inst, ListNo, ARM::PC);
6239 
6240   if (ListContainsSP && ListContainsPC)
6241     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6242                  "SP and PC may not be in the register list");
6243   else if (ListContainsSP)
6244     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6245                  "SP may not be in the register list");
6246   else if (ListContainsPC)
6247     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6248                  "PC may not be in the register list");
6249   return false;
6250 }
6251 
6252 // FIXME: We would really like to be able to tablegen'erate this.
6253 bool ARMAsmParser::validateInstruction(MCInst &Inst,
6254                                        const OperandVector &Operands) {
6255   const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
6256   SMLoc Loc = Operands[0]->getStartLoc();
6257 
6258   // Check the IT block state first.
6259   // NOTE: BKPT and HLT instructions have the interesting property of being
6260   // allowed in IT blocks, but not being predicable. They just always execute.
6261   if (inITBlock() && !instIsBreakpoint(Inst)) {
6262     // The instruction must be predicable.
6263     if (!MCID.isPredicable())
6264       return Error(Loc, "instructions in IT block must be predicable");
6265     ARMCC::CondCodes Cond = ARMCC::CondCodes(
6266         Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm());
6267     if (Cond != currentITCond()) {
6268       // Find the condition code Operand to get its SMLoc information.
6269       SMLoc CondLoc;
6270       for (unsigned I = 1; I < Operands.size(); ++I)
6271         if (static_cast<ARMOperand &>(*Operands[I]).isCondCode())
6272           CondLoc = Operands[I]->getStartLoc();
6273       return Error(CondLoc, "incorrect condition in IT block; got '" +
6274                                 StringRef(ARMCondCodeToString(Cond)) +
6275                                 "', but expected '" +
6276                                 ARMCondCodeToString(currentITCond()) + "'");
6277     }
6278   // Check for non-'al' condition codes outside of the IT block.
6279   } else if (isThumbTwo() && MCID.isPredicable() &&
6280              Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm() !=
6281              ARMCC::AL && Inst.getOpcode() != ARM::tBcc &&
6282              Inst.getOpcode() != ARM::t2Bcc) {
6283     return Error(Loc, "predicated instructions must be in IT block");
6284   } else if (!isThumb() && !useImplicitITARM() && MCID.isPredicable() &&
6285              Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm() !=
6286                  ARMCC::AL) {
6287     return Warning(Loc, "predicated instructions should be in IT block");
6288   }
6289 
6290   // PC-setting instructions in an IT block, but not the last instruction of
6291   // the block, are UNPREDICTABLE.
6292   if (inExplicitITBlock() && !lastInITBlock() && isITBlockTerminator(Inst)) {
6293     return Error(Loc, "instruction must be outside of IT block or the last instruction in an IT block");
6294   }
6295 
6296   const unsigned Opcode = Inst.getOpcode();
6297   switch (Opcode) {
6298   case ARM::LDRD:
6299   case ARM::LDRD_PRE:
6300   case ARM::LDRD_POST: {
6301     const unsigned RtReg = Inst.getOperand(0).getReg();
6302 
6303     // Rt can't be R14.
6304     if (RtReg == ARM::LR)
6305       return Error(Operands[3]->getStartLoc(),
6306                    "Rt can't be R14");
6307 
6308     const unsigned Rt = MRI->getEncodingValue(RtReg);
6309     // Rt must be even-numbered.
6310     if ((Rt & 1) == 1)
6311       return Error(Operands[3]->getStartLoc(),
6312                    "Rt must be even-numbered");
6313 
6314     // Rt2 must be Rt + 1.
6315     const unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6316     if (Rt2 != Rt + 1)
6317       return Error(Operands[3]->getStartLoc(),
6318                    "destination operands must be sequential");
6319 
6320     if (Opcode == ARM::LDRD_PRE || Opcode == ARM::LDRD_POST) {
6321       const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(3).getReg());
6322       // For addressing modes with writeback, the base register needs to be
6323       // different from the destination registers.
6324       if (Rn == Rt || Rn == Rt2)
6325         return Error(Operands[3]->getStartLoc(),
6326                      "base register needs to be different from destination "
6327                      "registers");
6328     }
6329 
6330     return false;
6331   }
6332   case ARM::t2LDRDi8:
6333   case ARM::t2LDRD_PRE:
6334   case ARM::t2LDRD_POST: {
6335     // Rt2 must be different from Rt.
6336     unsigned Rt = MRI->getEncodingValue(Inst.getOperand(0).getReg());
6337     unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6338     if (Rt2 == Rt)
6339       return Error(Operands[3]->getStartLoc(),
6340                    "destination operands can't be identical");
6341     return false;
6342   }
6343   case ARM::t2BXJ: {
6344     const unsigned RmReg = Inst.getOperand(0).getReg();
6345     // Rm = SP is no longer unpredictable in v8-A
6346     if (RmReg == ARM::SP && !hasV8Ops())
6347       return Error(Operands[2]->getStartLoc(),
6348                    "r13 (SP) is an unpredictable operand to BXJ");
6349     return false;
6350   }
6351   case ARM::STRD: {
6352     // Rt2 must be Rt + 1.
6353     unsigned Rt = MRI->getEncodingValue(Inst.getOperand(0).getReg());
6354     unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6355     if (Rt2 != Rt + 1)
6356       return Error(Operands[3]->getStartLoc(),
6357                    "source operands must be sequential");
6358     return false;
6359   }
6360   case ARM::STRD_PRE:
6361   case ARM::STRD_POST: {
6362     // Rt2 must be Rt + 1.
6363     unsigned Rt = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6364     unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(2).getReg());
6365     if (Rt2 != Rt + 1)
6366       return Error(Operands[3]->getStartLoc(),
6367                    "source operands must be sequential");
6368     return false;
6369   }
6370   case ARM::STR_PRE_IMM:
6371   case ARM::STR_PRE_REG:
6372   case ARM::STR_POST_IMM:
6373   case ARM::STR_POST_REG:
6374   case ARM::STRH_PRE:
6375   case ARM::STRH_POST:
6376   case ARM::STRB_PRE_IMM:
6377   case ARM::STRB_PRE_REG:
6378   case ARM::STRB_POST_IMM:
6379   case ARM::STRB_POST_REG: {
6380     // Rt must be different from Rn.
6381     const unsigned Rt = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6382     const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(2).getReg());
6383 
6384     if (Rt == Rn)
6385       return Error(Operands[3]->getStartLoc(),
6386                    "source register and base register can't be identical");
6387     return false;
6388   }
6389   case ARM::LDR_PRE_IMM:
6390   case ARM::LDR_PRE_REG:
6391   case ARM::LDR_POST_IMM:
6392   case ARM::LDR_POST_REG:
6393   case ARM::LDRH_PRE:
6394   case ARM::LDRH_POST:
6395   case ARM::LDRSH_PRE:
6396   case ARM::LDRSH_POST:
6397   case ARM::LDRB_PRE_IMM:
6398   case ARM::LDRB_PRE_REG:
6399   case ARM::LDRB_POST_IMM:
6400   case ARM::LDRB_POST_REG:
6401   case ARM::LDRSB_PRE:
6402   case ARM::LDRSB_POST: {
6403     // Rt must be different from Rn.
6404     const unsigned Rt = MRI->getEncodingValue(Inst.getOperand(0).getReg());
6405     const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(2).getReg());
6406 
6407     if (Rt == Rn)
6408       return Error(Operands[3]->getStartLoc(),
6409                    "destination register and base register can't be identical");
6410     return false;
6411   }
6412   case ARM::SBFX:
6413   case ARM::UBFX: {
6414     // Width must be in range [1, 32-lsb].
6415     unsigned LSB = Inst.getOperand(2).getImm();
6416     unsigned Widthm1 = Inst.getOperand(3).getImm();
6417     if (Widthm1 >= 32 - LSB)
6418       return Error(Operands[5]->getStartLoc(),
6419                    "bitfield width must be in range [1,32-lsb]");
6420     return false;
6421   }
6422   // Notionally handles ARM::tLDMIA_UPD too.
6423   case ARM::tLDMIA: {
6424     // If we're parsing Thumb2, the .w variant is available and handles
6425     // most cases that are normally illegal for a Thumb1 LDM instruction.
6426     // We'll make the transformation in processInstruction() if necessary.
6427     //
6428     // Thumb LDM instructions are writeback iff the base register is not
6429     // in the register list.
6430     unsigned Rn = Inst.getOperand(0).getReg();
6431     bool HasWritebackToken =
6432         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
6433          static_cast<ARMOperand &>(*Operands[3]).getToken() == "!");
6434     bool ListContainsBase;
6435     if (checkLowRegisterList(Inst, 3, Rn, 0, ListContainsBase) && !isThumbTwo())
6436       return Error(Operands[3 + HasWritebackToken]->getStartLoc(),
6437                    "registers must be in range r0-r7");
6438     // If we should have writeback, then there should be a '!' token.
6439     if (!ListContainsBase && !HasWritebackToken && !isThumbTwo())
6440       return Error(Operands[2]->getStartLoc(),
6441                    "writeback operator '!' expected");
6442     // If we should not have writeback, there must not be a '!'. This is
6443     // true even for the 32-bit wide encodings.
6444     if (ListContainsBase && HasWritebackToken)
6445       return Error(Operands[3]->getStartLoc(),
6446                    "writeback operator '!' not allowed when base register "
6447                    "in register list");
6448 
6449     if (validatetLDMRegList(Inst, Operands, 3))
6450       return true;
6451     break;
6452   }
6453   case ARM::LDMIA_UPD:
6454   case ARM::LDMDB_UPD:
6455   case ARM::LDMIB_UPD:
6456   case ARM::LDMDA_UPD:
6457     // ARM variants loading and updating the same register are only officially
6458     // UNPREDICTABLE on v7 upwards. Goodness knows what they did before.
6459     if (!hasV7Ops())
6460       break;
6461     if (listContainsReg(Inst, 3, Inst.getOperand(0).getReg()))
6462       return Error(Operands.back()->getStartLoc(),
6463                    "writeback register not allowed in register list");
6464     break;
6465   case ARM::t2LDMIA:
6466   case ARM::t2LDMDB:
6467     if (validatetLDMRegList(Inst, Operands, 3))
6468       return true;
6469     break;
6470   case ARM::t2STMIA:
6471   case ARM::t2STMDB:
6472     if (validatetSTMRegList(Inst, Operands, 3))
6473       return true;
6474     break;
6475   case ARM::t2LDMIA_UPD:
6476   case ARM::t2LDMDB_UPD:
6477   case ARM::t2STMIA_UPD:
6478   case ARM::t2STMDB_UPD:
6479     if (listContainsReg(Inst, 3, Inst.getOperand(0).getReg()))
6480       return Error(Operands.back()->getStartLoc(),
6481                    "writeback register not allowed in register list");
6482 
6483     if (Opcode == ARM::t2LDMIA_UPD || Opcode == ARM::t2LDMDB_UPD) {
6484       if (validatetLDMRegList(Inst, Operands, 3))
6485         return true;
6486     } else {
6487       if (validatetSTMRegList(Inst, Operands, 3))
6488         return true;
6489     }
6490     break;
6491 
6492   case ARM::sysLDMIA_UPD:
6493   case ARM::sysLDMDA_UPD:
6494   case ARM::sysLDMDB_UPD:
6495   case ARM::sysLDMIB_UPD:
6496     if (!listContainsReg(Inst, 3, ARM::PC))
6497       return Error(Operands[4]->getStartLoc(),
6498                    "writeback register only allowed on system LDM "
6499                    "if PC in register-list");
6500     break;
6501   case ARM::sysSTMIA_UPD:
6502   case ARM::sysSTMDA_UPD:
6503   case ARM::sysSTMDB_UPD:
6504   case ARM::sysSTMIB_UPD:
6505     return Error(Operands[2]->getStartLoc(),
6506                  "system STM cannot have writeback register");
6507   case ARM::tMUL:
6508     // The second source operand must be the same register as the destination
6509     // operand.
6510     //
6511     // In this case, we must directly check the parsed operands because the
6512     // cvtThumbMultiply() function is written in such a way that it guarantees
6513     // this first statement is always true for the new Inst.  Essentially, the
6514     // destination is unconditionally copied into the second source operand
6515     // without checking to see if it matches what we actually parsed.
6516     if (Operands.size() == 6 && (((ARMOperand &)*Operands[3]).getReg() !=
6517                                  ((ARMOperand &)*Operands[5]).getReg()) &&
6518         (((ARMOperand &)*Operands[3]).getReg() !=
6519          ((ARMOperand &)*Operands[4]).getReg())) {
6520       return Error(Operands[3]->getStartLoc(),
6521                    "destination register must match source register");
6522     }
6523     break;
6524 
6525   // Like for ldm/stm, push and pop have hi-reg handling version in Thumb2,
6526   // so only issue a diagnostic for thumb1. The instructions will be
6527   // switched to the t2 encodings in processInstruction() if necessary.
6528   case ARM::tPOP: {
6529     bool ListContainsBase;
6530     if (checkLowRegisterList(Inst, 2, 0, ARM::PC, ListContainsBase) &&
6531         !isThumbTwo())
6532       return Error(Operands[2]->getStartLoc(),
6533                    "registers must be in range r0-r7 or pc");
6534     if (validatetLDMRegList(Inst, Operands, 2, !isMClass()))
6535       return true;
6536     break;
6537   }
6538   case ARM::tPUSH: {
6539     bool ListContainsBase;
6540     if (checkLowRegisterList(Inst, 2, 0, ARM::LR, ListContainsBase) &&
6541         !isThumbTwo())
6542       return Error(Operands[2]->getStartLoc(),
6543                    "registers must be in range r0-r7 or lr");
6544     if (validatetSTMRegList(Inst, Operands, 2))
6545       return true;
6546     break;
6547   }
6548   case ARM::tSTMIA_UPD: {
6549     bool ListContainsBase, InvalidLowList;
6550     InvalidLowList = checkLowRegisterList(Inst, 4, Inst.getOperand(0).getReg(),
6551                                           0, ListContainsBase);
6552     if (InvalidLowList && !isThumbTwo())
6553       return Error(Operands[4]->getStartLoc(),
6554                    "registers must be in range r0-r7");
6555 
6556     // This would be converted to a 32-bit stm, but that's not valid if the
6557     // writeback register is in the list.
6558     if (InvalidLowList && ListContainsBase)
6559       return Error(Operands[4]->getStartLoc(),
6560                    "writeback operator '!' not allowed when base register "
6561                    "in register list");
6562 
6563     if (validatetSTMRegList(Inst, Operands, 4))
6564       return true;
6565     break;
6566   }
6567   case ARM::tADDrSP:
6568     // If the non-SP source operand and the destination operand are not the
6569     // same, we need thumb2 (for the wide encoding), or we have an error.
6570     if (!isThumbTwo() &&
6571         Inst.getOperand(0).getReg() != Inst.getOperand(2).getReg()) {
6572       return Error(Operands[4]->getStartLoc(),
6573                    "source register must be the same as destination");
6574     }
6575     break;
6576 
6577   // Final range checking for Thumb unconditional branch instructions.
6578   case ARM::tB:
6579     if (!(static_cast<ARMOperand &>(*Operands[2])).isSignedOffset<11, 1>())
6580       return Error(Operands[2]->getStartLoc(), "branch target out of range");
6581     break;
6582   case ARM::t2B: {
6583     int op = (Operands[2]->isImm()) ? 2 : 3;
6584     if (!static_cast<ARMOperand &>(*Operands[op]).isSignedOffset<24, 1>())
6585       return Error(Operands[op]->getStartLoc(), "branch target out of range");
6586     break;
6587   }
6588   // Final range checking for Thumb conditional branch instructions.
6589   case ARM::tBcc:
6590     if (!static_cast<ARMOperand &>(*Operands[2]).isSignedOffset<8, 1>())
6591       return Error(Operands[2]->getStartLoc(), "branch target out of range");
6592     break;
6593   case ARM::t2Bcc: {
6594     int Op = (Operands[2]->isImm()) ? 2 : 3;
6595     if (!static_cast<ARMOperand &>(*Operands[Op]).isSignedOffset<20, 1>())
6596       return Error(Operands[Op]->getStartLoc(), "branch target out of range");
6597     break;
6598   }
6599   case ARM::tCBZ:
6600   case ARM::tCBNZ: {
6601     if (!static_cast<ARMOperand &>(*Operands[2]).isUnsignedOffset<6, 1>())
6602       return Error(Operands[2]->getStartLoc(), "branch target out of range");
6603     break;
6604   }
6605   case ARM::MOVi16:
6606   case ARM::MOVTi16:
6607   case ARM::t2MOVi16:
6608   case ARM::t2MOVTi16:
6609     {
6610     // We want to avoid misleadingly allowing something like "mov r0, <symbol>"
6611     // especially when we turn it into a movw and the expression <symbol> does
6612     // not have a :lower16: or :upper16 as part of the expression.  We don't
6613     // want the behavior of silently truncating, which can be unexpected and
6614     // lead to bugs that are difficult to find since this is an easy mistake
6615     // to make.
6616     int i = (Operands[3]->isImm()) ? 3 : 4;
6617     ARMOperand &Op = static_cast<ARMOperand &>(*Operands[i]);
6618     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm());
6619     if (CE) break;
6620     const MCExpr *E = dyn_cast<MCExpr>(Op.getImm());
6621     if (!E) break;
6622     const ARMMCExpr *ARM16Expr = dyn_cast<ARMMCExpr>(E);
6623     if (!ARM16Expr || (ARM16Expr->getKind() != ARMMCExpr::VK_ARM_HI16 &&
6624                        ARM16Expr->getKind() != ARMMCExpr::VK_ARM_LO16))
6625       return Error(
6626           Op.getStartLoc(),
6627           "immediate expression for mov requires :lower16: or :upper16");
6628     break;
6629   }
6630   case ARM::HINT:
6631   case ARM::t2HINT: {
6632     unsigned Imm8 = Inst.getOperand(0).getImm();
6633     unsigned Pred = Inst.getOperand(1).getImm();
6634     // ESB is not predicable (pred must be AL). Without the RAS extension, this
6635     // behaves as any other unallocated hint.
6636     if (Imm8 == 0x10 && Pred != ARMCC::AL && hasRAS())
6637       return Error(Operands[1]->getStartLoc(), "instruction 'esb' is not "
6638                                                "predicable, but condition "
6639                                                "code specified");
6640     if (Imm8 == 0x14 && Pred != ARMCC::AL)
6641       return Error(Operands[1]->getStartLoc(), "instruction 'csdb' is not "
6642                                                "predicable, but condition "
6643                                                "code specified");
6644     break;
6645   }
6646   case ARM::VMOVRRS: {
6647     // Source registers must be sequential.
6648     const unsigned Sm = MRI->getEncodingValue(Inst.getOperand(2).getReg());
6649     const unsigned Sm1 = MRI->getEncodingValue(Inst.getOperand(3).getReg());
6650     if (Sm1 != Sm + 1)
6651       return Error(Operands[5]->getStartLoc(),
6652                    "source operands must be sequential");
6653     break;
6654   }
6655   case ARM::VMOVSRR: {
6656     // Destination registers must be sequential.
6657     const unsigned Sm = MRI->getEncodingValue(Inst.getOperand(0).getReg());
6658     const unsigned Sm1 = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6659     if (Sm1 != Sm + 1)
6660       return Error(Operands[3]->getStartLoc(),
6661                    "destination operands must be sequential");
6662     break;
6663   }
6664   }
6665 
6666   return false;
6667 }
6668 
6669 static unsigned getRealVSTOpcode(unsigned Opc, unsigned &Spacing) {
6670   switch(Opc) {
6671   default: llvm_unreachable("unexpected opcode!");
6672   // VST1LN
6673   case ARM::VST1LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST1LNd8_UPD;
6674   case ARM::VST1LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST1LNd16_UPD;
6675   case ARM::VST1LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST1LNd32_UPD;
6676   case ARM::VST1LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST1LNd8_UPD;
6677   case ARM::VST1LNdWB_register_Asm_16: Spacing = 1; return ARM::VST1LNd16_UPD;
6678   case ARM::VST1LNdWB_register_Asm_32: Spacing = 1; return ARM::VST1LNd32_UPD;
6679   case ARM::VST1LNdAsm_8:  Spacing = 1; return ARM::VST1LNd8;
6680   case ARM::VST1LNdAsm_16: Spacing = 1; return ARM::VST1LNd16;
6681   case ARM::VST1LNdAsm_32: Spacing = 1; return ARM::VST1LNd32;
6682 
6683   // VST2LN
6684   case ARM::VST2LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST2LNd8_UPD;
6685   case ARM::VST2LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST2LNd16_UPD;
6686   case ARM::VST2LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST2LNd32_UPD;
6687   case ARM::VST2LNqWB_fixed_Asm_16: Spacing = 2; return ARM::VST2LNq16_UPD;
6688   case ARM::VST2LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST2LNq32_UPD;
6689 
6690   case ARM::VST2LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST2LNd8_UPD;
6691   case ARM::VST2LNdWB_register_Asm_16: Spacing = 1; return ARM::VST2LNd16_UPD;
6692   case ARM::VST2LNdWB_register_Asm_32: Spacing = 1; return ARM::VST2LNd32_UPD;
6693   case ARM::VST2LNqWB_register_Asm_16: Spacing = 2; return ARM::VST2LNq16_UPD;
6694   case ARM::VST2LNqWB_register_Asm_32: Spacing = 2; return ARM::VST2LNq32_UPD;
6695 
6696   case ARM::VST2LNdAsm_8:  Spacing = 1; return ARM::VST2LNd8;
6697   case ARM::VST2LNdAsm_16: Spacing = 1; return ARM::VST2LNd16;
6698   case ARM::VST2LNdAsm_32: Spacing = 1; return ARM::VST2LNd32;
6699   case ARM::VST2LNqAsm_16: Spacing = 2; return ARM::VST2LNq16;
6700   case ARM::VST2LNqAsm_32: Spacing = 2; return ARM::VST2LNq32;
6701 
6702   // VST3LN
6703   case ARM::VST3LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST3LNd8_UPD;
6704   case ARM::VST3LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST3LNd16_UPD;
6705   case ARM::VST3LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST3LNd32_UPD;
6706   case ARM::VST3LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VST3LNq16_UPD;
6707   case ARM::VST3LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST3LNq32_UPD;
6708   case ARM::VST3LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST3LNd8_UPD;
6709   case ARM::VST3LNdWB_register_Asm_16: Spacing = 1; return ARM::VST3LNd16_UPD;
6710   case ARM::VST3LNdWB_register_Asm_32: Spacing = 1; return ARM::VST3LNd32_UPD;
6711   case ARM::VST3LNqWB_register_Asm_16: Spacing = 2; return ARM::VST3LNq16_UPD;
6712   case ARM::VST3LNqWB_register_Asm_32: Spacing = 2; return ARM::VST3LNq32_UPD;
6713   case ARM::VST3LNdAsm_8:  Spacing = 1; return ARM::VST3LNd8;
6714   case ARM::VST3LNdAsm_16: Spacing = 1; return ARM::VST3LNd16;
6715   case ARM::VST3LNdAsm_32: Spacing = 1; return ARM::VST3LNd32;
6716   case ARM::VST3LNqAsm_16: Spacing = 2; return ARM::VST3LNq16;
6717   case ARM::VST3LNqAsm_32: Spacing = 2; return ARM::VST3LNq32;
6718 
6719   // VST3
6720   case ARM::VST3dWB_fixed_Asm_8:  Spacing = 1; return ARM::VST3d8_UPD;
6721   case ARM::VST3dWB_fixed_Asm_16: Spacing = 1; return ARM::VST3d16_UPD;
6722   case ARM::VST3dWB_fixed_Asm_32: Spacing = 1; return ARM::VST3d32_UPD;
6723   case ARM::VST3qWB_fixed_Asm_8:  Spacing = 2; return ARM::VST3q8_UPD;
6724   case ARM::VST3qWB_fixed_Asm_16: Spacing = 2; return ARM::VST3q16_UPD;
6725   case ARM::VST3qWB_fixed_Asm_32: Spacing = 2; return ARM::VST3q32_UPD;
6726   case ARM::VST3dWB_register_Asm_8:  Spacing = 1; return ARM::VST3d8_UPD;
6727   case ARM::VST3dWB_register_Asm_16: Spacing = 1; return ARM::VST3d16_UPD;
6728   case ARM::VST3dWB_register_Asm_32: Spacing = 1; return ARM::VST3d32_UPD;
6729   case ARM::VST3qWB_register_Asm_8:  Spacing = 2; return ARM::VST3q8_UPD;
6730   case ARM::VST3qWB_register_Asm_16: Spacing = 2; return ARM::VST3q16_UPD;
6731   case ARM::VST3qWB_register_Asm_32: Spacing = 2; return ARM::VST3q32_UPD;
6732   case ARM::VST3dAsm_8:  Spacing = 1; return ARM::VST3d8;
6733   case ARM::VST3dAsm_16: Spacing = 1; return ARM::VST3d16;
6734   case ARM::VST3dAsm_32: Spacing = 1; return ARM::VST3d32;
6735   case ARM::VST3qAsm_8:  Spacing = 2; return ARM::VST3q8;
6736   case ARM::VST3qAsm_16: Spacing = 2; return ARM::VST3q16;
6737   case ARM::VST3qAsm_32: Spacing = 2; return ARM::VST3q32;
6738 
6739   // VST4LN
6740   case ARM::VST4LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST4LNd8_UPD;
6741   case ARM::VST4LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST4LNd16_UPD;
6742   case ARM::VST4LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST4LNd32_UPD;
6743   case ARM::VST4LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VST4LNq16_UPD;
6744   case ARM::VST4LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST4LNq32_UPD;
6745   case ARM::VST4LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST4LNd8_UPD;
6746   case ARM::VST4LNdWB_register_Asm_16: Spacing = 1; return ARM::VST4LNd16_UPD;
6747   case ARM::VST4LNdWB_register_Asm_32: Spacing = 1; return ARM::VST4LNd32_UPD;
6748   case ARM::VST4LNqWB_register_Asm_16: Spacing = 2; return ARM::VST4LNq16_UPD;
6749   case ARM::VST4LNqWB_register_Asm_32: Spacing = 2; return ARM::VST4LNq32_UPD;
6750   case ARM::VST4LNdAsm_8:  Spacing = 1; return ARM::VST4LNd8;
6751   case ARM::VST4LNdAsm_16: Spacing = 1; return ARM::VST4LNd16;
6752   case ARM::VST4LNdAsm_32: Spacing = 1; return ARM::VST4LNd32;
6753   case ARM::VST4LNqAsm_16: Spacing = 2; return ARM::VST4LNq16;
6754   case ARM::VST4LNqAsm_32: Spacing = 2; return ARM::VST4LNq32;
6755 
6756   // VST4
6757   case ARM::VST4dWB_fixed_Asm_8:  Spacing = 1; return ARM::VST4d8_UPD;
6758   case ARM::VST4dWB_fixed_Asm_16: Spacing = 1; return ARM::VST4d16_UPD;
6759   case ARM::VST4dWB_fixed_Asm_32: Spacing = 1; return ARM::VST4d32_UPD;
6760   case ARM::VST4qWB_fixed_Asm_8:  Spacing = 2; return ARM::VST4q8_UPD;
6761   case ARM::VST4qWB_fixed_Asm_16: Spacing = 2; return ARM::VST4q16_UPD;
6762   case ARM::VST4qWB_fixed_Asm_32: Spacing = 2; return ARM::VST4q32_UPD;
6763   case ARM::VST4dWB_register_Asm_8:  Spacing = 1; return ARM::VST4d8_UPD;
6764   case ARM::VST4dWB_register_Asm_16: Spacing = 1; return ARM::VST4d16_UPD;
6765   case ARM::VST4dWB_register_Asm_32: Spacing = 1; return ARM::VST4d32_UPD;
6766   case ARM::VST4qWB_register_Asm_8:  Spacing = 2; return ARM::VST4q8_UPD;
6767   case ARM::VST4qWB_register_Asm_16: Spacing = 2; return ARM::VST4q16_UPD;
6768   case ARM::VST4qWB_register_Asm_32: Spacing = 2; return ARM::VST4q32_UPD;
6769   case ARM::VST4dAsm_8:  Spacing = 1; return ARM::VST4d8;
6770   case ARM::VST4dAsm_16: Spacing = 1; return ARM::VST4d16;
6771   case ARM::VST4dAsm_32: Spacing = 1; return ARM::VST4d32;
6772   case ARM::VST4qAsm_8:  Spacing = 2; return ARM::VST4q8;
6773   case ARM::VST4qAsm_16: Spacing = 2; return ARM::VST4q16;
6774   case ARM::VST4qAsm_32: Spacing = 2; return ARM::VST4q32;
6775   }
6776 }
6777 
6778 static unsigned getRealVLDOpcode(unsigned Opc, unsigned &Spacing) {
6779   switch(Opc) {
6780   default: llvm_unreachable("unexpected opcode!");
6781   // VLD1LN
6782   case ARM::VLD1LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD1LNd8_UPD;
6783   case ARM::VLD1LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD1LNd16_UPD;
6784   case ARM::VLD1LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD1LNd32_UPD;
6785   case ARM::VLD1LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD1LNd8_UPD;
6786   case ARM::VLD1LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD1LNd16_UPD;
6787   case ARM::VLD1LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD1LNd32_UPD;
6788   case ARM::VLD1LNdAsm_8:  Spacing = 1; return ARM::VLD1LNd8;
6789   case ARM::VLD1LNdAsm_16: Spacing = 1; return ARM::VLD1LNd16;
6790   case ARM::VLD1LNdAsm_32: Spacing = 1; return ARM::VLD1LNd32;
6791 
6792   // VLD2LN
6793   case ARM::VLD2LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD2LNd8_UPD;
6794   case ARM::VLD2LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD2LNd16_UPD;
6795   case ARM::VLD2LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD2LNd32_UPD;
6796   case ARM::VLD2LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD2LNq16_UPD;
6797   case ARM::VLD2LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD2LNq32_UPD;
6798   case ARM::VLD2LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD2LNd8_UPD;
6799   case ARM::VLD2LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD2LNd16_UPD;
6800   case ARM::VLD2LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD2LNd32_UPD;
6801   case ARM::VLD2LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD2LNq16_UPD;
6802   case ARM::VLD2LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD2LNq32_UPD;
6803   case ARM::VLD2LNdAsm_8:  Spacing = 1; return ARM::VLD2LNd8;
6804   case ARM::VLD2LNdAsm_16: Spacing = 1; return ARM::VLD2LNd16;
6805   case ARM::VLD2LNdAsm_32: Spacing = 1; return ARM::VLD2LNd32;
6806   case ARM::VLD2LNqAsm_16: Spacing = 2; return ARM::VLD2LNq16;
6807   case ARM::VLD2LNqAsm_32: Spacing = 2; return ARM::VLD2LNq32;
6808 
6809   // VLD3DUP
6810   case ARM::VLD3DUPdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3DUPd8_UPD;
6811   case ARM::VLD3DUPdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3DUPd16_UPD;
6812   case ARM::VLD3DUPdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3DUPd32_UPD;
6813   case ARM::VLD3DUPqWB_fixed_Asm_8: Spacing = 1; return ARM::VLD3DUPq8_UPD;
6814   case ARM::VLD3DUPqWB_fixed_Asm_16: Spacing = 2; return ARM::VLD3DUPq16_UPD;
6815   case ARM::VLD3DUPqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3DUPq32_UPD;
6816   case ARM::VLD3DUPdWB_register_Asm_8:  Spacing = 1; return ARM::VLD3DUPd8_UPD;
6817   case ARM::VLD3DUPdWB_register_Asm_16: Spacing = 1; return ARM::VLD3DUPd16_UPD;
6818   case ARM::VLD3DUPdWB_register_Asm_32: Spacing = 1; return ARM::VLD3DUPd32_UPD;
6819   case ARM::VLD3DUPqWB_register_Asm_8: Spacing = 2; return ARM::VLD3DUPq8_UPD;
6820   case ARM::VLD3DUPqWB_register_Asm_16: Spacing = 2; return ARM::VLD3DUPq16_UPD;
6821   case ARM::VLD3DUPqWB_register_Asm_32: Spacing = 2; return ARM::VLD3DUPq32_UPD;
6822   case ARM::VLD3DUPdAsm_8:  Spacing = 1; return ARM::VLD3DUPd8;
6823   case ARM::VLD3DUPdAsm_16: Spacing = 1; return ARM::VLD3DUPd16;
6824   case ARM::VLD3DUPdAsm_32: Spacing = 1; return ARM::VLD3DUPd32;
6825   case ARM::VLD3DUPqAsm_8: Spacing = 2; return ARM::VLD3DUPq8;
6826   case ARM::VLD3DUPqAsm_16: Spacing = 2; return ARM::VLD3DUPq16;
6827   case ARM::VLD3DUPqAsm_32: Spacing = 2; return ARM::VLD3DUPq32;
6828 
6829   // VLD3LN
6830   case ARM::VLD3LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3LNd8_UPD;
6831   case ARM::VLD3LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3LNd16_UPD;
6832   case ARM::VLD3LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3LNd32_UPD;
6833   case ARM::VLD3LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3LNq16_UPD;
6834   case ARM::VLD3LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3LNq32_UPD;
6835   case ARM::VLD3LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD3LNd8_UPD;
6836   case ARM::VLD3LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD3LNd16_UPD;
6837   case ARM::VLD3LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD3LNd32_UPD;
6838   case ARM::VLD3LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD3LNq16_UPD;
6839   case ARM::VLD3LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD3LNq32_UPD;
6840   case ARM::VLD3LNdAsm_8:  Spacing = 1; return ARM::VLD3LNd8;
6841   case ARM::VLD3LNdAsm_16: Spacing = 1; return ARM::VLD3LNd16;
6842   case ARM::VLD3LNdAsm_32: Spacing = 1; return ARM::VLD3LNd32;
6843   case ARM::VLD3LNqAsm_16: Spacing = 2; return ARM::VLD3LNq16;
6844   case ARM::VLD3LNqAsm_32: Spacing = 2; return ARM::VLD3LNq32;
6845 
6846   // VLD3
6847   case ARM::VLD3dWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3d8_UPD;
6848   case ARM::VLD3dWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3d16_UPD;
6849   case ARM::VLD3dWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3d32_UPD;
6850   case ARM::VLD3qWB_fixed_Asm_8:  Spacing = 2; return ARM::VLD3q8_UPD;
6851   case ARM::VLD3qWB_fixed_Asm_16: Spacing = 2; return ARM::VLD3q16_UPD;
6852   case ARM::VLD3qWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3q32_UPD;
6853   case ARM::VLD3dWB_register_Asm_8:  Spacing = 1; return ARM::VLD3d8_UPD;
6854   case ARM::VLD3dWB_register_Asm_16: Spacing = 1; return ARM::VLD3d16_UPD;
6855   case ARM::VLD3dWB_register_Asm_32: Spacing = 1; return ARM::VLD3d32_UPD;
6856   case ARM::VLD3qWB_register_Asm_8:  Spacing = 2; return ARM::VLD3q8_UPD;
6857   case ARM::VLD3qWB_register_Asm_16: Spacing = 2; return ARM::VLD3q16_UPD;
6858   case ARM::VLD3qWB_register_Asm_32: Spacing = 2; return ARM::VLD3q32_UPD;
6859   case ARM::VLD3dAsm_8:  Spacing = 1; return ARM::VLD3d8;
6860   case ARM::VLD3dAsm_16: Spacing = 1; return ARM::VLD3d16;
6861   case ARM::VLD3dAsm_32: Spacing = 1; return ARM::VLD3d32;
6862   case ARM::VLD3qAsm_8:  Spacing = 2; return ARM::VLD3q8;
6863   case ARM::VLD3qAsm_16: Spacing = 2; return ARM::VLD3q16;
6864   case ARM::VLD3qAsm_32: Spacing = 2; return ARM::VLD3q32;
6865 
6866   // VLD4LN
6867   case ARM::VLD4LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4LNd8_UPD;
6868   case ARM::VLD4LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4LNd16_UPD;
6869   case ARM::VLD4LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4LNd32_UPD;
6870   case ARM::VLD4LNqWB_fixed_Asm_16: Spacing = 2; return ARM::VLD4LNq16_UPD;
6871   case ARM::VLD4LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4LNq32_UPD;
6872   case ARM::VLD4LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD4LNd8_UPD;
6873   case ARM::VLD4LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD4LNd16_UPD;
6874   case ARM::VLD4LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD4LNd32_UPD;
6875   case ARM::VLD4LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD4LNq16_UPD;
6876   case ARM::VLD4LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD4LNq32_UPD;
6877   case ARM::VLD4LNdAsm_8:  Spacing = 1; return ARM::VLD4LNd8;
6878   case ARM::VLD4LNdAsm_16: Spacing = 1; return ARM::VLD4LNd16;
6879   case ARM::VLD4LNdAsm_32: Spacing = 1; return ARM::VLD4LNd32;
6880   case ARM::VLD4LNqAsm_16: Spacing = 2; return ARM::VLD4LNq16;
6881   case ARM::VLD4LNqAsm_32: Spacing = 2; return ARM::VLD4LNq32;
6882 
6883   // VLD4DUP
6884   case ARM::VLD4DUPdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4DUPd8_UPD;
6885   case ARM::VLD4DUPdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4DUPd16_UPD;
6886   case ARM::VLD4DUPdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4DUPd32_UPD;
6887   case ARM::VLD4DUPqWB_fixed_Asm_8: Spacing = 1; return ARM::VLD4DUPq8_UPD;
6888   case ARM::VLD4DUPqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4DUPq16_UPD;
6889   case ARM::VLD4DUPqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4DUPq32_UPD;
6890   case ARM::VLD4DUPdWB_register_Asm_8:  Spacing = 1; return ARM::VLD4DUPd8_UPD;
6891   case ARM::VLD4DUPdWB_register_Asm_16: Spacing = 1; return ARM::VLD4DUPd16_UPD;
6892   case ARM::VLD4DUPdWB_register_Asm_32: Spacing = 1; return ARM::VLD4DUPd32_UPD;
6893   case ARM::VLD4DUPqWB_register_Asm_8: Spacing = 2; return ARM::VLD4DUPq8_UPD;
6894   case ARM::VLD4DUPqWB_register_Asm_16: Spacing = 2; return ARM::VLD4DUPq16_UPD;
6895   case ARM::VLD4DUPqWB_register_Asm_32: Spacing = 2; return ARM::VLD4DUPq32_UPD;
6896   case ARM::VLD4DUPdAsm_8:  Spacing = 1; return ARM::VLD4DUPd8;
6897   case ARM::VLD4DUPdAsm_16: Spacing = 1; return ARM::VLD4DUPd16;
6898   case ARM::VLD4DUPdAsm_32: Spacing = 1; return ARM::VLD4DUPd32;
6899   case ARM::VLD4DUPqAsm_8: Spacing = 2; return ARM::VLD4DUPq8;
6900   case ARM::VLD4DUPqAsm_16: Spacing = 2; return ARM::VLD4DUPq16;
6901   case ARM::VLD4DUPqAsm_32: Spacing = 2; return ARM::VLD4DUPq32;
6902 
6903   // VLD4
6904   case ARM::VLD4dWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4d8_UPD;
6905   case ARM::VLD4dWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4d16_UPD;
6906   case ARM::VLD4dWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4d32_UPD;
6907   case ARM::VLD4qWB_fixed_Asm_8:  Spacing = 2; return ARM::VLD4q8_UPD;
6908   case ARM::VLD4qWB_fixed_Asm_16: Spacing = 2; return ARM::VLD4q16_UPD;
6909   case ARM::VLD4qWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4q32_UPD;
6910   case ARM::VLD4dWB_register_Asm_8:  Spacing = 1; return ARM::VLD4d8_UPD;
6911   case ARM::VLD4dWB_register_Asm_16: Spacing = 1; return ARM::VLD4d16_UPD;
6912   case ARM::VLD4dWB_register_Asm_32: Spacing = 1; return ARM::VLD4d32_UPD;
6913   case ARM::VLD4qWB_register_Asm_8:  Spacing = 2; return ARM::VLD4q8_UPD;
6914   case ARM::VLD4qWB_register_Asm_16: Spacing = 2; return ARM::VLD4q16_UPD;
6915   case ARM::VLD4qWB_register_Asm_32: Spacing = 2; return ARM::VLD4q32_UPD;
6916   case ARM::VLD4dAsm_8:  Spacing = 1; return ARM::VLD4d8;
6917   case ARM::VLD4dAsm_16: Spacing = 1; return ARM::VLD4d16;
6918   case ARM::VLD4dAsm_32: Spacing = 1; return ARM::VLD4d32;
6919   case ARM::VLD4qAsm_8:  Spacing = 2; return ARM::VLD4q8;
6920   case ARM::VLD4qAsm_16: Spacing = 2; return ARM::VLD4q16;
6921   case ARM::VLD4qAsm_32: Spacing = 2; return ARM::VLD4q32;
6922   }
6923 }
6924 
6925 bool ARMAsmParser::processInstruction(MCInst &Inst,
6926                                       const OperandVector &Operands,
6927                                       MCStreamer &Out) {
6928   // Check if we have the wide qualifier, because if it's present we
6929   // must avoid selecting a 16-bit thumb instruction.
6930   bool HasWideQualifier = false;
6931   for (auto &Op : Operands) {
6932     ARMOperand &ARMOp = static_cast<ARMOperand&>(*Op);
6933     if (ARMOp.isToken() && ARMOp.getToken() == ".w") {
6934       HasWideQualifier = true;
6935       break;
6936     }
6937   }
6938 
6939   switch (Inst.getOpcode()) {
6940   // Alias for alternate form of 'ldr{,b}t Rt, [Rn], #imm' instruction.
6941   case ARM::LDRT_POST:
6942   case ARM::LDRBT_POST: {
6943     const unsigned Opcode =
6944       (Inst.getOpcode() == ARM::LDRT_POST) ? ARM::LDRT_POST_IMM
6945                                            : ARM::LDRBT_POST_IMM;
6946     MCInst TmpInst;
6947     TmpInst.setOpcode(Opcode);
6948     TmpInst.addOperand(Inst.getOperand(0));
6949     TmpInst.addOperand(Inst.getOperand(1));
6950     TmpInst.addOperand(Inst.getOperand(1));
6951     TmpInst.addOperand(MCOperand::createReg(0));
6952     TmpInst.addOperand(MCOperand::createImm(0));
6953     TmpInst.addOperand(Inst.getOperand(2));
6954     TmpInst.addOperand(Inst.getOperand(3));
6955     Inst = TmpInst;
6956     return true;
6957   }
6958   // Alias for alternate form of 'str{,b}t Rt, [Rn], #imm' instruction.
6959   case ARM::STRT_POST:
6960   case ARM::STRBT_POST: {
6961     const unsigned Opcode =
6962       (Inst.getOpcode() == ARM::STRT_POST) ? ARM::STRT_POST_IMM
6963                                            : ARM::STRBT_POST_IMM;
6964     MCInst TmpInst;
6965     TmpInst.setOpcode(Opcode);
6966     TmpInst.addOperand(Inst.getOperand(1));
6967     TmpInst.addOperand(Inst.getOperand(0));
6968     TmpInst.addOperand(Inst.getOperand(1));
6969     TmpInst.addOperand(MCOperand::createReg(0));
6970     TmpInst.addOperand(MCOperand::createImm(0));
6971     TmpInst.addOperand(Inst.getOperand(2));
6972     TmpInst.addOperand(Inst.getOperand(3));
6973     Inst = TmpInst;
6974     return true;
6975   }
6976   // Alias for alternate form of 'ADR Rd, #imm' instruction.
6977   case ARM::ADDri: {
6978     if (Inst.getOperand(1).getReg() != ARM::PC ||
6979         Inst.getOperand(5).getReg() != 0 ||
6980         !(Inst.getOperand(2).isExpr() || Inst.getOperand(2).isImm()))
6981       return false;
6982     MCInst TmpInst;
6983     TmpInst.setOpcode(ARM::ADR);
6984     TmpInst.addOperand(Inst.getOperand(0));
6985     if (Inst.getOperand(2).isImm()) {
6986       // Immediate (mod_imm) will be in its encoded form, we must unencode it
6987       // before passing it to the ADR instruction.
6988       unsigned Enc = Inst.getOperand(2).getImm();
6989       TmpInst.addOperand(MCOperand::createImm(
6990         ARM_AM::rotr32(Enc & 0xFF, (Enc & 0xF00) >> 7)));
6991     } else {
6992       // Turn PC-relative expression into absolute expression.
6993       // Reading PC provides the start of the current instruction + 8 and
6994       // the transform to adr is biased by that.
6995       MCSymbol *Dot = getContext().createTempSymbol();
6996       Out.EmitLabel(Dot);
6997       const MCExpr *OpExpr = Inst.getOperand(2).getExpr();
6998       const MCExpr *InstPC = MCSymbolRefExpr::create(Dot,
6999                                                      MCSymbolRefExpr::VK_None,
7000                                                      getContext());
7001       const MCExpr *Const8 = MCConstantExpr::create(8, getContext());
7002       const MCExpr *ReadPC = MCBinaryExpr::createAdd(InstPC, Const8,
7003                                                      getContext());
7004       const MCExpr *FixupAddr = MCBinaryExpr::createAdd(ReadPC, OpExpr,
7005                                                         getContext());
7006       TmpInst.addOperand(MCOperand::createExpr(FixupAddr));
7007     }
7008     TmpInst.addOperand(Inst.getOperand(3));
7009     TmpInst.addOperand(Inst.getOperand(4));
7010     Inst = TmpInst;
7011     return true;
7012   }
7013   // Aliases for alternate PC+imm syntax of LDR instructions.
7014   case ARM::t2LDRpcrel:
7015     // Select the narrow version if the immediate will fit.
7016     if (Inst.getOperand(1).getImm() > 0 &&
7017         Inst.getOperand(1).getImm() <= 0xff &&
7018         !HasWideQualifier)
7019       Inst.setOpcode(ARM::tLDRpci);
7020     else
7021       Inst.setOpcode(ARM::t2LDRpci);
7022     return true;
7023   case ARM::t2LDRBpcrel:
7024     Inst.setOpcode(ARM::t2LDRBpci);
7025     return true;
7026   case ARM::t2LDRHpcrel:
7027     Inst.setOpcode(ARM::t2LDRHpci);
7028     return true;
7029   case ARM::t2LDRSBpcrel:
7030     Inst.setOpcode(ARM::t2LDRSBpci);
7031     return true;
7032   case ARM::t2LDRSHpcrel:
7033     Inst.setOpcode(ARM::t2LDRSHpci);
7034     return true;
7035   case ARM::LDRConstPool:
7036   case ARM::tLDRConstPool:
7037   case ARM::t2LDRConstPool: {
7038     // Pseudo instruction ldr rt, =immediate is converted to a
7039     // MOV rt, immediate if immediate is known and representable
7040     // otherwise we create a constant pool entry that we load from.
7041     MCInst TmpInst;
7042     if (Inst.getOpcode() == ARM::LDRConstPool)
7043       TmpInst.setOpcode(ARM::LDRi12);
7044     else if (Inst.getOpcode() == ARM::tLDRConstPool)
7045       TmpInst.setOpcode(ARM::tLDRpci);
7046     else if (Inst.getOpcode() == ARM::t2LDRConstPool)
7047       TmpInst.setOpcode(ARM::t2LDRpci);
7048     const ARMOperand &PoolOperand =
7049       (HasWideQualifier ?
7050        static_cast<ARMOperand &>(*Operands[4]) :
7051        static_cast<ARMOperand &>(*Operands[3]));
7052     const MCExpr *SubExprVal = PoolOperand.getConstantPoolImm();
7053     // If SubExprVal is a constant we may be able to use a MOV
7054     if (isa<MCConstantExpr>(SubExprVal) &&
7055         Inst.getOperand(0).getReg() != ARM::PC &&
7056         Inst.getOperand(0).getReg() != ARM::SP) {
7057       int64_t Value =
7058         (int64_t) (cast<MCConstantExpr>(SubExprVal))->getValue();
7059       bool UseMov  = true;
7060       bool MovHasS = true;
7061       if (Inst.getOpcode() == ARM::LDRConstPool) {
7062         // ARM Constant
7063         if (ARM_AM::getSOImmVal(Value) != -1) {
7064           Value = ARM_AM::getSOImmVal(Value);
7065           TmpInst.setOpcode(ARM::MOVi);
7066         }
7067         else if (ARM_AM::getSOImmVal(~Value) != -1) {
7068           Value = ARM_AM::getSOImmVal(~Value);
7069           TmpInst.setOpcode(ARM::MVNi);
7070         }
7071         else if (hasV6T2Ops() &&
7072                  Value >=0 && Value < 65536) {
7073           TmpInst.setOpcode(ARM::MOVi16);
7074           MovHasS = false;
7075         }
7076         else
7077           UseMov = false;
7078       }
7079       else {
7080         // Thumb/Thumb2 Constant
7081         if (hasThumb2() &&
7082             ARM_AM::getT2SOImmVal(Value) != -1)
7083           TmpInst.setOpcode(ARM::t2MOVi);
7084         else if (hasThumb2() &&
7085                  ARM_AM::getT2SOImmVal(~Value) != -1) {
7086           TmpInst.setOpcode(ARM::t2MVNi);
7087           Value = ~Value;
7088         }
7089         else if (hasV8MBaseline() &&
7090                  Value >=0 && Value < 65536) {
7091           TmpInst.setOpcode(ARM::t2MOVi16);
7092           MovHasS = false;
7093         }
7094         else
7095           UseMov = false;
7096       }
7097       if (UseMov) {
7098         TmpInst.addOperand(Inst.getOperand(0));           // Rt
7099         TmpInst.addOperand(MCOperand::createImm(Value));  // Immediate
7100         TmpInst.addOperand(Inst.getOperand(2));           // CondCode
7101         TmpInst.addOperand(Inst.getOperand(3));           // CondCode
7102         if (MovHasS)
7103           TmpInst.addOperand(MCOperand::createReg(0));    // S
7104         Inst = TmpInst;
7105         return true;
7106       }
7107     }
7108     // No opportunity to use MOV/MVN create constant pool
7109     const MCExpr *CPLoc =
7110       getTargetStreamer().addConstantPoolEntry(SubExprVal,
7111                                                PoolOperand.getStartLoc());
7112     TmpInst.addOperand(Inst.getOperand(0));           // Rt
7113     TmpInst.addOperand(MCOperand::createExpr(CPLoc)); // offset to constpool
7114     if (TmpInst.getOpcode() == ARM::LDRi12)
7115       TmpInst.addOperand(MCOperand::createImm(0));    // unused offset
7116     TmpInst.addOperand(Inst.getOperand(2));           // CondCode
7117     TmpInst.addOperand(Inst.getOperand(3));           // CondCode
7118     Inst = TmpInst;
7119     return true;
7120   }
7121   // Handle NEON VST complex aliases.
7122   case ARM::VST1LNdWB_register_Asm_8:
7123   case ARM::VST1LNdWB_register_Asm_16:
7124   case ARM::VST1LNdWB_register_Asm_32: {
7125     MCInst TmpInst;
7126     // Shuffle the operands around so the lane index operand is in the
7127     // right place.
7128     unsigned Spacing;
7129     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7130     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7131     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7132     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7133     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7134     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7135     TmpInst.addOperand(Inst.getOperand(1)); // lane
7136     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7137     TmpInst.addOperand(Inst.getOperand(6));
7138     Inst = TmpInst;
7139     return true;
7140   }
7141 
7142   case ARM::VST2LNdWB_register_Asm_8:
7143   case ARM::VST2LNdWB_register_Asm_16:
7144   case ARM::VST2LNdWB_register_Asm_32:
7145   case ARM::VST2LNqWB_register_Asm_16:
7146   case ARM::VST2LNqWB_register_Asm_32: {
7147     MCInst TmpInst;
7148     // Shuffle the operands around so the lane index operand is in the
7149     // right place.
7150     unsigned Spacing;
7151     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7152     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7153     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7154     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7155     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7156     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7157     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7158                                             Spacing));
7159     TmpInst.addOperand(Inst.getOperand(1)); // lane
7160     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7161     TmpInst.addOperand(Inst.getOperand(6));
7162     Inst = TmpInst;
7163     return true;
7164   }
7165 
7166   case ARM::VST3LNdWB_register_Asm_8:
7167   case ARM::VST3LNdWB_register_Asm_16:
7168   case ARM::VST3LNdWB_register_Asm_32:
7169   case ARM::VST3LNqWB_register_Asm_16:
7170   case ARM::VST3LNqWB_register_Asm_32: {
7171     MCInst TmpInst;
7172     // Shuffle the operands around so the lane index operand is in the
7173     // right place.
7174     unsigned Spacing;
7175     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7176     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7177     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7178     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7179     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7180     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7181     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7182                                             Spacing));
7183     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7184                                             Spacing * 2));
7185     TmpInst.addOperand(Inst.getOperand(1)); // lane
7186     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7187     TmpInst.addOperand(Inst.getOperand(6));
7188     Inst = TmpInst;
7189     return true;
7190   }
7191 
7192   case ARM::VST4LNdWB_register_Asm_8:
7193   case ARM::VST4LNdWB_register_Asm_16:
7194   case ARM::VST4LNdWB_register_Asm_32:
7195   case ARM::VST4LNqWB_register_Asm_16:
7196   case ARM::VST4LNqWB_register_Asm_32: {
7197     MCInst TmpInst;
7198     // Shuffle the operands around so the lane index operand is in the
7199     // right place.
7200     unsigned Spacing;
7201     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7202     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7203     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7204     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7205     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7206     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7207     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7208                                             Spacing));
7209     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7210                                             Spacing * 2));
7211     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7212                                             Spacing * 3));
7213     TmpInst.addOperand(Inst.getOperand(1)); // lane
7214     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7215     TmpInst.addOperand(Inst.getOperand(6));
7216     Inst = TmpInst;
7217     return true;
7218   }
7219 
7220   case ARM::VST1LNdWB_fixed_Asm_8:
7221   case ARM::VST1LNdWB_fixed_Asm_16:
7222   case ARM::VST1LNdWB_fixed_Asm_32: {
7223     MCInst TmpInst;
7224     // Shuffle the operands around so the lane index operand is in the
7225     // right place.
7226     unsigned Spacing;
7227     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7228     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7229     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7230     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7231     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7232     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7233     TmpInst.addOperand(Inst.getOperand(1)); // lane
7234     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7235     TmpInst.addOperand(Inst.getOperand(5));
7236     Inst = TmpInst;
7237     return true;
7238   }
7239 
7240   case ARM::VST2LNdWB_fixed_Asm_8:
7241   case ARM::VST2LNdWB_fixed_Asm_16:
7242   case ARM::VST2LNdWB_fixed_Asm_32:
7243   case ARM::VST2LNqWB_fixed_Asm_16:
7244   case ARM::VST2LNqWB_fixed_Asm_32: {
7245     MCInst TmpInst;
7246     // Shuffle the operands around so the lane index operand is in the
7247     // right place.
7248     unsigned Spacing;
7249     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7250     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7251     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7252     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7253     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7254     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7255     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7256                                             Spacing));
7257     TmpInst.addOperand(Inst.getOperand(1)); // lane
7258     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7259     TmpInst.addOperand(Inst.getOperand(5));
7260     Inst = TmpInst;
7261     return true;
7262   }
7263 
7264   case ARM::VST3LNdWB_fixed_Asm_8:
7265   case ARM::VST3LNdWB_fixed_Asm_16:
7266   case ARM::VST3LNdWB_fixed_Asm_32:
7267   case ARM::VST3LNqWB_fixed_Asm_16:
7268   case ARM::VST3LNqWB_fixed_Asm_32: {
7269     MCInst TmpInst;
7270     // Shuffle the operands around so the lane index operand is in the
7271     // right place.
7272     unsigned Spacing;
7273     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7274     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7275     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7276     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7277     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7278     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7279     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7280                                             Spacing));
7281     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7282                                             Spacing * 2));
7283     TmpInst.addOperand(Inst.getOperand(1)); // lane
7284     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7285     TmpInst.addOperand(Inst.getOperand(5));
7286     Inst = TmpInst;
7287     return true;
7288   }
7289 
7290   case ARM::VST4LNdWB_fixed_Asm_8:
7291   case ARM::VST4LNdWB_fixed_Asm_16:
7292   case ARM::VST4LNdWB_fixed_Asm_32:
7293   case ARM::VST4LNqWB_fixed_Asm_16:
7294   case ARM::VST4LNqWB_fixed_Asm_32: {
7295     MCInst TmpInst;
7296     // Shuffle the operands around so the lane index operand is in the
7297     // right place.
7298     unsigned Spacing;
7299     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7300     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7301     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7302     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7303     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7304     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7305     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7306                                             Spacing));
7307     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7308                                             Spacing * 2));
7309     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7310                                             Spacing * 3));
7311     TmpInst.addOperand(Inst.getOperand(1)); // lane
7312     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7313     TmpInst.addOperand(Inst.getOperand(5));
7314     Inst = TmpInst;
7315     return true;
7316   }
7317 
7318   case ARM::VST1LNdAsm_8:
7319   case ARM::VST1LNdAsm_16:
7320   case ARM::VST1LNdAsm_32: {
7321     MCInst TmpInst;
7322     // Shuffle the operands around so the lane index operand is in the
7323     // right place.
7324     unsigned Spacing;
7325     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7326     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7327     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7328     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7329     TmpInst.addOperand(Inst.getOperand(1)); // lane
7330     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7331     TmpInst.addOperand(Inst.getOperand(5));
7332     Inst = TmpInst;
7333     return true;
7334   }
7335 
7336   case ARM::VST2LNdAsm_8:
7337   case ARM::VST2LNdAsm_16:
7338   case ARM::VST2LNdAsm_32:
7339   case ARM::VST2LNqAsm_16:
7340   case ARM::VST2LNqAsm_32: {
7341     MCInst TmpInst;
7342     // Shuffle the operands around so the lane index operand is in the
7343     // right place.
7344     unsigned Spacing;
7345     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7346     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7347     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7348     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7349     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7350                                             Spacing));
7351     TmpInst.addOperand(Inst.getOperand(1)); // lane
7352     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7353     TmpInst.addOperand(Inst.getOperand(5));
7354     Inst = TmpInst;
7355     return true;
7356   }
7357 
7358   case ARM::VST3LNdAsm_8:
7359   case ARM::VST3LNdAsm_16:
7360   case ARM::VST3LNdAsm_32:
7361   case ARM::VST3LNqAsm_16:
7362   case ARM::VST3LNqAsm_32: {
7363     MCInst TmpInst;
7364     // Shuffle the operands around so the lane index operand is in the
7365     // right place.
7366     unsigned Spacing;
7367     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7368     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7369     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7370     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7371     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7372                                             Spacing));
7373     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7374                                             Spacing * 2));
7375     TmpInst.addOperand(Inst.getOperand(1)); // lane
7376     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7377     TmpInst.addOperand(Inst.getOperand(5));
7378     Inst = TmpInst;
7379     return true;
7380   }
7381 
7382   case ARM::VST4LNdAsm_8:
7383   case ARM::VST4LNdAsm_16:
7384   case ARM::VST4LNdAsm_32:
7385   case ARM::VST4LNqAsm_16:
7386   case ARM::VST4LNqAsm_32: {
7387     MCInst TmpInst;
7388     // Shuffle the operands around so the lane index operand is in the
7389     // right place.
7390     unsigned Spacing;
7391     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7392     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7393     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7394     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7395     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7396                                             Spacing));
7397     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7398                                             Spacing * 2));
7399     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7400                                             Spacing * 3));
7401     TmpInst.addOperand(Inst.getOperand(1)); // lane
7402     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7403     TmpInst.addOperand(Inst.getOperand(5));
7404     Inst = TmpInst;
7405     return true;
7406   }
7407 
7408   // Handle NEON VLD complex aliases.
7409   case ARM::VLD1LNdWB_register_Asm_8:
7410   case ARM::VLD1LNdWB_register_Asm_16:
7411   case ARM::VLD1LNdWB_register_Asm_32: {
7412     MCInst TmpInst;
7413     // Shuffle the operands around so the lane index operand is in the
7414     // right place.
7415     unsigned Spacing;
7416     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7417     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7418     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7419     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7420     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7421     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7422     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7423     TmpInst.addOperand(Inst.getOperand(1)); // lane
7424     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7425     TmpInst.addOperand(Inst.getOperand(6));
7426     Inst = TmpInst;
7427     return true;
7428   }
7429 
7430   case ARM::VLD2LNdWB_register_Asm_8:
7431   case ARM::VLD2LNdWB_register_Asm_16:
7432   case ARM::VLD2LNdWB_register_Asm_32:
7433   case ARM::VLD2LNqWB_register_Asm_16:
7434   case ARM::VLD2LNqWB_register_Asm_32: {
7435     MCInst TmpInst;
7436     // Shuffle the operands around so the lane index operand is in the
7437     // right place.
7438     unsigned Spacing;
7439     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7440     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7441     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7442                                             Spacing));
7443     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7444     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7445     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7446     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7447     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7448     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7449                                             Spacing));
7450     TmpInst.addOperand(Inst.getOperand(1)); // lane
7451     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7452     TmpInst.addOperand(Inst.getOperand(6));
7453     Inst = TmpInst;
7454     return true;
7455   }
7456 
7457   case ARM::VLD3LNdWB_register_Asm_8:
7458   case ARM::VLD3LNdWB_register_Asm_16:
7459   case ARM::VLD3LNdWB_register_Asm_32:
7460   case ARM::VLD3LNqWB_register_Asm_16:
7461   case ARM::VLD3LNqWB_register_Asm_32: {
7462     MCInst TmpInst;
7463     // Shuffle the operands around so the lane index operand is in the
7464     // right place.
7465     unsigned Spacing;
7466     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7467     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7468     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7469                                             Spacing));
7470     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7471                                             Spacing * 2));
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(Inst.getOperand(1)); // lane
7482     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7483     TmpInst.addOperand(Inst.getOperand(6));
7484     Inst = TmpInst;
7485     return true;
7486   }
7487 
7488   case ARM::VLD4LNdWB_register_Asm_8:
7489   case ARM::VLD4LNdWB_register_Asm_16:
7490   case ARM::VLD4LNdWB_register_Asm_32:
7491   case ARM::VLD4LNqWB_register_Asm_16:
7492   case ARM::VLD4LNqWB_register_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(MCOperand::createReg(Inst.getOperand(0).getReg() +
7500                                             Spacing));
7501     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7502                                             Spacing * 2));
7503     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7504                                             Spacing * 3));
7505     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7506     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7507     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7508     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7509     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7510     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7511                                             Spacing));
7512     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7513                                             Spacing * 2));
7514     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7515                                             Spacing * 3));
7516     TmpInst.addOperand(Inst.getOperand(1)); // lane
7517     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7518     TmpInst.addOperand(Inst.getOperand(6));
7519     Inst = TmpInst;
7520     return true;
7521   }
7522 
7523   case ARM::VLD1LNdWB_fixed_Asm_8:
7524   case ARM::VLD1LNdWB_fixed_Asm_16:
7525   case ARM::VLD1LNdWB_fixed_Asm_32: {
7526     MCInst TmpInst;
7527     // Shuffle the operands around so the lane index operand is in the
7528     // right place.
7529     unsigned Spacing;
7530     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7531     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7532     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7533     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7534     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7535     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7536     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7537     TmpInst.addOperand(Inst.getOperand(1)); // lane
7538     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7539     TmpInst.addOperand(Inst.getOperand(5));
7540     Inst = TmpInst;
7541     return true;
7542   }
7543 
7544   case ARM::VLD2LNdWB_fixed_Asm_8:
7545   case ARM::VLD2LNdWB_fixed_Asm_16:
7546   case ARM::VLD2LNdWB_fixed_Asm_32:
7547   case ARM::VLD2LNqWB_fixed_Asm_16:
7548   case ARM::VLD2LNqWB_fixed_Asm_32: {
7549     MCInst TmpInst;
7550     // Shuffle the operands around so the lane index operand is in the
7551     // right place.
7552     unsigned Spacing;
7553     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7554     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7555     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7556                                             Spacing));
7557     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7558     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7559     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7560     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7561     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7562     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7563                                             Spacing));
7564     TmpInst.addOperand(Inst.getOperand(1)); // lane
7565     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7566     TmpInst.addOperand(Inst.getOperand(5));
7567     Inst = TmpInst;
7568     return true;
7569   }
7570 
7571   case ARM::VLD3LNdWB_fixed_Asm_8:
7572   case ARM::VLD3LNdWB_fixed_Asm_16:
7573   case ARM::VLD3LNdWB_fixed_Asm_32:
7574   case ARM::VLD3LNqWB_fixed_Asm_16:
7575   case ARM::VLD3LNqWB_fixed_Asm_32: {
7576     MCInst TmpInst;
7577     // Shuffle the operands around so the lane index operand is in the
7578     // right place.
7579     unsigned Spacing;
7580     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7581     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7582     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7583                                             Spacing));
7584     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7585                                             Spacing * 2));
7586     TmpInst.addOperand(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(Inst.getOperand(1)); // lane
7596     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7597     TmpInst.addOperand(Inst.getOperand(5));
7598     Inst = TmpInst;
7599     return true;
7600   }
7601 
7602   case ARM::VLD4LNdWB_fixed_Asm_8:
7603   case ARM::VLD4LNdWB_fixed_Asm_16:
7604   case ARM::VLD4LNdWB_fixed_Asm_32:
7605   case ARM::VLD4LNqWB_fixed_Asm_16:
7606   case ARM::VLD4LNqWB_fixed_Asm_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(MCOperand::createReg(Inst.getOperand(0).getReg() +
7614                                             Spacing));
7615     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7616                                             Spacing * 2));
7617     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7618                                             Spacing * 3));
7619     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7620     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7621     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7622     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7623     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7624     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7625                                             Spacing));
7626     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7627                                             Spacing * 2));
7628     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7629                                             Spacing * 3));
7630     TmpInst.addOperand(Inst.getOperand(1)); // lane
7631     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7632     TmpInst.addOperand(Inst.getOperand(5));
7633     Inst = TmpInst;
7634     return true;
7635   }
7636 
7637   case ARM::VLD1LNdAsm_8:
7638   case ARM::VLD1LNdAsm_16:
7639   case ARM::VLD1LNdAsm_32: {
7640     MCInst TmpInst;
7641     // Shuffle the operands around so the lane index operand is in the
7642     // right place.
7643     unsigned Spacing;
7644     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7645     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7646     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7647     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7648     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7649     TmpInst.addOperand(Inst.getOperand(1)); // lane
7650     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7651     TmpInst.addOperand(Inst.getOperand(5));
7652     Inst = TmpInst;
7653     return true;
7654   }
7655 
7656   case ARM::VLD2LNdAsm_8:
7657   case ARM::VLD2LNdAsm_16:
7658   case ARM::VLD2LNdAsm_32:
7659   case ARM::VLD2LNqAsm_16:
7660   case ARM::VLD2LNqAsm_32: {
7661     MCInst TmpInst;
7662     // Shuffle the operands around so the lane index operand is in the
7663     // right place.
7664     unsigned Spacing;
7665     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7666     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7667     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7668                                             Spacing));
7669     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7670     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7671     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7672     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7673                                             Spacing));
7674     TmpInst.addOperand(Inst.getOperand(1)); // lane
7675     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7676     TmpInst.addOperand(Inst.getOperand(5));
7677     Inst = TmpInst;
7678     return true;
7679   }
7680 
7681   case ARM::VLD3LNdAsm_8:
7682   case ARM::VLD3LNdAsm_16:
7683   case ARM::VLD3LNdAsm_32:
7684   case ARM::VLD3LNqAsm_16:
7685   case ARM::VLD3LNqAsm_32: {
7686     MCInst TmpInst;
7687     // Shuffle the operands around so the lane index operand is in the
7688     // right place.
7689     unsigned Spacing;
7690     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7691     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7692     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7693                                             Spacing));
7694     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7695                                             Spacing * 2));
7696     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7697     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7698     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7699     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7700                                             Spacing));
7701     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7702                                             Spacing * 2));
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   case ARM::VLD4LNdAsm_8:
7711   case ARM::VLD4LNdAsm_16:
7712   case ARM::VLD4LNdAsm_32:
7713   case ARM::VLD4LNqAsm_16:
7714   case ARM::VLD4LNqAsm_32: {
7715     MCInst TmpInst;
7716     // Shuffle the operands around so the lane index operand is in the
7717     // right place.
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(MCOperand::createReg(Inst.getOperand(0).getReg() +
7726                                             Spacing * 3));
7727     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7728     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7729     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7730     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7731                                             Spacing));
7732     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7733                                             Spacing * 2));
7734     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7735                                             Spacing * 3));
7736     TmpInst.addOperand(Inst.getOperand(1)); // lane
7737     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7738     TmpInst.addOperand(Inst.getOperand(5));
7739     Inst = TmpInst;
7740     return true;
7741   }
7742 
7743   // VLD3DUP single 3-element structure to all lanes instructions.
7744   case ARM::VLD3DUPdAsm_8:
7745   case ARM::VLD3DUPdAsm_16:
7746   case ARM::VLD3DUPdAsm_32:
7747   case ARM::VLD3DUPqAsm_8:
7748   case ARM::VLD3DUPqAsm_16:
7749   case ARM::VLD3DUPqAsm_32: {
7750     MCInst TmpInst;
7751     unsigned Spacing;
7752     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7753     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7754     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7755                                             Spacing));
7756     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7757                                             Spacing * 2));
7758     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7759     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7760     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7761     TmpInst.addOperand(Inst.getOperand(4));
7762     Inst = TmpInst;
7763     return true;
7764   }
7765 
7766   case ARM::VLD3DUPdWB_fixed_Asm_8:
7767   case ARM::VLD3DUPdWB_fixed_Asm_16:
7768   case ARM::VLD3DUPdWB_fixed_Asm_32:
7769   case ARM::VLD3DUPqWB_fixed_Asm_8:
7770   case ARM::VLD3DUPqWB_fixed_Asm_16:
7771   case ARM::VLD3DUPqWB_fixed_Asm_32: {
7772     MCInst TmpInst;
7773     unsigned Spacing;
7774     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7775     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7776     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7777                                             Spacing));
7778     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7779                                             Spacing * 2));
7780     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7781     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7782     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7783     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7784     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7785     TmpInst.addOperand(Inst.getOperand(4));
7786     Inst = TmpInst;
7787     return true;
7788   }
7789 
7790   case ARM::VLD3DUPdWB_register_Asm_8:
7791   case ARM::VLD3DUPdWB_register_Asm_16:
7792   case ARM::VLD3DUPdWB_register_Asm_32:
7793   case ARM::VLD3DUPqWB_register_Asm_8:
7794   case ARM::VLD3DUPqWB_register_Asm_16:
7795   case ARM::VLD3DUPqWB_register_Asm_32: {
7796     MCInst TmpInst;
7797     unsigned Spacing;
7798     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7799     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7800     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7801                                             Spacing));
7802     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7803                                             Spacing * 2));
7804     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7805     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7806     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7807     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7808     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7809     TmpInst.addOperand(Inst.getOperand(5));
7810     Inst = TmpInst;
7811     return true;
7812   }
7813 
7814   // VLD3 multiple 3-element structure instructions.
7815   case ARM::VLD3dAsm_8:
7816   case ARM::VLD3dAsm_16:
7817   case ARM::VLD3dAsm_32:
7818   case ARM::VLD3qAsm_8:
7819   case ARM::VLD3qAsm_16:
7820   case ARM::VLD3qAsm_32: {
7821     MCInst TmpInst;
7822     unsigned Spacing;
7823     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7824     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7825     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7826                                             Spacing));
7827     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7828                                             Spacing * 2));
7829     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7830     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7831     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7832     TmpInst.addOperand(Inst.getOperand(4));
7833     Inst = TmpInst;
7834     return true;
7835   }
7836 
7837   case ARM::VLD3dWB_fixed_Asm_8:
7838   case ARM::VLD3dWB_fixed_Asm_16:
7839   case ARM::VLD3dWB_fixed_Asm_32:
7840   case ARM::VLD3qWB_fixed_Asm_8:
7841   case ARM::VLD3qWB_fixed_Asm_16:
7842   case ARM::VLD3qWB_fixed_Asm_32: {
7843     MCInst TmpInst;
7844     unsigned Spacing;
7845     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7846     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7847     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7848                                             Spacing));
7849     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7850                                             Spacing * 2));
7851     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7852     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7853     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7854     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7855     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7856     TmpInst.addOperand(Inst.getOperand(4));
7857     Inst = TmpInst;
7858     return true;
7859   }
7860 
7861   case ARM::VLD3dWB_register_Asm_8:
7862   case ARM::VLD3dWB_register_Asm_16:
7863   case ARM::VLD3dWB_register_Asm_32:
7864   case ARM::VLD3qWB_register_Asm_8:
7865   case ARM::VLD3qWB_register_Asm_16:
7866   case ARM::VLD3qWB_register_Asm_32: {
7867     MCInst TmpInst;
7868     unsigned Spacing;
7869     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7870     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7871     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7872                                             Spacing));
7873     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7874                                             Spacing * 2));
7875     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7876     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7877     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7878     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7879     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7880     TmpInst.addOperand(Inst.getOperand(5));
7881     Inst = TmpInst;
7882     return true;
7883   }
7884 
7885   // VLD4DUP single 3-element structure to all lanes instructions.
7886   case ARM::VLD4DUPdAsm_8:
7887   case ARM::VLD4DUPdAsm_16:
7888   case ARM::VLD4DUPdAsm_32:
7889   case ARM::VLD4DUPqAsm_8:
7890   case ARM::VLD4DUPqAsm_16:
7891   case ARM::VLD4DUPqAsm_32: {
7892     MCInst TmpInst;
7893     unsigned Spacing;
7894     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7895     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7896     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7897                                             Spacing));
7898     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7899                                             Spacing * 2));
7900     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7901                                             Spacing * 3));
7902     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7903     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7904     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7905     TmpInst.addOperand(Inst.getOperand(4));
7906     Inst = TmpInst;
7907     return true;
7908   }
7909 
7910   case ARM::VLD4DUPdWB_fixed_Asm_8:
7911   case ARM::VLD4DUPdWB_fixed_Asm_16:
7912   case ARM::VLD4DUPdWB_fixed_Asm_32:
7913   case ARM::VLD4DUPqWB_fixed_Asm_8:
7914   case ARM::VLD4DUPqWB_fixed_Asm_16:
7915   case ARM::VLD4DUPqWB_fixed_Asm_32: {
7916     MCInst TmpInst;
7917     unsigned Spacing;
7918     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7919     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7920     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7921                                             Spacing));
7922     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7923                                             Spacing * 2));
7924     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7925                                             Spacing * 3));
7926     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7927     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7928     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7929     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7930     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7931     TmpInst.addOperand(Inst.getOperand(4));
7932     Inst = TmpInst;
7933     return true;
7934   }
7935 
7936   case ARM::VLD4DUPdWB_register_Asm_8:
7937   case ARM::VLD4DUPdWB_register_Asm_16:
7938   case ARM::VLD4DUPdWB_register_Asm_32:
7939   case ARM::VLD4DUPqWB_register_Asm_8:
7940   case ARM::VLD4DUPqWB_register_Asm_16:
7941   case ARM::VLD4DUPqWB_register_Asm_32: {
7942     MCInst TmpInst;
7943     unsigned Spacing;
7944     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7945     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7946     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7947                                             Spacing));
7948     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7949                                             Spacing * 2));
7950     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7951                                             Spacing * 3));
7952     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7953     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7954     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7955     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7956     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7957     TmpInst.addOperand(Inst.getOperand(5));
7958     Inst = TmpInst;
7959     return true;
7960   }
7961 
7962   // VLD4 multiple 4-element structure instructions.
7963   case ARM::VLD4dAsm_8:
7964   case ARM::VLD4dAsm_16:
7965   case ARM::VLD4dAsm_32:
7966   case ARM::VLD4qAsm_8:
7967   case ARM::VLD4qAsm_16:
7968   case ARM::VLD4qAsm_32: {
7969     MCInst TmpInst;
7970     unsigned Spacing;
7971     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7972     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7973     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7974                                             Spacing));
7975     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7976                                             Spacing * 2));
7977     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7978                                             Spacing * 3));
7979     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7980     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7981     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7982     TmpInst.addOperand(Inst.getOperand(4));
7983     Inst = TmpInst;
7984     return true;
7985   }
7986 
7987   case ARM::VLD4dWB_fixed_Asm_8:
7988   case ARM::VLD4dWB_fixed_Asm_16:
7989   case ARM::VLD4dWB_fixed_Asm_32:
7990   case ARM::VLD4qWB_fixed_Asm_8:
7991   case ARM::VLD4qWB_fixed_Asm_16:
7992   case ARM::VLD4qWB_fixed_Asm_32: {
7993     MCInst TmpInst;
7994     unsigned Spacing;
7995     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7996     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7997     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7998                                             Spacing));
7999     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8000                                             Spacing * 2));
8001     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8002                                             Spacing * 3));
8003     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8004     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8005     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8006     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8007     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8008     TmpInst.addOperand(Inst.getOperand(4));
8009     Inst = TmpInst;
8010     return true;
8011   }
8012 
8013   case ARM::VLD4dWB_register_Asm_8:
8014   case ARM::VLD4dWB_register_Asm_16:
8015   case ARM::VLD4dWB_register_Asm_32:
8016   case ARM::VLD4qWB_register_Asm_8:
8017   case ARM::VLD4qWB_register_Asm_16:
8018   case ARM::VLD4qWB_register_Asm_32: {
8019     MCInst TmpInst;
8020     unsigned Spacing;
8021     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8022     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8023     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8024                                             Spacing));
8025     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8026                                             Spacing * 2));
8027     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8028                                             Spacing * 3));
8029     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8030     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8031     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8032     TmpInst.addOperand(Inst.getOperand(3)); // Rm
8033     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8034     TmpInst.addOperand(Inst.getOperand(5));
8035     Inst = TmpInst;
8036     return true;
8037   }
8038 
8039   // VST3 multiple 3-element structure instructions.
8040   case ARM::VST3dAsm_8:
8041   case ARM::VST3dAsm_16:
8042   case ARM::VST3dAsm_32:
8043   case ARM::VST3qAsm_8:
8044   case ARM::VST3qAsm_16:
8045   case ARM::VST3qAsm_32: {
8046     MCInst TmpInst;
8047     unsigned Spacing;
8048     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8049     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8050     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8051     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8052     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8053                                             Spacing));
8054     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8055                                             Spacing * 2));
8056     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8057     TmpInst.addOperand(Inst.getOperand(4));
8058     Inst = TmpInst;
8059     return true;
8060   }
8061 
8062   case ARM::VST3dWB_fixed_Asm_8:
8063   case ARM::VST3dWB_fixed_Asm_16:
8064   case ARM::VST3dWB_fixed_Asm_32:
8065   case ARM::VST3qWB_fixed_Asm_8:
8066   case ARM::VST3qWB_fixed_Asm_16:
8067   case ARM::VST3qWB_fixed_Asm_32: {
8068     MCInst TmpInst;
8069     unsigned Spacing;
8070     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8071     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8072     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8073     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8074     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8075     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8076     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8077                                             Spacing));
8078     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8079                                             Spacing * 2));
8080     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8081     TmpInst.addOperand(Inst.getOperand(4));
8082     Inst = TmpInst;
8083     return true;
8084   }
8085 
8086   case ARM::VST3dWB_register_Asm_8:
8087   case ARM::VST3dWB_register_Asm_16:
8088   case ARM::VST3dWB_register_Asm_32:
8089   case ARM::VST3qWB_register_Asm_8:
8090   case ARM::VST3qWB_register_Asm_16:
8091   case ARM::VST3qWB_register_Asm_32: {
8092     MCInst TmpInst;
8093     unsigned Spacing;
8094     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8095     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8096     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8097     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8098     TmpInst.addOperand(Inst.getOperand(3)); // Rm
8099     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8100     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8101                                             Spacing));
8102     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8103                                             Spacing * 2));
8104     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8105     TmpInst.addOperand(Inst.getOperand(5));
8106     Inst = TmpInst;
8107     return true;
8108   }
8109 
8110   // VST4 multiple 3-element structure instructions.
8111   case ARM::VST4dAsm_8:
8112   case ARM::VST4dAsm_16:
8113   case ARM::VST4dAsm_32:
8114   case ARM::VST4qAsm_8:
8115   case ARM::VST4qAsm_16:
8116   case ARM::VST4qAsm_32: {
8117     MCInst TmpInst;
8118     unsigned Spacing;
8119     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8120     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8121     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8122     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8123     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8124                                             Spacing));
8125     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8126                                             Spacing * 2));
8127     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8128                                             Spacing * 3));
8129     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8130     TmpInst.addOperand(Inst.getOperand(4));
8131     Inst = TmpInst;
8132     return true;
8133   }
8134 
8135   case ARM::VST4dWB_fixed_Asm_8:
8136   case ARM::VST4dWB_fixed_Asm_16:
8137   case ARM::VST4dWB_fixed_Asm_32:
8138   case ARM::VST4qWB_fixed_Asm_8:
8139   case ARM::VST4qWB_fixed_Asm_16:
8140   case ARM::VST4qWB_fixed_Asm_32: {
8141     MCInst TmpInst;
8142     unsigned Spacing;
8143     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8144     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8145     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8146     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8147     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8148     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8149     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8150                                             Spacing));
8151     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8152                                             Spacing * 2));
8153     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8154                                             Spacing * 3));
8155     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8156     TmpInst.addOperand(Inst.getOperand(4));
8157     Inst = TmpInst;
8158     return true;
8159   }
8160 
8161   case ARM::VST4dWB_register_Asm_8:
8162   case ARM::VST4dWB_register_Asm_16:
8163   case ARM::VST4dWB_register_Asm_32:
8164   case ARM::VST4qWB_register_Asm_8:
8165   case ARM::VST4qWB_register_Asm_16:
8166   case ARM::VST4qWB_register_Asm_32: {
8167     MCInst TmpInst;
8168     unsigned Spacing;
8169     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8170     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8171     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8172     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8173     TmpInst.addOperand(Inst.getOperand(3)); // Rm
8174     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8175     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8176                                             Spacing));
8177     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8178                                             Spacing * 2));
8179     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8180                                             Spacing * 3));
8181     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8182     TmpInst.addOperand(Inst.getOperand(5));
8183     Inst = TmpInst;
8184     return true;
8185   }
8186 
8187   // Handle encoding choice for the shift-immediate instructions.
8188   case ARM::t2LSLri:
8189   case ARM::t2LSRri:
8190   case ARM::t2ASRri:
8191     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8192         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8193         Inst.getOperand(5).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
8194         !HasWideQualifier) {
8195       unsigned NewOpc;
8196       switch (Inst.getOpcode()) {
8197       default: llvm_unreachable("unexpected opcode");
8198       case ARM::t2LSLri: NewOpc = ARM::tLSLri; break;
8199       case ARM::t2LSRri: NewOpc = ARM::tLSRri; break;
8200       case ARM::t2ASRri: NewOpc = ARM::tASRri; break;
8201       }
8202       // The Thumb1 operands aren't in the same order. Awesome, eh?
8203       MCInst TmpInst;
8204       TmpInst.setOpcode(NewOpc);
8205       TmpInst.addOperand(Inst.getOperand(0));
8206       TmpInst.addOperand(Inst.getOperand(5));
8207       TmpInst.addOperand(Inst.getOperand(1));
8208       TmpInst.addOperand(Inst.getOperand(2));
8209       TmpInst.addOperand(Inst.getOperand(3));
8210       TmpInst.addOperand(Inst.getOperand(4));
8211       Inst = TmpInst;
8212       return true;
8213     }
8214     return false;
8215 
8216   // Handle the Thumb2 mode MOV complex aliases.
8217   case ARM::t2MOVsr:
8218   case ARM::t2MOVSsr: {
8219     // Which instruction to expand to depends on the CCOut operand and
8220     // whether we're in an IT block if the register operands are low
8221     // registers.
8222     bool isNarrow = false;
8223     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8224         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8225         isARMLowRegister(Inst.getOperand(2).getReg()) &&
8226         Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() &&
8227         inITBlock() == (Inst.getOpcode() == ARM::t2MOVsr) &&
8228         !HasWideQualifier)
8229       isNarrow = true;
8230     MCInst TmpInst;
8231     unsigned newOpc;
8232     switch(ARM_AM::getSORegShOp(Inst.getOperand(3).getImm())) {
8233     default: llvm_unreachable("unexpected opcode!");
8234     case ARM_AM::asr: newOpc = isNarrow ? ARM::tASRrr : ARM::t2ASRrr; break;
8235     case ARM_AM::lsr: newOpc = isNarrow ? ARM::tLSRrr : ARM::t2LSRrr; break;
8236     case ARM_AM::lsl: newOpc = isNarrow ? ARM::tLSLrr : ARM::t2LSLrr; break;
8237     case ARM_AM::ror: newOpc = isNarrow ? ARM::tROR   : ARM::t2RORrr; break;
8238     }
8239     TmpInst.setOpcode(newOpc);
8240     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8241     if (isNarrow)
8242       TmpInst.addOperand(MCOperand::createReg(
8243           Inst.getOpcode() == ARM::t2MOVSsr ? ARM::CPSR : 0));
8244     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8245     TmpInst.addOperand(Inst.getOperand(2)); // Rm
8246     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8247     TmpInst.addOperand(Inst.getOperand(5));
8248     if (!isNarrow)
8249       TmpInst.addOperand(MCOperand::createReg(
8250           Inst.getOpcode() == ARM::t2MOVSsr ? ARM::CPSR : 0));
8251     Inst = TmpInst;
8252     return true;
8253   }
8254   case ARM::t2MOVsi:
8255   case ARM::t2MOVSsi: {
8256     // Which instruction to expand to depends on the CCOut operand and
8257     // whether we're in an IT block if the register operands are low
8258     // registers.
8259     bool isNarrow = false;
8260     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8261         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8262         inITBlock() == (Inst.getOpcode() == ARM::t2MOVsi) &&
8263         !HasWideQualifier)
8264       isNarrow = true;
8265     MCInst TmpInst;
8266     unsigned newOpc;
8267     unsigned Shift = ARM_AM::getSORegShOp(Inst.getOperand(2).getImm());
8268     unsigned Amount = ARM_AM::getSORegOffset(Inst.getOperand(2).getImm());
8269     bool isMov = false;
8270     // MOV rd, rm, LSL #0 is actually a MOV instruction
8271     if (Shift == ARM_AM::lsl && Amount == 0) {
8272       isMov = true;
8273       // The 16-bit encoding of MOV rd, rm, LSL #N is explicitly encoding T2 of
8274       // MOV (register) in the ARMv8-A and ARMv8-M manuals, and immediate 0 is
8275       // unpredictable in an IT block so the 32-bit encoding T3 has to be used
8276       // instead.
8277       if (inITBlock()) {
8278         isNarrow = false;
8279       }
8280       newOpc = isNarrow ? ARM::tMOVSr : ARM::t2MOVr;
8281     } else {
8282       switch(Shift) {
8283       default: llvm_unreachable("unexpected opcode!");
8284       case ARM_AM::asr: newOpc = isNarrow ? ARM::tASRri : ARM::t2ASRri; break;
8285       case ARM_AM::lsr: newOpc = isNarrow ? ARM::tLSRri : ARM::t2LSRri; break;
8286       case ARM_AM::lsl: newOpc = isNarrow ? ARM::tLSLri : ARM::t2LSLri; break;
8287       case ARM_AM::ror: newOpc = ARM::t2RORri; isNarrow = false; break;
8288       case ARM_AM::rrx: isNarrow = false; newOpc = ARM::t2RRX; break;
8289       }
8290     }
8291     if (Amount == 32) Amount = 0;
8292     TmpInst.setOpcode(newOpc);
8293     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8294     if (isNarrow && !isMov)
8295       TmpInst.addOperand(MCOperand::createReg(
8296           Inst.getOpcode() == ARM::t2MOVSsi ? ARM::CPSR : 0));
8297     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8298     if (newOpc != ARM::t2RRX && !isMov)
8299       TmpInst.addOperand(MCOperand::createImm(Amount));
8300     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8301     TmpInst.addOperand(Inst.getOperand(4));
8302     if (!isNarrow)
8303       TmpInst.addOperand(MCOperand::createReg(
8304           Inst.getOpcode() == ARM::t2MOVSsi ? ARM::CPSR : 0));
8305     Inst = TmpInst;
8306     return true;
8307   }
8308   // Handle the ARM mode MOV complex aliases.
8309   case ARM::ASRr:
8310   case ARM::LSRr:
8311   case ARM::LSLr:
8312   case ARM::RORr: {
8313     ARM_AM::ShiftOpc ShiftTy;
8314     switch(Inst.getOpcode()) {
8315     default: llvm_unreachable("unexpected opcode!");
8316     case ARM::ASRr: ShiftTy = ARM_AM::asr; break;
8317     case ARM::LSRr: ShiftTy = ARM_AM::lsr; break;
8318     case ARM::LSLr: ShiftTy = ARM_AM::lsl; break;
8319     case ARM::RORr: ShiftTy = ARM_AM::ror; break;
8320     }
8321     unsigned Shifter = ARM_AM::getSORegOpc(ShiftTy, 0);
8322     MCInst TmpInst;
8323     TmpInst.setOpcode(ARM::MOVsr);
8324     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8325     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8326     TmpInst.addOperand(Inst.getOperand(2)); // Rm
8327     TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
8328     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8329     TmpInst.addOperand(Inst.getOperand(4));
8330     TmpInst.addOperand(Inst.getOperand(5)); // cc_out
8331     Inst = TmpInst;
8332     return true;
8333   }
8334   case ARM::ASRi:
8335   case ARM::LSRi:
8336   case ARM::LSLi:
8337   case ARM::RORi: {
8338     ARM_AM::ShiftOpc ShiftTy;
8339     switch(Inst.getOpcode()) {
8340     default: llvm_unreachable("unexpected opcode!");
8341     case ARM::ASRi: ShiftTy = ARM_AM::asr; break;
8342     case ARM::LSRi: ShiftTy = ARM_AM::lsr; break;
8343     case ARM::LSLi: ShiftTy = ARM_AM::lsl; break;
8344     case ARM::RORi: ShiftTy = ARM_AM::ror; break;
8345     }
8346     // A shift by zero is a plain MOVr, not a MOVsi.
8347     unsigned Amt = Inst.getOperand(2).getImm();
8348     unsigned Opc = Amt == 0 ? ARM::MOVr : ARM::MOVsi;
8349     // A shift by 32 should be encoded as 0 when permitted
8350     if (Amt == 32 && (ShiftTy == ARM_AM::lsr || ShiftTy == ARM_AM::asr))
8351       Amt = 0;
8352     unsigned Shifter = ARM_AM::getSORegOpc(ShiftTy, Amt);
8353     MCInst TmpInst;
8354     TmpInst.setOpcode(Opc);
8355     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8356     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8357     if (Opc == ARM::MOVsi)
8358       TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
8359     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8360     TmpInst.addOperand(Inst.getOperand(4));
8361     TmpInst.addOperand(Inst.getOperand(5)); // cc_out
8362     Inst = TmpInst;
8363     return true;
8364   }
8365   case ARM::RRXi: {
8366     unsigned Shifter = ARM_AM::getSORegOpc(ARM_AM::rrx, 0);
8367     MCInst TmpInst;
8368     TmpInst.setOpcode(ARM::MOVsi);
8369     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8370     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8371     TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
8372     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8373     TmpInst.addOperand(Inst.getOperand(3));
8374     TmpInst.addOperand(Inst.getOperand(4)); // cc_out
8375     Inst = TmpInst;
8376     return true;
8377   }
8378   case ARM::t2LDMIA_UPD: {
8379     // If this is a load of a single register, then we should use
8380     // a post-indexed LDR instruction instead, per the ARM ARM.
8381     if (Inst.getNumOperands() != 5)
8382       return false;
8383     MCInst TmpInst;
8384     TmpInst.setOpcode(ARM::t2LDR_POST);
8385     TmpInst.addOperand(Inst.getOperand(4)); // Rt
8386     TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8387     TmpInst.addOperand(Inst.getOperand(1)); // Rn
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   case ARM::t2STMDB_UPD: {
8395     // If this is a store of a single register, then we should use
8396     // a pre-indexed STR instruction instead, per the ARM ARM.
8397     if (Inst.getNumOperands() != 5)
8398       return false;
8399     MCInst TmpInst;
8400     TmpInst.setOpcode(ARM::t2STR_PRE);
8401     TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8402     TmpInst.addOperand(Inst.getOperand(4)); // Rt
8403     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8404     TmpInst.addOperand(MCOperand::createImm(-4));
8405     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8406     TmpInst.addOperand(Inst.getOperand(3));
8407     Inst = TmpInst;
8408     return true;
8409   }
8410   case ARM::LDMIA_UPD:
8411     // If this is a load of a single register via a 'pop', then we should use
8412     // a post-indexed LDR instruction instead, per the ARM ARM.
8413     if (static_cast<ARMOperand &>(*Operands[0]).getToken() == "pop" &&
8414         Inst.getNumOperands() == 5) {
8415       MCInst TmpInst;
8416       TmpInst.setOpcode(ARM::LDR_POST_IMM);
8417       TmpInst.addOperand(Inst.getOperand(4)); // Rt
8418       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8419       TmpInst.addOperand(Inst.getOperand(1)); // Rn
8420       TmpInst.addOperand(MCOperand::createReg(0));  // am2offset
8421       TmpInst.addOperand(MCOperand::createImm(4));
8422       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8423       TmpInst.addOperand(Inst.getOperand(3));
8424       Inst = TmpInst;
8425       return true;
8426     }
8427     break;
8428   case ARM::STMDB_UPD:
8429     // If this is a store of a single register via a 'push', then we should use
8430     // a pre-indexed STR instruction instead, per the ARM ARM.
8431     if (static_cast<ARMOperand &>(*Operands[0]).getToken() == "push" &&
8432         Inst.getNumOperands() == 5) {
8433       MCInst TmpInst;
8434       TmpInst.setOpcode(ARM::STR_PRE_IMM);
8435       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8436       TmpInst.addOperand(Inst.getOperand(4)); // Rt
8437       TmpInst.addOperand(Inst.getOperand(1)); // addrmode_imm12
8438       TmpInst.addOperand(MCOperand::createImm(-4));
8439       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8440       TmpInst.addOperand(Inst.getOperand(3));
8441       Inst = TmpInst;
8442     }
8443     break;
8444   case ARM::t2ADDri12:
8445     // If the immediate fits for encoding T3 (t2ADDri) and the generic "add"
8446     // mnemonic was used (not "addw"), encoding T3 is preferred.
8447     if (static_cast<ARMOperand &>(*Operands[0]).getToken() != "add" ||
8448         ARM_AM::getT2SOImmVal(Inst.getOperand(2).getImm()) == -1)
8449       break;
8450     Inst.setOpcode(ARM::t2ADDri);
8451     Inst.addOperand(MCOperand::createReg(0)); // cc_out
8452     break;
8453   case ARM::t2SUBri12:
8454     // If the immediate fits for encoding T3 (t2SUBri) and the generic "sub"
8455     // mnemonic was used (not "subw"), encoding T3 is preferred.
8456     if (static_cast<ARMOperand &>(*Operands[0]).getToken() != "sub" ||
8457         ARM_AM::getT2SOImmVal(Inst.getOperand(2).getImm()) == -1)
8458       break;
8459     Inst.setOpcode(ARM::t2SUBri);
8460     Inst.addOperand(MCOperand::createReg(0)); // cc_out
8461     break;
8462   case ARM::tADDi8:
8463     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
8464     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
8465     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
8466     // to encoding T1 if <Rd> is omitted."
8467     if ((unsigned)Inst.getOperand(3).getImm() < 8 && Operands.size() == 6) {
8468       Inst.setOpcode(ARM::tADDi3);
8469       return true;
8470     }
8471     break;
8472   case ARM::tSUBi8:
8473     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
8474     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
8475     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
8476     // to encoding T1 if <Rd> is omitted."
8477     if ((unsigned)Inst.getOperand(3).getImm() < 8 && Operands.size() == 6) {
8478       Inst.setOpcode(ARM::tSUBi3);
8479       return true;
8480     }
8481     break;
8482   case ARM::t2ADDri:
8483   case ARM::t2SUBri: {
8484     // If the destination and first source operand are the same, and
8485     // the flags are compatible with the current IT status, use encoding T2
8486     // instead of T3. For compatibility with the system 'as'. Make sure the
8487     // wide encoding wasn't explicit.
8488     if (Inst.getOperand(0).getReg() != Inst.getOperand(1).getReg() ||
8489         !isARMLowRegister(Inst.getOperand(0).getReg()) ||
8490         (Inst.getOperand(2).isImm() &&
8491          (unsigned)Inst.getOperand(2).getImm() > 255) ||
8492         Inst.getOperand(5).getReg() != (inITBlock() ? 0 : ARM::CPSR) ||
8493         HasWideQualifier)
8494       break;
8495     MCInst TmpInst;
8496     TmpInst.setOpcode(Inst.getOpcode() == ARM::t2ADDri ?
8497                       ARM::tADDi8 : ARM::tSUBi8);
8498     TmpInst.addOperand(Inst.getOperand(0));
8499     TmpInst.addOperand(Inst.getOperand(5));
8500     TmpInst.addOperand(Inst.getOperand(0));
8501     TmpInst.addOperand(Inst.getOperand(2));
8502     TmpInst.addOperand(Inst.getOperand(3));
8503     TmpInst.addOperand(Inst.getOperand(4));
8504     Inst = TmpInst;
8505     return true;
8506   }
8507   case ARM::t2ADDrr: {
8508     // If the destination and first source operand are the same, and
8509     // there's no setting of the flags, use encoding T2 instead of T3.
8510     // Note that this is only for ADD, not SUB. This mirrors the system
8511     // 'as' behaviour.  Also take advantage of ADD being commutative.
8512     // Make sure the wide encoding wasn't explicit.
8513     bool Swap = false;
8514     auto DestReg = Inst.getOperand(0).getReg();
8515     bool Transform = DestReg == Inst.getOperand(1).getReg();
8516     if (!Transform && DestReg == Inst.getOperand(2).getReg()) {
8517       Transform = true;
8518       Swap = true;
8519     }
8520     if (!Transform ||
8521         Inst.getOperand(5).getReg() != 0 ||
8522         HasWideQualifier)
8523       break;
8524     MCInst TmpInst;
8525     TmpInst.setOpcode(ARM::tADDhirr);
8526     TmpInst.addOperand(Inst.getOperand(0));
8527     TmpInst.addOperand(Inst.getOperand(0));
8528     TmpInst.addOperand(Inst.getOperand(Swap ? 1 : 2));
8529     TmpInst.addOperand(Inst.getOperand(3));
8530     TmpInst.addOperand(Inst.getOperand(4));
8531     Inst = TmpInst;
8532     return true;
8533   }
8534   case ARM::tADDrSP:
8535     // If the non-SP source operand and the destination operand are not the
8536     // same, we need to use the 32-bit encoding if it's available.
8537     if (Inst.getOperand(0).getReg() != Inst.getOperand(2).getReg()) {
8538       Inst.setOpcode(ARM::t2ADDrr);
8539       Inst.addOperand(MCOperand::createReg(0)); // cc_out
8540       return true;
8541     }
8542     break;
8543   case ARM::tB:
8544     // A Thumb conditional branch outside of an IT block is a tBcc.
8545     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock()) {
8546       Inst.setOpcode(ARM::tBcc);
8547       return true;
8548     }
8549     break;
8550   case ARM::t2B:
8551     // A Thumb2 conditional branch outside of an IT block is a t2Bcc.
8552     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock()){
8553       Inst.setOpcode(ARM::t2Bcc);
8554       return true;
8555     }
8556     break;
8557   case ARM::t2Bcc:
8558     // If the conditional is AL or we're in an IT block, we really want t2B.
8559     if (Inst.getOperand(1).getImm() == ARMCC::AL || inITBlock()) {
8560       Inst.setOpcode(ARM::t2B);
8561       return true;
8562     }
8563     break;
8564   case ARM::tBcc:
8565     // If the conditional is AL, we really want tB.
8566     if (Inst.getOperand(1).getImm() == ARMCC::AL) {
8567       Inst.setOpcode(ARM::tB);
8568       return true;
8569     }
8570     break;
8571   case ARM::tLDMIA: {
8572     // If the register list contains any high registers, or if the writeback
8573     // doesn't match what tLDMIA can do, we need to use the 32-bit encoding
8574     // instead if we're in Thumb2. Otherwise, this should have generated
8575     // an error in validateInstruction().
8576     unsigned Rn = Inst.getOperand(0).getReg();
8577     bool hasWritebackToken =
8578         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
8579          static_cast<ARMOperand &>(*Operands[3]).getToken() == "!");
8580     bool listContainsBase;
8581     if (checkLowRegisterList(Inst, 3, Rn, 0, listContainsBase) ||
8582         (!listContainsBase && !hasWritebackToken) ||
8583         (listContainsBase && hasWritebackToken)) {
8584       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
8585       assert(isThumbTwo());
8586       Inst.setOpcode(hasWritebackToken ? ARM::t2LDMIA_UPD : ARM::t2LDMIA);
8587       // If we're switching to the updating version, we need to insert
8588       // the writeback tied operand.
8589       if (hasWritebackToken)
8590         Inst.insert(Inst.begin(),
8591                     MCOperand::createReg(Inst.getOperand(0).getReg()));
8592       return true;
8593     }
8594     break;
8595   }
8596   case ARM::tSTMIA_UPD: {
8597     // If the register list contains any high registers, we need to use
8598     // the 32-bit encoding instead if we're in Thumb2. Otherwise, this
8599     // should have generated an error in validateInstruction().
8600     unsigned Rn = Inst.getOperand(0).getReg();
8601     bool listContainsBase;
8602     if (checkLowRegisterList(Inst, 4, Rn, 0, listContainsBase)) {
8603       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
8604       assert(isThumbTwo());
8605       Inst.setOpcode(ARM::t2STMIA_UPD);
8606       return true;
8607     }
8608     break;
8609   }
8610   case ARM::tPOP: {
8611     bool listContainsBase;
8612     // If the register list contains any high registers, we need to use
8613     // the 32-bit encoding instead if we're in Thumb2. Otherwise, this
8614     // should have generated an error in validateInstruction().
8615     if (!checkLowRegisterList(Inst, 2, 0, ARM::PC, listContainsBase))
8616       return false;
8617     assert(isThumbTwo());
8618     Inst.setOpcode(ARM::t2LDMIA_UPD);
8619     // Add the base register and writeback operands.
8620     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8621     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8622     return true;
8623   }
8624   case ARM::tPUSH: {
8625     bool listContainsBase;
8626     if (!checkLowRegisterList(Inst, 2, 0, ARM::LR, listContainsBase))
8627       return false;
8628     assert(isThumbTwo());
8629     Inst.setOpcode(ARM::t2STMDB_UPD);
8630     // Add the base register and writeback operands.
8631     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8632     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8633     return true;
8634   }
8635   case ARM::t2MOVi:
8636     // If we can use the 16-bit encoding and the user didn't explicitly
8637     // request the 32-bit variant, transform it here.
8638     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8639         (Inst.getOperand(1).isImm() &&
8640          (unsigned)Inst.getOperand(1).getImm() <= 255) &&
8641         Inst.getOperand(4).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
8642         !HasWideQualifier) {
8643       // The operands aren't in the same order for tMOVi8...
8644       MCInst TmpInst;
8645       TmpInst.setOpcode(ARM::tMOVi8);
8646       TmpInst.addOperand(Inst.getOperand(0));
8647       TmpInst.addOperand(Inst.getOperand(4));
8648       TmpInst.addOperand(Inst.getOperand(1));
8649       TmpInst.addOperand(Inst.getOperand(2));
8650       TmpInst.addOperand(Inst.getOperand(3));
8651       Inst = TmpInst;
8652       return true;
8653     }
8654     break;
8655 
8656   case ARM::t2MOVr:
8657     // If we can use the 16-bit encoding and the user didn't explicitly
8658     // request the 32-bit variant, transform it here.
8659     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8660         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8661         Inst.getOperand(2).getImm() == ARMCC::AL &&
8662         Inst.getOperand(4).getReg() == ARM::CPSR &&
8663         !HasWideQualifier) {
8664       // The operands aren't the same for tMOV[S]r... (no cc_out)
8665       MCInst TmpInst;
8666       TmpInst.setOpcode(Inst.getOperand(4).getReg() ? ARM::tMOVSr : ARM::tMOVr);
8667       TmpInst.addOperand(Inst.getOperand(0));
8668       TmpInst.addOperand(Inst.getOperand(1));
8669       TmpInst.addOperand(Inst.getOperand(2));
8670       TmpInst.addOperand(Inst.getOperand(3));
8671       Inst = TmpInst;
8672       return true;
8673     }
8674     break;
8675 
8676   case ARM::t2SXTH:
8677   case ARM::t2SXTB:
8678   case ARM::t2UXTH:
8679   case ARM::t2UXTB:
8680     // If we can use the 16-bit encoding and the user didn't explicitly
8681     // request the 32-bit variant, transform it here.
8682     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8683         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8684         Inst.getOperand(2).getImm() == 0 &&
8685         !HasWideQualifier) {
8686       unsigned NewOpc;
8687       switch (Inst.getOpcode()) {
8688       default: llvm_unreachable("Illegal opcode!");
8689       case ARM::t2SXTH: NewOpc = ARM::tSXTH; break;
8690       case ARM::t2SXTB: NewOpc = ARM::tSXTB; break;
8691       case ARM::t2UXTH: NewOpc = ARM::tUXTH; break;
8692       case ARM::t2UXTB: NewOpc = ARM::tUXTB; break;
8693       }
8694       // The operands aren't the same for thumb1 (no rotate operand).
8695       MCInst TmpInst;
8696       TmpInst.setOpcode(NewOpc);
8697       TmpInst.addOperand(Inst.getOperand(0));
8698       TmpInst.addOperand(Inst.getOperand(1));
8699       TmpInst.addOperand(Inst.getOperand(3));
8700       TmpInst.addOperand(Inst.getOperand(4));
8701       Inst = TmpInst;
8702       return true;
8703     }
8704     break;
8705 
8706   case ARM::MOVsi: {
8707     ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(Inst.getOperand(2).getImm());
8708     // rrx shifts and asr/lsr of #32 is encoded as 0
8709     if (SOpc == ARM_AM::rrx || SOpc == ARM_AM::asr || SOpc == ARM_AM::lsr)
8710       return false;
8711     if (ARM_AM::getSORegOffset(Inst.getOperand(2).getImm()) == 0) {
8712       // Shifting by zero is accepted as a vanilla 'MOVr'
8713       MCInst TmpInst;
8714       TmpInst.setOpcode(ARM::MOVr);
8715       TmpInst.addOperand(Inst.getOperand(0));
8716       TmpInst.addOperand(Inst.getOperand(1));
8717       TmpInst.addOperand(Inst.getOperand(3));
8718       TmpInst.addOperand(Inst.getOperand(4));
8719       TmpInst.addOperand(Inst.getOperand(5));
8720       Inst = TmpInst;
8721       return true;
8722     }
8723     return false;
8724   }
8725   case ARM::ANDrsi:
8726   case ARM::ORRrsi:
8727   case ARM::EORrsi:
8728   case ARM::BICrsi:
8729   case ARM::SUBrsi:
8730   case ARM::ADDrsi: {
8731     unsigned newOpc;
8732     ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(Inst.getOperand(3).getImm());
8733     if (SOpc == ARM_AM::rrx) return false;
8734     switch (Inst.getOpcode()) {
8735     default: llvm_unreachable("unexpected opcode!");
8736     case ARM::ANDrsi: newOpc = ARM::ANDrr; break;
8737     case ARM::ORRrsi: newOpc = ARM::ORRrr; break;
8738     case ARM::EORrsi: newOpc = ARM::EORrr; break;
8739     case ARM::BICrsi: newOpc = ARM::BICrr; break;
8740     case ARM::SUBrsi: newOpc = ARM::SUBrr; break;
8741     case ARM::ADDrsi: newOpc = ARM::ADDrr; break;
8742     }
8743     // If the shift is by zero, use the non-shifted instruction definition.
8744     // The exception is for right shifts, where 0 == 32
8745     if (ARM_AM::getSORegOffset(Inst.getOperand(3).getImm()) == 0 &&
8746         !(SOpc == ARM_AM::lsr || SOpc == ARM_AM::asr)) {
8747       MCInst TmpInst;
8748       TmpInst.setOpcode(newOpc);
8749       TmpInst.addOperand(Inst.getOperand(0));
8750       TmpInst.addOperand(Inst.getOperand(1));
8751       TmpInst.addOperand(Inst.getOperand(2));
8752       TmpInst.addOperand(Inst.getOperand(4));
8753       TmpInst.addOperand(Inst.getOperand(5));
8754       TmpInst.addOperand(Inst.getOperand(6));
8755       Inst = TmpInst;
8756       return true;
8757     }
8758     return false;
8759   }
8760   case ARM::ITasm:
8761   case ARM::t2IT: {
8762     MCOperand &MO = Inst.getOperand(1);
8763     unsigned Mask = MO.getImm();
8764     ARMCC::CondCodes Cond = ARMCC::CondCodes(Inst.getOperand(0).getImm());
8765 
8766     // Set up the IT block state according to the IT instruction we just
8767     // matched.
8768     assert(!inITBlock() && "nested IT blocks?!");
8769     startExplicitITBlock(Cond, Mask);
8770     MO.setImm(getITMaskEncoding());
8771     break;
8772   }
8773   case ARM::t2LSLrr:
8774   case ARM::t2LSRrr:
8775   case ARM::t2ASRrr:
8776   case ARM::t2SBCrr:
8777   case ARM::t2RORrr:
8778   case ARM::t2BICrr:
8779     // Assemblers should use the narrow encodings of these instructions when permissible.
8780     if ((isARMLowRegister(Inst.getOperand(1).getReg()) &&
8781          isARMLowRegister(Inst.getOperand(2).getReg())) &&
8782         Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() &&
8783         Inst.getOperand(5).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
8784         !HasWideQualifier) {
8785       unsigned NewOpc;
8786       switch (Inst.getOpcode()) {
8787         default: llvm_unreachable("unexpected opcode");
8788         case ARM::t2LSLrr: NewOpc = ARM::tLSLrr; break;
8789         case ARM::t2LSRrr: NewOpc = ARM::tLSRrr; break;
8790         case ARM::t2ASRrr: NewOpc = ARM::tASRrr; break;
8791         case ARM::t2SBCrr: NewOpc = ARM::tSBC; break;
8792         case ARM::t2RORrr: NewOpc = ARM::tROR; break;
8793         case ARM::t2BICrr: NewOpc = ARM::tBIC; break;
8794       }
8795       MCInst TmpInst;
8796       TmpInst.setOpcode(NewOpc);
8797       TmpInst.addOperand(Inst.getOperand(0));
8798       TmpInst.addOperand(Inst.getOperand(5));
8799       TmpInst.addOperand(Inst.getOperand(1));
8800       TmpInst.addOperand(Inst.getOperand(2));
8801       TmpInst.addOperand(Inst.getOperand(3));
8802       TmpInst.addOperand(Inst.getOperand(4));
8803       Inst = TmpInst;
8804       return true;
8805     }
8806     return false;
8807 
8808   case ARM::t2ANDrr:
8809   case ARM::t2EORrr:
8810   case ARM::t2ADCrr:
8811   case ARM::t2ORRrr:
8812     // Assemblers should use the narrow encodings of these instructions when permissible.
8813     // These instructions are special in that they are commutable, so shorter encodings
8814     // are available more often.
8815     if ((isARMLowRegister(Inst.getOperand(1).getReg()) &&
8816          isARMLowRegister(Inst.getOperand(2).getReg())) &&
8817         (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() ||
8818          Inst.getOperand(0).getReg() == Inst.getOperand(2).getReg()) &&
8819         Inst.getOperand(5).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
8820         !HasWideQualifier) {
8821       unsigned NewOpc;
8822       switch (Inst.getOpcode()) {
8823         default: llvm_unreachable("unexpected opcode");
8824         case ARM::t2ADCrr: NewOpc = ARM::tADC; break;
8825         case ARM::t2ANDrr: NewOpc = ARM::tAND; break;
8826         case ARM::t2EORrr: NewOpc = ARM::tEOR; break;
8827         case ARM::t2ORRrr: NewOpc = ARM::tORR; break;
8828       }
8829       MCInst TmpInst;
8830       TmpInst.setOpcode(NewOpc);
8831       TmpInst.addOperand(Inst.getOperand(0));
8832       TmpInst.addOperand(Inst.getOperand(5));
8833       if (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg()) {
8834         TmpInst.addOperand(Inst.getOperand(1));
8835         TmpInst.addOperand(Inst.getOperand(2));
8836       } else {
8837         TmpInst.addOperand(Inst.getOperand(2));
8838         TmpInst.addOperand(Inst.getOperand(1));
8839       }
8840       TmpInst.addOperand(Inst.getOperand(3));
8841       TmpInst.addOperand(Inst.getOperand(4));
8842       Inst = TmpInst;
8843       return true;
8844     }
8845     return false;
8846   }
8847   return false;
8848 }
8849 
8850 unsigned ARMAsmParser::checkTargetMatchPredicate(MCInst &Inst) {
8851   // 16-bit thumb arithmetic instructions either require or preclude the 'S'
8852   // suffix depending on whether they're in an IT block or not.
8853   unsigned Opc = Inst.getOpcode();
8854   const MCInstrDesc &MCID = MII.get(Opc);
8855   if (MCID.TSFlags & ARMII::ThumbArithFlagSetting) {
8856     assert(MCID.hasOptionalDef() &&
8857            "optionally flag setting instruction missing optional def operand");
8858     assert(MCID.NumOperands == Inst.getNumOperands() &&
8859            "operand count mismatch!");
8860     // Find the optional-def operand (cc_out).
8861     unsigned OpNo;
8862     for (OpNo = 0;
8863          !MCID.OpInfo[OpNo].isOptionalDef() && OpNo < MCID.NumOperands;
8864          ++OpNo)
8865       ;
8866     // If we're parsing Thumb1, reject it completely.
8867     if (isThumbOne() && Inst.getOperand(OpNo).getReg() != ARM::CPSR)
8868       return Match_RequiresFlagSetting;
8869     // If we're parsing Thumb2, which form is legal depends on whether we're
8870     // in an IT block.
8871     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() != ARM::CPSR &&
8872         !inITBlock())
8873       return Match_RequiresITBlock;
8874     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() == ARM::CPSR &&
8875         inITBlock())
8876       return Match_RequiresNotITBlock;
8877     // LSL with zero immediate is not allowed in an IT block
8878     if (Opc == ARM::tLSLri && Inst.getOperand(3).getImm() == 0 && inITBlock())
8879       return Match_RequiresNotITBlock;
8880   } else if (isThumbOne()) {
8881     // Some high-register supporting Thumb1 encodings only allow both registers
8882     // to be from r0-r7 when in Thumb2.
8883     if (Opc == ARM::tADDhirr && !hasV6MOps() &&
8884         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8885         isARMLowRegister(Inst.getOperand(2).getReg()))
8886       return Match_RequiresThumb2;
8887     // Others only require ARMv6 or later.
8888     else if (Opc == ARM::tMOVr && !hasV6Ops() &&
8889              isARMLowRegister(Inst.getOperand(0).getReg()) &&
8890              isARMLowRegister(Inst.getOperand(1).getReg()))
8891       return Match_RequiresV6;
8892   }
8893 
8894   // Before ARMv8 the rules for when SP is allowed in t2MOVr are more complex
8895   // than the loop below can handle, so it uses the GPRnopc register class and
8896   // we do SP handling here.
8897   if (Opc == ARM::t2MOVr && !hasV8Ops())
8898   {
8899     // SP as both source and destination is not allowed
8900     if (Inst.getOperand(0).getReg() == ARM::SP &&
8901         Inst.getOperand(1).getReg() == ARM::SP)
8902       return Match_RequiresV8;
8903     // When flags-setting SP as either source or destination is not allowed
8904     if (Inst.getOperand(4).getReg() == ARM::CPSR &&
8905         (Inst.getOperand(0).getReg() == ARM::SP ||
8906          Inst.getOperand(1).getReg() == ARM::SP))
8907       return Match_RequiresV8;
8908   }
8909 
8910   // Use of SP for VMRS/VMSR is only allowed in ARM mode with the exception of
8911   // ARMv8-A.
8912   if ((Inst.getOpcode() == ARM::VMRS || Inst.getOpcode() == ARM::VMSR) &&
8913       Inst.getOperand(0).getReg() == ARM::SP && (isThumb() && !hasV8Ops()))
8914     return Match_InvalidOperand;
8915 
8916   for (unsigned I = 0; I < MCID.NumOperands; ++I)
8917     if (MCID.OpInfo[I].RegClass == ARM::rGPRRegClassID) {
8918       // rGPRRegClass excludes PC, and also excluded SP before ARMv8
8919       if ((Inst.getOperand(I).getReg() == ARM::SP) && !hasV8Ops())
8920         return Match_RequiresV8;
8921       else if (Inst.getOperand(I).getReg() == ARM::PC)
8922         return Match_InvalidOperand;
8923     }
8924 
8925   return Match_Success;
8926 }
8927 
8928 namespace llvm {
8929 
8930 template <> inline bool IsCPSRDead<MCInst>(const MCInst *Instr) {
8931   return true; // In an assembly source, no need to second-guess
8932 }
8933 
8934 } // end namespace llvm
8935 
8936 // Returns true if Inst is unpredictable if it is in and IT block, but is not
8937 // the last instruction in the block.
8938 bool ARMAsmParser::isITBlockTerminator(MCInst &Inst) const {
8939   const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
8940 
8941   // All branch & call instructions terminate IT blocks with the exception of
8942   // SVC.
8943   if (MCID.isTerminator() || (MCID.isCall() && Inst.getOpcode() != ARM::tSVC) ||
8944       MCID.isReturn() || MCID.isBranch() || MCID.isIndirectBranch())
8945     return true;
8946 
8947   // Any arithmetic instruction which writes to the PC also terminates the IT
8948   // block.
8949   for (unsigned OpIdx = 0; OpIdx < MCID.getNumDefs(); ++OpIdx) {
8950     MCOperand &Op = Inst.getOperand(OpIdx);
8951     if (Op.isReg() && Op.getReg() == ARM::PC)
8952       return true;
8953   }
8954 
8955   if (MCID.hasImplicitDefOfPhysReg(ARM::PC, MRI))
8956     return true;
8957 
8958   // Instructions with variable operand lists, which write to the variable
8959   // operands. We only care about Thumb instructions here, as ARM instructions
8960   // obviously can't be in an IT block.
8961   switch (Inst.getOpcode()) {
8962   case ARM::tLDMIA:
8963   case ARM::t2LDMIA:
8964   case ARM::t2LDMIA_UPD:
8965   case ARM::t2LDMDB:
8966   case ARM::t2LDMDB_UPD:
8967     if (listContainsReg(Inst, 3, ARM::PC))
8968       return true;
8969     break;
8970   case ARM::tPOP:
8971     if (listContainsReg(Inst, 2, ARM::PC))
8972       return true;
8973     break;
8974   }
8975 
8976   return false;
8977 }
8978 
8979 unsigned ARMAsmParser::MatchInstruction(OperandVector &Operands, MCInst &Inst,
8980                                           SmallVectorImpl<NearMissInfo> &NearMisses,
8981                                           bool MatchingInlineAsm,
8982                                           bool &EmitInITBlock,
8983                                           MCStreamer &Out) {
8984   // If we can't use an implicit IT block here, just match as normal.
8985   if (inExplicitITBlock() || !isThumbTwo() || !useImplicitITThumb())
8986     return MatchInstructionImpl(Operands, Inst, &NearMisses, MatchingInlineAsm);
8987 
8988   // Try to match the instruction in an extension of the current IT block (if
8989   // there is one).
8990   if (inImplicitITBlock()) {
8991     extendImplicitITBlock(ITState.Cond);
8992     if (MatchInstructionImpl(Operands, Inst, nullptr, MatchingInlineAsm) ==
8993             Match_Success) {
8994       // The match succeded, but we still have to check that the instruction is
8995       // valid in this implicit IT block.
8996       const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
8997       if (MCID.isPredicable()) {
8998         ARMCC::CondCodes InstCond =
8999             (ARMCC::CondCodes)Inst.getOperand(MCID.findFirstPredOperandIdx())
9000                 .getImm();
9001         ARMCC::CondCodes ITCond = currentITCond();
9002         if (InstCond == ITCond) {
9003           EmitInITBlock = true;
9004           return Match_Success;
9005         } else if (InstCond == ARMCC::getOppositeCondition(ITCond)) {
9006           invertCurrentITCondition();
9007           EmitInITBlock = true;
9008           return Match_Success;
9009         }
9010       }
9011     }
9012     rewindImplicitITPosition();
9013   }
9014 
9015   // Finish the current IT block, and try to match outside any IT block.
9016   flushPendingInstructions(Out);
9017   unsigned PlainMatchResult =
9018       MatchInstructionImpl(Operands, Inst, &NearMisses, MatchingInlineAsm);
9019   if (PlainMatchResult == Match_Success) {
9020     const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
9021     if (MCID.isPredicable()) {
9022       ARMCC::CondCodes InstCond =
9023           (ARMCC::CondCodes)Inst.getOperand(MCID.findFirstPredOperandIdx())
9024               .getImm();
9025       // Some forms of the branch instruction have their own condition code
9026       // fields, so can be conditionally executed without an IT block.
9027       if (Inst.getOpcode() == ARM::tBcc || Inst.getOpcode() == ARM::t2Bcc) {
9028         EmitInITBlock = false;
9029         return Match_Success;
9030       }
9031       if (InstCond == ARMCC::AL) {
9032         EmitInITBlock = false;
9033         return Match_Success;
9034       }
9035     } else {
9036       EmitInITBlock = false;
9037       return Match_Success;
9038     }
9039   }
9040 
9041   // Try to match in a new IT block. The matcher doesn't check the actual
9042   // condition, so we create an IT block with a dummy condition, and fix it up
9043   // once we know the actual condition.
9044   startImplicitITBlock();
9045   if (MatchInstructionImpl(Operands, Inst, nullptr, MatchingInlineAsm) ==
9046       Match_Success) {
9047     const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
9048     if (MCID.isPredicable()) {
9049       ITState.Cond =
9050           (ARMCC::CondCodes)Inst.getOperand(MCID.findFirstPredOperandIdx())
9051               .getImm();
9052       EmitInITBlock = true;
9053       return Match_Success;
9054     }
9055   }
9056   discardImplicitITBlock();
9057 
9058   // If none of these succeed, return the error we got when trying to match
9059   // outside any IT blocks.
9060   EmitInITBlock = false;
9061   return PlainMatchResult;
9062 }
9063 
9064 static std::string ARMMnemonicSpellCheck(StringRef S, uint64_t FBS,
9065                                          unsigned VariantID = 0);
9066 
9067 static const char *getSubtargetFeatureName(uint64_t Val);
9068 bool ARMAsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
9069                                            OperandVector &Operands,
9070                                            MCStreamer &Out, uint64_t &ErrorInfo,
9071                                            bool MatchingInlineAsm) {
9072   MCInst Inst;
9073   unsigned MatchResult;
9074   bool PendConditionalInstruction = false;
9075 
9076   SmallVector<NearMissInfo, 4> NearMisses;
9077   MatchResult = MatchInstruction(Operands, Inst, NearMisses, MatchingInlineAsm,
9078                                  PendConditionalInstruction, Out);
9079 
9080   switch (MatchResult) {
9081   case Match_Success:
9082     // Context sensitive operand constraints aren't handled by the matcher,
9083     // so check them here.
9084     if (validateInstruction(Inst, Operands)) {
9085       // Still progress the IT block, otherwise one wrong condition causes
9086       // nasty cascading errors.
9087       forwardITPosition();
9088       return true;
9089     }
9090 
9091     { // processInstruction() updates inITBlock state, we need to save it away
9092       bool wasInITBlock = inITBlock();
9093 
9094       // Some instructions need post-processing to, for example, tweak which
9095       // encoding is selected. Loop on it while changes happen so the
9096       // individual transformations can chain off each other. E.g.,
9097       // tPOP(r8)->t2LDMIA_UPD(sp,r8)->t2STR_POST(sp,r8)
9098       while (processInstruction(Inst, Operands, Out))
9099         ;
9100 
9101       // Only after the instruction is fully processed, we can validate it
9102       if (wasInITBlock && hasV8Ops() && isThumb() &&
9103           !isV8EligibleForIT(&Inst)) {
9104         Warning(IDLoc, "deprecated instruction in IT block");
9105       }
9106     }
9107 
9108     // Only move forward at the very end so that everything in validate
9109     // and process gets a consistent answer about whether we're in an IT
9110     // block.
9111     forwardITPosition();
9112 
9113     // ITasm is an ARM mode pseudo-instruction that just sets the ITblock and
9114     // doesn't actually encode.
9115     if (Inst.getOpcode() == ARM::ITasm)
9116       return false;
9117 
9118     Inst.setLoc(IDLoc);
9119     if (PendConditionalInstruction) {
9120       PendingConditionalInsts.push_back(Inst);
9121       if (isITBlockFull() || isITBlockTerminator(Inst))
9122         flushPendingInstructions(Out);
9123     } else {
9124       Out.EmitInstruction(Inst, getSTI());
9125     }
9126     return false;
9127   case Match_NearMisses:
9128     ReportNearMisses(NearMisses, IDLoc, Operands);
9129     return true;
9130   case Match_MnemonicFail: {
9131     uint64_t FBS = ComputeAvailableFeatures(getSTI().getFeatureBits());
9132     std::string Suggestion = ARMMnemonicSpellCheck(
9133       ((ARMOperand &)*Operands[0]).getToken(), FBS);
9134     return Error(IDLoc, "invalid instruction" + Suggestion,
9135                  ((ARMOperand &)*Operands[0]).getLocRange());
9136   }
9137   }
9138 
9139   llvm_unreachable("Implement any new match types added!");
9140 }
9141 
9142 /// parseDirective parses the arm specific directives
9143 bool ARMAsmParser::ParseDirective(AsmToken DirectiveID) {
9144   const MCObjectFileInfo::Environment Format =
9145     getContext().getObjectFileInfo()->getObjectFileType();
9146   bool IsMachO = Format == MCObjectFileInfo::IsMachO;
9147   bool IsCOFF = Format == MCObjectFileInfo::IsCOFF;
9148 
9149   StringRef IDVal = DirectiveID.getIdentifier();
9150   if (IDVal == ".word")
9151     parseLiteralValues(4, DirectiveID.getLoc());
9152   else if (IDVal == ".short" || IDVal == ".hword")
9153     parseLiteralValues(2, DirectiveID.getLoc());
9154   else if (IDVal == ".thumb")
9155     parseDirectiveThumb(DirectiveID.getLoc());
9156   else if (IDVal == ".arm")
9157     parseDirectiveARM(DirectiveID.getLoc());
9158   else if (IDVal == ".thumb_func")
9159     parseDirectiveThumbFunc(DirectiveID.getLoc());
9160   else if (IDVal == ".code")
9161     parseDirectiveCode(DirectiveID.getLoc());
9162   else if (IDVal == ".syntax")
9163     parseDirectiveSyntax(DirectiveID.getLoc());
9164   else if (IDVal == ".unreq")
9165     parseDirectiveUnreq(DirectiveID.getLoc());
9166   else if (IDVal == ".fnend")
9167     parseDirectiveFnEnd(DirectiveID.getLoc());
9168   else if (IDVal == ".cantunwind")
9169     parseDirectiveCantUnwind(DirectiveID.getLoc());
9170   else if (IDVal == ".personality")
9171     parseDirectivePersonality(DirectiveID.getLoc());
9172   else if (IDVal == ".handlerdata")
9173     parseDirectiveHandlerData(DirectiveID.getLoc());
9174   else if (IDVal == ".setfp")
9175     parseDirectiveSetFP(DirectiveID.getLoc());
9176   else if (IDVal == ".pad")
9177     parseDirectivePad(DirectiveID.getLoc());
9178   else if (IDVal == ".save")
9179     parseDirectiveRegSave(DirectiveID.getLoc(), false);
9180   else if (IDVal == ".vsave")
9181     parseDirectiveRegSave(DirectiveID.getLoc(), true);
9182   else if (IDVal == ".ltorg" || IDVal == ".pool")
9183     parseDirectiveLtorg(DirectiveID.getLoc());
9184   else if (IDVal == ".even")
9185     parseDirectiveEven(DirectiveID.getLoc());
9186   else if (IDVal == ".personalityindex")
9187     parseDirectivePersonalityIndex(DirectiveID.getLoc());
9188   else if (IDVal == ".unwind_raw")
9189     parseDirectiveUnwindRaw(DirectiveID.getLoc());
9190   else if (IDVal == ".movsp")
9191     parseDirectiveMovSP(DirectiveID.getLoc());
9192   else if (IDVal == ".arch_extension")
9193     parseDirectiveArchExtension(DirectiveID.getLoc());
9194   else if (IDVal == ".align")
9195     return parseDirectiveAlign(DirectiveID.getLoc()); // Use Generic on failure.
9196   else if (IDVal == ".thumb_set")
9197     parseDirectiveThumbSet(DirectiveID.getLoc());
9198   else if (!IsMachO && !IsCOFF) {
9199     if (IDVal == ".arch")
9200       parseDirectiveArch(DirectiveID.getLoc());
9201     else if (IDVal == ".cpu")
9202       parseDirectiveCPU(DirectiveID.getLoc());
9203     else if (IDVal == ".eabi_attribute")
9204       parseDirectiveEabiAttr(DirectiveID.getLoc());
9205     else if (IDVal == ".fpu")
9206       parseDirectiveFPU(DirectiveID.getLoc());
9207     else if (IDVal == ".fnstart")
9208       parseDirectiveFnStart(DirectiveID.getLoc());
9209     else if (IDVal == ".inst")
9210       parseDirectiveInst(DirectiveID.getLoc());
9211     else if (IDVal == ".inst.n")
9212       parseDirectiveInst(DirectiveID.getLoc(), 'n');
9213     else if (IDVal == ".inst.w")
9214       parseDirectiveInst(DirectiveID.getLoc(), 'w');
9215     else if (IDVal == ".object_arch")
9216       parseDirectiveObjectArch(DirectiveID.getLoc());
9217     else if (IDVal == ".tlsdescseq")
9218       parseDirectiveTLSDescSeq(DirectiveID.getLoc());
9219     else
9220       return true;
9221   } else
9222     return true;
9223   return false;
9224 }
9225 
9226 /// parseLiteralValues
9227 ///  ::= .hword expression [, expression]*
9228 ///  ::= .short expression [, expression]*
9229 ///  ::= .word expression [, expression]*
9230 bool ARMAsmParser::parseLiteralValues(unsigned Size, SMLoc L) {
9231   auto parseOne = [&]() -> bool {
9232     const MCExpr *Value;
9233     if (getParser().parseExpression(Value))
9234       return true;
9235     getParser().getStreamer().EmitValue(Value, Size, L);
9236     return false;
9237   };
9238   return (parseMany(parseOne));
9239 }
9240 
9241 /// parseDirectiveThumb
9242 ///  ::= .thumb
9243 bool ARMAsmParser::parseDirectiveThumb(SMLoc L) {
9244   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive") ||
9245       check(!hasThumb(), L, "target does not support Thumb mode"))
9246     return true;
9247 
9248   if (!isThumb())
9249     SwitchMode();
9250 
9251   getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
9252   return false;
9253 }
9254 
9255 /// parseDirectiveARM
9256 ///  ::= .arm
9257 bool ARMAsmParser::parseDirectiveARM(SMLoc L) {
9258   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive") ||
9259       check(!hasARM(), L, "target does not support ARM mode"))
9260     return true;
9261 
9262   if (isThumb())
9263     SwitchMode();
9264   getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
9265   return false;
9266 }
9267 
9268 void ARMAsmParser::onLabelParsed(MCSymbol *Symbol) {
9269   // We need to flush the current implicit IT block on a label, because it is
9270   // not legal to branch into an IT block.
9271   flushPendingInstructions(getStreamer());
9272   if (NextSymbolIsThumb) {
9273     getParser().getStreamer().EmitThumbFunc(Symbol);
9274     NextSymbolIsThumb = false;
9275   }
9276 }
9277 
9278 /// parseDirectiveThumbFunc
9279 ///  ::= .thumbfunc symbol_name
9280 bool ARMAsmParser::parseDirectiveThumbFunc(SMLoc L) {
9281   MCAsmParser &Parser = getParser();
9282   const auto Format = getContext().getObjectFileInfo()->getObjectFileType();
9283   bool IsMachO = Format == MCObjectFileInfo::IsMachO;
9284 
9285   // Darwin asm has (optionally) function name after .thumb_func direction
9286   // ELF doesn't
9287 
9288   if (IsMachO) {
9289     if (Parser.getTok().is(AsmToken::Identifier) ||
9290         Parser.getTok().is(AsmToken::String)) {
9291       MCSymbol *Func = getParser().getContext().getOrCreateSymbol(
9292           Parser.getTok().getIdentifier());
9293       getParser().getStreamer().EmitThumbFunc(Func);
9294       Parser.Lex();
9295       if (parseToken(AsmToken::EndOfStatement,
9296                      "unexpected token in '.thumb_func' directive"))
9297         return true;
9298       return false;
9299     }
9300   }
9301 
9302   if (parseToken(AsmToken::EndOfStatement,
9303                  "unexpected token in '.thumb_func' directive"))
9304     return true;
9305 
9306   NextSymbolIsThumb = true;
9307   return false;
9308 }
9309 
9310 /// parseDirectiveSyntax
9311 ///  ::= .syntax unified | divided
9312 bool ARMAsmParser::parseDirectiveSyntax(SMLoc L) {
9313   MCAsmParser &Parser = getParser();
9314   const AsmToken &Tok = Parser.getTok();
9315   if (Tok.isNot(AsmToken::Identifier)) {
9316     Error(L, "unexpected token in .syntax directive");
9317     return false;
9318   }
9319 
9320   StringRef Mode = Tok.getString();
9321   Parser.Lex();
9322   if (check(Mode == "divided" || Mode == "DIVIDED", L,
9323             "'.syntax divided' arm assembly not supported") ||
9324       check(Mode != "unified" && Mode != "UNIFIED", L,
9325             "unrecognized syntax mode in .syntax directive") ||
9326       parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
9327     return true;
9328 
9329   // TODO tell the MC streamer the mode
9330   // getParser().getStreamer().Emit???();
9331   return false;
9332 }
9333 
9334 /// parseDirectiveCode
9335 ///  ::= .code 16 | 32
9336 bool ARMAsmParser::parseDirectiveCode(SMLoc L) {
9337   MCAsmParser &Parser = getParser();
9338   const AsmToken &Tok = Parser.getTok();
9339   if (Tok.isNot(AsmToken::Integer))
9340     return Error(L, "unexpected token in .code directive");
9341   int64_t Val = Parser.getTok().getIntVal();
9342   if (Val != 16 && Val != 32) {
9343     Error(L, "invalid operand to .code directive");
9344     return false;
9345   }
9346   Parser.Lex();
9347 
9348   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
9349     return true;
9350 
9351   if (Val == 16) {
9352     if (!hasThumb())
9353       return Error(L, "target does not support Thumb mode");
9354 
9355     if (!isThumb())
9356       SwitchMode();
9357     getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
9358   } else {
9359     if (!hasARM())
9360       return Error(L, "target does not support ARM mode");
9361 
9362     if (isThumb())
9363       SwitchMode();
9364     getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
9365   }
9366 
9367   return false;
9368 }
9369 
9370 /// parseDirectiveReq
9371 ///  ::= name .req registername
9372 bool ARMAsmParser::parseDirectiveReq(StringRef Name, SMLoc L) {
9373   MCAsmParser &Parser = getParser();
9374   Parser.Lex(); // Eat the '.req' token.
9375   unsigned Reg;
9376   SMLoc SRegLoc, ERegLoc;
9377   if (check(ParseRegister(Reg, SRegLoc, ERegLoc), SRegLoc,
9378             "register name expected") ||
9379       parseToken(AsmToken::EndOfStatement,
9380                  "unexpected input in .req directive."))
9381     return true;
9382 
9383   if (RegisterReqs.insert(std::make_pair(Name, Reg)).first->second != Reg)
9384     return Error(SRegLoc,
9385                  "redefinition of '" + Name + "' does not match original.");
9386 
9387   return false;
9388 }
9389 
9390 /// parseDirectiveUneq
9391 ///  ::= .unreq registername
9392 bool ARMAsmParser::parseDirectiveUnreq(SMLoc L) {
9393   MCAsmParser &Parser = getParser();
9394   if (Parser.getTok().isNot(AsmToken::Identifier))
9395     return Error(L, "unexpected input in .unreq directive.");
9396   RegisterReqs.erase(Parser.getTok().getIdentifier().lower());
9397   Parser.Lex(); // Eat the identifier.
9398   if (parseToken(AsmToken::EndOfStatement,
9399                  "unexpected input in '.unreq' directive"))
9400     return true;
9401   return false;
9402 }
9403 
9404 // After changing arch/CPU, try to put the ARM/Thumb mode back to what it was
9405 // before, if supported by the new target, or emit mapping symbols for the mode
9406 // switch.
9407 void ARMAsmParser::FixModeAfterArchChange(bool WasThumb, SMLoc Loc) {
9408   if (WasThumb != isThumb()) {
9409     if (WasThumb && hasThumb()) {
9410       // Stay in Thumb mode
9411       SwitchMode();
9412     } else if (!WasThumb && hasARM()) {
9413       // Stay in ARM mode
9414       SwitchMode();
9415     } else {
9416       // Mode switch forced, because the new arch doesn't support the old mode.
9417       getParser().getStreamer().EmitAssemblerFlag(isThumb() ? MCAF_Code16
9418                                                             : MCAF_Code32);
9419       // Warn about the implcit mode switch. GAS does not switch modes here,
9420       // but instead stays in the old mode, reporting an error on any following
9421       // instructions as the mode does not exist on the target.
9422       Warning(Loc, Twine("new target does not support ") +
9423                        (WasThumb ? "thumb" : "arm") + " mode, switching to " +
9424                        (!WasThumb ? "thumb" : "arm") + " mode");
9425     }
9426   }
9427 }
9428 
9429 /// parseDirectiveArch
9430 ///  ::= .arch token
9431 bool ARMAsmParser::parseDirectiveArch(SMLoc L) {
9432   StringRef Arch = getParser().parseStringToEndOfStatement().trim();
9433   ARM::ArchKind ID = ARM::parseArch(Arch);
9434 
9435   if (ID == ARM::ArchKind::INVALID)
9436     return Error(L, "Unknown arch name");
9437 
9438   bool WasThumb = isThumb();
9439   Triple T;
9440   MCSubtargetInfo &STI = copySTI();
9441   STI.setDefaultFeatures("", ("+" + ARM::getArchName(ID)).str());
9442   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
9443   FixModeAfterArchChange(WasThumb, L);
9444 
9445   getTargetStreamer().emitArch(ID);
9446   return false;
9447 }
9448 
9449 /// parseDirectiveEabiAttr
9450 ///  ::= .eabi_attribute int, int [, "str"]
9451 ///  ::= .eabi_attribute Tag_name, int [, "str"]
9452 bool ARMAsmParser::parseDirectiveEabiAttr(SMLoc L) {
9453   MCAsmParser &Parser = getParser();
9454   int64_t Tag;
9455   SMLoc TagLoc;
9456   TagLoc = Parser.getTok().getLoc();
9457   if (Parser.getTok().is(AsmToken::Identifier)) {
9458     StringRef Name = Parser.getTok().getIdentifier();
9459     Tag = ARMBuildAttrs::AttrTypeFromString(Name);
9460     if (Tag == -1) {
9461       Error(TagLoc, "attribute name not recognised: " + Name);
9462       return false;
9463     }
9464     Parser.Lex();
9465   } else {
9466     const MCExpr *AttrExpr;
9467 
9468     TagLoc = Parser.getTok().getLoc();
9469     if (Parser.parseExpression(AttrExpr))
9470       return true;
9471 
9472     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(AttrExpr);
9473     if (check(!CE, TagLoc, "expected numeric constant"))
9474       return true;
9475 
9476     Tag = CE->getValue();
9477   }
9478 
9479   if (Parser.parseToken(AsmToken::Comma, "comma expected"))
9480     return true;
9481 
9482   StringRef StringValue = "";
9483   bool IsStringValue = false;
9484 
9485   int64_t IntegerValue = 0;
9486   bool IsIntegerValue = false;
9487 
9488   if (Tag == ARMBuildAttrs::CPU_raw_name || Tag == ARMBuildAttrs::CPU_name)
9489     IsStringValue = true;
9490   else if (Tag == ARMBuildAttrs::compatibility) {
9491     IsStringValue = true;
9492     IsIntegerValue = true;
9493   } else if (Tag < 32 || Tag % 2 == 0)
9494     IsIntegerValue = true;
9495   else if (Tag % 2 == 1)
9496     IsStringValue = true;
9497   else
9498     llvm_unreachable("invalid tag type");
9499 
9500   if (IsIntegerValue) {
9501     const MCExpr *ValueExpr;
9502     SMLoc ValueExprLoc = Parser.getTok().getLoc();
9503     if (Parser.parseExpression(ValueExpr))
9504       return true;
9505 
9506     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ValueExpr);
9507     if (!CE)
9508       return Error(ValueExprLoc, "expected numeric constant");
9509     IntegerValue = CE->getValue();
9510   }
9511 
9512   if (Tag == ARMBuildAttrs::compatibility) {
9513     if (Parser.parseToken(AsmToken::Comma, "comma expected"))
9514       return true;
9515   }
9516 
9517   if (IsStringValue) {
9518     if (Parser.getTok().isNot(AsmToken::String))
9519       return Error(Parser.getTok().getLoc(), "bad string constant");
9520 
9521     StringValue = Parser.getTok().getStringContents();
9522     Parser.Lex();
9523   }
9524 
9525   if (Parser.parseToken(AsmToken::EndOfStatement,
9526                         "unexpected token in '.eabi_attribute' directive"))
9527     return true;
9528 
9529   if (IsIntegerValue && IsStringValue) {
9530     assert(Tag == ARMBuildAttrs::compatibility);
9531     getTargetStreamer().emitIntTextAttribute(Tag, IntegerValue, StringValue);
9532   } else if (IsIntegerValue)
9533     getTargetStreamer().emitAttribute(Tag, IntegerValue);
9534   else if (IsStringValue)
9535     getTargetStreamer().emitTextAttribute(Tag, StringValue);
9536   return false;
9537 }
9538 
9539 /// parseDirectiveCPU
9540 ///  ::= .cpu str
9541 bool ARMAsmParser::parseDirectiveCPU(SMLoc L) {
9542   StringRef CPU = getParser().parseStringToEndOfStatement().trim();
9543   getTargetStreamer().emitTextAttribute(ARMBuildAttrs::CPU_name, CPU);
9544 
9545   // FIXME: This is using table-gen data, but should be moved to
9546   // ARMTargetParser once that is table-gen'd.
9547   if (!getSTI().isCPUStringValid(CPU))
9548     return Error(L, "Unknown CPU name");
9549 
9550   bool WasThumb = isThumb();
9551   MCSubtargetInfo &STI = copySTI();
9552   STI.setDefaultFeatures(CPU, "");
9553   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
9554   FixModeAfterArchChange(WasThumb, L);
9555 
9556   return false;
9557 }
9558 
9559 /// parseDirectiveFPU
9560 ///  ::= .fpu str
9561 bool ARMAsmParser::parseDirectiveFPU(SMLoc L) {
9562   SMLoc FPUNameLoc = getTok().getLoc();
9563   StringRef FPU = getParser().parseStringToEndOfStatement().trim();
9564 
9565   unsigned ID = ARM::parseFPU(FPU);
9566   std::vector<StringRef> Features;
9567   if (!ARM::getFPUFeatures(ID, Features))
9568     return Error(FPUNameLoc, "Unknown FPU name");
9569 
9570   MCSubtargetInfo &STI = copySTI();
9571   for (auto Feature : Features)
9572     STI.ApplyFeatureFlag(Feature);
9573   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
9574 
9575   getTargetStreamer().emitFPU(ID);
9576   return false;
9577 }
9578 
9579 /// parseDirectiveFnStart
9580 ///  ::= .fnstart
9581 bool ARMAsmParser::parseDirectiveFnStart(SMLoc L) {
9582   if (parseToken(AsmToken::EndOfStatement,
9583                  "unexpected token in '.fnstart' directive"))
9584     return true;
9585 
9586   if (UC.hasFnStart()) {
9587     Error(L, ".fnstart starts before the end of previous one");
9588     UC.emitFnStartLocNotes();
9589     return true;
9590   }
9591 
9592   // Reset the unwind directives parser state
9593   UC.reset();
9594 
9595   getTargetStreamer().emitFnStart();
9596 
9597   UC.recordFnStart(L);
9598   return false;
9599 }
9600 
9601 /// parseDirectiveFnEnd
9602 ///  ::= .fnend
9603 bool ARMAsmParser::parseDirectiveFnEnd(SMLoc L) {
9604   if (parseToken(AsmToken::EndOfStatement,
9605                  "unexpected token in '.fnend' directive"))
9606     return true;
9607   // Check the ordering of unwind directives
9608   if (!UC.hasFnStart())
9609     return Error(L, ".fnstart must precede .fnend directive");
9610 
9611   // Reset the unwind directives parser state
9612   getTargetStreamer().emitFnEnd();
9613 
9614   UC.reset();
9615   return false;
9616 }
9617 
9618 /// parseDirectiveCantUnwind
9619 ///  ::= .cantunwind
9620 bool ARMAsmParser::parseDirectiveCantUnwind(SMLoc L) {
9621   if (parseToken(AsmToken::EndOfStatement,
9622                  "unexpected token in '.cantunwind' directive"))
9623     return true;
9624 
9625   UC.recordCantUnwind(L);
9626   // Check the ordering of unwind directives
9627   if (check(!UC.hasFnStart(), L, ".fnstart must precede .cantunwind directive"))
9628     return true;
9629 
9630   if (UC.hasHandlerData()) {
9631     Error(L, ".cantunwind can't be used with .handlerdata directive");
9632     UC.emitHandlerDataLocNotes();
9633     return true;
9634   }
9635   if (UC.hasPersonality()) {
9636     Error(L, ".cantunwind can't be used with .personality directive");
9637     UC.emitPersonalityLocNotes();
9638     return true;
9639   }
9640 
9641   getTargetStreamer().emitCantUnwind();
9642   return false;
9643 }
9644 
9645 /// parseDirectivePersonality
9646 ///  ::= .personality name
9647 bool ARMAsmParser::parseDirectivePersonality(SMLoc L) {
9648   MCAsmParser &Parser = getParser();
9649   bool HasExistingPersonality = UC.hasPersonality();
9650 
9651   // Parse the name of the personality routine
9652   if (Parser.getTok().isNot(AsmToken::Identifier))
9653     return Error(L, "unexpected input in .personality directive.");
9654   StringRef Name(Parser.getTok().getIdentifier());
9655   Parser.Lex();
9656 
9657   if (parseToken(AsmToken::EndOfStatement,
9658                  "unexpected token in '.personality' directive"))
9659     return true;
9660 
9661   UC.recordPersonality(L);
9662 
9663   // Check the ordering of unwind directives
9664   if (!UC.hasFnStart())
9665     return Error(L, ".fnstart must precede .personality directive");
9666   if (UC.cantUnwind()) {
9667     Error(L, ".personality can't be used with .cantunwind directive");
9668     UC.emitCantUnwindLocNotes();
9669     return true;
9670   }
9671   if (UC.hasHandlerData()) {
9672     Error(L, ".personality must precede .handlerdata directive");
9673     UC.emitHandlerDataLocNotes();
9674     return true;
9675   }
9676   if (HasExistingPersonality) {
9677     Error(L, "multiple personality directives");
9678     UC.emitPersonalityLocNotes();
9679     return true;
9680   }
9681 
9682   MCSymbol *PR = getParser().getContext().getOrCreateSymbol(Name);
9683   getTargetStreamer().emitPersonality(PR);
9684   return false;
9685 }
9686 
9687 /// parseDirectiveHandlerData
9688 ///  ::= .handlerdata
9689 bool ARMAsmParser::parseDirectiveHandlerData(SMLoc L) {
9690   if (parseToken(AsmToken::EndOfStatement,
9691                  "unexpected token in '.handlerdata' directive"))
9692     return true;
9693 
9694   UC.recordHandlerData(L);
9695   // Check the ordering of unwind directives
9696   if (!UC.hasFnStart())
9697     return Error(L, ".fnstart must precede .personality directive");
9698   if (UC.cantUnwind()) {
9699     Error(L, ".handlerdata can't be used with .cantunwind directive");
9700     UC.emitCantUnwindLocNotes();
9701     return true;
9702   }
9703 
9704   getTargetStreamer().emitHandlerData();
9705   return false;
9706 }
9707 
9708 /// parseDirectiveSetFP
9709 ///  ::= .setfp fpreg, spreg [, offset]
9710 bool ARMAsmParser::parseDirectiveSetFP(SMLoc L) {
9711   MCAsmParser &Parser = getParser();
9712   // Check the ordering of unwind directives
9713   if (check(!UC.hasFnStart(), L, ".fnstart must precede .setfp directive") ||
9714       check(UC.hasHandlerData(), L,
9715             ".setfp must precede .handlerdata directive"))
9716     return true;
9717 
9718   // Parse fpreg
9719   SMLoc FPRegLoc = Parser.getTok().getLoc();
9720   int FPReg = tryParseRegister();
9721 
9722   if (check(FPReg == -1, FPRegLoc, "frame pointer register expected") ||
9723       Parser.parseToken(AsmToken::Comma, "comma expected"))
9724     return true;
9725 
9726   // Parse spreg
9727   SMLoc SPRegLoc = Parser.getTok().getLoc();
9728   int SPReg = tryParseRegister();
9729   if (check(SPReg == -1, SPRegLoc, "stack pointer register expected") ||
9730       check(SPReg != ARM::SP && SPReg != UC.getFPReg(), SPRegLoc,
9731             "register should be either $sp or the latest fp register"))
9732     return true;
9733 
9734   // Update the frame pointer register
9735   UC.saveFPReg(FPReg);
9736 
9737   // Parse offset
9738   int64_t Offset = 0;
9739   if (Parser.parseOptionalToken(AsmToken::Comma)) {
9740     if (Parser.getTok().isNot(AsmToken::Hash) &&
9741         Parser.getTok().isNot(AsmToken::Dollar))
9742       return Error(Parser.getTok().getLoc(), "'#' expected");
9743     Parser.Lex(); // skip hash token.
9744 
9745     const MCExpr *OffsetExpr;
9746     SMLoc ExLoc = Parser.getTok().getLoc();
9747     SMLoc EndLoc;
9748     if (getParser().parseExpression(OffsetExpr, EndLoc))
9749       return Error(ExLoc, "malformed setfp offset");
9750     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
9751     if (check(!CE, ExLoc, "setfp offset must be an immediate"))
9752       return true;
9753     Offset = CE->getValue();
9754   }
9755 
9756   if (Parser.parseToken(AsmToken::EndOfStatement))
9757     return true;
9758 
9759   getTargetStreamer().emitSetFP(static_cast<unsigned>(FPReg),
9760                                 static_cast<unsigned>(SPReg), Offset);
9761   return false;
9762 }
9763 
9764 /// parseDirective
9765 ///  ::= .pad offset
9766 bool ARMAsmParser::parseDirectivePad(SMLoc L) {
9767   MCAsmParser &Parser = getParser();
9768   // Check the ordering of unwind directives
9769   if (!UC.hasFnStart())
9770     return Error(L, ".fnstart must precede .pad directive");
9771   if (UC.hasHandlerData())
9772     return Error(L, ".pad must precede .handlerdata directive");
9773 
9774   // Parse the offset
9775   if (Parser.getTok().isNot(AsmToken::Hash) &&
9776       Parser.getTok().isNot(AsmToken::Dollar))
9777     return Error(Parser.getTok().getLoc(), "'#' expected");
9778   Parser.Lex(); // skip hash token.
9779 
9780   const MCExpr *OffsetExpr;
9781   SMLoc ExLoc = Parser.getTok().getLoc();
9782   SMLoc EndLoc;
9783   if (getParser().parseExpression(OffsetExpr, EndLoc))
9784     return Error(ExLoc, "malformed pad offset");
9785   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
9786   if (!CE)
9787     return Error(ExLoc, "pad offset must be an immediate");
9788 
9789   if (parseToken(AsmToken::EndOfStatement,
9790                  "unexpected token in '.pad' directive"))
9791     return true;
9792 
9793   getTargetStreamer().emitPad(CE->getValue());
9794   return false;
9795 }
9796 
9797 /// parseDirectiveRegSave
9798 ///  ::= .save  { registers }
9799 ///  ::= .vsave { registers }
9800 bool ARMAsmParser::parseDirectiveRegSave(SMLoc L, bool IsVector) {
9801   // Check the ordering of unwind directives
9802   if (!UC.hasFnStart())
9803     return Error(L, ".fnstart must precede .save or .vsave directives");
9804   if (UC.hasHandlerData())
9805     return Error(L, ".save or .vsave must precede .handlerdata directive");
9806 
9807   // RAII object to make sure parsed operands are deleted.
9808   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> Operands;
9809 
9810   // Parse the register list
9811   if (parseRegisterList(Operands) ||
9812       parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
9813     return true;
9814   ARMOperand &Op = (ARMOperand &)*Operands[0];
9815   if (!IsVector && !Op.isRegList())
9816     return Error(L, ".save expects GPR registers");
9817   if (IsVector && !Op.isDPRRegList())
9818     return Error(L, ".vsave expects DPR registers");
9819 
9820   getTargetStreamer().emitRegSave(Op.getRegList(), IsVector);
9821   return false;
9822 }
9823 
9824 /// parseDirectiveInst
9825 ///  ::= .inst opcode [, ...]
9826 ///  ::= .inst.n opcode [, ...]
9827 ///  ::= .inst.w opcode [, ...]
9828 bool ARMAsmParser::parseDirectiveInst(SMLoc Loc, char Suffix) {
9829   int Width = 4;
9830 
9831   if (isThumb()) {
9832     switch (Suffix) {
9833     case 'n':
9834       Width = 2;
9835       break;
9836     case 'w':
9837       break;
9838     default:
9839       return Error(Loc, "cannot determine Thumb instruction size, "
9840                         "use inst.n/inst.w instead");
9841     }
9842   } else {
9843     if (Suffix)
9844       return Error(Loc, "width suffixes are invalid in ARM mode");
9845   }
9846 
9847   auto parseOne = [&]() -> bool {
9848     const MCExpr *Expr;
9849     if (getParser().parseExpression(Expr))
9850       return true;
9851     const MCConstantExpr *Value = dyn_cast_or_null<MCConstantExpr>(Expr);
9852     if (!Value) {
9853       return Error(Loc, "expected constant expression");
9854     }
9855 
9856     switch (Width) {
9857     case 2:
9858       if (Value->getValue() > 0xffff)
9859         return Error(Loc, "inst.n operand is too big, use inst.w instead");
9860       break;
9861     case 4:
9862       if (Value->getValue() > 0xffffffff)
9863         return Error(Loc, StringRef(Suffix ? "inst.w" : "inst") +
9864                               " operand is too big");
9865       break;
9866     default:
9867       llvm_unreachable("only supported widths are 2 and 4");
9868     }
9869 
9870     getTargetStreamer().emitInst(Value->getValue(), Suffix);
9871     return false;
9872   };
9873 
9874   if (parseOptionalToken(AsmToken::EndOfStatement))
9875     return Error(Loc, "expected expression following directive");
9876   if (parseMany(parseOne))
9877     return true;
9878   return false;
9879 }
9880 
9881 /// parseDirectiveLtorg
9882 ///  ::= .ltorg | .pool
9883 bool ARMAsmParser::parseDirectiveLtorg(SMLoc L) {
9884   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
9885     return true;
9886   getTargetStreamer().emitCurrentConstantPool();
9887   return false;
9888 }
9889 
9890 bool ARMAsmParser::parseDirectiveEven(SMLoc L) {
9891   const MCSection *Section = getStreamer().getCurrentSectionOnly();
9892 
9893   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
9894     return true;
9895 
9896   if (!Section) {
9897     getStreamer().InitSections(false);
9898     Section = getStreamer().getCurrentSectionOnly();
9899   }
9900 
9901   assert(Section && "must have section to emit alignment");
9902   if (Section->UseCodeAlign())
9903     getStreamer().EmitCodeAlignment(2);
9904   else
9905     getStreamer().EmitValueToAlignment(2);
9906 
9907   return false;
9908 }
9909 
9910 /// parseDirectivePersonalityIndex
9911 ///   ::= .personalityindex index
9912 bool ARMAsmParser::parseDirectivePersonalityIndex(SMLoc L) {
9913   MCAsmParser &Parser = getParser();
9914   bool HasExistingPersonality = UC.hasPersonality();
9915 
9916   const MCExpr *IndexExpression;
9917   SMLoc IndexLoc = Parser.getTok().getLoc();
9918   if (Parser.parseExpression(IndexExpression) ||
9919       parseToken(AsmToken::EndOfStatement,
9920                  "unexpected token in '.personalityindex' directive")) {
9921     return true;
9922   }
9923 
9924   UC.recordPersonalityIndex(L);
9925 
9926   if (!UC.hasFnStart()) {
9927     return Error(L, ".fnstart must precede .personalityindex directive");
9928   }
9929   if (UC.cantUnwind()) {
9930     Error(L, ".personalityindex cannot be used with .cantunwind");
9931     UC.emitCantUnwindLocNotes();
9932     return true;
9933   }
9934   if (UC.hasHandlerData()) {
9935     Error(L, ".personalityindex must precede .handlerdata directive");
9936     UC.emitHandlerDataLocNotes();
9937     return true;
9938   }
9939   if (HasExistingPersonality) {
9940     Error(L, "multiple personality directives");
9941     UC.emitPersonalityLocNotes();
9942     return true;
9943   }
9944 
9945   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(IndexExpression);
9946   if (!CE)
9947     return Error(IndexLoc, "index must be a constant number");
9948   if (CE->getValue() < 0 || CE->getValue() >= ARM::EHABI::NUM_PERSONALITY_INDEX)
9949     return Error(IndexLoc,
9950                  "personality routine index should be in range [0-3]");
9951 
9952   getTargetStreamer().emitPersonalityIndex(CE->getValue());
9953   return false;
9954 }
9955 
9956 /// parseDirectiveUnwindRaw
9957 ///   ::= .unwind_raw offset, opcode [, opcode...]
9958 bool ARMAsmParser::parseDirectiveUnwindRaw(SMLoc L) {
9959   MCAsmParser &Parser = getParser();
9960   int64_t StackOffset;
9961   const MCExpr *OffsetExpr;
9962   SMLoc OffsetLoc = getLexer().getLoc();
9963 
9964   if (!UC.hasFnStart())
9965     return Error(L, ".fnstart must precede .unwind_raw directives");
9966   if (getParser().parseExpression(OffsetExpr))
9967     return Error(OffsetLoc, "expected expression");
9968 
9969   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
9970   if (!CE)
9971     return Error(OffsetLoc, "offset must be a constant");
9972 
9973   StackOffset = CE->getValue();
9974 
9975   if (Parser.parseToken(AsmToken::Comma, "expected comma"))
9976     return true;
9977 
9978   SmallVector<uint8_t, 16> Opcodes;
9979 
9980   auto parseOne = [&]() -> bool {
9981     const MCExpr *OE;
9982     SMLoc OpcodeLoc = getLexer().getLoc();
9983     if (check(getLexer().is(AsmToken::EndOfStatement) ||
9984                   Parser.parseExpression(OE),
9985               OpcodeLoc, "expected opcode expression"))
9986       return true;
9987     const MCConstantExpr *OC = dyn_cast<MCConstantExpr>(OE);
9988     if (!OC)
9989       return Error(OpcodeLoc, "opcode value must be a constant");
9990     const int64_t Opcode = OC->getValue();
9991     if (Opcode & ~0xff)
9992       return Error(OpcodeLoc, "invalid opcode");
9993     Opcodes.push_back(uint8_t(Opcode));
9994     return false;
9995   };
9996 
9997   // Must have at least 1 element
9998   SMLoc OpcodeLoc = getLexer().getLoc();
9999   if (parseOptionalToken(AsmToken::EndOfStatement))
10000     return Error(OpcodeLoc, "expected opcode expression");
10001   if (parseMany(parseOne))
10002     return true;
10003 
10004   getTargetStreamer().emitUnwindRaw(StackOffset, Opcodes);
10005   return false;
10006 }
10007 
10008 /// parseDirectiveTLSDescSeq
10009 ///   ::= .tlsdescseq tls-variable
10010 bool ARMAsmParser::parseDirectiveTLSDescSeq(SMLoc L) {
10011   MCAsmParser &Parser = getParser();
10012 
10013   if (getLexer().isNot(AsmToken::Identifier))
10014     return TokError("expected variable after '.tlsdescseq' directive");
10015 
10016   const MCSymbolRefExpr *SRE =
10017     MCSymbolRefExpr::create(Parser.getTok().getIdentifier(),
10018                             MCSymbolRefExpr::VK_ARM_TLSDESCSEQ, getContext());
10019   Lex();
10020 
10021   if (parseToken(AsmToken::EndOfStatement,
10022                  "unexpected token in '.tlsdescseq' directive"))
10023     return true;
10024 
10025   getTargetStreamer().AnnotateTLSDescriptorSequence(SRE);
10026   return false;
10027 }
10028 
10029 /// parseDirectiveMovSP
10030 ///  ::= .movsp reg [, #offset]
10031 bool ARMAsmParser::parseDirectiveMovSP(SMLoc L) {
10032   MCAsmParser &Parser = getParser();
10033   if (!UC.hasFnStart())
10034     return Error(L, ".fnstart must precede .movsp directives");
10035   if (UC.getFPReg() != ARM::SP)
10036     return Error(L, "unexpected .movsp directive");
10037 
10038   SMLoc SPRegLoc = Parser.getTok().getLoc();
10039   int SPReg = tryParseRegister();
10040   if (SPReg == -1)
10041     return Error(SPRegLoc, "register expected");
10042   if (SPReg == ARM::SP || SPReg == ARM::PC)
10043     return Error(SPRegLoc, "sp and pc are not permitted in .movsp directive");
10044 
10045   int64_t Offset = 0;
10046   if (Parser.parseOptionalToken(AsmToken::Comma)) {
10047     if (Parser.parseToken(AsmToken::Hash, "expected #constant"))
10048       return true;
10049 
10050     const MCExpr *OffsetExpr;
10051     SMLoc OffsetLoc = Parser.getTok().getLoc();
10052 
10053     if (Parser.parseExpression(OffsetExpr))
10054       return Error(OffsetLoc, "malformed offset expression");
10055 
10056     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
10057     if (!CE)
10058       return Error(OffsetLoc, "offset must be an immediate constant");
10059 
10060     Offset = CE->getValue();
10061   }
10062 
10063   if (parseToken(AsmToken::EndOfStatement,
10064                  "unexpected token in '.movsp' directive"))
10065     return true;
10066 
10067   getTargetStreamer().emitMovSP(SPReg, Offset);
10068   UC.saveFPReg(SPReg);
10069 
10070   return false;
10071 }
10072 
10073 /// parseDirectiveObjectArch
10074 ///   ::= .object_arch name
10075 bool ARMAsmParser::parseDirectiveObjectArch(SMLoc L) {
10076   MCAsmParser &Parser = getParser();
10077   if (getLexer().isNot(AsmToken::Identifier))
10078     return Error(getLexer().getLoc(), "unexpected token");
10079 
10080   StringRef Arch = Parser.getTok().getString();
10081   SMLoc ArchLoc = Parser.getTok().getLoc();
10082   Lex();
10083 
10084   ARM::ArchKind ID = ARM::parseArch(Arch);
10085 
10086   if (ID == ARM::ArchKind::INVALID)
10087     return Error(ArchLoc, "unknown architecture '" + Arch + "'");
10088   if (parseToken(AsmToken::EndOfStatement))
10089     return true;
10090 
10091   getTargetStreamer().emitObjectArch(ID);
10092   return false;
10093 }
10094 
10095 /// parseDirectiveAlign
10096 ///   ::= .align
10097 bool ARMAsmParser::parseDirectiveAlign(SMLoc L) {
10098   // NOTE: if this is not the end of the statement, fall back to the target
10099   // agnostic handling for this directive which will correctly handle this.
10100   if (parseOptionalToken(AsmToken::EndOfStatement)) {
10101     // '.align' is target specifically handled to mean 2**2 byte alignment.
10102     const MCSection *Section = getStreamer().getCurrentSectionOnly();
10103     assert(Section && "must have section to emit alignment");
10104     if (Section->UseCodeAlign())
10105       getStreamer().EmitCodeAlignment(4, 0);
10106     else
10107       getStreamer().EmitValueToAlignment(4, 0, 1, 0);
10108     return false;
10109   }
10110   return true;
10111 }
10112 
10113 /// parseDirectiveThumbSet
10114 ///  ::= .thumb_set name, value
10115 bool ARMAsmParser::parseDirectiveThumbSet(SMLoc L) {
10116   MCAsmParser &Parser = getParser();
10117 
10118   StringRef Name;
10119   if (check(Parser.parseIdentifier(Name),
10120             "expected identifier after '.thumb_set'") ||
10121       parseToken(AsmToken::Comma, "expected comma after name '" + Name + "'"))
10122     return true;
10123 
10124   MCSymbol *Sym;
10125   const MCExpr *Value;
10126   if (MCParserUtils::parseAssignmentExpression(Name, /* allow_redef */ true,
10127                                                Parser, Sym, Value))
10128     return true;
10129 
10130   getTargetStreamer().emitThumbSet(Sym, Value);
10131   return false;
10132 }
10133 
10134 /// Force static initialization.
10135 extern "C" void LLVMInitializeARMAsmParser() {
10136   RegisterMCAsmParser<ARMAsmParser> X(getTheARMLETarget());
10137   RegisterMCAsmParser<ARMAsmParser> Y(getTheARMBETarget());
10138   RegisterMCAsmParser<ARMAsmParser> A(getTheThumbLETarget());
10139   RegisterMCAsmParser<ARMAsmParser> B(getTheThumbBETarget());
10140 }
10141 
10142 #define GET_REGISTER_MATCHER
10143 #define GET_SUBTARGET_FEATURE_NAME
10144 #define GET_MATCHER_IMPLEMENTATION
10145 #define GET_MNEMONIC_SPELL_CHECKER
10146 #include "ARMGenAsmMatcher.inc"
10147 
10148 // Some diagnostics need to vary with subtarget features, so they are handled
10149 // here. For example, the DPR class has either 16 or 32 registers, depending
10150 // on the FPU available.
10151 const char *
10152 ARMAsmParser::getCustomOperandDiag(ARMMatchResultTy MatchError) {
10153   switch (MatchError) {
10154   // rGPR contains sp starting with ARMv8.
10155   case Match_rGPR:
10156     return hasV8Ops() ? "operand must be a register in range [r0, r14]"
10157                       : "operand must be a register in range [r0, r12] or r14";
10158   // DPR contains 16 registers for some FPUs, and 32 for others.
10159   case Match_DPR:
10160     return hasD16() ? "operand must be a register in range [d0, d15]"
10161                     : "operand must be a register in range [d0, d31]";
10162   case Match_DPR_RegList:
10163     return hasD16() ? "operand must be a list of registers in range [d0, d15]"
10164                     : "operand must be a list of registers in range [d0, d31]";
10165 
10166   // For all other diags, use the static string from tablegen.
10167   default:
10168     return getMatchKindDiag(MatchError);
10169   }
10170 }
10171 
10172 // Process the list of near-misses, throwing away ones we don't want to report
10173 // to the user, and converting the rest to a source location and string that
10174 // should be reported.
10175 void
10176 ARMAsmParser::FilterNearMisses(SmallVectorImpl<NearMissInfo> &NearMissesIn,
10177                                SmallVectorImpl<NearMissMessage> &NearMissesOut,
10178                                SMLoc IDLoc, OperandVector &Operands) {
10179   // TODO: If operand didn't match, sub in a dummy one and run target
10180   // predicate, so that we can avoid reporting near-misses that are invalid?
10181   // TODO: Many operand types dont have SuperClasses set, so we report
10182   // redundant ones.
10183   // TODO: Some operands are superclasses of registers (e.g.
10184   // MCK_RegShiftedImm), we don't have any way to represent that currently.
10185   // TODO: This is not all ARM-specific, can some of it be factored out?
10186 
10187   // Record some information about near-misses that we have already seen, so
10188   // that we can avoid reporting redundant ones. For example, if there are
10189   // variants of an instruction that take 8- and 16-bit immediates, we want
10190   // to only report the widest one.
10191   std::multimap<unsigned, unsigned> OperandMissesSeen;
10192   SmallSet<uint64_t, 4> FeatureMissesSeen;
10193   bool ReportedTooFewOperands = false;
10194 
10195   // Process the near-misses in reverse order, so that we see more general ones
10196   // first, and so can avoid emitting more specific ones.
10197   for (NearMissInfo &I : reverse(NearMissesIn)) {
10198     switch (I.getKind()) {
10199     case NearMissInfo::NearMissOperand: {
10200       SMLoc OperandLoc =
10201           ((ARMOperand &)*Operands[I.getOperandIndex()]).getStartLoc();
10202       const char *OperandDiag =
10203           getCustomOperandDiag((ARMMatchResultTy)I.getOperandError());
10204 
10205       // If we have already emitted a message for a superclass, don't also report
10206       // the sub-class. We consider all operand classes that we don't have a
10207       // specialised diagnostic for to be equal for the propose of this check,
10208       // so that we don't report the generic error multiple times on the same
10209       // operand.
10210       unsigned DupCheckMatchClass = OperandDiag ? I.getOperandClass() : ~0U;
10211       auto PrevReports = OperandMissesSeen.equal_range(I.getOperandIndex());
10212       if (std::any_of(PrevReports.first, PrevReports.second,
10213                       [DupCheckMatchClass](
10214                           const std::pair<unsigned, unsigned> Pair) {
10215             if (DupCheckMatchClass == ~0U || Pair.second == ~0U)
10216               return Pair.second == DupCheckMatchClass;
10217             else
10218               return isSubclass((MatchClassKind)DupCheckMatchClass,
10219                                 (MatchClassKind)Pair.second);
10220           }))
10221         break;
10222       OperandMissesSeen.insert(
10223           std::make_pair(I.getOperandIndex(), DupCheckMatchClass));
10224 
10225       NearMissMessage Message;
10226       Message.Loc = OperandLoc;
10227       if (OperandDiag) {
10228         Message.Message = OperandDiag;
10229       } else if (I.getOperandClass() == InvalidMatchClass) {
10230         Message.Message = "too many operands for instruction";
10231       } else {
10232         Message.Message = "invalid operand for instruction";
10233         DEBUG(dbgs() << "Missing diagnostic string for operand class " <<
10234               getMatchClassName((MatchClassKind)I.getOperandClass())
10235               << I.getOperandClass() << ", error " << I.getOperandError()
10236               << ", opcode " << MII.getName(I.getOpcode()) << "\n");
10237       }
10238       NearMissesOut.emplace_back(Message);
10239       break;
10240     }
10241     case NearMissInfo::NearMissFeature: {
10242       uint64_t MissingFeatures = I.getFeatures();
10243       // Don't report the same set of features twice.
10244       if (FeatureMissesSeen.count(MissingFeatures))
10245         break;
10246       FeatureMissesSeen.insert(MissingFeatures);
10247 
10248       // Special case: don't report a feature set which includes arm-mode for
10249       // targets that don't have ARM mode.
10250       if ((MissingFeatures & Feature_IsARM) && !hasARM())
10251         break;
10252       // Don't report any near-misses that both require switching instruction
10253       // set, and adding other subtarget features.
10254       if (isThumb() && (MissingFeatures & Feature_IsARM) &&
10255           (MissingFeatures & ~Feature_IsARM))
10256         break;
10257       if (!isThumb() && (MissingFeatures & Feature_IsThumb) &&
10258           (MissingFeatures & ~Feature_IsThumb))
10259         break;
10260       if (!isThumb() && (MissingFeatures & Feature_IsThumb2) &&
10261           (MissingFeatures & ~(Feature_IsThumb2 | Feature_IsThumb)))
10262         break;
10263       if (isMClass() && (MissingFeatures & Feature_HasNEON))
10264         break;
10265 
10266       NearMissMessage Message;
10267       Message.Loc = IDLoc;
10268       raw_svector_ostream OS(Message.Message);
10269 
10270       OS << "instruction requires:";
10271       uint64_t Mask = 1;
10272       for (unsigned MaskPos = 0; MaskPos < (sizeof(MissingFeatures) * 8 - 1);
10273            ++MaskPos) {
10274         if (MissingFeatures & Mask) {
10275           OS << " " << getSubtargetFeatureName(MissingFeatures & Mask);
10276         }
10277         Mask <<= 1;
10278       }
10279       NearMissesOut.emplace_back(Message);
10280 
10281       break;
10282     }
10283     case NearMissInfo::NearMissPredicate: {
10284       NearMissMessage Message;
10285       Message.Loc = IDLoc;
10286       switch (I.getPredicateError()) {
10287       case Match_RequiresNotITBlock:
10288         Message.Message = "flag setting instruction only valid outside IT block";
10289         break;
10290       case Match_RequiresITBlock:
10291         Message.Message = "instruction only valid inside IT block";
10292         break;
10293       case Match_RequiresV6:
10294         Message.Message = "instruction variant requires ARMv6 or later";
10295         break;
10296       case Match_RequiresThumb2:
10297         Message.Message = "instruction variant requires Thumb2";
10298         break;
10299       case Match_RequiresV8:
10300         Message.Message = "instruction variant requires ARMv8 or later";
10301         break;
10302       case Match_RequiresFlagSetting:
10303         Message.Message = "no flag-preserving variant of this instruction available";
10304         break;
10305       case Match_InvalidOperand:
10306         Message.Message = "invalid operand for instruction";
10307         break;
10308       default:
10309         llvm_unreachable("Unhandled target predicate error");
10310         break;
10311       }
10312       NearMissesOut.emplace_back(Message);
10313       break;
10314     }
10315     case NearMissInfo::NearMissTooFewOperands: {
10316       if (!ReportedTooFewOperands) {
10317         SMLoc EndLoc = ((ARMOperand &)*Operands.back()).getEndLoc();
10318         NearMissesOut.emplace_back(NearMissMessage{
10319             EndLoc, StringRef("too few operands for instruction")});
10320         ReportedTooFewOperands = true;
10321       }
10322       break;
10323     }
10324     case NearMissInfo::NoNearMiss:
10325       // This should never leave the matcher.
10326       llvm_unreachable("not a near-miss");
10327       break;
10328     }
10329   }
10330 }
10331 
10332 void ARMAsmParser::ReportNearMisses(SmallVectorImpl<NearMissInfo> &NearMisses,
10333                                     SMLoc IDLoc, OperandVector &Operands) {
10334   SmallVector<NearMissMessage, 4> Messages;
10335   FilterNearMisses(NearMisses, Messages, IDLoc, Operands);
10336 
10337   if (Messages.size() == 0) {
10338     // No near-misses were found, so the best we can do is "invalid
10339     // instruction".
10340     Error(IDLoc, "invalid instruction");
10341   } else if (Messages.size() == 1) {
10342     // One near miss was found, report it as the sole error.
10343     Error(Messages[0].Loc, Messages[0].Message);
10344   } else {
10345     // More than one near miss, so report a generic "invalid instruction"
10346     // error, followed by notes for each of the near-misses.
10347     Error(IDLoc, "invalid instruction, any one of the following would fix this:");
10348     for (auto &M : Messages) {
10349       Note(M.Loc, M.Message);
10350     }
10351   }
10352 }
10353 
10354 // FIXME: This structure should be moved inside ARMTargetParser
10355 // when we start to table-generate them, and we can use the ARM
10356 // flags below, that were generated by table-gen.
10357 static const struct {
10358   const unsigned Kind;
10359   const uint64_t ArchCheck;
10360   const FeatureBitset Features;
10361 } Extensions[] = {
10362   { ARM::AEK_CRC, Feature_HasV8, {ARM::FeatureCRC} },
10363   { ARM::AEK_CRYPTO,  Feature_HasV8,
10364     {ARM::FeatureCrypto, ARM::FeatureNEON, ARM::FeatureFPARMv8} },
10365   { ARM::AEK_FP, Feature_HasV8, {ARM::FeatureFPARMv8} },
10366   { (ARM::AEK_HWDIVTHUMB | ARM::AEK_HWDIVARM), Feature_HasV7 | Feature_IsNotMClass,
10367     {ARM::FeatureHWDivThumb, ARM::FeatureHWDivARM} },
10368   { ARM::AEK_MP, Feature_HasV7 | Feature_IsNotMClass, {ARM::FeatureMP} },
10369   { ARM::AEK_SIMD, Feature_HasV8, {ARM::FeatureNEON, ARM::FeatureFPARMv8} },
10370   { ARM::AEK_SEC, Feature_HasV6K, {ARM::FeatureTrustZone} },
10371   // FIXME: Only available in A-class, isel not predicated
10372   { ARM::AEK_VIRT, Feature_HasV7, {ARM::FeatureVirtualization} },
10373   { ARM::AEK_FP16, Feature_HasV8_2a, {ARM::FeatureFPARMv8, ARM::FeatureFullFP16} },
10374   { ARM::AEK_RAS, Feature_HasV8, {ARM::FeatureRAS} },
10375   // FIXME: Unsupported extensions.
10376   { ARM::AEK_OS, Feature_None, {} },
10377   { ARM::AEK_IWMMXT, Feature_None, {} },
10378   { ARM::AEK_IWMMXT2, Feature_None, {} },
10379   { ARM::AEK_MAVERICK, Feature_None, {} },
10380   { ARM::AEK_XSCALE, Feature_None, {} },
10381 };
10382 
10383 /// parseDirectiveArchExtension
10384 ///   ::= .arch_extension [no]feature
10385 bool ARMAsmParser::parseDirectiveArchExtension(SMLoc L) {
10386   MCAsmParser &Parser = getParser();
10387 
10388   if (getLexer().isNot(AsmToken::Identifier))
10389     return Error(getLexer().getLoc(), "expected architecture extension name");
10390 
10391   StringRef Name = Parser.getTok().getString();
10392   SMLoc ExtLoc = Parser.getTok().getLoc();
10393   Lex();
10394 
10395   if (parseToken(AsmToken::EndOfStatement,
10396                  "unexpected token in '.arch_extension' directive"))
10397     return true;
10398 
10399   bool EnableFeature = true;
10400   if (Name.startswith_lower("no")) {
10401     EnableFeature = false;
10402     Name = Name.substr(2);
10403   }
10404   unsigned FeatureKind = ARM::parseArchExt(Name);
10405   if (FeatureKind == ARM::AEK_INVALID)
10406     return Error(ExtLoc, "unknown architectural extension: " + Name);
10407 
10408   for (const auto &Extension : Extensions) {
10409     if (Extension.Kind != FeatureKind)
10410       continue;
10411 
10412     if (Extension.Features.none())
10413       return Error(ExtLoc, "unsupported architectural extension: " + Name);
10414 
10415     if ((getAvailableFeatures() & Extension.ArchCheck) != Extension.ArchCheck)
10416       return Error(ExtLoc, "architectural extension '" + Name +
10417                                "' is not "
10418                                "allowed for the current base architecture");
10419 
10420     MCSubtargetInfo &STI = copySTI();
10421     FeatureBitset ToggleFeatures = EnableFeature
10422       ? (~STI.getFeatureBits() & Extension.Features)
10423       : ( STI.getFeatureBits() & Extension.Features);
10424 
10425     uint64_t Features =
10426         ComputeAvailableFeatures(STI.ToggleFeature(ToggleFeatures));
10427     setAvailableFeatures(Features);
10428     return false;
10429   }
10430 
10431   return Error(ExtLoc, "unknown architectural extension: " + Name);
10432 }
10433 
10434 // Define this matcher function after the auto-generated include so we
10435 // have the match class enum definitions.
10436 unsigned ARMAsmParser::validateTargetOperandClass(MCParsedAsmOperand &AsmOp,
10437                                                   unsigned Kind) {
10438   ARMOperand &Op = static_cast<ARMOperand &>(AsmOp);
10439   // If the kind is a token for a literal immediate, check if our asm
10440   // operand matches. This is for InstAliases which have a fixed-value
10441   // immediate in the syntax.
10442   switch (Kind) {
10443   default: break;
10444   case MCK__35_0:
10445     if (Op.isImm())
10446       if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm()))
10447         if (CE->getValue() == 0)
10448           return Match_Success;
10449     break;
10450   case MCK_ModImm:
10451     if (Op.isImm()) {
10452       const MCExpr *SOExpr = Op.getImm();
10453       int64_t Value;
10454       if (!SOExpr->evaluateAsAbsolute(Value))
10455         return Match_Success;
10456       assert((Value >= std::numeric_limits<int32_t>::min() &&
10457               Value <= std::numeric_limits<uint32_t>::max()) &&
10458              "expression value must be representable in 32 bits");
10459     }
10460     break;
10461   case MCK_rGPR:
10462     if (hasV8Ops() && Op.isReg() && Op.getReg() == ARM::SP)
10463       return Match_Success;
10464     return Match_rGPR;
10465   case MCK_GPRPair:
10466     if (Op.isReg() &&
10467         MRI->getRegClass(ARM::GPRRegClassID).contains(Op.getReg()))
10468       return Match_Success;
10469     break;
10470   }
10471   return Match_InvalidOperand;
10472 }
10473