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 { return Kind == k_Memory; }
1154   bool isShifterImm() const { return Kind == k_ShifterImmediate; }
1155   bool isRegShiftedReg() const { return Kind == k_ShiftedRegister; }
1156   bool isRegShiftedImm() const { return Kind == k_ShiftedImmediate; }
1157   bool isRotImm() const { return Kind == k_RotateImmediate; }
1158   bool isModImm() const { return Kind == k_ModifiedImmediate; }
1159 
1160   bool isModImmNot() const {
1161     if (!isImm()) return false;
1162     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1163     if (!CE) return false;
1164     int64_t Value = CE->getValue();
1165     return ARM_AM::getSOImmVal(~Value) != -1;
1166   }
1167 
1168   bool isModImmNeg() const {
1169     if (!isImm()) return false;
1170     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1171     if (!CE) return false;
1172     int64_t Value = CE->getValue();
1173     return ARM_AM::getSOImmVal(Value) == -1 &&
1174       ARM_AM::getSOImmVal(-Value) != -1;
1175   }
1176 
1177   bool isThumbModImmNeg1_7() const {
1178     if (!isImm()) return false;
1179     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1180     if (!CE) return false;
1181     int32_t Value = -(int32_t)CE->getValue();
1182     return 0 < Value && Value < 8;
1183   }
1184 
1185   bool isThumbModImmNeg8_255() const {
1186     if (!isImm()) return false;
1187     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1188     if (!CE) return false;
1189     int32_t Value = -(int32_t)CE->getValue();
1190     return 7 < Value && Value < 256;
1191   }
1192 
1193   bool isConstantPoolImm() const { return Kind == k_ConstantPoolImmediate; }
1194   bool isBitfield() const { return Kind == k_BitfieldDescriptor; }
1195   bool isPostIdxRegShifted() const { return Kind == k_PostIndexRegister; }
1196   bool isPostIdxReg() const {
1197     return Kind == k_PostIndexRegister && PostIdxReg.ShiftTy ==ARM_AM::no_shift;
1198   }
1199   bool isMemNoOffset(bool alignOK = false, unsigned Alignment = 0) const {
1200     if (!isMem())
1201       return false;
1202     // No offset of any kind.
1203     return Memory.OffsetRegNum == 0 && Memory.OffsetImm == nullptr &&
1204      (alignOK || Memory.Alignment == Alignment);
1205   }
1206   bool isMemPCRelImm12() const {
1207     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1208       return false;
1209     // Base register must be PC.
1210     if (Memory.BaseRegNum != ARM::PC)
1211       return false;
1212     // Immediate offset in range [-4095, 4095].
1213     if (!Memory.OffsetImm) return true;
1214     int64_t Val = Memory.OffsetImm->getValue();
1215     return (Val > -4096 && Val < 4096) ||
1216            (Val == std::numeric_limits<int32_t>::min());
1217   }
1218 
1219   bool isAlignedMemory() const {
1220     return isMemNoOffset(true);
1221   }
1222 
1223   bool isAlignedMemoryNone() const {
1224     return isMemNoOffset(false, 0);
1225   }
1226 
1227   bool isDupAlignedMemoryNone() const {
1228     return isMemNoOffset(false, 0);
1229   }
1230 
1231   bool isAlignedMemory16() const {
1232     if (isMemNoOffset(false, 2)) // alignment in bytes for 16-bits is 2.
1233       return true;
1234     return isMemNoOffset(false, 0);
1235   }
1236 
1237   bool isDupAlignedMemory16() const {
1238     if (isMemNoOffset(false, 2)) // alignment in bytes for 16-bits is 2.
1239       return true;
1240     return isMemNoOffset(false, 0);
1241   }
1242 
1243   bool isAlignedMemory32() const {
1244     if (isMemNoOffset(false, 4)) // alignment in bytes for 32-bits is 4.
1245       return true;
1246     return isMemNoOffset(false, 0);
1247   }
1248 
1249   bool isDupAlignedMemory32() const {
1250     if (isMemNoOffset(false, 4)) // alignment in bytes for 32-bits is 4.
1251       return true;
1252     return isMemNoOffset(false, 0);
1253   }
1254 
1255   bool isAlignedMemory64() const {
1256     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1257       return true;
1258     return isMemNoOffset(false, 0);
1259   }
1260 
1261   bool isDupAlignedMemory64() const {
1262     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1263       return true;
1264     return isMemNoOffset(false, 0);
1265   }
1266 
1267   bool isAlignedMemory64or128() const {
1268     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1269       return true;
1270     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1271       return true;
1272     return isMemNoOffset(false, 0);
1273   }
1274 
1275   bool isDupAlignedMemory64or128() const {
1276     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1277       return true;
1278     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1279       return true;
1280     return isMemNoOffset(false, 0);
1281   }
1282 
1283   bool isAlignedMemory64or128or256() const {
1284     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1285       return true;
1286     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1287       return true;
1288     if (isMemNoOffset(false, 32)) // alignment in bytes for 256-bits is 32.
1289       return true;
1290     return isMemNoOffset(false, 0);
1291   }
1292 
1293   bool isAddrMode2() const {
1294     if (!isMem() || Memory.Alignment != 0) return false;
1295     // Check for register offset.
1296     if (Memory.OffsetRegNum) return true;
1297     // Immediate offset in range [-4095, 4095].
1298     if (!Memory.OffsetImm) return true;
1299     int64_t Val = Memory.OffsetImm->getValue();
1300     return Val > -4096 && Val < 4096;
1301   }
1302 
1303   bool isAM2OffsetImm() const {
1304     if (!isImm()) return false;
1305     // Immediate offset in range [-4095, 4095].
1306     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1307     if (!CE) return false;
1308     int64_t Val = CE->getValue();
1309     return (Val == std::numeric_limits<int32_t>::min()) ||
1310            (Val > -4096 && Val < 4096);
1311   }
1312 
1313   bool isAddrMode3() const {
1314     // If we have an immediate that's not a constant, treat it as a label
1315     // reference needing a fixup. If it is a constant, it's something else
1316     // and we reject it.
1317     if (isImm() && !isa<MCConstantExpr>(getImm()))
1318       return true;
1319     if (!isMem() || Memory.Alignment != 0) return false;
1320     // No shifts are legal for AM3.
1321     if (Memory.ShiftType != ARM_AM::no_shift) return false;
1322     // Check for register offset.
1323     if (Memory.OffsetRegNum) return true;
1324     // Immediate offset in range [-255, 255].
1325     if (!Memory.OffsetImm) return true;
1326     int64_t Val = Memory.OffsetImm->getValue();
1327     // The #-0 offset is encoded as std::numeric_limits<int32_t>::min(), and we
1328     // have to check for this too.
1329     return (Val > -256 && Val < 256) ||
1330            Val == std::numeric_limits<int32_t>::min();
1331   }
1332 
1333   bool isAM3Offset() const {
1334     if (Kind != k_Immediate && Kind != k_PostIndexRegister)
1335       return false;
1336     if (Kind == k_PostIndexRegister)
1337       return PostIdxReg.ShiftTy == ARM_AM::no_shift;
1338     // Immediate offset in range [-255, 255].
1339     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1340     if (!CE) return false;
1341     int64_t Val = CE->getValue();
1342     // Special case, #-0 is std::numeric_limits<int32_t>::min().
1343     return (Val > -256 && Val < 256) ||
1344            Val == std::numeric_limits<int32_t>::min();
1345   }
1346 
1347   bool isAddrMode5() const {
1348     // If we have an immediate that's not a constant, treat it as a label
1349     // reference needing a fixup. If it is a constant, it's something else
1350     // and we reject it.
1351     if (isImm() && !isa<MCConstantExpr>(getImm()))
1352       return true;
1353     if (!isMem() || Memory.Alignment != 0) return false;
1354     // Check for register offset.
1355     if (Memory.OffsetRegNum) return false;
1356     // Immediate offset in range [-1020, 1020] and a multiple of 4.
1357     if (!Memory.OffsetImm) return true;
1358     int64_t Val = Memory.OffsetImm->getValue();
1359     return (Val >= -1020 && Val <= 1020 && ((Val & 3) == 0)) ||
1360       Val == std::numeric_limits<int32_t>::min();
1361   }
1362 
1363   bool isAddrMode5FP16() const {
1364     // If we have an immediate that's not a constant, treat it as a label
1365     // reference needing a fixup. If it is a constant, it's something else
1366     // and we reject it.
1367     if (isImm() && !isa<MCConstantExpr>(getImm()))
1368       return true;
1369     if (!isMem() || Memory.Alignment != 0) return false;
1370     // Check for register offset.
1371     if (Memory.OffsetRegNum) return false;
1372     // Immediate offset in range [-510, 510] and a multiple of 2.
1373     if (!Memory.OffsetImm) return true;
1374     int64_t Val = Memory.OffsetImm->getValue();
1375     return (Val >= -510 && Val <= 510 && ((Val & 1) == 0)) ||
1376            Val == std::numeric_limits<int32_t>::min();
1377   }
1378 
1379   bool isMemTBB() const {
1380     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1381         Memory.ShiftType != ARM_AM::no_shift || Memory.Alignment != 0)
1382       return false;
1383     return true;
1384   }
1385 
1386   bool isMemTBH() const {
1387     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1388         Memory.ShiftType != ARM_AM::lsl || Memory.ShiftImm != 1 ||
1389         Memory.Alignment != 0 )
1390       return false;
1391     return true;
1392   }
1393 
1394   bool isMemRegOffset() const {
1395     if (!isMem() || !Memory.OffsetRegNum || Memory.Alignment != 0)
1396       return false;
1397     return true;
1398   }
1399 
1400   bool isT2MemRegOffset() const {
1401     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1402         Memory.Alignment != 0 || Memory.BaseRegNum == ARM::PC)
1403       return false;
1404     // Only lsl #{0, 1, 2, 3} allowed.
1405     if (Memory.ShiftType == ARM_AM::no_shift)
1406       return true;
1407     if (Memory.ShiftType != ARM_AM::lsl || Memory.ShiftImm > 3)
1408       return false;
1409     return true;
1410   }
1411 
1412   bool isMemThumbRR() const {
1413     // Thumb reg+reg addressing is simple. Just two registers, a base and
1414     // an offset. No shifts, negations or any other complicating factors.
1415     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1416         Memory.ShiftType != ARM_AM::no_shift || Memory.Alignment != 0)
1417       return false;
1418     return isARMLowRegister(Memory.BaseRegNum) &&
1419       (!Memory.OffsetRegNum || isARMLowRegister(Memory.OffsetRegNum));
1420   }
1421 
1422   bool isMemThumbRIs4() const {
1423     if (!isMem() || Memory.OffsetRegNum != 0 ||
1424         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1425       return false;
1426     // Immediate offset, multiple of 4 in range [0, 124].
1427     if (!Memory.OffsetImm) return true;
1428     int64_t Val = Memory.OffsetImm->getValue();
1429     return Val >= 0 && Val <= 124 && (Val % 4) == 0;
1430   }
1431 
1432   bool isMemThumbRIs2() const {
1433     if (!isMem() || Memory.OffsetRegNum != 0 ||
1434         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1435       return false;
1436     // Immediate offset, multiple of 4 in range [0, 62].
1437     if (!Memory.OffsetImm) return true;
1438     int64_t Val = Memory.OffsetImm->getValue();
1439     return Val >= 0 && Val <= 62 && (Val % 2) == 0;
1440   }
1441 
1442   bool isMemThumbRIs1() const {
1443     if (!isMem() || Memory.OffsetRegNum != 0 ||
1444         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1445       return false;
1446     // Immediate offset in range [0, 31].
1447     if (!Memory.OffsetImm) return true;
1448     int64_t Val = Memory.OffsetImm->getValue();
1449     return Val >= 0 && Val <= 31;
1450   }
1451 
1452   bool isMemThumbSPI() const {
1453     if (!isMem() || Memory.OffsetRegNum != 0 ||
1454         Memory.BaseRegNum != ARM::SP || Memory.Alignment != 0)
1455       return false;
1456     // Immediate offset, multiple of 4 in range [0, 1020].
1457     if (!Memory.OffsetImm) return true;
1458     int64_t Val = Memory.OffsetImm->getValue();
1459     return Val >= 0 && Val <= 1020 && (Val % 4) == 0;
1460   }
1461 
1462   bool isMemImm8s4Offset() const {
1463     // If we have an immediate that's not a constant, treat it as a label
1464     // reference needing a fixup. If it is a constant, it's something else
1465     // and we reject it.
1466     if (isImm() && !isa<MCConstantExpr>(getImm()))
1467       return true;
1468     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1469       return false;
1470     // Immediate offset a multiple of 4 in range [-1020, 1020].
1471     if (!Memory.OffsetImm) return true;
1472     int64_t Val = Memory.OffsetImm->getValue();
1473     // Special case, #-0 is std::numeric_limits<int32_t>::min().
1474     return (Val >= -1020 && Val <= 1020 && (Val & 3) == 0) ||
1475            Val == std::numeric_limits<int32_t>::min();
1476   }
1477 
1478   bool isMemImm0_1020s4Offset() const {
1479     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1480       return false;
1481     // Immediate offset a multiple of 4 in range [0, 1020].
1482     if (!Memory.OffsetImm) return true;
1483     int64_t Val = Memory.OffsetImm->getValue();
1484     return Val >= 0 && Val <= 1020 && (Val & 3) == 0;
1485   }
1486 
1487   bool isMemImm8Offset() const {
1488     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1489       return false;
1490     // Base reg of PC isn't allowed for these encodings.
1491     if (Memory.BaseRegNum == ARM::PC) return false;
1492     // Immediate offset in range [-255, 255].
1493     if (!Memory.OffsetImm) return true;
1494     int64_t Val = Memory.OffsetImm->getValue();
1495     return (Val == std::numeric_limits<int32_t>::min()) ||
1496            (Val > -256 && Val < 256);
1497   }
1498 
1499   bool isMemPosImm8Offset() const {
1500     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1501       return false;
1502     // Immediate offset in range [0, 255].
1503     if (!Memory.OffsetImm) return true;
1504     int64_t Val = Memory.OffsetImm->getValue();
1505     return Val >= 0 && Val < 256;
1506   }
1507 
1508   bool isMemNegImm8Offset() const {
1509     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1510       return false;
1511     // Base reg of PC isn't allowed for these encodings.
1512     if (Memory.BaseRegNum == ARM::PC) return false;
1513     // Immediate offset in range [-255, -1].
1514     if (!Memory.OffsetImm) return false;
1515     int64_t Val = Memory.OffsetImm->getValue();
1516     return (Val == std::numeric_limits<int32_t>::min()) ||
1517            (Val > -256 && Val < 0);
1518   }
1519 
1520   bool isMemUImm12Offset() const {
1521     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1522       return false;
1523     // Immediate offset in range [0, 4095].
1524     if (!Memory.OffsetImm) return true;
1525     int64_t Val = Memory.OffsetImm->getValue();
1526     return (Val >= 0 && Val < 4096);
1527   }
1528 
1529   bool isMemImm12Offset() const {
1530     // If we have an immediate that's not a constant, treat it as a label
1531     // reference needing a fixup. If it is a constant, it's something else
1532     // and we reject it.
1533 
1534     if (isImm() && !isa<MCConstantExpr>(getImm()))
1535       return true;
1536 
1537     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1538       return false;
1539     // Immediate offset in range [-4095, 4095].
1540     if (!Memory.OffsetImm) return true;
1541     int64_t Val = Memory.OffsetImm->getValue();
1542     return (Val > -4096 && Val < 4096) ||
1543            (Val == std::numeric_limits<int32_t>::min());
1544   }
1545 
1546   bool isConstPoolAsmImm() const {
1547     // Delay processing of Constant Pool Immediate, this will turn into
1548     // a constant. Match no other operand
1549     return (isConstantPoolImm());
1550   }
1551 
1552   bool isPostIdxImm8() const {
1553     if (!isImm()) return false;
1554     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1555     if (!CE) return false;
1556     int64_t Val = CE->getValue();
1557     return (Val > -256 && Val < 256) ||
1558            (Val == std::numeric_limits<int32_t>::min());
1559   }
1560 
1561   bool isPostIdxImm8s4() const {
1562     if (!isImm()) return false;
1563     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1564     if (!CE) return false;
1565     int64_t Val = CE->getValue();
1566     return ((Val & 3) == 0 && Val >= -1020 && Val <= 1020) ||
1567            (Val == std::numeric_limits<int32_t>::min());
1568   }
1569 
1570   bool isMSRMask() const { return Kind == k_MSRMask; }
1571   bool isBankedReg() const { return Kind == k_BankedReg; }
1572   bool isProcIFlags() const { return Kind == k_ProcIFlags; }
1573 
1574   // NEON operands.
1575   bool isSingleSpacedVectorList() const {
1576     return Kind == k_VectorList && !VectorList.isDoubleSpaced;
1577   }
1578 
1579   bool isDoubleSpacedVectorList() const {
1580     return Kind == k_VectorList && VectorList.isDoubleSpaced;
1581   }
1582 
1583   bool isVecListOneD() const {
1584     if (!isSingleSpacedVectorList()) return false;
1585     return VectorList.Count == 1;
1586   }
1587 
1588   bool isVecListDPair() const {
1589     if (!isSingleSpacedVectorList()) return false;
1590     return (ARMMCRegisterClasses[ARM::DPairRegClassID]
1591               .contains(VectorList.RegNum));
1592   }
1593 
1594   bool isVecListThreeD() const {
1595     if (!isSingleSpacedVectorList()) return false;
1596     return VectorList.Count == 3;
1597   }
1598 
1599   bool isVecListFourD() const {
1600     if (!isSingleSpacedVectorList()) return false;
1601     return VectorList.Count == 4;
1602   }
1603 
1604   bool isVecListDPairSpaced() const {
1605     if (Kind != k_VectorList) return false;
1606     if (isSingleSpacedVectorList()) return false;
1607     return (ARMMCRegisterClasses[ARM::DPairSpcRegClassID]
1608               .contains(VectorList.RegNum));
1609   }
1610 
1611   bool isVecListThreeQ() const {
1612     if (!isDoubleSpacedVectorList()) return false;
1613     return VectorList.Count == 3;
1614   }
1615 
1616   bool isVecListFourQ() const {
1617     if (!isDoubleSpacedVectorList()) return false;
1618     return VectorList.Count == 4;
1619   }
1620 
1621   bool isSingleSpacedVectorAllLanes() const {
1622     return Kind == k_VectorListAllLanes && !VectorList.isDoubleSpaced;
1623   }
1624 
1625   bool isDoubleSpacedVectorAllLanes() const {
1626     return Kind == k_VectorListAllLanes && VectorList.isDoubleSpaced;
1627   }
1628 
1629   bool isVecListOneDAllLanes() const {
1630     if (!isSingleSpacedVectorAllLanes()) return false;
1631     return VectorList.Count == 1;
1632   }
1633 
1634   bool isVecListDPairAllLanes() const {
1635     if (!isSingleSpacedVectorAllLanes()) return false;
1636     return (ARMMCRegisterClasses[ARM::DPairRegClassID]
1637               .contains(VectorList.RegNum));
1638   }
1639 
1640   bool isVecListDPairSpacedAllLanes() const {
1641     if (!isDoubleSpacedVectorAllLanes()) return false;
1642     return VectorList.Count == 2;
1643   }
1644 
1645   bool isVecListThreeDAllLanes() const {
1646     if (!isSingleSpacedVectorAllLanes()) return false;
1647     return VectorList.Count == 3;
1648   }
1649 
1650   bool isVecListThreeQAllLanes() const {
1651     if (!isDoubleSpacedVectorAllLanes()) return false;
1652     return VectorList.Count == 3;
1653   }
1654 
1655   bool isVecListFourDAllLanes() const {
1656     if (!isSingleSpacedVectorAllLanes()) return false;
1657     return VectorList.Count == 4;
1658   }
1659 
1660   bool isVecListFourQAllLanes() const {
1661     if (!isDoubleSpacedVectorAllLanes()) return false;
1662     return VectorList.Count == 4;
1663   }
1664 
1665   bool isSingleSpacedVectorIndexed() const {
1666     return Kind == k_VectorListIndexed && !VectorList.isDoubleSpaced;
1667   }
1668 
1669   bool isDoubleSpacedVectorIndexed() const {
1670     return Kind == k_VectorListIndexed && VectorList.isDoubleSpaced;
1671   }
1672 
1673   bool isVecListOneDByteIndexed() const {
1674     if (!isSingleSpacedVectorIndexed()) return false;
1675     return VectorList.Count == 1 && VectorList.LaneIndex <= 7;
1676   }
1677 
1678   bool isVecListOneDHWordIndexed() const {
1679     if (!isSingleSpacedVectorIndexed()) return false;
1680     return VectorList.Count == 1 && VectorList.LaneIndex <= 3;
1681   }
1682 
1683   bool isVecListOneDWordIndexed() const {
1684     if (!isSingleSpacedVectorIndexed()) return false;
1685     return VectorList.Count == 1 && VectorList.LaneIndex <= 1;
1686   }
1687 
1688   bool isVecListTwoDByteIndexed() const {
1689     if (!isSingleSpacedVectorIndexed()) return false;
1690     return VectorList.Count == 2 && VectorList.LaneIndex <= 7;
1691   }
1692 
1693   bool isVecListTwoDHWordIndexed() const {
1694     if (!isSingleSpacedVectorIndexed()) return false;
1695     return VectorList.Count == 2 && VectorList.LaneIndex <= 3;
1696   }
1697 
1698   bool isVecListTwoQWordIndexed() const {
1699     if (!isDoubleSpacedVectorIndexed()) return false;
1700     return VectorList.Count == 2 && VectorList.LaneIndex <= 1;
1701   }
1702 
1703   bool isVecListTwoQHWordIndexed() const {
1704     if (!isDoubleSpacedVectorIndexed()) return false;
1705     return VectorList.Count == 2 && VectorList.LaneIndex <= 3;
1706   }
1707 
1708   bool isVecListTwoDWordIndexed() const {
1709     if (!isSingleSpacedVectorIndexed()) return false;
1710     return VectorList.Count == 2 && VectorList.LaneIndex <= 1;
1711   }
1712 
1713   bool isVecListThreeDByteIndexed() const {
1714     if (!isSingleSpacedVectorIndexed()) return false;
1715     return VectorList.Count == 3 && VectorList.LaneIndex <= 7;
1716   }
1717 
1718   bool isVecListThreeDHWordIndexed() const {
1719     if (!isSingleSpacedVectorIndexed()) return false;
1720     return VectorList.Count == 3 && VectorList.LaneIndex <= 3;
1721   }
1722 
1723   bool isVecListThreeQWordIndexed() const {
1724     if (!isDoubleSpacedVectorIndexed()) return false;
1725     return VectorList.Count == 3 && VectorList.LaneIndex <= 1;
1726   }
1727 
1728   bool isVecListThreeQHWordIndexed() const {
1729     if (!isDoubleSpacedVectorIndexed()) return false;
1730     return VectorList.Count == 3 && VectorList.LaneIndex <= 3;
1731   }
1732 
1733   bool isVecListThreeDWordIndexed() const {
1734     if (!isSingleSpacedVectorIndexed()) return false;
1735     return VectorList.Count == 3 && VectorList.LaneIndex <= 1;
1736   }
1737 
1738   bool isVecListFourDByteIndexed() const {
1739     if (!isSingleSpacedVectorIndexed()) return false;
1740     return VectorList.Count == 4 && VectorList.LaneIndex <= 7;
1741   }
1742 
1743   bool isVecListFourDHWordIndexed() const {
1744     if (!isSingleSpacedVectorIndexed()) return false;
1745     return VectorList.Count == 4 && VectorList.LaneIndex <= 3;
1746   }
1747 
1748   bool isVecListFourQWordIndexed() const {
1749     if (!isDoubleSpacedVectorIndexed()) return false;
1750     return VectorList.Count == 4 && VectorList.LaneIndex <= 1;
1751   }
1752 
1753   bool isVecListFourQHWordIndexed() const {
1754     if (!isDoubleSpacedVectorIndexed()) return false;
1755     return VectorList.Count == 4 && VectorList.LaneIndex <= 3;
1756   }
1757 
1758   bool isVecListFourDWordIndexed() const {
1759     if (!isSingleSpacedVectorIndexed()) return false;
1760     return VectorList.Count == 4 && VectorList.LaneIndex <= 1;
1761   }
1762 
1763   bool isVectorIndex8() const {
1764     if (Kind != k_VectorIndex) return false;
1765     return VectorIndex.Val < 8;
1766   }
1767 
1768   bool isVectorIndex16() const {
1769     if (Kind != k_VectorIndex) return false;
1770     return VectorIndex.Val < 4;
1771   }
1772 
1773   bool isVectorIndex32() const {
1774     if (Kind != k_VectorIndex) return false;
1775     return VectorIndex.Val < 2;
1776   }
1777   bool isVectorIndex64() const {
1778     if (Kind != k_VectorIndex) return false;
1779     return VectorIndex.Val < 1;
1780   }
1781 
1782   bool isNEONi8splat() const {
1783     if (!isImm()) return false;
1784     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1785     // Must be a constant.
1786     if (!CE) return false;
1787     int64_t Value = CE->getValue();
1788     // i8 value splatted across 8 bytes. The immediate is just the 8 byte
1789     // value.
1790     return Value >= 0 && Value < 256;
1791   }
1792 
1793   bool isNEONi16splat() const {
1794     if (isNEONByteReplicate(2))
1795       return false; // Leave that for bytes replication and forbid by default.
1796     if (!isImm())
1797       return false;
1798     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1799     // Must be a constant.
1800     if (!CE) return false;
1801     unsigned Value = CE->getValue();
1802     return ARM_AM::isNEONi16splat(Value);
1803   }
1804 
1805   bool isNEONi16splatNot() const {
1806     if (!isImm())
1807       return false;
1808     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1809     // Must be a constant.
1810     if (!CE) return false;
1811     unsigned Value = CE->getValue();
1812     return ARM_AM::isNEONi16splat(~Value & 0xffff);
1813   }
1814 
1815   bool isNEONi32splat() const {
1816     if (isNEONByteReplicate(4))
1817       return false; // Leave that for bytes replication and forbid by default.
1818     if (!isImm())
1819       return false;
1820     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1821     // Must be a constant.
1822     if (!CE) return false;
1823     unsigned Value = CE->getValue();
1824     return ARM_AM::isNEONi32splat(Value);
1825   }
1826 
1827   bool isNEONi32splatNot() const {
1828     if (!isImm())
1829       return false;
1830     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1831     // Must be a constant.
1832     if (!CE) return false;
1833     unsigned Value = CE->getValue();
1834     return ARM_AM::isNEONi32splat(~Value);
1835   }
1836 
1837   bool isNEONByteReplicate(unsigned NumBytes) const {
1838     if (!isImm())
1839       return false;
1840     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1841     // Must be a constant.
1842     if (!CE)
1843       return false;
1844     int64_t Value = CE->getValue();
1845     if (!Value)
1846       return false; // Don't bother with zero.
1847 
1848     unsigned char B = Value & 0xff;
1849     for (unsigned i = 1; i < NumBytes; ++i) {
1850       Value >>= 8;
1851       if ((Value & 0xff) != B)
1852         return false;
1853     }
1854     return true;
1855   }
1856 
1857   bool isNEONi16ByteReplicate() const { return isNEONByteReplicate(2); }
1858   bool isNEONi32ByteReplicate() const { return isNEONByteReplicate(4); }
1859 
1860   bool isNEONi32vmov() const {
1861     if (isNEONByteReplicate(4))
1862       return false; // Let it to be classified as byte-replicate case.
1863     if (!isImm())
1864       return false;
1865     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1866     // Must be a constant.
1867     if (!CE)
1868       return false;
1869     int64_t Value = CE->getValue();
1870     // i32 value with set bits only in one byte X000, 0X00, 00X0, or 000X,
1871     // for VMOV/VMVN only, 00Xf or 0Xff are also accepted.
1872     // FIXME: This is probably wrong and a copy and paste from previous example
1873     return (Value >= 0 && Value < 256) ||
1874       (Value >= 0x0100 && Value <= 0xff00) ||
1875       (Value >= 0x010000 && Value <= 0xff0000) ||
1876       (Value >= 0x01000000 && Value <= 0xff000000) ||
1877       (Value >= 0x01ff && Value <= 0xffff && (Value & 0xff) == 0xff) ||
1878       (Value >= 0x01ffff && Value <= 0xffffff && (Value & 0xffff) == 0xffff);
1879   }
1880 
1881   bool isNEONi32vmovNeg() const {
1882     if (!isImm()) return false;
1883     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1884     // Must be a constant.
1885     if (!CE) return false;
1886     int64_t Value = ~CE->getValue();
1887     // i32 value with set bits only in one byte X000, 0X00, 00X0, or 000X,
1888     // for VMOV/VMVN only, 00Xf or 0Xff are also accepted.
1889     // FIXME: This is probably wrong and a copy and paste from previous example
1890     return (Value >= 0 && Value < 256) ||
1891       (Value >= 0x0100 && Value <= 0xff00) ||
1892       (Value >= 0x010000 && Value <= 0xff0000) ||
1893       (Value >= 0x01000000 && Value <= 0xff000000) ||
1894       (Value >= 0x01ff && Value <= 0xffff && (Value & 0xff) == 0xff) ||
1895       (Value >= 0x01ffff && Value <= 0xffffff && (Value & 0xffff) == 0xffff);
1896   }
1897 
1898   bool isNEONi64splat() const {
1899     if (!isImm()) return false;
1900     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1901     // Must be a constant.
1902     if (!CE) return false;
1903     uint64_t Value = CE->getValue();
1904     // i64 value with each byte being either 0 or 0xff.
1905     for (unsigned i = 0; i < 8; ++i, Value >>= 8)
1906       if ((Value & 0xff) != 0 && (Value & 0xff) != 0xff) return false;
1907     return true;
1908   }
1909 
1910   template<int64_t Angle, int64_t Remainder>
1911   bool isComplexRotation() const {
1912     if (!isImm()) return false;
1913 
1914     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1915     if (!CE) return false;
1916     uint64_t Value = CE->getValue();
1917 
1918     return (Value % Angle == Remainder && Value <= 270);
1919   }
1920 
1921   void addExpr(MCInst &Inst, const MCExpr *Expr) const {
1922     // Add as immediates when possible.  Null MCExpr = 0.
1923     if (!Expr)
1924       Inst.addOperand(MCOperand::createImm(0));
1925     else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
1926       Inst.addOperand(MCOperand::createImm(CE->getValue()));
1927     else
1928       Inst.addOperand(MCOperand::createExpr(Expr));
1929   }
1930 
1931   void addARMBranchTargetOperands(MCInst &Inst, unsigned N) const {
1932     assert(N == 1 && "Invalid number of operands!");
1933     addExpr(Inst, getImm());
1934   }
1935 
1936   void addThumbBranchTargetOperands(MCInst &Inst, unsigned N) const {
1937     assert(N == 1 && "Invalid number of operands!");
1938     addExpr(Inst, getImm());
1939   }
1940 
1941   void addCondCodeOperands(MCInst &Inst, unsigned N) const {
1942     assert(N == 2 && "Invalid number of operands!");
1943     Inst.addOperand(MCOperand::createImm(unsigned(getCondCode())));
1944     unsigned RegNum = getCondCode() == ARMCC::AL ? 0: ARM::CPSR;
1945     Inst.addOperand(MCOperand::createReg(RegNum));
1946   }
1947 
1948   void addCoprocNumOperands(MCInst &Inst, unsigned N) const {
1949     assert(N == 1 && "Invalid number of operands!");
1950     Inst.addOperand(MCOperand::createImm(getCoproc()));
1951   }
1952 
1953   void addCoprocRegOperands(MCInst &Inst, unsigned N) const {
1954     assert(N == 1 && "Invalid number of operands!");
1955     Inst.addOperand(MCOperand::createImm(getCoproc()));
1956   }
1957 
1958   void addCoprocOptionOperands(MCInst &Inst, unsigned N) const {
1959     assert(N == 1 && "Invalid number of operands!");
1960     Inst.addOperand(MCOperand::createImm(CoprocOption.Val));
1961   }
1962 
1963   void addITMaskOperands(MCInst &Inst, unsigned N) const {
1964     assert(N == 1 && "Invalid number of operands!");
1965     Inst.addOperand(MCOperand::createImm(ITMask.Mask));
1966   }
1967 
1968   void addITCondCodeOperands(MCInst &Inst, unsigned N) const {
1969     assert(N == 1 && "Invalid number of operands!");
1970     Inst.addOperand(MCOperand::createImm(unsigned(getCondCode())));
1971   }
1972 
1973   void addCCOutOperands(MCInst &Inst, unsigned N) const {
1974     assert(N == 1 && "Invalid number of operands!");
1975     Inst.addOperand(MCOperand::createReg(getReg()));
1976   }
1977 
1978   void addRegOperands(MCInst &Inst, unsigned N) const {
1979     assert(N == 1 && "Invalid number of operands!");
1980     Inst.addOperand(MCOperand::createReg(getReg()));
1981   }
1982 
1983   void addRegShiftedRegOperands(MCInst &Inst, unsigned N) const {
1984     assert(N == 3 && "Invalid number of operands!");
1985     assert(isRegShiftedReg() &&
1986            "addRegShiftedRegOperands() on non-RegShiftedReg!");
1987     Inst.addOperand(MCOperand::createReg(RegShiftedReg.SrcReg));
1988     Inst.addOperand(MCOperand::createReg(RegShiftedReg.ShiftReg));
1989     Inst.addOperand(MCOperand::createImm(
1990       ARM_AM::getSORegOpc(RegShiftedReg.ShiftTy, RegShiftedReg.ShiftImm)));
1991   }
1992 
1993   void addRegShiftedImmOperands(MCInst &Inst, unsigned N) const {
1994     assert(N == 2 && "Invalid number of operands!");
1995     assert(isRegShiftedImm() &&
1996            "addRegShiftedImmOperands() on non-RegShiftedImm!");
1997     Inst.addOperand(MCOperand::createReg(RegShiftedImm.SrcReg));
1998     // Shift of #32 is encoded as 0 where permitted
1999     unsigned Imm = (RegShiftedImm.ShiftImm == 32 ? 0 : RegShiftedImm.ShiftImm);
2000     Inst.addOperand(MCOperand::createImm(
2001       ARM_AM::getSORegOpc(RegShiftedImm.ShiftTy, Imm)));
2002   }
2003 
2004   void addShifterImmOperands(MCInst &Inst, unsigned N) const {
2005     assert(N == 1 && "Invalid number of operands!");
2006     Inst.addOperand(MCOperand::createImm((ShifterImm.isASR << 5) |
2007                                          ShifterImm.Imm));
2008   }
2009 
2010   void addRegListOperands(MCInst &Inst, unsigned N) const {
2011     assert(N == 1 && "Invalid number of operands!");
2012     const SmallVectorImpl<unsigned> &RegList = getRegList();
2013     for (SmallVectorImpl<unsigned>::const_iterator
2014            I = RegList.begin(), E = RegList.end(); I != E; ++I)
2015       Inst.addOperand(MCOperand::createReg(*I));
2016   }
2017 
2018   void addDPRRegListOperands(MCInst &Inst, unsigned N) const {
2019     addRegListOperands(Inst, N);
2020   }
2021 
2022   void addSPRRegListOperands(MCInst &Inst, unsigned N) const {
2023     addRegListOperands(Inst, N);
2024   }
2025 
2026   void addRotImmOperands(MCInst &Inst, unsigned N) const {
2027     assert(N == 1 && "Invalid number of operands!");
2028     // Encoded as val>>3. The printer handles display as 8, 16, 24.
2029     Inst.addOperand(MCOperand::createImm(RotImm.Imm >> 3));
2030   }
2031 
2032   void addModImmOperands(MCInst &Inst, unsigned N) const {
2033     assert(N == 1 && "Invalid number of operands!");
2034 
2035     // Support for fixups (MCFixup)
2036     if (isImm())
2037       return addImmOperands(Inst, N);
2038 
2039     Inst.addOperand(MCOperand::createImm(ModImm.Bits | (ModImm.Rot << 7)));
2040   }
2041 
2042   void addModImmNotOperands(MCInst &Inst, unsigned N) const {
2043     assert(N == 1 && "Invalid number of operands!");
2044     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2045     uint32_t Enc = ARM_AM::getSOImmVal(~CE->getValue());
2046     Inst.addOperand(MCOperand::createImm(Enc));
2047   }
2048 
2049   void addModImmNegOperands(MCInst &Inst, unsigned N) const {
2050     assert(N == 1 && "Invalid number of operands!");
2051     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2052     uint32_t Enc = ARM_AM::getSOImmVal(-CE->getValue());
2053     Inst.addOperand(MCOperand::createImm(Enc));
2054   }
2055 
2056   void addThumbModImmNeg8_255Operands(MCInst &Inst, unsigned N) const {
2057     assert(N == 1 && "Invalid number of operands!");
2058     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2059     uint32_t Val = -CE->getValue();
2060     Inst.addOperand(MCOperand::createImm(Val));
2061   }
2062 
2063   void addThumbModImmNeg1_7Operands(MCInst &Inst, unsigned N) const {
2064     assert(N == 1 && "Invalid number of operands!");
2065     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2066     uint32_t Val = -CE->getValue();
2067     Inst.addOperand(MCOperand::createImm(Val));
2068   }
2069 
2070   void addBitfieldOperands(MCInst &Inst, unsigned N) const {
2071     assert(N == 1 && "Invalid number of operands!");
2072     // Munge the lsb/width into a bitfield mask.
2073     unsigned lsb = Bitfield.LSB;
2074     unsigned width = Bitfield.Width;
2075     // Make a 32-bit mask w/ the referenced bits clear and all other bits set.
2076     uint32_t Mask = ~(((uint32_t)0xffffffff >> lsb) << (32 - width) >>
2077                       (32 - (lsb + width)));
2078     Inst.addOperand(MCOperand::createImm(Mask));
2079   }
2080 
2081   void addImmOperands(MCInst &Inst, unsigned N) const {
2082     assert(N == 1 && "Invalid number of operands!");
2083     addExpr(Inst, getImm());
2084   }
2085 
2086   void addFBits16Operands(MCInst &Inst, unsigned N) const {
2087     assert(N == 1 && "Invalid number of operands!");
2088     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2089     Inst.addOperand(MCOperand::createImm(16 - CE->getValue()));
2090   }
2091 
2092   void addFBits32Operands(MCInst &Inst, unsigned N) const {
2093     assert(N == 1 && "Invalid number of operands!");
2094     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2095     Inst.addOperand(MCOperand::createImm(32 - CE->getValue()));
2096   }
2097 
2098   void addFPImmOperands(MCInst &Inst, unsigned N) const {
2099     assert(N == 1 && "Invalid number of operands!");
2100     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2101     int Val = ARM_AM::getFP32Imm(APInt(32, CE->getValue()));
2102     Inst.addOperand(MCOperand::createImm(Val));
2103   }
2104 
2105   void addImm8s4Operands(MCInst &Inst, unsigned N) const {
2106     assert(N == 1 && "Invalid number of operands!");
2107     // FIXME: We really want to scale the value here, but the LDRD/STRD
2108     // instruction don't encode operands that way yet.
2109     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2110     Inst.addOperand(MCOperand::createImm(CE->getValue()));
2111   }
2112 
2113   void addImm0_1020s4Operands(MCInst &Inst, unsigned N) const {
2114     assert(N == 1 && "Invalid number of operands!");
2115     // The immediate is scaled by four in the encoding and is stored
2116     // in the MCInst as such. Lop off the low two bits here.
2117     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2118     Inst.addOperand(MCOperand::createImm(CE->getValue() / 4));
2119   }
2120 
2121   void addImm0_508s4NegOperands(MCInst &Inst, unsigned N) const {
2122     assert(N == 1 && "Invalid number of operands!");
2123     // The immediate is scaled by four in the encoding and is stored
2124     // in the MCInst as such. Lop off the low two bits here.
2125     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2126     Inst.addOperand(MCOperand::createImm(-(CE->getValue() / 4)));
2127   }
2128 
2129   void addImm0_508s4Operands(MCInst &Inst, unsigned N) const {
2130     assert(N == 1 && "Invalid number of operands!");
2131     // The immediate is scaled by four in the encoding and is stored
2132     // in the MCInst as such. Lop off the low two bits here.
2133     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2134     Inst.addOperand(MCOperand::createImm(CE->getValue() / 4));
2135   }
2136 
2137   void addImm1_16Operands(MCInst &Inst, unsigned N) const {
2138     assert(N == 1 && "Invalid number of operands!");
2139     // The constant encodes as the immediate-1, and we store in the instruction
2140     // the bits as encoded, so subtract off one here.
2141     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2142     Inst.addOperand(MCOperand::createImm(CE->getValue() - 1));
2143   }
2144 
2145   void addImm1_32Operands(MCInst &Inst, unsigned N) const {
2146     assert(N == 1 && "Invalid number of operands!");
2147     // The constant encodes as the immediate-1, and we store in the instruction
2148     // the bits as encoded, so subtract off one here.
2149     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2150     Inst.addOperand(MCOperand::createImm(CE->getValue() - 1));
2151   }
2152 
2153   void addImmThumbSROperands(MCInst &Inst, unsigned N) const {
2154     assert(N == 1 && "Invalid number of operands!");
2155     // The constant encodes as the immediate, except for 32, which encodes as
2156     // zero.
2157     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2158     unsigned Imm = CE->getValue();
2159     Inst.addOperand(MCOperand::createImm((Imm == 32 ? 0 : Imm)));
2160   }
2161 
2162   void addPKHASRImmOperands(MCInst &Inst, unsigned N) const {
2163     assert(N == 1 && "Invalid number of operands!");
2164     // An ASR value of 32 encodes as 0, so that's how we want to add it to
2165     // the instruction as well.
2166     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2167     int Val = CE->getValue();
2168     Inst.addOperand(MCOperand::createImm(Val == 32 ? 0 : Val));
2169   }
2170 
2171   void addT2SOImmNotOperands(MCInst &Inst, unsigned N) const {
2172     assert(N == 1 && "Invalid number of operands!");
2173     // The operand is actually a t2_so_imm, but we have its bitwise
2174     // negation in the assembly source, so twiddle it here.
2175     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2176     Inst.addOperand(MCOperand::createImm(~(uint32_t)CE->getValue()));
2177   }
2178 
2179   void addT2SOImmNegOperands(MCInst &Inst, unsigned N) const {
2180     assert(N == 1 && "Invalid number of operands!");
2181     // The operand is actually a t2_so_imm, but we have its
2182     // negation in the assembly source, so twiddle it here.
2183     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2184     Inst.addOperand(MCOperand::createImm(-(uint32_t)CE->getValue()));
2185   }
2186 
2187   void addImm0_4095NegOperands(MCInst &Inst, unsigned N) const {
2188     assert(N == 1 && "Invalid number of operands!");
2189     // The operand is actually an imm0_4095, but we have its
2190     // negation in the assembly source, so twiddle it here.
2191     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2192     Inst.addOperand(MCOperand::createImm(-CE->getValue()));
2193   }
2194 
2195   void addUnsignedOffset_b8s2Operands(MCInst &Inst, unsigned N) const {
2196     if(const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm())) {
2197       Inst.addOperand(MCOperand::createImm(CE->getValue() >> 2));
2198       return;
2199     }
2200 
2201     const MCSymbolRefExpr *SR = dyn_cast<MCSymbolRefExpr>(Imm.Val);
2202     assert(SR && "Unknown value type!");
2203     Inst.addOperand(MCOperand::createExpr(SR));
2204   }
2205 
2206   void addThumbMemPCOperands(MCInst &Inst, unsigned N) const {
2207     assert(N == 1 && "Invalid number of operands!");
2208     if (isImm()) {
2209       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2210       if (CE) {
2211         Inst.addOperand(MCOperand::createImm(CE->getValue()));
2212         return;
2213       }
2214 
2215       const MCSymbolRefExpr *SR = dyn_cast<MCSymbolRefExpr>(Imm.Val);
2216 
2217       assert(SR && "Unknown value type!");
2218       Inst.addOperand(MCOperand::createExpr(SR));
2219       return;
2220     }
2221 
2222     assert(isMem()  && "Unknown value type!");
2223     assert(isa<MCConstantExpr>(Memory.OffsetImm) && "Unknown value type!");
2224     Inst.addOperand(MCOperand::createImm(Memory.OffsetImm->getValue()));
2225   }
2226 
2227   void addMemBarrierOptOperands(MCInst &Inst, unsigned N) const {
2228     assert(N == 1 && "Invalid number of operands!");
2229     Inst.addOperand(MCOperand::createImm(unsigned(getMemBarrierOpt())));
2230   }
2231 
2232   void addInstSyncBarrierOptOperands(MCInst &Inst, unsigned N) const {
2233     assert(N == 1 && "Invalid number of operands!");
2234     Inst.addOperand(MCOperand::createImm(unsigned(getInstSyncBarrierOpt())));
2235   }
2236 
2237   void addMemNoOffsetOperands(MCInst &Inst, unsigned N) const {
2238     assert(N == 1 && "Invalid number of operands!");
2239     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2240   }
2241 
2242   void addMemPCRelImm12Operands(MCInst &Inst, unsigned N) const {
2243     assert(N == 1 && "Invalid number of operands!");
2244     int32_t Imm = Memory.OffsetImm->getValue();
2245     Inst.addOperand(MCOperand::createImm(Imm));
2246   }
2247 
2248   void addAdrLabelOperands(MCInst &Inst, unsigned N) const {
2249     assert(N == 1 && "Invalid number of operands!");
2250     assert(isImm() && "Not an immediate!");
2251 
2252     // If we have an immediate that's not a constant, treat it as a label
2253     // reference needing a fixup.
2254     if (!isa<MCConstantExpr>(getImm())) {
2255       Inst.addOperand(MCOperand::createExpr(getImm()));
2256       return;
2257     }
2258 
2259     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2260     int Val = CE->getValue();
2261     Inst.addOperand(MCOperand::createImm(Val));
2262   }
2263 
2264   void addAlignedMemoryOperands(MCInst &Inst, unsigned N) const {
2265     assert(N == 2 && "Invalid number of operands!");
2266     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2267     Inst.addOperand(MCOperand::createImm(Memory.Alignment));
2268   }
2269 
2270   void addDupAlignedMemoryNoneOperands(MCInst &Inst, unsigned N) const {
2271     addAlignedMemoryOperands(Inst, N);
2272   }
2273 
2274   void addAlignedMemoryNoneOperands(MCInst &Inst, unsigned N) const {
2275     addAlignedMemoryOperands(Inst, N);
2276   }
2277 
2278   void addAlignedMemory16Operands(MCInst &Inst, unsigned N) const {
2279     addAlignedMemoryOperands(Inst, N);
2280   }
2281 
2282   void addDupAlignedMemory16Operands(MCInst &Inst, unsigned N) const {
2283     addAlignedMemoryOperands(Inst, N);
2284   }
2285 
2286   void addAlignedMemory32Operands(MCInst &Inst, unsigned N) const {
2287     addAlignedMemoryOperands(Inst, N);
2288   }
2289 
2290   void addDupAlignedMemory32Operands(MCInst &Inst, unsigned N) const {
2291     addAlignedMemoryOperands(Inst, N);
2292   }
2293 
2294   void addAlignedMemory64Operands(MCInst &Inst, unsigned N) const {
2295     addAlignedMemoryOperands(Inst, N);
2296   }
2297 
2298   void addDupAlignedMemory64Operands(MCInst &Inst, unsigned N) const {
2299     addAlignedMemoryOperands(Inst, N);
2300   }
2301 
2302   void addAlignedMemory64or128Operands(MCInst &Inst, unsigned N) const {
2303     addAlignedMemoryOperands(Inst, N);
2304   }
2305 
2306   void addDupAlignedMemory64or128Operands(MCInst &Inst, unsigned N) const {
2307     addAlignedMemoryOperands(Inst, N);
2308   }
2309 
2310   void addAlignedMemory64or128or256Operands(MCInst &Inst, unsigned N) const {
2311     addAlignedMemoryOperands(Inst, N);
2312   }
2313 
2314   void addAddrMode2Operands(MCInst &Inst, unsigned N) const {
2315     assert(N == 3 && "Invalid number of operands!");
2316     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2317     if (!Memory.OffsetRegNum) {
2318       ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2319       // Special case for #-0
2320       if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2321       if (Val < 0) Val = -Val;
2322       Val = ARM_AM::getAM2Opc(AddSub, Val, ARM_AM::no_shift);
2323     } else {
2324       // For register offset, we encode the shift type and negation flag
2325       // here.
2326       Val = ARM_AM::getAM2Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add,
2327                               Memory.ShiftImm, Memory.ShiftType);
2328     }
2329     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2330     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2331     Inst.addOperand(MCOperand::createImm(Val));
2332   }
2333 
2334   void addAM2OffsetImmOperands(MCInst &Inst, unsigned N) const {
2335     assert(N == 2 && "Invalid number of operands!");
2336     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2337     assert(CE && "non-constant AM2OffsetImm operand!");
2338     int32_t Val = CE->getValue();
2339     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2340     // Special case for #-0
2341     if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2342     if (Val < 0) Val = -Val;
2343     Val = ARM_AM::getAM2Opc(AddSub, Val, ARM_AM::no_shift);
2344     Inst.addOperand(MCOperand::createReg(0));
2345     Inst.addOperand(MCOperand::createImm(Val));
2346   }
2347 
2348   void addAddrMode3Operands(MCInst &Inst, unsigned N) const {
2349     assert(N == 3 && "Invalid number of operands!");
2350     // If we have an immediate that's not a constant, treat it as a label
2351     // reference needing a fixup. If it is a constant, it's something else
2352     // and we reject it.
2353     if (isImm()) {
2354       Inst.addOperand(MCOperand::createExpr(getImm()));
2355       Inst.addOperand(MCOperand::createReg(0));
2356       Inst.addOperand(MCOperand::createImm(0));
2357       return;
2358     }
2359 
2360     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2361     if (!Memory.OffsetRegNum) {
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::getAM3Opc(AddSub, Val);
2367     } else {
2368       // For register offset, we encode the shift type and negation flag
2369       // here.
2370       Val = ARM_AM::getAM3Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add, 0);
2371     }
2372     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2373     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2374     Inst.addOperand(MCOperand::createImm(Val));
2375   }
2376 
2377   void addAM3OffsetOperands(MCInst &Inst, unsigned N) const {
2378     assert(N == 2 && "Invalid number of operands!");
2379     if (Kind == k_PostIndexRegister) {
2380       int32_t Val =
2381         ARM_AM::getAM3Opc(PostIdxReg.isAdd ? ARM_AM::add : ARM_AM::sub, 0);
2382       Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
2383       Inst.addOperand(MCOperand::createImm(Val));
2384       return;
2385     }
2386 
2387     // Constant offset.
2388     const MCConstantExpr *CE = static_cast<const MCConstantExpr*>(getImm());
2389     int32_t Val = CE->getValue();
2390     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2391     // Special case for #-0
2392     if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2393     if (Val < 0) Val = -Val;
2394     Val = ARM_AM::getAM3Opc(AddSub, Val);
2395     Inst.addOperand(MCOperand::createReg(0));
2396     Inst.addOperand(MCOperand::createImm(Val));
2397   }
2398 
2399   void addAddrMode5Operands(MCInst &Inst, unsigned N) const {
2400     assert(N == 2 && "Invalid number of operands!");
2401     // If we have an immediate that's not a constant, treat it as a label
2402     // reference needing a fixup. If it is a constant, it's something else
2403     // and we reject it.
2404     if (isImm()) {
2405       Inst.addOperand(MCOperand::createExpr(getImm()));
2406       Inst.addOperand(MCOperand::createImm(0));
2407       return;
2408     }
2409 
2410     // The lower two bits are always zero and as such are not encoded.
2411     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 4 : 0;
2412     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2413     // Special case for #-0
2414     if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2415     if (Val < 0) Val = -Val;
2416     Val = ARM_AM::getAM5Opc(AddSub, Val);
2417     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2418     Inst.addOperand(MCOperand::createImm(Val));
2419   }
2420 
2421   void addAddrMode5FP16Operands(MCInst &Inst, unsigned N) const {
2422     assert(N == 2 && "Invalid number of operands!");
2423     // If we have an immediate that's not a constant, treat it as a label
2424     // reference needing a fixup. If it is a constant, it's something else
2425     // and we reject it.
2426     if (isImm()) {
2427       Inst.addOperand(MCOperand::createExpr(getImm()));
2428       Inst.addOperand(MCOperand::createImm(0));
2429       return;
2430     }
2431 
2432     // The lower bit is always zero and as such is not encoded.
2433     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 2 : 0;
2434     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2435     // Special case for #-0
2436     if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2437     if (Val < 0) Val = -Val;
2438     Val = ARM_AM::getAM5FP16Opc(AddSub, Val);
2439     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2440     Inst.addOperand(MCOperand::createImm(Val));
2441   }
2442 
2443   void addMemImm8s4OffsetOperands(MCInst &Inst, unsigned N) const {
2444     assert(N == 2 && "Invalid number of operands!");
2445     // If we have an immediate that's not a constant, treat it as a label
2446     // reference needing a fixup. If it is a constant, it's something else
2447     // and we reject it.
2448     if (isImm()) {
2449       Inst.addOperand(MCOperand::createExpr(getImm()));
2450       Inst.addOperand(MCOperand::createImm(0));
2451       return;
2452     }
2453 
2454     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2455     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2456     Inst.addOperand(MCOperand::createImm(Val));
2457   }
2458 
2459   void addMemImm0_1020s4OffsetOperands(MCInst &Inst, unsigned N) const {
2460     assert(N == 2 && "Invalid number of operands!");
2461     // The lower two bits are always zero and as such are not encoded.
2462     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 4 : 0;
2463     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2464     Inst.addOperand(MCOperand::createImm(Val));
2465   }
2466 
2467   void addMemImm8OffsetOperands(MCInst &Inst, unsigned N) const {
2468     assert(N == 2 && "Invalid number of operands!");
2469     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2470     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2471     Inst.addOperand(MCOperand::createImm(Val));
2472   }
2473 
2474   void addMemPosImm8OffsetOperands(MCInst &Inst, unsigned N) const {
2475     addMemImm8OffsetOperands(Inst, N);
2476   }
2477 
2478   void addMemNegImm8OffsetOperands(MCInst &Inst, unsigned N) const {
2479     addMemImm8OffsetOperands(Inst, N);
2480   }
2481 
2482   void addMemUImm12OffsetOperands(MCInst &Inst, unsigned N) const {
2483     assert(N == 2 && "Invalid number of operands!");
2484     // If this is an immediate, it's a label reference.
2485     if (isImm()) {
2486       addExpr(Inst, getImm());
2487       Inst.addOperand(MCOperand::createImm(0));
2488       return;
2489     }
2490 
2491     // Otherwise, it's a normal memory reg+offset.
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 addMemImm12OffsetOperands(MCInst &Inst, unsigned N) const {
2498     assert(N == 2 && "Invalid number of operands!");
2499     // If this is an immediate, it's a label reference.
2500     if (isImm()) {
2501       addExpr(Inst, getImm());
2502       Inst.addOperand(MCOperand::createImm(0));
2503       return;
2504     }
2505 
2506     // Otherwise, it's a normal memory reg+offset.
2507     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2508     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2509     Inst.addOperand(MCOperand::createImm(Val));
2510   }
2511 
2512   void addConstPoolAsmImmOperands(MCInst &Inst, unsigned N) const {
2513     assert(N == 1 && "Invalid number of operands!");
2514     // This is container for the immediate that we will create the constant
2515     // pool from
2516     addExpr(Inst, getConstantPoolImm());
2517     return;
2518   }
2519 
2520   void addMemTBBOperands(MCInst &Inst, unsigned N) const {
2521     assert(N == 2 && "Invalid number of operands!");
2522     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2523     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2524   }
2525 
2526   void addMemTBHOperands(MCInst &Inst, unsigned N) const {
2527     assert(N == 2 && "Invalid number of operands!");
2528     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2529     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2530   }
2531 
2532   void addMemRegOffsetOperands(MCInst &Inst, unsigned N) const {
2533     assert(N == 3 && "Invalid number of operands!");
2534     unsigned Val =
2535       ARM_AM::getAM2Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add,
2536                         Memory.ShiftImm, Memory.ShiftType);
2537     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2538     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2539     Inst.addOperand(MCOperand::createImm(Val));
2540   }
2541 
2542   void addT2MemRegOffsetOperands(MCInst &Inst, unsigned N) const {
2543     assert(N == 3 && "Invalid number of operands!");
2544     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2545     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2546     Inst.addOperand(MCOperand::createImm(Memory.ShiftImm));
2547   }
2548 
2549   void addMemThumbRROperands(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 addMemThumbRIs4Operands(MCInst &Inst, unsigned N) const {
2556     assert(N == 2 && "Invalid number of operands!");
2557     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 4) : 0;
2558     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2559     Inst.addOperand(MCOperand::createImm(Val));
2560   }
2561 
2562   void addMemThumbRIs2Operands(MCInst &Inst, unsigned N) const {
2563     assert(N == 2 && "Invalid number of operands!");
2564     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 2) : 0;
2565     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2566     Inst.addOperand(MCOperand::createImm(Val));
2567   }
2568 
2569   void addMemThumbRIs1Operands(MCInst &Inst, unsigned N) const {
2570     assert(N == 2 && "Invalid number of operands!");
2571     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue()) : 0;
2572     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2573     Inst.addOperand(MCOperand::createImm(Val));
2574   }
2575 
2576   void addMemThumbSPIOperands(MCInst &Inst, unsigned N) const {
2577     assert(N == 2 && "Invalid number of operands!");
2578     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 4) : 0;
2579     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2580     Inst.addOperand(MCOperand::createImm(Val));
2581   }
2582 
2583   void addPostIdxImm8Operands(MCInst &Inst, unsigned N) const {
2584     assert(N == 1 && "Invalid number of operands!");
2585     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2586     assert(CE && "non-constant post-idx-imm8 operand!");
2587     int Imm = CE->getValue();
2588     bool isAdd = Imm >= 0;
2589     if (Imm == std::numeric_limits<int32_t>::min()) Imm = 0;
2590     Imm = (Imm < 0 ? -Imm : Imm) | (int)isAdd << 8;
2591     Inst.addOperand(MCOperand::createImm(Imm));
2592   }
2593 
2594   void addPostIdxImm8s4Operands(MCInst &Inst, unsigned N) const {
2595     assert(N == 1 && "Invalid number of operands!");
2596     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2597     assert(CE && "non-constant post-idx-imm8s4 operand!");
2598     int Imm = CE->getValue();
2599     bool isAdd = Imm >= 0;
2600     if (Imm == std::numeric_limits<int32_t>::min()) Imm = 0;
2601     // Immediate is scaled by 4.
2602     Imm = ((Imm < 0 ? -Imm : Imm) / 4) | (int)isAdd << 8;
2603     Inst.addOperand(MCOperand::createImm(Imm));
2604   }
2605 
2606   void addPostIdxRegOperands(MCInst &Inst, unsigned N) const {
2607     assert(N == 2 && "Invalid number of operands!");
2608     Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
2609     Inst.addOperand(MCOperand::createImm(PostIdxReg.isAdd));
2610   }
2611 
2612   void addPostIdxRegShiftedOperands(MCInst &Inst, unsigned N) const {
2613     assert(N == 2 && "Invalid number of operands!");
2614     Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
2615     // The sign, shift type, and shift amount are encoded in a single operand
2616     // using the AM2 encoding helpers.
2617     ARM_AM::AddrOpc opc = PostIdxReg.isAdd ? ARM_AM::add : ARM_AM::sub;
2618     unsigned Imm = ARM_AM::getAM2Opc(opc, PostIdxReg.ShiftImm,
2619                                      PostIdxReg.ShiftTy);
2620     Inst.addOperand(MCOperand::createImm(Imm));
2621   }
2622 
2623   void addMSRMaskOperands(MCInst &Inst, unsigned N) const {
2624     assert(N == 1 && "Invalid number of operands!");
2625     Inst.addOperand(MCOperand::createImm(unsigned(getMSRMask())));
2626   }
2627 
2628   void addBankedRegOperands(MCInst &Inst, unsigned N) const {
2629     assert(N == 1 && "Invalid number of operands!");
2630     Inst.addOperand(MCOperand::createImm(unsigned(getBankedReg())));
2631   }
2632 
2633   void addProcIFlagsOperands(MCInst &Inst, unsigned N) const {
2634     assert(N == 1 && "Invalid number of operands!");
2635     Inst.addOperand(MCOperand::createImm(unsigned(getProcIFlags())));
2636   }
2637 
2638   void addVecListOperands(MCInst &Inst, unsigned N) const {
2639     assert(N == 1 && "Invalid number of operands!");
2640     Inst.addOperand(MCOperand::createReg(VectorList.RegNum));
2641   }
2642 
2643   void addVecListIndexedOperands(MCInst &Inst, unsigned N) const {
2644     assert(N == 2 && "Invalid number of operands!");
2645     Inst.addOperand(MCOperand::createReg(VectorList.RegNum));
2646     Inst.addOperand(MCOperand::createImm(VectorList.LaneIndex));
2647   }
2648 
2649   void addVectorIndex8Operands(MCInst &Inst, unsigned N) const {
2650     assert(N == 1 && "Invalid number of operands!");
2651     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
2652   }
2653 
2654   void addVectorIndex16Operands(MCInst &Inst, unsigned N) const {
2655     assert(N == 1 && "Invalid number of operands!");
2656     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
2657   }
2658 
2659   void addVectorIndex32Operands(MCInst &Inst, unsigned N) const {
2660     assert(N == 1 && "Invalid number of operands!");
2661     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
2662   }
2663 
2664   void addVectorIndex64Operands(MCInst &Inst, unsigned N) const {
2665     assert(N == 1 && "Invalid number of operands!");
2666     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
2667   }
2668 
2669   void addNEONi8splatOperands(MCInst &Inst, unsigned N) const {
2670     assert(N == 1 && "Invalid number of operands!");
2671     // The immediate encodes the type of constant as well as the value.
2672     // Mask in that this is an i8 splat.
2673     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2674     Inst.addOperand(MCOperand::createImm(CE->getValue() | 0xe00));
2675   }
2676 
2677   void addNEONi16splatOperands(MCInst &Inst, unsigned N) const {
2678     assert(N == 1 && "Invalid number of operands!");
2679     // The immediate encodes the type of constant as well as the value.
2680     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2681     unsigned Value = CE->getValue();
2682     Value = ARM_AM::encodeNEONi16splat(Value);
2683     Inst.addOperand(MCOperand::createImm(Value));
2684   }
2685 
2686   void addNEONi16splatNotOperands(MCInst &Inst, unsigned N) const {
2687     assert(N == 1 && "Invalid number of operands!");
2688     // The immediate encodes the type of constant as well as the value.
2689     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2690     unsigned Value = CE->getValue();
2691     Value = ARM_AM::encodeNEONi16splat(~Value & 0xffff);
2692     Inst.addOperand(MCOperand::createImm(Value));
2693   }
2694 
2695   void addNEONi32splatOperands(MCInst &Inst, unsigned N) const {
2696     assert(N == 1 && "Invalid number of operands!");
2697     // The immediate encodes the type of constant as well as the value.
2698     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2699     unsigned Value = CE->getValue();
2700     Value = ARM_AM::encodeNEONi32splat(Value);
2701     Inst.addOperand(MCOperand::createImm(Value));
2702   }
2703 
2704   void addNEONi32splatNotOperands(MCInst &Inst, unsigned N) const {
2705     assert(N == 1 && "Invalid number of operands!");
2706     // The immediate encodes the type of constant as well as the value.
2707     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2708     unsigned Value = CE->getValue();
2709     Value = ARM_AM::encodeNEONi32splat(~Value);
2710     Inst.addOperand(MCOperand::createImm(Value));
2711   }
2712 
2713   void addNEONinvByteReplicateOperands(MCInst &Inst, unsigned N) const {
2714     assert(N == 1 && "Invalid number of operands!");
2715     // The immediate encodes the type of constant as well as the value.
2716     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2717     unsigned Value = CE->getValue();
2718     assert((Inst.getOpcode() == ARM::VMOVv8i8 ||
2719             Inst.getOpcode() == ARM::VMOVv16i8) &&
2720            "All vmvn instructions that wants to replicate non-zero byte "
2721            "always must be replaced with VMOVv8i8 or VMOVv16i8.");
2722     unsigned B = ((~Value) & 0xff);
2723     B |= 0xe00; // cmode = 0b1110
2724     Inst.addOperand(MCOperand::createImm(B));
2725   }
2726 
2727   void addNEONi32vmovOperands(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     if (Value >= 256 && Value <= 0xffff)
2733       Value = (Value >> 8) | ((Value & 0xff) ? 0xc00 : 0x200);
2734     else if (Value > 0xffff && Value <= 0xffffff)
2735       Value = (Value >> 16) | ((Value & 0xff) ? 0xd00 : 0x400);
2736     else if (Value > 0xffffff)
2737       Value = (Value >> 24) | 0x600;
2738     Inst.addOperand(MCOperand::createImm(Value));
2739   }
2740 
2741   void addNEONvmovByteReplicateOperands(MCInst &Inst, unsigned N) const {
2742     assert(N == 1 && "Invalid number of operands!");
2743     // The immediate encodes the type of constant as well as the value.
2744     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2745     unsigned Value = CE->getValue();
2746     assert((Inst.getOpcode() == ARM::VMOVv8i8 ||
2747             Inst.getOpcode() == ARM::VMOVv16i8) &&
2748            "All instructions that wants to replicate non-zero byte "
2749            "always must be replaced with VMOVv8i8 or VMOVv16i8.");
2750     unsigned B = Value & 0xff;
2751     B |= 0xe00; // cmode = 0b1110
2752     Inst.addOperand(MCOperand::createImm(B));
2753   }
2754 
2755   void addNEONi32vmovNegOperands(MCInst &Inst, unsigned N) const {
2756     assert(N == 1 && "Invalid number of operands!");
2757     // The immediate encodes the type of constant as well as the value.
2758     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2759     unsigned Value = ~CE->getValue();
2760     if (Value >= 256 && Value <= 0xffff)
2761       Value = (Value >> 8) | ((Value & 0xff) ? 0xc00 : 0x200);
2762     else if (Value > 0xffff && Value <= 0xffffff)
2763       Value = (Value >> 16) | ((Value & 0xff) ? 0xd00 : 0x400);
2764     else if (Value > 0xffffff)
2765       Value = (Value >> 24) | 0x600;
2766     Inst.addOperand(MCOperand::createImm(Value));
2767   }
2768 
2769   void addNEONi64splatOperands(MCInst &Inst, unsigned N) const {
2770     assert(N == 1 && "Invalid number of operands!");
2771     // The immediate encodes the type of constant as well as the value.
2772     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2773     uint64_t Value = CE->getValue();
2774     unsigned Imm = 0;
2775     for (unsigned i = 0; i < 8; ++i, Value >>= 8) {
2776       Imm |= (Value & 1) << i;
2777     }
2778     Inst.addOperand(MCOperand::createImm(Imm | 0x1e00));
2779   }
2780 
2781   void addComplexRotationEvenOperands(MCInst &Inst, unsigned N) const {
2782     assert(N == 1 && "Invalid number of operands!");
2783     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2784     Inst.addOperand(MCOperand::createImm(CE->getValue() / 90));
2785   }
2786 
2787   void addComplexRotationOddOperands(MCInst &Inst, unsigned N) const {
2788     assert(N == 1 && "Invalid number of operands!");
2789     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2790     Inst.addOperand(MCOperand::createImm((CE->getValue() - 90) / 180));
2791   }
2792 
2793   void print(raw_ostream &OS) const override;
2794 
2795   static std::unique_ptr<ARMOperand> CreateITMask(unsigned Mask, SMLoc S) {
2796     auto Op = make_unique<ARMOperand>(k_ITCondMask);
2797     Op->ITMask.Mask = Mask;
2798     Op->StartLoc = S;
2799     Op->EndLoc = S;
2800     return Op;
2801   }
2802 
2803   static std::unique_ptr<ARMOperand> CreateCondCode(ARMCC::CondCodes CC,
2804                                                     SMLoc S) {
2805     auto Op = make_unique<ARMOperand>(k_CondCode);
2806     Op->CC.Val = CC;
2807     Op->StartLoc = S;
2808     Op->EndLoc = S;
2809     return Op;
2810   }
2811 
2812   static std::unique_ptr<ARMOperand> CreateCoprocNum(unsigned CopVal, SMLoc S) {
2813     auto Op = make_unique<ARMOperand>(k_CoprocNum);
2814     Op->Cop.Val = CopVal;
2815     Op->StartLoc = S;
2816     Op->EndLoc = S;
2817     return Op;
2818   }
2819 
2820   static std::unique_ptr<ARMOperand> CreateCoprocReg(unsigned CopVal, SMLoc S) {
2821     auto Op = make_unique<ARMOperand>(k_CoprocReg);
2822     Op->Cop.Val = CopVal;
2823     Op->StartLoc = S;
2824     Op->EndLoc = S;
2825     return Op;
2826   }
2827 
2828   static std::unique_ptr<ARMOperand> CreateCoprocOption(unsigned Val, SMLoc S,
2829                                                         SMLoc E) {
2830     auto Op = make_unique<ARMOperand>(k_CoprocOption);
2831     Op->Cop.Val = Val;
2832     Op->StartLoc = S;
2833     Op->EndLoc = E;
2834     return Op;
2835   }
2836 
2837   static std::unique_ptr<ARMOperand> CreateCCOut(unsigned RegNum, SMLoc S) {
2838     auto Op = make_unique<ARMOperand>(k_CCOut);
2839     Op->Reg.RegNum = RegNum;
2840     Op->StartLoc = S;
2841     Op->EndLoc = S;
2842     return Op;
2843   }
2844 
2845   static std::unique_ptr<ARMOperand> CreateToken(StringRef Str, SMLoc S) {
2846     auto Op = make_unique<ARMOperand>(k_Token);
2847     Op->Tok.Data = Str.data();
2848     Op->Tok.Length = Str.size();
2849     Op->StartLoc = S;
2850     Op->EndLoc = S;
2851     return Op;
2852   }
2853 
2854   static std::unique_ptr<ARMOperand> CreateReg(unsigned RegNum, SMLoc S,
2855                                                SMLoc E) {
2856     auto Op = make_unique<ARMOperand>(k_Register);
2857     Op->Reg.RegNum = RegNum;
2858     Op->StartLoc = S;
2859     Op->EndLoc = E;
2860     return Op;
2861   }
2862 
2863   static std::unique_ptr<ARMOperand>
2864   CreateShiftedRegister(ARM_AM::ShiftOpc ShTy, unsigned SrcReg,
2865                         unsigned ShiftReg, unsigned ShiftImm, SMLoc S,
2866                         SMLoc E) {
2867     auto Op = make_unique<ARMOperand>(k_ShiftedRegister);
2868     Op->RegShiftedReg.ShiftTy = ShTy;
2869     Op->RegShiftedReg.SrcReg = SrcReg;
2870     Op->RegShiftedReg.ShiftReg = ShiftReg;
2871     Op->RegShiftedReg.ShiftImm = ShiftImm;
2872     Op->StartLoc = S;
2873     Op->EndLoc = E;
2874     return Op;
2875   }
2876 
2877   static std::unique_ptr<ARMOperand>
2878   CreateShiftedImmediate(ARM_AM::ShiftOpc ShTy, unsigned SrcReg,
2879                          unsigned ShiftImm, SMLoc S, SMLoc E) {
2880     auto Op = make_unique<ARMOperand>(k_ShiftedImmediate);
2881     Op->RegShiftedImm.ShiftTy = ShTy;
2882     Op->RegShiftedImm.SrcReg = SrcReg;
2883     Op->RegShiftedImm.ShiftImm = ShiftImm;
2884     Op->StartLoc = S;
2885     Op->EndLoc = E;
2886     return Op;
2887   }
2888 
2889   static std::unique_ptr<ARMOperand> CreateShifterImm(bool isASR, unsigned Imm,
2890                                                       SMLoc S, SMLoc E) {
2891     auto Op = make_unique<ARMOperand>(k_ShifterImmediate);
2892     Op->ShifterImm.isASR = isASR;
2893     Op->ShifterImm.Imm = Imm;
2894     Op->StartLoc = S;
2895     Op->EndLoc = E;
2896     return Op;
2897   }
2898 
2899   static std::unique_ptr<ARMOperand> CreateRotImm(unsigned Imm, SMLoc S,
2900                                                   SMLoc E) {
2901     auto Op = make_unique<ARMOperand>(k_RotateImmediate);
2902     Op->RotImm.Imm = Imm;
2903     Op->StartLoc = S;
2904     Op->EndLoc = E;
2905     return Op;
2906   }
2907 
2908   static std::unique_ptr<ARMOperand> CreateModImm(unsigned Bits, unsigned Rot,
2909                                                   SMLoc S, SMLoc E) {
2910     auto Op = make_unique<ARMOperand>(k_ModifiedImmediate);
2911     Op->ModImm.Bits = Bits;
2912     Op->ModImm.Rot = Rot;
2913     Op->StartLoc = S;
2914     Op->EndLoc = E;
2915     return Op;
2916   }
2917 
2918   static std::unique_ptr<ARMOperand>
2919   CreateConstantPoolImm(const MCExpr *Val, SMLoc S, SMLoc E) {
2920     auto Op = make_unique<ARMOperand>(k_ConstantPoolImmediate);
2921     Op->Imm.Val = Val;
2922     Op->StartLoc = S;
2923     Op->EndLoc = E;
2924     return Op;
2925   }
2926 
2927   static std::unique_ptr<ARMOperand>
2928   CreateBitfield(unsigned LSB, unsigned Width, SMLoc S, SMLoc E) {
2929     auto Op = make_unique<ARMOperand>(k_BitfieldDescriptor);
2930     Op->Bitfield.LSB = LSB;
2931     Op->Bitfield.Width = Width;
2932     Op->StartLoc = S;
2933     Op->EndLoc = E;
2934     return Op;
2935   }
2936 
2937   static std::unique_ptr<ARMOperand>
2938   CreateRegList(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs,
2939                 SMLoc StartLoc, SMLoc EndLoc) {
2940     assert(Regs.size() > 0 && "RegList contains no registers?");
2941     KindTy Kind = k_RegisterList;
2942 
2943     if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Regs.front().second))
2944       Kind = k_DPRRegisterList;
2945     else if (ARMMCRegisterClasses[ARM::SPRRegClassID].
2946              contains(Regs.front().second))
2947       Kind = k_SPRRegisterList;
2948 
2949     // Sort based on the register encoding values.
2950     array_pod_sort(Regs.begin(), Regs.end());
2951 
2952     auto Op = make_unique<ARMOperand>(Kind);
2953     for (SmallVectorImpl<std::pair<unsigned, unsigned>>::const_iterator
2954            I = Regs.begin(), E = Regs.end(); I != E; ++I)
2955       Op->Registers.push_back(I->second);
2956     Op->StartLoc = StartLoc;
2957     Op->EndLoc = EndLoc;
2958     return Op;
2959   }
2960 
2961   static std::unique_ptr<ARMOperand> CreateVectorList(unsigned RegNum,
2962                                                       unsigned Count,
2963                                                       bool isDoubleSpaced,
2964                                                       SMLoc S, SMLoc E) {
2965     auto Op = make_unique<ARMOperand>(k_VectorList);
2966     Op->VectorList.RegNum = RegNum;
2967     Op->VectorList.Count = Count;
2968     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
2969     Op->StartLoc = S;
2970     Op->EndLoc = E;
2971     return Op;
2972   }
2973 
2974   static std::unique_ptr<ARMOperand>
2975   CreateVectorListAllLanes(unsigned RegNum, unsigned Count, bool isDoubleSpaced,
2976                            SMLoc S, SMLoc E) {
2977     auto Op = make_unique<ARMOperand>(k_VectorListAllLanes);
2978     Op->VectorList.RegNum = RegNum;
2979     Op->VectorList.Count = Count;
2980     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
2981     Op->StartLoc = S;
2982     Op->EndLoc = E;
2983     return Op;
2984   }
2985 
2986   static std::unique_ptr<ARMOperand>
2987   CreateVectorListIndexed(unsigned RegNum, unsigned Count, unsigned Index,
2988                           bool isDoubleSpaced, SMLoc S, SMLoc E) {
2989     auto Op = make_unique<ARMOperand>(k_VectorListIndexed);
2990     Op->VectorList.RegNum = RegNum;
2991     Op->VectorList.Count = Count;
2992     Op->VectorList.LaneIndex = Index;
2993     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
2994     Op->StartLoc = S;
2995     Op->EndLoc = E;
2996     return Op;
2997   }
2998 
2999   static std::unique_ptr<ARMOperand>
3000   CreateVectorIndex(unsigned Idx, SMLoc S, SMLoc E, MCContext &Ctx) {
3001     auto Op = make_unique<ARMOperand>(k_VectorIndex);
3002     Op->VectorIndex.Val = Idx;
3003     Op->StartLoc = S;
3004     Op->EndLoc = E;
3005     return Op;
3006   }
3007 
3008   static std::unique_ptr<ARMOperand> CreateImm(const MCExpr *Val, SMLoc S,
3009                                                SMLoc E) {
3010     auto Op = make_unique<ARMOperand>(k_Immediate);
3011     Op->Imm.Val = Val;
3012     Op->StartLoc = S;
3013     Op->EndLoc = E;
3014     return Op;
3015   }
3016 
3017   static std::unique_ptr<ARMOperand>
3018   CreateMem(unsigned BaseRegNum, const MCConstantExpr *OffsetImm,
3019             unsigned OffsetRegNum, ARM_AM::ShiftOpc ShiftType,
3020             unsigned ShiftImm, unsigned Alignment, bool isNegative, SMLoc S,
3021             SMLoc E, SMLoc AlignmentLoc = SMLoc()) {
3022     auto Op = make_unique<ARMOperand>(k_Memory);
3023     Op->Memory.BaseRegNum = BaseRegNum;
3024     Op->Memory.OffsetImm = OffsetImm;
3025     Op->Memory.OffsetRegNum = OffsetRegNum;
3026     Op->Memory.ShiftType = ShiftType;
3027     Op->Memory.ShiftImm = ShiftImm;
3028     Op->Memory.Alignment = Alignment;
3029     Op->Memory.isNegative = isNegative;
3030     Op->StartLoc = S;
3031     Op->EndLoc = E;
3032     Op->AlignmentLoc = AlignmentLoc;
3033     return Op;
3034   }
3035 
3036   static std::unique_ptr<ARMOperand>
3037   CreatePostIdxReg(unsigned RegNum, bool isAdd, ARM_AM::ShiftOpc ShiftTy,
3038                    unsigned ShiftImm, SMLoc S, SMLoc E) {
3039     auto Op = make_unique<ARMOperand>(k_PostIndexRegister);
3040     Op->PostIdxReg.RegNum = RegNum;
3041     Op->PostIdxReg.isAdd = isAdd;
3042     Op->PostIdxReg.ShiftTy = ShiftTy;
3043     Op->PostIdxReg.ShiftImm = ShiftImm;
3044     Op->StartLoc = S;
3045     Op->EndLoc = E;
3046     return Op;
3047   }
3048 
3049   static std::unique_ptr<ARMOperand> CreateMemBarrierOpt(ARM_MB::MemBOpt Opt,
3050                                                          SMLoc S) {
3051     auto Op = make_unique<ARMOperand>(k_MemBarrierOpt);
3052     Op->MBOpt.Val = Opt;
3053     Op->StartLoc = S;
3054     Op->EndLoc = S;
3055     return Op;
3056   }
3057 
3058   static std::unique_ptr<ARMOperand>
3059   CreateInstSyncBarrierOpt(ARM_ISB::InstSyncBOpt Opt, SMLoc S) {
3060     auto Op = make_unique<ARMOperand>(k_InstSyncBarrierOpt);
3061     Op->ISBOpt.Val = Opt;
3062     Op->StartLoc = S;
3063     Op->EndLoc = S;
3064     return Op;
3065   }
3066 
3067   static std::unique_ptr<ARMOperand> CreateProcIFlags(ARM_PROC::IFlags IFlags,
3068                                                       SMLoc S) {
3069     auto Op = make_unique<ARMOperand>(k_ProcIFlags);
3070     Op->IFlags.Val = IFlags;
3071     Op->StartLoc = S;
3072     Op->EndLoc = S;
3073     return Op;
3074   }
3075 
3076   static std::unique_ptr<ARMOperand> CreateMSRMask(unsigned MMask, SMLoc S) {
3077     auto Op = make_unique<ARMOperand>(k_MSRMask);
3078     Op->MMask.Val = MMask;
3079     Op->StartLoc = S;
3080     Op->EndLoc = S;
3081     return Op;
3082   }
3083 
3084   static std::unique_ptr<ARMOperand> CreateBankedReg(unsigned Reg, SMLoc S) {
3085     auto Op = make_unique<ARMOperand>(k_BankedReg);
3086     Op->BankedReg.Val = Reg;
3087     Op->StartLoc = S;
3088     Op->EndLoc = S;
3089     return Op;
3090   }
3091 };
3092 
3093 } // end anonymous namespace.
3094 
3095 void ARMOperand::print(raw_ostream &OS) const {
3096   switch (Kind) {
3097   case k_CondCode:
3098     OS << "<ARMCC::" << ARMCondCodeToString(getCondCode()) << ">";
3099     break;
3100   case k_CCOut:
3101     OS << "<ccout " << getReg() << ">";
3102     break;
3103   case k_ITCondMask: {
3104     static const char *const MaskStr[] = {
3105       "()", "(t)", "(e)", "(tt)", "(et)", "(te)", "(ee)", "(ttt)", "(ett)",
3106       "(tet)", "(eet)", "(tte)", "(ete)", "(tee)", "(eee)"
3107     };
3108     assert((ITMask.Mask & 0xf) == ITMask.Mask);
3109     OS << "<it-mask " << MaskStr[ITMask.Mask] << ">";
3110     break;
3111   }
3112   case k_CoprocNum:
3113     OS << "<coprocessor number: " << getCoproc() << ">";
3114     break;
3115   case k_CoprocReg:
3116     OS << "<coprocessor register: " << getCoproc() << ">";
3117     break;
3118   case k_CoprocOption:
3119     OS << "<coprocessor option: " << CoprocOption.Val << ">";
3120     break;
3121   case k_MSRMask:
3122     OS << "<mask: " << getMSRMask() << ">";
3123     break;
3124   case k_BankedReg:
3125     OS << "<banked reg: " << getBankedReg() << ">";
3126     break;
3127   case k_Immediate:
3128     OS << *getImm();
3129     break;
3130   case k_MemBarrierOpt:
3131     OS << "<ARM_MB::" << MemBOptToString(getMemBarrierOpt(), false) << ">";
3132     break;
3133   case k_InstSyncBarrierOpt:
3134     OS << "<ARM_ISB::" << InstSyncBOptToString(getInstSyncBarrierOpt()) << ">";
3135     break;
3136   case k_Memory:
3137     OS << "<memory "
3138        << " base:" << Memory.BaseRegNum;
3139     OS << ">";
3140     break;
3141   case k_PostIndexRegister:
3142     OS << "post-idx register " << (PostIdxReg.isAdd ? "" : "-")
3143        << PostIdxReg.RegNum;
3144     if (PostIdxReg.ShiftTy != ARM_AM::no_shift)
3145       OS << ARM_AM::getShiftOpcStr(PostIdxReg.ShiftTy) << " "
3146          << PostIdxReg.ShiftImm;
3147     OS << ">";
3148     break;
3149   case k_ProcIFlags: {
3150     OS << "<ARM_PROC::";
3151     unsigned IFlags = getProcIFlags();
3152     for (int i=2; i >= 0; --i)
3153       if (IFlags & (1 << i))
3154         OS << ARM_PROC::IFlagsToString(1 << i);
3155     OS << ">";
3156     break;
3157   }
3158   case k_Register:
3159     OS << "<register " << getReg() << ">";
3160     break;
3161   case k_ShifterImmediate:
3162     OS << "<shift " << (ShifterImm.isASR ? "asr" : "lsl")
3163        << " #" << ShifterImm.Imm << ">";
3164     break;
3165   case k_ShiftedRegister:
3166     OS << "<so_reg_reg "
3167        << RegShiftedReg.SrcReg << " "
3168        << ARM_AM::getShiftOpcStr(RegShiftedReg.ShiftTy)
3169        << " " << RegShiftedReg.ShiftReg << ">";
3170     break;
3171   case k_ShiftedImmediate:
3172     OS << "<so_reg_imm "
3173        << RegShiftedImm.SrcReg << " "
3174        << ARM_AM::getShiftOpcStr(RegShiftedImm.ShiftTy)
3175        << " #" << RegShiftedImm.ShiftImm << ">";
3176     break;
3177   case k_RotateImmediate:
3178     OS << "<ror " << " #" << (RotImm.Imm * 8) << ">";
3179     break;
3180   case k_ModifiedImmediate:
3181     OS << "<mod_imm #" << ModImm.Bits << ", #"
3182        <<  ModImm.Rot << ")>";
3183     break;
3184   case k_ConstantPoolImmediate:
3185     OS << "<constant_pool_imm #" << *getConstantPoolImm();
3186     break;
3187   case k_BitfieldDescriptor:
3188     OS << "<bitfield " << "lsb: " << Bitfield.LSB
3189        << ", width: " << Bitfield.Width << ">";
3190     break;
3191   case k_RegisterList:
3192   case k_DPRRegisterList:
3193   case k_SPRRegisterList: {
3194     OS << "<register_list ";
3195 
3196     const SmallVectorImpl<unsigned> &RegList = getRegList();
3197     for (SmallVectorImpl<unsigned>::const_iterator
3198            I = RegList.begin(), E = RegList.end(); I != E; ) {
3199       OS << *I;
3200       if (++I < E) OS << ", ";
3201     }
3202 
3203     OS << ">";
3204     break;
3205   }
3206   case k_VectorList:
3207     OS << "<vector_list " << VectorList.Count << " * "
3208        << VectorList.RegNum << ">";
3209     break;
3210   case k_VectorListAllLanes:
3211     OS << "<vector_list(all lanes) " << VectorList.Count << " * "
3212        << VectorList.RegNum << ">";
3213     break;
3214   case k_VectorListIndexed:
3215     OS << "<vector_list(lane " << VectorList.LaneIndex << ") "
3216        << VectorList.Count << " * " << VectorList.RegNum << ">";
3217     break;
3218   case k_Token:
3219     OS << "'" << getToken() << "'";
3220     break;
3221   case k_VectorIndex:
3222     OS << "<vectorindex " << getVectorIndex() << ">";
3223     break;
3224   }
3225 }
3226 
3227 /// @name Auto-generated Match Functions
3228 /// {
3229 
3230 static unsigned MatchRegisterName(StringRef Name);
3231 
3232 /// }
3233 
3234 bool ARMAsmParser::ParseRegister(unsigned &RegNo,
3235                                  SMLoc &StartLoc, SMLoc &EndLoc) {
3236   const AsmToken &Tok = getParser().getTok();
3237   StartLoc = Tok.getLoc();
3238   EndLoc = Tok.getEndLoc();
3239   RegNo = tryParseRegister();
3240 
3241   return (RegNo == (unsigned)-1);
3242 }
3243 
3244 /// Try to parse a register name.  The token must be an Identifier when called,
3245 /// and if it is a register name the token is eaten and the register number is
3246 /// returned.  Otherwise return -1.
3247 int ARMAsmParser::tryParseRegister() {
3248   MCAsmParser &Parser = getParser();
3249   const AsmToken &Tok = Parser.getTok();
3250   if (Tok.isNot(AsmToken::Identifier)) return -1;
3251 
3252   std::string lowerCase = Tok.getString().lower();
3253   unsigned RegNum = MatchRegisterName(lowerCase);
3254   if (!RegNum) {
3255     RegNum = StringSwitch<unsigned>(lowerCase)
3256       .Case("r13", ARM::SP)
3257       .Case("r14", ARM::LR)
3258       .Case("r15", ARM::PC)
3259       .Case("ip", ARM::R12)
3260       // Additional register name aliases for 'gas' compatibility.
3261       .Case("a1", ARM::R0)
3262       .Case("a2", ARM::R1)
3263       .Case("a3", ARM::R2)
3264       .Case("a4", ARM::R3)
3265       .Case("v1", ARM::R4)
3266       .Case("v2", ARM::R5)
3267       .Case("v3", ARM::R6)
3268       .Case("v4", ARM::R7)
3269       .Case("v5", ARM::R8)
3270       .Case("v6", ARM::R9)
3271       .Case("v7", ARM::R10)
3272       .Case("v8", ARM::R11)
3273       .Case("sb", ARM::R9)
3274       .Case("sl", ARM::R10)
3275       .Case("fp", ARM::R11)
3276       .Default(0);
3277   }
3278   if (!RegNum) {
3279     // Check for aliases registered via .req. Canonicalize to lower case.
3280     // That's more consistent since register names are case insensitive, and
3281     // it's how the original entry was passed in from MC/MCParser/AsmParser.
3282     StringMap<unsigned>::const_iterator Entry = RegisterReqs.find(lowerCase);
3283     // If no match, return failure.
3284     if (Entry == RegisterReqs.end())
3285       return -1;
3286     Parser.Lex(); // Eat identifier token.
3287     return Entry->getValue();
3288   }
3289 
3290   // Some FPUs only have 16 D registers, so D16-D31 are invalid
3291   if (hasD16() && RegNum >= ARM::D16 && RegNum <= ARM::D31)
3292     return -1;
3293 
3294   Parser.Lex(); // Eat identifier token.
3295 
3296   return RegNum;
3297 }
3298 
3299 // Try to parse a shifter  (e.g., "lsl <amt>"). On success, return 0.
3300 // If a recoverable error occurs, return 1. If an irrecoverable error
3301 // occurs, return -1. An irrecoverable error is one where tokens have been
3302 // consumed in the process of trying to parse the shifter (i.e., when it is
3303 // indeed a shifter operand, but malformed).
3304 int ARMAsmParser::tryParseShiftRegister(OperandVector &Operands) {
3305   MCAsmParser &Parser = getParser();
3306   SMLoc S = Parser.getTok().getLoc();
3307   const AsmToken &Tok = Parser.getTok();
3308   if (Tok.isNot(AsmToken::Identifier))
3309     return -1;
3310 
3311   std::string lowerCase = Tok.getString().lower();
3312   ARM_AM::ShiftOpc ShiftTy = StringSwitch<ARM_AM::ShiftOpc>(lowerCase)
3313       .Case("asl", ARM_AM::lsl)
3314       .Case("lsl", ARM_AM::lsl)
3315       .Case("lsr", ARM_AM::lsr)
3316       .Case("asr", ARM_AM::asr)
3317       .Case("ror", ARM_AM::ror)
3318       .Case("rrx", ARM_AM::rrx)
3319       .Default(ARM_AM::no_shift);
3320 
3321   if (ShiftTy == ARM_AM::no_shift)
3322     return 1;
3323 
3324   Parser.Lex(); // Eat the operator.
3325 
3326   // The source register for the shift has already been added to the
3327   // operand list, so we need to pop it off and combine it into the shifted
3328   // register operand instead.
3329   std::unique_ptr<ARMOperand> PrevOp(
3330       (ARMOperand *)Operands.pop_back_val().release());
3331   if (!PrevOp->isReg())
3332     return Error(PrevOp->getStartLoc(), "shift must be of a register");
3333   int SrcReg = PrevOp->getReg();
3334 
3335   SMLoc EndLoc;
3336   int64_t Imm = 0;
3337   int ShiftReg = 0;
3338   if (ShiftTy == ARM_AM::rrx) {
3339     // RRX Doesn't have an explicit shift amount. The encoder expects
3340     // the shift register to be the same as the source register. Seems odd,
3341     // but OK.
3342     ShiftReg = SrcReg;
3343   } else {
3344     // Figure out if this is shifted by a constant or a register (for non-RRX).
3345     if (Parser.getTok().is(AsmToken::Hash) ||
3346         Parser.getTok().is(AsmToken::Dollar)) {
3347       Parser.Lex(); // Eat hash.
3348       SMLoc ImmLoc = Parser.getTok().getLoc();
3349       const MCExpr *ShiftExpr = nullptr;
3350       if (getParser().parseExpression(ShiftExpr, EndLoc)) {
3351         Error(ImmLoc, "invalid immediate shift value");
3352         return -1;
3353       }
3354       // The expression must be evaluatable as an immediate.
3355       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftExpr);
3356       if (!CE) {
3357         Error(ImmLoc, "invalid immediate shift value");
3358         return -1;
3359       }
3360       // Range check the immediate.
3361       // lsl, ror: 0 <= imm <= 31
3362       // lsr, asr: 0 <= imm <= 32
3363       Imm = CE->getValue();
3364       if (Imm < 0 ||
3365           ((ShiftTy == ARM_AM::lsl || ShiftTy == ARM_AM::ror) && Imm > 31) ||
3366           ((ShiftTy == ARM_AM::lsr || ShiftTy == ARM_AM::asr) && Imm > 32)) {
3367         Error(ImmLoc, "immediate shift value out of range");
3368         return -1;
3369       }
3370       // shift by zero is a nop. Always send it through as lsl.
3371       // ('as' compatibility)
3372       if (Imm == 0)
3373         ShiftTy = ARM_AM::lsl;
3374     } else if (Parser.getTok().is(AsmToken::Identifier)) {
3375       SMLoc L = Parser.getTok().getLoc();
3376       EndLoc = Parser.getTok().getEndLoc();
3377       ShiftReg = tryParseRegister();
3378       if (ShiftReg == -1) {
3379         Error(L, "expected immediate or register in shift operand");
3380         return -1;
3381       }
3382     } else {
3383       Error(Parser.getTok().getLoc(),
3384             "expected immediate or register in shift operand");
3385       return -1;
3386     }
3387   }
3388 
3389   if (ShiftReg && ShiftTy != ARM_AM::rrx)
3390     Operands.push_back(ARMOperand::CreateShiftedRegister(ShiftTy, SrcReg,
3391                                                          ShiftReg, Imm,
3392                                                          S, EndLoc));
3393   else
3394     Operands.push_back(ARMOperand::CreateShiftedImmediate(ShiftTy, SrcReg, Imm,
3395                                                           S, EndLoc));
3396 
3397   return 0;
3398 }
3399 
3400 /// Try to parse a register name.  The token must be an Identifier when called.
3401 /// If it's a register, an AsmOperand is created. Another AsmOperand is created
3402 /// if there is a "writeback". 'true' if it's not a register.
3403 ///
3404 /// TODO this is likely to change to allow different register types and or to
3405 /// parse for a specific register type.
3406 bool ARMAsmParser::tryParseRegisterWithWriteBack(OperandVector &Operands) {
3407   MCAsmParser &Parser = getParser();
3408   SMLoc RegStartLoc = Parser.getTok().getLoc();
3409   SMLoc RegEndLoc = Parser.getTok().getEndLoc();
3410   int RegNo = tryParseRegister();
3411   if (RegNo == -1)
3412     return true;
3413 
3414   Operands.push_back(ARMOperand::CreateReg(RegNo, RegStartLoc, RegEndLoc));
3415 
3416   const AsmToken &ExclaimTok = Parser.getTok();
3417   if (ExclaimTok.is(AsmToken::Exclaim)) {
3418     Operands.push_back(ARMOperand::CreateToken(ExclaimTok.getString(),
3419                                                ExclaimTok.getLoc()));
3420     Parser.Lex(); // Eat exclaim token
3421     return false;
3422   }
3423 
3424   // Also check for an index operand. This is only legal for vector registers,
3425   // but that'll get caught OK in operand matching, so we don't need to
3426   // explicitly filter everything else out here.
3427   if (Parser.getTok().is(AsmToken::LBrac)) {
3428     SMLoc SIdx = Parser.getTok().getLoc();
3429     Parser.Lex(); // Eat left bracket token.
3430 
3431     const MCExpr *ImmVal;
3432     if (getParser().parseExpression(ImmVal))
3433       return true;
3434     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(ImmVal);
3435     if (!MCE)
3436       return TokError("immediate value expected for vector index");
3437 
3438     if (Parser.getTok().isNot(AsmToken::RBrac))
3439       return Error(Parser.getTok().getLoc(), "']' expected");
3440 
3441     SMLoc E = Parser.getTok().getEndLoc();
3442     Parser.Lex(); // Eat right bracket token.
3443 
3444     Operands.push_back(ARMOperand::CreateVectorIndex(MCE->getValue(),
3445                                                      SIdx, E,
3446                                                      getContext()));
3447   }
3448 
3449   return false;
3450 }
3451 
3452 /// MatchCoprocessorOperandName - Try to parse an coprocessor related
3453 /// instruction with a symbolic operand name.
3454 /// We accept "crN" syntax for GAS compatibility.
3455 /// <operand-name> ::= <prefix><number>
3456 /// If CoprocOp is 'c', then:
3457 ///   <prefix> ::= c | cr
3458 /// If CoprocOp is 'p', then :
3459 ///   <prefix> ::= p
3460 /// <number> ::= integer in range [0, 15]
3461 static int MatchCoprocessorOperandName(StringRef Name, char CoprocOp) {
3462   // Use the same layout as the tablegen'erated register name matcher. Ugly,
3463   // but efficient.
3464   if (Name.size() < 2 || Name[0] != CoprocOp)
3465     return -1;
3466   Name = (Name[1] == 'r') ? Name.drop_front(2) : Name.drop_front();
3467 
3468   switch (Name.size()) {
3469   default: return -1;
3470   case 1:
3471     switch (Name[0]) {
3472     default:  return -1;
3473     case '0': return 0;
3474     case '1': return 1;
3475     case '2': return 2;
3476     case '3': return 3;
3477     case '4': return 4;
3478     case '5': return 5;
3479     case '6': return 6;
3480     case '7': return 7;
3481     case '8': return 8;
3482     case '9': return 9;
3483     }
3484   case 2:
3485     if (Name[0] != '1')
3486       return -1;
3487     switch (Name[1]) {
3488     default:  return -1;
3489     // CP10 and CP11 are VFP/NEON and so vector instructions should be used.
3490     // However, old cores (v5/v6) did use them in that way.
3491     case '0': return 10;
3492     case '1': return 11;
3493     case '2': return 12;
3494     case '3': return 13;
3495     case '4': return 14;
3496     case '5': return 15;
3497     }
3498   }
3499 }
3500 
3501 /// parseITCondCode - Try to parse a condition code for an IT instruction.
3502 OperandMatchResultTy
3503 ARMAsmParser::parseITCondCode(OperandVector &Operands) {
3504   MCAsmParser &Parser = getParser();
3505   SMLoc S = Parser.getTok().getLoc();
3506   const AsmToken &Tok = Parser.getTok();
3507   if (!Tok.is(AsmToken::Identifier))
3508     return MatchOperand_NoMatch;
3509   unsigned CC = ARMCondCodeFromString(Tok.getString());
3510   if (CC == ~0U)
3511     return MatchOperand_NoMatch;
3512   Parser.Lex(); // Eat the token.
3513 
3514   Operands.push_back(ARMOperand::CreateCondCode(ARMCC::CondCodes(CC), S));
3515 
3516   return MatchOperand_Success;
3517 }
3518 
3519 /// parseCoprocNumOperand - Try to parse an coprocessor number operand. The
3520 /// token must be an Identifier when called, and if it is a coprocessor
3521 /// number, the token is eaten and the operand is added to the operand list.
3522 OperandMatchResultTy
3523 ARMAsmParser::parseCoprocNumOperand(OperandVector &Operands) {
3524   MCAsmParser &Parser = getParser();
3525   SMLoc S = Parser.getTok().getLoc();
3526   const AsmToken &Tok = Parser.getTok();
3527   if (Tok.isNot(AsmToken::Identifier))
3528     return MatchOperand_NoMatch;
3529 
3530   int Num = MatchCoprocessorOperandName(Tok.getString(), 'p');
3531   if (Num == -1)
3532     return MatchOperand_NoMatch;
3533   // ARMv7 and v8 don't allow cp10/cp11 due to VFP/NEON specific instructions
3534   if ((hasV7Ops() || hasV8Ops()) && (Num == 10 || Num == 11))
3535     return MatchOperand_NoMatch;
3536 
3537   Parser.Lex(); // Eat identifier token.
3538   Operands.push_back(ARMOperand::CreateCoprocNum(Num, S));
3539   return MatchOperand_Success;
3540 }
3541 
3542 /// parseCoprocRegOperand - Try to parse an coprocessor register 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::parseCoprocRegOperand(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 Reg = MatchCoprocessorOperandName(Tok.getString(), 'c');
3554   if (Reg == -1)
3555     return MatchOperand_NoMatch;
3556 
3557   Parser.Lex(); // Eat identifier token.
3558   Operands.push_back(ARMOperand::CreateCoprocReg(Reg, S));
3559   return MatchOperand_Success;
3560 }
3561 
3562 /// parseCoprocOptionOperand - Try to parse an coprocessor option operand.
3563 /// coproc_option : '{' imm0_255 '}'
3564 OperandMatchResultTy
3565 ARMAsmParser::parseCoprocOptionOperand(OperandVector &Operands) {
3566   MCAsmParser &Parser = getParser();
3567   SMLoc S = Parser.getTok().getLoc();
3568 
3569   // If this isn't a '{', this isn't a coprocessor immediate operand.
3570   if (Parser.getTok().isNot(AsmToken::LCurly))
3571     return MatchOperand_NoMatch;
3572   Parser.Lex(); // Eat the '{'
3573 
3574   const MCExpr *Expr;
3575   SMLoc Loc = Parser.getTok().getLoc();
3576   if (getParser().parseExpression(Expr)) {
3577     Error(Loc, "illegal expression");
3578     return MatchOperand_ParseFail;
3579   }
3580   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
3581   if (!CE || CE->getValue() < 0 || CE->getValue() > 255) {
3582     Error(Loc, "coprocessor option must be an immediate in range [0, 255]");
3583     return MatchOperand_ParseFail;
3584   }
3585   int Val = CE->getValue();
3586 
3587   // Check for and consume the closing '}'
3588   if (Parser.getTok().isNot(AsmToken::RCurly))
3589     return MatchOperand_ParseFail;
3590   SMLoc E = Parser.getTok().getEndLoc();
3591   Parser.Lex(); // Eat the '}'
3592 
3593   Operands.push_back(ARMOperand::CreateCoprocOption(Val, S, E));
3594   return MatchOperand_Success;
3595 }
3596 
3597 // For register list parsing, we need to map from raw GPR register numbering
3598 // to the enumeration values. The enumeration values aren't sorted by
3599 // register number due to our using "sp", "lr" and "pc" as canonical names.
3600 static unsigned getNextRegister(unsigned Reg) {
3601   // If this is a GPR, we need to do it manually, otherwise we can rely
3602   // on the sort ordering of the enumeration since the other reg-classes
3603   // are sane.
3604   if (!ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
3605     return Reg + 1;
3606   switch(Reg) {
3607   default: llvm_unreachable("Invalid GPR number!");
3608   case ARM::R0:  return ARM::R1;  case ARM::R1:  return ARM::R2;
3609   case ARM::R2:  return ARM::R3;  case ARM::R3:  return ARM::R4;
3610   case ARM::R4:  return ARM::R5;  case ARM::R5:  return ARM::R6;
3611   case ARM::R6:  return ARM::R7;  case ARM::R7:  return ARM::R8;
3612   case ARM::R8:  return ARM::R9;  case ARM::R9:  return ARM::R10;
3613   case ARM::R10: return ARM::R11; case ARM::R11: return ARM::R12;
3614   case ARM::R12: return ARM::SP;  case ARM::SP:  return ARM::LR;
3615   case ARM::LR:  return ARM::PC;  case ARM::PC:  return ARM::R0;
3616   }
3617 }
3618 
3619 /// Parse a register list.
3620 bool ARMAsmParser::parseRegisterList(OperandVector &Operands) {
3621   MCAsmParser &Parser = getParser();
3622   if (Parser.getTok().isNot(AsmToken::LCurly))
3623     return TokError("Token is not a Left Curly Brace");
3624   SMLoc S = Parser.getTok().getLoc();
3625   Parser.Lex(); // Eat '{' token.
3626   SMLoc RegLoc = Parser.getTok().getLoc();
3627 
3628   // Check the first register in the list to see what register class
3629   // this is a list of.
3630   int Reg = tryParseRegister();
3631   if (Reg == -1)
3632     return Error(RegLoc, "register expected");
3633 
3634   // The reglist instructions have at most 16 registers, so reserve
3635   // space for that many.
3636   int EReg = 0;
3637   SmallVector<std::pair<unsigned, unsigned>, 16> Registers;
3638 
3639   // Allow Q regs and just interpret them as the two D sub-registers.
3640   if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3641     Reg = getDRegFromQReg(Reg);
3642     EReg = MRI->getEncodingValue(Reg);
3643     Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3644     ++Reg;
3645   }
3646   const MCRegisterClass *RC;
3647   if (ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
3648     RC = &ARMMCRegisterClasses[ARM::GPRRegClassID];
3649   else if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Reg))
3650     RC = &ARMMCRegisterClasses[ARM::DPRRegClassID];
3651   else if (ARMMCRegisterClasses[ARM::SPRRegClassID].contains(Reg))
3652     RC = &ARMMCRegisterClasses[ARM::SPRRegClassID];
3653   else
3654     return Error(RegLoc, "invalid register in register list");
3655 
3656   // Store the register.
3657   EReg = MRI->getEncodingValue(Reg);
3658   Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3659 
3660   // This starts immediately after the first register token in the list,
3661   // so we can see either a comma or a minus (range separator) as a legal
3662   // next token.
3663   while (Parser.getTok().is(AsmToken::Comma) ||
3664          Parser.getTok().is(AsmToken::Minus)) {
3665     if (Parser.getTok().is(AsmToken::Minus)) {
3666       Parser.Lex(); // Eat the minus.
3667       SMLoc AfterMinusLoc = Parser.getTok().getLoc();
3668       int EndReg = tryParseRegister();
3669       if (EndReg == -1)
3670         return Error(AfterMinusLoc, "register expected");
3671       // Allow Q regs and just interpret them as the two D sub-registers.
3672       if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(EndReg))
3673         EndReg = getDRegFromQReg(EndReg) + 1;
3674       // If the register is the same as the start reg, there's nothing
3675       // more to do.
3676       if (Reg == EndReg)
3677         continue;
3678       // The register must be in the same register class as the first.
3679       if (!RC->contains(EndReg))
3680         return Error(AfterMinusLoc, "invalid register in register list");
3681       // Ranges must go from low to high.
3682       if (MRI->getEncodingValue(Reg) > MRI->getEncodingValue(EndReg))
3683         return Error(AfterMinusLoc, "bad range in register list");
3684 
3685       // Add all the registers in the range to the register list.
3686       while (Reg != EndReg) {
3687         Reg = getNextRegister(Reg);
3688         EReg = MRI->getEncodingValue(Reg);
3689         Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3690       }
3691       continue;
3692     }
3693     Parser.Lex(); // Eat the comma.
3694     RegLoc = Parser.getTok().getLoc();
3695     int OldReg = Reg;
3696     const AsmToken RegTok = Parser.getTok();
3697     Reg = tryParseRegister();
3698     if (Reg == -1)
3699       return Error(RegLoc, "register expected");
3700     // Allow Q regs and just interpret them as the two D sub-registers.
3701     bool isQReg = false;
3702     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3703       Reg = getDRegFromQReg(Reg);
3704       isQReg = true;
3705     }
3706     // The register must be in the same register class as the first.
3707     if (!RC->contains(Reg))
3708       return Error(RegLoc, "invalid register in register list");
3709     // List must be monotonically increasing.
3710     if (MRI->getEncodingValue(Reg) < MRI->getEncodingValue(OldReg)) {
3711       if (ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
3712         Warning(RegLoc, "register list not in ascending order");
3713       else
3714         return Error(RegLoc, "register list not in ascending order");
3715     }
3716     if (MRI->getEncodingValue(Reg) == MRI->getEncodingValue(OldReg)) {
3717       Warning(RegLoc, "duplicated register (" + RegTok.getString() +
3718               ") in register list");
3719       continue;
3720     }
3721     // VFP register lists must also be contiguous.
3722     if (RC != &ARMMCRegisterClasses[ARM::GPRRegClassID] &&
3723         Reg != OldReg + 1)
3724       return Error(RegLoc, "non-contiguous register range");
3725     EReg = MRI->getEncodingValue(Reg);
3726     Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3727     if (isQReg) {
3728       EReg = MRI->getEncodingValue(++Reg);
3729       Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3730     }
3731   }
3732 
3733   if (Parser.getTok().isNot(AsmToken::RCurly))
3734     return Error(Parser.getTok().getLoc(), "'}' expected");
3735   SMLoc E = Parser.getTok().getEndLoc();
3736   Parser.Lex(); // Eat '}' token.
3737 
3738   // Push the register list operand.
3739   Operands.push_back(ARMOperand::CreateRegList(Registers, S, E));
3740 
3741   // The ARM system instruction variants for LDM/STM have a '^' token here.
3742   if (Parser.getTok().is(AsmToken::Caret)) {
3743     Operands.push_back(ARMOperand::CreateToken("^",Parser.getTok().getLoc()));
3744     Parser.Lex(); // Eat '^' token.
3745   }
3746 
3747   return false;
3748 }
3749 
3750 // Helper function to parse the lane index for vector lists.
3751 OperandMatchResultTy ARMAsmParser::
3752 parseVectorLane(VectorLaneTy &LaneKind, unsigned &Index, SMLoc &EndLoc) {
3753   MCAsmParser &Parser = getParser();
3754   Index = 0; // Always return a defined index value.
3755   if (Parser.getTok().is(AsmToken::LBrac)) {
3756     Parser.Lex(); // Eat the '['.
3757     if (Parser.getTok().is(AsmToken::RBrac)) {
3758       // "Dn[]" is the 'all lanes' syntax.
3759       LaneKind = AllLanes;
3760       EndLoc = Parser.getTok().getEndLoc();
3761       Parser.Lex(); // Eat the ']'.
3762       return MatchOperand_Success;
3763     }
3764 
3765     // There's an optional '#' token here. Normally there wouldn't be, but
3766     // inline assemble puts one in, and it's friendly to accept that.
3767     if (Parser.getTok().is(AsmToken::Hash))
3768       Parser.Lex(); // Eat '#' or '$'.
3769 
3770     const MCExpr *LaneIndex;
3771     SMLoc Loc = Parser.getTok().getLoc();
3772     if (getParser().parseExpression(LaneIndex)) {
3773       Error(Loc, "illegal expression");
3774       return MatchOperand_ParseFail;
3775     }
3776     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(LaneIndex);
3777     if (!CE) {
3778       Error(Loc, "lane index must be empty or an integer");
3779       return MatchOperand_ParseFail;
3780     }
3781     if (Parser.getTok().isNot(AsmToken::RBrac)) {
3782       Error(Parser.getTok().getLoc(), "']' expected");
3783       return MatchOperand_ParseFail;
3784     }
3785     EndLoc = Parser.getTok().getEndLoc();
3786     Parser.Lex(); // Eat the ']'.
3787     int64_t Val = CE->getValue();
3788 
3789     // FIXME: Make this range check context sensitive for .8, .16, .32.
3790     if (Val < 0 || Val > 7) {
3791       Error(Parser.getTok().getLoc(), "lane index out of range");
3792       return MatchOperand_ParseFail;
3793     }
3794     Index = Val;
3795     LaneKind = IndexedLane;
3796     return MatchOperand_Success;
3797   }
3798   LaneKind = NoLanes;
3799   return MatchOperand_Success;
3800 }
3801 
3802 // parse a vector register list
3803 OperandMatchResultTy
3804 ARMAsmParser::parseVectorList(OperandVector &Operands) {
3805   MCAsmParser &Parser = getParser();
3806   VectorLaneTy LaneKind;
3807   unsigned LaneIndex;
3808   SMLoc S = Parser.getTok().getLoc();
3809   // As an extension (to match gas), support a plain D register or Q register
3810   // (without encosing curly braces) as a single or double entry list,
3811   // respectively.
3812   if (Parser.getTok().is(AsmToken::Identifier)) {
3813     SMLoc E = Parser.getTok().getEndLoc();
3814     int Reg = tryParseRegister();
3815     if (Reg == -1)
3816       return MatchOperand_NoMatch;
3817     if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Reg)) {
3818       OperandMatchResultTy Res = parseVectorLane(LaneKind, LaneIndex, E);
3819       if (Res != MatchOperand_Success)
3820         return Res;
3821       switch (LaneKind) {
3822       case NoLanes:
3823         Operands.push_back(ARMOperand::CreateVectorList(Reg, 1, false, S, E));
3824         break;
3825       case AllLanes:
3826         Operands.push_back(ARMOperand::CreateVectorListAllLanes(Reg, 1, false,
3827                                                                 S, E));
3828         break;
3829       case IndexedLane:
3830         Operands.push_back(ARMOperand::CreateVectorListIndexed(Reg, 1,
3831                                                                LaneIndex,
3832                                                                false, S, E));
3833         break;
3834       }
3835       return MatchOperand_Success;
3836     }
3837     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3838       Reg = getDRegFromQReg(Reg);
3839       OperandMatchResultTy Res = parseVectorLane(LaneKind, LaneIndex, E);
3840       if (Res != MatchOperand_Success)
3841         return Res;
3842       switch (LaneKind) {
3843       case NoLanes:
3844         Reg = MRI->getMatchingSuperReg(Reg, ARM::dsub_0,
3845                                    &ARMMCRegisterClasses[ARM::DPairRegClassID]);
3846         Operands.push_back(ARMOperand::CreateVectorList(Reg, 2, false, S, E));
3847         break;
3848       case AllLanes:
3849         Reg = MRI->getMatchingSuperReg(Reg, ARM::dsub_0,
3850                                    &ARMMCRegisterClasses[ARM::DPairRegClassID]);
3851         Operands.push_back(ARMOperand::CreateVectorListAllLanes(Reg, 2, false,
3852                                                                 S, E));
3853         break;
3854       case IndexedLane:
3855         Operands.push_back(ARMOperand::CreateVectorListIndexed(Reg, 2,
3856                                                                LaneIndex,
3857                                                                false, S, E));
3858         break;
3859       }
3860       return MatchOperand_Success;
3861     }
3862     Error(S, "vector register expected");
3863     return MatchOperand_ParseFail;
3864   }
3865 
3866   if (Parser.getTok().isNot(AsmToken::LCurly))
3867     return MatchOperand_NoMatch;
3868 
3869   Parser.Lex(); // Eat '{' token.
3870   SMLoc RegLoc = Parser.getTok().getLoc();
3871 
3872   int Reg = tryParseRegister();
3873   if (Reg == -1) {
3874     Error(RegLoc, "register expected");
3875     return MatchOperand_ParseFail;
3876   }
3877   unsigned Count = 1;
3878   int Spacing = 0;
3879   unsigned FirstReg = Reg;
3880   // The list is of D registers, but we also allow Q regs and just interpret
3881   // them as the two D sub-registers.
3882   if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3883     FirstReg = Reg = getDRegFromQReg(Reg);
3884     Spacing = 1; // double-spacing requires explicit D registers, otherwise
3885                  // it's ambiguous with four-register single spaced.
3886     ++Reg;
3887     ++Count;
3888   }
3889 
3890   SMLoc E;
3891   if (parseVectorLane(LaneKind, LaneIndex, E) != MatchOperand_Success)
3892     return MatchOperand_ParseFail;
3893 
3894   while (Parser.getTok().is(AsmToken::Comma) ||
3895          Parser.getTok().is(AsmToken::Minus)) {
3896     if (Parser.getTok().is(AsmToken::Minus)) {
3897       if (!Spacing)
3898         Spacing = 1; // Register range implies a single spaced list.
3899       else if (Spacing == 2) {
3900         Error(Parser.getTok().getLoc(),
3901               "sequential registers in double spaced list");
3902         return MatchOperand_ParseFail;
3903       }
3904       Parser.Lex(); // Eat the minus.
3905       SMLoc AfterMinusLoc = Parser.getTok().getLoc();
3906       int EndReg = tryParseRegister();
3907       if (EndReg == -1) {
3908         Error(AfterMinusLoc, "register expected");
3909         return MatchOperand_ParseFail;
3910       }
3911       // Allow Q regs and just interpret them as the two D sub-registers.
3912       if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(EndReg))
3913         EndReg = getDRegFromQReg(EndReg) + 1;
3914       // If the register is the same as the start reg, there's nothing
3915       // more to do.
3916       if (Reg == EndReg)
3917         continue;
3918       // The register must be in the same register class as the first.
3919       if (!ARMMCRegisterClasses[ARM::DPRRegClassID].contains(EndReg)) {
3920         Error(AfterMinusLoc, "invalid register in register list");
3921         return MatchOperand_ParseFail;
3922       }
3923       // Ranges must go from low to high.
3924       if (Reg > EndReg) {
3925         Error(AfterMinusLoc, "bad range in register list");
3926         return MatchOperand_ParseFail;
3927       }
3928       // Parse the lane specifier if present.
3929       VectorLaneTy NextLaneKind;
3930       unsigned NextLaneIndex;
3931       if (parseVectorLane(NextLaneKind, NextLaneIndex, E) !=
3932           MatchOperand_Success)
3933         return MatchOperand_ParseFail;
3934       if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
3935         Error(AfterMinusLoc, "mismatched lane index in register list");
3936         return MatchOperand_ParseFail;
3937       }
3938 
3939       // Add all the registers in the range to the register list.
3940       Count += EndReg - Reg;
3941       Reg = EndReg;
3942       continue;
3943     }
3944     Parser.Lex(); // Eat the comma.
3945     RegLoc = Parser.getTok().getLoc();
3946     int OldReg = Reg;
3947     Reg = tryParseRegister();
3948     if (Reg == -1) {
3949       Error(RegLoc, "register expected");
3950       return MatchOperand_ParseFail;
3951     }
3952     // vector register lists must be contiguous.
3953     // It's OK to use the enumeration values directly here rather, as the
3954     // VFP register classes have the enum sorted properly.
3955     //
3956     // The list is of D registers, but we also allow Q regs and just interpret
3957     // them as the two D sub-registers.
3958     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3959       if (!Spacing)
3960         Spacing = 1; // Register range implies a single spaced list.
3961       else if (Spacing == 2) {
3962         Error(RegLoc,
3963               "invalid register in double-spaced list (must be 'D' register')");
3964         return MatchOperand_ParseFail;
3965       }
3966       Reg = getDRegFromQReg(Reg);
3967       if (Reg != OldReg + 1) {
3968         Error(RegLoc, "non-contiguous register range");
3969         return MatchOperand_ParseFail;
3970       }
3971       ++Reg;
3972       Count += 2;
3973       // Parse the lane specifier if present.
3974       VectorLaneTy NextLaneKind;
3975       unsigned NextLaneIndex;
3976       SMLoc LaneLoc = Parser.getTok().getLoc();
3977       if (parseVectorLane(NextLaneKind, NextLaneIndex, E) !=
3978           MatchOperand_Success)
3979         return MatchOperand_ParseFail;
3980       if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
3981         Error(LaneLoc, "mismatched lane index in register list");
3982         return MatchOperand_ParseFail;
3983       }
3984       continue;
3985     }
3986     // Normal D register.
3987     // Figure out the register spacing (single or double) of the list if
3988     // we don't know it already.
3989     if (!Spacing)
3990       Spacing = 1 + (Reg == OldReg + 2);
3991 
3992     // Just check that it's contiguous and keep going.
3993     if (Reg != OldReg + Spacing) {
3994       Error(RegLoc, "non-contiguous register range");
3995       return MatchOperand_ParseFail;
3996     }
3997     ++Count;
3998     // Parse the lane specifier if present.
3999     VectorLaneTy NextLaneKind;
4000     unsigned NextLaneIndex;
4001     SMLoc EndLoc = Parser.getTok().getLoc();
4002     if (parseVectorLane(NextLaneKind, NextLaneIndex, E) != MatchOperand_Success)
4003       return MatchOperand_ParseFail;
4004     if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
4005       Error(EndLoc, "mismatched lane index in register list");
4006       return MatchOperand_ParseFail;
4007     }
4008   }
4009 
4010   if (Parser.getTok().isNot(AsmToken::RCurly)) {
4011     Error(Parser.getTok().getLoc(), "'}' expected");
4012     return MatchOperand_ParseFail;
4013   }
4014   E = Parser.getTok().getEndLoc();
4015   Parser.Lex(); // Eat '}' token.
4016 
4017   switch (LaneKind) {
4018   case NoLanes:
4019     // Two-register operands have been converted to the
4020     // composite register classes.
4021     if (Count == 2) {
4022       const MCRegisterClass *RC = (Spacing == 1) ?
4023         &ARMMCRegisterClasses[ARM::DPairRegClassID] :
4024         &ARMMCRegisterClasses[ARM::DPairSpcRegClassID];
4025       FirstReg = MRI->getMatchingSuperReg(FirstReg, ARM::dsub_0, RC);
4026     }
4027     Operands.push_back(ARMOperand::CreateVectorList(FirstReg, Count,
4028                                                     (Spacing == 2), S, E));
4029     break;
4030   case AllLanes:
4031     // Two-register operands have been converted to the
4032     // composite register classes.
4033     if (Count == 2) {
4034       const MCRegisterClass *RC = (Spacing == 1) ?
4035         &ARMMCRegisterClasses[ARM::DPairRegClassID] :
4036         &ARMMCRegisterClasses[ARM::DPairSpcRegClassID];
4037       FirstReg = MRI->getMatchingSuperReg(FirstReg, ARM::dsub_0, RC);
4038     }
4039     Operands.push_back(ARMOperand::CreateVectorListAllLanes(FirstReg, Count,
4040                                                             (Spacing == 2),
4041                                                             S, E));
4042     break;
4043   case IndexedLane:
4044     Operands.push_back(ARMOperand::CreateVectorListIndexed(FirstReg, Count,
4045                                                            LaneIndex,
4046                                                            (Spacing == 2),
4047                                                            S, E));
4048     break;
4049   }
4050   return MatchOperand_Success;
4051 }
4052 
4053 /// parseMemBarrierOptOperand - Try to parse DSB/DMB data barrier options.
4054 OperandMatchResultTy
4055 ARMAsmParser::parseMemBarrierOptOperand(OperandVector &Operands) {
4056   MCAsmParser &Parser = getParser();
4057   SMLoc S = Parser.getTok().getLoc();
4058   const AsmToken &Tok = Parser.getTok();
4059   unsigned Opt;
4060 
4061   if (Tok.is(AsmToken::Identifier)) {
4062     StringRef OptStr = Tok.getString();
4063 
4064     Opt = StringSwitch<unsigned>(OptStr.slice(0, OptStr.size()).lower())
4065       .Case("sy",    ARM_MB::SY)
4066       .Case("st",    ARM_MB::ST)
4067       .Case("ld",    ARM_MB::LD)
4068       .Case("sh",    ARM_MB::ISH)
4069       .Case("ish",   ARM_MB::ISH)
4070       .Case("shst",  ARM_MB::ISHST)
4071       .Case("ishst", ARM_MB::ISHST)
4072       .Case("ishld", ARM_MB::ISHLD)
4073       .Case("nsh",   ARM_MB::NSH)
4074       .Case("un",    ARM_MB::NSH)
4075       .Case("nshst", ARM_MB::NSHST)
4076       .Case("nshld", ARM_MB::NSHLD)
4077       .Case("unst",  ARM_MB::NSHST)
4078       .Case("osh",   ARM_MB::OSH)
4079       .Case("oshst", ARM_MB::OSHST)
4080       .Case("oshld", ARM_MB::OSHLD)
4081       .Default(~0U);
4082 
4083     // ishld, oshld, nshld and ld are only available from ARMv8.
4084     if (!hasV8Ops() && (Opt == ARM_MB::ISHLD || Opt == ARM_MB::OSHLD ||
4085                         Opt == ARM_MB::NSHLD || Opt == ARM_MB::LD))
4086       Opt = ~0U;
4087 
4088     if (Opt == ~0U)
4089       return MatchOperand_NoMatch;
4090 
4091     Parser.Lex(); // Eat identifier token.
4092   } else if (Tok.is(AsmToken::Hash) ||
4093              Tok.is(AsmToken::Dollar) ||
4094              Tok.is(AsmToken::Integer)) {
4095     if (Parser.getTok().isNot(AsmToken::Integer))
4096       Parser.Lex(); // Eat '#' or '$'.
4097     SMLoc Loc = Parser.getTok().getLoc();
4098 
4099     const MCExpr *MemBarrierID;
4100     if (getParser().parseExpression(MemBarrierID)) {
4101       Error(Loc, "illegal expression");
4102       return MatchOperand_ParseFail;
4103     }
4104 
4105     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(MemBarrierID);
4106     if (!CE) {
4107       Error(Loc, "constant expression expected");
4108       return MatchOperand_ParseFail;
4109     }
4110 
4111     int Val = CE->getValue();
4112     if (Val & ~0xf) {
4113       Error(Loc, "immediate value out of range");
4114       return MatchOperand_ParseFail;
4115     }
4116 
4117     Opt = ARM_MB::RESERVED_0 + Val;
4118   } else
4119     return MatchOperand_ParseFail;
4120 
4121   Operands.push_back(ARMOperand::CreateMemBarrierOpt((ARM_MB::MemBOpt)Opt, S));
4122   return MatchOperand_Success;
4123 }
4124 
4125 /// parseInstSyncBarrierOptOperand - Try to parse ISB inst sync barrier options.
4126 OperandMatchResultTy
4127 ARMAsmParser::parseInstSyncBarrierOptOperand(OperandVector &Operands) {
4128   MCAsmParser &Parser = getParser();
4129   SMLoc S = Parser.getTok().getLoc();
4130   const AsmToken &Tok = Parser.getTok();
4131   unsigned Opt;
4132 
4133   if (Tok.is(AsmToken::Identifier)) {
4134     StringRef OptStr = Tok.getString();
4135 
4136     if (OptStr.equals_lower("sy"))
4137       Opt = ARM_ISB::SY;
4138     else
4139       return MatchOperand_NoMatch;
4140 
4141     Parser.Lex(); // Eat identifier token.
4142   } else if (Tok.is(AsmToken::Hash) ||
4143              Tok.is(AsmToken::Dollar) ||
4144              Tok.is(AsmToken::Integer)) {
4145     if (Parser.getTok().isNot(AsmToken::Integer))
4146       Parser.Lex(); // Eat '#' or '$'.
4147     SMLoc Loc = Parser.getTok().getLoc();
4148 
4149     const MCExpr *ISBarrierID;
4150     if (getParser().parseExpression(ISBarrierID)) {
4151       Error(Loc, "illegal expression");
4152       return MatchOperand_ParseFail;
4153     }
4154 
4155     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ISBarrierID);
4156     if (!CE) {
4157       Error(Loc, "constant expression expected");
4158       return MatchOperand_ParseFail;
4159     }
4160 
4161     int Val = CE->getValue();
4162     if (Val & ~0xf) {
4163       Error(Loc, "immediate value out of range");
4164       return MatchOperand_ParseFail;
4165     }
4166 
4167     Opt = ARM_ISB::RESERVED_0 + Val;
4168   } else
4169     return MatchOperand_ParseFail;
4170 
4171   Operands.push_back(ARMOperand::CreateInstSyncBarrierOpt(
4172           (ARM_ISB::InstSyncBOpt)Opt, S));
4173   return MatchOperand_Success;
4174 }
4175 
4176 
4177 /// parseProcIFlagsOperand - Try to parse iflags from CPS instruction.
4178 OperandMatchResultTy
4179 ARMAsmParser::parseProcIFlagsOperand(OperandVector &Operands) {
4180   MCAsmParser &Parser = getParser();
4181   SMLoc S = Parser.getTok().getLoc();
4182   const AsmToken &Tok = Parser.getTok();
4183   if (!Tok.is(AsmToken::Identifier))
4184     return MatchOperand_NoMatch;
4185   StringRef IFlagsStr = Tok.getString();
4186 
4187   // An iflags string of "none" is interpreted to mean that none of the AIF
4188   // bits are set.  Not a terribly useful instruction, but a valid encoding.
4189   unsigned IFlags = 0;
4190   if (IFlagsStr != "none") {
4191         for (int i = 0, e = IFlagsStr.size(); i != e; ++i) {
4192       unsigned Flag = StringSwitch<unsigned>(IFlagsStr.substr(i, 1).lower())
4193         .Case("a", ARM_PROC::A)
4194         .Case("i", ARM_PROC::I)
4195         .Case("f", ARM_PROC::F)
4196         .Default(~0U);
4197 
4198       // If some specific iflag is already set, it means that some letter is
4199       // present more than once, this is not acceptable.
4200       if (Flag == ~0U || (IFlags & Flag))
4201         return MatchOperand_NoMatch;
4202 
4203       IFlags |= Flag;
4204     }
4205   }
4206 
4207   Parser.Lex(); // Eat identifier token.
4208   Operands.push_back(ARMOperand::CreateProcIFlags((ARM_PROC::IFlags)IFlags, S));
4209   return MatchOperand_Success;
4210 }
4211 
4212 /// parseMSRMaskOperand - Try to parse mask flags from MSR instruction.
4213 OperandMatchResultTy
4214 ARMAsmParser::parseMSRMaskOperand(OperandVector &Operands) {
4215   MCAsmParser &Parser = getParser();
4216   SMLoc S = Parser.getTok().getLoc();
4217   const AsmToken &Tok = Parser.getTok();
4218   if (!Tok.is(AsmToken::Identifier))
4219     return MatchOperand_NoMatch;
4220   StringRef Mask = Tok.getString();
4221 
4222   if (isMClass()) {
4223     auto TheReg = ARMSysReg::lookupMClassSysRegByName(Mask.lower());
4224     if (!TheReg || !TheReg->hasRequiredFeatures(getSTI().getFeatureBits()))
4225       return MatchOperand_NoMatch;
4226 
4227     unsigned SYSmvalue = TheReg->Encoding & 0xFFF;
4228 
4229     Parser.Lex(); // Eat identifier token.
4230     Operands.push_back(ARMOperand::CreateMSRMask(SYSmvalue, S));
4231     return MatchOperand_Success;
4232   }
4233 
4234   // Split spec_reg from flag, example: CPSR_sxf => "CPSR" and "sxf"
4235   size_t Start = 0, Next = Mask.find('_');
4236   StringRef Flags = "";
4237   std::string SpecReg = Mask.slice(Start, Next).lower();
4238   if (Next != StringRef::npos)
4239     Flags = Mask.slice(Next+1, Mask.size());
4240 
4241   // FlagsVal contains the complete mask:
4242   // 3-0: Mask
4243   // 4: Special Reg (cpsr, apsr => 0; spsr => 1)
4244   unsigned FlagsVal = 0;
4245 
4246   if (SpecReg == "apsr") {
4247     FlagsVal = StringSwitch<unsigned>(Flags)
4248     .Case("nzcvq",  0x8) // same as CPSR_f
4249     .Case("g",      0x4) // same as CPSR_s
4250     .Case("nzcvqg", 0xc) // same as CPSR_fs
4251     .Default(~0U);
4252 
4253     if (FlagsVal == ~0U) {
4254       if (!Flags.empty())
4255         return MatchOperand_NoMatch;
4256       else
4257         FlagsVal = 8; // No flag
4258     }
4259   } else if (SpecReg == "cpsr" || SpecReg == "spsr") {
4260     // cpsr_all is an alias for cpsr_fc, as is plain cpsr.
4261     if (Flags == "all" || Flags == "")
4262       Flags = "fc";
4263     for (int i = 0, e = Flags.size(); i != e; ++i) {
4264       unsigned Flag = StringSwitch<unsigned>(Flags.substr(i, 1))
4265       .Case("c", 1)
4266       .Case("x", 2)
4267       .Case("s", 4)
4268       .Case("f", 8)
4269       .Default(~0U);
4270 
4271       // If some specific flag is already set, it means that some letter is
4272       // present more than once, this is not acceptable.
4273       if (Flag == ~0U || (FlagsVal & Flag))
4274         return MatchOperand_NoMatch;
4275       FlagsVal |= Flag;
4276     }
4277   } else // No match for special register.
4278     return MatchOperand_NoMatch;
4279 
4280   // Special register without flags is NOT equivalent to "fc" flags.
4281   // NOTE: This is a divergence from gas' behavior.  Uncommenting the following
4282   // two lines would enable gas compatibility at the expense of breaking
4283   // round-tripping.
4284   //
4285   // if (!FlagsVal)
4286   //  FlagsVal = 0x9;
4287 
4288   // Bit 4: Special Reg (cpsr, apsr => 0; spsr => 1)
4289   if (SpecReg == "spsr")
4290     FlagsVal |= 16;
4291 
4292   Parser.Lex(); // Eat identifier token.
4293   Operands.push_back(ARMOperand::CreateMSRMask(FlagsVal, S));
4294   return MatchOperand_Success;
4295 }
4296 
4297 /// parseBankedRegOperand - Try to parse a banked register (e.g. "lr_irq") for
4298 /// use in the MRS/MSR instructions added to support virtualization.
4299 OperandMatchResultTy
4300 ARMAsmParser::parseBankedRegOperand(OperandVector &Operands) {
4301   MCAsmParser &Parser = getParser();
4302   SMLoc S = Parser.getTok().getLoc();
4303   const AsmToken &Tok = Parser.getTok();
4304   if (!Tok.is(AsmToken::Identifier))
4305     return MatchOperand_NoMatch;
4306   StringRef RegName = Tok.getString();
4307 
4308   auto TheReg = ARMBankedReg::lookupBankedRegByName(RegName.lower());
4309   if (!TheReg)
4310     return MatchOperand_NoMatch;
4311   unsigned Encoding = TheReg->Encoding;
4312 
4313   Parser.Lex(); // Eat identifier token.
4314   Operands.push_back(ARMOperand::CreateBankedReg(Encoding, S));
4315   return MatchOperand_Success;
4316 }
4317 
4318 OperandMatchResultTy
4319 ARMAsmParser::parsePKHImm(OperandVector &Operands, StringRef Op, int Low,
4320                           int High) {
4321   MCAsmParser &Parser = getParser();
4322   const AsmToken &Tok = Parser.getTok();
4323   if (Tok.isNot(AsmToken::Identifier)) {
4324     Error(Parser.getTok().getLoc(), Op + " operand expected.");
4325     return MatchOperand_ParseFail;
4326   }
4327   StringRef ShiftName = Tok.getString();
4328   std::string LowerOp = Op.lower();
4329   std::string UpperOp = Op.upper();
4330   if (ShiftName != LowerOp && ShiftName != UpperOp) {
4331     Error(Parser.getTok().getLoc(), Op + " operand expected.");
4332     return MatchOperand_ParseFail;
4333   }
4334   Parser.Lex(); // Eat shift type token.
4335 
4336   // There must be a '#' and a shift amount.
4337   if (Parser.getTok().isNot(AsmToken::Hash) &&
4338       Parser.getTok().isNot(AsmToken::Dollar)) {
4339     Error(Parser.getTok().getLoc(), "'#' expected");
4340     return MatchOperand_ParseFail;
4341   }
4342   Parser.Lex(); // Eat hash token.
4343 
4344   const MCExpr *ShiftAmount;
4345   SMLoc Loc = Parser.getTok().getLoc();
4346   SMLoc EndLoc;
4347   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
4348     Error(Loc, "illegal expression");
4349     return MatchOperand_ParseFail;
4350   }
4351   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
4352   if (!CE) {
4353     Error(Loc, "constant expression expected");
4354     return MatchOperand_ParseFail;
4355   }
4356   int Val = CE->getValue();
4357   if (Val < Low || Val > High) {
4358     Error(Loc, "immediate value out of range");
4359     return MatchOperand_ParseFail;
4360   }
4361 
4362   Operands.push_back(ARMOperand::CreateImm(CE, Loc, EndLoc));
4363 
4364   return MatchOperand_Success;
4365 }
4366 
4367 OperandMatchResultTy
4368 ARMAsmParser::parseSetEndImm(OperandVector &Operands) {
4369   MCAsmParser &Parser = getParser();
4370   const AsmToken &Tok = Parser.getTok();
4371   SMLoc S = Tok.getLoc();
4372   if (Tok.isNot(AsmToken::Identifier)) {
4373     Error(S, "'be' or 'le' operand expected");
4374     return MatchOperand_ParseFail;
4375   }
4376   int Val = StringSwitch<int>(Tok.getString().lower())
4377     .Case("be", 1)
4378     .Case("le", 0)
4379     .Default(-1);
4380   Parser.Lex(); // Eat the token.
4381 
4382   if (Val == -1) {
4383     Error(S, "'be' or 'le' operand expected");
4384     return MatchOperand_ParseFail;
4385   }
4386   Operands.push_back(ARMOperand::CreateImm(MCConstantExpr::create(Val,
4387                                                                   getContext()),
4388                                            S, Tok.getEndLoc()));
4389   return MatchOperand_Success;
4390 }
4391 
4392 /// parseShifterImm - Parse the shifter immediate operand for SSAT/USAT
4393 /// instructions. Legal values are:
4394 ///     lsl #n  'n' in [0,31]
4395 ///     asr #n  'n' in [1,32]
4396 ///             n == 32 encoded as n == 0.
4397 OperandMatchResultTy
4398 ARMAsmParser::parseShifterImm(OperandVector &Operands) {
4399   MCAsmParser &Parser = getParser();
4400   const AsmToken &Tok = Parser.getTok();
4401   SMLoc S = Tok.getLoc();
4402   if (Tok.isNot(AsmToken::Identifier)) {
4403     Error(S, "shift operator 'asr' or 'lsl' expected");
4404     return MatchOperand_ParseFail;
4405   }
4406   StringRef ShiftName = Tok.getString();
4407   bool isASR;
4408   if (ShiftName == "lsl" || ShiftName == "LSL")
4409     isASR = false;
4410   else if (ShiftName == "asr" || ShiftName == "ASR")
4411     isASR = true;
4412   else {
4413     Error(S, "shift operator 'asr' or 'lsl' expected");
4414     return MatchOperand_ParseFail;
4415   }
4416   Parser.Lex(); // Eat the operator.
4417 
4418   // A '#' and a shift amount.
4419   if (Parser.getTok().isNot(AsmToken::Hash) &&
4420       Parser.getTok().isNot(AsmToken::Dollar)) {
4421     Error(Parser.getTok().getLoc(), "'#' expected");
4422     return MatchOperand_ParseFail;
4423   }
4424   Parser.Lex(); // Eat hash token.
4425   SMLoc ExLoc = Parser.getTok().getLoc();
4426 
4427   const MCExpr *ShiftAmount;
4428   SMLoc EndLoc;
4429   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
4430     Error(ExLoc, "malformed shift expression");
4431     return MatchOperand_ParseFail;
4432   }
4433   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
4434   if (!CE) {
4435     Error(ExLoc, "shift amount must be an immediate");
4436     return MatchOperand_ParseFail;
4437   }
4438 
4439   int64_t Val = CE->getValue();
4440   if (isASR) {
4441     // Shift amount must be in [1,32]
4442     if (Val < 1 || Val > 32) {
4443       Error(ExLoc, "'asr' shift amount must be in range [1,32]");
4444       return MatchOperand_ParseFail;
4445     }
4446     // asr #32 encoded as asr #0, but is not allowed in Thumb2 mode.
4447     if (isThumb() && Val == 32) {
4448       Error(ExLoc, "'asr #32' shift amount not allowed in Thumb mode");
4449       return MatchOperand_ParseFail;
4450     }
4451     if (Val == 32) Val = 0;
4452   } else {
4453     // Shift amount must be in [1,32]
4454     if (Val < 0 || Val > 31) {
4455       Error(ExLoc, "'lsr' shift amount must be in range [0,31]");
4456       return MatchOperand_ParseFail;
4457     }
4458   }
4459 
4460   Operands.push_back(ARMOperand::CreateShifterImm(isASR, Val, S, EndLoc));
4461 
4462   return MatchOperand_Success;
4463 }
4464 
4465 /// parseRotImm - Parse the shifter immediate operand for SXTB/UXTB family
4466 /// of instructions. Legal values are:
4467 ///     ror #n  'n' in {0, 8, 16, 24}
4468 OperandMatchResultTy
4469 ARMAsmParser::parseRotImm(OperandVector &Operands) {
4470   MCAsmParser &Parser = getParser();
4471   const AsmToken &Tok = Parser.getTok();
4472   SMLoc S = Tok.getLoc();
4473   if (Tok.isNot(AsmToken::Identifier))
4474     return MatchOperand_NoMatch;
4475   StringRef ShiftName = Tok.getString();
4476   if (ShiftName != "ror" && ShiftName != "ROR")
4477     return MatchOperand_NoMatch;
4478   Parser.Lex(); // Eat the operator.
4479 
4480   // A '#' and a rotate amount.
4481   if (Parser.getTok().isNot(AsmToken::Hash) &&
4482       Parser.getTok().isNot(AsmToken::Dollar)) {
4483     Error(Parser.getTok().getLoc(), "'#' expected");
4484     return MatchOperand_ParseFail;
4485   }
4486   Parser.Lex(); // Eat hash token.
4487   SMLoc ExLoc = Parser.getTok().getLoc();
4488 
4489   const MCExpr *ShiftAmount;
4490   SMLoc EndLoc;
4491   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
4492     Error(ExLoc, "malformed rotate expression");
4493     return MatchOperand_ParseFail;
4494   }
4495   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
4496   if (!CE) {
4497     Error(ExLoc, "rotate amount must be an immediate");
4498     return MatchOperand_ParseFail;
4499   }
4500 
4501   int64_t Val = CE->getValue();
4502   // Shift amount must be in {0, 8, 16, 24} (0 is undocumented extension)
4503   // normally, zero is represented in asm by omitting the rotate operand
4504   // entirely.
4505   if (Val != 8 && Val != 16 && Val != 24 && Val != 0) {
4506     Error(ExLoc, "'ror' rotate amount must be 8, 16, or 24");
4507     return MatchOperand_ParseFail;
4508   }
4509 
4510   Operands.push_back(ARMOperand::CreateRotImm(Val, S, EndLoc));
4511 
4512   return MatchOperand_Success;
4513 }
4514 
4515 OperandMatchResultTy
4516 ARMAsmParser::parseModImm(OperandVector &Operands) {
4517   MCAsmParser &Parser = getParser();
4518   MCAsmLexer &Lexer = getLexer();
4519   int64_t Imm1, Imm2;
4520 
4521   SMLoc S = Parser.getTok().getLoc();
4522 
4523   // 1) A mod_imm operand can appear in the place of a register name:
4524   //   add r0, #mod_imm
4525   //   add r0, r0, #mod_imm
4526   // to correctly handle the latter, we bail out as soon as we see an
4527   // identifier.
4528   //
4529   // 2) Similarly, we do not want to parse into complex operands:
4530   //   mov r0, #mod_imm
4531   //   mov r0, :lower16:(_foo)
4532   if (Parser.getTok().is(AsmToken::Identifier) ||
4533       Parser.getTok().is(AsmToken::Colon))
4534     return MatchOperand_NoMatch;
4535 
4536   // Hash (dollar) is optional as per the ARMARM
4537   if (Parser.getTok().is(AsmToken::Hash) ||
4538       Parser.getTok().is(AsmToken::Dollar)) {
4539     // Avoid parsing into complex operands (#:)
4540     if (Lexer.peekTok().is(AsmToken::Colon))
4541       return MatchOperand_NoMatch;
4542 
4543     // Eat the hash (dollar)
4544     Parser.Lex();
4545   }
4546 
4547   SMLoc Sx1, Ex1;
4548   Sx1 = Parser.getTok().getLoc();
4549   const MCExpr *Imm1Exp;
4550   if (getParser().parseExpression(Imm1Exp, Ex1)) {
4551     Error(Sx1, "malformed expression");
4552     return MatchOperand_ParseFail;
4553   }
4554 
4555   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm1Exp);
4556 
4557   if (CE) {
4558     // Immediate must fit within 32-bits
4559     Imm1 = CE->getValue();
4560     int Enc = ARM_AM::getSOImmVal(Imm1);
4561     if (Enc != -1 && Parser.getTok().is(AsmToken::EndOfStatement)) {
4562       // We have a match!
4563       Operands.push_back(ARMOperand::CreateModImm((Enc & 0xFF),
4564                                                   (Enc & 0xF00) >> 7,
4565                                                   Sx1, Ex1));
4566       return MatchOperand_Success;
4567     }
4568 
4569     // We have parsed an immediate which is not for us, fallback to a plain
4570     // immediate. This can happen for instruction aliases. For an example,
4571     // ARMInstrInfo.td defines the alias [mov <-> mvn] which can transform
4572     // a mov (mvn) with a mod_imm_neg/mod_imm_not operand into the opposite
4573     // instruction with a mod_imm operand. The alias is defined such that the
4574     // parser method is shared, that's why we have to do this here.
4575     if (Parser.getTok().is(AsmToken::EndOfStatement)) {
4576       Operands.push_back(ARMOperand::CreateImm(Imm1Exp, Sx1, Ex1));
4577       return MatchOperand_Success;
4578     }
4579   } else {
4580     // Operands like #(l1 - l2) can only be evaluated at a later stage (via an
4581     // MCFixup). Fallback to a plain immediate.
4582     Operands.push_back(ARMOperand::CreateImm(Imm1Exp, Sx1, Ex1));
4583     return MatchOperand_Success;
4584   }
4585 
4586   // From this point onward, we expect the input to be a (#bits, #rot) pair
4587   if (Parser.getTok().isNot(AsmToken::Comma)) {
4588     Error(Sx1, "expected modified immediate operand: #[0, 255], #even[0-30]");
4589     return MatchOperand_ParseFail;
4590   }
4591 
4592   if (Imm1 & ~0xFF) {
4593     Error(Sx1, "immediate operand must a number in the range [0, 255]");
4594     return MatchOperand_ParseFail;
4595   }
4596 
4597   // Eat the comma
4598   Parser.Lex();
4599 
4600   // Repeat for #rot
4601   SMLoc Sx2, Ex2;
4602   Sx2 = Parser.getTok().getLoc();
4603 
4604   // Eat the optional hash (dollar)
4605   if (Parser.getTok().is(AsmToken::Hash) ||
4606       Parser.getTok().is(AsmToken::Dollar))
4607     Parser.Lex();
4608 
4609   const MCExpr *Imm2Exp;
4610   if (getParser().parseExpression(Imm2Exp, Ex2)) {
4611     Error(Sx2, "malformed expression");
4612     return MatchOperand_ParseFail;
4613   }
4614 
4615   CE = dyn_cast<MCConstantExpr>(Imm2Exp);
4616 
4617   if (CE) {
4618     Imm2 = CE->getValue();
4619     if (!(Imm2 & ~0x1E)) {
4620       // We have a match!
4621       Operands.push_back(ARMOperand::CreateModImm(Imm1, Imm2, S, Ex2));
4622       return MatchOperand_Success;
4623     }
4624     Error(Sx2, "immediate operand must an even number in the range [0, 30]");
4625     return MatchOperand_ParseFail;
4626   } else {
4627     Error(Sx2, "constant expression expected");
4628     return MatchOperand_ParseFail;
4629   }
4630 }
4631 
4632 OperandMatchResultTy
4633 ARMAsmParser::parseBitfield(OperandVector &Operands) {
4634   MCAsmParser &Parser = getParser();
4635   SMLoc S = Parser.getTok().getLoc();
4636   // The bitfield descriptor is really two operands, the LSB and the width.
4637   if (Parser.getTok().isNot(AsmToken::Hash) &&
4638       Parser.getTok().isNot(AsmToken::Dollar)) {
4639     Error(Parser.getTok().getLoc(), "'#' expected");
4640     return MatchOperand_ParseFail;
4641   }
4642   Parser.Lex(); // Eat hash token.
4643 
4644   const MCExpr *LSBExpr;
4645   SMLoc E = Parser.getTok().getLoc();
4646   if (getParser().parseExpression(LSBExpr)) {
4647     Error(E, "malformed immediate expression");
4648     return MatchOperand_ParseFail;
4649   }
4650   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(LSBExpr);
4651   if (!CE) {
4652     Error(E, "'lsb' operand must be an immediate");
4653     return MatchOperand_ParseFail;
4654   }
4655 
4656   int64_t LSB = CE->getValue();
4657   // The LSB must be in the range [0,31]
4658   if (LSB < 0 || LSB > 31) {
4659     Error(E, "'lsb' operand must be in the range [0,31]");
4660     return MatchOperand_ParseFail;
4661   }
4662   E = Parser.getTok().getLoc();
4663 
4664   // Expect another immediate operand.
4665   if (Parser.getTok().isNot(AsmToken::Comma)) {
4666     Error(Parser.getTok().getLoc(), "too few operands");
4667     return MatchOperand_ParseFail;
4668   }
4669   Parser.Lex(); // Eat hash token.
4670   if (Parser.getTok().isNot(AsmToken::Hash) &&
4671       Parser.getTok().isNot(AsmToken::Dollar)) {
4672     Error(Parser.getTok().getLoc(), "'#' expected");
4673     return MatchOperand_ParseFail;
4674   }
4675   Parser.Lex(); // Eat hash token.
4676 
4677   const MCExpr *WidthExpr;
4678   SMLoc EndLoc;
4679   if (getParser().parseExpression(WidthExpr, EndLoc)) {
4680     Error(E, "malformed immediate expression");
4681     return MatchOperand_ParseFail;
4682   }
4683   CE = dyn_cast<MCConstantExpr>(WidthExpr);
4684   if (!CE) {
4685     Error(E, "'width' operand must be an immediate");
4686     return MatchOperand_ParseFail;
4687   }
4688 
4689   int64_t Width = CE->getValue();
4690   // The LSB must be in the range [1,32-lsb]
4691   if (Width < 1 || Width > 32 - LSB) {
4692     Error(E, "'width' operand must be in the range [1,32-lsb]");
4693     return MatchOperand_ParseFail;
4694   }
4695 
4696   Operands.push_back(ARMOperand::CreateBitfield(LSB, Width, S, EndLoc));
4697 
4698   return MatchOperand_Success;
4699 }
4700 
4701 OperandMatchResultTy
4702 ARMAsmParser::parsePostIdxReg(OperandVector &Operands) {
4703   // Check for a post-index addressing register operand. Specifically:
4704   // postidx_reg := '+' register {, shift}
4705   //              | '-' register {, shift}
4706   //              | register {, shift}
4707 
4708   // This method must return MatchOperand_NoMatch without consuming any tokens
4709   // in the case where there is no match, as other alternatives take other
4710   // parse methods.
4711   MCAsmParser &Parser = getParser();
4712   AsmToken Tok = Parser.getTok();
4713   SMLoc S = Tok.getLoc();
4714   bool haveEaten = false;
4715   bool isAdd = true;
4716   if (Tok.is(AsmToken::Plus)) {
4717     Parser.Lex(); // Eat the '+' token.
4718     haveEaten = true;
4719   } else if (Tok.is(AsmToken::Minus)) {
4720     Parser.Lex(); // Eat the '-' token.
4721     isAdd = false;
4722     haveEaten = true;
4723   }
4724 
4725   SMLoc E = Parser.getTok().getEndLoc();
4726   int Reg = tryParseRegister();
4727   if (Reg == -1) {
4728     if (!haveEaten)
4729       return MatchOperand_NoMatch;
4730     Error(Parser.getTok().getLoc(), "register expected");
4731     return MatchOperand_ParseFail;
4732   }
4733 
4734   ARM_AM::ShiftOpc ShiftTy = ARM_AM::no_shift;
4735   unsigned ShiftImm = 0;
4736   if (Parser.getTok().is(AsmToken::Comma)) {
4737     Parser.Lex(); // Eat the ','.
4738     if (parseMemRegOffsetShift(ShiftTy, ShiftImm))
4739       return MatchOperand_ParseFail;
4740 
4741     // FIXME: Only approximates end...may include intervening whitespace.
4742     E = Parser.getTok().getLoc();
4743   }
4744 
4745   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ShiftTy,
4746                                                   ShiftImm, S, E));
4747 
4748   return MatchOperand_Success;
4749 }
4750 
4751 OperandMatchResultTy
4752 ARMAsmParser::parseAM3Offset(OperandVector &Operands) {
4753   // Check for a post-index addressing register operand. Specifically:
4754   // am3offset := '+' register
4755   //              | '-' register
4756   //              | register
4757   //              | # imm
4758   //              | # + imm
4759   //              | # - imm
4760 
4761   // This method must return MatchOperand_NoMatch without consuming any tokens
4762   // in the case where there is no match, as other alternatives take other
4763   // parse methods.
4764   MCAsmParser &Parser = getParser();
4765   AsmToken Tok = Parser.getTok();
4766   SMLoc S = Tok.getLoc();
4767 
4768   // Do immediates first, as we always parse those if we have a '#'.
4769   if (Parser.getTok().is(AsmToken::Hash) ||
4770       Parser.getTok().is(AsmToken::Dollar)) {
4771     Parser.Lex(); // Eat '#' or '$'.
4772     // Explicitly look for a '-', as we need to encode negative zero
4773     // differently.
4774     bool isNegative = Parser.getTok().is(AsmToken::Minus);
4775     const MCExpr *Offset;
4776     SMLoc E;
4777     if (getParser().parseExpression(Offset, E))
4778       return MatchOperand_ParseFail;
4779     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
4780     if (!CE) {
4781       Error(S, "constant expression expected");
4782       return MatchOperand_ParseFail;
4783     }
4784     // Negative zero is encoded as the flag value
4785     // std::numeric_limits<int32_t>::min().
4786     int32_t Val = CE->getValue();
4787     if (isNegative && Val == 0)
4788       Val = std::numeric_limits<int32_t>::min();
4789 
4790     Operands.push_back(
4791       ARMOperand::CreateImm(MCConstantExpr::create(Val, getContext()), S, E));
4792 
4793     return MatchOperand_Success;
4794   }
4795 
4796   bool haveEaten = false;
4797   bool isAdd = true;
4798   if (Tok.is(AsmToken::Plus)) {
4799     Parser.Lex(); // Eat the '+' token.
4800     haveEaten = true;
4801   } else if (Tok.is(AsmToken::Minus)) {
4802     Parser.Lex(); // Eat the '-' token.
4803     isAdd = false;
4804     haveEaten = true;
4805   }
4806 
4807   Tok = Parser.getTok();
4808   int Reg = tryParseRegister();
4809   if (Reg == -1) {
4810     if (!haveEaten)
4811       return MatchOperand_NoMatch;
4812     Error(Tok.getLoc(), "register expected");
4813     return MatchOperand_ParseFail;
4814   }
4815 
4816   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ARM_AM::no_shift,
4817                                                   0, S, Tok.getEndLoc()));
4818 
4819   return MatchOperand_Success;
4820 }
4821 
4822 /// Convert parsed operands to MCInst.  Needed here because this instruction
4823 /// only has two register operands, but multiplication is commutative so
4824 /// assemblers should accept both "mul rD, rN, rD" and "mul rD, rD, rN".
4825 void ARMAsmParser::cvtThumbMultiply(MCInst &Inst,
4826                                     const OperandVector &Operands) {
4827   ((ARMOperand &)*Operands[3]).addRegOperands(Inst, 1);
4828   ((ARMOperand &)*Operands[1]).addCCOutOperands(Inst, 1);
4829   // If we have a three-operand form, make sure to set Rn to be the operand
4830   // that isn't the same as Rd.
4831   unsigned RegOp = 4;
4832   if (Operands.size() == 6 &&
4833       ((ARMOperand &)*Operands[4]).getReg() ==
4834           ((ARMOperand &)*Operands[3]).getReg())
4835     RegOp = 5;
4836   ((ARMOperand &)*Operands[RegOp]).addRegOperands(Inst, 1);
4837   Inst.addOperand(Inst.getOperand(0));
4838   ((ARMOperand &)*Operands[2]).addCondCodeOperands(Inst, 2);
4839 }
4840 
4841 void ARMAsmParser::cvtThumbBranches(MCInst &Inst,
4842                                     const OperandVector &Operands) {
4843   int CondOp = -1, ImmOp = -1;
4844   switch(Inst.getOpcode()) {
4845     case ARM::tB:
4846     case ARM::tBcc:  CondOp = 1; ImmOp = 2; break;
4847 
4848     case ARM::t2B:
4849     case ARM::t2Bcc: CondOp = 1; ImmOp = 3; break;
4850 
4851     default: llvm_unreachable("Unexpected instruction in cvtThumbBranches");
4852   }
4853   // first decide whether or not the branch should be conditional
4854   // by looking at it's location relative to an IT block
4855   if(inITBlock()) {
4856     // inside an IT block we cannot have any conditional branches. any
4857     // such instructions needs to be converted to unconditional form
4858     switch(Inst.getOpcode()) {
4859       case ARM::tBcc: Inst.setOpcode(ARM::tB); break;
4860       case ARM::t2Bcc: Inst.setOpcode(ARM::t2B); break;
4861     }
4862   } else {
4863     // outside IT blocks we can only have unconditional branches with AL
4864     // condition code or conditional branches with non-AL condition code
4865     unsigned Cond = static_cast<ARMOperand &>(*Operands[CondOp]).getCondCode();
4866     switch(Inst.getOpcode()) {
4867       case ARM::tB:
4868       case ARM::tBcc:
4869         Inst.setOpcode(Cond == ARMCC::AL ? ARM::tB : ARM::tBcc);
4870         break;
4871       case ARM::t2B:
4872       case ARM::t2Bcc:
4873         Inst.setOpcode(Cond == ARMCC::AL ? ARM::t2B : ARM::t2Bcc);
4874         break;
4875     }
4876   }
4877 
4878   // now decide on encoding size based on branch target range
4879   switch(Inst.getOpcode()) {
4880     // classify tB as either t2B or t1B based on range of immediate operand
4881     case ARM::tB: {
4882       ARMOperand &op = static_cast<ARMOperand &>(*Operands[ImmOp]);
4883       if (!op.isSignedOffset<11, 1>() && isThumb() && hasV8MBaseline())
4884         Inst.setOpcode(ARM::t2B);
4885       break;
4886     }
4887     // classify tBcc as either t2Bcc or t1Bcc based on range of immediate operand
4888     case ARM::tBcc: {
4889       ARMOperand &op = static_cast<ARMOperand &>(*Operands[ImmOp]);
4890       if (!op.isSignedOffset<8, 1>() && isThumb() && hasV8MBaseline())
4891         Inst.setOpcode(ARM::t2Bcc);
4892       break;
4893     }
4894   }
4895   ((ARMOperand &)*Operands[ImmOp]).addImmOperands(Inst, 1);
4896   ((ARMOperand &)*Operands[CondOp]).addCondCodeOperands(Inst, 2);
4897 }
4898 
4899 /// Parse an ARM memory expression, return false if successful else return true
4900 /// or an error.  The first token must be a '[' when called.
4901 bool ARMAsmParser::parseMemory(OperandVector &Operands) {
4902   MCAsmParser &Parser = getParser();
4903   SMLoc S, E;
4904   if (Parser.getTok().isNot(AsmToken::LBrac))
4905     return TokError("Token is not a Left Bracket");
4906   S = Parser.getTok().getLoc();
4907   Parser.Lex(); // Eat left bracket token.
4908 
4909   const AsmToken &BaseRegTok = Parser.getTok();
4910   int BaseRegNum = tryParseRegister();
4911   if (BaseRegNum == -1)
4912     return Error(BaseRegTok.getLoc(), "register expected");
4913 
4914   // The next token must either be a comma, a colon or a closing bracket.
4915   const AsmToken &Tok = Parser.getTok();
4916   if (!Tok.is(AsmToken::Colon) && !Tok.is(AsmToken::Comma) &&
4917       !Tok.is(AsmToken::RBrac))
4918     return Error(Tok.getLoc(), "malformed memory operand");
4919 
4920   if (Tok.is(AsmToken::RBrac)) {
4921     E = Tok.getEndLoc();
4922     Parser.Lex(); // Eat right bracket token.
4923 
4924     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, 0,
4925                                              ARM_AM::no_shift, 0, 0, false,
4926                                              S, E));
4927 
4928     // If there's a pre-indexing writeback marker, '!', just add it as a token
4929     // operand. It's rather odd, but syntactically valid.
4930     if (Parser.getTok().is(AsmToken::Exclaim)) {
4931       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
4932       Parser.Lex(); // Eat the '!'.
4933     }
4934 
4935     return false;
4936   }
4937 
4938   assert((Tok.is(AsmToken::Colon) || Tok.is(AsmToken::Comma)) &&
4939          "Lost colon or comma in memory operand?!");
4940   if (Tok.is(AsmToken::Comma)) {
4941     Parser.Lex(); // Eat the comma.
4942   }
4943 
4944   // If we have a ':', it's an alignment specifier.
4945   if (Parser.getTok().is(AsmToken::Colon)) {
4946     Parser.Lex(); // Eat the ':'.
4947     E = Parser.getTok().getLoc();
4948     SMLoc AlignmentLoc = Tok.getLoc();
4949 
4950     const MCExpr *Expr;
4951     if (getParser().parseExpression(Expr))
4952      return true;
4953 
4954     // The expression has to be a constant. Memory references with relocations
4955     // don't come through here, as they use the <label> forms of the relevant
4956     // instructions.
4957     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
4958     if (!CE)
4959       return Error (E, "constant expression expected");
4960 
4961     unsigned Align = 0;
4962     switch (CE->getValue()) {
4963     default:
4964       return Error(E,
4965                    "alignment specifier must be 16, 32, 64, 128, or 256 bits");
4966     case 16:  Align = 2; break;
4967     case 32:  Align = 4; break;
4968     case 64:  Align = 8; break;
4969     case 128: Align = 16; break;
4970     case 256: Align = 32; break;
4971     }
4972 
4973     // Now we should have the closing ']'
4974     if (Parser.getTok().isNot(AsmToken::RBrac))
4975       return Error(Parser.getTok().getLoc(), "']' expected");
4976     E = Parser.getTok().getEndLoc();
4977     Parser.Lex(); // Eat right bracket token.
4978 
4979     // Don't worry about range checking the value here. That's handled by
4980     // the is*() predicates.
4981     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, 0,
4982                                              ARM_AM::no_shift, 0, Align,
4983                                              false, S, E, AlignmentLoc));
4984 
4985     // If there's a pre-indexing writeback marker, '!', just add it as a token
4986     // operand.
4987     if (Parser.getTok().is(AsmToken::Exclaim)) {
4988       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
4989       Parser.Lex(); // Eat the '!'.
4990     }
4991 
4992     return false;
4993   }
4994 
4995   // If we have a '#', it's an immediate offset, else assume it's a register
4996   // offset. Be friendly and also accept a plain integer (without a leading
4997   // hash) for gas compatibility.
4998   if (Parser.getTok().is(AsmToken::Hash) ||
4999       Parser.getTok().is(AsmToken::Dollar) ||
5000       Parser.getTok().is(AsmToken::Integer)) {
5001     if (Parser.getTok().isNot(AsmToken::Integer))
5002       Parser.Lex(); // Eat '#' or '$'.
5003     E = Parser.getTok().getLoc();
5004 
5005     bool isNegative = getParser().getTok().is(AsmToken::Minus);
5006     const MCExpr *Offset;
5007     if (getParser().parseExpression(Offset))
5008      return true;
5009 
5010     // The expression has to be a constant. Memory references with relocations
5011     // don't come through here, as they use the <label> forms of the relevant
5012     // instructions.
5013     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
5014     if (!CE)
5015       return Error (E, "constant expression expected");
5016 
5017     // If the constant was #-0, represent it as
5018     // std::numeric_limits<int32_t>::min().
5019     int32_t Val = CE->getValue();
5020     if (isNegative && Val == 0)
5021       CE = MCConstantExpr::create(std::numeric_limits<int32_t>::min(),
5022                                   getContext());
5023 
5024     // Now we should have the closing ']'
5025     if (Parser.getTok().isNot(AsmToken::RBrac))
5026       return Error(Parser.getTok().getLoc(), "']' expected");
5027     E = Parser.getTok().getEndLoc();
5028     Parser.Lex(); // Eat right bracket token.
5029 
5030     // Don't worry about range checking the value here. That's handled by
5031     // the is*() predicates.
5032     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, CE, 0,
5033                                              ARM_AM::no_shift, 0, 0,
5034                                              false, S, E));
5035 
5036     // If there's a pre-indexing writeback marker, '!', just add it as a token
5037     // operand.
5038     if (Parser.getTok().is(AsmToken::Exclaim)) {
5039       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
5040       Parser.Lex(); // Eat the '!'.
5041     }
5042 
5043     return false;
5044   }
5045 
5046   // The register offset is optionally preceded by a '+' or '-'
5047   bool isNegative = false;
5048   if (Parser.getTok().is(AsmToken::Minus)) {
5049     isNegative = true;
5050     Parser.Lex(); // Eat the '-'.
5051   } else if (Parser.getTok().is(AsmToken::Plus)) {
5052     // Nothing to do.
5053     Parser.Lex(); // Eat the '+'.
5054   }
5055 
5056   E = Parser.getTok().getLoc();
5057   int OffsetRegNum = tryParseRegister();
5058   if (OffsetRegNum == -1)
5059     return Error(E, "register expected");
5060 
5061   // If there's a shift operator, handle it.
5062   ARM_AM::ShiftOpc ShiftType = ARM_AM::no_shift;
5063   unsigned ShiftImm = 0;
5064   if (Parser.getTok().is(AsmToken::Comma)) {
5065     Parser.Lex(); // Eat the ','.
5066     if (parseMemRegOffsetShift(ShiftType, ShiftImm))
5067       return true;
5068   }
5069 
5070   // Now we should have the closing ']'
5071   if (Parser.getTok().isNot(AsmToken::RBrac))
5072     return Error(Parser.getTok().getLoc(), "']' expected");
5073   E = Parser.getTok().getEndLoc();
5074   Parser.Lex(); // Eat right bracket token.
5075 
5076   Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, OffsetRegNum,
5077                                            ShiftType, ShiftImm, 0, isNegative,
5078                                            S, E));
5079 
5080   // If there's a pre-indexing writeback marker, '!', just add it as a token
5081   // operand.
5082   if (Parser.getTok().is(AsmToken::Exclaim)) {
5083     Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
5084     Parser.Lex(); // Eat the '!'.
5085   }
5086 
5087   return false;
5088 }
5089 
5090 /// parseMemRegOffsetShift - one of these two:
5091 ///   ( lsl | lsr | asr | ror ) , # shift_amount
5092 ///   rrx
5093 /// return true if it parses a shift otherwise it returns false.
5094 bool ARMAsmParser::parseMemRegOffsetShift(ARM_AM::ShiftOpc &St,
5095                                           unsigned &Amount) {
5096   MCAsmParser &Parser = getParser();
5097   SMLoc Loc = Parser.getTok().getLoc();
5098   const AsmToken &Tok = Parser.getTok();
5099   if (Tok.isNot(AsmToken::Identifier))
5100     return Error(Loc, "illegal shift operator");
5101   StringRef ShiftName = Tok.getString();
5102   if (ShiftName == "lsl" || ShiftName == "LSL" ||
5103       ShiftName == "asl" || ShiftName == "ASL")
5104     St = ARM_AM::lsl;
5105   else if (ShiftName == "lsr" || ShiftName == "LSR")
5106     St = ARM_AM::lsr;
5107   else if (ShiftName == "asr" || ShiftName == "ASR")
5108     St = ARM_AM::asr;
5109   else if (ShiftName == "ror" || ShiftName == "ROR")
5110     St = ARM_AM::ror;
5111   else if (ShiftName == "rrx" || ShiftName == "RRX")
5112     St = ARM_AM::rrx;
5113   else
5114     return Error(Loc, "illegal shift operator");
5115   Parser.Lex(); // Eat shift type token.
5116 
5117   // rrx stands alone.
5118   Amount = 0;
5119   if (St != ARM_AM::rrx) {
5120     Loc = Parser.getTok().getLoc();
5121     // A '#' and a shift amount.
5122     const AsmToken &HashTok = Parser.getTok();
5123     if (HashTok.isNot(AsmToken::Hash) &&
5124         HashTok.isNot(AsmToken::Dollar))
5125       return Error(HashTok.getLoc(), "'#' expected");
5126     Parser.Lex(); // Eat hash token.
5127 
5128     const MCExpr *Expr;
5129     if (getParser().parseExpression(Expr))
5130       return true;
5131     // Range check the immediate.
5132     // lsl, ror: 0 <= imm <= 31
5133     // lsr, asr: 0 <= imm <= 32
5134     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
5135     if (!CE)
5136       return Error(Loc, "shift amount must be an immediate");
5137     int64_t Imm = CE->getValue();
5138     if (Imm < 0 ||
5139         ((St == ARM_AM::lsl || St == ARM_AM::ror) && Imm > 31) ||
5140         ((St == ARM_AM::lsr || St == ARM_AM::asr) && Imm > 32))
5141       return Error(Loc, "immediate shift value out of range");
5142     // If <ShiftTy> #0, turn it into a no_shift.
5143     if (Imm == 0)
5144       St = ARM_AM::lsl;
5145     // For consistency, treat lsr #32 and asr #32 as having immediate value 0.
5146     if (Imm == 32)
5147       Imm = 0;
5148     Amount = Imm;
5149   }
5150 
5151   return false;
5152 }
5153 
5154 /// parseFPImm - A floating point immediate expression operand.
5155 OperandMatchResultTy
5156 ARMAsmParser::parseFPImm(OperandVector &Operands) {
5157   MCAsmParser &Parser = getParser();
5158   // Anything that can accept a floating point constant as an operand
5159   // needs to go through here, as the regular parseExpression is
5160   // integer only.
5161   //
5162   // This routine still creates a generic Immediate operand, containing
5163   // a bitcast of the 64-bit floating point value. The various operands
5164   // that accept floats can check whether the value is valid for them
5165   // via the standard is*() predicates.
5166 
5167   SMLoc S = Parser.getTok().getLoc();
5168 
5169   if (Parser.getTok().isNot(AsmToken::Hash) &&
5170       Parser.getTok().isNot(AsmToken::Dollar))
5171     return MatchOperand_NoMatch;
5172 
5173   // Disambiguate the VMOV forms that can accept an FP immediate.
5174   // vmov.f32 <sreg>, #imm
5175   // vmov.f64 <dreg>, #imm
5176   // vmov.f32 <dreg>, #imm  @ vector f32x2
5177   // vmov.f32 <qreg>, #imm  @ vector f32x4
5178   //
5179   // There are also the NEON VMOV instructions which expect an
5180   // integer constant. Make sure we don't try to parse an FPImm
5181   // for these:
5182   // vmov.i{8|16|32|64} <dreg|qreg>, #imm
5183   ARMOperand &TyOp = static_cast<ARMOperand &>(*Operands[2]);
5184   bool isVmovf = TyOp.isToken() &&
5185                  (TyOp.getToken() == ".f32" || TyOp.getToken() == ".f64" ||
5186                   TyOp.getToken() == ".f16");
5187   ARMOperand &Mnemonic = static_cast<ARMOperand &>(*Operands[0]);
5188   bool isFconst = Mnemonic.isToken() && (Mnemonic.getToken() == "fconstd" ||
5189                                          Mnemonic.getToken() == "fconsts");
5190   if (!(isVmovf || isFconst))
5191     return MatchOperand_NoMatch;
5192 
5193   Parser.Lex(); // Eat '#' or '$'.
5194 
5195   // Handle negation, as that still comes through as a separate token.
5196   bool isNegative = false;
5197   if (Parser.getTok().is(AsmToken::Minus)) {
5198     isNegative = true;
5199     Parser.Lex();
5200   }
5201   const AsmToken &Tok = Parser.getTok();
5202   SMLoc Loc = Tok.getLoc();
5203   if (Tok.is(AsmToken::Real) && isVmovf) {
5204     APFloat RealVal(APFloat::IEEEsingle(), Tok.getString());
5205     uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
5206     // If we had a '-' in front, toggle the sign bit.
5207     IntVal ^= (uint64_t)isNegative << 31;
5208     Parser.Lex(); // Eat the token.
5209     Operands.push_back(ARMOperand::CreateImm(
5210           MCConstantExpr::create(IntVal, getContext()),
5211           S, Parser.getTok().getLoc()));
5212     return MatchOperand_Success;
5213   }
5214   // Also handle plain integers. Instructions which allow floating point
5215   // immediates also allow a raw encoded 8-bit value.
5216   if (Tok.is(AsmToken::Integer) && isFconst) {
5217     int64_t Val = Tok.getIntVal();
5218     Parser.Lex(); // Eat the token.
5219     if (Val > 255 || Val < 0) {
5220       Error(Loc, "encoded floating point value out of range");
5221       return MatchOperand_ParseFail;
5222     }
5223     float RealVal = ARM_AM::getFPImmFloat(Val);
5224     Val = APFloat(RealVal).bitcastToAPInt().getZExtValue();
5225 
5226     Operands.push_back(ARMOperand::CreateImm(
5227         MCConstantExpr::create(Val, getContext()), S,
5228         Parser.getTok().getLoc()));
5229     return MatchOperand_Success;
5230   }
5231 
5232   Error(Loc, "invalid floating point immediate");
5233   return MatchOperand_ParseFail;
5234 }
5235 
5236 /// Parse a arm instruction operand.  For now this parses the operand regardless
5237 /// of the mnemonic.
5238 bool ARMAsmParser::parseOperand(OperandVector &Operands, StringRef Mnemonic) {
5239   MCAsmParser &Parser = getParser();
5240   SMLoc S, E;
5241 
5242   // Check if the current operand has a custom associated parser, if so, try to
5243   // custom parse the operand, or fallback to the general approach.
5244   OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
5245   if (ResTy == MatchOperand_Success)
5246     return false;
5247   // If there wasn't a custom match, try the generic matcher below. Otherwise,
5248   // there was a match, but an error occurred, in which case, just return that
5249   // the operand parsing failed.
5250   if (ResTy == MatchOperand_ParseFail)
5251     return true;
5252 
5253   switch (getLexer().getKind()) {
5254   default:
5255     Error(Parser.getTok().getLoc(), "unexpected token in operand");
5256     return true;
5257   case AsmToken::Identifier: {
5258     // If we've seen a branch mnemonic, the next operand must be a label.  This
5259     // is true even if the label is a register name.  So "br r1" means branch to
5260     // label "r1".
5261     bool ExpectLabel = Mnemonic == "b" || Mnemonic == "bl";
5262     if (!ExpectLabel) {
5263       if (!tryParseRegisterWithWriteBack(Operands))
5264         return false;
5265       int Res = tryParseShiftRegister(Operands);
5266       if (Res == 0) // success
5267         return false;
5268       else if (Res == -1) // irrecoverable error
5269         return true;
5270       // If this is VMRS, check for the apsr_nzcv operand.
5271       if (Mnemonic == "vmrs" &&
5272           Parser.getTok().getString().equals_lower("apsr_nzcv")) {
5273         S = Parser.getTok().getLoc();
5274         Parser.Lex();
5275         Operands.push_back(ARMOperand::CreateToken("APSR_nzcv", S));
5276         return false;
5277       }
5278     }
5279 
5280     // Fall though for the Identifier case that is not a register or a
5281     // special name.
5282     LLVM_FALLTHROUGH;
5283   }
5284   case AsmToken::LParen:  // parenthesized expressions like (_strcmp-4)
5285   case AsmToken::Integer: // things like 1f and 2b as a branch targets
5286   case AsmToken::String:  // quoted label names.
5287   case AsmToken::Dot: {   // . as a branch target
5288     // This was not a register so parse other operands that start with an
5289     // identifier (like labels) as expressions and create them as immediates.
5290     const MCExpr *IdVal;
5291     S = Parser.getTok().getLoc();
5292     if (getParser().parseExpression(IdVal))
5293       return true;
5294     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5295     Operands.push_back(ARMOperand::CreateImm(IdVal, S, E));
5296     return false;
5297   }
5298   case AsmToken::LBrac:
5299     return parseMemory(Operands);
5300   case AsmToken::LCurly:
5301     return parseRegisterList(Operands);
5302   case AsmToken::Dollar:
5303   case AsmToken::Hash:
5304     // #42 -> immediate.
5305     S = Parser.getTok().getLoc();
5306     Parser.Lex();
5307 
5308     if (Parser.getTok().isNot(AsmToken::Colon)) {
5309       bool isNegative = Parser.getTok().is(AsmToken::Minus);
5310       const MCExpr *ImmVal;
5311       if (getParser().parseExpression(ImmVal))
5312         return true;
5313       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ImmVal);
5314       if (CE) {
5315         int32_t Val = CE->getValue();
5316         if (isNegative && Val == 0)
5317           ImmVal = MCConstantExpr::create(std::numeric_limits<int32_t>::min(),
5318                                           getContext());
5319       }
5320       E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5321       Operands.push_back(ARMOperand::CreateImm(ImmVal, S, E));
5322 
5323       // There can be a trailing '!' on operands that we want as a separate
5324       // '!' Token operand. Handle that here. For example, the compatibility
5325       // alias for 'srsdb sp!, #imm' is 'srsdb #imm!'.
5326       if (Parser.getTok().is(AsmToken::Exclaim)) {
5327         Operands.push_back(ARMOperand::CreateToken(Parser.getTok().getString(),
5328                                                    Parser.getTok().getLoc()));
5329         Parser.Lex(); // Eat exclaim token
5330       }
5331       return false;
5332     }
5333     // w/ a ':' after the '#', it's just like a plain ':'.
5334     LLVM_FALLTHROUGH;
5335 
5336   case AsmToken::Colon: {
5337     S = Parser.getTok().getLoc();
5338     // ":lower16:" and ":upper16:" expression prefixes
5339     // FIXME: Check it's an expression prefix,
5340     // e.g. (FOO - :lower16:BAR) isn't legal.
5341     ARMMCExpr::VariantKind RefKind;
5342     if (parsePrefix(RefKind))
5343       return true;
5344 
5345     const MCExpr *SubExprVal;
5346     if (getParser().parseExpression(SubExprVal))
5347       return true;
5348 
5349     const MCExpr *ExprVal = ARMMCExpr::create(RefKind, SubExprVal,
5350                                               getContext());
5351     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5352     Operands.push_back(ARMOperand::CreateImm(ExprVal, S, E));
5353     return false;
5354   }
5355   case AsmToken::Equal: {
5356     S = Parser.getTok().getLoc();
5357     if (Mnemonic != "ldr") // only parse for ldr pseudo (e.g. ldr r0, =val)
5358       return Error(S, "unexpected token in operand");
5359     Parser.Lex(); // Eat '='
5360     const MCExpr *SubExprVal;
5361     if (getParser().parseExpression(SubExprVal))
5362       return true;
5363     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5364 
5365     // execute-only: we assume that assembly programmers know what they are
5366     // doing and allow literal pool creation here
5367     Operands.push_back(ARMOperand::CreateConstantPoolImm(SubExprVal, S, E));
5368     return false;
5369   }
5370   }
5371 }
5372 
5373 // parsePrefix - Parse ARM 16-bit relocations expression prefix, i.e.
5374 //  :lower16: and :upper16:.
5375 bool ARMAsmParser::parsePrefix(ARMMCExpr::VariantKind &RefKind) {
5376   MCAsmParser &Parser = getParser();
5377   RefKind = ARMMCExpr::VK_ARM_None;
5378 
5379   // consume an optional '#' (GNU compatibility)
5380   if (getLexer().is(AsmToken::Hash))
5381     Parser.Lex();
5382 
5383   // :lower16: and :upper16: modifiers
5384   assert(getLexer().is(AsmToken::Colon) && "expected a :");
5385   Parser.Lex(); // Eat ':'
5386 
5387   if (getLexer().isNot(AsmToken::Identifier)) {
5388     Error(Parser.getTok().getLoc(), "expected prefix identifier in operand");
5389     return true;
5390   }
5391 
5392   enum {
5393     COFF = (1 << MCObjectFileInfo::IsCOFF),
5394     ELF = (1 << MCObjectFileInfo::IsELF),
5395     MACHO = (1 << MCObjectFileInfo::IsMachO),
5396     WASM = (1 << MCObjectFileInfo::IsWasm),
5397   };
5398   static const struct PrefixEntry {
5399     const char *Spelling;
5400     ARMMCExpr::VariantKind VariantKind;
5401     uint8_t SupportedFormats;
5402   } PrefixEntries[] = {
5403     { "lower16", ARMMCExpr::VK_ARM_LO16, COFF | ELF | MACHO },
5404     { "upper16", ARMMCExpr::VK_ARM_HI16, COFF | ELF | MACHO },
5405   };
5406 
5407   StringRef IDVal = Parser.getTok().getIdentifier();
5408 
5409   const auto &Prefix =
5410       std::find_if(std::begin(PrefixEntries), std::end(PrefixEntries),
5411                    [&IDVal](const PrefixEntry &PE) {
5412                       return PE.Spelling == IDVal;
5413                    });
5414   if (Prefix == std::end(PrefixEntries)) {
5415     Error(Parser.getTok().getLoc(), "unexpected prefix in operand");
5416     return true;
5417   }
5418 
5419   uint8_t CurrentFormat;
5420   switch (getContext().getObjectFileInfo()->getObjectFileType()) {
5421   case MCObjectFileInfo::IsMachO:
5422     CurrentFormat = MACHO;
5423     break;
5424   case MCObjectFileInfo::IsELF:
5425     CurrentFormat = ELF;
5426     break;
5427   case MCObjectFileInfo::IsCOFF:
5428     CurrentFormat = COFF;
5429     break;
5430   case MCObjectFileInfo::IsWasm:
5431     CurrentFormat = WASM;
5432     break;
5433   }
5434 
5435   if (~Prefix->SupportedFormats & CurrentFormat) {
5436     Error(Parser.getTok().getLoc(),
5437           "cannot represent relocation in the current file format");
5438     return true;
5439   }
5440 
5441   RefKind = Prefix->VariantKind;
5442   Parser.Lex();
5443 
5444   if (getLexer().isNot(AsmToken::Colon)) {
5445     Error(Parser.getTok().getLoc(), "unexpected token after prefix");
5446     return true;
5447   }
5448   Parser.Lex(); // Eat the last ':'
5449 
5450   return false;
5451 }
5452 
5453 /// \brief Given a mnemonic, split out possible predication code and carry
5454 /// setting letters to form a canonical mnemonic and flags.
5455 //
5456 // FIXME: Would be nice to autogen this.
5457 // FIXME: This is a bit of a maze of special cases.
5458 StringRef ARMAsmParser::splitMnemonic(StringRef Mnemonic,
5459                                       unsigned &PredicationCode,
5460                                       bool &CarrySetting,
5461                                       unsigned &ProcessorIMod,
5462                                       StringRef &ITMask) {
5463   PredicationCode = ARMCC::AL;
5464   CarrySetting = false;
5465   ProcessorIMod = 0;
5466 
5467   // Ignore some mnemonics we know aren't predicated forms.
5468   //
5469   // FIXME: Would be nice to autogen this.
5470   if ((Mnemonic == "movs" && isThumb()) ||
5471       Mnemonic == "teq"   || Mnemonic == "vceq"   || Mnemonic == "svc"   ||
5472       Mnemonic == "mls"   || Mnemonic == "smmls"  || Mnemonic == "vcls"  ||
5473       Mnemonic == "vmls"  || Mnemonic == "vnmls"  || Mnemonic == "vacge" ||
5474       Mnemonic == "vcge"  || Mnemonic == "vclt"   || Mnemonic == "vacgt" ||
5475       Mnemonic == "vaclt" || Mnemonic == "vacle"  || Mnemonic == "hlt" ||
5476       Mnemonic == "vcgt"  || Mnemonic == "vcle"   || Mnemonic == "smlal" ||
5477       Mnemonic == "umaal" || Mnemonic == "umlal"  || Mnemonic == "vabal" ||
5478       Mnemonic == "vmlal" || Mnemonic == "vpadal" || Mnemonic == "vqdmlal" ||
5479       Mnemonic == "fmuls" || Mnemonic == "vmaxnm" || Mnemonic == "vminnm" ||
5480       Mnemonic == "vcvta" || Mnemonic == "vcvtn"  || Mnemonic == "vcvtp" ||
5481       Mnemonic == "vcvtm" || Mnemonic == "vrinta" || Mnemonic == "vrintn" ||
5482       Mnemonic == "vrintp" || Mnemonic == "vrintm" || Mnemonic == "hvc" ||
5483       Mnemonic.startswith("vsel") || Mnemonic == "vins" || Mnemonic == "vmovx" ||
5484       Mnemonic == "bxns"  || Mnemonic == "blxns" ||
5485       Mnemonic == "vudot" || Mnemonic == "vsdot" ||
5486       Mnemonic == "vcmla" || Mnemonic == "vcadd")
5487     return Mnemonic;
5488 
5489   // First, split out any predication code. Ignore mnemonics we know aren't
5490   // predicated but do have a carry-set and so weren't caught above.
5491   if (Mnemonic != "adcs" && Mnemonic != "bics" && Mnemonic != "movs" &&
5492       Mnemonic != "muls" && Mnemonic != "smlals" && Mnemonic != "smulls" &&
5493       Mnemonic != "umlals" && Mnemonic != "umulls" && Mnemonic != "lsls" &&
5494       Mnemonic != "sbcs" && Mnemonic != "rscs") {
5495     unsigned CC = ARMCondCodeFromString(Mnemonic.substr(Mnemonic.size()-2));
5496     if (CC != ~0U) {
5497       Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 2);
5498       PredicationCode = CC;
5499     }
5500   }
5501 
5502   // Next, determine if we have a carry setting bit. We explicitly ignore all
5503   // the instructions we know end in 's'.
5504   if (Mnemonic.endswith("s") &&
5505       !(Mnemonic == "cps" || Mnemonic == "mls" ||
5506         Mnemonic == "mrs" || Mnemonic == "smmls" || Mnemonic == "vabs" ||
5507         Mnemonic == "vcls" || Mnemonic == "vmls" || Mnemonic == "vmrs" ||
5508         Mnemonic == "vnmls" || Mnemonic == "vqabs" || Mnemonic == "vrecps" ||
5509         Mnemonic == "vrsqrts" || Mnemonic == "srs" || Mnemonic == "flds" ||
5510         Mnemonic == "fmrs" || Mnemonic == "fsqrts" || Mnemonic == "fsubs" ||
5511         Mnemonic == "fsts" || Mnemonic == "fcpys" || Mnemonic == "fdivs" ||
5512         Mnemonic == "fmuls" || Mnemonic == "fcmps" || Mnemonic == "fcmpzs" ||
5513         Mnemonic == "vfms" || Mnemonic == "vfnms" || Mnemonic == "fconsts" ||
5514         Mnemonic == "bxns" || Mnemonic == "blxns" ||
5515         (Mnemonic == "movs" && isThumb()))) {
5516     Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 1);
5517     CarrySetting = true;
5518   }
5519 
5520   // The "cps" instruction can have a interrupt mode operand which is glued into
5521   // the mnemonic. Check if this is the case, split it and parse the imod op
5522   if (Mnemonic.startswith("cps")) {
5523     // Split out any imod code.
5524     unsigned IMod =
5525       StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2, 2))
5526       .Case("ie", ARM_PROC::IE)
5527       .Case("id", ARM_PROC::ID)
5528       .Default(~0U);
5529     if (IMod != ~0U) {
5530       Mnemonic = Mnemonic.slice(0, Mnemonic.size()-2);
5531       ProcessorIMod = IMod;
5532     }
5533   }
5534 
5535   // The "it" instruction has the condition mask on the end of the mnemonic.
5536   if (Mnemonic.startswith("it")) {
5537     ITMask = Mnemonic.slice(2, Mnemonic.size());
5538     Mnemonic = Mnemonic.slice(0, 2);
5539   }
5540 
5541   return Mnemonic;
5542 }
5543 
5544 /// \brief Given a canonical mnemonic, determine if the instruction ever allows
5545 /// inclusion of carry set or predication code operands.
5546 //
5547 // FIXME: It would be nice to autogen this.
5548 void ARMAsmParser::getMnemonicAcceptInfo(StringRef Mnemonic, StringRef FullInst,
5549                                          bool &CanAcceptCarrySet,
5550                                          bool &CanAcceptPredicationCode) {
5551   CanAcceptCarrySet =
5552       Mnemonic == "and" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
5553       Mnemonic == "rrx" || Mnemonic == "ror" || Mnemonic == "sub" ||
5554       Mnemonic == "add" || Mnemonic == "adc" || Mnemonic == "mul" ||
5555       Mnemonic == "bic" || Mnemonic == "asr" || Mnemonic == "orr" ||
5556       Mnemonic == "mvn" || Mnemonic == "rsb" || Mnemonic == "rsc" ||
5557       Mnemonic == "orn" || Mnemonic == "sbc" || Mnemonic == "eor" ||
5558       Mnemonic == "neg" || Mnemonic == "vfm" || Mnemonic == "vfnm" ||
5559       (!isThumb() &&
5560        (Mnemonic == "smull" || Mnemonic == "mov" || Mnemonic == "mla" ||
5561         Mnemonic == "smlal" || Mnemonic == "umlal" || Mnemonic == "umull"));
5562 
5563   if (Mnemonic == "bkpt" || Mnemonic == "cbnz" || Mnemonic == "setend" ||
5564       Mnemonic == "cps" || Mnemonic == "it" || Mnemonic == "cbz" ||
5565       Mnemonic == "trap" || Mnemonic == "hlt" || Mnemonic == "udf" ||
5566       Mnemonic.startswith("crc32") || Mnemonic.startswith("cps") ||
5567       Mnemonic.startswith("vsel") || Mnemonic == "vmaxnm" ||
5568       Mnemonic == "vminnm" || Mnemonic == "vcvta" || Mnemonic == "vcvtn" ||
5569       Mnemonic == "vcvtp" || Mnemonic == "vcvtm" || Mnemonic == "vrinta" ||
5570       Mnemonic == "vrintn" || Mnemonic == "vrintp" || Mnemonic == "vrintm" ||
5571       Mnemonic.startswith("aes") || Mnemonic == "hvc" || Mnemonic == "setpan" ||
5572       Mnemonic.startswith("sha1") || Mnemonic.startswith("sha256") ||
5573       (FullInst.startswith("vmull") && FullInst.endswith(".p64")) ||
5574       Mnemonic == "vmovx" || Mnemonic == "vins" ||
5575       Mnemonic == "vudot" || Mnemonic == "vsdot" ||
5576       Mnemonic == "vcmla" || Mnemonic == "vcadd") {
5577     // These mnemonics are never predicable
5578     CanAcceptPredicationCode = false;
5579   } else if (!isThumb()) {
5580     // Some instructions are only predicable in Thumb mode
5581     CanAcceptPredicationCode =
5582         Mnemonic != "cdp2" && Mnemonic != "clrex" && Mnemonic != "mcr2" &&
5583         Mnemonic != "mcrr2" && Mnemonic != "mrc2" && Mnemonic != "mrrc2" &&
5584         Mnemonic != "dmb" && Mnemonic != "dsb" && Mnemonic != "isb" &&
5585         Mnemonic != "pld" && Mnemonic != "pli" && Mnemonic != "pldw" &&
5586         Mnemonic != "ldc2" && Mnemonic != "ldc2l" && Mnemonic != "stc2" &&
5587         Mnemonic != "stc2l" && !Mnemonic.startswith("rfe") &&
5588         !Mnemonic.startswith("srs");
5589   } else if (isThumbOne()) {
5590     if (hasV6MOps())
5591       CanAcceptPredicationCode = Mnemonic != "movs";
5592     else
5593       CanAcceptPredicationCode = Mnemonic != "nop" && Mnemonic != "movs";
5594   } else
5595     CanAcceptPredicationCode = true;
5596 }
5597 
5598 // \brief Some Thumb instructions have two operand forms that are not
5599 // available as three operand, convert to two operand form if possible.
5600 //
5601 // FIXME: We would really like to be able to tablegen'erate this.
5602 void ARMAsmParser::tryConvertingToTwoOperandForm(StringRef Mnemonic,
5603                                                  bool CarrySetting,
5604                                                  OperandVector &Operands) {
5605   if (Operands.size() != 6)
5606     return;
5607 
5608   const auto &Op3 = static_cast<ARMOperand &>(*Operands[3]);
5609         auto &Op4 = static_cast<ARMOperand &>(*Operands[4]);
5610   if (!Op3.isReg() || !Op4.isReg())
5611     return;
5612 
5613   auto Op3Reg = Op3.getReg();
5614   auto Op4Reg = Op4.getReg();
5615 
5616   // For most Thumb2 cases we just generate the 3 operand form and reduce
5617   // it in processInstruction(), but the 3 operand form of ADD (t2ADDrr)
5618   // won't accept SP or PC so we do the transformation here taking care
5619   // with immediate range in the 'add sp, sp #imm' case.
5620   auto &Op5 = static_cast<ARMOperand &>(*Operands[5]);
5621   if (isThumbTwo()) {
5622     if (Mnemonic != "add")
5623       return;
5624     bool TryTransform = Op3Reg == ARM::PC || Op4Reg == ARM::PC ||
5625                         (Op5.isReg() && Op5.getReg() == ARM::PC);
5626     if (!TryTransform) {
5627       TryTransform = (Op3Reg == ARM::SP || Op4Reg == ARM::SP ||
5628                       (Op5.isReg() && Op5.getReg() == ARM::SP)) &&
5629                      !(Op3Reg == ARM::SP && Op4Reg == ARM::SP &&
5630                        Op5.isImm() && !Op5.isImm0_508s4());
5631     }
5632     if (!TryTransform)
5633       return;
5634   } else if (!isThumbOne())
5635     return;
5636 
5637   if (!(Mnemonic == "add" || Mnemonic == "sub" || Mnemonic == "and" ||
5638         Mnemonic == "eor" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
5639         Mnemonic == "asr" || Mnemonic == "adc" || Mnemonic == "sbc" ||
5640         Mnemonic == "ror" || Mnemonic == "orr" || Mnemonic == "bic"))
5641     return;
5642 
5643   // If first 2 operands of a 3 operand instruction are the same
5644   // then transform to 2 operand version of the same instruction
5645   // e.g. 'adds r0, r0, #1' transforms to 'adds r0, #1'
5646   bool Transform = Op3Reg == Op4Reg;
5647 
5648   // For communtative operations, we might be able to transform if we swap
5649   // Op4 and Op5.  The 'ADD Rdm, SP, Rdm' form is already handled specially
5650   // as tADDrsp.
5651   const ARMOperand *LastOp = &Op5;
5652   bool Swap = false;
5653   if (!Transform && Op5.isReg() && Op3Reg == Op5.getReg() &&
5654       ((Mnemonic == "add" && Op4Reg != ARM::SP) ||
5655        Mnemonic == "and" || Mnemonic == "eor" ||
5656        Mnemonic == "adc" || Mnemonic == "orr")) {
5657     Swap = true;
5658     LastOp = &Op4;
5659     Transform = true;
5660   }
5661 
5662   // If both registers are the same then remove one of them from
5663   // the operand list, with certain exceptions.
5664   if (Transform) {
5665     // Don't transform 'adds Rd, Rd, Rm' or 'sub{s} Rd, Rd, Rm' because the
5666     // 2 operand forms don't exist.
5667     if (((Mnemonic == "add" && CarrySetting) || Mnemonic == "sub") &&
5668         LastOp->isReg())
5669       Transform = false;
5670 
5671     // Don't transform 'add/sub{s} Rd, Rd, #imm' if the immediate fits into
5672     // 3-bits because the ARMARM says not to.
5673     if ((Mnemonic == "add" || Mnemonic == "sub") && LastOp->isImm0_7())
5674       Transform = false;
5675   }
5676 
5677   if (Transform) {
5678     if (Swap)
5679       std::swap(Op4, Op5);
5680     Operands.erase(Operands.begin() + 3);
5681   }
5682 }
5683 
5684 bool ARMAsmParser::shouldOmitCCOutOperand(StringRef Mnemonic,
5685                                           OperandVector &Operands) {
5686   // FIXME: This is all horribly hacky. We really need a better way to deal
5687   // with optional operands like this in the matcher table.
5688 
5689   // The 'mov' mnemonic is special. One variant has a cc_out operand, while
5690   // another does not. Specifically, the MOVW instruction does not. So we
5691   // special case it here and remove the defaulted (non-setting) cc_out
5692   // operand if that's the instruction we're trying to match.
5693   //
5694   // We do this as post-processing of the explicit operands rather than just
5695   // conditionally adding the cc_out in the first place because we need
5696   // to check the type of the parsed immediate operand.
5697   if (Mnemonic == "mov" && Operands.size() > 4 && !isThumb() &&
5698       !static_cast<ARMOperand &>(*Operands[4]).isModImm() &&
5699       static_cast<ARMOperand &>(*Operands[4]).isImm0_65535Expr() &&
5700       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0)
5701     return true;
5702 
5703   // Register-register 'add' for thumb does not have a cc_out operand
5704   // when there are only two register operands.
5705   if (isThumb() && Mnemonic == "add" && Operands.size() == 5 &&
5706       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5707       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5708       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0)
5709     return true;
5710   // Register-register 'add' for thumb does not have a cc_out operand
5711   // when it's an ADD Rdm, SP, {Rdm|#imm0_255} instruction. We do
5712   // have to check the immediate range here since Thumb2 has a variant
5713   // that can handle a different range and has a cc_out operand.
5714   if (((isThumb() && Mnemonic == "add") ||
5715        (isThumbTwo() && Mnemonic == "sub")) &&
5716       Operands.size() == 6 && static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5717       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5718       static_cast<ARMOperand &>(*Operands[4]).getReg() == ARM::SP &&
5719       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5720       ((Mnemonic == "add" && static_cast<ARMOperand &>(*Operands[5]).isReg()) ||
5721        static_cast<ARMOperand &>(*Operands[5]).isImm0_1020s4()))
5722     return true;
5723   // For Thumb2, add/sub immediate does not have a cc_out operand for the
5724   // imm0_4095 variant. That's the least-preferred variant when
5725   // selecting via the generic "add" mnemonic, so to know that we
5726   // should remove the cc_out operand, we have to explicitly check that
5727   // it's not one of the other variants. Ugh.
5728   if (isThumbTwo() && (Mnemonic == "add" || Mnemonic == "sub") &&
5729       Operands.size() == 6 && static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5730       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5731       static_cast<ARMOperand &>(*Operands[5]).isImm()) {
5732     // Nest conditions rather than one big 'if' statement for readability.
5733     //
5734     // If both registers are low, we're in an IT block, and the immediate is
5735     // in range, we should use encoding T1 instead, which has a cc_out.
5736     if (inITBlock() &&
5737         isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) &&
5738         isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) &&
5739         static_cast<ARMOperand &>(*Operands[5]).isImm0_7())
5740       return false;
5741     // Check against T3. If the second register is the PC, this is an
5742     // alternate form of ADR, which uses encoding T4, so check for that too.
5743     if (static_cast<ARMOperand &>(*Operands[4]).getReg() != ARM::PC &&
5744         static_cast<ARMOperand &>(*Operands[5]).isT2SOImm())
5745       return false;
5746 
5747     // Otherwise, we use encoding T4, which does not have a cc_out
5748     // operand.
5749     return true;
5750   }
5751 
5752   // The thumb2 multiply instruction doesn't have a CCOut register, so
5753   // if we have a "mul" mnemonic in Thumb mode, check if we'll be able to
5754   // use the 16-bit encoding or not.
5755   if (isThumbTwo() && Mnemonic == "mul" && Operands.size() == 6 &&
5756       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5757       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5758       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5759       static_cast<ARMOperand &>(*Operands[5]).isReg() &&
5760       // If the registers aren't low regs, the destination reg isn't the
5761       // same as one of the source regs, or the cc_out operand is zero
5762       // outside of an IT block, we have to use the 32-bit encoding, so
5763       // remove the cc_out operand.
5764       (!isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) ||
5765        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) ||
5766        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[5]).getReg()) ||
5767        !inITBlock() || (static_cast<ARMOperand &>(*Operands[3]).getReg() !=
5768                             static_cast<ARMOperand &>(*Operands[5]).getReg() &&
5769                         static_cast<ARMOperand &>(*Operands[3]).getReg() !=
5770                             static_cast<ARMOperand &>(*Operands[4]).getReg())))
5771     return true;
5772 
5773   // Also check the 'mul' syntax variant that doesn't specify an explicit
5774   // destination register.
5775   if (isThumbTwo() && Mnemonic == "mul" && Operands.size() == 5 &&
5776       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5777       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5778       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5779       // If the registers aren't low regs  or the cc_out operand is zero
5780       // outside of an IT block, we have to use the 32-bit encoding, so
5781       // remove the cc_out operand.
5782       (!isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) ||
5783        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) ||
5784        !inITBlock()))
5785     return true;
5786 
5787   // Register-register 'add/sub' for thumb does not have a cc_out operand
5788   // when it's an ADD/SUB SP, #imm. Be lenient on count since there's also
5789   // the "add/sub SP, SP, #imm" version. If the follow-up operands aren't
5790   // right, this will result in better diagnostics (which operand is off)
5791   // anyway.
5792   if (isThumb() && (Mnemonic == "add" || Mnemonic == "sub") &&
5793       (Operands.size() == 5 || Operands.size() == 6) &&
5794       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5795       static_cast<ARMOperand &>(*Operands[3]).getReg() == ARM::SP &&
5796       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5797       (static_cast<ARMOperand &>(*Operands[4]).isImm() ||
5798        (Operands.size() == 6 &&
5799         static_cast<ARMOperand &>(*Operands[5]).isImm())))
5800     return true;
5801 
5802   return false;
5803 }
5804 
5805 bool ARMAsmParser::shouldOmitPredicateOperand(StringRef Mnemonic,
5806                                               OperandVector &Operands) {
5807   // VRINT{Z, R, X} have a predicate operand in VFP, but not in NEON
5808   unsigned RegIdx = 3;
5809   if ((Mnemonic == "vrintz" || Mnemonic == "vrintx" || Mnemonic == "vrintr") &&
5810       (static_cast<ARMOperand &>(*Operands[2]).getToken() == ".f32" ||
5811        static_cast<ARMOperand &>(*Operands[2]).getToken() == ".f16")) {
5812     if (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
5813         (static_cast<ARMOperand &>(*Operands[3]).getToken() == ".f32" ||
5814          static_cast<ARMOperand &>(*Operands[3]).getToken() == ".f16"))
5815       RegIdx = 4;
5816 
5817     if (static_cast<ARMOperand &>(*Operands[RegIdx]).isReg() &&
5818         (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(
5819              static_cast<ARMOperand &>(*Operands[RegIdx]).getReg()) ||
5820          ARMMCRegisterClasses[ARM::QPRRegClassID].contains(
5821              static_cast<ARMOperand &>(*Operands[RegIdx]).getReg())))
5822       return true;
5823   }
5824   return false;
5825 }
5826 
5827 static bool isDataTypeToken(StringRef Tok) {
5828   return Tok == ".8" || Tok == ".16" || Tok == ".32" || Tok == ".64" ||
5829     Tok == ".i8" || Tok == ".i16" || Tok == ".i32" || Tok == ".i64" ||
5830     Tok == ".u8" || Tok == ".u16" || Tok == ".u32" || Tok == ".u64" ||
5831     Tok == ".s8" || Tok == ".s16" || Tok == ".s32" || Tok == ".s64" ||
5832     Tok == ".p8" || Tok == ".p16" || Tok == ".f32" || Tok == ".f64" ||
5833     Tok == ".f" || Tok == ".d";
5834 }
5835 
5836 // FIXME: This bit should probably be handled via an explicit match class
5837 // in the .td files that matches the suffix instead of having it be
5838 // a literal string token the way it is now.
5839 static bool doesIgnoreDataTypeSuffix(StringRef Mnemonic, StringRef DT) {
5840   return Mnemonic.startswith("vldm") || Mnemonic.startswith("vstm");
5841 }
5842 
5843 static void applyMnemonicAliases(StringRef &Mnemonic, uint64_t Features,
5844                                  unsigned VariantID);
5845 
5846 static bool RequiresVFPRegListValidation(StringRef Inst,
5847                                          bool &AcceptSinglePrecisionOnly,
5848                                          bool &AcceptDoublePrecisionOnly) {
5849   if (Inst.size() < 7)
5850     return false;
5851 
5852   if (Inst.startswith("fldm") || Inst.startswith("fstm")) {
5853     StringRef AddressingMode = Inst.substr(4, 2);
5854     if (AddressingMode == "ia" || AddressingMode == "db" ||
5855         AddressingMode == "ea" || AddressingMode == "fd") {
5856       AcceptSinglePrecisionOnly = Inst[6] == 's';
5857       AcceptDoublePrecisionOnly = Inst[6] == 'd' || Inst[6] == 'x';
5858       return true;
5859     }
5860   }
5861 
5862   return false;
5863 }
5864 
5865 // The GNU assembler has aliases of ldrd and strd with the second register
5866 // omitted. We don't have a way to do that in tablegen, so fix it up here.
5867 //
5868 // We have to be careful to not emit an invalid Rt2 here, because the rest of
5869 // the assmebly parser could then generate confusing diagnostics refering to
5870 // it. If we do find anything that prevents us from doing the transformation we
5871 // bail out, and let the assembly parser report an error on the instruction as
5872 // it is written.
5873 void ARMAsmParser::fixupGNULDRDAlias(StringRef Mnemonic,
5874                                      OperandVector &Operands) {
5875   if (Mnemonic != "ldrd" && Mnemonic != "strd")
5876     return;
5877   if (Operands.size() < 4)
5878     return;
5879 
5880   ARMOperand &Op2 = static_cast<ARMOperand &>(*Operands[2]);
5881   ARMOperand &Op3 = static_cast<ARMOperand &>(*Operands[3]);
5882 
5883   if (!Op2.isReg())
5884     return;
5885   if (!Op3.isMem())
5886     return;
5887 
5888   const MCRegisterClass &GPR = MRI->getRegClass(ARM::GPRRegClassID);
5889   if (!GPR.contains(Op2.getReg()))
5890     return;
5891 
5892   unsigned RtEncoding = MRI->getEncodingValue(Op2.getReg());
5893   if (!isThumb() && (RtEncoding & 1)) {
5894     // In ARM mode, the registers must be from an aligned pair, this
5895     // restriction does not apply in Thumb mode.
5896     return;
5897   }
5898   if (Op2.getReg() == ARM::PC)
5899     return;
5900   unsigned PairedReg = GPR.getRegister(RtEncoding + 1);
5901   if (!PairedReg || PairedReg == ARM::PC ||
5902       (PairedReg == ARM::SP && !hasV8Ops()))
5903     return;
5904 
5905   Operands.insert(
5906       Operands.begin() + 3,
5907       ARMOperand::CreateReg(PairedReg, Op2.getStartLoc(), Op2.getEndLoc()));
5908   return;
5909 }
5910 
5911 /// Parse an arm instruction mnemonic followed by its operands.
5912 bool ARMAsmParser::ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
5913                                     SMLoc NameLoc, OperandVector &Operands) {
5914   MCAsmParser &Parser = getParser();
5915   // FIXME: Can this be done via tablegen in some fashion?
5916   bool RequireVFPRegisterListCheck;
5917   bool AcceptSinglePrecisionOnly;
5918   bool AcceptDoublePrecisionOnly;
5919   RequireVFPRegisterListCheck =
5920     RequiresVFPRegListValidation(Name, AcceptSinglePrecisionOnly,
5921                                  AcceptDoublePrecisionOnly);
5922 
5923   // Apply mnemonic aliases before doing anything else, as the destination
5924   // mnemonic may include suffices and we want to handle them normally.
5925   // The generic tblgen'erated code does this later, at the start of
5926   // MatchInstructionImpl(), but that's too late for aliases that include
5927   // any sort of suffix.
5928   uint64_t AvailableFeatures = getAvailableFeatures();
5929   unsigned AssemblerDialect = getParser().getAssemblerDialect();
5930   applyMnemonicAliases(Name, AvailableFeatures, AssemblerDialect);
5931 
5932   // First check for the ARM-specific .req directive.
5933   if (Parser.getTok().is(AsmToken::Identifier) &&
5934       Parser.getTok().getIdentifier() == ".req") {
5935     parseDirectiveReq(Name, NameLoc);
5936     // We always return 'error' for this, as we're done with this
5937     // statement and don't need to match the 'instruction."
5938     return true;
5939   }
5940 
5941   // Create the leading tokens for the mnemonic, split by '.' characters.
5942   size_t Start = 0, Next = Name.find('.');
5943   StringRef Mnemonic = Name.slice(Start, Next);
5944 
5945   // Split out the predication code and carry setting flag from the mnemonic.
5946   unsigned PredicationCode;
5947   unsigned ProcessorIMod;
5948   bool CarrySetting;
5949   StringRef ITMask;
5950   Mnemonic = splitMnemonic(Mnemonic, PredicationCode, CarrySetting,
5951                            ProcessorIMod, ITMask);
5952 
5953   // In Thumb1, only the branch (B) instruction can be predicated.
5954   if (isThumbOne() && PredicationCode != ARMCC::AL && Mnemonic != "b") {
5955     return Error(NameLoc, "conditional execution not supported in Thumb1");
5956   }
5957 
5958   Operands.push_back(ARMOperand::CreateToken(Mnemonic, NameLoc));
5959 
5960   // Handle the IT instruction ITMask. Convert it to a bitmask. This
5961   // is the mask as it will be for the IT encoding if the conditional
5962   // encoding has a '1' as it's bit0 (i.e. 't' ==> '1'). In the case
5963   // where the conditional bit0 is zero, the instruction post-processing
5964   // will adjust the mask accordingly.
5965   if (Mnemonic == "it") {
5966     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + 2);
5967     if (ITMask.size() > 3) {
5968       return Error(Loc, "too many conditions on IT instruction");
5969     }
5970     unsigned Mask = 8;
5971     for (unsigned i = ITMask.size(); i != 0; --i) {
5972       char pos = ITMask[i - 1];
5973       if (pos != 't' && pos != 'e') {
5974         return Error(Loc, "illegal IT block condition mask '" + ITMask + "'");
5975       }
5976       Mask >>= 1;
5977       if (ITMask[i - 1] == 't')
5978         Mask |= 8;
5979     }
5980     Operands.push_back(ARMOperand::CreateITMask(Mask, Loc));
5981   }
5982 
5983   // FIXME: This is all a pretty gross hack. We should automatically handle
5984   // optional operands like this via tblgen.
5985 
5986   // Next, add the CCOut and ConditionCode operands, if needed.
5987   //
5988   // For mnemonics which can ever incorporate a carry setting bit or predication
5989   // code, our matching model involves us always generating CCOut and
5990   // ConditionCode operands to match the mnemonic "as written" and then we let
5991   // the matcher deal with finding the right instruction or generating an
5992   // appropriate error.
5993   bool CanAcceptCarrySet, CanAcceptPredicationCode;
5994   getMnemonicAcceptInfo(Mnemonic, Name, CanAcceptCarrySet, CanAcceptPredicationCode);
5995 
5996   // If we had a carry-set on an instruction that can't do that, issue an
5997   // error.
5998   if (!CanAcceptCarrySet && CarrySetting) {
5999     return Error(NameLoc, "instruction '" + Mnemonic +
6000                  "' can not set flags, but 's' suffix specified");
6001   }
6002   // If we had a predication code on an instruction that can't do that, issue an
6003   // error.
6004   if (!CanAcceptPredicationCode && PredicationCode != ARMCC::AL) {
6005     return Error(NameLoc, "instruction '" + Mnemonic +
6006                  "' is not predicable, but condition code specified");
6007   }
6008 
6009   // Add the carry setting operand, if necessary.
6010   if (CanAcceptCarrySet) {
6011     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size());
6012     Operands.push_back(ARMOperand::CreateCCOut(CarrySetting ? ARM::CPSR : 0,
6013                                                Loc));
6014   }
6015 
6016   // Add the predication code operand, if necessary.
6017   if (CanAcceptPredicationCode) {
6018     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size() +
6019                                       CarrySetting);
6020     Operands.push_back(ARMOperand::CreateCondCode(
6021                          ARMCC::CondCodes(PredicationCode), Loc));
6022   }
6023 
6024   // Add the processor imod operand, if necessary.
6025   if (ProcessorIMod) {
6026     Operands.push_back(ARMOperand::CreateImm(
6027           MCConstantExpr::create(ProcessorIMod, getContext()),
6028                                  NameLoc, NameLoc));
6029   } else if (Mnemonic == "cps" && isMClass()) {
6030     return Error(NameLoc, "instruction 'cps' requires effect for M-class");
6031   }
6032 
6033   // Add the remaining tokens in the mnemonic.
6034   while (Next != StringRef::npos) {
6035     Start = Next;
6036     Next = Name.find('.', Start + 1);
6037     StringRef ExtraToken = Name.slice(Start, Next);
6038 
6039     // Some NEON instructions have an optional datatype suffix that is
6040     // completely ignored. Check for that.
6041     if (isDataTypeToken(ExtraToken) &&
6042         doesIgnoreDataTypeSuffix(Mnemonic, ExtraToken))
6043       continue;
6044 
6045     // For for ARM mode generate an error if the .n qualifier is used.
6046     if (ExtraToken == ".n" && !isThumb()) {
6047       SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Start);
6048       return Error(Loc, "instruction with .n (narrow) qualifier not allowed in "
6049                    "arm mode");
6050     }
6051 
6052     // The .n qualifier is always discarded as that is what the tables
6053     // and matcher expect.  In ARM mode the .w qualifier has no effect,
6054     // so discard it to avoid errors that can be caused by the matcher.
6055     if (ExtraToken != ".n" && (isThumb() || ExtraToken != ".w")) {
6056       SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Start);
6057       Operands.push_back(ARMOperand::CreateToken(ExtraToken, Loc));
6058     }
6059   }
6060 
6061   // Read the remaining operands.
6062   if (getLexer().isNot(AsmToken::EndOfStatement)) {
6063     // Read the first operand.
6064     if (parseOperand(Operands, Mnemonic)) {
6065       return true;
6066     }
6067 
6068     while (parseOptionalToken(AsmToken::Comma)) {
6069       // Parse and remember the operand.
6070       if (parseOperand(Operands, Mnemonic)) {
6071         return true;
6072       }
6073     }
6074   }
6075 
6076   if (parseToken(AsmToken::EndOfStatement, "unexpected token in argument list"))
6077     return true;
6078 
6079   if (RequireVFPRegisterListCheck) {
6080     ARMOperand &Op = static_cast<ARMOperand &>(*Operands.back());
6081     if (AcceptSinglePrecisionOnly && !Op.isSPRRegList())
6082       return Error(Op.getStartLoc(),
6083                    "VFP/Neon single precision register expected");
6084     if (AcceptDoublePrecisionOnly && !Op.isDPRRegList())
6085       return Error(Op.getStartLoc(),
6086                    "VFP/Neon double precision register expected");
6087   }
6088 
6089   tryConvertingToTwoOperandForm(Mnemonic, CarrySetting, Operands);
6090 
6091   // Some instructions, mostly Thumb, have forms for the same mnemonic that
6092   // do and don't have a cc_out optional-def operand. With some spot-checks
6093   // of the operand list, we can figure out which variant we're trying to
6094   // parse and adjust accordingly before actually matching. We shouldn't ever
6095   // try to remove a cc_out operand that was explicitly set on the
6096   // mnemonic, of course (CarrySetting == true). Reason number #317 the
6097   // table driven matcher doesn't fit well with the ARM instruction set.
6098   if (!CarrySetting && shouldOmitCCOutOperand(Mnemonic, Operands))
6099     Operands.erase(Operands.begin() + 1);
6100 
6101   // Some instructions have the same mnemonic, but don't always
6102   // have a predicate. Distinguish them here and delete the
6103   // predicate if needed.
6104   if (shouldOmitPredicateOperand(Mnemonic, Operands))
6105     Operands.erase(Operands.begin() + 1);
6106 
6107   // ARM mode 'blx' need special handling, as the register operand version
6108   // is predicable, but the label operand version is not. So, we can't rely
6109   // on the Mnemonic based checking to correctly figure out when to put
6110   // a k_CondCode operand in the list. If we're trying to match the label
6111   // version, remove the k_CondCode operand here.
6112   if (!isThumb() && Mnemonic == "blx" && Operands.size() == 3 &&
6113       static_cast<ARMOperand &>(*Operands[2]).isImm())
6114     Operands.erase(Operands.begin() + 1);
6115 
6116   // Adjust operands of ldrexd/strexd to MCK_GPRPair.
6117   // ldrexd/strexd require even/odd GPR pair. To enforce this constraint,
6118   // a single GPRPair reg operand is used in the .td file to replace the two
6119   // GPRs. However, when parsing from asm, the two GRPs cannot be automatically
6120   // expressed as a GPRPair, so we have to manually merge them.
6121   // FIXME: We would really like to be able to tablegen'erate this.
6122   if (!isThumb() && Operands.size() > 4 &&
6123       (Mnemonic == "ldrexd" || Mnemonic == "strexd" || Mnemonic == "ldaexd" ||
6124        Mnemonic == "stlexd")) {
6125     bool isLoad = (Mnemonic == "ldrexd" || Mnemonic == "ldaexd");
6126     unsigned Idx = isLoad ? 2 : 3;
6127     ARMOperand &Op1 = static_cast<ARMOperand &>(*Operands[Idx]);
6128     ARMOperand &Op2 = static_cast<ARMOperand &>(*Operands[Idx + 1]);
6129 
6130     const MCRegisterClass& MRC = MRI->getRegClass(ARM::GPRRegClassID);
6131     // Adjust only if Op1 and Op2 are GPRs.
6132     if (Op1.isReg() && Op2.isReg() && MRC.contains(Op1.getReg()) &&
6133         MRC.contains(Op2.getReg())) {
6134       unsigned Reg1 = Op1.getReg();
6135       unsigned Reg2 = Op2.getReg();
6136       unsigned Rt = MRI->getEncodingValue(Reg1);
6137       unsigned Rt2 = MRI->getEncodingValue(Reg2);
6138 
6139       // Rt2 must be Rt + 1 and Rt must be even.
6140       if (Rt + 1 != Rt2 || (Rt & 1)) {
6141         return Error(Op2.getStartLoc(),
6142                      isLoad ? "destination operands must be sequential"
6143                             : "source operands must be sequential");
6144       }
6145       unsigned NewReg = MRI->getMatchingSuperReg(Reg1, ARM::gsub_0,
6146           &(MRI->getRegClass(ARM::GPRPairRegClassID)));
6147       Operands[Idx] =
6148           ARMOperand::CreateReg(NewReg, Op1.getStartLoc(), Op2.getEndLoc());
6149       Operands.erase(Operands.begin() + Idx + 1);
6150     }
6151   }
6152 
6153   // GNU Assembler extension (compatibility).
6154   fixupGNULDRDAlias(Mnemonic, Operands);
6155 
6156   // FIXME: As said above, this is all a pretty gross hack.  This instruction
6157   // does not fit with other "subs" and tblgen.
6158   // Adjust operands of B9.3.19 SUBS PC, LR, #imm (Thumb2) system instruction
6159   // so the Mnemonic is the original name "subs" and delete the predicate
6160   // operand so it will match the table entry.
6161   if (isThumbTwo() && Mnemonic == "sub" && Operands.size() == 6 &&
6162       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6163       static_cast<ARMOperand &>(*Operands[3]).getReg() == ARM::PC &&
6164       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
6165       static_cast<ARMOperand &>(*Operands[4]).getReg() == ARM::LR &&
6166       static_cast<ARMOperand &>(*Operands[5]).isImm()) {
6167     Operands.front() = ARMOperand::CreateToken(Name, NameLoc);
6168     Operands.erase(Operands.begin() + 1);
6169   }
6170   return false;
6171 }
6172 
6173 // Validate context-sensitive operand constraints.
6174 
6175 // return 'true' if register list contains non-low GPR registers,
6176 // 'false' otherwise. If Reg is in the register list or is HiReg, set
6177 // 'containsReg' to true.
6178 static bool checkLowRegisterList(const MCInst &Inst, unsigned OpNo,
6179                                  unsigned Reg, unsigned HiReg,
6180                                  bool &containsReg) {
6181   containsReg = false;
6182   for (unsigned i = OpNo; i < Inst.getNumOperands(); ++i) {
6183     unsigned OpReg = Inst.getOperand(i).getReg();
6184     if (OpReg == Reg)
6185       containsReg = true;
6186     // Anything other than a low register isn't legal here.
6187     if (!isARMLowRegister(OpReg) && (!HiReg || OpReg != HiReg))
6188       return true;
6189   }
6190   return false;
6191 }
6192 
6193 // Check if the specified regisgter is in the register list of the inst,
6194 // starting at the indicated operand number.
6195 static bool listContainsReg(const MCInst &Inst, unsigned OpNo, unsigned Reg) {
6196   for (unsigned i = OpNo, e = Inst.getNumOperands(); i < e; ++i) {
6197     unsigned OpReg = Inst.getOperand(i).getReg();
6198     if (OpReg == Reg)
6199       return true;
6200   }
6201   return false;
6202 }
6203 
6204 // Return true if instruction has the interesting property of being
6205 // allowed in IT blocks, but not being predicable.
6206 static bool instIsBreakpoint(const MCInst &Inst) {
6207     return Inst.getOpcode() == ARM::tBKPT ||
6208            Inst.getOpcode() == ARM::BKPT ||
6209            Inst.getOpcode() == ARM::tHLT ||
6210            Inst.getOpcode() == ARM::HLT;
6211 }
6212 
6213 bool ARMAsmParser::validatetLDMRegList(const MCInst &Inst,
6214                                        const OperandVector &Operands,
6215                                        unsigned ListNo, bool IsARPop) {
6216   const ARMOperand &Op = static_cast<const ARMOperand &>(*Operands[ListNo]);
6217   bool HasWritebackToken = Op.isToken() && Op.getToken() == "!";
6218 
6219   bool ListContainsSP = listContainsReg(Inst, ListNo, ARM::SP);
6220   bool ListContainsLR = listContainsReg(Inst, ListNo, ARM::LR);
6221   bool ListContainsPC = listContainsReg(Inst, ListNo, ARM::PC);
6222 
6223   if (!IsARPop && ListContainsSP)
6224     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6225                  "SP may not be in the register list");
6226   else if (ListContainsPC && ListContainsLR)
6227     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6228                  "PC and LR may not be in the register list simultaneously");
6229   return false;
6230 }
6231 
6232 bool ARMAsmParser::validatetSTMRegList(const MCInst &Inst,
6233                                        const OperandVector &Operands,
6234                                        unsigned ListNo) {
6235   const ARMOperand &Op = static_cast<const ARMOperand &>(*Operands[ListNo]);
6236   bool HasWritebackToken = Op.isToken() && Op.getToken() == "!";
6237 
6238   bool ListContainsSP = listContainsReg(Inst, ListNo, ARM::SP);
6239   bool ListContainsPC = listContainsReg(Inst, ListNo, ARM::PC);
6240 
6241   if (ListContainsSP && ListContainsPC)
6242     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6243                  "SP and PC may not be in the register list");
6244   else if (ListContainsSP)
6245     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6246                  "SP may not be in the register list");
6247   else if (ListContainsPC)
6248     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6249                  "PC may not be in the register list");
6250   return false;
6251 }
6252 
6253 // FIXME: We would really like to be able to tablegen'erate this.
6254 bool ARMAsmParser::validateInstruction(MCInst &Inst,
6255                                        const OperandVector &Operands) {
6256   const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
6257   SMLoc Loc = Operands[0]->getStartLoc();
6258 
6259   // Check the IT block state first.
6260   // NOTE: BKPT and HLT instructions have the interesting property of being
6261   // allowed in IT blocks, but not being predicable. They just always execute.
6262   if (inITBlock() && !instIsBreakpoint(Inst)) {
6263     // The instruction must be predicable.
6264     if (!MCID.isPredicable())
6265       return Error(Loc, "instructions in IT block must be predicable");
6266     unsigned Cond = 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(ARMCC::CondCodes(Cond))) +
6275                    "', but expected '" +
6276                    ARMCondCodeToString(ARMCC::CondCodes(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     if (hasRAS()) {
6633       // ESB is not predicable (pred must be AL)
6634       unsigned Imm8 = Inst.getOperand(0).getImm();
6635       unsigned Pred = Inst.getOperand(1).getImm();
6636       if (Imm8 == 0x10 && Pred != ARMCC::AL)
6637         return Error(Operands[1]->getStartLoc(), "instruction 'esb' is not "
6638                                                  "predicable, but condition "
6639                                                  "code specified");
6640     }
6641     // Without the RAS extension, this behaves as any other unallocated hint.
6642     break;
6643   }
6644 
6645   return false;
6646 }
6647 
6648 static unsigned getRealVSTOpcode(unsigned Opc, unsigned &Spacing) {
6649   switch(Opc) {
6650   default: llvm_unreachable("unexpected opcode!");
6651   // VST1LN
6652   case ARM::VST1LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST1LNd8_UPD;
6653   case ARM::VST1LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST1LNd16_UPD;
6654   case ARM::VST1LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST1LNd32_UPD;
6655   case ARM::VST1LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST1LNd8_UPD;
6656   case ARM::VST1LNdWB_register_Asm_16: Spacing = 1; return ARM::VST1LNd16_UPD;
6657   case ARM::VST1LNdWB_register_Asm_32: Spacing = 1; return ARM::VST1LNd32_UPD;
6658   case ARM::VST1LNdAsm_8:  Spacing = 1; return ARM::VST1LNd8;
6659   case ARM::VST1LNdAsm_16: Spacing = 1; return ARM::VST1LNd16;
6660   case ARM::VST1LNdAsm_32: Spacing = 1; return ARM::VST1LNd32;
6661 
6662   // VST2LN
6663   case ARM::VST2LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST2LNd8_UPD;
6664   case ARM::VST2LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST2LNd16_UPD;
6665   case ARM::VST2LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST2LNd32_UPD;
6666   case ARM::VST2LNqWB_fixed_Asm_16: Spacing = 2; return ARM::VST2LNq16_UPD;
6667   case ARM::VST2LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST2LNq32_UPD;
6668 
6669   case ARM::VST2LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST2LNd8_UPD;
6670   case ARM::VST2LNdWB_register_Asm_16: Spacing = 1; return ARM::VST2LNd16_UPD;
6671   case ARM::VST2LNdWB_register_Asm_32: Spacing = 1; return ARM::VST2LNd32_UPD;
6672   case ARM::VST2LNqWB_register_Asm_16: Spacing = 2; return ARM::VST2LNq16_UPD;
6673   case ARM::VST2LNqWB_register_Asm_32: Spacing = 2; return ARM::VST2LNq32_UPD;
6674 
6675   case ARM::VST2LNdAsm_8:  Spacing = 1; return ARM::VST2LNd8;
6676   case ARM::VST2LNdAsm_16: Spacing = 1; return ARM::VST2LNd16;
6677   case ARM::VST2LNdAsm_32: Spacing = 1; return ARM::VST2LNd32;
6678   case ARM::VST2LNqAsm_16: Spacing = 2; return ARM::VST2LNq16;
6679   case ARM::VST2LNqAsm_32: Spacing = 2; return ARM::VST2LNq32;
6680 
6681   // VST3LN
6682   case ARM::VST3LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST3LNd8_UPD;
6683   case ARM::VST3LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST3LNd16_UPD;
6684   case ARM::VST3LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST3LNd32_UPD;
6685   case ARM::VST3LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VST3LNq16_UPD;
6686   case ARM::VST3LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST3LNq32_UPD;
6687   case ARM::VST3LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST3LNd8_UPD;
6688   case ARM::VST3LNdWB_register_Asm_16: Spacing = 1; return ARM::VST3LNd16_UPD;
6689   case ARM::VST3LNdWB_register_Asm_32: Spacing = 1; return ARM::VST3LNd32_UPD;
6690   case ARM::VST3LNqWB_register_Asm_16: Spacing = 2; return ARM::VST3LNq16_UPD;
6691   case ARM::VST3LNqWB_register_Asm_32: Spacing = 2; return ARM::VST3LNq32_UPD;
6692   case ARM::VST3LNdAsm_8:  Spacing = 1; return ARM::VST3LNd8;
6693   case ARM::VST3LNdAsm_16: Spacing = 1; return ARM::VST3LNd16;
6694   case ARM::VST3LNdAsm_32: Spacing = 1; return ARM::VST3LNd32;
6695   case ARM::VST3LNqAsm_16: Spacing = 2; return ARM::VST3LNq16;
6696   case ARM::VST3LNqAsm_32: Spacing = 2; return ARM::VST3LNq32;
6697 
6698   // VST3
6699   case ARM::VST3dWB_fixed_Asm_8:  Spacing = 1; return ARM::VST3d8_UPD;
6700   case ARM::VST3dWB_fixed_Asm_16: Spacing = 1; return ARM::VST3d16_UPD;
6701   case ARM::VST3dWB_fixed_Asm_32: Spacing = 1; return ARM::VST3d32_UPD;
6702   case ARM::VST3qWB_fixed_Asm_8:  Spacing = 2; return ARM::VST3q8_UPD;
6703   case ARM::VST3qWB_fixed_Asm_16: Spacing = 2; return ARM::VST3q16_UPD;
6704   case ARM::VST3qWB_fixed_Asm_32: Spacing = 2; return ARM::VST3q32_UPD;
6705   case ARM::VST3dWB_register_Asm_8:  Spacing = 1; return ARM::VST3d8_UPD;
6706   case ARM::VST3dWB_register_Asm_16: Spacing = 1; return ARM::VST3d16_UPD;
6707   case ARM::VST3dWB_register_Asm_32: Spacing = 1; return ARM::VST3d32_UPD;
6708   case ARM::VST3qWB_register_Asm_8:  Spacing = 2; return ARM::VST3q8_UPD;
6709   case ARM::VST3qWB_register_Asm_16: Spacing = 2; return ARM::VST3q16_UPD;
6710   case ARM::VST3qWB_register_Asm_32: Spacing = 2; return ARM::VST3q32_UPD;
6711   case ARM::VST3dAsm_8:  Spacing = 1; return ARM::VST3d8;
6712   case ARM::VST3dAsm_16: Spacing = 1; return ARM::VST3d16;
6713   case ARM::VST3dAsm_32: Spacing = 1; return ARM::VST3d32;
6714   case ARM::VST3qAsm_8:  Spacing = 2; return ARM::VST3q8;
6715   case ARM::VST3qAsm_16: Spacing = 2; return ARM::VST3q16;
6716   case ARM::VST3qAsm_32: Spacing = 2; return ARM::VST3q32;
6717 
6718   // VST4LN
6719   case ARM::VST4LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST4LNd8_UPD;
6720   case ARM::VST4LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST4LNd16_UPD;
6721   case ARM::VST4LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST4LNd32_UPD;
6722   case ARM::VST4LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VST4LNq16_UPD;
6723   case ARM::VST4LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST4LNq32_UPD;
6724   case ARM::VST4LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST4LNd8_UPD;
6725   case ARM::VST4LNdWB_register_Asm_16: Spacing = 1; return ARM::VST4LNd16_UPD;
6726   case ARM::VST4LNdWB_register_Asm_32: Spacing = 1; return ARM::VST4LNd32_UPD;
6727   case ARM::VST4LNqWB_register_Asm_16: Spacing = 2; return ARM::VST4LNq16_UPD;
6728   case ARM::VST4LNqWB_register_Asm_32: Spacing = 2; return ARM::VST4LNq32_UPD;
6729   case ARM::VST4LNdAsm_8:  Spacing = 1; return ARM::VST4LNd8;
6730   case ARM::VST4LNdAsm_16: Spacing = 1; return ARM::VST4LNd16;
6731   case ARM::VST4LNdAsm_32: Spacing = 1; return ARM::VST4LNd32;
6732   case ARM::VST4LNqAsm_16: Spacing = 2; return ARM::VST4LNq16;
6733   case ARM::VST4LNqAsm_32: Spacing = 2; return ARM::VST4LNq32;
6734 
6735   // VST4
6736   case ARM::VST4dWB_fixed_Asm_8:  Spacing = 1; return ARM::VST4d8_UPD;
6737   case ARM::VST4dWB_fixed_Asm_16: Spacing = 1; return ARM::VST4d16_UPD;
6738   case ARM::VST4dWB_fixed_Asm_32: Spacing = 1; return ARM::VST4d32_UPD;
6739   case ARM::VST4qWB_fixed_Asm_8:  Spacing = 2; return ARM::VST4q8_UPD;
6740   case ARM::VST4qWB_fixed_Asm_16: Spacing = 2; return ARM::VST4q16_UPD;
6741   case ARM::VST4qWB_fixed_Asm_32: Spacing = 2; return ARM::VST4q32_UPD;
6742   case ARM::VST4dWB_register_Asm_8:  Spacing = 1; return ARM::VST4d8_UPD;
6743   case ARM::VST4dWB_register_Asm_16: Spacing = 1; return ARM::VST4d16_UPD;
6744   case ARM::VST4dWB_register_Asm_32: Spacing = 1; return ARM::VST4d32_UPD;
6745   case ARM::VST4qWB_register_Asm_8:  Spacing = 2; return ARM::VST4q8_UPD;
6746   case ARM::VST4qWB_register_Asm_16: Spacing = 2; return ARM::VST4q16_UPD;
6747   case ARM::VST4qWB_register_Asm_32: Spacing = 2; return ARM::VST4q32_UPD;
6748   case ARM::VST4dAsm_8:  Spacing = 1; return ARM::VST4d8;
6749   case ARM::VST4dAsm_16: Spacing = 1; return ARM::VST4d16;
6750   case ARM::VST4dAsm_32: Spacing = 1; return ARM::VST4d32;
6751   case ARM::VST4qAsm_8:  Spacing = 2; return ARM::VST4q8;
6752   case ARM::VST4qAsm_16: Spacing = 2; return ARM::VST4q16;
6753   case ARM::VST4qAsm_32: Spacing = 2; return ARM::VST4q32;
6754   }
6755 }
6756 
6757 static unsigned getRealVLDOpcode(unsigned Opc, unsigned &Spacing) {
6758   switch(Opc) {
6759   default: llvm_unreachable("unexpected opcode!");
6760   // VLD1LN
6761   case ARM::VLD1LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD1LNd8_UPD;
6762   case ARM::VLD1LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD1LNd16_UPD;
6763   case ARM::VLD1LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD1LNd32_UPD;
6764   case ARM::VLD1LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD1LNd8_UPD;
6765   case ARM::VLD1LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD1LNd16_UPD;
6766   case ARM::VLD1LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD1LNd32_UPD;
6767   case ARM::VLD1LNdAsm_8:  Spacing = 1; return ARM::VLD1LNd8;
6768   case ARM::VLD1LNdAsm_16: Spacing = 1; return ARM::VLD1LNd16;
6769   case ARM::VLD1LNdAsm_32: Spacing = 1; return ARM::VLD1LNd32;
6770 
6771   // VLD2LN
6772   case ARM::VLD2LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD2LNd8_UPD;
6773   case ARM::VLD2LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD2LNd16_UPD;
6774   case ARM::VLD2LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD2LNd32_UPD;
6775   case ARM::VLD2LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD2LNq16_UPD;
6776   case ARM::VLD2LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD2LNq32_UPD;
6777   case ARM::VLD2LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD2LNd8_UPD;
6778   case ARM::VLD2LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD2LNd16_UPD;
6779   case ARM::VLD2LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD2LNd32_UPD;
6780   case ARM::VLD2LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD2LNq16_UPD;
6781   case ARM::VLD2LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD2LNq32_UPD;
6782   case ARM::VLD2LNdAsm_8:  Spacing = 1; return ARM::VLD2LNd8;
6783   case ARM::VLD2LNdAsm_16: Spacing = 1; return ARM::VLD2LNd16;
6784   case ARM::VLD2LNdAsm_32: Spacing = 1; return ARM::VLD2LNd32;
6785   case ARM::VLD2LNqAsm_16: Spacing = 2; return ARM::VLD2LNq16;
6786   case ARM::VLD2LNqAsm_32: Spacing = 2; return ARM::VLD2LNq32;
6787 
6788   // VLD3DUP
6789   case ARM::VLD3DUPdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3DUPd8_UPD;
6790   case ARM::VLD3DUPdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3DUPd16_UPD;
6791   case ARM::VLD3DUPdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3DUPd32_UPD;
6792   case ARM::VLD3DUPqWB_fixed_Asm_8: Spacing = 1; return ARM::VLD3DUPq8_UPD;
6793   case ARM::VLD3DUPqWB_fixed_Asm_16: Spacing = 2; return ARM::VLD3DUPq16_UPD;
6794   case ARM::VLD3DUPqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3DUPq32_UPD;
6795   case ARM::VLD3DUPdWB_register_Asm_8:  Spacing = 1; return ARM::VLD3DUPd8_UPD;
6796   case ARM::VLD3DUPdWB_register_Asm_16: Spacing = 1; return ARM::VLD3DUPd16_UPD;
6797   case ARM::VLD3DUPdWB_register_Asm_32: Spacing = 1; return ARM::VLD3DUPd32_UPD;
6798   case ARM::VLD3DUPqWB_register_Asm_8: Spacing = 2; return ARM::VLD3DUPq8_UPD;
6799   case ARM::VLD3DUPqWB_register_Asm_16: Spacing = 2; return ARM::VLD3DUPq16_UPD;
6800   case ARM::VLD3DUPqWB_register_Asm_32: Spacing = 2; return ARM::VLD3DUPq32_UPD;
6801   case ARM::VLD3DUPdAsm_8:  Spacing = 1; return ARM::VLD3DUPd8;
6802   case ARM::VLD3DUPdAsm_16: Spacing = 1; return ARM::VLD3DUPd16;
6803   case ARM::VLD3DUPdAsm_32: Spacing = 1; return ARM::VLD3DUPd32;
6804   case ARM::VLD3DUPqAsm_8: Spacing = 2; return ARM::VLD3DUPq8;
6805   case ARM::VLD3DUPqAsm_16: Spacing = 2; return ARM::VLD3DUPq16;
6806   case ARM::VLD3DUPqAsm_32: Spacing = 2; return ARM::VLD3DUPq32;
6807 
6808   // VLD3LN
6809   case ARM::VLD3LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3LNd8_UPD;
6810   case ARM::VLD3LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3LNd16_UPD;
6811   case ARM::VLD3LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3LNd32_UPD;
6812   case ARM::VLD3LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3LNq16_UPD;
6813   case ARM::VLD3LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3LNq32_UPD;
6814   case ARM::VLD3LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD3LNd8_UPD;
6815   case ARM::VLD3LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD3LNd16_UPD;
6816   case ARM::VLD3LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD3LNd32_UPD;
6817   case ARM::VLD3LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD3LNq16_UPD;
6818   case ARM::VLD3LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD3LNq32_UPD;
6819   case ARM::VLD3LNdAsm_8:  Spacing = 1; return ARM::VLD3LNd8;
6820   case ARM::VLD3LNdAsm_16: Spacing = 1; return ARM::VLD3LNd16;
6821   case ARM::VLD3LNdAsm_32: Spacing = 1; return ARM::VLD3LNd32;
6822   case ARM::VLD3LNqAsm_16: Spacing = 2; return ARM::VLD3LNq16;
6823   case ARM::VLD3LNqAsm_32: Spacing = 2; return ARM::VLD3LNq32;
6824 
6825   // VLD3
6826   case ARM::VLD3dWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3d8_UPD;
6827   case ARM::VLD3dWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3d16_UPD;
6828   case ARM::VLD3dWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3d32_UPD;
6829   case ARM::VLD3qWB_fixed_Asm_8:  Spacing = 2; return ARM::VLD3q8_UPD;
6830   case ARM::VLD3qWB_fixed_Asm_16: Spacing = 2; return ARM::VLD3q16_UPD;
6831   case ARM::VLD3qWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3q32_UPD;
6832   case ARM::VLD3dWB_register_Asm_8:  Spacing = 1; return ARM::VLD3d8_UPD;
6833   case ARM::VLD3dWB_register_Asm_16: Spacing = 1; return ARM::VLD3d16_UPD;
6834   case ARM::VLD3dWB_register_Asm_32: Spacing = 1; return ARM::VLD3d32_UPD;
6835   case ARM::VLD3qWB_register_Asm_8:  Spacing = 2; return ARM::VLD3q8_UPD;
6836   case ARM::VLD3qWB_register_Asm_16: Spacing = 2; return ARM::VLD3q16_UPD;
6837   case ARM::VLD3qWB_register_Asm_32: Spacing = 2; return ARM::VLD3q32_UPD;
6838   case ARM::VLD3dAsm_8:  Spacing = 1; return ARM::VLD3d8;
6839   case ARM::VLD3dAsm_16: Spacing = 1; return ARM::VLD3d16;
6840   case ARM::VLD3dAsm_32: Spacing = 1; return ARM::VLD3d32;
6841   case ARM::VLD3qAsm_8:  Spacing = 2; return ARM::VLD3q8;
6842   case ARM::VLD3qAsm_16: Spacing = 2; return ARM::VLD3q16;
6843   case ARM::VLD3qAsm_32: Spacing = 2; return ARM::VLD3q32;
6844 
6845   // VLD4LN
6846   case ARM::VLD4LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4LNd8_UPD;
6847   case ARM::VLD4LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4LNd16_UPD;
6848   case ARM::VLD4LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4LNd32_UPD;
6849   case ARM::VLD4LNqWB_fixed_Asm_16: Spacing = 2; return ARM::VLD4LNq16_UPD;
6850   case ARM::VLD4LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4LNq32_UPD;
6851   case ARM::VLD4LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD4LNd8_UPD;
6852   case ARM::VLD4LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD4LNd16_UPD;
6853   case ARM::VLD4LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD4LNd32_UPD;
6854   case ARM::VLD4LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD4LNq16_UPD;
6855   case ARM::VLD4LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD4LNq32_UPD;
6856   case ARM::VLD4LNdAsm_8:  Spacing = 1; return ARM::VLD4LNd8;
6857   case ARM::VLD4LNdAsm_16: Spacing = 1; return ARM::VLD4LNd16;
6858   case ARM::VLD4LNdAsm_32: Spacing = 1; return ARM::VLD4LNd32;
6859   case ARM::VLD4LNqAsm_16: Spacing = 2; return ARM::VLD4LNq16;
6860   case ARM::VLD4LNqAsm_32: Spacing = 2; return ARM::VLD4LNq32;
6861 
6862   // VLD4DUP
6863   case ARM::VLD4DUPdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4DUPd8_UPD;
6864   case ARM::VLD4DUPdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4DUPd16_UPD;
6865   case ARM::VLD4DUPdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4DUPd32_UPD;
6866   case ARM::VLD4DUPqWB_fixed_Asm_8: Spacing = 1; return ARM::VLD4DUPq8_UPD;
6867   case ARM::VLD4DUPqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4DUPq16_UPD;
6868   case ARM::VLD4DUPqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4DUPq32_UPD;
6869   case ARM::VLD4DUPdWB_register_Asm_8:  Spacing = 1; return ARM::VLD4DUPd8_UPD;
6870   case ARM::VLD4DUPdWB_register_Asm_16: Spacing = 1; return ARM::VLD4DUPd16_UPD;
6871   case ARM::VLD4DUPdWB_register_Asm_32: Spacing = 1; return ARM::VLD4DUPd32_UPD;
6872   case ARM::VLD4DUPqWB_register_Asm_8: Spacing = 2; return ARM::VLD4DUPq8_UPD;
6873   case ARM::VLD4DUPqWB_register_Asm_16: Spacing = 2; return ARM::VLD4DUPq16_UPD;
6874   case ARM::VLD4DUPqWB_register_Asm_32: Spacing = 2; return ARM::VLD4DUPq32_UPD;
6875   case ARM::VLD4DUPdAsm_8:  Spacing = 1; return ARM::VLD4DUPd8;
6876   case ARM::VLD4DUPdAsm_16: Spacing = 1; return ARM::VLD4DUPd16;
6877   case ARM::VLD4DUPdAsm_32: Spacing = 1; return ARM::VLD4DUPd32;
6878   case ARM::VLD4DUPqAsm_8: Spacing = 2; return ARM::VLD4DUPq8;
6879   case ARM::VLD4DUPqAsm_16: Spacing = 2; return ARM::VLD4DUPq16;
6880   case ARM::VLD4DUPqAsm_32: Spacing = 2; return ARM::VLD4DUPq32;
6881 
6882   // VLD4
6883   case ARM::VLD4dWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4d8_UPD;
6884   case ARM::VLD4dWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4d16_UPD;
6885   case ARM::VLD4dWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4d32_UPD;
6886   case ARM::VLD4qWB_fixed_Asm_8:  Spacing = 2; return ARM::VLD4q8_UPD;
6887   case ARM::VLD4qWB_fixed_Asm_16: Spacing = 2; return ARM::VLD4q16_UPD;
6888   case ARM::VLD4qWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4q32_UPD;
6889   case ARM::VLD4dWB_register_Asm_8:  Spacing = 1; return ARM::VLD4d8_UPD;
6890   case ARM::VLD4dWB_register_Asm_16: Spacing = 1; return ARM::VLD4d16_UPD;
6891   case ARM::VLD4dWB_register_Asm_32: Spacing = 1; return ARM::VLD4d32_UPD;
6892   case ARM::VLD4qWB_register_Asm_8:  Spacing = 2; return ARM::VLD4q8_UPD;
6893   case ARM::VLD4qWB_register_Asm_16: Spacing = 2; return ARM::VLD4q16_UPD;
6894   case ARM::VLD4qWB_register_Asm_32: Spacing = 2; return ARM::VLD4q32_UPD;
6895   case ARM::VLD4dAsm_8:  Spacing = 1; return ARM::VLD4d8;
6896   case ARM::VLD4dAsm_16: Spacing = 1; return ARM::VLD4d16;
6897   case ARM::VLD4dAsm_32: Spacing = 1; return ARM::VLD4d32;
6898   case ARM::VLD4qAsm_8:  Spacing = 2; return ARM::VLD4q8;
6899   case ARM::VLD4qAsm_16: Spacing = 2; return ARM::VLD4q16;
6900   case ARM::VLD4qAsm_32: Spacing = 2; return ARM::VLD4q32;
6901   }
6902 }
6903 
6904 bool ARMAsmParser::processInstruction(MCInst &Inst,
6905                                       const OperandVector &Operands,
6906                                       MCStreamer &Out) {
6907   // Check if we have the wide qualifier, because if it's present we
6908   // must avoid selecting a 16-bit thumb instruction.
6909   bool HasWideQualifier = false;
6910   for (auto &Op : Operands) {
6911     ARMOperand &ARMOp = static_cast<ARMOperand&>(*Op);
6912     if (ARMOp.isToken() && ARMOp.getToken() == ".w") {
6913       HasWideQualifier = true;
6914       break;
6915     }
6916   }
6917 
6918   switch (Inst.getOpcode()) {
6919   // Alias for alternate form of 'ldr{,b}t Rt, [Rn], #imm' instruction.
6920   case ARM::LDRT_POST:
6921   case ARM::LDRBT_POST: {
6922     const unsigned Opcode =
6923       (Inst.getOpcode() == ARM::LDRT_POST) ? ARM::LDRT_POST_IMM
6924                                            : ARM::LDRBT_POST_IMM;
6925     MCInst TmpInst;
6926     TmpInst.setOpcode(Opcode);
6927     TmpInst.addOperand(Inst.getOperand(0));
6928     TmpInst.addOperand(Inst.getOperand(1));
6929     TmpInst.addOperand(Inst.getOperand(1));
6930     TmpInst.addOperand(MCOperand::createReg(0));
6931     TmpInst.addOperand(MCOperand::createImm(0));
6932     TmpInst.addOperand(Inst.getOperand(2));
6933     TmpInst.addOperand(Inst.getOperand(3));
6934     Inst = TmpInst;
6935     return true;
6936   }
6937   // Alias for alternate form of 'str{,b}t Rt, [Rn], #imm' instruction.
6938   case ARM::STRT_POST:
6939   case ARM::STRBT_POST: {
6940     const unsigned Opcode =
6941       (Inst.getOpcode() == ARM::STRT_POST) ? ARM::STRT_POST_IMM
6942                                            : ARM::STRBT_POST_IMM;
6943     MCInst TmpInst;
6944     TmpInst.setOpcode(Opcode);
6945     TmpInst.addOperand(Inst.getOperand(1));
6946     TmpInst.addOperand(Inst.getOperand(0));
6947     TmpInst.addOperand(Inst.getOperand(1));
6948     TmpInst.addOperand(MCOperand::createReg(0));
6949     TmpInst.addOperand(MCOperand::createImm(0));
6950     TmpInst.addOperand(Inst.getOperand(2));
6951     TmpInst.addOperand(Inst.getOperand(3));
6952     Inst = TmpInst;
6953     return true;
6954   }
6955   // Alias for alternate form of 'ADR Rd, #imm' instruction.
6956   case ARM::ADDri: {
6957     if (Inst.getOperand(1).getReg() != ARM::PC ||
6958         Inst.getOperand(5).getReg() != 0 ||
6959         !(Inst.getOperand(2).isExpr() || Inst.getOperand(2).isImm()))
6960       return false;
6961     MCInst TmpInst;
6962     TmpInst.setOpcode(ARM::ADR);
6963     TmpInst.addOperand(Inst.getOperand(0));
6964     if (Inst.getOperand(2).isImm()) {
6965       // Immediate (mod_imm) will be in its encoded form, we must unencode it
6966       // before passing it to the ADR instruction.
6967       unsigned Enc = Inst.getOperand(2).getImm();
6968       TmpInst.addOperand(MCOperand::createImm(
6969         ARM_AM::rotr32(Enc & 0xFF, (Enc & 0xF00) >> 7)));
6970     } else {
6971       // Turn PC-relative expression into absolute expression.
6972       // Reading PC provides the start of the current instruction + 8 and
6973       // the transform to adr is biased by that.
6974       MCSymbol *Dot = getContext().createTempSymbol();
6975       Out.EmitLabel(Dot);
6976       const MCExpr *OpExpr = Inst.getOperand(2).getExpr();
6977       const MCExpr *InstPC = MCSymbolRefExpr::create(Dot,
6978                                                      MCSymbolRefExpr::VK_None,
6979                                                      getContext());
6980       const MCExpr *Const8 = MCConstantExpr::create(8, getContext());
6981       const MCExpr *ReadPC = MCBinaryExpr::createAdd(InstPC, Const8,
6982                                                      getContext());
6983       const MCExpr *FixupAddr = MCBinaryExpr::createAdd(ReadPC, OpExpr,
6984                                                         getContext());
6985       TmpInst.addOperand(MCOperand::createExpr(FixupAddr));
6986     }
6987     TmpInst.addOperand(Inst.getOperand(3));
6988     TmpInst.addOperand(Inst.getOperand(4));
6989     Inst = TmpInst;
6990     return true;
6991   }
6992   // Aliases for alternate PC+imm syntax of LDR instructions.
6993   case ARM::t2LDRpcrel:
6994     // Select the narrow version if the immediate will fit.
6995     if (Inst.getOperand(1).getImm() > 0 &&
6996         Inst.getOperand(1).getImm() <= 0xff &&
6997         !HasWideQualifier)
6998       Inst.setOpcode(ARM::tLDRpci);
6999     else
7000       Inst.setOpcode(ARM::t2LDRpci);
7001     return true;
7002   case ARM::t2LDRBpcrel:
7003     Inst.setOpcode(ARM::t2LDRBpci);
7004     return true;
7005   case ARM::t2LDRHpcrel:
7006     Inst.setOpcode(ARM::t2LDRHpci);
7007     return true;
7008   case ARM::t2LDRSBpcrel:
7009     Inst.setOpcode(ARM::t2LDRSBpci);
7010     return true;
7011   case ARM::t2LDRSHpcrel:
7012     Inst.setOpcode(ARM::t2LDRSHpci);
7013     return true;
7014   case ARM::LDRConstPool:
7015   case ARM::tLDRConstPool:
7016   case ARM::t2LDRConstPool: {
7017     // Pseudo instruction ldr rt, =immediate is converted to a
7018     // MOV rt, immediate if immediate is known and representable
7019     // otherwise we create a constant pool entry that we load from.
7020     MCInst TmpInst;
7021     if (Inst.getOpcode() == ARM::LDRConstPool)
7022       TmpInst.setOpcode(ARM::LDRi12);
7023     else if (Inst.getOpcode() == ARM::tLDRConstPool)
7024       TmpInst.setOpcode(ARM::tLDRpci);
7025     else if (Inst.getOpcode() == ARM::t2LDRConstPool)
7026       TmpInst.setOpcode(ARM::t2LDRpci);
7027     const ARMOperand &PoolOperand =
7028       (HasWideQualifier ?
7029        static_cast<ARMOperand &>(*Operands[4]) :
7030        static_cast<ARMOperand &>(*Operands[3]));
7031     const MCExpr *SubExprVal = PoolOperand.getConstantPoolImm();
7032     // If SubExprVal is a constant we may be able to use a MOV
7033     if (isa<MCConstantExpr>(SubExprVal) &&
7034         Inst.getOperand(0).getReg() != ARM::PC &&
7035         Inst.getOperand(0).getReg() != ARM::SP) {
7036       int64_t Value =
7037         (int64_t) (cast<MCConstantExpr>(SubExprVal))->getValue();
7038       bool UseMov  = true;
7039       bool MovHasS = true;
7040       if (Inst.getOpcode() == ARM::LDRConstPool) {
7041         // ARM Constant
7042         if (ARM_AM::getSOImmVal(Value) != -1) {
7043           Value = ARM_AM::getSOImmVal(Value);
7044           TmpInst.setOpcode(ARM::MOVi);
7045         }
7046         else if (ARM_AM::getSOImmVal(~Value) != -1) {
7047           Value = ARM_AM::getSOImmVal(~Value);
7048           TmpInst.setOpcode(ARM::MVNi);
7049         }
7050         else if (hasV6T2Ops() &&
7051                  Value >=0 && Value < 65536) {
7052           TmpInst.setOpcode(ARM::MOVi16);
7053           MovHasS = false;
7054         }
7055         else
7056           UseMov = false;
7057       }
7058       else {
7059         // Thumb/Thumb2 Constant
7060         if (hasThumb2() &&
7061             ARM_AM::getT2SOImmVal(Value) != -1)
7062           TmpInst.setOpcode(ARM::t2MOVi);
7063         else if (hasThumb2() &&
7064                  ARM_AM::getT2SOImmVal(~Value) != -1) {
7065           TmpInst.setOpcode(ARM::t2MVNi);
7066           Value = ~Value;
7067         }
7068         else if (hasV8MBaseline() &&
7069                  Value >=0 && Value < 65536) {
7070           TmpInst.setOpcode(ARM::t2MOVi16);
7071           MovHasS = false;
7072         }
7073         else
7074           UseMov = false;
7075       }
7076       if (UseMov) {
7077         TmpInst.addOperand(Inst.getOperand(0));           // Rt
7078         TmpInst.addOperand(MCOperand::createImm(Value));  // Immediate
7079         TmpInst.addOperand(Inst.getOperand(2));           // CondCode
7080         TmpInst.addOperand(Inst.getOperand(3));           // CondCode
7081         if (MovHasS)
7082           TmpInst.addOperand(MCOperand::createReg(0));    // S
7083         Inst = TmpInst;
7084         return true;
7085       }
7086     }
7087     // No opportunity to use MOV/MVN create constant pool
7088     const MCExpr *CPLoc =
7089       getTargetStreamer().addConstantPoolEntry(SubExprVal,
7090                                                PoolOperand.getStartLoc());
7091     TmpInst.addOperand(Inst.getOperand(0));           // Rt
7092     TmpInst.addOperand(MCOperand::createExpr(CPLoc)); // offset to constpool
7093     if (TmpInst.getOpcode() == ARM::LDRi12)
7094       TmpInst.addOperand(MCOperand::createImm(0));    // unused offset
7095     TmpInst.addOperand(Inst.getOperand(2));           // CondCode
7096     TmpInst.addOperand(Inst.getOperand(3));           // CondCode
7097     Inst = TmpInst;
7098     return true;
7099   }
7100   // Handle NEON VST complex aliases.
7101   case ARM::VST1LNdWB_register_Asm_8:
7102   case ARM::VST1LNdWB_register_Asm_16:
7103   case ARM::VST1LNdWB_register_Asm_32: {
7104     MCInst TmpInst;
7105     // Shuffle the operands around so the lane index operand is in the
7106     // right place.
7107     unsigned Spacing;
7108     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7109     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7110     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7111     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7112     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7113     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7114     TmpInst.addOperand(Inst.getOperand(1)); // lane
7115     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7116     TmpInst.addOperand(Inst.getOperand(6));
7117     Inst = TmpInst;
7118     return true;
7119   }
7120 
7121   case ARM::VST2LNdWB_register_Asm_8:
7122   case ARM::VST2LNdWB_register_Asm_16:
7123   case ARM::VST2LNdWB_register_Asm_32:
7124   case ARM::VST2LNqWB_register_Asm_16:
7125   case ARM::VST2LNqWB_register_Asm_32: {
7126     MCInst TmpInst;
7127     // Shuffle the operands around so the lane index operand is in the
7128     // right place.
7129     unsigned Spacing;
7130     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7131     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7132     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7133     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7134     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7135     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7136     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7137                                             Spacing));
7138     TmpInst.addOperand(Inst.getOperand(1)); // lane
7139     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7140     TmpInst.addOperand(Inst.getOperand(6));
7141     Inst = TmpInst;
7142     return true;
7143   }
7144 
7145   case ARM::VST3LNdWB_register_Asm_8:
7146   case ARM::VST3LNdWB_register_Asm_16:
7147   case ARM::VST3LNdWB_register_Asm_32:
7148   case ARM::VST3LNqWB_register_Asm_16:
7149   case ARM::VST3LNqWB_register_Asm_32: {
7150     MCInst TmpInst;
7151     // Shuffle the operands around so the lane index operand is in the
7152     // right place.
7153     unsigned Spacing;
7154     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7155     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7156     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7157     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7158     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7159     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7160     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7161                                             Spacing));
7162     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7163                                             Spacing * 2));
7164     TmpInst.addOperand(Inst.getOperand(1)); // lane
7165     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7166     TmpInst.addOperand(Inst.getOperand(6));
7167     Inst = TmpInst;
7168     return true;
7169   }
7170 
7171   case ARM::VST4LNdWB_register_Asm_8:
7172   case ARM::VST4LNdWB_register_Asm_16:
7173   case ARM::VST4LNdWB_register_Asm_32:
7174   case ARM::VST4LNqWB_register_Asm_16:
7175   case ARM::VST4LNqWB_register_Asm_32: {
7176     MCInst TmpInst;
7177     // Shuffle the operands around so the lane index operand is in the
7178     // right place.
7179     unsigned Spacing;
7180     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7181     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7182     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7183     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7184     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7185     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7186     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7187                                             Spacing));
7188     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7189                                             Spacing * 2));
7190     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7191                                             Spacing * 3));
7192     TmpInst.addOperand(Inst.getOperand(1)); // lane
7193     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7194     TmpInst.addOperand(Inst.getOperand(6));
7195     Inst = TmpInst;
7196     return true;
7197   }
7198 
7199   case ARM::VST1LNdWB_fixed_Asm_8:
7200   case ARM::VST1LNdWB_fixed_Asm_16:
7201   case ARM::VST1LNdWB_fixed_Asm_32: {
7202     MCInst TmpInst;
7203     // Shuffle the operands around so the lane index operand is in the
7204     // right place.
7205     unsigned Spacing;
7206     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7207     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7208     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7209     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7210     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7211     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7212     TmpInst.addOperand(Inst.getOperand(1)); // lane
7213     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7214     TmpInst.addOperand(Inst.getOperand(5));
7215     Inst = TmpInst;
7216     return true;
7217   }
7218 
7219   case ARM::VST2LNdWB_fixed_Asm_8:
7220   case ARM::VST2LNdWB_fixed_Asm_16:
7221   case ARM::VST2LNdWB_fixed_Asm_32:
7222   case ARM::VST2LNqWB_fixed_Asm_16:
7223   case ARM::VST2LNqWB_fixed_Asm_32: {
7224     MCInst TmpInst;
7225     // Shuffle the operands around so the lane index operand is in the
7226     // right place.
7227     unsigned Spacing;
7228     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7229     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7230     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7231     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7232     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7233     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7234     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7235                                             Spacing));
7236     TmpInst.addOperand(Inst.getOperand(1)); // lane
7237     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7238     TmpInst.addOperand(Inst.getOperand(5));
7239     Inst = TmpInst;
7240     return true;
7241   }
7242 
7243   case ARM::VST3LNdWB_fixed_Asm_8:
7244   case ARM::VST3LNdWB_fixed_Asm_16:
7245   case ARM::VST3LNdWB_fixed_Asm_32:
7246   case ARM::VST3LNqWB_fixed_Asm_16:
7247   case ARM::VST3LNqWB_fixed_Asm_32: {
7248     MCInst TmpInst;
7249     // Shuffle the operands around so the lane index operand is in the
7250     // right place.
7251     unsigned Spacing;
7252     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7253     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7254     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7255     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7256     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7257     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7258     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7259                                             Spacing));
7260     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7261                                             Spacing * 2));
7262     TmpInst.addOperand(Inst.getOperand(1)); // lane
7263     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7264     TmpInst.addOperand(Inst.getOperand(5));
7265     Inst = TmpInst;
7266     return true;
7267   }
7268 
7269   case ARM::VST4LNdWB_fixed_Asm_8:
7270   case ARM::VST4LNdWB_fixed_Asm_16:
7271   case ARM::VST4LNdWB_fixed_Asm_32:
7272   case ARM::VST4LNqWB_fixed_Asm_16:
7273   case ARM::VST4LNqWB_fixed_Asm_32: {
7274     MCInst TmpInst;
7275     // Shuffle the operands around so the lane index operand is in the
7276     // right place.
7277     unsigned Spacing;
7278     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7279     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7280     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7281     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7282     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7283     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7284     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7285                                             Spacing));
7286     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7287                                             Spacing * 2));
7288     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7289                                             Spacing * 3));
7290     TmpInst.addOperand(Inst.getOperand(1)); // lane
7291     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7292     TmpInst.addOperand(Inst.getOperand(5));
7293     Inst = TmpInst;
7294     return true;
7295   }
7296 
7297   case ARM::VST1LNdAsm_8:
7298   case ARM::VST1LNdAsm_16:
7299   case ARM::VST1LNdAsm_32: {
7300     MCInst TmpInst;
7301     // Shuffle the operands around so the lane index operand is in the
7302     // right place.
7303     unsigned Spacing;
7304     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7305     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7306     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7307     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7308     TmpInst.addOperand(Inst.getOperand(1)); // lane
7309     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7310     TmpInst.addOperand(Inst.getOperand(5));
7311     Inst = TmpInst;
7312     return true;
7313   }
7314 
7315   case ARM::VST2LNdAsm_8:
7316   case ARM::VST2LNdAsm_16:
7317   case ARM::VST2LNdAsm_32:
7318   case ARM::VST2LNqAsm_16:
7319   case ARM::VST2LNqAsm_32: {
7320     MCInst TmpInst;
7321     // Shuffle the operands around so the lane index operand is in the
7322     // right place.
7323     unsigned Spacing;
7324     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7325     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7326     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7327     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7328     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7329                                             Spacing));
7330     TmpInst.addOperand(Inst.getOperand(1)); // lane
7331     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7332     TmpInst.addOperand(Inst.getOperand(5));
7333     Inst = TmpInst;
7334     return true;
7335   }
7336 
7337   case ARM::VST3LNdAsm_8:
7338   case ARM::VST3LNdAsm_16:
7339   case ARM::VST3LNdAsm_32:
7340   case ARM::VST3LNqAsm_16:
7341   case ARM::VST3LNqAsm_32: {
7342     MCInst TmpInst;
7343     // Shuffle the operands around so the lane index operand is in the
7344     // right place.
7345     unsigned Spacing;
7346     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7347     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7348     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7349     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7350     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7351                                             Spacing));
7352     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7353                                             Spacing * 2));
7354     TmpInst.addOperand(Inst.getOperand(1)); // lane
7355     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7356     TmpInst.addOperand(Inst.getOperand(5));
7357     Inst = TmpInst;
7358     return true;
7359   }
7360 
7361   case ARM::VST4LNdAsm_8:
7362   case ARM::VST4LNdAsm_16:
7363   case ARM::VST4LNdAsm_32:
7364   case ARM::VST4LNqAsm_16:
7365   case ARM::VST4LNqAsm_32: {
7366     MCInst TmpInst;
7367     // Shuffle the operands around so the lane index operand is in the
7368     // right place.
7369     unsigned Spacing;
7370     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7371     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7372     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7373     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7374     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7375                                             Spacing));
7376     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7377                                             Spacing * 2));
7378     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7379                                             Spacing * 3));
7380     TmpInst.addOperand(Inst.getOperand(1)); // lane
7381     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7382     TmpInst.addOperand(Inst.getOperand(5));
7383     Inst = TmpInst;
7384     return true;
7385   }
7386 
7387   // Handle NEON VLD complex aliases.
7388   case ARM::VLD1LNdWB_register_Asm_8:
7389   case ARM::VLD1LNdWB_register_Asm_16:
7390   case ARM::VLD1LNdWB_register_Asm_32: {
7391     MCInst TmpInst;
7392     // Shuffle the operands around so the lane index operand is in the
7393     // right place.
7394     unsigned Spacing;
7395     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7396     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7397     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7398     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7399     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7400     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7401     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7402     TmpInst.addOperand(Inst.getOperand(1)); // lane
7403     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7404     TmpInst.addOperand(Inst.getOperand(6));
7405     Inst = TmpInst;
7406     return true;
7407   }
7408 
7409   case ARM::VLD2LNdWB_register_Asm_8:
7410   case ARM::VLD2LNdWB_register_Asm_16:
7411   case ARM::VLD2LNdWB_register_Asm_32:
7412   case ARM::VLD2LNqWB_register_Asm_16:
7413   case ARM::VLD2LNqWB_register_Asm_32: {
7414     MCInst TmpInst;
7415     // Shuffle the operands around so the lane index operand is in the
7416     // right place.
7417     unsigned Spacing;
7418     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7419     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7420     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7421                                             Spacing));
7422     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7423     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7424     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7425     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7426     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7427     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7428                                             Spacing));
7429     TmpInst.addOperand(Inst.getOperand(1)); // lane
7430     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7431     TmpInst.addOperand(Inst.getOperand(6));
7432     Inst = TmpInst;
7433     return true;
7434   }
7435 
7436   case ARM::VLD3LNdWB_register_Asm_8:
7437   case ARM::VLD3LNdWB_register_Asm_16:
7438   case ARM::VLD3LNdWB_register_Asm_32:
7439   case ARM::VLD3LNqWB_register_Asm_16:
7440   case ARM::VLD3LNqWB_register_Asm_32: {
7441     MCInst TmpInst;
7442     // Shuffle the operands around so the lane index operand is in the
7443     // right place.
7444     unsigned Spacing;
7445     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7446     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7447     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7448                                             Spacing));
7449     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7450                                             Spacing * 2));
7451     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7452     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7453     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7454     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7455     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7456     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7457                                             Spacing));
7458     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7459                                             Spacing * 2));
7460     TmpInst.addOperand(Inst.getOperand(1)); // lane
7461     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7462     TmpInst.addOperand(Inst.getOperand(6));
7463     Inst = TmpInst;
7464     return true;
7465   }
7466 
7467   case ARM::VLD4LNdWB_register_Asm_8:
7468   case ARM::VLD4LNdWB_register_Asm_16:
7469   case ARM::VLD4LNdWB_register_Asm_32:
7470   case ARM::VLD4LNqWB_register_Asm_16:
7471   case ARM::VLD4LNqWB_register_Asm_32: {
7472     MCInst TmpInst;
7473     // Shuffle the operands around so the lane index operand is in the
7474     // right place.
7475     unsigned Spacing;
7476     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7477     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7478     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7479                                             Spacing));
7480     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7481                                             Spacing * 2));
7482     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7483                                             Spacing * 3));
7484     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7485     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7486     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7487     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7488     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7489     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7490                                             Spacing));
7491     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7492                                             Spacing * 2));
7493     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7494                                             Spacing * 3));
7495     TmpInst.addOperand(Inst.getOperand(1)); // lane
7496     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7497     TmpInst.addOperand(Inst.getOperand(6));
7498     Inst = TmpInst;
7499     return true;
7500   }
7501 
7502   case ARM::VLD1LNdWB_fixed_Asm_8:
7503   case ARM::VLD1LNdWB_fixed_Asm_16:
7504   case ARM::VLD1LNdWB_fixed_Asm_32: {
7505     MCInst TmpInst;
7506     // Shuffle the operands around so the lane index operand is in the
7507     // right place.
7508     unsigned Spacing;
7509     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7510     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7511     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7512     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7513     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7514     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7515     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7516     TmpInst.addOperand(Inst.getOperand(1)); // lane
7517     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7518     TmpInst.addOperand(Inst.getOperand(5));
7519     Inst = TmpInst;
7520     return true;
7521   }
7522 
7523   case ARM::VLD2LNdWB_fixed_Asm_8:
7524   case ARM::VLD2LNdWB_fixed_Asm_16:
7525   case ARM::VLD2LNdWB_fixed_Asm_32:
7526   case ARM::VLD2LNqWB_fixed_Asm_16:
7527   case ARM::VLD2LNqWB_fixed_Asm_32: {
7528     MCInst TmpInst;
7529     // Shuffle the operands around so the lane index operand is in the
7530     // right place.
7531     unsigned Spacing;
7532     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7533     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7534     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7535                                             Spacing));
7536     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7537     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7538     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7539     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7540     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7541     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7542                                             Spacing));
7543     TmpInst.addOperand(Inst.getOperand(1)); // lane
7544     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7545     TmpInst.addOperand(Inst.getOperand(5));
7546     Inst = TmpInst;
7547     return true;
7548   }
7549 
7550   case ARM::VLD3LNdWB_fixed_Asm_8:
7551   case ARM::VLD3LNdWB_fixed_Asm_16:
7552   case ARM::VLD3LNdWB_fixed_Asm_32:
7553   case ARM::VLD3LNqWB_fixed_Asm_16:
7554   case ARM::VLD3LNqWB_fixed_Asm_32: {
7555     MCInst TmpInst;
7556     // Shuffle the operands around so the lane index operand is in the
7557     // right place.
7558     unsigned Spacing;
7559     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7560     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7561     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7562                                             Spacing));
7563     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7564                                             Spacing * 2));
7565     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7566     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7567     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7568     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7569     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7570     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7571                                             Spacing));
7572     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7573                                             Spacing * 2));
7574     TmpInst.addOperand(Inst.getOperand(1)); // lane
7575     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7576     TmpInst.addOperand(Inst.getOperand(5));
7577     Inst = TmpInst;
7578     return true;
7579   }
7580 
7581   case ARM::VLD4LNdWB_fixed_Asm_8:
7582   case ARM::VLD4LNdWB_fixed_Asm_16:
7583   case ARM::VLD4LNdWB_fixed_Asm_32:
7584   case ARM::VLD4LNqWB_fixed_Asm_16:
7585   case ARM::VLD4LNqWB_fixed_Asm_32: {
7586     MCInst TmpInst;
7587     // Shuffle the operands around so the lane index operand is in the
7588     // right place.
7589     unsigned Spacing;
7590     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7591     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7592     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7593                                             Spacing));
7594     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7595                                             Spacing * 2));
7596     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7597                                             Spacing * 3));
7598     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7599     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7600     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7601     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7602     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7603     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7604                                             Spacing));
7605     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7606                                             Spacing * 2));
7607     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7608                                             Spacing * 3));
7609     TmpInst.addOperand(Inst.getOperand(1)); // lane
7610     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7611     TmpInst.addOperand(Inst.getOperand(5));
7612     Inst = TmpInst;
7613     return true;
7614   }
7615 
7616   case ARM::VLD1LNdAsm_8:
7617   case ARM::VLD1LNdAsm_16:
7618   case ARM::VLD1LNdAsm_32: {
7619     MCInst TmpInst;
7620     // Shuffle the operands around so the lane index operand is in the
7621     // right place.
7622     unsigned Spacing;
7623     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7624     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7625     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7626     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7627     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7628     TmpInst.addOperand(Inst.getOperand(1)); // lane
7629     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7630     TmpInst.addOperand(Inst.getOperand(5));
7631     Inst = TmpInst;
7632     return true;
7633   }
7634 
7635   case ARM::VLD2LNdAsm_8:
7636   case ARM::VLD2LNdAsm_16:
7637   case ARM::VLD2LNdAsm_32:
7638   case ARM::VLD2LNqAsm_16:
7639   case ARM::VLD2LNqAsm_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(MCOperand::createReg(Inst.getOperand(0).getReg() +
7647                                             Spacing));
7648     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7649     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7650     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7651     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7652                                             Spacing));
7653     TmpInst.addOperand(Inst.getOperand(1)); // lane
7654     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7655     TmpInst.addOperand(Inst.getOperand(5));
7656     Inst = TmpInst;
7657     return true;
7658   }
7659 
7660   case ARM::VLD3LNdAsm_8:
7661   case ARM::VLD3LNdAsm_16:
7662   case ARM::VLD3LNdAsm_32:
7663   case ARM::VLD3LNqAsm_16:
7664   case ARM::VLD3LNqAsm_32: {
7665     MCInst TmpInst;
7666     // Shuffle the operands around so the lane index operand is in the
7667     // right place.
7668     unsigned Spacing;
7669     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7670     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7671     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7672                                             Spacing));
7673     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7674                                             Spacing * 2));
7675     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7676     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7677     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7678     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7679                                             Spacing));
7680     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7681                                             Spacing * 2));
7682     TmpInst.addOperand(Inst.getOperand(1)); // lane
7683     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7684     TmpInst.addOperand(Inst.getOperand(5));
7685     Inst = TmpInst;
7686     return true;
7687   }
7688 
7689   case ARM::VLD4LNdAsm_8:
7690   case ARM::VLD4LNdAsm_16:
7691   case ARM::VLD4LNdAsm_32:
7692   case ARM::VLD4LNqAsm_16:
7693   case ARM::VLD4LNqAsm_32: {
7694     MCInst TmpInst;
7695     // Shuffle the operands around so the lane index operand is in the
7696     // right place.
7697     unsigned Spacing;
7698     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7699     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7700     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7701                                             Spacing));
7702     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7703                                             Spacing * 2));
7704     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7705                                             Spacing * 3));
7706     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7707     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7708     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7709     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7710                                             Spacing));
7711     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7712                                             Spacing * 2));
7713     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7714                                             Spacing * 3));
7715     TmpInst.addOperand(Inst.getOperand(1)); // lane
7716     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7717     TmpInst.addOperand(Inst.getOperand(5));
7718     Inst = TmpInst;
7719     return true;
7720   }
7721 
7722   // VLD3DUP single 3-element structure to all lanes instructions.
7723   case ARM::VLD3DUPdAsm_8:
7724   case ARM::VLD3DUPdAsm_16:
7725   case ARM::VLD3DUPdAsm_32:
7726   case ARM::VLD3DUPqAsm_8:
7727   case ARM::VLD3DUPqAsm_16:
7728   case ARM::VLD3DUPqAsm_32: {
7729     MCInst TmpInst;
7730     unsigned Spacing;
7731     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7732     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7733     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7734                                             Spacing));
7735     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7736                                             Spacing * 2));
7737     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7738     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7739     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7740     TmpInst.addOperand(Inst.getOperand(4));
7741     Inst = TmpInst;
7742     return true;
7743   }
7744 
7745   case ARM::VLD3DUPdWB_fixed_Asm_8:
7746   case ARM::VLD3DUPdWB_fixed_Asm_16:
7747   case ARM::VLD3DUPdWB_fixed_Asm_32:
7748   case ARM::VLD3DUPqWB_fixed_Asm_8:
7749   case ARM::VLD3DUPqWB_fixed_Asm_16:
7750   case ARM::VLD3DUPqWB_fixed_Asm_32: {
7751     MCInst TmpInst;
7752     unsigned Spacing;
7753     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7754     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7755     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7756                                             Spacing));
7757     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7758                                             Spacing * 2));
7759     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7760     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7761     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7762     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7763     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7764     TmpInst.addOperand(Inst.getOperand(4));
7765     Inst = TmpInst;
7766     return true;
7767   }
7768 
7769   case ARM::VLD3DUPdWB_register_Asm_8:
7770   case ARM::VLD3DUPdWB_register_Asm_16:
7771   case ARM::VLD3DUPdWB_register_Asm_32:
7772   case ARM::VLD3DUPqWB_register_Asm_8:
7773   case ARM::VLD3DUPqWB_register_Asm_16:
7774   case ARM::VLD3DUPqWB_register_Asm_32: {
7775     MCInst TmpInst;
7776     unsigned Spacing;
7777     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7778     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7779     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7780                                             Spacing));
7781     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7782                                             Spacing * 2));
7783     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7784     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7785     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7786     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7787     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7788     TmpInst.addOperand(Inst.getOperand(5));
7789     Inst = TmpInst;
7790     return true;
7791   }
7792 
7793   // VLD3 multiple 3-element structure instructions.
7794   case ARM::VLD3dAsm_8:
7795   case ARM::VLD3dAsm_16:
7796   case ARM::VLD3dAsm_32:
7797   case ARM::VLD3qAsm_8:
7798   case ARM::VLD3qAsm_16:
7799   case ARM::VLD3qAsm_32: {
7800     MCInst TmpInst;
7801     unsigned Spacing;
7802     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7803     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7804     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7805                                             Spacing));
7806     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7807                                             Spacing * 2));
7808     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7809     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7810     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7811     TmpInst.addOperand(Inst.getOperand(4));
7812     Inst = TmpInst;
7813     return true;
7814   }
7815 
7816   case ARM::VLD3dWB_fixed_Asm_8:
7817   case ARM::VLD3dWB_fixed_Asm_16:
7818   case ARM::VLD3dWB_fixed_Asm_32:
7819   case ARM::VLD3qWB_fixed_Asm_8:
7820   case ARM::VLD3qWB_fixed_Asm_16:
7821   case ARM::VLD3qWB_fixed_Asm_32: {
7822     MCInst TmpInst;
7823     unsigned Spacing;
7824     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7825     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7826     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7827                                             Spacing));
7828     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7829                                             Spacing * 2));
7830     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7831     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7832     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7833     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7834     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7835     TmpInst.addOperand(Inst.getOperand(4));
7836     Inst = TmpInst;
7837     return true;
7838   }
7839 
7840   case ARM::VLD3dWB_register_Asm_8:
7841   case ARM::VLD3dWB_register_Asm_16:
7842   case ARM::VLD3dWB_register_Asm_32:
7843   case ARM::VLD3qWB_register_Asm_8:
7844   case ARM::VLD3qWB_register_Asm_16:
7845   case ARM::VLD3qWB_register_Asm_32: {
7846     MCInst TmpInst;
7847     unsigned Spacing;
7848     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7849     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7850     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7851                                             Spacing));
7852     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7853                                             Spacing * 2));
7854     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7855     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7856     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7857     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7858     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7859     TmpInst.addOperand(Inst.getOperand(5));
7860     Inst = TmpInst;
7861     return true;
7862   }
7863 
7864   // VLD4DUP single 3-element structure to all lanes instructions.
7865   case ARM::VLD4DUPdAsm_8:
7866   case ARM::VLD4DUPdAsm_16:
7867   case ARM::VLD4DUPdAsm_32:
7868   case ARM::VLD4DUPqAsm_8:
7869   case ARM::VLD4DUPqAsm_16:
7870   case ARM::VLD4DUPqAsm_32: {
7871     MCInst TmpInst;
7872     unsigned Spacing;
7873     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7874     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7875     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7876                                             Spacing));
7877     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7878                                             Spacing * 2));
7879     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7880                                             Spacing * 3));
7881     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7882     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7883     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7884     TmpInst.addOperand(Inst.getOperand(4));
7885     Inst = TmpInst;
7886     return true;
7887   }
7888 
7889   case ARM::VLD4DUPdWB_fixed_Asm_8:
7890   case ARM::VLD4DUPdWB_fixed_Asm_16:
7891   case ARM::VLD4DUPdWB_fixed_Asm_32:
7892   case ARM::VLD4DUPqWB_fixed_Asm_8:
7893   case ARM::VLD4DUPqWB_fixed_Asm_16:
7894   case ARM::VLD4DUPqWB_fixed_Asm_32: {
7895     MCInst TmpInst;
7896     unsigned Spacing;
7897     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7898     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7899     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7900                                             Spacing));
7901     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7902                                             Spacing * 2));
7903     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7904                                             Spacing * 3));
7905     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7906     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7907     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7908     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7909     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7910     TmpInst.addOperand(Inst.getOperand(4));
7911     Inst = TmpInst;
7912     return true;
7913   }
7914 
7915   case ARM::VLD4DUPdWB_register_Asm_8:
7916   case ARM::VLD4DUPdWB_register_Asm_16:
7917   case ARM::VLD4DUPdWB_register_Asm_32:
7918   case ARM::VLD4DUPqWB_register_Asm_8:
7919   case ARM::VLD4DUPqWB_register_Asm_16:
7920   case ARM::VLD4DUPqWB_register_Asm_32: {
7921     MCInst TmpInst;
7922     unsigned Spacing;
7923     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7924     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7925     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7926                                             Spacing));
7927     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7928                                             Spacing * 2));
7929     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7930                                             Spacing * 3));
7931     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7932     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7933     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7934     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7935     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7936     TmpInst.addOperand(Inst.getOperand(5));
7937     Inst = TmpInst;
7938     return true;
7939   }
7940 
7941   // VLD4 multiple 4-element structure instructions.
7942   case ARM::VLD4dAsm_8:
7943   case ARM::VLD4dAsm_16:
7944   case ARM::VLD4dAsm_32:
7945   case ARM::VLD4qAsm_8:
7946   case ARM::VLD4qAsm_16:
7947   case ARM::VLD4qAsm_32: {
7948     MCInst TmpInst;
7949     unsigned Spacing;
7950     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7951     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7952     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7953                                             Spacing));
7954     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7955                                             Spacing * 2));
7956     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7957                                             Spacing * 3));
7958     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7959     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7960     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7961     TmpInst.addOperand(Inst.getOperand(4));
7962     Inst = TmpInst;
7963     return true;
7964   }
7965 
7966   case ARM::VLD4dWB_fixed_Asm_8:
7967   case ARM::VLD4dWB_fixed_Asm_16:
7968   case ARM::VLD4dWB_fixed_Asm_32:
7969   case ARM::VLD4qWB_fixed_Asm_8:
7970   case ARM::VLD4qWB_fixed_Asm_16:
7971   case ARM::VLD4qWB_fixed_Asm_32: {
7972     MCInst TmpInst;
7973     unsigned Spacing;
7974     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7975     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7976     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7977                                             Spacing));
7978     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7979                                             Spacing * 2));
7980     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7981                                             Spacing * 3));
7982     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7983     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7984     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7985     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7986     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7987     TmpInst.addOperand(Inst.getOperand(4));
7988     Inst = TmpInst;
7989     return true;
7990   }
7991 
7992   case ARM::VLD4dWB_register_Asm_8:
7993   case ARM::VLD4dWB_register_Asm_16:
7994   case ARM::VLD4dWB_register_Asm_32:
7995   case ARM::VLD4qWB_register_Asm_8:
7996   case ARM::VLD4qWB_register_Asm_16:
7997   case ARM::VLD4qWB_register_Asm_32: {
7998     MCInst TmpInst;
7999     unsigned Spacing;
8000     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
8001     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8002     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8003                                             Spacing));
8004     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8005                                             Spacing * 2));
8006     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8007                                             Spacing * 3));
8008     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8009     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8010     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8011     TmpInst.addOperand(Inst.getOperand(3)); // Rm
8012     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8013     TmpInst.addOperand(Inst.getOperand(5));
8014     Inst = TmpInst;
8015     return true;
8016   }
8017 
8018   // VST3 multiple 3-element structure instructions.
8019   case ARM::VST3dAsm_8:
8020   case ARM::VST3dAsm_16:
8021   case ARM::VST3dAsm_32:
8022   case ARM::VST3qAsm_8:
8023   case ARM::VST3qAsm_16:
8024   case ARM::VST3qAsm_32: {
8025     MCInst TmpInst;
8026     unsigned Spacing;
8027     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8028     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8029     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8030     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8031     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8032                                             Spacing));
8033     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8034                                             Spacing * 2));
8035     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8036     TmpInst.addOperand(Inst.getOperand(4));
8037     Inst = TmpInst;
8038     return true;
8039   }
8040 
8041   case ARM::VST3dWB_fixed_Asm_8:
8042   case ARM::VST3dWB_fixed_Asm_16:
8043   case ARM::VST3dWB_fixed_Asm_32:
8044   case ARM::VST3qWB_fixed_Asm_8:
8045   case ARM::VST3qWB_fixed_Asm_16:
8046   case ARM::VST3qWB_fixed_Asm_32: {
8047     MCInst TmpInst;
8048     unsigned Spacing;
8049     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8050     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8051     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8052     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8053     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8054     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8055     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8056                                             Spacing));
8057     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8058                                             Spacing * 2));
8059     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8060     TmpInst.addOperand(Inst.getOperand(4));
8061     Inst = TmpInst;
8062     return true;
8063   }
8064 
8065   case ARM::VST3dWB_register_Asm_8:
8066   case ARM::VST3dWB_register_Asm_16:
8067   case ARM::VST3dWB_register_Asm_32:
8068   case ARM::VST3qWB_register_Asm_8:
8069   case ARM::VST3qWB_register_Asm_16:
8070   case ARM::VST3qWB_register_Asm_32: {
8071     MCInst TmpInst;
8072     unsigned Spacing;
8073     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8074     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8075     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8076     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8077     TmpInst.addOperand(Inst.getOperand(3)); // Rm
8078     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8079     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8080                                             Spacing));
8081     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8082                                             Spacing * 2));
8083     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8084     TmpInst.addOperand(Inst.getOperand(5));
8085     Inst = TmpInst;
8086     return true;
8087   }
8088 
8089   // VST4 multiple 3-element structure instructions.
8090   case ARM::VST4dAsm_8:
8091   case ARM::VST4dAsm_16:
8092   case ARM::VST4dAsm_32:
8093   case ARM::VST4qAsm_8:
8094   case ARM::VST4qAsm_16:
8095   case ARM::VST4qAsm_32: {
8096     MCInst TmpInst;
8097     unsigned Spacing;
8098     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8099     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8100     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8101     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8102     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8103                                             Spacing));
8104     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8105                                             Spacing * 2));
8106     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8107                                             Spacing * 3));
8108     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8109     TmpInst.addOperand(Inst.getOperand(4));
8110     Inst = TmpInst;
8111     return true;
8112   }
8113 
8114   case ARM::VST4dWB_fixed_Asm_8:
8115   case ARM::VST4dWB_fixed_Asm_16:
8116   case ARM::VST4dWB_fixed_Asm_32:
8117   case ARM::VST4qWB_fixed_Asm_8:
8118   case ARM::VST4qWB_fixed_Asm_16:
8119   case ARM::VST4qWB_fixed_Asm_32: {
8120     MCInst TmpInst;
8121     unsigned Spacing;
8122     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8123     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8124     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8125     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8126     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8127     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8128     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8129                                             Spacing));
8130     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8131                                             Spacing * 2));
8132     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8133                                             Spacing * 3));
8134     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8135     TmpInst.addOperand(Inst.getOperand(4));
8136     Inst = TmpInst;
8137     return true;
8138   }
8139 
8140   case ARM::VST4dWB_register_Asm_8:
8141   case ARM::VST4dWB_register_Asm_16:
8142   case ARM::VST4dWB_register_Asm_32:
8143   case ARM::VST4qWB_register_Asm_8:
8144   case ARM::VST4qWB_register_Asm_16:
8145   case ARM::VST4qWB_register_Asm_32: {
8146     MCInst TmpInst;
8147     unsigned Spacing;
8148     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8149     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8150     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8151     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8152     TmpInst.addOperand(Inst.getOperand(3)); // Rm
8153     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8154     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8155                                             Spacing));
8156     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8157                                             Spacing * 2));
8158     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8159                                             Spacing * 3));
8160     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8161     TmpInst.addOperand(Inst.getOperand(5));
8162     Inst = TmpInst;
8163     return true;
8164   }
8165 
8166   // Handle encoding choice for the shift-immediate instructions.
8167   case ARM::t2LSLri:
8168   case ARM::t2LSRri:
8169   case ARM::t2ASRri:
8170     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8171         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8172         Inst.getOperand(5).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
8173         !HasWideQualifier) {
8174       unsigned NewOpc;
8175       switch (Inst.getOpcode()) {
8176       default: llvm_unreachable("unexpected opcode");
8177       case ARM::t2LSLri: NewOpc = ARM::tLSLri; break;
8178       case ARM::t2LSRri: NewOpc = ARM::tLSRri; break;
8179       case ARM::t2ASRri: NewOpc = ARM::tASRri; break;
8180       }
8181       // The Thumb1 operands aren't in the same order. Awesome, eh?
8182       MCInst TmpInst;
8183       TmpInst.setOpcode(NewOpc);
8184       TmpInst.addOperand(Inst.getOperand(0));
8185       TmpInst.addOperand(Inst.getOperand(5));
8186       TmpInst.addOperand(Inst.getOperand(1));
8187       TmpInst.addOperand(Inst.getOperand(2));
8188       TmpInst.addOperand(Inst.getOperand(3));
8189       TmpInst.addOperand(Inst.getOperand(4));
8190       Inst = TmpInst;
8191       return true;
8192     }
8193     return false;
8194 
8195   // Handle the Thumb2 mode MOV complex aliases.
8196   case ARM::t2MOVsr:
8197   case ARM::t2MOVSsr: {
8198     // Which instruction to expand to depends on the CCOut operand and
8199     // whether we're in an IT block if the register operands are low
8200     // registers.
8201     bool isNarrow = false;
8202     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8203         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8204         isARMLowRegister(Inst.getOperand(2).getReg()) &&
8205         Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() &&
8206         inITBlock() == (Inst.getOpcode() == ARM::t2MOVsr) &&
8207         !HasWideQualifier)
8208       isNarrow = true;
8209     MCInst TmpInst;
8210     unsigned newOpc;
8211     switch(ARM_AM::getSORegShOp(Inst.getOperand(3).getImm())) {
8212     default: llvm_unreachable("unexpected opcode!");
8213     case ARM_AM::asr: newOpc = isNarrow ? ARM::tASRrr : ARM::t2ASRrr; break;
8214     case ARM_AM::lsr: newOpc = isNarrow ? ARM::tLSRrr : ARM::t2LSRrr; break;
8215     case ARM_AM::lsl: newOpc = isNarrow ? ARM::tLSLrr : ARM::t2LSLrr; break;
8216     case ARM_AM::ror: newOpc = isNarrow ? ARM::tROR   : ARM::t2RORrr; break;
8217     }
8218     TmpInst.setOpcode(newOpc);
8219     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8220     if (isNarrow)
8221       TmpInst.addOperand(MCOperand::createReg(
8222           Inst.getOpcode() == ARM::t2MOVSsr ? ARM::CPSR : 0));
8223     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8224     TmpInst.addOperand(Inst.getOperand(2)); // Rm
8225     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8226     TmpInst.addOperand(Inst.getOperand(5));
8227     if (!isNarrow)
8228       TmpInst.addOperand(MCOperand::createReg(
8229           Inst.getOpcode() == ARM::t2MOVSsr ? ARM::CPSR : 0));
8230     Inst = TmpInst;
8231     return true;
8232   }
8233   case ARM::t2MOVsi:
8234   case ARM::t2MOVSsi: {
8235     // Which instruction to expand to depends on the CCOut operand and
8236     // whether we're in an IT block if the register operands are low
8237     // registers.
8238     bool isNarrow = false;
8239     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8240         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8241         inITBlock() == (Inst.getOpcode() == ARM::t2MOVsi) &&
8242         !HasWideQualifier)
8243       isNarrow = true;
8244     MCInst TmpInst;
8245     unsigned newOpc;
8246     unsigned Shift = ARM_AM::getSORegShOp(Inst.getOperand(2).getImm());
8247     unsigned Amount = ARM_AM::getSORegOffset(Inst.getOperand(2).getImm());
8248     bool isMov = false;
8249     // MOV rd, rm, LSL #0 is actually a MOV instruction
8250     if (Shift == ARM_AM::lsl && Amount == 0) {
8251       isMov = true;
8252       // The 16-bit encoding of MOV rd, rm, LSL #N is explicitly encoding T2 of
8253       // MOV (register) in the ARMv8-A and ARMv8-M manuals, and immediate 0 is
8254       // unpredictable in an IT block so the 32-bit encoding T3 has to be used
8255       // instead.
8256       if (inITBlock()) {
8257         isNarrow = false;
8258       }
8259       newOpc = isNarrow ? ARM::tMOVSr : ARM::t2MOVr;
8260     } else {
8261       switch(Shift) {
8262       default: llvm_unreachable("unexpected opcode!");
8263       case ARM_AM::asr: newOpc = isNarrow ? ARM::tASRri : ARM::t2ASRri; break;
8264       case ARM_AM::lsr: newOpc = isNarrow ? ARM::tLSRri : ARM::t2LSRri; break;
8265       case ARM_AM::lsl: newOpc = isNarrow ? ARM::tLSLri : ARM::t2LSLri; break;
8266       case ARM_AM::ror: newOpc = ARM::t2RORri; isNarrow = false; break;
8267       case ARM_AM::rrx: isNarrow = false; newOpc = ARM::t2RRX; break;
8268       }
8269     }
8270     if (Amount == 32) Amount = 0;
8271     TmpInst.setOpcode(newOpc);
8272     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8273     if (isNarrow && !isMov)
8274       TmpInst.addOperand(MCOperand::createReg(
8275           Inst.getOpcode() == ARM::t2MOVSsi ? ARM::CPSR : 0));
8276     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8277     if (newOpc != ARM::t2RRX && !isMov)
8278       TmpInst.addOperand(MCOperand::createImm(Amount));
8279     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8280     TmpInst.addOperand(Inst.getOperand(4));
8281     if (!isNarrow)
8282       TmpInst.addOperand(MCOperand::createReg(
8283           Inst.getOpcode() == ARM::t2MOVSsi ? ARM::CPSR : 0));
8284     Inst = TmpInst;
8285     return true;
8286   }
8287   // Handle the ARM mode MOV complex aliases.
8288   case ARM::ASRr:
8289   case ARM::LSRr:
8290   case ARM::LSLr:
8291   case ARM::RORr: {
8292     ARM_AM::ShiftOpc ShiftTy;
8293     switch(Inst.getOpcode()) {
8294     default: llvm_unreachable("unexpected opcode!");
8295     case ARM::ASRr: ShiftTy = ARM_AM::asr; break;
8296     case ARM::LSRr: ShiftTy = ARM_AM::lsr; break;
8297     case ARM::LSLr: ShiftTy = ARM_AM::lsl; break;
8298     case ARM::RORr: ShiftTy = ARM_AM::ror; break;
8299     }
8300     unsigned Shifter = ARM_AM::getSORegOpc(ShiftTy, 0);
8301     MCInst TmpInst;
8302     TmpInst.setOpcode(ARM::MOVsr);
8303     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8304     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8305     TmpInst.addOperand(Inst.getOperand(2)); // Rm
8306     TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
8307     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8308     TmpInst.addOperand(Inst.getOperand(4));
8309     TmpInst.addOperand(Inst.getOperand(5)); // cc_out
8310     Inst = TmpInst;
8311     return true;
8312   }
8313   case ARM::ASRi:
8314   case ARM::LSRi:
8315   case ARM::LSLi:
8316   case ARM::RORi: {
8317     ARM_AM::ShiftOpc ShiftTy;
8318     switch(Inst.getOpcode()) {
8319     default: llvm_unreachable("unexpected opcode!");
8320     case ARM::ASRi: ShiftTy = ARM_AM::asr; break;
8321     case ARM::LSRi: ShiftTy = ARM_AM::lsr; break;
8322     case ARM::LSLi: ShiftTy = ARM_AM::lsl; break;
8323     case ARM::RORi: ShiftTy = ARM_AM::ror; break;
8324     }
8325     // A shift by zero is a plain MOVr, not a MOVsi.
8326     unsigned Amt = Inst.getOperand(2).getImm();
8327     unsigned Opc = Amt == 0 ? ARM::MOVr : ARM::MOVsi;
8328     // A shift by 32 should be encoded as 0 when permitted
8329     if (Amt == 32 && (ShiftTy == ARM_AM::lsr || ShiftTy == ARM_AM::asr))
8330       Amt = 0;
8331     unsigned Shifter = ARM_AM::getSORegOpc(ShiftTy, Amt);
8332     MCInst TmpInst;
8333     TmpInst.setOpcode(Opc);
8334     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8335     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8336     if (Opc == ARM::MOVsi)
8337       TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
8338     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8339     TmpInst.addOperand(Inst.getOperand(4));
8340     TmpInst.addOperand(Inst.getOperand(5)); // cc_out
8341     Inst = TmpInst;
8342     return true;
8343   }
8344   case ARM::RRXi: {
8345     unsigned Shifter = ARM_AM::getSORegOpc(ARM_AM::rrx, 0);
8346     MCInst TmpInst;
8347     TmpInst.setOpcode(ARM::MOVsi);
8348     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8349     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8350     TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
8351     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8352     TmpInst.addOperand(Inst.getOperand(3));
8353     TmpInst.addOperand(Inst.getOperand(4)); // cc_out
8354     Inst = TmpInst;
8355     return true;
8356   }
8357   case ARM::t2LDMIA_UPD: {
8358     // If this is a load of a single register, then we should use
8359     // a post-indexed LDR instruction instead, per the ARM ARM.
8360     if (Inst.getNumOperands() != 5)
8361       return false;
8362     MCInst TmpInst;
8363     TmpInst.setOpcode(ARM::t2LDR_POST);
8364     TmpInst.addOperand(Inst.getOperand(4)); // Rt
8365     TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8366     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8367     TmpInst.addOperand(MCOperand::createImm(4));
8368     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8369     TmpInst.addOperand(Inst.getOperand(3));
8370     Inst = TmpInst;
8371     return true;
8372   }
8373   case ARM::t2STMDB_UPD: {
8374     // If this is a store of a single register, then we should use
8375     // a pre-indexed STR instruction instead, per the ARM ARM.
8376     if (Inst.getNumOperands() != 5)
8377       return false;
8378     MCInst TmpInst;
8379     TmpInst.setOpcode(ARM::t2STR_PRE);
8380     TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8381     TmpInst.addOperand(Inst.getOperand(4)); // Rt
8382     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8383     TmpInst.addOperand(MCOperand::createImm(-4));
8384     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8385     TmpInst.addOperand(Inst.getOperand(3));
8386     Inst = TmpInst;
8387     return true;
8388   }
8389   case ARM::LDMIA_UPD:
8390     // If this is a load of a single register via a 'pop', then we should use
8391     // a post-indexed LDR instruction instead, per the ARM ARM.
8392     if (static_cast<ARMOperand &>(*Operands[0]).getToken() == "pop" &&
8393         Inst.getNumOperands() == 5) {
8394       MCInst TmpInst;
8395       TmpInst.setOpcode(ARM::LDR_POST_IMM);
8396       TmpInst.addOperand(Inst.getOperand(4)); // Rt
8397       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8398       TmpInst.addOperand(Inst.getOperand(1)); // Rn
8399       TmpInst.addOperand(MCOperand::createReg(0));  // am2offset
8400       TmpInst.addOperand(MCOperand::createImm(4));
8401       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8402       TmpInst.addOperand(Inst.getOperand(3));
8403       Inst = TmpInst;
8404       return true;
8405     }
8406     break;
8407   case ARM::STMDB_UPD:
8408     // If this is a store of a single register via a 'push', then we should use
8409     // a pre-indexed STR instruction instead, per the ARM ARM.
8410     if (static_cast<ARMOperand &>(*Operands[0]).getToken() == "push" &&
8411         Inst.getNumOperands() == 5) {
8412       MCInst TmpInst;
8413       TmpInst.setOpcode(ARM::STR_PRE_IMM);
8414       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8415       TmpInst.addOperand(Inst.getOperand(4)); // Rt
8416       TmpInst.addOperand(Inst.getOperand(1)); // addrmode_imm12
8417       TmpInst.addOperand(MCOperand::createImm(-4));
8418       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8419       TmpInst.addOperand(Inst.getOperand(3));
8420       Inst = TmpInst;
8421     }
8422     break;
8423   case ARM::t2ADDri12:
8424     // If the immediate fits for encoding T3 (t2ADDri) and the generic "add"
8425     // mnemonic was used (not "addw"), encoding T3 is preferred.
8426     if (static_cast<ARMOperand &>(*Operands[0]).getToken() != "add" ||
8427         ARM_AM::getT2SOImmVal(Inst.getOperand(2).getImm()) == -1)
8428       break;
8429     Inst.setOpcode(ARM::t2ADDri);
8430     Inst.addOperand(MCOperand::createReg(0)); // cc_out
8431     break;
8432   case ARM::t2SUBri12:
8433     // If the immediate fits for encoding T3 (t2SUBri) and the generic "sub"
8434     // mnemonic was used (not "subw"), encoding T3 is preferred.
8435     if (static_cast<ARMOperand &>(*Operands[0]).getToken() != "sub" ||
8436         ARM_AM::getT2SOImmVal(Inst.getOperand(2).getImm()) == -1)
8437       break;
8438     Inst.setOpcode(ARM::t2SUBri);
8439     Inst.addOperand(MCOperand::createReg(0)); // cc_out
8440     break;
8441   case ARM::tADDi8:
8442     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
8443     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
8444     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
8445     // to encoding T1 if <Rd> is omitted."
8446     if ((unsigned)Inst.getOperand(3).getImm() < 8 && Operands.size() == 6) {
8447       Inst.setOpcode(ARM::tADDi3);
8448       return true;
8449     }
8450     break;
8451   case ARM::tSUBi8:
8452     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
8453     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
8454     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
8455     // to encoding T1 if <Rd> is omitted."
8456     if ((unsigned)Inst.getOperand(3).getImm() < 8 && Operands.size() == 6) {
8457       Inst.setOpcode(ARM::tSUBi3);
8458       return true;
8459     }
8460     break;
8461   case ARM::t2ADDri:
8462   case ARM::t2SUBri: {
8463     // If the destination and first source operand are the same, and
8464     // the flags are compatible with the current IT status, use encoding T2
8465     // instead of T3. For compatibility with the system 'as'. Make sure the
8466     // wide encoding wasn't explicit.
8467     if (Inst.getOperand(0).getReg() != Inst.getOperand(1).getReg() ||
8468         !isARMLowRegister(Inst.getOperand(0).getReg()) ||
8469         (Inst.getOperand(2).isImm() &&
8470          (unsigned)Inst.getOperand(2).getImm() > 255) ||
8471         Inst.getOperand(5).getReg() != (inITBlock() ? 0 : ARM::CPSR) ||
8472         HasWideQualifier)
8473       break;
8474     MCInst TmpInst;
8475     TmpInst.setOpcode(Inst.getOpcode() == ARM::t2ADDri ?
8476                       ARM::tADDi8 : ARM::tSUBi8);
8477     TmpInst.addOperand(Inst.getOperand(0));
8478     TmpInst.addOperand(Inst.getOperand(5));
8479     TmpInst.addOperand(Inst.getOperand(0));
8480     TmpInst.addOperand(Inst.getOperand(2));
8481     TmpInst.addOperand(Inst.getOperand(3));
8482     TmpInst.addOperand(Inst.getOperand(4));
8483     Inst = TmpInst;
8484     return true;
8485   }
8486   case ARM::t2ADDrr: {
8487     // If the destination and first source operand are the same, and
8488     // there's no setting of the flags, use encoding T2 instead of T3.
8489     // Note that this is only for ADD, not SUB. This mirrors the system
8490     // 'as' behaviour.  Also take advantage of ADD being commutative.
8491     // Make sure the wide encoding wasn't explicit.
8492     bool Swap = false;
8493     auto DestReg = Inst.getOperand(0).getReg();
8494     bool Transform = DestReg == Inst.getOperand(1).getReg();
8495     if (!Transform && DestReg == Inst.getOperand(2).getReg()) {
8496       Transform = true;
8497       Swap = true;
8498     }
8499     if (!Transform ||
8500         Inst.getOperand(5).getReg() != 0 ||
8501         HasWideQualifier)
8502       break;
8503     MCInst TmpInst;
8504     TmpInst.setOpcode(ARM::tADDhirr);
8505     TmpInst.addOperand(Inst.getOperand(0));
8506     TmpInst.addOperand(Inst.getOperand(0));
8507     TmpInst.addOperand(Inst.getOperand(Swap ? 1 : 2));
8508     TmpInst.addOperand(Inst.getOperand(3));
8509     TmpInst.addOperand(Inst.getOperand(4));
8510     Inst = TmpInst;
8511     return true;
8512   }
8513   case ARM::tADDrSP:
8514     // If the non-SP source operand and the destination operand are not the
8515     // same, we need to use the 32-bit encoding if it's available.
8516     if (Inst.getOperand(0).getReg() != Inst.getOperand(2).getReg()) {
8517       Inst.setOpcode(ARM::t2ADDrr);
8518       Inst.addOperand(MCOperand::createReg(0)); // cc_out
8519       return true;
8520     }
8521     break;
8522   case ARM::tB:
8523     // A Thumb conditional branch outside of an IT block is a tBcc.
8524     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock()) {
8525       Inst.setOpcode(ARM::tBcc);
8526       return true;
8527     }
8528     break;
8529   case ARM::t2B:
8530     // A Thumb2 conditional branch outside of an IT block is a t2Bcc.
8531     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock()){
8532       Inst.setOpcode(ARM::t2Bcc);
8533       return true;
8534     }
8535     break;
8536   case ARM::t2Bcc:
8537     // If the conditional is AL or we're in an IT block, we really want t2B.
8538     if (Inst.getOperand(1).getImm() == ARMCC::AL || inITBlock()) {
8539       Inst.setOpcode(ARM::t2B);
8540       return true;
8541     }
8542     break;
8543   case ARM::tBcc:
8544     // If the conditional is AL, we really want tB.
8545     if (Inst.getOperand(1).getImm() == ARMCC::AL) {
8546       Inst.setOpcode(ARM::tB);
8547       return true;
8548     }
8549     break;
8550   case ARM::tLDMIA: {
8551     // If the register list contains any high registers, or if the writeback
8552     // doesn't match what tLDMIA can do, we need to use the 32-bit encoding
8553     // instead if we're in Thumb2. Otherwise, this should have generated
8554     // an error in validateInstruction().
8555     unsigned Rn = Inst.getOperand(0).getReg();
8556     bool hasWritebackToken =
8557         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
8558          static_cast<ARMOperand &>(*Operands[3]).getToken() == "!");
8559     bool listContainsBase;
8560     if (checkLowRegisterList(Inst, 3, Rn, 0, listContainsBase) ||
8561         (!listContainsBase && !hasWritebackToken) ||
8562         (listContainsBase && hasWritebackToken)) {
8563       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
8564       assert(isThumbTwo());
8565       Inst.setOpcode(hasWritebackToken ? ARM::t2LDMIA_UPD : ARM::t2LDMIA);
8566       // If we're switching to the updating version, we need to insert
8567       // the writeback tied operand.
8568       if (hasWritebackToken)
8569         Inst.insert(Inst.begin(),
8570                     MCOperand::createReg(Inst.getOperand(0).getReg()));
8571       return true;
8572     }
8573     break;
8574   }
8575   case ARM::tSTMIA_UPD: {
8576     // If the register list contains any high registers, we need to use
8577     // the 32-bit encoding instead if we're in Thumb2. Otherwise, this
8578     // should have generated an error in validateInstruction().
8579     unsigned Rn = Inst.getOperand(0).getReg();
8580     bool listContainsBase;
8581     if (checkLowRegisterList(Inst, 4, Rn, 0, listContainsBase)) {
8582       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
8583       assert(isThumbTwo());
8584       Inst.setOpcode(ARM::t2STMIA_UPD);
8585       return true;
8586     }
8587     break;
8588   }
8589   case ARM::tPOP: {
8590     bool listContainsBase;
8591     // If the register list contains any high registers, we need to use
8592     // the 32-bit encoding instead if we're in Thumb2. Otherwise, this
8593     // should have generated an error in validateInstruction().
8594     if (!checkLowRegisterList(Inst, 2, 0, ARM::PC, listContainsBase))
8595       return false;
8596     assert(isThumbTwo());
8597     Inst.setOpcode(ARM::t2LDMIA_UPD);
8598     // Add the base register and writeback operands.
8599     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8600     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8601     return true;
8602   }
8603   case ARM::tPUSH: {
8604     bool listContainsBase;
8605     if (!checkLowRegisterList(Inst, 2, 0, ARM::LR, listContainsBase))
8606       return false;
8607     assert(isThumbTwo());
8608     Inst.setOpcode(ARM::t2STMDB_UPD);
8609     // Add the base register and writeback operands.
8610     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8611     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8612     return true;
8613   }
8614   case ARM::t2MOVi:
8615     // If we can use the 16-bit encoding and the user didn't explicitly
8616     // request the 32-bit variant, transform it here.
8617     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8618         (Inst.getOperand(1).isImm() &&
8619          (unsigned)Inst.getOperand(1).getImm() <= 255) &&
8620         Inst.getOperand(4).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
8621         !HasWideQualifier) {
8622       // The operands aren't in the same order for tMOVi8...
8623       MCInst TmpInst;
8624       TmpInst.setOpcode(ARM::tMOVi8);
8625       TmpInst.addOperand(Inst.getOperand(0));
8626       TmpInst.addOperand(Inst.getOperand(4));
8627       TmpInst.addOperand(Inst.getOperand(1));
8628       TmpInst.addOperand(Inst.getOperand(2));
8629       TmpInst.addOperand(Inst.getOperand(3));
8630       Inst = TmpInst;
8631       return true;
8632     }
8633     break;
8634 
8635   case ARM::t2MOVr:
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         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8640         Inst.getOperand(2).getImm() == ARMCC::AL &&
8641         Inst.getOperand(4).getReg() == ARM::CPSR &&
8642         !HasWideQualifier) {
8643       // The operands aren't the same for tMOV[S]r... (no cc_out)
8644       MCInst TmpInst;
8645       TmpInst.setOpcode(Inst.getOperand(4).getReg() ? ARM::tMOVSr : ARM::tMOVr);
8646       TmpInst.addOperand(Inst.getOperand(0));
8647       TmpInst.addOperand(Inst.getOperand(1));
8648       TmpInst.addOperand(Inst.getOperand(2));
8649       TmpInst.addOperand(Inst.getOperand(3));
8650       Inst = TmpInst;
8651       return true;
8652     }
8653     break;
8654 
8655   case ARM::t2SXTH:
8656   case ARM::t2SXTB:
8657   case ARM::t2UXTH:
8658   case ARM::t2UXTB:
8659     // If we can use the 16-bit encoding and the user didn't explicitly
8660     // request the 32-bit variant, transform it here.
8661     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8662         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8663         Inst.getOperand(2).getImm() == 0 &&
8664         !HasWideQualifier) {
8665       unsigned NewOpc;
8666       switch (Inst.getOpcode()) {
8667       default: llvm_unreachable("Illegal opcode!");
8668       case ARM::t2SXTH: NewOpc = ARM::tSXTH; break;
8669       case ARM::t2SXTB: NewOpc = ARM::tSXTB; break;
8670       case ARM::t2UXTH: NewOpc = ARM::tUXTH; break;
8671       case ARM::t2UXTB: NewOpc = ARM::tUXTB; break;
8672       }
8673       // The operands aren't the same for thumb1 (no rotate operand).
8674       MCInst TmpInst;
8675       TmpInst.setOpcode(NewOpc);
8676       TmpInst.addOperand(Inst.getOperand(0));
8677       TmpInst.addOperand(Inst.getOperand(1));
8678       TmpInst.addOperand(Inst.getOperand(3));
8679       TmpInst.addOperand(Inst.getOperand(4));
8680       Inst = TmpInst;
8681       return true;
8682     }
8683     break;
8684 
8685   case ARM::MOVsi: {
8686     ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(Inst.getOperand(2).getImm());
8687     // rrx shifts and asr/lsr of #32 is encoded as 0
8688     if (SOpc == ARM_AM::rrx || SOpc == ARM_AM::asr || SOpc == ARM_AM::lsr)
8689       return false;
8690     if (ARM_AM::getSORegOffset(Inst.getOperand(2).getImm()) == 0) {
8691       // Shifting by zero is accepted as a vanilla 'MOVr'
8692       MCInst TmpInst;
8693       TmpInst.setOpcode(ARM::MOVr);
8694       TmpInst.addOperand(Inst.getOperand(0));
8695       TmpInst.addOperand(Inst.getOperand(1));
8696       TmpInst.addOperand(Inst.getOperand(3));
8697       TmpInst.addOperand(Inst.getOperand(4));
8698       TmpInst.addOperand(Inst.getOperand(5));
8699       Inst = TmpInst;
8700       return true;
8701     }
8702     return false;
8703   }
8704   case ARM::ANDrsi:
8705   case ARM::ORRrsi:
8706   case ARM::EORrsi:
8707   case ARM::BICrsi:
8708   case ARM::SUBrsi:
8709   case ARM::ADDrsi: {
8710     unsigned newOpc;
8711     ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(Inst.getOperand(3).getImm());
8712     if (SOpc == ARM_AM::rrx) return false;
8713     switch (Inst.getOpcode()) {
8714     default: llvm_unreachable("unexpected opcode!");
8715     case ARM::ANDrsi: newOpc = ARM::ANDrr; break;
8716     case ARM::ORRrsi: newOpc = ARM::ORRrr; break;
8717     case ARM::EORrsi: newOpc = ARM::EORrr; break;
8718     case ARM::BICrsi: newOpc = ARM::BICrr; break;
8719     case ARM::SUBrsi: newOpc = ARM::SUBrr; break;
8720     case ARM::ADDrsi: newOpc = ARM::ADDrr; break;
8721     }
8722     // If the shift is by zero, use the non-shifted instruction definition.
8723     // The exception is for right shifts, where 0 == 32
8724     if (ARM_AM::getSORegOffset(Inst.getOperand(3).getImm()) == 0 &&
8725         !(SOpc == ARM_AM::lsr || SOpc == ARM_AM::asr)) {
8726       MCInst TmpInst;
8727       TmpInst.setOpcode(newOpc);
8728       TmpInst.addOperand(Inst.getOperand(0));
8729       TmpInst.addOperand(Inst.getOperand(1));
8730       TmpInst.addOperand(Inst.getOperand(2));
8731       TmpInst.addOperand(Inst.getOperand(4));
8732       TmpInst.addOperand(Inst.getOperand(5));
8733       TmpInst.addOperand(Inst.getOperand(6));
8734       Inst = TmpInst;
8735       return true;
8736     }
8737     return false;
8738   }
8739   case ARM::ITasm:
8740   case ARM::t2IT: {
8741     MCOperand &MO = Inst.getOperand(1);
8742     unsigned Mask = MO.getImm();
8743     ARMCC::CondCodes Cond = ARMCC::CondCodes(Inst.getOperand(0).getImm());
8744 
8745     // Set up the IT block state according to the IT instruction we just
8746     // matched.
8747     assert(!inITBlock() && "nested IT blocks?!");
8748     startExplicitITBlock(Cond, Mask);
8749     MO.setImm(getITMaskEncoding());
8750     break;
8751   }
8752   case ARM::t2LSLrr:
8753   case ARM::t2LSRrr:
8754   case ARM::t2ASRrr:
8755   case ARM::t2SBCrr:
8756   case ARM::t2RORrr:
8757   case ARM::t2BICrr:
8758     // Assemblers should use the narrow encodings of these instructions when permissible.
8759     if ((isARMLowRegister(Inst.getOperand(1).getReg()) &&
8760          isARMLowRegister(Inst.getOperand(2).getReg())) &&
8761         Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() &&
8762         Inst.getOperand(5).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
8763         !HasWideQualifier) {
8764       unsigned NewOpc;
8765       switch (Inst.getOpcode()) {
8766         default: llvm_unreachable("unexpected opcode");
8767         case ARM::t2LSLrr: NewOpc = ARM::tLSLrr; break;
8768         case ARM::t2LSRrr: NewOpc = ARM::tLSRrr; break;
8769         case ARM::t2ASRrr: NewOpc = ARM::tASRrr; break;
8770         case ARM::t2SBCrr: NewOpc = ARM::tSBC; break;
8771         case ARM::t2RORrr: NewOpc = ARM::tROR; break;
8772         case ARM::t2BICrr: NewOpc = ARM::tBIC; break;
8773       }
8774       MCInst TmpInst;
8775       TmpInst.setOpcode(NewOpc);
8776       TmpInst.addOperand(Inst.getOperand(0));
8777       TmpInst.addOperand(Inst.getOperand(5));
8778       TmpInst.addOperand(Inst.getOperand(1));
8779       TmpInst.addOperand(Inst.getOperand(2));
8780       TmpInst.addOperand(Inst.getOperand(3));
8781       TmpInst.addOperand(Inst.getOperand(4));
8782       Inst = TmpInst;
8783       return true;
8784     }
8785     return false;
8786 
8787   case ARM::t2ANDrr:
8788   case ARM::t2EORrr:
8789   case ARM::t2ADCrr:
8790   case ARM::t2ORRrr:
8791     // Assemblers should use the narrow encodings of these instructions when permissible.
8792     // These instructions are special in that they are commutable, so shorter encodings
8793     // are available more often.
8794     if ((isARMLowRegister(Inst.getOperand(1).getReg()) &&
8795          isARMLowRegister(Inst.getOperand(2).getReg())) &&
8796         (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() ||
8797          Inst.getOperand(0).getReg() == Inst.getOperand(2).getReg()) &&
8798         Inst.getOperand(5).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
8799         !HasWideQualifier) {
8800       unsigned NewOpc;
8801       switch (Inst.getOpcode()) {
8802         default: llvm_unreachable("unexpected opcode");
8803         case ARM::t2ADCrr: NewOpc = ARM::tADC; break;
8804         case ARM::t2ANDrr: NewOpc = ARM::tAND; break;
8805         case ARM::t2EORrr: NewOpc = ARM::tEOR; break;
8806         case ARM::t2ORRrr: NewOpc = ARM::tORR; break;
8807       }
8808       MCInst TmpInst;
8809       TmpInst.setOpcode(NewOpc);
8810       TmpInst.addOperand(Inst.getOperand(0));
8811       TmpInst.addOperand(Inst.getOperand(5));
8812       if (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg()) {
8813         TmpInst.addOperand(Inst.getOperand(1));
8814         TmpInst.addOperand(Inst.getOperand(2));
8815       } else {
8816         TmpInst.addOperand(Inst.getOperand(2));
8817         TmpInst.addOperand(Inst.getOperand(1));
8818       }
8819       TmpInst.addOperand(Inst.getOperand(3));
8820       TmpInst.addOperand(Inst.getOperand(4));
8821       Inst = TmpInst;
8822       return true;
8823     }
8824     return false;
8825   }
8826   return false;
8827 }
8828 
8829 unsigned ARMAsmParser::checkTargetMatchPredicate(MCInst &Inst) {
8830   // 16-bit thumb arithmetic instructions either require or preclude the 'S'
8831   // suffix depending on whether they're in an IT block or not.
8832   unsigned Opc = Inst.getOpcode();
8833   const MCInstrDesc &MCID = MII.get(Opc);
8834   if (MCID.TSFlags & ARMII::ThumbArithFlagSetting) {
8835     assert(MCID.hasOptionalDef() &&
8836            "optionally flag setting instruction missing optional def operand");
8837     assert(MCID.NumOperands == Inst.getNumOperands() &&
8838            "operand count mismatch!");
8839     // Find the optional-def operand (cc_out).
8840     unsigned OpNo;
8841     for (OpNo = 0;
8842          !MCID.OpInfo[OpNo].isOptionalDef() && OpNo < MCID.NumOperands;
8843          ++OpNo)
8844       ;
8845     // If we're parsing Thumb1, reject it completely.
8846     if (isThumbOne() && Inst.getOperand(OpNo).getReg() != ARM::CPSR)
8847       return Match_RequiresFlagSetting;
8848     // If we're parsing Thumb2, which form is legal depends on whether we're
8849     // in an IT block.
8850     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() != ARM::CPSR &&
8851         !inITBlock())
8852       return Match_RequiresITBlock;
8853     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() == ARM::CPSR &&
8854         inITBlock())
8855       return Match_RequiresNotITBlock;
8856     // LSL with zero immediate is not allowed in an IT block
8857     if (Opc == ARM::tLSLri && Inst.getOperand(3).getImm() == 0 && inITBlock())
8858       return Match_RequiresNotITBlock;
8859   } else if (isThumbOne()) {
8860     // Some high-register supporting Thumb1 encodings only allow both registers
8861     // to be from r0-r7 when in Thumb2.
8862     if (Opc == ARM::tADDhirr && !hasV6MOps() &&
8863         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8864         isARMLowRegister(Inst.getOperand(2).getReg()))
8865       return Match_RequiresThumb2;
8866     // Others only require ARMv6 or later.
8867     else if (Opc == ARM::tMOVr && !hasV6Ops() &&
8868              isARMLowRegister(Inst.getOperand(0).getReg()) &&
8869              isARMLowRegister(Inst.getOperand(1).getReg()))
8870       return Match_RequiresV6;
8871   }
8872 
8873   // Before ARMv8 the rules for when SP is allowed in t2MOVr are more complex
8874   // than the loop below can handle, so it uses the GPRnopc register class and
8875   // we do SP handling here.
8876   if (Opc == ARM::t2MOVr && !hasV8Ops())
8877   {
8878     // SP as both source and destination is not allowed
8879     if (Inst.getOperand(0).getReg() == ARM::SP &&
8880         Inst.getOperand(1).getReg() == ARM::SP)
8881       return Match_RequiresV8;
8882     // When flags-setting SP as either source or destination is not allowed
8883     if (Inst.getOperand(4).getReg() == ARM::CPSR &&
8884         (Inst.getOperand(0).getReg() == ARM::SP ||
8885          Inst.getOperand(1).getReg() == ARM::SP))
8886       return Match_RequiresV8;
8887   }
8888 
8889   // Use of SP for VMRS/VMSR is only allowed in ARM mode with the exception of
8890   // ARMv8-A.
8891   if ((Inst.getOpcode() == ARM::VMRS || Inst.getOpcode() == ARM::VMSR) &&
8892       Inst.getOperand(0).getReg() == ARM::SP && (isThumb() && !hasV8Ops()))
8893     return Match_InvalidOperand;
8894 
8895   for (unsigned I = 0; I < MCID.NumOperands; ++I)
8896     if (MCID.OpInfo[I].RegClass == ARM::rGPRRegClassID) {
8897       // rGPRRegClass excludes PC, and also excluded SP before ARMv8
8898       if ((Inst.getOperand(I).getReg() == ARM::SP) && !hasV8Ops())
8899         return Match_RequiresV8;
8900       else if (Inst.getOperand(I).getReg() == ARM::PC)
8901         return Match_InvalidOperand;
8902     }
8903 
8904   return Match_Success;
8905 }
8906 
8907 namespace llvm {
8908 
8909 template <> inline bool IsCPSRDead<MCInst>(const MCInst *Instr) {
8910   return true; // In an assembly source, no need to second-guess
8911 }
8912 
8913 } // end namespace llvm
8914 
8915 // Returns true if Inst is unpredictable if it is in and IT block, but is not
8916 // the last instruction in the block.
8917 bool ARMAsmParser::isITBlockTerminator(MCInst &Inst) const {
8918   const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
8919 
8920   // All branch & call instructions terminate IT blocks with the exception of
8921   // SVC.
8922   if (MCID.isTerminator() || (MCID.isCall() && Inst.getOpcode() != ARM::tSVC) ||
8923       MCID.isReturn() || MCID.isBranch() || MCID.isIndirectBranch())
8924     return true;
8925 
8926   // Any arithmetic instruction which writes to the PC also terminates the IT
8927   // block.
8928   for (unsigned OpIdx = 0; OpIdx < MCID.getNumDefs(); ++OpIdx) {
8929     MCOperand &Op = Inst.getOperand(OpIdx);
8930     if (Op.isReg() && Op.getReg() == ARM::PC)
8931       return true;
8932   }
8933 
8934   if (MCID.hasImplicitDefOfPhysReg(ARM::PC, MRI))
8935     return true;
8936 
8937   // Instructions with variable operand lists, which write to the variable
8938   // operands. We only care about Thumb instructions here, as ARM instructions
8939   // obviously can't be in an IT block.
8940   switch (Inst.getOpcode()) {
8941   case ARM::tLDMIA:
8942   case ARM::t2LDMIA:
8943   case ARM::t2LDMIA_UPD:
8944   case ARM::t2LDMDB:
8945   case ARM::t2LDMDB_UPD:
8946     if (listContainsReg(Inst, 3, ARM::PC))
8947       return true;
8948     break;
8949   case ARM::tPOP:
8950     if (listContainsReg(Inst, 2, ARM::PC))
8951       return true;
8952     break;
8953   }
8954 
8955   return false;
8956 }
8957 
8958 unsigned ARMAsmParser::MatchInstruction(OperandVector &Operands, MCInst &Inst,
8959                                           SmallVectorImpl<NearMissInfo> &NearMisses,
8960                                           bool MatchingInlineAsm,
8961                                           bool &EmitInITBlock,
8962                                           MCStreamer &Out) {
8963   // If we can't use an implicit IT block here, just match as normal.
8964   if (inExplicitITBlock() || !isThumbTwo() || !useImplicitITThumb())
8965     return MatchInstructionImpl(Operands, Inst, &NearMisses, MatchingInlineAsm);
8966 
8967   // Try to match the instruction in an extension of the current IT block (if
8968   // there is one).
8969   if (inImplicitITBlock()) {
8970     extendImplicitITBlock(ITState.Cond);
8971     if (MatchInstructionImpl(Operands, Inst, nullptr, MatchingInlineAsm) ==
8972             Match_Success) {
8973       // The match succeded, but we still have to check that the instruction is
8974       // valid in this implicit IT block.
8975       const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
8976       if (MCID.isPredicable()) {
8977         ARMCC::CondCodes InstCond =
8978             (ARMCC::CondCodes)Inst.getOperand(MCID.findFirstPredOperandIdx())
8979                 .getImm();
8980         ARMCC::CondCodes ITCond = currentITCond();
8981         if (InstCond == ITCond) {
8982           EmitInITBlock = true;
8983           return Match_Success;
8984         } else if (InstCond == ARMCC::getOppositeCondition(ITCond)) {
8985           invertCurrentITCondition();
8986           EmitInITBlock = true;
8987           return Match_Success;
8988         }
8989       }
8990     }
8991     rewindImplicitITPosition();
8992   }
8993 
8994   // Finish the current IT block, and try to match outside any IT block.
8995   flushPendingInstructions(Out);
8996   unsigned PlainMatchResult =
8997       MatchInstructionImpl(Operands, Inst, &NearMisses, MatchingInlineAsm);
8998   if (PlainMatchResult == Match_Success) {
8999     const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
9000     if (MCID.isPredicable()) {
9001       ARMCC::CondCodes InstCond =
9002           (ARMCC::CondCodes)Inst.getOperand(MCID.findFirstPredOperandIdx())
9003               .getImm();
9004       // Some forms of the branch instruction have their own condition code
9005       // fields, so can be conditionally executed without an IT block.
9006       if (Inst.getOpcode() == ARM::tBcc || Inst.getOpcode() == ARM::t2Bcc) {
9007         EmitInITBlock = false;
9008         return Match_Success;
9009       }
9010       if (InstCond == ARMCC::AL) {
9011         EmitInITBlock = false;
9012         return Match_Success;
9013       }
9014     } else {
9015       EmitInITBlock = false;
9016       return Match_Success;
9017     }
9018   }
9019 
9020   // Try to match in a new IT block. The matcher doesn't check the actual
9021   // condition, so we create an IT block with a dummy condition, and fix it up
9022   // once we know the actual condition.
9023   startImplicitITBlock();
9024   if (MatchInstructionImpl(Operands, Inst, nullptr, MatchingInlineAsm) ==
9025       Match_Success) {
9026     const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
9027     if (MCID.isPredicable()) {
9028       ITState.Cond =
9029           (ARMCC::CondCodes)Inst.getOperand(MCID.findFirstPredOperandIdx())
9030               .getImm();
9031       EmitInITBlock = true;
9032       return Match_Success;
9033     }
9034   }
9035   discardImplicitITBlock();
9036 
9037   // If none of these succeed, return the error we got when trying to match
9038   // outside any IT blocks.
9039   EmitInITBlock = false;
9040   return PlainMatchResult;
9041 }
9042 
9043 static std::string ARMMnemonicSpellCheck(StringRef S, uint64_t FBS,
9044                                          unsigned VariantID = 0);
9045 
9046 static const char *getSubtargetFeatureName(uint64_t Val);
9047 bool ARMAsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
9048                                            OperandVector &Operands,
9049                                            MCStreamer &Out, uint64_t &ErrorInfo,
9050                                            bool MatchingInlineAsm) {
9051   MCInst Inst;
9052   unsigned MatchResult;
9053   bool PendConditionalInstruction = false;
9054 
9055   SmallVector<NearMissInfo, 4> NearMisses;
9056   MatchResult = MatchInstruction(Operands, Inst, NearMisses, MatchingInlineAsm,
9057                                  PendConditionalInstruction, Out);
9058 
9059   switch (MatchResult) {
9060   case Match_Success:
9061     // Context sensitive operand constraints aren't handled by the matcher,
9062     // so check them here.
9063     if (validateInstruction(Inst, Operands)) {
9064       // Still progress the IT block, otherwise one wrong condition causes
9065       // nasty cascading errors.
9066       forwardITPosition();
9067       return true;
9068     }
9069 
9070     { // processInstruction() updates inITBlock state, we need to save it away
9071       bool wasInITBlock = inITBlock();
9072 
9073       // Some instructions need post-processing to, for example, tweak which
9074       // encoding is selected. Loop on it while changes happen so the
9075       // individual transformations can chain off each other. E.g.,
9076       // tPOP(r8)->t2LDMIA_UPD(sp,r8)->t2STR_POST(sp,r8)
9077       while (processInstruction(Inst, Operands, Out))
9078         ;
9079 
9080       // Only after the instruction is fully processed, we can validate it
9081       if (wasInITBlock && hasV8Ops() && isThumb() &&
9082           !isV8EligibleForIT(&Inst)) {
9083         Warning(IDLoc, "deprecated instruction in IT block");
9084       }
9085     }
9086 
9087     // Only move forward at the very end so that everything in validate
9088     // and process gets a consistent answer about whether we're in an IT
9089     // block.
9090     forwardITPosition();
9091 
9092     // ITasm is an ARM mode pseudo-instruction that just sets the ITblock and
9093     // doesn't actually encode.
9094     if (Inst.getOpcode() == ARM::ITasm)
9095       return false;
9096 
9097     Inst.setLoc(IDLoc);
9098     if (PendConditionalInstruction) {
9099       PendingConditionalInsts.push_back(Inst);
9100       if (isITBlockFull() || isITBlockTerminator(Inst))
9101         flushPendingInstructions(Out);
9102     } else {
9103       Out.EmitInstruction(Inst, getSTI());
9104     }
9105     return false;
9106   case Match_NearMisses:
9107     ReportNearMisses(NearMisses, IDLoc, Operands);
9108     return true;
9109   case Match_MnemonicFail: {
9110     uint64_t FBS = ComputeAvailableFeatures(getSTI().getFeatureBits());
9111     std::string Suggestion = ARMMnemonicSpellCheck(
9112       ((ARMOperand &)*Operands[0]).getToken(), FBS);
9113     return Error(IDLoc, "invalid instruction" + Suggestion,
9114                  ((ARMOperand &)*Operands[0]).getLocRange());
9115   }
9116   }
9117 
9118   llvm_unreachable("Implement any new match types added!");
9119 }
9120 
9121 /// parseDirective parses the arm specific directives
9122 bool ARMAsmParser::ParseDirective(AsmToken DirectiveID) {
9123   const MCObjectFileInfo::Environment Format =
9124     getContext().getObjectFileInfo()->getObjectFileType();
9125   bool IsMachO = Format == MCObjectFileInfo::IsMachO;
9126   bool IsCOFF = Format == MCObjectFileInfo::IsCOFF;
9127 
9128   StringRef IDVal = DirectiveID.getIdentifier();
9129   if (IDVal == ".word")
9130     parseLiteralValues(4, DirectiveID.getLoc());
9131   else if (IDVal == ".short" || IDVal == ".hword")
9132     parseLiteralValues(2, DirectiveID.getLoc());
9133   else if (IDVal == ".thumb")
9134     parseDirectiveThumb(DirectiveID.getLoc());
9135   else if (IDVal == ".arm")
9136     parseDirectiveARM(DirectiveID.getLoc());
9137   else if (IDVal == ".thumb_func")
9138     parseDirectiveThumbFunc(DirectiveID.getLoc());
9139   else if (IDVal == ".code")
9140     parseDirectiveCode(DirectiveID.getLoc());
9141   else if (IDVal == ".syntax")
9142     parseDirectiveSyntax(DirectiveID.getLoc());
9143   else if (IDVal == ".unreq")
9144     parseDirectiveUnreq(DirectiveID.getLoc());
9145   else if (IDVal == ".fnend")
9146     parseDirectiveFnEnd(DirectiveID.getLoc());
9147   else if (IDVal == ".cantunwind")
9148     parseDirectiveCantUnwind(DirectiveID.getLoc());
9149   else if (IDVal == ".personality")
9150     parseDirectivePersonality(DirectiveID.getLoc());
9151   else if (IDVal == ".handlerdata")
9152     parseDirectiveHandlerData(DirectiveID.getLoc());
9153   else if (IDVal == ".setfp")
9154     parseDirectiveSetFP(DirectiveID.getLoc());
9155   else if (IDVal == ".pad")
9156     parseDirectivePad(DirectiveID.getLoc());
9157   else if (IDVal == ".save")
9158     parseDirectiveRegSave(DirectiveID.getLoc(), false);
9159   else if (IDVal == ".vsave")
9160     parseDirectiveRegSave(DirectiveID.getLoc(), true);
9161   else if (IDVal == ".ltorg" || IDVal == ".pool")
9162     parseDirectiveLtorg(DirectiveID.getLoc());
9163   else if (IDVal == ".even")
9164     parseDirectiveEven(DirectiveID.getLoc());
9165   else if (IDVal == ".personalityindex")
9166     parseDirectivePersonalityIndex(DirectiveID.getLoc());
9167   else if (IDVal == ".unwind_raw")
9168     parseDirectiveUnwindRaw(DirectiveID.getLoc());
9169   else if (IDVal == ".movsp")
9170     parseDirectiveMovSP(DirectiveID.getLoc());
9171   else if (IDVal == ".arch_extension")
9172     parseDirectiveArchExtension(DirectiveID.getLoc());
9173   else if (IDVal == ".align")
9174     return parseDirectiveAlign(DirectiveID.getLoc()); // Use Generic on failure.
9175   else if (IDVal == ".thumb_set")
9176     parseDirectiveThumbSet(DirectiveID.getLoc());
9177   else if (!IsMachO && !IsCOFF) {
9178     if (IDVal == ".arch")
9179       parseDirectiveArch(DirectiveID.getLoc());
9180     else if (IDVal == ".cpu")
9181       parseDirectiveCPU(DirectiveID.getLoc());
9182     else if (IDVal == ".eabi_attribute")
9183       parseDirectiveEabiAttr(DirectiveID.getLoc());
9184     else if (IDVal == ".fpu")
9185       parseDirectiveFPU(DirectiveID.getLoc());
9186     else if (IDVal == ".fnstart")
9187       parseDirectiveFnStart(DirectiveID.getLoc());
9188     else if (IDVal == ".inst")
9189       parseDirectiveInst(DirectiveID.getLoc());
9190     else if (IDVal == ".inst.n")
9191       parseDirectiveInst(DirectiveID.getLoc(), 'n');
9192     else if (IDVal == ".inst.w")
9193       parseDirectiveInst(DirectiveID.getLoc(), 'w');
9194     else if (IDVal == ".object_arch")
9195       parseDirectiveObjectArch(DirectiveID.getLoc());
9196     else if (IDVal == ".tlsdescseq")
9197       parseDirectiveTLSDescSeq(DirectiveID.getLoc());
9198     else
9199       return true;
9200   } else
9201     return true;
9202   return false;
9203 }
9204 
9205 /// parseLiteralValues
9206 ///  ::= .hword expression [, expression]*
9207 ///  ::= .short expression [, expression]*
9208 ///  ::= .word expression [, expression]*
9209 bool ARMAsmParser::parseLiteralValues(unsigned Size, SMLoc L) {
9210   auto parseOne = [&]() -> bool {
9211     const MCExpr *Value;
9212     if (getParser().parseExpression(Value))
9213       return true;
9214     getParser().getStreamer().EmitValue(Value, Size, L);
9215     return false;
9216   };
9217   return (parseMany(parseOne));
9218 }
9219 
9220 /// parseDirectiveThumb
9221 ///  ::= .thumb
9222 bool ARMAsmParser::parseDirectiveThumb(SMLoc L) {
9223   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive") ||
9224       check(!hasThumb(), L, "target does not support Thumb mode"))
9225     return true;
9226 
9227   if (!isThumb())
9228     SwitchMode();
9229 
9230   getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
9231   return false;
9232 }
9233 
9234 /// parseDirectiveARM
9235 ///  ::= .arm
9236 bool ARMAsmParser::parseDirectiveARM(SMLoc L) {
9237   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive") ||
9238       check(!hasARM(), L, "target does not support ARM mode"))
9239     return true;
9240 
9241   if (isThumb())
9242     SwitchMode();
9243   getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
9244   return false;
9245 }
9246 
9247 void ARMAsmParser::onLabelParsed(MCSymbol *Symbol) {
9248   // We need to flush the current implicit IT block on a label, because it is
9249   // not legal to branch into an IT block.
9250   flushPendingInstructions(getStreamer());
9251   if (NextSymbolIsThumb) {
9252     getParser().getStreamer().EmitThumbFunc(Symbol);
9253     NextSymbolIsThumb = false;
9254   }
9255 }
9256 
9257 /// parseDirectiveThumbFunc
9258 ///  ::= .thumbfunc symbol_name
9259 bool ARMAsmParser::parseDirectiveThumbFunc(SMLoc L) {
9260   MCAsmParser &Parser = getParser();
9261   const auto Format = getContext().getObjectFileInfo()->getObjectFileType();
9262   bool IsMachO = Format == MCObjectFileInfo::IsMachO;
9263 
9264   // Darwin asm has (optionally) function name after .thumb_func direction
9265   // ELF doesn't
9266 
9267   if (IsMachO) {
9268     if (Parser.getTok().is(AsmToken::Identifier) ||
9269         Parser.getTok().is(AsmToken::String)) {
9270       MCSymbol *Func = getParser().getContext().getOrCreateSymbol(
9271           Parser.getTok().getIdentifier());
9272       getParser().getStreamer().EmitThumbFunc(Func);
9273       Parser.Lex();
9274       if (parseToken(AsmToken::EndOfStatement,
9275                      "unexpected token in '.thumb_func' directive"))
9276         return true;
9277       return false;
9278     }
9279   }
9280 
9281   if (parseToken(AsmToken::EndOfStatement,
9282                  "unexpected token in '.thumb_func' directive"))
9283     return true;
9284 
9285   NextSymbolIsThumb = true;
9286   return false;
9287 }
9288 
9289 /// parseDirectiveSyntax
9290 ///  ::= .syntax unified | divided
9291 bool ARMAsmParser::parseDirectiveSyntax(SMLoc L) {
9292   MCAsmParser &Parser = getParser();
9293   const AsmToken &Tok = Parser.getTok();
9294   if (Tok.isNot(AsmToken::Identifier)) {
9295     Error(L, "unexpected token in .syntax directive");
9296     return false;
9297   }
9298 
9299   StringRef Mode = Tok.getString();
9300   Parser.Lex();
9301   if (check(Mode == "divided" || Mode == "DIVIDED", L,
9302             "'.syntax divided' arm assembly not supported") ||
9303       check(Mode != "unified" && Mode != "UNIFIED", L,
9304             "unrecognized syntax mode in .syntax directive") ||
9305       parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
9306     return true;
9307 
9308   // TODO tell the MC streamer the mode
9309   // getParser().getStreamer().Emit???();
9310   return false;
9311 }
9312 
9313 /// parseDirectiveCode
9314 ///  ::= .code 16 | 32
9315 bool ARMAsmParser::parseDirectiveCode(SMLoc L) {
9316   MCAsmParser &Parser = getParser();
9317   const AsmToken &Tok = Parser.getTok();
9318   if (Tok.isNot(AsmToken::Integer))
9319     return Error(L, "unexpected token in .code directive");
9320   int64_t Val = Parser.getTok().getIntVal();
9321   if (Val != 16 && Val != 32) {
9322     Error(L, "invalid operand to .code directive");
9323     return false;
9324   }
9325   Parser.Lex();
9326 
9327   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
9328     return true;
9329 
9330   if (Val == 16) {
9331     if (!hasThumb())
9332       return Error(L, "target does not support Thumb mode");
9333 
9334     if (!isThumb())
9335       SwitchMode();
9336     getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
9337   } else {
9338     if (!hasARM())
9339       return Error(L, "target does not support ARM mode");
9340 
9341     if (isThumb())
9342       SwitchMode();
9343     getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
9344   }
9345 
9346   return false;
9347 }
9348 
9349 /// parseDirectiveReq
9350 ///  ::= name .req registername
9351 bool ARMAsmParser::parseDirectiveReq(StringRef Name, SMLoc L) {
9352   MCAsmParser &Parser = getParser();
9353   Parser.Lex(); // Eat the '.req' token.
9354   unsigned Reg;
9355   SMLoc SRegLoc, ERegLoc;
9356   if (check(ParseRegister(Reg, SRegLoc, ERegLoc), SRegLoc,
9357             "register name expected") ||
9358       parseToken(AsmToken::EndOfStatement,
9359                  "unexpected input in .req directive."))
9360     return true;
9361 
9362   if (RegisterReqs.insert(std::make_pair(Name, Reg)).first->second != Reg)
9363     return Error(SRegLoc,
9364                  "redefinition of '" + Name + "' does not match original.");
9365 
9366   return false;
9367 }
9368 
9369 /// parseDirectiveUneq
9370 ///  ::= .unreq registername
9371 bool ARMAsmParser::parseDirectiveUnreq(SMLoc L) {
9372   MCAsmParser &Parser = getParser();
9373   if (Parser.getTok().isNot(AsmToken::Identifier))
9374     return Error(L, "unexpected input in .unreq directive.");
9375   RegisterReqs.erase(Parser.getTok().getIdentifier().lower());
9376   Parser.Lex(); // Eat the identifier.
9377   if (parseToken(AsmToken::EndOfStatement,
9378                  "unexpected input in '.unreq' directive"))
9379     return true;
9380   return false;
9381 }
9382 
9383 // After changing arch/CPU, try to put the ARM/Thumb mode back to what it was
9384 // before, if supported by the new target, or emit mapping symbols for the mode
9385 // switch.
9386 void ARMAsmParser::FixModeAfterArchChange(bool WasThumb, SMLoc Loc) {
9387   if (WasThumb != isThumb()) {
9388     if (WasThumb && hasThumb()) {
9389       // Stay in Thumb mode
9390       SwitchMode();
9391     } else if (!WasThumb && hasARM()) {
9392       // Stay in ARM mode
9393       SwitchMode();
9394     } else {
9395       // Mode switch forced, because the new arch doesn't support the old mode.
9396       getParser().getStreamer().EmitAssemblerFlag(isThumb() ? MCAF_Code16
9397                                                             : MCAF_Code32);
9398       // Warn about the implcit mode switch. GAS does not switch modes here,
9399       // but instead stays in the old mode, reporting an error on any following
9400       // instructions as the mode does not exist on the target.
9401       Warning(Loc, Twine("new target does not support ") +
9402                        (WasThumb ? "thumb" : "arm") + " mode, switching to " +
9403                        (!WasThumb ? "thumb" : "arm") + " mode");
9404     }
9405   }
9406 }
9407 
9408 /// parseDirectiveArch
9409 ///  ::= .arch token
9410 bool ARMAsmParser::parseDirectiveArch(SMLoc L) {
9411   StringRef Arch = getParser().parseStringToEndOfStatement().trim();
9412   ARM::ArchKind ID = ARM::parseArch(Arch);
9413 
9414   if (ID == ARM::ArchKind::INVALID)
9415     return Error(L, "Unknown arch name");
9416 
9417   bool WasThumb = isThumb();
9418   Triple T;
9419   MCSubtargetInfo &STI = copySTI();
9420   STI.setDefaultFeatures("", ("+" + ARM::getArchName(ID)).str());
9421   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
9422   FixModeAfterArchChange(WasThumb, L);
9423 
9424   getTargetStreamer().emitArch(ID);
9425   return false;
9426 }
9427 
9428 /// parseDirectiveEabiAttr
9429 ///  ::= .eabi_attribute int, int [, "str"]
9430 ///  ::= .eabi_attribute Tag_name, int [, "str"]
9431 bool ARMAsmParser::parseDirectiveEabiAttr(SMLoc L) {
9432   MCAsmParser &Parser = getParser();
9433   int64_t Tag;
9434   SMLoc TagLoc;
9435   TagLoc = Parser.getTok().getLoc();
9436   if (Parser.getTok().is(AsmToken::Identifier)) {
9437     StringRef Name = Parser.getTok().getIdentifier();
9438     Tag = ARMBuildAttrs::AttrTypeFromString(Name);
9439     if (Tag == -1) {
9440       Error(TagLoc, "attribute name not recognised: " + Name);
9441       return false;
9442     }
9443     Parser.Lex();
9444   } else {
9445     const MCExpr *AttrExpr;
9446 
9447     TagLoc = Parser.getTok().getLoc();
9448     if (Parser.parseExpression(AttrExpr))
9449       return true;
9450 
9451     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(AttrExpr);
9452     if (check(!CE, TagLoc, "expected numeric constant"))
9453       return true;
9454 
9455     Tag = CE->getValue();
9456   }
9457 
9458   if (Parser.parseToken(AsmToken::Comma, "comma expected"))
9459     return true;
9460 
9461   StringRef StringValue = "";
9462   bool IsStringValue = false;
9463 
9464   int64_t IntegerValue = 0;
9465   bool IsIntegerValue = false;
9466 
9467   if (Tag == ARMBuildAttrs::CPU_raw_name || Tag == ARMBuildAttrs::CPU_name)
9468     IsStringValue = true;
9469   else if (Tag == ARMBuildAttrs::compatibility) {
9470     IsStringValue = true;
9471     IsIntegerValue = true;
9472   } else if (Tag < 32 || Tag % 2 == 0)
9473     IsIntegerValue = true;
9474   else if (Tag % 2 == 1)
9475     IsStringValue = true;
9476   else
9477     llvm_unreachable("invalid tag type");
9478 
9479   if (IsIntegerValue) {
9480     const MCExpr *ValueExpr;
9481     SMLoc ValueExprLoc = Parser.getTok().getLoc();
9482     if (Parser.parseExpression(ValueExpr))
9483       return true;
9484 
9485     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ValueExpr);
9486     if (!CE)
9487       return Error(ValueExprLoc, "expected numeric constant");
9488     IntegerValue = CE->getValue();
9489   }
9490 
9491   if (Tag == ARMBuildAttrs::compatibility) {
9492     if (Parser.parseToken(AsmToken::Comma, "comma expected"))
9493       return true;
9494   }
9495 
9496   if (IsStringValue) {
9497     if (Parser.getTok().isNot(AsmToken::String))
9498       return Error(Parser.getTok().getLoc(), "bad string constant");
9499 
9500     StringValue = Parser.getTok().getStringContents();
9501     Parser.Lex();
9502   }
9503 
9504   if (Parser.parseToken(AsmToken::EndOfStatement,
9505                         "unexpected token in '.eabi_attribute' directive"))
9506     return true;
9507 
9508   if (IsIntegerValue && IsStringValue) {
9509     assert(Tag == ARMBuildAttrs::compatibility);
9510     getTargetStreamer().emitIntTextAttribute(Tag, IntegerValue, StringValue);
9511   } else if (IsIntegerValue)
9512     getTargetStreamer().emitAttribute(Tag, IntegerValue);
9513   else if (IsStringValue)
9514     getTargetStreamer().emitTextAttribute(Tag, StringValue);
9515   return false;
9516 }
9517 
9518 /// parseDirectiveCPU
9519 ///  ::= .cpu str
9520 bool ARMAsmParser::parseDirectiveCPU(SMLoc L) {
9521   StringRef CPU = getParser().parseStringToEndOfStatement().trim();
9522   getTargetStreamer().emitTextAttribute(ARMBuildAttrs::CPU_name, CPU);
9523 
9524   // FIXME: This is using table-gen data, but should be moved to
9525   // ARMTargetParser once that is table-gen'd.
9526   if (!getSTI().isCPUStringValid(CPU))
9527     return Error(L, "Unknown CPU name");
9528 
9529   bool WasThumb = isThumb();
9530   MCSubtargetInfo &STI = copySTI();
9531   STI.setDefaultFeatures(CPU, "");
9532   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
9533   FixModeAfterArchChange(WasThumb, L);
9534 
9535   return false;
9536 }
9537 
9538 /// parseDirectiveFPU
9539 ///  ::= .fpu str
9540 bool ARMAsmParser::parseDirectiveFPU(SMLoc L) {
9541   SMLoc FPUNameLoc = getTok().getLoc();
9542   StringRef FPU = getParser().parseStringToEndOfStatement().trim();
9543 
9544   unsigned ID = ARM::parseFPU(FPU);
9545   std::vector<StringRef> Features;
9546   if (!ARM::getFPUFeatures(ID, Features))
9547     return Error(FPUNameLoc, "Unknown FPU name");
9548 
9549   MCSubtargetInfo &STI = copySTI();
9550   for (auto Feature : Features)
9551     STI.ApplyFeatureFlag(Feature);
9552   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
9553 
9554   getTargetStreamer().emitFPU(ID);
9555   return false;
9556 }
9557 
9558 /// parseDirectiveFnStart
9559 ///  ::= .fnstart
9560 bool ARMAsmParser::parseDirectiveFnStart(SMLoc L) {
9561   if (parseToken(AsmToken::EndOfStatement,
9562                  "unexpected token in '.fnstart' directive"))
9563     return true;
9564 
9565   if (UC.hasFnStart()) {
9566     Error(L, ".fnstart starts before the end of previous one");
9567     UC.emitFnStartLocNotes();
9568     return true;
9569   }
9570 
9571   // Reset the unwind directives parser state
9572   UC.reset();
9573 
9574   getTargetStreamer().emitFnStart();
9575 
9576   UC.recordFnStart(L);
9577   return false;
9578 }
9579 
9580 /// parseDirectiveFnEnd
9581 ///  ::= .fnend
9582 bool ARMAsmParser::parseDirectiveFnEnd(SMLoc L) {
9583   if (parseToken(AsmToken::EndOfStatement,
9584                  "unexpected token in '.fnend' directive"))
9585     return true;
9586   // Check the ordering of unwind directives
9587   if (!UC.hasFnStart())
9588     return Error(L, ".fnstart must precede .fnend directive");
9589 
9590   // Reset the unwind directives parser state
9591   getTargetStreamer().emitFnEnd();
9592 
9593   UC.reset();
9594   return false;
9595 }
9596 
9597 /// parseDirectiveCantUnwind
9598 ///  ::= .cantunwind
9599 bool ARMAsmParser::parseDirectiveCantUnwind(SMLoc L) {
9600   if (parseToken(AsmToken::EndOfStatement,
9601                  "unexpected token in '.cantunwind' directive"))
9602     return true;
9603 
9604   UC.recordCantUnwind(L);
9605   // Check the ordering of unwind directives
9606   if (check(!UC.hasFnStart(), L, ".fnstart must precede .cantunwind directive"))
9607     return true;
9608 
9609   if (UC.hasHandlerData()) {
9610     Error(L, ".cantunwind can't be used with .handlerdata directive");
9611     UC.emitHandlerDataLocNotes();
9612     return true;
9613   }
9614   if (UC.hasPersonality()) {
9615     Error(L, ".cantunwind can't be used with .personality directive");
9616     UC.emitPersonalityLocNotes();
9617     return true;
9618   }
9619 
9620   getTargetStreamer().emitCantUnwind();
9621   return false;
9622 }
9623 
9624 /// parseDirectivePersonality
9625 ///  ::= .personality name
9626 bool ARMAsmParser::parseDirectivePersonality(SMLoc L) {
9627   MCAsmParser &Parser = getParser();
9628   bool HasExistingPersonality = UC.hasPersonality();
9629 
9630   // Parse the name of the personality routine
9631   if (Parser.getTok().isNot(AsmToken::Identifier))
9632     return Error(L, "unexpected input in .personality directive.");
9633   StringRef Name(Parser.getTok().getIdentifier());
9634   Parser.Lex();
9635 
9636   if (parseToken(AsmToken::EndOfStatement,
9637                  "unexpected token in '.personality' directive"))
9638     return true;
9639 
9640   UC.recordPersonality(L);
9641 
9642   // Check the ordering of unwind directives
9643   if (!UC.hasFnStart())
9644     return Error(L, ".fnstart must precede .personality directive");
9645   if (UC.cantUnwind()) {
9646     Error(L, ".personality can't be used with .cantunwind directive");
9647     UC.emitCantUnwindLocNotes();
9648     return true;
9649   }
9650   if (UC.hasHandlerData()) {
9651     Error(L, ".personality must precede .handlerdata directive");
9652     UC.emitHandlerDataLocNotes();
9653     return true;
9654   }
9655   if (HasExistingPersonality) {
9656     Error(L, "multiple personality directives");
9657     UC.emitPersonalityLocNotes();
9658     return true;
9659   }
9660 
9661   MCSymbol *PR = getParser().getContext().getOrCreateSymbol(Name);
9662   getTargetStreamer().emitPersonality(PR);
9663   return false;
9664 }
9665 
9666 /// parseDirectiveHandlerData
9667 ///  ::= .handlerdata
9668 bool ARMAsmParser::parseDirectiveHandlerData(SMLoc L) {
9669   if (parseToken(AsmToken::EndOfStatement,
9670                  "unexpected token in '.handlerdata' directive"))
9671     return true;
9672 
9673   UC.recordHandlerData(L);
9674   // Check the ordering of unwind directives
9675   if (!UC.hasFnStart())
9676     return Error(L, ".fnstart must precede .personality directive");
9677   if (UC.cantUnwind()) {
9678     Error(L, ".handlerdata can't be used with .cantunwind directive");
9679     UC.emitCantUnwindLocNotes();
9680     return true;
9681   }
9682 
9683   getTargetStreamer().emitHandlerData();
9684   return false;
9685 }
9686 
9687 /// parseDirectiveSetFP
9688 ///  ::= .setfp fpreg, spreg [, offset]
9689 bool ARMAsmParser::parseDirectiveSetFP(SMLoc L) {
9690   MCAsmParser &Parser = getParser();
9691   // Check the ordering of unwind directives
9692   if (check(!UC.hasFnStart(), L, ".fnstart must precede .setfp directive") ||
9693       check(UC.hasHandlerData(), L,
9694             ".setfp must precede .handlerdata directive"))
9695     return true;
9696 
9697   // Parse fpreg
9698   SMLoc FPRegLoc = Parser.getTok().getLoc();
9699   int FPReg = tryParseRegister();
9700 
9701   if (check(FPReg == -1, FPRegLoc, "frame pointer register expected") ||
9702       Parser.parseToken(AsmToken::Comma, "comma expected"))
9703     return true;
9704 
9705   // Parse spreg
9706   SMLoc SPRegLoc = Parser.getTok().getLoc();
9707   int SPReg = tryParseRegister();
9708   if (check(SPReg == -1, SPRegLoc, "stack pointer register expected") ||
9709       check(SPReg != ARM::SP && SPReg != UC.getFPReg(), SPRegLoc,
9710             "register should be either $sp or the latest fp register"))
9711     return true;
9712 
9713   // Update the frame pointer register
9714   UC.saveFPReg(FPReg);
9715 
9716   // Parse offset
9717   int64_t Offset = 0;
9718   if (Parser.parseOptionalToken(AsmToken::Comma)) {
9719     if (Parser.getTok().isNot(AsmToken::Hash) &&
9720         Parser.getTok().isNot(AsmToken::Dollar))
9721       return Error(Parser.getTok().getLoc(), "'#' expected");
9722     Parser.Lex(); // skip hash token.
9723 
9724     const MCExpr *OffsetExpr;
9725     SMLoc ExLoc = Parser.getTok().getLoc();
9726     SMLoc EndLoc;
9727     if (getParser().parseExpression(OffsetExpr, EndLoc))
9728       return Error(ExLoc, "malformed setfp offset");
9729     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
9730     if (check(!CE, ExLoc, "setfp offset must be an immediate"))
9731       return true;
9732     Offset = CE->getValue();
9733   }
9734 
9735   if (Parser.parseToken(AsmToken::EndOfStatement))
9736     return true;
9737 
9738   getTargetStreamer().emitSetFP(static_cast<unsigned>(FPReg),
9739                                 static_cast<unsigned>(SPReg), Offset);
9740   return false;
9741 }
9742 
9743 /// parseDirective
9744 ///  ::= .pad offset
9745 bool ARMAsmParser::parseDirectivePad(SMLoc L) {
9746   MCAsmParser &Parser = getParser();
9747   // Check the ordering of unwind directives
9748   if (!UC.hasFnStart())
9749     return Error(L, ".fnstart must precede .pad directive");
9750   if (UC.hasHandlerData())
9751     return Error(L, ".pad must precede .handlerdata directive");
9752 
9753   // Parse the offset
9754   if (Parser.getTok().isNot(AsmToken::Hash) &&
9755       Parser.getTok().isNot(AsmToken::Dollar))
9756     return Error(Parser.getTok().getLoc(), "'#' expected");
9757   Parser.Lex(); // skip hash token.
9758 
9759   const MCExpr *OffsetExpr;
9760   SMLoc ExLoc = Parser.getTok().getLoc();
9761   SMLoc EndLoc;
9762   if (getParser().parseExpression(OffsetExpr, EndLoc))
9763     return Error(ExLoc, "malformed pad offset");
9764   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
9765   if (!CE)
9766     return Error(ExLoc, "pad offset must be an immediate");
9767 
9768   if (parseToken(AsmToken::EndOfStatement,
9769                  "unexpected token in '.pad' directive"))
9770     return true;
9771 
9772   getTargetStreamer().emitPad(CE->getValue());
9773   return false;
9774 }
9775 
9776 /// parseDirectiveRegSave
9777 ///  ::= .save  { registers }
9778 ///  ::= .vsave { registers }
9779 bool ARMAsmParser::parseDirectiveRegSave(SMLoc L, bool IsVector) {
9780   // Check the ordering of unwind directives
9781   if (!UC.hasFnStart())
9782     return Error(L, ".fnstart must precede .save or .vsave directives");
9783   if (UC.hasHandlerData())
9784     return Error(L, ".save or .vsave must precede .handlerdata directive");
9785 
9786   // RAII object to make sure parsed operands are deleted.
9787   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> Operands;
9788 
9789   // Parse the register list
9790   if (parseRegisterList(Operands) ||
9791       parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
9792     return true;
9793   ARMOperand &Op = (ARMOperand &)*Operands[0];
9794   if (!IsVector && !Op.isRegList())
9795     return Error(L, ".save expects GPR registers");
9796   if (IsVector && !Op.isDPRRegList())
9797     return Error(L, ".vsave expects DPR registers");
9798 
9799   getTargetStreamer().emitRegSave(Op.getRegList(), IsVector);
9800   return false;
9801 }
9802 
9803 /// parseDirectiveInst
9804 ///  ::= .inst opcode [, ...]
9805 ///  ::= .inst.n opcode [, ...]
9806 ///  ::= .inst.w opcode [, ...]
9807 bool ARMAsmParser::parseDirectiveInst(SMLoc Loc, char Suffix) {
9808   int Width = 4;
9809 
9810   if (isThumb()) {
9811     switch (Suffix) {
9812     case 'n':
9813       Width = 2;
9814       break;
9815     case 'w':
9816       break;
9817     default:
9818       return Error(Loc, "cannot determine Thumb instruction size, "
9819                         "use inst.n/inst.w instead");
9820     }
9821   } else {
9822     if (Suffix)
9823       return Error(Loc, "width suffixes are invalid in ARM mode");
9824   }
9825 
9826   auto parseOne = [&]() -> bool {
9827     const MCExpr *Expr;
9828     if (getParser().parseExpression(Expr))
9829       return true;
9830     const MCConstantExpr *Value = dyn_cast_or_null<MCConstantExpr>(Expr);
9831     if (!Value) {
9832       return Error(Loc, "expected constant expression");
9833     }
9834 
9835     switch (Width) {
9836     case 2:
9837       if (Value->getValue() > 0xffff)
9838         return Error(Loc, "inst.n operand is too big, use inst.w instead");
9839       break;
9840     case 4:
9841       if (Value->getValue() > 0xffffffff)
9842         return Error(Loc, StringRef(Suffix ? "inst.w" : "inst") +
9843                               " operand is too big");
9844       break;
9845     default:
9846       llvm_unreachable("only supported widths are 2 and 4");
9847     }
9848 
9849     getTargetStreamer().emitInst(Value->getValue(), Suffix);
9850     return false;
9851   };
9852 
9853   if (parseOptionalToken(AsmToken::EndOfStatement))
9854     return Error(Loc, "expected expression following directive");
9855   if (parseMany(parseOne))
9856     return true;
9857   return false;
9858 }
9859 
9860 /// parseDirectiveLtorg
9861 ///  ::= .ltorg | .pool
9862 bool ARMAsmParser::parseDirectiveLtorg(SMLoc L) {
9863   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
9864     return true;
9865   getTargetStreamer().emitCurrentConstantPool();
9866   return false;
9867 }
9868 
9869 bool ARMAsmParser::parseDirectiveEven(SMLoc L) {
9870   const MCSection *Section = getStreamer().getCurrentSectionOnly();
9871 
9872   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
9873     return true;
9874 
9875   if (!Section) {
9876     getStreamer().InitSections(false);
9877     Section = getStreamer().getCurrentSectionOnly();
9878   }
9879 
9880   assert(Section && "must have section to emit alignment");
9881   if (Section->UseCodeAlign())
9882     getStreamer().EmitCodeAlignment(2);
9883   else
9884     getStreamer().EmitValueToAlignment(2);
9885 
9886   return false;
9887 }
9888 
9889 /// parseDirectivePersonalityIndex
9890 ///   ::= .personalityindex index
9891 bool ARMAsmParser::parseDirectivePersonalityIndex(SMLoc L) {
9892   MCAsmParser &Parser = getParser();
9893   bool HasExistingPersonality = UC.hasPersonality();
9894 
9895   const MCExpr *IndexExpression;
9896   SMLoc IndexLoc = Parser.getTok().getLoc();
9897   if (Parser.parseExpression(IndexExpression) ||
9898       parseToken(AsmToken::EndOfStatement,
9899                  "unexpected token in '.personalityindex' directive")) {
9900     return true;
9901   }
9902 
9903   UC.recordPersonalityIndex(L);
9904 
9905   if (!UC.hasFnStart()) {
9906     return Error(L, ".fnstart must precede .personalityindex directive");
9907   }
9908   if (UC.cantUnwind()) {
9909     Error(L, ".personalityindex cannot be used with .cantunwind");
9910     UC.emitCantUnwindLocNotes();
9911     return true;
9912   }
9913   if (UC.hasHandlerData()) {
9914     Error(L, ".personalityindex must precede .handlerdata directive");
9915     UC.emitHandlerDataLocNotes();
9916     return true;
9917   }
9918   if (HasExistingPersonality) {
9919     Error(L, "multiple personality directives");
9920     UC.emitPersonalityLocNotes();
9921     return true;
9922   }
9923 
9924   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(IndexExpression);
9925   if (!CE)
9926     return Error(IndexLoc, "index must be a constant number");
9927   if (CE->getValue() < 0 || CE->getValue() >= ARM::EHABI::NUM_PERSONALITY_INDEX)
9928     return Error(IndexLoc,
9929                  "personality routine index should be in range [0-3]");
9930 
9931   getTargetStreamer().emitPersonalityIndex(CE->getValue());
9932   return false;
9933 }
9934 
9935 /// parseDirectiveUnwindRaw
9936 ///   ::= .unwind_raw offset, opcode [, opcode...]
9937 bool ARMAsmParser::parseDirectiveUnwindRaw(SMLoc L) {
9938   MCAsmParser &Parser = getParser();
9939   int64_t StackOffset;
9940   const MCExpr *OffsetExpr;
9941   SMLoc OffsetLoc = getLexer().getLoc();
9942 
9943   if (!UC.hasFnStart())
9944     return Error(L, ".fnstart must precede .unwind_raw directives");
9945   if (getParser().parseExpression(OffsetExpr))
9946     return Error(OffsetLoc, "expected expression");
9947 
9948   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
9949   if (!CE)
9950     return Error(OffsetLoc, "offset must be a constant");
9951 
9952   StackOffset = CE->getValue();
9953 
9954   if (Parser.parseToken(AsmToken::Comma, "expected comma"))
9955     return true;
9956 
9957   SmallVector<uint8_t, 16> Opcodes;
9958 
9959   auto parseOne = [&]() -> bool {
9960     const MCExpr *OE;
9961     SMLoc OpcodeLoc = getLexer().getLoc();
9962     if (check(getLexer().is(AsmToken::EndOfStatement) ||
9963                   Parser.parseExpression(OE),
9964               OpcodeLoc, "expected opcode expression"))
9965       return true;
9966     const MCConstantExpr *OC = dyn_cast<MCConstantExpr>(OE);
9967     if (!OC)
9968       return Error(OpcodeLoc, "opcode value must be a constant");
9969     const int64_t Opcode = OC->getValue();
9970     if (Opcode & ~0xff)
9971       return Error(OpcodeLoc, "invalid opcode");
9972     Opcodes.push_back(uint8_t(Opcode));
9973     return false;
9974   };
9975 
9976   // Must have at least 1 element
9977   SMLoc OpcodeLoc = getLexer().getLoc();
9978   if (parseOptionalToken(AsmToken::EndOfStatement))
9979     return Error(OpcodeLoc, "expected opcode expression");
9980   if (parseMany(parseOne))
9981     return true;
9982 
9983   getTargetStreamer().emitUnwindRaw(StackOffset, Opcodes);
9984   return false;
9985 }
9986 
9987 /// parseDirectiveTLSDescSeq
9988 ///   ::= .tlsdescseq tls-variable
9989 bool ARMAsmParser::parseDirectiveTLSDescSeq(SMLoc L) {
9990   MCAsmParser &Parser = getParser();
9991 
9992   if (getLexer().isNot(AsmToken::Identifier))
9993     return TokError("expected variable after '.tlsdescseq' directive");
9994 
9995   const MCSymbolRefExpr *SRE =
9996     MCSymbolRefExpr::create(Parser.getTok().getIdentifier(),
9997                             MCSymbolRefExpr::VK_ARM_TLSDESCSEQ, getContext());
9998   Lex();
9999 
10000   if (parseToken(AsmToken::EndOfStatement,
10001                  "unexpected token in '.tlsdescseq' directive"))
10002     return true;
10003 
10004   getTargetStreamer().AnnotateTLSDescriptorSequence(SRE);
10005   return false;
10006 }
10007 
10008 /// parseDirectiveMovSP
10009 ///  ::= .movsp reg [, #offset]
10010 bool ARMAsmParser::parseDirectiveMovSP(SMLoc L) {
10011   MCAsmParser &Parser = getParser();
10012   if (!UC.hasFnStart())
10013     return Error(L, ".fnstart must precede .movsp directives");
10014   if (UC.getFPReg() != ARM::SP)
10015     return Error(L, "unexpected .movsp directive");
10016 
10017   SMLoc SPRegLoc = Parser.getTok().getLoc();
10018   int SPReg = tryParseRegister();
10019   if (SPReg == -1)
10020     return Error(SPRegLoc, "register expected");
10021   if (SPReg == ARM::SP || SPReg == ARM::PC)
10022     return Error(SPRegLoc, "sp and pc are not permitted in .movsp directive");
10023 
10024   int64_t Offset = 0;
10025   if (Parser.parseOptionalToken(AsmToken::Comma)) {
10026     if (Parser.parseToken(AsmToken::Hash, "expected #constant"))
10027       return true;
10028 
10029     const MCExpr *OffsetExpr;
10030     SMLoc OffsetLoc = Parser.getTok().getLoc();
10031 
10032     if (Parser.parseExpression(OffsetExpr))
10033       return Error(OffsetLoc, "malformed offset expression");
10034 
10035     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
10036     if (!CE)
10037       return Error(OffsetLoc, "offset must be an immediate constant");
10038 
10039     Offset = CE->getValue();
10040   }
10041 
10042   if (parseToken(AsmToken::EndOfStatement,
10043                  "unexpected token in '.movsp' directive"))
10044     return true;
10045 
10046   getTargetStreamer().emitMovSP(SPReg, Offset);
10047   UC.saveFPReg(SPReg);
10048 
10049   return false;
10050 }
10051 
10052 /// parseDirectiveObjectArch
10053 ///   ::= .object_arch name
10054 bool ARMAsmParser::parseDirectiveObjectArch(SMLoc L) {
10055   MCAsmParser &Parser = getParser();
10056   if (getLexer().isNot(AsmToken::Identifier))
10057     return Error(getLexer().getLoc(), "unexpected token");
10058 
10059   StringRef Arch = Parser.getTok().getString();
10060   SMLoc ArchLoc = Parser.getTok().getLoc();
10061   Lex();
10062 
10063   ARM::ArchKind ID = ARM::parseArch(Arch);
10064 
10065   if (ID == ARM::ArchKind::INVALID)
10066     return Error(ArchLoc, "unknown architecture '" + Arch + "'");
10067   if (parseToken(AsmToken::EndOfStatement))
10068     return true;
10069 
10070   getTargetStreamer().emitObjectArch(ID);
10071   return false;
10072 }
10073 
10074 /// parseDirectiveAlign
10075 ///   ::= .align
10076 bool ARMAsmParser::parseDirectiveAlign(SMLoc L) {
10077   // NOTE: if this is not the end of the statement, fall back to the target
10078   // agnostic handling for this directive which will correctly handle this.
10079   if (parseOptionalToken(AsmToken::EndOfStatement)) {
10080     // '.align' is target specifically handled to mean 2**2 byte alignment.
10081     const MCSection *Section = getStreamer().getCurrentSectionOnly();
10082     assert(Section && "must have section to emit alignment");
10083     if (Section->UseCodeAlign())
10084       getStreamer().EmitCodeAlignment(4, 0);
10085     else
10086       getStreamer().EmitValueToAlignment(4, 0, 1, 0);
10087     return false;
10088   }
10089   return true;
10090 }
10091 
10092 /// parseDirectiveThumbSet
10093 ///  ::= .thumb_set name, value
10094 bool ARMAsmParser::parseDirectiveThumbSet(SMLoc L) {
10095   MCAsmParser &Parser = getParser();
10096 
10097   StringRef Name;
10098   if (check(Parser.parseIdentifier(Name),
10099             "expected identifier after '.thumb_set'") ||
10100       parseToken(AsmToken::Comma, "expected comma after name '" + Name + "'"))
10101     return true;
10102 
10103   MCSymbol *Sym;
10104   const MCExpr *Value;
10105   if (MCParserUtils::parseAssignmentExpression(Name, /* allow_redef */ true,
10106                                                Parser, Sym, Value))
10107     return true;
10108 
10109   getTargetStreamer().emitThumbSet(Sym, Value);
10110   return false;
10111 }
10112 
10113 /// Force static initialization.
10114 extern "C" void LLVMInitializeARMAsmParser() {
10115   RegisterMCAsmParser<ARMAsmParser> X(getTheARMLETarget());
10116   RegisterMCAsmParser<ARMAsmParser> Y(getTheARMBETarget());
10117   RegisterMCAsmParser<ARMAsmParser> A(getTheThumbLETarget());
10118   RegisterMCAsmParser<ARMAsmParser> B(getTheThumbBETarget());
10119 }
10120 
10121 #define GET_REGISTER_MATCHER
10122 #define GET_SUBTARGET_FEATURE_NAME
10123 #define GET_MATCHER_IMPLEMENTATION
10124 #define GET_MNEMONIC_SPELL_CHECKER
10125 #include "ARMGenAsmMatcher.inc"
10126 
10127 // Some diagnostics need to vary with subtarget features, so they are handled
10128 // here. For example, the DPR class has either 16 or 32 registers, depending
10129 // on the FPU available.
10130 const char *
10131 ARMAsmParser::getCustomOperandDiag(ARMMatchResultTy MatchError) {
10132   switch (MatchError) {
10133   // rGPR contains sp starting with ARMv8.
10134   case Match_rGPR:
10135     return hasV8Ops() ? "operand must be a register in range [r0, r14]"
10136                       : "operand must be a register in range [r0, r12] or r14";
10137   // DPR contains 16 registers for some FPUs, and 32 for others.
10138   case Match_DPR:
10139     return hasD16() ? "operand must be a register in range [d0, d15]"
10140                     : "operand must be a register in range [d0, d31]";
10141 
10142   // For all other diags, use the static string from tablegen.
10143   default:
10144     return getMatchKindDiag(MatchError);
10145   }
10146 }
10147 
10148 // Process the list of near-misses, throwing away ones we don't want to report
10149 // to the user, and converting the rest to a source location and string that
10150 // should be reported.
10151 void
10152 ARMAsmParser::FilterNearMisses(SmallVectorImpl<NearMissInfo> &NearMissesIn,
10153                                SmallVectorImpl<NearMissMessage> &NearMissesOut,
10154                                SMLoc IDLoc, OperandVector &Operands) {
10155   // TODO: If operand didn't match, sub in a dummy one and run target
10156   // predicate, so that we can avoid reporting near-misses that are invalid?
10157   // TODO: Many operand types dont have SuperClasses set, so we report
10158   // redundant ones.
10159   // TODO: Some operands are superclasses of registers (e.g.
10160   // MCK_RegShiftedImm), we don't have any way to represent that currently.
10161   // TODO: This is not all ARM-specific, can some of it be factored out?
10162 
10163   // Record some information about near-misses that we have already seen, so
10164   // that we can avoid reporting redundant ones. For example, if there are
10165   // variants of an instruction that take 8- and 16-bit immediates, we want
10166   // to only report the widest one.
10167   std::multimap<unsigned, unsigned> OperandMissesSeen;
10168   SmallSet<uint64_t, 4> FeatureMissesSeen;
10169 
10170   // Process the near-misses in reverse order, so that we see more general ones
10171   // first, and so can avoid emitting more specific ones.
10172   for (NearMissInfo &I : reverse(NearMissesIn)) {
10173     switch (I.getKind()) {
10174     case NearMissInfo::NearMissOperand: {
10175       SMLoc OperandLoc =
10176           ((ARMOperand &)*Operands[I.getOperandIndex()]).getStartLoc();
10177       const char *OperandDiag =
10178           getCustomOperandDiag((ARMMatchResultTy)I.getOperandError());
10179 
10180       // If we have already emitted a message for a superclass, don't also report
10181       // the sub-class. We consider all operand classes that we don't have a
10182       // specialised diagnostic for to be equal for the propose of this check,
10183       // so that we don't report the generic error multiple times on the same
10184       // operand.
10185       unsigned DupCheckMatchClass = OperandDiag ? I.getOperandClass() : ~0U;
10186       auto PrevReports = OperandMissesSeen.equal_range(I.getOperandIndex());
10187       if (std::any_of(PrevReports.first, PrevReports.second,
10188                       [DupCheckMatchClass](
10189                           const std::pair<unsigned, unsigned> Pair) {
10190             if (DupCheckMatchClass == ~0U || Pair.second == ~0U)
10191               return Pair.second == DupCheckMatchClass;
10192             else
10193               return isSubclass((MatchClassKind)DupCheckMatchClass,
10194                                 (MatchClassKind)Pair.second);
10195           }))
10196         break;
10197       OperandMissesSeen.insert(
10198           std::make_pair(I.getOperandIndex(), DupCheckMatchClass));
10199 
10200       NearMissMessage Message;
10201       Message.Loc = OperandLoc;
10202       if (OperandDiag) {
10203         Message.Message = OperandDiag;
10204       } else if (I.getOperandClass() == InvalidMatchClass) {
10205         Message.Message = "too many operands for instruction";
10206       } else {
10207         Message.Message = "invalid operand for instruction";
10208         DEBUG(dbgs() << "Missing diagnostic string for operand class " <<
10209               getMatchClassName((MatchClassKind)I.getOperandClass())
10210               << I.getOperandClass() << ", error " << I.getOperandError()
10211               << ", opcode " << MII.getName(I.getOpcode()) << "\n");
10212       }
10213       NearMissesOut.emplace_back(Message);
10214       break;
10215     }
10216     case NearMissInfo::NearMissFeature: {
10217       uint64_t MissingFeatures = I.getFeatures();
10218       // Don't report the same set of features twice.
10219       if (FeatureMissesSeen.count(MissingFeatures))
10220         break;
10221       FeatureMissesSeen.insert(MissingFeatures);
10222 
10223       // Special case: don't report a feature set which includes arm-mode for
10224       // targets that don't have ARM mode.
10225       if ((MissingFeatures & Feature_IsARM) && !hasARM())
10226         break;
10227       // Don't report any near-misses that both require switching instruction
10228       // set, and adding other subtarget features.
10229       if (isThumb() && (MissingFeatures & Feature_IsARM) &&
10230           (MissingFeatures & ~Feature_IsARM))
10231         break;
10232       if (!isThumb() && (MissingFeatures & Feature_IsThumb) &&
10233           (MissingFeatures & ~Feature_IsThumb))
10234         break;
10235       if (!isThumb() && (MissingFeatures & Feature_IsThumb2) &&
10236           (MissingFeatures & ~(Feature_IsThumb2 | Feature_IsThumb)))
10237         break;
10238 
10239       NearMissMessage Message;
10240       Message.Loc = IDLoc;
10241       raw_svector_ostream OS(Message.Message);
10242 
10243       OS << "instruction requires:";
10244       uint64_t Mask = 1;
10245       for (unsigned MaskPos = 0; MaskPos < (sizeof(MissingFeatures) * 8 - 1);
10246            ++MaskPos) {
10247         if (MissingFeatures & Mask) {
10248           OS << " " << getSubtargetFeatureName(MissingFeatures & Mask);
10249         }
10250         Mask <<= 1;
10251       }
10252       NearMissesOut.emplace_back(Message);
10253 
10254       break;
10255     }
10256     case NearMissInfo::NearMissPredicate: {
10257       NearMissMessage Message;
10258       Message.Loc = IDLoc;
10259       switch (I.getPredicateError()) {
10260       case Match_RequiresNotITBlock:
10261         Message.Message = "flag setting instruction only valid outside IT block";
10262         break;
10263       case Match_RequiresITBlock:
10264         Message.Message = "instruction only valid inside IT block";
10265         break;
10266       case Match_RequiresV6:
10267         Message.Message = "instruction variant requires ARMv6 or later";
10268         break;
10269       case Match_RequiresThumb2:
10270         Message.Message = "instruction variant requires Thumb2";
10271         break;
10272       case Match_RequiresV8:
10273         Message.Message = "instruction variant requires ARMv8 or later";
10274         break;
10275       case Match_RequiresFlagSetting:
10276         Message.Message = "no flag-preserving variant of this instruction available";
10277         break;
10278       case Match_InvalidOperand:
10279         Message.Message = "invalid operand for instruction";
10280         break;
10281       default:
10282         llvm_unreachable("Unhandled target predicate error");
10283         break;
10284       }
10285       NearMissesOut.emplace_back(Message);
10286       break;
10287     }
10288     case NearMissInfo::NearMissTooFewOperands: {
10289       SMLoc EndLoc = ((ARMOperand &)*Operands.back()).getEndLoc();
10290       NearMissesOut.emplace_back(
10291           NearMissMessage{ EndLoc, StringRef("too few operands for instruction") });
10292       break;
10293     }
10294     case NearMissInfo::NoNearMiss:
10295       // This should never leave the matcher.
10296       llvm_unreachable("not a near-miss");
10297       break;
10298     }
10299   }
10300 }
10301 
10302 void ARMAsmParser::ReportNearMisses(SmallVectorImpl<NearMissInfo> &NearMisses,
10303                                     SMLoc IDLoc, OperandVector &Operands) {
10304   SmallVector<NearMissMessage, 4> Messages;
10305   FilterNearMisses(NearMisses, Messages, IDLoc, Operands);
10306 
10307   if (Messages.size() == 0) {
10308     // No near-misses were found, so the best we can do is "invalid
10309     // instruction".
10310     Error(IDLoc, "invalid instruction");
10311   } else if (Messages.size() == 1) {
10312     // One near miss was found, report it as the sole error.
10313     Error(Messages[0].Loc, Messages[0].Message);
10314   } else {
10315     // More than one near miss, so report a generic "invalid instruction"
10316     // error, followed by notes for each of the near-misses.
10317     Error(IDLoc, "invalid instruction, any one of the following would fix this:");
10318     for (auto &M : Messages) {
10319       Note(M.Loc, M.Message);
10320     }
10321   }
10322 }
10323 
10324 // FIXME: This structure should be moved inside ARMTargetParser
10325 // when we start to table-generate them, and we can use the ARM
10326 // flags below, that were generated by table-gen.
10327 static const struct {
10328   const unsigned Kind;
10329   const uint64_t ArchCheck;
10330   const FeatureBitset Features;
10331 } Extensions[] = {
10332   { ARM::AEK_CRC, Feature_HasV8, {ARM::FeatureCRC} },
10333   { ARM::AEK_CRYPTO,  Feature_HasV8,
10334     {ARM::FeatureCrypto, ARM::FeatureNEON, ARM::FeatureFPARMv8} },
10335   { ARM::AEK_FP, Feature_HasV8, {ARM::FeatureFPARMv8} },
10336   { (ARM::AEK_HWDIVTHUMB | ARM::AEK_HWDIVARM), Feature_HasV7 | Feature_IsNotMClass,
10337     {ARM::FeatureHWDivThumb, ARM::FeatureHWDivARM} },
10338   { ARM::AEK_MP, Feature_HasV7 | Feature_IsNotMClass, {ARM::FeatureMP} },
10339   { ARM::AEK_SIMD, Feature_HasV8, {ARM::FeatureNEON, ARM::FeatureFPARMv8} },
10340   { ARM::AEK_SEC, Feature_HasV6K, {ARM::FeatureTrustZone} },
10341   // FIXME: Only available in A-class, isel not predicated
10342   { ARM::AEK_VIRT, Feature_HasV7, {ARM::FeatureVirtualization} },
10343   { ARM::AEK_FP16, Feature_HasV8_2a, {ARM::FeatureFPARMv8, ARM::FeatureFullFP16} },
10344   { ARM::AEK_RAS, Feature_HasV8, {ARM::FeatureRAS} },
10345   // FIXME: Unsupported extensions.
10346   { ARM::AEK_OS, Feature_None, {} },
10347   { ARM::AEK_IWMMXT, Feature_None, {} },
10348   { ARM::AEK_IWMMXT2, Feature_None, {} },
10349   { ARM::AEK_MAVERICK, Feature_None, {} },
10350   { ARM::AEK_XSCALE, Feature_None, {} },
10351 };
10352 
10353 /// parseDirectiveArchExtension
10354 ///   ::= .arch_extension [no]feature
10355 bool ARMAsmParser::parseDirectiveArchExtension(SMLoc L) {
10356   MCAsmParser &Parser = getParser();
10357 
10358   if (getLexer().isNot(AsmToken::Identifier))
10359     return Error(getLexer().getLoc(), "expected architecture extension name");
10360 
10361   StringRef Name = Parser.getTok().getString();
10362   SMLoc ExtLoc = Parser.getTok().getLoc();
10363   Lex();
10364 
10365   if (parseToken(AsmToken::EndOfStatement,
10366                  "unexpected token in '.arch_extension' directive"))
10367     return true;
10368 
10369   bool EnableFeature = true;
10370   if (Name.startswith_lower("no")) {
10371     EnableFeature = false;
10372     Name = Name.substr(2);
10373   }
10374   unsigned FeatureKind = ARM::parseArchExt(Name);
10375   if (FeatureKind == ARM::AEK_INVALID)
10376     return Error(ExtLoc, "unknown architectural extension: " + Name);
10377 
10378   for (const auto &Extension : Extensions) {
10379     if (Extension.Kind != FeatureKind)
10380       continue;
10381 
10382     if (Extension.Features.none())
10383       return Error(ExtLoc, "unsupported architectural extension: " + Name);
10384 
10385     if ((getAvailableFeatures() & Extension.ArchCheck) != Extension.ArchCheck)
10386       return Error(ExtLoc, "architectural extension '" + Name +
10387                                "' is not "
10388                                "allowed for the current base architecture");
10389 
10390     MCSubtargetInfo &STI = copySTI();
10391     FeatureBitset ToggleFeatures = EnableFeature
10392       ? (~STI.getFeatureBits() & Extension.Features)
10393       : ( STI.getFeatureBits() & Extension.Features);
10394 
10395     uint64_t Features =
10396         ComputeAvailableFeatures(STI.ToggleFeature(ToggleFeatures));
10397     setAvailableFeatures(Features);
10398     return false;
10399   }
10400 
10401   return Error(ExtLoc, "unknown architectural extension: " + Name);
10402 }
10403 
10404 // Define this matcher function after the auto-generated include so we
10405 // have the match class enum definitions.
10406 unsigned ARMAsmParser::validateTargetOperandClass(MCParsedAsmOperand &AsmOp,
10407                                                   unsigned Kind) {
10408   ARMOperand &Op = static_cast<ARMOperand &>(AsmOp);
10409   // If the kind is a token for a literal immediate, check if our asm
10410   // operand matches. This is for InstAliases which have a fixed-value
10411   // immediate in the syntax.
10412   switch (Kind) {
10413   default: break;
10414   case MCK__35_0:
10415     if (Op.isImm())
10416       if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm()))
10417         if (CE->getValue() == 0)
10418           return Match_Success;
10419     break;
10420   case MCK_ModImm:
10421     if (Op.isImm()) {
10422       const MCExpr *SOExpr = Op.getImm();
10423       int64_t Value;
10424       if (!SOExpr->evaluateAsAbsolute(Value))
10425         return Match_Success;
10426       assert((Value >= std::numeric_limits<int32_t>::min() &&
10427               Value <= std::numeric_limits<uint32_t>::max()) &&
10428              "expression value must be representable in 32 bits");
10429     }
10430     break;
10431   case MCK_rGPR:
10432     if (hasV8Ops() && Op.isReg() && Op.getReg() == ARM::SP)
10433       return Match_Success;
10434     return Match_rGPR;
10435   case MCK_GPRPair:
10436     if (Op.isReg() &&
10437         MRI->getRegClass(ARM::GPRRegClassID).contains(Op.getReg()))
10438       return Match_Success;
10439     break;
10440   }
10441   return Match_InvalidOperand;
10442 }
10443