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 using namespace llvm;
68 
69 namespace {
70 
71 enum class ImplicitItModeTy { Always, Never, ARMOnly, ThumbOnly };
72 
73 static cl::opt<ImplicitItModeTy> ImplicitItMode(
74     "arm-implicit-it", cl::init(ImplicitItModeTy::ARMOnly),
75     cl::desc("Allow conditional instructions outdside of an IT block"),
76     cl::values(clEnumValN(ImplicitItModeTy::Always, "always",
77                           "Accept in both ISAs, emit implicit ITs in Thumb"),
78                clEnumValN(ImplicitItModeTy::Never, "never",
79                           "Warn in ARM, reject in Thumb"),
80                clEnumValN(ImplicitItModeTy::ARMOnly, "arm",
81                           "Accept in ARM, reject in Thumb"),
82                clEnumValN(ImplicitItModeTy::ThumbOnly, "thumb",
83                           "Warn in ARM, emit implicit ITs in Thumb")));
84 
85 static cl::opt<bool> AddBuildAttributes("arm-add-build-attributes",
86                                         cl::init(false));
87 
88 cl::opt<bool>
89 DevDiags("arm-asm-parser-dev-diags", cl::init(false),
90          cl::desc("Use extended diagnostics, which include implementation "
91                   "details useful for development"));
92 
93 enum VectorLaneTy { NoLanes, AllLanes, IndexedLane };
94 
95 class UnwindContext {
96   using Locs = SmallVector<SMLoc, 4>;
97 
98   MCAsmParser &Parser;
99   Locs FnStartLocs;
100   Locs CantUnwindLocs;
101   Locs PersonalityLocs;
102   Locs PersonalityIndexLocs;
103   Locs HandlerDataLocs;
104   int FPReg;
105 
106 public:
107   UnwindContext(MCAsmParser &P) : Parser(P), FPReg(ARM::SP) {}
108 
109   bool hasFnStart() const { return !FnStartLocs.empty(); }
110   bool cantUnwind() const { return !CantUnwindLocs.empty(); }
111   bool hasHandlerData() const { return !HandlerDataLocs.empty(); }
112 
113   bool hasPersonality() const {
114     return !(PersonalityLocs.empty() && PersonalityIndexLocs.empty());
115   }
116 
117   void recordFnStart(SMLoc L) { FnStartLocs.push_back(L); }
118   void recordCantUnwind(SMLoc L) { CantUnwindLocs.push_back(L); }
119   void recordPersonality(SMLoc L) { PersonalityLocs.push_back(L); }
120   void recordHandlerData(SMLoc L) { HandlerDataLocs.push_back(L); }
121   void recordPersonalityIndex(SMLoc L) { PersonalityIndexLocs.push_back(L); }
122 
123   void saveFPReg(int Reg) { FPReg = Reg; }
124   int getFPReg() const { return FPReg; }
125 
126   void emitFnStartLocNotes() const {
127     for (Locs::const_iterator FI = FnStartLocs.begin(), FE = FnStartLocs.end();
128          FI != FE; ++FI)
129       Parser.Note(*FI, ".fnstart was specified here");
130   }
131 
132   void emitCantUnwindLocNotes() const {
133     for (Locs::const_iterator UI = CantUnwindLocs.begin(),
134                               UE = CantUnwindLocs.end(); UI != UE; ++UI)
135       Parser.Note(*UI, ".cantunwind was specified here");
136   }
137 
138   void emitHandlerDataLocNotes() const {
139     for (Locs::const_iterator HI = HandlerDataLocs.begin(),
140                               HE = HandlerDataLocs.end(); HI != HE; ++HI)
141       Parser.Note(*HI, ".handlerdata was specified here");
142   }
143 
144   void emitPersonalityLocNotes() const {
145     for (Locs::const_iterator PI = PersonalityLocs.begin(),
146                               PE = PersonalityLocs.end(),
147                               PII = PersonalityIndexLocs.begin(),
148                               PIE = PersonalityIndexLocs.end();
149          PI != PE || PII != PIE;) {
150       if (PI != PE && (PII == PIE || PI->getPointer() < PII->getPointer()))
151         Parser.Note(*PI++, ".personality was specified here");
152       else if (PII != PIE && (PI == PE || PII->getPointer() < PI->getPointer()))
153         Parser.Note(*PII++, ".personalityindex was specified here");
154       else
155         llvm_unreachable(".personality and .personalityindex cannot be "
156                          "at the same location");
157     }
158   }
159 
160   void reset() {
161     FnStartLocs = Locs();
162     CantUnwindLocs = Locs();
163     PersonalityLocs = Locs();
164     HandlerDataLocs = Locs();
165     PersonalityIndexLocs = Locs();
166     FPReg = ARM::SP;
167   }
168 };
169 
170 class ARMAsmParser : public MCTargetAsmParser {
171   const MCInstrInfo &MII;
172   const MCRegisterInfo *MRI;
173   UnwindContext UC;
174 
175   ARMTargetStreamer &getTargetStreamer() {
176     assert(getParser().getStreamer().getTargetStreamer() &&
177            "do not have a target streamer");
178     MCTargetStreamer &TS = *getParser().getStreamer().getTargetStreamer();
179     return static_cast<ARMTargetStreamer &>(TS);
180   }
181 
182   // Map of register aliases registers via the .req directive.
183   StringMap<unsigned> RegisterReqs;
184 
185   bool NextSymbolIsThumb;
186 
187   bool useImplicitITThumb() const {
188     return ImplicitItMode == ImplicitItModeTy::Always ||
189            ImplicitItMode == ImplicitItModeTy::ThumbOnly;
190   }
191 
192   bool useImplicitITARM() const {
193     return ImplicitItMode == ImplicitItModeTy::Always ||
194            ImplicitItMode == ImplicitItModeTy::ARMOnly;
195   }
196 
197   struct {
198     ARMCC::CondCodes Cond;    // Condition for IT block.
199     unsigned Mask:4;          // Condition mask for instructions.
200                               // Starting at first 1 (from lsb).
201                               //   '1'  condition as indicated in IT.
202                               //   '0'  inverse of condition (else).
203                               // Count of instructions in IT block is
204                               // 4 - trailingzeroes(mask)
205                               // Note that this does not have the same encoding
206                               // as in the IT instruction, which also depends
207                               // on the low bit of the condition code.
208 
209     unsigned CurPosition;     // Current position in parsing of IT
210                               // block. In range [0,4], with 0 being the IT
211                               // instruction itself. Initialized according to
212                               // count of instructions in block.  ~0U if no
213                               // active IT block.
214 
215     bool IsExplicit;          // true  - The IT instruction was present in the
216                               //         input, we should not modify it.
217                               // false - The IT instruction was added
218                               //         implicitly, we can extend it if that
219                               //         would be legal.
220   } ITState;
221 
222   SmallVector<MCInst, 4> PendingConditionalInsts;
223 
224   void flushPendingInstructions(MCStreamer &Out) override {
225     if (!inImplicitITBlock()) {
226       assert(PendingConditionalInsts.size() == 0);
227       return;
228     }
229 
230     // Emit the IT instruction
231     unsigned Mask = getITMaskEncoding();
232     MCInst ITInst;
233     ITInst.setOpcode(ARM::t2IT);
234     ITInst.addOperand(MCOperand::createImm(ITState.Cond));
235     ITInst.addOperand(MCOperand::createImm(Mask));
236     Out.EmitInstruction(ITInst, getSTI());
237 
238     // Emit the conditonal instructions
239     assert(PendingConditionalInsts.size() <= 4);
240     for (const MCInst &Inst : PendingConditionalInsts) {
241       Out.EmitInstruction(Inst, getSTI());
242     }
243     PendingConditionalInsts.clear();
244 
245     // Clear the IT state
246     ITState.Mask = 0;
247     ITState.CurPosition = ~0U;
248   }
249 
250   bool inITBlock() { return ITState.CurPosition != ~0U; }
251   bool inExplicitITBlock() { return inITBlock() && ITState.IsExplicit; }
252   bool inImplicitITBlock() { return inITBlock() && !ITState.IsExplicit; }
253 
254   bool lastInITBlock() {
255     return ITState.CurPosition == 4 - countTrailingZeros(ITState.Mask);
256   }
257 
258   void forwardITPosition() {
259     if (!inITBlock()) return;
260     // Move to the next instruction in the IT block, if there is one. If not,
261     // mark the block as done, except for implicit IT blocks, which we leave
262     // open until we find an instruction that can't be added to it.
263     unsigned TZ = countTrailingZeros(ITState.Mask);
264     if (++ITState.CurPosition == 5 - TZ && ITState.IsExplicit)
265       ITState.CurPosition = ~0U; // Done with the IT block after this.
266   }
267 
268   // Rewind the state of the current IT block, removing the last slot from it.
269   void rewindImplicitITPosition() {
270     assert(inImplicitITBlock());
271     assert(ITState.CurPosition > 1);
272     ITState.CurPosition--;
273     unsigned TZ = countTrailingZeros(ITState.Mask);
274     unsigned NewMask = 0;
275     NewMask |= ITState.Mask & (0xC << TZ);
276     NewMask |= 0x2 << TZ;
277     ITState.Mask = NewMask;
278   }
279 
280   // Rewind the state of the current IT block, removing the last slot from it.
281   // If we were at the first slot, this closes the IT block.
282   void discardImplicitITBlock() {
283     assert(inImplicitITBlock());
284     assert(ITState.CurPosition == 1);
285     ITState.CurPosition = ~0U;
286   }
287 
288   // Return the low-subreg of a given Q register.
289   unsigned getDRegFromQReg(unsigned QReg) const {
290     return MRI->getSubReg(QReg, ARM::dsub_0);
291   }
292 
293   // Get the encoding of the IT mask, as it will appear in an IT instruction.
294   unsigned getITMaskEncoding() {
295     assert(inITBlock());
296     unsigned Mask = ITState.Mask;
297     unsigned TZ = countTrailingZeros(Mask);
298     if ((ITState.Cond & 1) == 0) {
299       assert(Mask && TZ <= 3 && "illegal IT mask value!");
300       Mask ^= (0xE << TZ) & 0xF;
301     }
302     return Mask;
303   }
304 
305   // Get the condition code corresponding to the current IT block slot.
306   ARMCC::CondCodes currentITCond() {
307     unsigned MaskBit;
308     if (ITState.CurPosition == 1)
309       MaskBit = 1;
310     else
311       MaskBit = (ITState.Mask >> (5 - ITState.CurPosition)) & 1;
312 
313     return MaskBit ? ITState.Cond : ARMCC::getOppositeCondition(ITState.Cond);
314   }
315 
316   // Invert the condition of the current IT block slot without changing any
317   // other slots in the same block.
318   void invertCurrentITCondition() {
319     if (ITState.CurPosition == 1) {
320       ITState.Cond = ARMCC::getOppositeCondition(ITState.Cond);
321     } else {
322       ITState.Mask ^= 1 << (5 - ITState.CurPosition);
323     }
324   }
325 
326   // Returns true if the current IT block is full (all 4 slots used).
327   bool isITBlockFull() {
328     return inITBlock() && (ITState.Mask & 1);
329   }
330 
331   // Extend the current implicit IT block to have one more slot with the given
332   // condition code.
333   void extendImplicitITBlock(ARMCC::CondCodes Cond) {
334     assert(inImplicitITBlock());
335     assert(!isITBlockFull());
336     assert(Cond == ITState.Cond ||
337            Cond == ARMCC::getOppositeCondition(ITState.Cond));
338     unsigned TZ = countTrailingZeros(ITState.Mask);
339     unsigned NewMask = 0;
340     // Keep any existing condition bits.
341     NewMask |= ITState.Mask & (0xE << TZ);
342     // Insert the new condition bit.
343     NewMask |= (Cond == ITState.Cond) << TZ;
344     // Move the trailing 1 down one bit.
345     NewMask |= 1 << (TZ - 1);
346     ITState.Mask = NewMask;
347   }
348 
349   // Create a new implicit IT block with a dummy condition code.
350   void startImplicitITBlock() {
351     assert(!inITBlock());
352     ITState.Cond = ARMCC::AL;
353     ITState.Mask = 8;
354     ITState.CurPosition = 1;
355     ITState.IsExplicit = false;
356   }
357 
358   // Create a new explicit IT block with the given condition and mask. The mask
359   // should be in the parsed format, with a 1 implying 't', regardless of the
360   // low bit of the condition.
361   void startExplicitITBlock(ARMCC::CondCodes Cond, unsigned Mask) {
362     assert(!inITBlock());
363     ITState.Cond = Cond;
364     ITState.Mask = Mask;
365     ITState.CurPosition = 0;
366     ITState.IsExplicit = true;
367   }
368 
369   void Note(SMLoc L, const Twine &Msg, SMRange Range = None) {
370     return getParser().Note(L, Msg, Range);
371   }
372 
373   bool Warning(SMLoc L, const Twine &Msg, SMRange Range = None) {
374     return getParser().Warning(L, Msg, Range);
375   }
376 
377   bool Error(SMLoc L, const Twine &Msg, SMRange Range = None) {
378     return getParser().Error(L, Msg, Range);
379   }
380 
381   bool validatetLDMRegList(const MCInst &Inst, const OperandVector &Operands,
382                            unsigned ListNo, bool IsARPop = false);
383   bool validatetSTMRegList(const MCInst &Inst, const OperandVector &Operands,
384                            unsigned ListNo);
385 
386   int tryParseRegister();
387   bool tryParseRegisterWithWriteBack(OperandVector &);
388   int tryParseShiftRegister(OperandVector &);
389   bool parseRegisterList(OperandVector &);
390   bool parseMemory(OperandVector &);
391   bool parseOperand(OperandVector &, StringRef Mnemonic);
392   bool parsePrefix(ARMMCExpr::VariantKind &RefKind);
393   bool parseMemRegOffsetShift(ARM_AM::ShiftOpc &ShiftType,
394                               unsigned &ShiftAmount);
395   bool parseLiteralValues(unsigned Size, SMLoc L);
396   bool parseDirectiveThumb(SMLoc L);
397   bool parseDirectiveARM(SMLoc L);
398   bool parseDirectiveThumbFunc(SMLoc L);
399   bool parseDirectiveCode(SMLoc L);
400   bool parseDirectiveSyntax(SMLoc L);
401   bool parseDirectiveReq(StringRef Name, SMLoc L);
402   bool parseDirectiveUnreq(SMLoc L);
403   bool parseDirectiveArch(SMLoc L);
404   bool parseDirectiveEabiAttr(SMLoc L);
405   bool parseDirectiveCPU(SMLoc L);
406   bool parseDirectiveFPU(SMLoc L);
407   bool parseDirectiveFnStart(SMLoc L);
408   bool parseDirectiveFnEnd(SMLoc L);
409   bool parseDirectiveCantUnwind(SMLoc L);
410   bool parseDirectivePersonality(SMLoc L);
411   bool parseDirectiveHandlerData(SMLoc L);
412   bool parseDirectiveSetFP(SMLoc L);
413   bool parseDirectivePad(SMLoc L);
414   bool parseDirectiveRegSave(SMLoc L, bool IsVector);
415   bool parseDirectiveInst(SMLoc L, char Suffix = '\0');
416   bool parseDirectiveLtorg(SMLoc L);
417   bool parseDirectiveEven(SMLoc L);
418   bool parseDirectivePersonalityIndex(SMLoc L);
419   bool parseDirectiveUnwindRaw(SMLoc L);
420   bool parseDirectiveTLSDescSeq(SMLoc L);
421   bool parseDirectiveMovSP(SMLoc L);
422   bool parseDirectiveObjectArch(SMLoc L);
423   bool parseDirectiveArchExtension(SMLoc L);
424   bool parseDirectiveAlign(SMLoc L);
425   bool parseDirectiveThumbSet(SMLoc L);
426 
427   StringRef splitMnemonic(StringRef Mnemonic, unsigned &PredicationCode,
428                           bool &CarrySetting, unsigned &ProcessorIMod,
429                           StringRef &ITMask);
430   void getMnemonicAcceptInfo(StringRef Mnemonic, StringRef FullInst,
431                              bool &CanAcceptCarrySet,
432                              bool &CanAcceptPredicationCode);
433 
434   void tryConvertingToTwoOperandForm(StringRef Mnemonic, bool CarrySetting,
435                                      OperandVector &Operands);
436   bool isThumb() const {
437     // FIXME: Can tablegen auto-generate this?
438     return getSTI().getFeatureBits()[ARM::ModeThumb];
439   }
440 
441   bool isThumbOne() const {
442     return isThumb() && !getSTI().getFeatureBits()[ARM::FeatureThumb2];
443   }
444 
445   bool isThumbTwo() const {
446     return isThumb() && getSTI().getFeatureBits()[ARM::FeatureThumb2];
447   }
448 
449   bool hasThumb() const {
450     return getSTI().getFeatureBits()[ARM::HasV4TOps];
451   }
452 
453   bool hasThumb2() const {
454     return getSTI().getFeatureBits()[ARM::FeatureThumb2];
455   }
456 
457   bool hasV6Ops() const {
458     return getSTI().getFeatureBits()[ARM::HasV6Ops];
459   }
460 
461   bool hasV6T2Ops() const {
462     return getSTI().getFeatureBits()[ARM::HasV6T2Ops];
463   }
464 
465   bool hasV6MOps() const {
466     return getSTI().getFeatureBits()[ARM::HasV6MOps];
467   }
468 
469   bool hasV7Ops() const {
470     return getSTI().getFeatureBits()[ARM::HasV7Ops];
471   }
472 
473   bool hasV8Ops() const {
474     return getSTI().getFeatureBits()[ARM::HasV8Ops];
475   }
476 
477   bool hasV8MBaseline() const {
478     return getSTI().getFeatureBits()[ARM::HasV8MBaselineOps];
479   }
480 
481   bool hasV8MMainline() const {
482     return getSTI().getFeatureBits()[ARM::HasV8MMainlineOps];
483   }
484 
485   bool has8MSecExt() const {
486     return getSTI().getFeatureBits()[ARM::Feature8MSecExt];
487   }
488 
489   bool hasARM() const {
490     return !getSTI().getFeatureBits()[ARM::FeatureNoARM];
491   }
492 
493   bool hasDSP() const {
494     return getSTI().getFeatureBits()[ARM::FeatureDSP];
495   }
496 
497   bool hasD16() const {
498     return getSTI().getFeatureBits()[ARM::FeatureD16];
499   }
500 
501   bool hasV8_1aOps() const {
502     return getSTI().getFeatureBits()[ARM::HasV8_1aOps];
503   }
504 
505   bool hasRAS() const {
506     return getSTI().getFeatureBits()[ARM::FeatureRAS];
507   }
508 
509   void SwitchMode() {
510     MCSubtargetInfo &STI = copySTI();
511     uint64_t FB = ComputeAvailableFeatures(STI.ToggleFeature(ARM::ModeThumb));
512     setAvailableFeatures(FB);
513   }
514 
515   void FixModeAfterArchChange(bool WasThumb, SMLoc Loc);
516 
517   bool isMClass() const {
518     return getSTI().getFeatureBits()[ARM::FeatureMClass];
519   }
520 
521   /// @name Auto-generated Match Functions
522   /// {
523 
524 #define GET_ASSEMBLER_HEADER
525 #include "ARMGenAsmMatcher.inc"
526 
527   /// }
528 
529   OperandMatchResultTy parseITCondCode(OperandVector &);
530   OperandMatchResultTy parseCoprocNumOperand(OperandVector &);
531   OperandMatchResultTy parseCoprocRegOperand(OperandVector &);
532   OperandMatchResultTy parseCoprocOptionOperand(OperandVector &);
533   OperandMatchResultTy parseMemBarrierOptOperand(OperandVector &);
534   OperandMatchResultTy parseInstSyncBarrierOptOperand(OperandVector &);
535   OperandMatchResultTy parseProcIFlagsOperand(OperandVector &);
536   OperandMatchResultTy parseMSRMaskOperand(OperandVector &);
537   OperandMatchResultTy parseBankedRegOperand(OperandVector &);
538   OperandMatchResultTy parsePKHImm(OperandVector &O, StringRef Op, int Low,
539                                    int High);
540   OperandMatchResultTy parsePKHLSLImm(OperandVector &O) {
541     return parsePKHImm(O, "lsl", 0, 31);
542   }
543   OperandMatchResultTy parsePKHASRImm(OperandVector &O) {
544     return parsePKHImm(O, "asr", 1, 32);
545   }
546   OperandMatchResultTy parseSetEndImm(OperandVector &);
547   OperandMatchResultTy parseShifterImm(OperandVector &);
548   OperandMatchResultTy parseRotImm(OperandVector &);
549   OperandMatchResultTy parseModImm(OperandVector &);
550   OperandMatchResultTy parseBitfield(OperandVector &);
551   OperandMatchResultTy parsePostIdxReg(OperandVector &);
552   OperandMatchResultTy parseAM3Offset(OperandVector &);
553   OperandMatchResultTy parseFPImm(OperandVector &);
554   OperandMatchResultTy parseVectorList(OperandVector &);
555   OperandMatchResultTy parseVectorLane(VectorLaneTy &LaneKind, unsigned &Index,
556                                        SMLoc &EndLoc);
557 
558   // Asm Match Converter Methods
559   void cvtThumbMultiply(MCInst &Inst, const OperandVector &);
560   void cvtThumbBranches(MCInst &Inst, const OperandVector &);
561 
562   bool validateInstruction(MCInst &Inst, const OperandVector &Ops);
563   bool processInstruction(MCInst &Inst, const OperandVector &Ops, MCStreamer &Out);
564   bool shouldOmitCCOutOperand(StringRef Mnemonic, OperandVector &Operands);
565   bool shouldOmitPredicateOperand(StringRef Mnemonic, OperandVector &Operands);
566   bool isITBlockTerminator(MCInst &Inst) const;
567 
568 public:
569   enum ARMMatchResultTy {
570     Match_RequiresITBlock = FIRST_TARGET_MATCH_RESULT_TY,
571     Match_RequiresNotITBlock,
572     Match_RequiresV6,
573     Match_RequiresThumb2,
574     Match_RequiresV8,
575     Match_RequiresFlagSetting,
576 #define GET_OPERAND_DIAGNOSTIC_TYPES
577 #include "ARMGenAsmMatcher.inc"
578 
579   };
580 
581   ARMAsmParser(const MCSubtargetInfo &STI, MCAsmParser &Parser,
582                const MCInstrInfo &MII, const MCTargetOptions &Options)
583     : MCTargetAsmParser(Options, STI), MII(MII), UC(Parser) {
584     MCAsmParserExtension::Initialize(Parser);
585 
586     // Cache the MCRegisterInfo.
587     MRI = getContext().getRegisterInfo();
588 
589     // Initialize the set of available features.
590     setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
591 
592     // Add build attributes based on the selected target.
593     if (AddBuildAttributes)
594       getTargetStreamer().emitTargetAttributes(STI);
595 
596     // Not in an ITBlock to start with.
597     ITState.CurPosition = ~0U;
598 
599     NextSymbolIsThumb = false;
600   }
601 
602   // Implementation of the MCTargetAsmParser interface:
603   bool ParseRegister(unsigned &RegNo, SMLoc &StartLoc, SMLoc &EndLoc) override;
604   bool ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
605                         SMLoc NameLoc, OperandVector &Operands) override;
606   bool ParseDirective(AsmToken DirectiveID) override;
607 
608   unsigned validateTargetOperandClass(MCParsedAsmOperand &Op,
609                                       unsigned Kind) override;
610   unsigned checkTargetMatchPredicate(MCInst &Inst) override;
611 
612   bool MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
613                                OperandVector &Operands, MCStreamer &Out,
614                                uint64_t &ErrorInfo,
615                                bool MatchingInlineAsm) override;
616   unsigned MatchInstruction(OperandVector &Operands, MCInst &Inst,
617                             SmallVectorImpl<NearMissInfo> &NearMisses,
618                             bool MatchingInlineAsm, bool &EmitInITBlock,
619                             MCStreamer &Out);
620 
621   struct NearMissMessage {
622     SMLoc Loc;
623     SmallString<128> Message;
624   };
625 
626   void FilterNearMisses(SmallVectorImpl<NearMissInfo> &NearMissesIn,
627                         SmallVectorImpl<NearMissMessage> &NearMissesOut,
628                         SMLoc IDLoc, OperandVector &Operands);
629   void ReportNearMisses(SmallVectorImpl<NearMissInfo> &NearMisses, SMLoc IDLoc,
630                         OperandVector &Operands);
631 
632   void onLabelParsed(MCSymbol *Symbol) override;
633 };
634 
635 /// ARMOperand - Instances of this class represent a parsed ARM machine
636 /// operand.
637 class ARMOperand : public MCParsedAsmOperand {
638   enum KindTy {
639     k_CondCode,
640     k_CCOut,
641     k_ITCondMask,
642     k_CoprocNum,
643     k_CoprocReg,
644     k_CoprocOption,
645     k_Immediate,
646     k_MemBarrierOpt,
647     k_InstSyncBarrierOpt,
648     k_Memory,
649     k_PostIndexRegister,
650     k_MSRMask,
651     k_BankedReg,
652     k_ProcIFlags,
653     k_VectorIndex,
654     k_Register,
655     k_RegisterList,
656     k_DPRRegisterList,
657     k_SPRRegisterList,
658     k_VectorList,
659     k_VectorListAllLanes,
660     k_VectorListIndexed,
661     k_ShiftedRegister,
662     k_ShiftedImmediate,
663     k_ShifterImmediate,
664     k_RotateImmediate,
665     k_ModifiedImmediate,
666     k_ConstantPoolImmediate,
667     k_BitfieldDescriptor,
668     k_Token,
669   } Kind;
670 
671   SMLoc StartLoc, EndLoc, AlignmentLoc;
672   SmallVector<unsigned, 8> Registers;
673 
674   struct CCOp {
675     ARMCC::CondCodes Val;
676   };
677 
678   struct CopOp {
679     unsigned Val;
680   };
681 
682   struct CoprocOptionOp {
683     unsigned Val;
684   };
685 
686   struct ITMaskOp {
687     unsigned Mask:4;
688   };
689 
690   struct MBOptOp {
691     ARM_MB::MemBOpt Val;
692   };
693 
694   struct ISBOptOp {
695     ARM_ISB::InstSyncBOpt Val;
696   };
697 
698   struct IFlagsOp {
699     ARM_PROC::IFlags Val;
700   };
701 
702   struct MMaskOp {
703     unsigned Val;
704   };
705 
706   struct BankedRegOp {
707     unsigned Val;
708   };
709 
710   struct TokOp {
711     const char *Data;
712     unsigned Length;
713   };
714 
715   struct RegOp {
716     unsigned RegNum;
717   };
718 
719   // A vector register list is a sequential list of 1 to 4 registers.
720   struct VectorListOp {
721     unsigned RegNum;
722     unsigned Count;
723     unsigned LaneIndex;
724     bool isDoubleSpaced;
725   };
726 
727   struct VectorIndexOp {
728     unsigned Val;
729   };
730 
731   struct ImmOp {
732     const MCExpr *Val;
733   };
734 
735   /// Combined record for all forms of ARM address expressions.
736   struct MemoryOp {
737     unsigned BaseRegNum;
738     // Offset is in OffsetReg or OffsetImm. If both are zero, no offset
739     // was specified.
740     const MCConstantExpr *OffsetImm;  // Offset immediate value
741     unsigned OffsetRegNum;    // Offset register num, when OffsetImm == NULL
742     ARM_AM::ShiftOpc ShiftType; // Shift type for OffsetReg
743     unsigned ShiftImm;        // shift for OffsetReg.
744     unsigned Alignment;       // 0 = no alignment specified
745     // n = alignment in bytes (2, 4, 8, 16, or 32)
746     unsigned isNegative : 1;  // Negated OffsetReg? (~'U' bit)
747   };
748 
749   struct PostIdxRegOp {
750     unsigned RegNum;
751     bool isAdd;
752     ARM_AM::ShiftOpc ShiftTy;
753     unsigned ShiftImm;
754   };
755 
756   struct ShifterImmOp {
757     bool isASR;
758     unsigned Imm;
759   };
760 
761   struct RegShiftedRegOp {
762     ARM_AM::ShiftOpc ShiftTy;
763     unsigned SrcReg;
764     unsigned ShiftReg;
765     unsigned ShiftImm;
766   };
767 
768   struct RegShiftedImmOp {
769     ARM_AM::ShiftOpc ShiftTy;
770     unsigned SrcReg;
771     unsigned ShiftImm;
772   };
773 
774   struct RotImmOp {
775     unsigned Imm;
776   };
777 
778   struct ModImmOp {
779     unsigned Bits;
780     unsigned Rot;
781   };
782 
783   struct BitfieldOp {
784     unsigned LSB;
785     unsigned Width;
786   };
787 
788   union {
789     struct CCOp CC;
790     struct CopOp Cop;
791     struct CoprocOptionOp CoprocOption;
792     struct MBOptOp MBOpt;
793     struct ISBOptOp ISBOpt;
794     struct ITMaskOp ITMask;
795     struct IFlagsOp IFlags;
796     struct MMaskOp MMask;
797     struct BankedRegOp BankedReg;
798     struct TokOp Tok;
799     struct RegOp Reg;
800     struct VectorListOp VectorList;
801     struct VectorIndexOp VectorIndex;
802     struct ImmOp Imm;
803     struct MemoryOp Memory;
804     struct PostIdxRegOp PostIdxReg;
805     struct ShifterImmOp ShifterImm;
806     struct RegShiftedRegOp RegShiftedReg;
807     struct RegShiftedImmOp RegShiftedImm;
808     struct RotImmOp RotImm;
809     struct ModImmOp ModImm;
810     struct BitfieldOp Bitfield;
811   };
812 
813 public:
814   ARMOperand(KindTy K) : MCParsedAsmOperand(), Kind(K) {}
815 
816   /// getStartLoc - Get the location of the first token of this operand.
817   SMLoc getStartLoc() const override { return StartLoc; }
818 
819   /// getEndLoc - Get the location of the last token of this operand.
820   SMLoc getEndLoc() const override { return EndLoc; }
821 
822   /// getLocRange - Get the range between the first and last token of this
823   /// operand.
824   SMRange getLocRange() const { return SMRange(StartLoc, EndLoc); }
825 
826   /// getAlignmentLoc - Get the location of the Alignment token of this operand.
827   SMLoc getAlignmentLoc() const {
828     assert(Kind == k_Memory && "Invalid access!");
829     return AlignmentLoc;
830   }
831 
832   ARMCC::CondCodes getCondCode() const {
833     assert(Kind == k_CondCode && "Invalid access!");
834     return CC.Val;
835   }
836 
837   unsigned getCoproc() const {
838     assert((Kind == k_CoprocNum || Kind == k_CoprocReg) && "Invalid access!");
839     return Cop.Val;
840   }
841 
842   StringRef getToken() const {
843     assert(Kind == k_Token && "Invalid access!");
844     return StringRef(Tok.Data, Tok.Length);
845   }
846 
847   unsigned getReg() const override {
848     assert((Kind == k_Register || Kind == k_CCOut) && "Invalid access!");
849     return Reg.RegNum;
850   }
851 
852   const SmallVectorImpl<unsigned> &getRegList() const {
853     assert((Kind == k_RegisterList || Kind == k_DPRRegisterList ||
854             Kind == k_SPRRegisterList) && "Invalid access!");
855     return Registers;
856   }
857 
858   const MCExpr *getImm() const {
859     assert(isImm() && "Invalid access!");
860     return Imm.Val;
861   }
862 
863   const MCExpr *getConstantPoolImm() const {
864     assert(isConstantPoolImm() && "Invalid access!");
865     return Imm.Val;
866   }
867 
868   unsigned getVectorIndex() const {
869     assert(Kind == k_VectorIndex && "Invalid access!");
870     return VectorIndex.Val;
871   }
872 
873   ARM_MB::MemBOpt getMemBarrierOpt() const {
874     assert(Kind == k_MemBarrierOpt && "Invalid access!");
875     return MBOpt.Val;
876   }
877 
878   ARM_ISB::InstSyncBOpt getInstSyncBarrierOpt() const {
879     assert(Kind == k_InstSyncBarrierOpt && "Invalid access!");
880     return ISBOpt.Val;
881   }
882 
883   ARM_PROC::IFlags getProcIFlags() const {
884     assert(Kind == k_ProcIFlags && "Invalid access!");
885     return IFlags.Val;
886   }
887 
888   unsigned getMSRMask() const {
889     assert(Kind == k_MSRMask && "Invalid access!");
890     return MMask.Val;
891   }
892 
893   unsigned getBankedReg() const {
894     assert(Kind == k_BankedReg && "Invalid access!");
895     return BankedReg.Val;
896   }
897 
898   bool isCoprocNum() const { return Kind == k_CoprocNum; }
899   bool isCoprocReg() const { return Kind == k_CoprocReg; }
900   bool isCoprocOption() const { return Kind == k_CoprocOption; }
901   bool isCondCode() const { return Kind == k_CondCode; }
902   bool isCCOut() const { return Kind == k_CCOut; }
903   bool isITMask() const { return Kind == k_ITCondMask; }
904   bool isITCondCode() const { return Kind == k_CondCode; }
905   bool isImm() const override {
906     return Kind == k_Immediate;
907   }
908 
909   bool isARMBranchTarget() const {
910     if (!isImm()) return false;
911 
912     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm()))
913       return CE->getValue() % 4 == 0;
914     return true;
915   }
916 
917 
918   bool isThumbBranchTarget() const {
919     if (!isImm()) return false;
920 
921     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm()))
922       return CE->getValue() % 2 == 0;
923     return true;
924   }
925 
926   // checks whether this operand is an unsigned offset which fits is a field
927   // of specified width and scaled by a specific number of bits
928   template<unsigned width, unsigned scale>
929   bool isUnsignedOffset() const {
930     if (!isImm()) return false;
931     if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
932     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val)) {
933       int64_t Val = CE->getValue();
934       int64_t Align = 1LL << scale;
935       int64_t Max = Align * ((1LL << width) - 1);
936       return ((Val % Align) == 0) && (Val >= 0) && (Val <= Max);
937     }
938     return false;
939   }
940 
941   // checks whether this operand is an signed offset which fits is a field
942   // of specified width and scaled by a specific number of bits
943   template<unsigned width, unsigned scale>
944   bool isSignedOffset() const {
945     if (!isImm()) return false;
946     if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
947     if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val)) {
948       int64_t Val = CE->getValue();
949       int64_t Align = 1LL << scale;
950       int64_t Max = Align * ((1LL << (width-1)) - 1);
951       int64_t Min = -Align * (1LL << (width-1));
952       return ((Val % Align) == 0) && (Val >= Min) && (Val <= Max);
953     }
954     return false;
955   }
956 
957   // checks whether this operand is a memory operand computed as an offset
958   // applied to PC. the offset may have 8 bits of magnitude and is represented
959   // with two bits of shift. textually it may be either [pc, #imm], #imm or
960   // relocable expression...
961   bool isThumbMemPC() const {
962     int64_t Val = 0;
963     if (isImm()) {
964       if (isa<MCSymbolRefExpr>(Imm.Val)) return true;
965       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm.Val);
966       if (!CE) return false;
967       Val = CE->getValue();
968     }
969     else if (isMem()) {
970       if(!Memory.OffsetImm || Memory.OffsetRegNum) return false;
971       if(Memory.BaseRegNum != ARM::PC) return false;
972       Val = Memory.OffsetImm->getValue();
973     }
974     else return false;
975     return ((Val % 4) == 0) && (Val >= 0) && (Val <= 1020);
976   }
977 
978   bool isFPImm() const {
979     if (!isImm()) return false;
980     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
981     if (!CE) return false;
982     int Val = ARM_AM::getFP32Imm(APInt(32, CE->getValue()));
983     return Val != -1;
984   }
985 
986   template<int64_t N, int64_t M>
987   bool isImmediate() const {
988     if (!isImm()) return false;
989     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
990     if (!CE) return false;
991     int64_t Value = CE->getValue();
992     return Value >= N && Value <= M;
993   }
994 
995   template<int64_t N, int64_t M>
996   bool isImmediateS4() const {
997     if (!isImm()) return false;
998     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
999     if (!CE) return false;
1000     int64_t Value = CE->getValue();
1001     return ((Value & 3) == 0) && Value >= N && Value <= M;
1002   }
1003 
1004   bool isFBits16() const {
1005     return isImmediate<0, 17>();
1006   }
1007   bool isFBits32() const {
1008     return isImmediate<1, 33>();
1009   }
1010   bool isImm8s4() const {
1011     return isImmediateS4<-1020, 1020>();
1012   }
1013   bool isImm0_1020s4() const {
1014     return isImmediateS4<0, 1020>();
1015   }
1016   bool isImm0_508s4() const {
1017     return isImmediateS4<0, 508>();
1018   }
1019   bool isImm0_508s4Neg() const {
1020     if (!isImm()) return false;
1021     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1022     if (!CE) return false;
1023     int64_t Value = -CE->getValue();
1024     // explicitly exclude zero. we want that to use the normal 0_508 version.
1025     return ((Value & 3) == 0) && Value > 0 && Value <= 508;
1026   }
1027 
1028   bool isImm0_4095Neg() const {
1029     if (!isImm()) return false;
1030     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1031     if (!CE) return false;
1032     int64_t Value = -CE->getValue();
1033     return Value > 0 && Value < 4096;
1034   }
1035 
1036   bool isImm0_7() const {
1037     return isImmediate<0, 7>();
1038   }
1039 
1040   bool isImm1_16() const {
1041     return isImmediate<1, 16>();
1042   }
1043 
1044   bool isImm1_32() const {
1045     return isImmediate<1, 32>();
1046   }
1047 
1048   bool isImm8_255() const {
1049     return isImmediate<8, 255>();
1050   }
1051 
1052   bool isImm256_65535Expr() const {
1053     if (!isImm()) return false;
1054     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1055     // If it's not a constant expression, it'll generate a fixup and be
1056     // handled later.
1057     if (!CE) return true;
1058     int64_t Value = CE->getValue();
1059     return Value >= 256 && Value < 65536;
1060   }
1061 
1062   bool isImm0_65535Expr() const {
1063     if (!isImm()) return false;
1064     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1065     // If it's not a constant expression, it'll generate a fixup and be
1066     // handled later.
1067     if (!CE) return true;
1068     int64_t Value = CE->getValue();
1069     return Value >= 0 && Value < 65536;
1070   }
1071 
1072   bool isImm24bit() const {
1073     return isImmediate<0, 0xffffff + 1>();
1074   }
1075 
1076   bool isImmThumbSR() const {
1077     return isImmediate<1, 33>();
1078   }
1079 
1080   bool isPKHLSLImm() const {
1081     return isImmediate<0, 32>();
1082   }
1083 
1084   bool isPKHASRImm() const {
1085     return isImmediate<0, 33>();
1086   }
1087 
1088   bool isAdrLabel() const {
1089     // If we have an immediate that's not a constant, treat it as a label
1090     // reference needing a fixup.
1091     if (isImm() && !isa<MCConstantExpr>(getImm()))
1092       return true;
1093 
1094     // If it is a constant, it must fit into a modified immediate encoding.
1095     if (!isImm()) return false;
1096     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1097     if (!CE) return false;
1098     int64_t Value = CE->getValue();
1099     return (ARM_AM::getSOImmVal(Value) != -1 ||
1100             ARM_AM::getSOImmVal(-Value) != -1);
1101   }
1102 
1103   bool isT2SOImm() const {
1104     // If we have an immediate that's not a constant, treat it as an expression
1105     // needing a fixup.
1106     if (isImm() && !isa<MCConstantExpr>(getImm())) {
1107       // We want to avoid matching :upper16: and :lower16: as we want these
1108       // expressions to match in isImm0_65535Expr()
1109       const ARMMCExpr *ARM16Expr = dyn_cast<ARMMCExpr>(getImm());
1110       return (!ARM16Expr || (ARM16Expr->getKind() != ARMMCExpr::VK_ARM_HI16 &&
1111                              ARM16Expr->getKind() != ARMMCExpr::VK_ARM_LO16));
1112     }
1113     if (!isImm()) return false;
1114     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1115     if (!CE) return false;
1116     int64_t Value = CE->getValue();
1117     return ARM_AM::getT2SOImmVal(Value) != -1;
1118   }
1119 
1120   bool isT2SOImmNot() const {
1121     if (!isImm()) return false;
1122     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1123     if (!CE) return false;
1124     int64_t Value = CE->getValue();
1125     return ARM_AM::getT2SOImmVal(Value) == -1 &&
1126       ARM_AM::getT2SOImmVal(~Value) != -1;
1127   }
1128 
1129   bool isT2SOImmNeg() const {
1130     if (!isImm()) return false;
1131     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1132     if (!CE) return false;
1133     int64_t Value = CE->getValue();
1134     // Only use this when not representable as a plain so_imm.
1135     return ARM_AM::getT2SOImmVal(Value) == -1 &&
1136       ARM_AM::getT2SOImmVal(-Value) != -1;
1137   }
1138 
1139   bool isSetEndImm() const {
1140     if (!isImm()) return false;
1141     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1142     if (!CE) return false;
1143     int64_t Value = CE->getValue();
1144     return Value == 1 || Value == 0;
1145   }
1146 
1147   bool isReg() const override { return Kind == k_Register; }
1148   bool isRegList() const { return Kind == k_RegisterList; }
1149   bool isDPRRegList() const { return Kind == k_DPRRegisterList; }
1150   bool isSPRRegList() const { return Kind == k_SPRRegisterList; }
1151   bool isToken() const override { return Kind == k_Token; }
1152   bool isMemBarrierOpt() const { return Kind == k_MemBarrierOpt; }
1153   bool isInstSyncBarrierOpt() const { return Kind == k_InstSyncBarrierOpt; }
1154   bool isMem() const override { return Kind == k_Memory; }
1155   bool isShifterImm() const { return Kind == k_ShifterImmediate; }
1156   bool isRegShiftedReg() const { return Kind == k_ShiftedRegister; }
1157   bool isRegShiftedImm() const { return Kind == k_ShiftedImmediate; }
1158   bool isRotImm() const { return Kind == k_RotateImmediate; }
1159   bool isModImm() const { return Kind == k_ModifiedImmediate; }
1160 
1161   bool isModImmNot() const {
1162     if (!isImm()) return false;
1163     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1164     if (!CE) return false;
1165     int64_t Value = CE->getValue();
1166     return ARM_AM::getSOImmVal(~Value) != -1;
1167   }
1168 
1169   bool isModImmNeg() const {
1170     if (!isImm()) return false;
1171     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1172     if (!CE) return false;
1173     int64_t Value = CE->getValue();
1174     return ARM_AM::getSOImmVal(Value) == -1 &&
1175       ARM_AM::getSOImmVal(-Value) != -1;
1176   }
1177 
1178   bool isThumbModImmNeg1_7() const {
1179     if (!isImm()) return false;
1180     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1181     if (!CE) return false;
1182     int32_t Value = -(int32_t)CE->getValue();
1183     return 0 < Value && Value < 8;
1184   }
1185 
1186   bool isThumbModImmNeg8_255() const {
1187     if (!isImm()) return false;
1188     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1189     if (!CE) return false;
1190     int32_t Value = -(int32_t)CE->getValue();
1191     return 7 < Value && Value < 256;
1192   }
1193 
1194   bool isConstantPoolImm() const { return Kind == k_ConstantPoolImmediate; }
1195   bool isBitfield() const { return Kind == k_BitfieldDescriptor; }
1196   bool isPostIdxRegShifted() const { return Kind == k_PostIndexRegister; }
1197   bool isPostIdxReg() const {
1198     return Kind == k_PostIndexRegister && PostIdxReg.ShiftTy ==ARM_AM::no_shift;
1199   }
1200   bool isMemNoOffset(bool alignOK = false, unsigned Alignment = 0) const {
1201     if (!isMem())
1202       return false;
1203     // No offset of any kind.
1204     return Memory.OffsetRegNum == 0 && Memory.OffsetImm == nullptr &&
1205      (alignOK || Memory.Alignment == Alignment);
1206   }
1207   bool isMemPCRelImm12() const {
1208     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1209       return false;
1210     // Base register must be PC.
1211     if (Memory.BaseRegNum != ARM::PC)
1212       return false;
1213     // Immediate offset in range [-4095, 4095].
1214     if (!Memory.OffsetImm) return true;
1215     int64_t Val = Memory.OffsetImm->getValue();
1216     return (Val > -4096 && Val < 4096) ||
1217            (Val == std::numeric_limits<int32_t>::min());
1218   }
1219 
1220   bool isAlignedMemory() const {
1221     return isMemNoOffset(true);
1222   }
1223 
1224   bool isAlignedMemoryNone() const {
1225     return isMemNoOffset(false, 0);
1226   }
1227 
1228   bool isDupAlignedMemoryNone() const {
1229     return isMemNoOffset(false, 0);
1230   }
1231 
1232   bool isAlignedMemory16() const {
1233     if (isMemNoOffset(false, 2)) // alignment in bytes for 16-bits is 2.
1234       return true;
1235     return isMemNoOffset(false, 0);
1236   }
1237 
1238   bool isDupAlignedMemory16() const {
1239     if (isMemNoOffset(false, 2)) // alignment in bytes for 16-bits is 2.
1240       return true;
1241     return isMemNoOffset(false, 0);
1242   }
1243 
1244   bool isAlignedMemory32() const {
1245     if (isMemNoOffset(false, 4)) // alignment in bytes for 32-bits is 4.
1246       return true;
1247     return isMemNoOffset(false, 0);
1248   }
1249 
1250   bool isDupAlignedMemory32() const {
1251     if (isMemNoOffset(false, 4)) // alignment in bytes for 32-bits is 4.
1252       return true;
1253     return isMemNoOffset(false, 0);
1254   }
1255 
1256   bool isAlignedMemory64() const {
1257     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1258       return true;
1259     return isMemNoOffset(false, 0);
1260   }
1261 
1262   bool isDupAlignedMemory64() const {
1263     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1264       return true;
1265     return isMemNoOffset(false, 0);
1266   }
1267 
1268   bool isAlignedMemory64or128() const {
1269     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1270       return true;
1271     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1272       return true;
1273     return isMemNoOffset(false, 0);
1274   }
1275 
1276   bool isDupAlignedMemory64or128() const {
1277     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1278       return true;
1279     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1280       return true;
1281     return isMemNoOffset(false, 0);
1282   }
1283 
1284   bool isAlignedMemory64or128or256() const {
1285     if (isMemNoOffset(false, 8)) // alignment in bytes for 64-bits is 8.
1286       return true;
1287     if (isMemNoOffset(false, 16)) // alignment in bytes for 128-bits is 16.
1288       return true;
1289     if (isMemNoOffset(false, 32)) // alignment in bytes for 256-bits is 32.
1290       return true;
1291     return isMemNoOffset(false, 0);
1292   }
1293 
1294   bool isAddrMode2() const {
1295     if (!isMem() || Memory.Alignment != 0) return false;
1296     // Check for register offset.
1297     if (Memory.OffsetRegNum) return true;
1298     // Immediate offset in range [-4095, 4095].
1299     if (!Memory.OffsetImm) return true;
1300     int64_t Val = Memory.OffsetImm->getValue();
1301     return Val > -4096 && Val < 4096;
1302   }
1303 
1304   bool isAM2OffsetImm() const {
1305     if (!isImm()) return false;
1306     // Immediate offset in range [-4095, 4095].
1307     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1308     if (!CE) return false;
1309     int64_t Val = CE->getValue();
1310     return (Val == std::numeric_limits<int32_t>::min()) ||
1311            (Val > -4096 && Val < 4096);
1312   }
1313 
1314   bool isAddrMode3() const {
1315     // If we have an immediate that's not a constant, treat it as a label
1316     // reference needing a fixup. If it is a constant, it's something else
1317     // and we reject it.
1318     if (isImm() && !isa<MCConstantExpr>(getImm()))
1319       return true;
1320     if (!isMem() || Memory.Alignment != 0) return false;
1321     // No shifts are legal for AM3.
1322     if (Memory.ShiftType != ARM_AM::no_shift) return false;
1323     // Check for register offset.
1324     if (Memory.OffsetRegNum) return true;
1325     // Immediate offset in range [-255, 255].
1326     if (!Memory.OffsetImm) return true;
1327     int64_t Val = Memory.OffsetImm->getValue();
1328     // The #-0 offset is encoded as std::numeric_limits<int32_t>::min(), and we
1329     // have to check for this too.
1330     return (Val > -256 && Val < 256) ||
1331            Val == std::numeric_limits<int32_t>::min();
1332   }
1333 
1334   bool isAM3Offset() const {
1335     if (Kind != k_Immediate && Kind != k_PostIndexRegister)
1336       return false;
1337     if (Kind == k_PostIndexRegister)
1338       return PostIdxReg.ShiftTy == ARM_AM::no_shift;
1339     // Immediate offset in range [-255, 255].
1340     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1341     if (!CE) return false;
1342     int64_t Val = CE->getValue();
1343     // Special case, #-0 is std::numeric_limits<int32_t>::min().
1344     return (Val > -256 && Val < 256) ||
1345            Val == std::numeric_limits<int32_t>::min();
1346   }
1347 
1348   bool isAddrMode5() const {
1349     // If we have an immediate that's not a constant, treat it as a label
1350     // reference needing a fixup. If it is a constant, it's something else
1351     // and we reject it.
1352     if (isImm() && !isa<MCConstantExpr>(getImm()))
1353       return true;
1354     if (!isMem() || Memory.Alignment != 0) return false;
1355     // Check for register offset.
1356     if (Memory.OffsetRegNum) return false;
1357     // Immediate offset in range [-1020, 1020] and a multiple of 4.
1358     if (!Memory.OffsetImm) return true;
1359     int64_t Val = Memory.OffsetImm->getValue();
1360     return (Val >= -1020 && Val <= 1020 && ((Val & 3) == 0)) ||
1361       Val == std::numeric_limits<int32_t>::min();
1362   }
1363 
1364   bool isAddrMode5FP16() const {
1365     // If we have an immediate that's not a constant, treat it as a label
1366     // reference needing a fixup. If it is a constant, it's something else
1367     // and we reject it.
1368     if (isImm() && !isa<MCConstantExpr>(getImm()))
1369       return true;
1370     if (!isMem() || Memory.Alignment != 0) return false;
1371     // Check for register offset.
1372     if (Memory.OffsetRegNum) return false;
1373     // Immediate offset in range [-510, 510] and a multiple of 2.
1374     if (!Memory.OffsetImm) return true;
1375     int64_t Val = Memory.OffsetImm->getValue();
1376     return (Val >= -510 && Val <= 510 && ((Val & 1) == 0)) ||
1377            Val == std::numeric_limits<int32_t>::min();
1378   }
1379 
1380   bool isMemTBB() const {
1381     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1382         Memory.ShiftType != ARM_AM::no_shift || Memory.Alignment != 0)
1383       return false;
1384     return true;
1385   }
1386 
1387   bool isMemTBH() const {
1388     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1389         Memory.ShiftType != ARM_AM::lsl || Memory.ShiftImm != 1 ||
1390         Memory.Alignment != 0 )
1391       return false;
1392     return true;
1393   }
1394 
1395   bool isMemRegOffset() const {
1396     if (!isMem() || !Memory.OffsetRegNum || Memory.Alignment != 0)
1397       return false;
1398     return true;
1399   }
1400 
1401   bool isT2MemRegOffset() const {
1402     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1403         Memory.Alignment != 0 || Memory.BaseRegNum == ARM::PC)
1404       return false;
1405     // Only lsl #{0, 1, 2, 3} allowed.
1406     if (Memory.ShiftType == ARM_AM::no_shift)
1407       return true;
1408     if (Memory.ShiftType != ARM_AM::lsl || Memory.ShiftImm > 3)
1409       return false;
1410     return true;
1411   }
1412 
1413   bool isMemThumbRR() const {
1414     // Thumb reg+reg addressing is simple. Just two registers, a base and
1415     // an offset. No shifts, negations or any other complicating factors.
1416     if (!isMem() || !Memory.OffsetRegNum || Memory.isNegative ||
1417         Memory.ShiftType != ARM_AM::no_shift || Memory.Alignment != 0)
1418       return false;
1419     return isARMLowRegister(Memory.BaseRegNum) &&
1420       (!Memory.OffsetRegNum || isARMLowRegister(Memory.OffsetRegNum));
1421   }
1422 
1423   bool isMemThumbRIs4() const {
1424     if (!isMem() || Memory.OffsetRegNum != 0 ||
1425         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1426       return false;
1427     // Immediate offset, multiple of 4 in range [0, 124].
1428     if (!Memory.OffsetImm) return true;
1429     int64_t Val = Memory.OffsetImm->getValue();
1430     return Val >= 0 && Val <= 124 && (Val % 4) == 0;
1431   }
1432 
1433   bool isMemThumbRIs2() const {
1434     if (!isMem() || Memory.OffsetRegNum != 0 ||
1435         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1436       return false;
1437     // Immediate offset, multiple of 4 in range [0, 62].
1438     if (!Memory.OffsetImm) return true;
1439     int64_t Val = Memory.OffsetImm->getValue();
1440     return Val >= 0 && Val <= 62 && (Val % 2) == 0;
1441   }
1442 
1443   bool isMemThumbRIs1() const {
1444     if (!isMem() || Memory.OffsetRegNum != 0 ||
1445         !isARMLowRegister(Memory.BaseRegNum) || Memory.Alignment != 0)
1446       return false;
1447     // Immediate offset in range [0, 31].
1448     if (!Memory.OffsetImm) return true;
1449     int64_t Val = Memory.OffsetImm->getValue();
1450     return Val >= 0 && Val <= 31;
1451   }
1452 
1453   bool isMemThumbSPI() const {
1454     if (!isMem() || Memory.OffsetRegNum != 0 ||
1455         Memory.BaseRegNum != ARM::SP || Memory.Alignment != 0)
1456       return false;
1457     // Immediate offset, multiple of 4 in range [0, 1020].
1458     if (!Memory.OffsetImm) return true;
1459     int64_t Val = Memory.OffsetImm->getValue();
1460     return Val >= 0 && Val <= 1020 && (Val % 4) == 0;
1461   }
1462 
1463   bool isMemImm8s4Offset() const {
1464     // If we have an immediate that's not a constant, treat it as a label
1465     // reference needing a fixup. If it is a constant, it's something else
1466     // and we reject it.
1467     if (isImm() && !isa<MCConstantExpr>(getImm()))
1468       return true;
1469     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1470       return false;
1471     // Immediate offset a multiple of 4 in range [-1020, 1020].
1472     if (!Memory.OffsetImm) return true;
1473     int64_t Val = Memory.OffsetImm->getValue();
1474     // Special case, #-0 is std::numeric_limits<int32_t>::min().
1475     return (Val >= -1020 && Val <= 1020 && (Val & 3) == 0) ||
1476            Val == std::numeric_limits<int32_t>::min();
1477   }
1478 
1479   bool isMemImm0_1020s4Offset() const {
1480     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1481       return false;
1482     // Immediate offset a multiple of 4 in range [0, 1020].
1483     if (!Memory.OffsetImm) return true;
1484     int64_t Val = Memory.OffsetImm->getValue();
1485     return Val >= 0 && Val <= 1020 && (Val & 3) == 0;
1486   }
1487 
1488   bool isMemImm8Offset() const {
1489     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1490       return false;
1491     // Base reg of PC isn't allowed for these encodings.
1492     if (Memory.BaseRegNum == ARM::PC) return false;
1493     // Immediate offset in range [-255, 255].
1494     if (!Memory.OffsetImm) return true;
1495     int64_t Val = Memory.OffsetImm->getValue();
1496     return (Val == std::numeric_limits<int32_t>::min()) ||
1497            (Val > -256 && Val < 256);
1498   }
1499 
1500   bool isMemPosImm8Offset() const {
1501     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1502       return false;
1503     // Immediate offset in range [0, 255].
1504     if (!Memory.OffsetImm) return true;
1505     int64_t Val = Memory.OffsetImm->getValue();
1506     return Val >= 0 && Val < 256;
1507   }
1508 
1509   bool isMemNegImm8Offset() const {
1510     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1511       return false;
1512     // Base reg of PC isn't allowed for these encodings.
1513     if (Memory.BaseRegNum == ARM::PC) return false;
1514     // Immediate offset in range [-255, -1].
1515     if (!Memory.OffsetImm) return false;
1516     int64_t Val = Memory.OffsetImm->getValue();
1517     return (Val == std::numeric_limits<int32_t>::min()) ||
1518            (Val > -256 && Val < 0);
1519   }
1520 
1521   bool isMemUImm12Offset() const {
1522     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1523       return false;
1524     // Immediate offset in range [0, 4095].
1525     if (!Memory.OffsetImm) return true;
1526     int64_t Val = Memory.OffsetImm->getValue();
1527     return (Val >= 0 && Val < 4096);
1528   }
1529 
1530   bool isMemImm12Offset() const {
1531     // If we have an immediate that's not a constant, treat it as a label
1532     // reference needing a fixup. If it is a constant, it's something else
1533     // and we reject it.
1534 
1535     if (isImm() && !isa<MCConstantExpr>(getImm()))
1536       return true;
1537 
1538     if (!isMem() || Memory.OffsetRegNum != 0 || Memory.Alignment != 0)
1539       return false;
1540     // Immediate offset in range [-4095, 4095].
1541     if (!Memory.OffsetImm) return true;
1542     int64_t Val = Memory.OffsetImm->getValue();
1543     return (Val > -4096 && Val < 4096) ||
1544            (Val == std::numeric_limits<int32_t>::min());
1545   }
1546 
1547   bool isConstPoolAsmImm() const {
1548     // Delay processing of Constant Pool Immediate, this will turn into
1549     // a constant. Match no other operand
1550     return (isConstantPoolImm());
1551   }
1552 
1553   bool isPostIdxImm8() const {
1554     if (!isImm()) return false;
1555     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1556     if (!CE) return false;
1557     int64_t Val = CE->getValue();
1558     return (Val > -256 && Val < 256) ||
1559            (Val == std::numeric_limits<int32_t>::min());
1560   }
1561 
1562   bool isPostIdxImm8s4() const {
1563     if (!isImm()) return false;
1564     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1565     if (!CE) return false;
1566     int64_t Val = CE->getValue();
1567     return ((Val & 3) == 0 && Val >= -1020 && Val <= 1020) ||
1568            (Val == std::numeric_limits<int32_t>::min());
1569   }
1570 
1571   bool isMSRMask() const { return Kind == k_MSRMask; }
1572   bool isBankedReg() const { return Kind == k_BankedReg; }
1573   bool isProcIFlags() const { return Kind == k_ProcIFlags; }
1574 
1575   // NEON operands.
1576   bool isSingleSpacedVectorList() const {
1577     return Kind == k_VectorList && !VectorList.isDoubleSpaced;
1578   }
1579 
1580   bool isDoubleSpacedVectorList() const {
1581     return Kind == k_VectorList && VectorList.isDoubleSpaced;
1582   }
1583 
1584   bool isVecListOneD() const {
1585     if (!isSingleSpacedVectorList()) return false;
1586     return VectorList.Count == 1;
1587   }
1588 
1589   bool isVecListDPair() const {
1590     if (!isSingleSpacedVectorList()) return false;
1591     return (ARMMCRegisterClasses[ARM::DPairRegClassID]
1592               .contains(VectorList.RegNum));
1593   }
1594 
1595   bool isVecListThreeD() const {
1596     if (!isSingleSpacedVectorList()) return false;
1597     return VectorList.Count == 3;
1598   }
1599 
1600   bool isVecListFourD() const {
1601     if (!isSingleSpacedVectorList()) return false;
1602     return VectorList.Count == 4;
1603   }
1604 
1605   bool isVecListDPairSpaced() const {
1606     if (Kind != k_VectorList) return false;
1607     if (isSingleSpacedVectorList()) return false;
1608     return (ARMMCRegisterClasses[ARM::DPairSpcRegClassID]
1609               .contains(VectorList.RegNum));
1610   }
1611 
1612   bool isVecListThreeQ() const {
1613     if (!isDoubleSpacedVectorList()) return false;
1614     return VectorList.Count == 3;
1615   }
1616 
1617   bool isVecListFourQ() const {
1618     if (!isDoubleSpacedVectorList()) return false;
1619     return VectorList.Count == 4;
1620   }
1621 
1622   bool isSingleSpacedVectorAllLanes() const {
1623     return Kind == k_VectorListAllLanes && !VectorList.isDoubleSpaced;
1624   }
1625 
1626   bool isDoubleSpacedVectorAllLanes() const {
1627     return Kind == k_VectorListAllLanes && VectorList.isDoubleSpaced;
1628   }
1629 
1630   bool isVecListOneDAllLanes() const {
1631     if (!isSingleSpacedVectorAllLanes()) return false;
1632     return VectorList.Count == 1;
1633   }
1634 
1635   bool isVecListDPairAllLanes() const {
1636     if (!isSingleSpacedVectorAllLanes()) return false;
1637     return (ARMMCRegisterClasses[ARM::DPairRegClassID]
1638               .contains(VectorList.RegNum));
1639   }
1640 
1641   bool isVecListDPairSpacedAllLanes() const {
1642     if (!isDoubleSpacedVectorAllLanes()) return false;
1643     return VectorList.Count == 2;
1644   }
1645 
1646   bool isVecListThreeDAllLanes() const {
1647     if (!isSingleSpacedVectorAllLanes()) return false;
1648     return VectorList.Count == 3;
1649   }
1650 
1651   bool isVecListThreeQAllLanes() const {
1652     if (!isDoubleSpacedVectorAllLanes()) return false;
1653     return VectorList.Count == 3;
1654   }
1655 
1656   bool isVecListFourDAllLanes() const {
1657     if (!isSingleSpacedVectorAllLanes()) return false;
1658     return VectorList.Count == 4;
1659   }
1660 
1661   bool isVecListFourQAllLanes() const {
1662     if (!isDoubleSpacedVectorAllLanes()) return false;
1663     return VectorList.Count == 4;
1664   }
1665 
1666   bool isSingleSpacedVectorIndexed() const {
1667     return Kind == k_VectorListIndexed && !VectorList.isDoubleSpaced;
1668   }
1669 
1670   bool isDoubleSpacedVectorIndexed() const {
1671     return Kind == k_VectorListIndexed && VectorList.isDoubleSpaced;
1672   }
1673 
1674   bool isVecListOneDByteIndexed() const {
1675     if (!isSingleSpacedVectorIndexed()) return false;
1676     return VectorList.Count == 1 && VectorList.LaneIndex <= 7;
1677   }
1678 
1679   bool isVecListOneDHWordIndexed() const {
1680     if (!isSingleSpacedVectorIndexed()) return false;
1681     return VectorList.Count == 1 && VectorList.LaneIndex <= 3;
1682   }
1683 
1684   bool isVecListOneDWordIndexed() const {
1685     if (!isSingleSpacedVectorIndexed()) return false;
1686     return VectorList.Count == 1 && VectorList.LaneIndex <= 1;
1687   }
1688 
1689   bool isVecListTwoDByteIndexed() const {
1690     if (!isSingleSpacedVectorIndexed()) return false;
1691     return VectorList.Count == 2 && VectorList.LaneIndex <= 7;
1692   }
1693 
1694   bool isVecListTwoDHWordIndexed() const {
1695     if (!isSingleSpacedVectorIndexed()) return false;
1696     return VectorList.Count == 2 && VectorList.LaneIndex <= 3;
1697   }
1698 
1699   bool isVecListTwoQWordIndexed() const {
1700     if (!isDoubleSpacedVectorIndexed()) return false;
1701     return VectorList.Count == 2 && VectorList.LaneIndex <= 1;
1702   }
1703 
1704   bool isVecListTwoQHWordIndexed() const {
1705     if (!isDoubleSpacedVectorIndexed()) return false;
1706     return VectorList.Count == 2 && VectorList.LaneIndex <= 3;
1707   }
1708 
1709   bool isVecListTwoDWordIndexed() const {
1710     if (!isSingleSpacedVectorIndexed()) return false;
1711     return VectorList.Count == 2 && VectorList.LaneIndex <= 1;
1712   }
1713 
1714   bool isVecListThreeDByteIndexed() const {
1715     if (!isSingleSpacedVectorIndexed()) return false;
1716     return VectorList.Count == 3 && VectorList.LaneIndex <= 7;
1717   }
1718 
1719   bool isVecListThreeDHWordIndexed() const {
1720     if (!isSingleSpacedVectorIndexed()) return false;
1721     return VectorList.Count == 3 && VectorList.LaneIndex <= 3;
1722   }
1723 
1724   bool isVecListThreeQWordIndexed() const {
1725     if (!isDoubleSpacedVectorIndexed()) return false;
1726     return VectorList.Count == 3 && VectorList.LaneIndex <= 1;
1727   }
1728 
1729   bool isVecListThreeQHWordIndexed() const {
1730     if (!isDoubleSpacedVectorIndexed()) return false;
1731     return VectorList.Count == 3 && VectorList.LaneIndex <= 3;
1732   }
1733 
1734   bool isVecListThreeDWordIndexed() const {
1735     if (!isSingleSpacedVectorIndexed()) return false;
1736     return VectorList.Count == 3 && VectorList.LaneIndex <= 1;
1737   }
1738 
1739   bool isVecListFourDByteIndexed() const {
1740     if (!isSingleSpacedVectorIndexed()) return false;
1741     return VectorList.Count == 4 && VectorList.LaneIndex <= 7;
1742   }
1743 
1744   bool isVecListFourDHWordIndexed() const {
1745     if (!isSingleSpacedVectorIndexed()) return false;
1746     return VectorList.Count == 4 && VectorList.LaneIndex <= 3;
1747   }
1748 
1749   bool isVecListFourQWordIndexed() const {
1750     if (!isDoubleSpacedVectorIndexed()) return false;
1751     return VectorList.Count == 4 && VectorList.LaneIndex <= 1;
1752   }
1753 
1754   bool isVecListFourQHWordIndexed() const {
1755     if (!isDoubleSpacedVectorIndexed()) return false;
1756     return VectorList.Count == 4 && VectorList.LaneIndex <= 3;
1757   }
1758 
1759   bool isVecListFourDWordIndexed() const {
1760     if (!isSingleSpacedVectorIndexed()) return false;
1761     return VectorList.Count == 4 && VectorList.LaneIndex <= 1;
1762   }
1763 
1764   bool isVectorIndex8() const {
1765     if (Kind != k_VectorIndex) return false;
1766     return VectorIndex.Val < 8;
1767   }
1768 
1769   bool isVectorIndex16() const {
1770     if (Kind != k_VectorIndex) return false;
1771     return VectorIndex.Val < 4;
1772   }
1773 
1774   bool isVectorIndex32() const {
1775     if (Kind != k_VectorIndex) return false;
1776     return VectorIndex.Val < 2;
1777   }
1778   bool isVectorIndex64() const {
1779     if (Kind != k_VectorIndex) return false;
1780     return VectorIndex.Val < 1;
1781   }
1782 
1783   bool isNEONi8splat() const {
1784     if (!isImm()) return false;
1785     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1786     // Must be a constant.
1787     if (!CE) return false;
1788     int64_t Value = CE->getValue();
1789     // i8 value splatted across 8 bytes. The immediate is just the 8 byte
1790     // value.
1791     return Value >= 0 && Value < 256;
1792   }
1793 
1794   bool isNEONi16splat() const {
1795     if (isNEONByteReplicate(2))
1796       return false; // Leave that for bytes replication and forbid by default.
1797     if (!isImm())
1798       return false;
1799     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1800     // Must be a constant.
1801     if (!CE) return false;
1802     unsigned Value = CE->getValue();
1803     return ARM_AM::isNEONi16splat(Value);
1804   }
1805 
1806   bool isNEONi16splatNot() const {
1807     if (!isImm())
1808       return false;
1809     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1810     // Must be a constant.
1811     if (!CE) return false;
1812     unsigned Value = CE->getValue();
1813     return ARM_AM::isNEONi16splat(~Value & 0xffff);
1814   }
1815 
1816   bool isNEONi32splat() const {
1817     if (isNEONByteReplicate(4))
1818       return false; // Leave that for bytes replication and forbid by default.
1819     if (!isImm())
1820       return false;
1821     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1822     // Must be a constant.
1823     if (!CE) return false;
1824     unsigned Value = CE->getValue();
1825     return ARM_AM::isNEONi32splat(Value);
1826   }
1827 
1828   bool isNEONi32splatNot() const {
1829     if (!isImm())
1830       return false;
1831     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1832     // Must be a constant.
1833     if (!CE) return false;
1834     unsigned Value = CE->getValue();
1835     return ARM_AM::isNEONi32splat(~Value);
1836   }
1837 
1838   bool isNEONByteReplicate(unsigned NumBytes) const {
1839     if (!isImm())
1840       return false;
1841     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1842     // Must be a constant.
1843     if (!CE)
1844       return false;
1845     int64_t Value = CE->getValue();
1846     if (!Value)
1847       return false; // Don't bother with zero.
1848 
1849     unsigned char B = Value & 0xff;
1850     for (unsigned i = 1; i < NumBytes; ++i) {
1851       Value >>= 8;
1852       if ((Value & 0xff) != B)
1853         return false;
1854     }
1855     return true;
1856   }
1857 
1858   bool isNEONi16ByteReplicate() const { return isNEONByteReplicate(2); }
1859   bool isNEONi32ByteReplicate() const { return isNEONByteReplicate(4); }
1860 
1861   bool isNEONi32vmov() const {
1862     if (isNEONByteReplicate(4))
1863       return false; // Let it to be classified as byte-replicate case.
1864     if (!isImm())
1865       return false;
1866     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1867     // Must be a constant.
1868     if (!CE)
1869       return false;
1870     int64_t Value = CE->getValue();
1871     // i32 value with set bits only in one byte X000, 0X00, 00X0, or 000X,
1872     // for VMOV/VMVN only, 00Xf or 0Xff are also accepted.
1873     // FIXME: This is probably wrong and a copy and paste from previous example
1874     return (Value >= 0 && Value < 256) ||
1875       (Value >= 0x0100 && Value <= 0xff00) ||
1876       (Value >= 0x010000 && Value <= 0xff0000) ||
1877       (Value >= 0x01000000 && Value <= 0xff000000) ||
1878       (Value >= 0x01ff && Value <= 0xffff && (Value & 0xff) == 0xff) ||
1879       (Value >= 0x01ffff && Value <= 0xffffff && (Value & 0xffff) == 0xffff);
1880   }
1881 
1882   bool isNEONi32vmovNeg() const {
1883     if (!isImm()) return false;
1884     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1885     // Must be a constant.
1886     if (!CE) return false;
1887     int64_t Value = ~CE->getValue();
1888     // i32 value with set bits only in one byte X000, 0X00, 00X0, or 000X,
1889     // for VMOV/VMVN only, 00Xf or 0Xff are also accepted.
1890     // FIXME: This is probably wrong and a copy and paste from previous example
1891     return (Value >= 0 && Value < 256) ||
1892       (Value >= 0x0100 && Value <= 0xff00) ||
1893       (Value >= 0x010000 && Value <= 0xff0000) ||
1894       (Value >= 0x01000000 && Value <= 0xff000000) ||
1895       (Value >= 0x01ff && Value <= 0xffff && (Value & 0xff) == 0xff) ||
1896       (Value >= 0x01ffff && Value <= 0xffffff && (Value & 0xffff) == 0xffff);
1897   }
1898 
1899   bool isNEONi64splat() const {
1900     if (!isImm()) return false;
1901     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1902     // Must be a constant.
1903     if (!CE) return false;
1904     uint64_t Value = CE->getValue();
1905     // i64 value with each byte being either 0 or 0xff.
1906     for (unsigned i = 0; i < 8; ++i, Value >>= 8)
1907       if ((Value & 0xff) != 0 && (Value & 0xff) != 0xff) return false;
1908     return true;
1909   }
1910 
1911   template<int64_t Angle, int64_t Remainder>
1912   bool isComplexRotation() const {
1913     if (!isImm()) return false;
1914 
1915     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
1916     if (!CE) return false;
1917     uint64_t Value = CE->getValue();
1918 
1919     return (Value % Angle == Remainder && Value <= 270);
1920   }
1921 
1922   void addExpr(MCInst &Inst, const MCExpr *Expr) const {
1923     // Add as immediates when possible.  Null MCExpr = 0.
1924     if (!Expr)
1925       Inst.addOperand(MCOperand::createImm(0));
1926     else if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr))
1927       Inst.addOperand(MCOperand::createImm(CE->getValue()));
1928     else
1929       Inst.addOperand(MCOperand::createExpr(Expr));
1930   }
1931 
1932   void addARMBranchTargetOperands(MCInst &Inst, unsigned N) const {
1933     assert(N == 1 && "Invalid number of operands!");
1934     addExpr(Inst, getImm());
1935   }
1936 
1937   void addThumbBranchTargetOperands(MCInst &Inst, unsigned N) const {
1938     assert(N == 1 && "Invalid number of operands!");
1939     addExpr(Inst, getImm());
1940   }
1941 
1942   void addCondCodeOperands(MCInst &Inst, unsigned N) const {
1943     assert(N == 2 && "Invalid number of operands!");
1944     Inst.addOperand(MCOperand::createImm(unsigned(getCondCode())));
1945     unsigned RegNum = getCondCode() == ARMCC::AL ? 0: ARM::CPSR;
1946     Inst.addOperand(MCOperand::createReg(RegNum));
1947   }
1948 
1949   void addCoprocNumOperands(MCInst &Inst, unsigned N) const {
1950     assert(N == 1 && "Invalid number of operands!");
1951     Inst.addOperand(MCOperand::createImm(getCoproc()));
1952   }
1953 
1954   void addCoprocRegOperands(MCInst &Inst, unsigned N) const {
1955     assert(N == 1 && "Invalid number of operands!");
1956     Inst.addOperand(MCOperand::createImm(getCoproc()));
1957   }
1958 
1959   void addCoprocOptionOperands(MCInst &Inst, unsigned N) const {
1960     assert(N == 1 && "Invalid number of operands!");
1961     Inst.addOperand(MCOperand::createImm(CoprocOption.Val));
1962   }
1963 
1964   void addITMaskOperands(MCInst &Inst, unsigned N) const {
1965     assert(N == 1 && "Invalid number of operands!");
1966     Inst.addOperand(MCOperand::createImm(ITMask.Mask));
1967   }
1968 
1969   void addITCondCodeOperands(MCInst &Inst, unsigned N) const {
1970     assert(N == 1 && "Invalid number of operands!");
1971     Inst.addOperand(MCOperand::createImm(unsigned(getCondCode())));
1972   }
1973 
1974   void addCCOutOperands(MCInst &Inst, unsigned N) const {
1975     assert(N == 1 && "Invalid number of operands!");
1976     Inst.addOperand(MCOperand::createReg(getReg()));
1977   }
1978 
1979   void addRegOperands(MCInst &Inst, unsigned N) const {
1980     assert(N == 1 && "Invalid number of operands!");
1981     Inst.addOperand(MCOperand::createReg(getReg()));
1982   }
1983 
1984   void addRegShiftedRegOperands(MCInst &Inst, unsigned N) const {
1985     assert(N == 3 && "Invalid number of operands!");
1986     assert(isRegShiftedReg() &&
1987            "addRegShiftedRegOperands() on non-RegShiftedReg!");
1988     Inst.addOperand(MCOperand::createReg(RegShiftedReg.SrcReg));
1989     Inst.addOperand(MCOperand::createReg(RegShiftedReg.ShiftReg));
1990     Inst.addOperand(MCOperand::createImm(
1991       ARM_AM::getSORegOpc(RegShiftedReg.ShiftTy, RegShiftedReg.ShiftImm)));
1992   }
1993 
1994   void addRegShiftedImmOperands(MCInst &Inst, unsigned N) const {
1995     assert(N == 2 && "Invalid number of operands!");
1996     assert(isRegShiftedImm() &&
1997            "addRegShiftedImmOperands() on non-RegShiftedImm!");
1998     Inst.addOperand(MCOperand::createReg(RegShiftedImm.SrcReg));
1999     // Shift of #32 is encoded as 0 where permitted
2000     unsigned Imm = (RegShiftedImm.ShiftImm == 32 ? 0 : RegShiftedImm.ShiftImm);
2001     Inst.addOperand(MCOperand::createImm(
2002       ARM_AM::getSORegOpc(RegShiftedImm.ShiftTy, Imm)));
2003   }
2004 
2005   void addShifterImmOperands(MCInst &Inst, unsigned N) const {
2006     assert(N == 1 && "Invalid number of operands!");
2007     Inst.addOperand(MCOperand::createImm((ShifterImm.isASR << 5) |
2008                                          ShifterImm.Imm));
2009   }
2010 
2011   void addRegListOperands(MCInst &Inst, unsigned N) const {
2012     assert(N == 1 && "Invalid number of operands!");
2013     const SmallVectorImpl<unsigned> &RegList = getRegList();
2014     for (SmallVectorImpl<unsigned>::const_iterator
2015            I = RegList.begin(), E = RegList.end(); I != E; ++I)
2016       Inst.addOperand(MCOperand::createReg(*I));
2017   }
2018 
2019   void addDPRRegListOperands(MCInst &Inst, unsigned N) const {
2020     addRegListOperands(Inst, N);
2021   }
2022 
2023   void addSPRRegListOperands(MCInst &Inst, unsigned N) const {
2024     addRegListOperands(Inst, N);
2025   }
2026 
2027   void addRotImmOperands(MCInst &Inst, unsigned N) const {
2028     assert(N == 1 && "Invalid number of operands!");
2029     // Encoded as val>>3. The printer handles display as 8, 16, 24.
2030     Inst.addOperand(MCOperand::createImm(RotImm.Imm >> 3));
2031   }
2032 
2033   void addModImmOperands(MCInst &Inst, unsigned N) const {
2034     assert(N == 1 && "Invalid number of operands!");
2035 
2036     // Support for fixups (MCFixup)
2037     if (isImm())
2038       return addImmOperands(Inst, N);
2039 
2040     Inst.addOperand(MCOperand::createImm(ModImm.Bits | (ModImm.Rot << 7)));
2041   }
2042 
2043   void addModImmNotOperands(MCInst &Inst, unsigned N) const {
2044     assert(N == 1 && "Invalid number of operands!");
2045     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2046     uint32_t Enc = ARM_AM::getSOImmVal(~CE->getValue());
2047     Inst.addOperand(MCOperand::createImm(Enc));
2048   }
2049 
2050   void addModImmNegOperands(MCInst &Inst, unsigned N) const {
2051     assert(N == 1 && "Invalid number of operands!");
2052     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2053     uint32_t Enc = ARM_AM::getSOImmVal(-CE->getValue());
2054     Inst.addOperand(MCOperand::createImm(Enc));
2055   }
2056 
2057   void addThumbModImmNeg8_255Operands(MCInst &Inst, unsigned N) const {
2058     assert(N == 1 && "Invalid number of operands!");
2059     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2060     uint32_t Val = -CE->getValue();
2061     Inst.addOperand(MCOperand::createImm(Val));
2062   }
2063 
2064   void addThumbModImmNeg1_7Operands(MCInst &Inst, unsigned N) const {
2065     assert(N == 1 && "Invalid number of operands!");
2066     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2067     uint32_t Val = -CE->getValue();
2068     Inst.addOperand(MCOperand::createImm(Val));
2069   }
2070 
2071   void addBitfieldOperands(MCInst &Inst, unsigned N) const {
2072     assert(N == 1 && "Invalid number of operands!");
2073     // Munge the lsb/width into a bitfield mask.
2074     unsigned lsb = Bitfield.LSB;
2075     unsigned width = Bitfield.Width;
2076     // Make a 32-bit mask w/ the referenced bits clear and all other bits set.
2077     uint32_t Mask = ~(((uint32_t)0xffffffff >> lsb) << (32 - width) >>
2078                       (32 - (lsb + width)));
2079     Inst.addOperand(MCOperand::createImm(Mask));
2080   }
2081 
2082   void addImmOperands(MCInst &Inst, unsigned N) const {
2083     assert(N == 1 && "Invalid number of operands!");
2084     addExpr(Inst, getImm());
2085   }
2086 
2087   void addFBits16Operands(MCInst &Inst, unsigned N) const {
2088     assert(N == 1 && "Invalid number of operands!");
2089     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2090     Inst.addOperand(MCOperand::createImm(16 - CE->getValue()));
2091   }
2092 
2093   void addFBits32Operands(MCInst &Inst, unsigned N) const {
2094     assert(N == 1 && "Invalid number of operands!");
2095     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2096     Inst.addOperand(MCOperand::createImm(32 - CE->getValue()));
2097   }
2098 
2099   void addFPImmOperands(MCInst &Inst, unsigned N) const {
2100     assert(N == 1 && "Invalid number of operands!");
2101     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2102     int Val = ARM_AM::getFP32Imm(APInt(32, CE->getValue()));
2103     Inst.addOperand(MCOperand::createImm(Val));
2104   }
2105 
2106   void addImm8s4Operands(MCInst &Inst, unsigned N) const {
2107     assert(N == 1 && "Invalid number of operands!");
2108     // FIXME: We really want to scale the value here, but the LDRD/STRD
2109     // instruction don't encode operands that way yet.
2110     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2111     Inst.addOperand(MCOperand::createImm(CE->getValue()));
2112   }
2113 
2114   void addImm0_1020s4Operands(MCInst &Inst, unsigned N) const {
2115     assert(N == 1 && "Invalid number of operands!");
2116     // The immediate is scaled by four in the encoding and is stored
2117     // in the MCInst as such. Lop off the low two bits here.
2118     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2119     Inst.addOperand(MCOperand::createImm(CE->getValue() / 4));
2120   }
2121 
2122   void addImm0_508s4NegOperands(MCInst &Inst, unsigned N) const {
2123     assert(N == 1 && "Invalid number of operands!");
2124     // The immediate is scaled by four in the encoding and is stored
2125     // in the MCInst as such. Lop off the low two bits here.
2126     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2127     Inst.addOperand(MCOperand::createImm(-(CE->getValue() / 4)));
2128   }
2129 
2130   void addImm0_508s4Operands(MCInst &Inst, unsigned N) const {
2131     assert(N == 1 && "Invalid number of operands!");
2132     // The immediate is scaled by four in the encoding and is stored
2133     // in the MCInst as such. Lop off the low two bits here.
2134     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2135     Inst.addOperand(MCOperand::createImm(CE->getValue() / 4));
2136   }
2137 
2138   void addImm1_16Operands(MCInst &Inst, unsigned N) const {
2139     assert(N == 1 && "Invalid number of operands!");
2140     // The constant encodes as the immediate-1, and we store in the instruction
2141     // the bits as encoded, so subtract off one here.
2142     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2143     Inst.addOperand(MCOperand::createImm(CE->getValue() - 1));
2144   }
2145 
2146   void addImm1_32Operands(MCInst &Inst, unsigned N) const {
2147     assert(N == 1 && "Invalid number of operands!");
2148     // The constant encodes as the immediate-1, and we store in the instruction
2149     // the bits as encoded, so subtract off one here.
2150     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2151     Inst.addOperand(MCOperand::createImm(CE->getValue() - 1));
2152   }
2153 
2154   void addImmThumbSROperands(MCInst &Inst, unsigned N) const {
2155     assert(N == 1 && "Invalid number of operands!");
2156     // The constant encodes as the immediate, except for 32, which encodes as
2157     // zero.
2158     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2159     unsigned Imm = CE->getValue();
2160     Inst.addOperand(MCOperand::createImm((Imm == 32 ? 0 : Imm)));
2161   }
2162 
2163   void addPKHASRImmOperands(MCInst &Inst, unsigned N) const {
2164     assert(N == 1 && "Invalid number of operands!");
2165     // An ASR value of 32 encodes as 0, so that's how we want to add it to
2166     // the instruction as well.
2167     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2168     int Val = CE->getValue();
2169     Inst.addOperand(MCOperand::createImm(Val == 32 ? 0 : Val));
2170   }
2171 
2172   void addT2SOImmNotOperands(MCInst &Inst, unsigned N) const {
2173     assert(N == 1 && "Invalid number of operands!");
2174     // The operand is actually a t2_so_imm, but we have its bitwise
2175     // negation in the assembly source, so twiddle it here.
2176     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2177     Inst.addOperand(MCOperand::createImm(~(uint32_t)CE->getValue()));
2178   }
2179 
2180   void addT2SOImmNegOperands(MCInst &Inst, unsigned N) const {
2181     assert(N == 1 && "Invalid number of operands!");
2182     // The operand is actually a t2_so_imm, but we have its
2183     // negation in the assembly source, so twiddle it here.
2184     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2185     Inst.addOperand(MCOperand::createImm(-(uint32_t)CE->getValue()));
2186   }
2187 
2188   void addImm0_4095NegOperands(MCInst &Inst, unsigned N) const {
2189     assert(N == 1 && "Invalid number of operands!");
2190     // The operand is actually an imm0_4095, but we have its
2191     // negation in the assembly source, so twiddle it here.
2192     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2193     Inst.addOperand(MCOperand::createImm(-CE->getValue()));
2194   }
2195 
2196   void addUnsignedOffset_b8s2Operands(MCInst &Inst, unsigned N) const {
2197     if(const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm())) {
2198       Inst.addOperand(MCOperand::createImm(CE->getValue() >> 2));
2199       return;
2200     }
2201 
2202     const MCSymbolRefExpr *SR = dyn_cast<MCSymbolRefExpr>(Imm.Val);
2203     assert(SR && "Unknown value type!");
2204     Inst.addOperand(MCOperand::createExpr(SR));
2205   }
2206 
2207   void addThumbMemPCOperands(MCInst &Inst, unsigned N) const {
2208     assert(N == 1 && "Invalid number of operands!");
2209     if (isImm()) {
2210       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2211       if (CE) {
2212         Inst.addOperand(MCOperand::createImm(CE->getValue()));
2213         return;
2214       }
2215 
2216       const MCSymbolRefExpr *SR = dyn_cast<MCSymbolRefExpr>(Imm.Val);
2217 
2218       assert(SR && "Unknown value type!");
2219       Inst.addOperand(MCOperand::createExpr(SR));
2220       return;
2221     }
2222 
2223     assert(isMem()  && "Unknown value type!");
2224     assert(isa<MCConstantExpr>(Memory.OffsetImm) && "Unknown value type!");
2225     Inst.addOperand(MCOperand::createImm(Memory.OffsetImm->getValue()));
2226   }
2227 
2228   void addMemBarrierOptOperands(MCInst &Inst, unsigned N) const {
2229     assert(N == 1 && "Invalid number of operands!");
2230     Inst.addOperand(MCOperand::createImm(unsigned(getMemBarrierOpt())));
2231   }
2232 
2233   void addInstSyncBarrierOptOperands(MCInst &Inst, unsigned N) const {
2234     assert(N == 1 && "Invalid number of operands!");
2235     Inst.addOperand(MCOperand::createImm(unsigned(getInstSyncBarrierOpt())));
2236   }
2237 
2238   void addMemNoOffsetOperands(MCInst &Inst, unsigned N) const {
2239     assert(N == 1 && "Invalid number of operands!");
2240     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2241   }
2242 
2243   void addMemPCRelImm12Operands(MCInst &Inst, unsigned N) const {
2244     assert(N == 1 && "Invalid number of operands!");
2245     int32_t Imm = Memory.OffsetImm->getValue();
2246     Inst.addOperand(MCOperand::createImm(Imm));
2247   }
2248 
2249   void addAdrLabelOperands(MCInst &Inst, unsigned N) const {
2250     assert(N == 1 && "Invalid number of operands!");
2251     assert(isImm() && "Not an immediate!");
2252 
2253     // If we have an immediate that's not a constant, treat it as a label
2254     // reference needing a fixup.
2255     if (!isa<MCConstantExpr>(getImm())) {
2256       Inst.addOperand(MCOperand::createExpr(getImm()));
2257       return;
2258     }
2259 
2260     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2261     int Val = CE->getValue();
2262     Inst.addOperand(MCOperand::createImm(Val));
2263   }
2264 
2265   void addAlignedMemoryOperands(MCInst &Inst, unsigned N) const {
2266     assert(N == 2 && "Invalid number of operands!");
2267     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2268     Inst.addOperand(MCOperand::createImm(Memory.Alignment));
2269   }
2270 
2271   void addDupAlignedMemoryNoneOperands(MCInst &Inst, unsigned N) const {
2272     addAlignedMemoryOperands(Inst, N);
2273   }
2274 
2275   void addAlignedMemoryNoneOperands(MCInst &Inst, unsigned N) const {
2276     addAlignedMemoryOperands(Inst, N);
2277   }
2278 
2279   void addAlignedMemory16Operands(MCInst &Inst, unsigned N) const {
2280     addAlignedMemoryOperands(Inst, N);
2281   }
2282 
2283   void addDupAlignedMemory16Operands(MCInst &Inst, unsigned N) const {
2284     addAlignedMemoryOperands(Inst, N);
2285   }
2286 
2287   void addAlignedMemory32Operands(MCInst &Inst, unsigned N) const {
2288     addAlignedMemoryOperands(Inst, N);
2289   }
2290 
2291   void addDupAlignedMemory32Operands(MCInst &Inst, unsigned N) const {
2292     addAlignedMemoryOperands(Inst, N);
2293   }
2294 
2295   void addAlignedMemory64Operands(MCInst &Inst, unsigned N) const {
2296     addAlignedMemoryOperands(Inst, N);
2297   }
2298 
2299   void addDupAlignedMemory64Operands(MCInst &Inst, unsigned N) const {
2300     addAlignedMemoryOperands(Inst, N);
2301   }
2302 
2303   void addAlignedMemory64or128Operands(MCInst &Inst, unsigned N) const {
2304     addAlignedMemoryOperands(Inst, N);
2305   }
2306 
2307   void addDupAlignedMemory64or128Operands(MCInst &Inst, unsigned N) const {
2308     addAlignedMemoryOperands(Inst, N);
2309   }
2310 
2311   void addAlignedMemory64or128or256Operands(MCInst &Inst, unsigned N) const {
2312     addAlignedMemoryOperands(Inst, N);
2313   }
2314 
2315   void addAddrMode2Operands(MCInst &Inst, unsigned N) const {
2316     assert(N == 3 && "Invalid number of operands!");
2317     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2318     if (!Memory.OffsetRegNum) {
2319       ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2320       // Special case for #-0
2321       if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2322       if (Val < 0) Val = -Val;
2323       Val = ARM_AM::getAM2Opc(AddSub, Val, ARM_AM::no_shift);
2324     } else {
2325       // For register offset, we encode the shift type and negation flag
2326       // here.
2327       Val = ARM_AM::getAM2Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add,
2328                               Memory.ShiftImm, Memory.ShiftType);
2329     }
2330     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2331     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2332     Inst.addOperand(MCOperand::createImm(Val));
2333   }
2334 
2335   void addAM2OffsetImmOperands(MCInst &Inst, unsigned N) const {
2336     assert(N == 2 && "Invalid number of operands!");
2337     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2338     assert(CE && "non-constant AM2OffsetImm operand!");
2339     int32_t Val = CE->getValue();
2340     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2341     // Special case for #-0
2342     if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2343     if (Val < 0) Val = -Val;
2344     Val = ARM_AM::getAM2Opc(AddSub, Val, ARM_AM::no_shift);
2345     Inst.addOperand(MCOperand::createReg(0));
2346     Inst.addOperand(MCOperand::createImm(Val));
2347   }
2348 
2349   void addAddrMode3Operands(MCInst &Inst, unsigned N) const {
2350     assert(N == 3 && "Invalid number of operands!");
2351     // If we have an immediate that's not a constant, treat it as a label
2352     // reference needing a fixup. If it is a constant, it's something else
2353     // and we reject it.
2354     if (isImm()) {
2355       Inst.addOperand(MCOperand::createExpr(getImm()));
2356       Inst.addOperand(MCOperand::createReg(0));
2357       Inst.addOperand(MCOperand::createImm(0));
2358       return;
2359     }
2360 
2361     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2362     if (!Memory.OffsetRegNum) {
2363       ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2364       // Special case for #-0
2365       if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2366       if (Val < 0) Val = -Val;
2367       Val = ARM_AM::getAM3Opc(AddSub, Val);
2368     } else {
2369       // For register offset, we encode the shift type and negation flag
2370       // here.
2371       Val = ARM_AM::getAM3Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add, 0);
2372     }
2373     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2374     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2375     Inst.addOperand(MCOperand::createImm(Val));
2376   }
2377 
2378   void addAM3OffsetOperands(MCInst &Inst, unsigned N) const {
2379     assert(N == 2 && "Invalid number of operands!");
2380     if (Kind == k_PostIndexRegister) {
2381       int32_t Val =
2382         ARM_AM::getAM3Opc(PostIdxReg.isAdd ? ARM_AM::add : ARM_AM::sub, 0);
2383       Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
2384       Inst.addOperand(MCOperand::createImm(Val));
2385       return;
2386     }
2387 
2388     // Constant offset.
2389     const MCConstantExpr *CE = static_cast<const MCConstantExpr*>(getImm());
2390     int32_t Val = CE->getValue();
2391     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2392     // Special case for #-0
2393     if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2394     if (Val < 0) Val = -Val;
2395     Val = ARM_AM::getAM3Opc(AddSub, Val);
2396     Inst.addOperand(MCOperand::createReg(0));
2397     Inst.addOperand(MCOperand::createImm(Val));
2398   }
2399 
2400   void addAddrMode5Operands(MCInst &Inst, unsigned N) const {
2401     assert(N == 2 && "Invalid number of operands!");
2402     // If we have an immediate that's not a constant, treat it as a label
2403     // reference needing a fixup. If it is a constant, it's something else
2404     // and we reject it.
2405     if (isImm()) {
2406       Inst.addOperand(MCOperand::createExpr(getImm()));
2407       Inst.addOperand(MCOperand::createImm(0));
2408       return;
2409     }
2410 
2411     // The lower two bits are always zero and as such are not encoded.
2412     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 4 : 0;
2413     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2414     // Special case for #-0
2415     if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2416     if (Val < 0) Val = -Val;
2417     Val = ARM_AM::getAM5Opc(AddSub, Val);
2418     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2419     Inst.addOperand(MCOperand::createImm(Val));
2420   }
2421 
2422   void addAddrMode5FP16Operands(MCInst &Inst, unsigned N) const {
2423     assert(N == 2 && "Invalid number of operands!");
2424     // If we have an immediate that's not a constant, treat it as a label
2425     // reference needing a fixup. If it is a constant, it's something else
2426     // and we reject it.
2427     if (isImm()) {
2428       Inst.addOperand(MCOperand::createExpr(getImm()));
2429       Inst.addOperand(MCOperand::createImm(0));
2430       return;
2431     }
2432 
2433     // The lower bit is always zero and as such is not encoded.
2434     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 2 : 0;
2435     ARM_AM::AddrOpc AddSub = Val < 0 ? ARM_AM::sub : ARM_AM::add;
2436     // Special case for #-0
2437     if (Val == std::numeric_limits<int32_t>::min()) Val = 0;
2438     if (Val < 0) Val = -Val;
2439     Val = ARM_AM::getAM5FP16Opc(AddSub, Val);
2440     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2441     Inst.addOperand(MCOperand::createImm(Val));
2442   }
2443 
2444   void addMemImm8s4OffsetOperands(MCInst &Inst, unsigned N) const {
2445     assert(N == 2 && "Invalid number of operands!");
2446     // If we have an immediate that's not a constant, treat it as a label
2447     // reference needing a fixup. If it is a constant, it's something else
2448     // and we reject it.
2449     if (isImm()) {
2450       Inst.addOperand(MCOperand::createExpr(getImm()));
2451       Inst.addOperand(MCOperand::createImm(0));
2452       return;
2453     }
2454 
2455     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2456     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2457     Inst.addOperand(MCOperand::createImm(Val));
2458   }
2459 
2460   void addMemImm0_1020s4OffsetOperands(MCInst &Inst, unsigned N) const {
2461     assert(N == 2 && "Invalid number of operands!");
2462     // The lower two bits are always zero and as such are not encoded.
2463     int32_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() / 4 : 0;
2464     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2465     Inst.addOperand(MCOperand::createImm(Val));
2466   }
2467 
2468   void addMemImm8OffsetOperands(MCInst &Inst, unsigned N) const {
2469     assert(N == 2 && "Invalid number of operands!");
2470     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2471     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2472     Inst.addOperand(MCOperand::createImm(Val));
2473   }
2474 
2475   void addMemPosImm8OffsetOperands(MCInst &Inst, unsigned N) const {
2476     addMemImm8OffsetOperands(Inst, N);
2477   }
2478 
2479   void addMemNegImm8OffsetOperands(MCInst &Inst, unsigned N) const {
2480     addMemImm8OffsetOperands(Inst, N);
2481   }
2482 
2483   void addMemUImm12OffsetOperands(MCInst &Inst, unsigned N) const {
2484     assert(N == 2 && "Invalid number of operands!");
2485     // If this is an immediate, it's a label reference.
2486     if (isImm()) {
2487       addExpr(Inst, getImm());
2488       Inst.addOperand(MCOperand::createImm(0));
2489       return;
2490     }
2491 
2492     // Otherwise, it's a normal memory reg+offset.
2493     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2494     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2495     Inst.addOperand(MCOperand::createImm(Val));
2496   }
2497 
2498   void addMemImm12OffsetOperands(MCInst &Inst, unsigned N) const {
2499     assert(N == 2 && "Invalid number of operands!");
2500     // If this is an immediate, it's a label reference.
2501     if (isImm()) {
2502       addExpr(Inst, getImm());
2503       Inst.addOperand(MCOperand::createImm(0));
2504       return;
2505     }
2506 
2507     // Otherwise, it's a normal memory reg+offset.
2508     int64_t Val = Memory.OffsetImm ? Memory.OffsetImm->getValue() : 0;
2509     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2510     Inst.addOperand(MCOperand::createImm(Val));
2511   }
2512 
2513   void addConstPoolAsmImmOperands(MCInst &Inst, unsigned N) const {
2514     assert(N == 1 && "Invalid number of operands!");
2515     // This is container for the immediate that we will create the constant
2516     // pool from
2517     addExpr(Inst, getConstantPoolImm());
2518     return;
2519   }
2520 
2521   void addMemTBBOperands(MCInst &Inst, unsigned N) const {
2522     assert(N == 2 && "Invalid number of operands!");
2523     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2524     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2525   }
2526 
2527   void addMemTBHOperands(MCInst &Inst, unsigned N) const {
2528     assert(N == 2 && "Invalid number of operands!");
2529     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2530     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2531   }
2532 
2533   void addMemRegOffsetOperands(MCInst &Inst, unsigned N) const {
2534     assert(N == 3 && "Invalid number of operands!");
2535     unsigned Val =
2536       ARM_AM::getAM2Opc(Memory.isNegative ? ARM_AM::sub : ARM_AM::add,
2537                         Memory.ShiftImm, Memory.ShiftType);
2538     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2539     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2540     Inst.addOperand(MCOperand::createImm(Val));
2541   }
2542 
2543   void addT2MemRegOffsetOperands(MCInst &Inst, unsigned N) const {
2544     assert(N == 3 && "Invalid number of operands!");
2545     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2546     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2547     Inst.addOperand(MCOperand::createImm(Memory.ShiftImm));
2548   }
2549 
2550   void addMemThumbRROperands(MCInst &Inst, unsigned N) const {
2551     assert(N == 2 && "Invalid number of operands!");
2552     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2553     Inst.addOperand(MCOperand::createReg(Memory.OffsetRegNum));
2554   }
2555 
2556   void addMemThumbRIs4Operands(MCInst &Inst, unsigned N) const {
2557     assert(N == 2 && "Invalid number of operands!");
2558     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 4) : 0;
2559     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2560     Inst.addOperand(MCOperand::createImm(Val));
2561   }
2562 
2563   void addMemThumbRIs2Operands(MCInst &Inst, unsigned N) const {
2564     assert(N == 2 && "Invalid number of operands!");
2565     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 2) : 0;
2566     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2567     Inst.addOperand(MCOperand::createImm(Val));
2568   }
2569 
2570   void addMemThumbRIs1Operands(MCInst &Inst, unsigned N) const {
2571     assert(N == 2 && "Invalid number of operands!");
2572     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue()) : 0;
2573     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2574     Inst.addOperand(MCOperand::createImm(Val));
2575   }
2576 
2577   void addMemThumbSPIOperands(MCInst &Inst, unsigned N) const {
2578     assert(N == 2 && "Invalid number of operands!");
2579     int64_t Val = Memory.OffsetImm ? (Memory.OffsetImm->getValue() / 4) : 0;
2580     Inst.addOperand(MCOperand::createReg(Memory.BaseRegNum));
2581     Inst.addOperand(MCOperand::createImm(Val));
2582   }
2583 
2584   void addPostIdxImm8Operands(MCInst &Inst, unsigned N) const {
2585     assert(N == 1 && "Invalid number of operands!");
2586     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2587     assert(CE && "non-constant post-idx-imm8 operand!");
2588     int Imm = CE->getValue();
2589     bool isAdd = Imm >= 0;
2590     if (Imm == std::numeric_limits<int32_t>::min()) Imm = 0;
2591     Imm = (Imm < 0 ? -Imm : Imm) | (int)isAdd << 8;
2592     Inst.addOperand(MCOperand::createImm(Imm));
2593   }
2594 
2595   void addPostIdxImm8s4Operands(MCInst &Inst, unsigned N) const {
2596     assert(N == 1 && "Invalid number of operands!");
2597     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2598     assert(CE && "non-constant post-idx-imm8s4 operand!");
2599     int Imm = CE->getValue();
2600     bool isAdd = Imm >= 0;
2601     if (Imm == std::numeric_limits<int32_t>::min()) Imm = 0;
2602     // Immediate is scaled by 4.
2603     Imm = ((Imm < 0 ? -Imm : Imm) / 4) | (int)isAdd << 8;
2604     Inst.addOperand(MCOperand::createImm(Imm));
2605   }
2606 
2607   void addPostIdxRegOperands(MCInst &Inst, unsigned N) const {
2608     assert(N == 2 && "Invalid number of operands!");
2609     Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
2610     Inst.addOperand(MCOperand::createImm(PostIdxReg.isAdd));
2611   }
2612 
2613   void addPostIdxRegShiftedOperands(MCInst &Inst, unsigned N) const {
2614     assert(N == 2 && "Invalid number of operands!");
2615     Inst.addOperand(MCOperand::createReg(PostIdxReg.RegNum));
2616     // The sign, shift type, and shift amount are encoded in a single operand
2617     // using the AM2 encoding helpers.
2618     ARM_AM::AddrOpc opc = PostIdxReg.isAdd ? ARM_AM::add : ARM_AM::sub;
2619     unsigned Imm = ARM_AM::getAM2Opc(opc, PostIdxReg.ShiftImm,
2620                                      PostIdxReg.ShiftTy);
2621     Inst.addOperand(MCOperand::createImm(Imm));
2622   }
2623 
2624   void addMSRMaskOperands(MCInst &Inst, unsigned N) const {
2625     assert(N == 1 && "Invalid number of operands!");
2626     Inst.addOperand(MCOperand::createImm(unsigned(getMSRMask())));
2627   }
2628 
2629   void addBankedRegOperands(MCInst &Inst, unsigned N) const {
2630     assert(N == 1 && "Invalid number of operands!");
2631     Inst.addOperand(MCOperand::createImm(unsigned(getBankedReg())));
2632   }
2633 
2634   void addProcIFlagsOperands(MCInst &Inst, unsigned N) const {
2635     assert(N == 1 && "Invalid number of operands!");
2636     Inst.addOperand(MCOperand::createImm(unsigned(getProcIFlags())));
2637   }
2638 
2639   void addVecListOperands(MCInst &Inst, unsigned N) const {
2640     assert(N == 1 && "Invalid number of operands!");
2641     Inst.addOperand(MCOperand::createReg(VectorList.RegNum));
2642   }
2643 
2644   void addVecListIndexedOperands(MCInst &Inst, unsigned N) const {
2645     assert(N == 2 && "Invalid number of operands!");
2646     Inst.addOperand(MCOperand::createReg(VectorList.RegNum));
2647     Inst.addOperand(MCOperand::createImm(VectorList.LaneIndex));
2648   }
2649 
2650   void addVectorIndex8Operands(MCInst &Inst, unsigned N) const {
2651     assert(N == 1 && "Invalid number of operands!");
2652     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
2653   }
2654 
2655   void addVectorIndex16Operands(MCInst &Inst, unsigned N) const {
2656     assert(N == 1 && "Invalid number of operands!");
2657     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
2658   }
2659 
2660   void addVectorIndex32Operands(MCInst &Inst, unsigned N) const {
2661     assert(N == 1 && "Invalid number of operands!");
2662     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
2663   }
2664 
2665   void addVectorIndex64Operands(MCInst &Inst, unsigned N) const {
2666     assert(N == 1 && "Invalid number of operands!");
2667     Inst.addOperand(MCOperand::createImm(getVectorIndex()));
2668   }
2669 
2670   void addNEONi8splatOperands(MCInst &Inst, unsigned N) const {
2671     assert(N == 1 && "Invalid number of operands!");
2672     // The immediate encodes the type of constant as well as the value.
2673     // Mask in that this is an i8 splat.
2674     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2675     Inst.addOperand(MCOperand::createImm(CE->getValue() | 0xe00));
2676   }
2677 
2678   void addNEONi16splatOperands(MCInst &Inst, unsigned N) const {
2679     assert(N == 1 && "Invalid number of operands!");
2680     // The immediate encodes the type of constant as well as the value.
2681     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2682     unsigned Value = CE->getValue();
2683     Value = ARM_AM::encodeNEONi16splat(Value);
2684     Inst.addOperand(MCOperand::createImm(Value));
2685   }
2686 
2687   void addNEONi16splatNotOperands(MCInst &Inst, unsigned N) const {
2688     assert(N == 1 && "Invalid number of operands!");
2689     // The immediate encodes the type of constant as well as the value.
2690     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2691     unsigned Value = CE->getValue();
2692     Value = ARM_AM::encodeNEONi16splat(~Value & 0xffff);
2693     Inst.addOperand(MCOperand::createImm(Value));
2694   }
2695 
2696   void addNEONi32splatOperands(MCInst &Inst, unsigned N) const {
2697     assert(N == 1 && "Invalid number of operands!");
2698     // The immediate encodes the type of constant as well as the value.
2699     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2700     unsigned Value = CE->getValue();
2701     Value = ARM_AM::encodeNEONi32splat(Value);
2702     Inst.addOperand(MCOperand::createImm(Value));
2703   }
2704 
2705   void addNEONi32splatNotOperands(MCInst &Inst, unsigned N) const {
2706     assert(N == 1 && "Invalid number of operands!");
2707     // The immediate encodes the type of constant as well as the value.
2708     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2709     unsigned Value = CE->getValue();
2710     Value = ARM_AM::encodeNEONi32splat(~Value);
2711     Inst.addOperand(MCOperand::createImm(Value));
2712   }
2713 
2714   void addNEONinvByteReplicateOperands(MCInst &Inst, unsigned N) const {
2715     assert(N == 1 && "Invalid number of operands!");
2716     // The immediate encodes the type of constant as well as the value.
2717     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2718     unsigned Value = CE->getValue();
2719     assert((Inst.getOpcode() == ARM::VMOVv8i8 ||
2720             Inst.getOpcode() == ARM::VMOVv16i8) &&
2721            "All vmvn instructions that wants to replicate non-zero byte "
2722            "always must be replaced with VMOVv8i8 or VMOVv16i8.");
2723     unsigned B = ((~Value) & 0xff);
2724     B |= 0xe00; // cmode = 0b1110
2725     Inst.addOperand(MCOperand::createImm(B));
2726   }
2727 
2728   void addNEONi32vmovOperands(MCInst &Inst, unsigned N) const {
2729     assert(N == 1 && "Invalid number of operands!");
2730     // The immediate encodes the type of constant as well as the value.
2731     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2732     unsigned Value = CE->getValue();
2733     if (Value >= 256 && Value <= 0xffff)
2734       Value = (Value >> 8) | ((Value & 0xff) ? 0xc00 : 0x200);
2735     else if (Value > 0xffff && Value <= 0xffffff)
2736       Value = (Value >> 16) | ((Value & 0xff) ? 0xd00 : 0x400);
2737     else if (Value > 0xffffff)
2738       Value = (Value >> 24) | 0x600;
2739     Inst.addOperand(MCOperand::createImm(Value));
2740   }
2741 
2742   void addNEONvmovByteReplicateOperands(MCInst &Inst, unsigned N) const {
2743     assert(N == 1 && "Invalid number of operands!");
2744     // The immediate encodes the type of constant as well as the value.
2745     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2746     unsigned Value = CE->getValue();
2747     assert((Inst.getOpcode() == ARM::VMOVv8i8 ||
2748             Inst.getOpcode() == ARM::VMOVv16i8) &&
2749            "All instructions that wants to replicate non-zero byte "
2750            "always must be replaced with VMOVv8i8 or VMOVv16i8.");
2751     unsigned B = Value & 0xff;
2752     B |= 0xe00; // cmode = 0b1110
2753     Inst.addOperand(MCOperand::createImm(B));
2754   }
2755 
2756   void addNEONi32vmovNegOperands(MCInst &Inst, unsigned N) const {
2757     assert(N == 1 && "Invalid number of operands!");
2758     // The immediate encodes the type of constant as well as the value.
2759     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2760     unsigned Value = ~CE->getValue();
2761     if (Value >= 256 && Value <= 0xffff)
2762       Value = (Value >> 8) | ((Value & 0xff) ? 0xc00 : 0x200);
2763     else if (Value > 0xffff && Value <= 0xffffff)
2764       Value = (Value >> 16) | ((Value & 0xff) ? 0xd00 : 0x400);
2765     else if (Value > 0xffffff)
2766       Value = (Value >> 24) | 0x600;
2767     Inst.addOperand(MCOperand::createImm(Value));
2768   }
2769 
2770   void addNEONi64splatOperands(MCInst &Inst, unsigned N) const {
2771     assert(N == 1 && "Invalid number of operands!");
2772     // The immediate encodes the type of constant as well as the value.
2773     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2774     uint64_t Value = CE->getValue();
2775     unsigned Imm = 0;
2776     for (unsigned i = 0; i < 8; ++i, Value >>= 8) {
2777       Imm |= (Value & 1) << i;
2778     }
2779     Inst.addOperand(MCOperand::createImm(Imm | 0x1e00));
2780   }
2781 
2782   void addComplexRotationEvenOperands(MCInst &Inst, unsigned N) const {
2783     assert(N == 1 && "Invalid number of operands!");
2784     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2785     Inst.addOperand(MCOperand::createImm(CE->getValue() / 90));
2786   }
2787 
2788   void addComplexRotationOddOperands(MCInst &Inst, unsigned N) const {
2789     assert(N == 1 && "Invalid number of operands!");
2790     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(getImm());
2791     Inst.addOperand(MCOperand::createImm((CE->getValue() - 90) / 180));
2792   }
2793 
2794   void print(raw_ostream &OS) const override;
2795 
2796   static std::unique_ptr<ARMOperand> CreateITMask(unsigned Mask, SMLoc S) {
2797     auto Op = make_unique<ARMOperand>(k_ITCondMask);
2798     Op->ITMask.Mask = Mask;
2799     Op->StartLoc = S;
2800     Op->EndLoc = S;
2801     return Op;
2802   }
2803 
2804   static std::unique_ptr<ARMOperand> CreateCondCode(ARMCC::CondCodes CC,
2805                                                     SMLoc S) {
2806     auto Op = make_unique<ARMOperand>(k_CondCode);
2807     Op->CC.Val = CC;
2808     Op->StartLoc = S;
2809     Op->EndLoc = S;
2810     return Op;
2811   }
2812 
2813   static std::unique_ptr<ARMOperand> CreateCoprocNum(unsigned CopVal, SMLoc S) {
2814     auto Op = make_unique<ARMOperand>(k_CoprocNum);
2815     Op->Cop.Val = CopVal;
2816     Op->StartLoc = S;
2817     Op->EndLoc = S;
2818     return Op;
2819   }
2820 
2821   static std::unique_ptr<ARMOperand> CreateCoprocReg(unsigned CopVal, SMLoc S) {
2822     auto Op = make_unique<ARMOperand>(k_CoprocReg);
2823     Op->Cop.Val = CopVal;
2824     Op->StartLoc = S;
2825     Op->EndLoc = S;
2826     return Op;
2827   }
2828 
2829   static std::unique_ptr<ARMOperand> CreateCoprocOption(unsigned Val, SMLoc S,
2830                                                         SMLoc E) {
2831     auto Op = make_unique<ARMOperand>(k_CoprocOption);
2832     Op->Cop.Val = Val;
2833     Op->StartLoc = S;
2834     Op->EndLoc = E;
2835     return Op;
2836   }
2837 
2838   static std::unique_ptr<ARMOperand> CreateCCOut(unsigned RegNum, SMLoc S) {
2839     auto Op = make_unique<ARMOperand>(k_CCOut);
2840     Op->Reg.RegNum = RegNum;
2841     Op->StartLoc = S;
2842     Op->EndLoc = S;
2843     return Op;
2844   }
2845 
2846   static std::unique_ptr<ARMOperand> CreateToken(StringRef Str, SMLoc S) {
2847     auto Op = make_unique<ARMOperand>(k_Token);
2848     Op->Tok.Data = Str.data();
2849     Op->Tok.Length = Str.size();
2850     Op->StartLoc = S;
2851     Op->EndLoc = S;
2852     return Op;
2853   }
2854 
2855   static std::unique_ptr<ARMOperand> CreateReg(unsigned RegNum, SMLoc S,
2856                                                SMLoc E) {
2857     auto Op = make_unique<ARMOperand>(k_Register);
2858     Op->Reg.RegNum = RegNum;
2859     Op->StartLoc = S;
2860     Op->EndLoc = E;
2861     return Op;
2862   }
2863 
2864   static std::unique_ptr<ARMOperand>
2865   CreateShiftedRegister(ARM_AM::ShiftOpc ShTy, unsigned SrcReg,
2866                         unsigned ShiftReg, unsigned ShiftImm, SMLoc S,
2867                         SMLoc E) {
2868     auto Op = make_unique<ARMOperand>(k_ShiftedRegister);
2869     Op->RegShiftedReg.ShiftTy = ShTy;
2870     Op->RegShiftedReg.SrcReg = SrcReg;
2871     Op->RegShiftedReg.ShiftReg = ShiftReg;
2872     Op->RegShiftedReg.ShiftImm = ShiftImm;
2873     Op->StartLoc = S;
2874     Op->EndLoc = E;
2875     return Op;
2876   }
2877 
2878   static std::unique_ptr<ARMOperand>
2879   CreateShiftedImmediate(ARM_AM::ShiftOpc ShTy, unsigned SrcReg,
2880                          unsigned ShiftImm, SMLoc S, SMLoc E) {
2881     auto Op = make_unique<ARMOperand>(k_ShiftedImmediate);
2882     Op->RegShiftedImm.ShiftTy = ShTy;
2883     Op->RegShiftedImm.SrcReg = SrcReg;
2884     Op->RegShiftedImm.ShiftImm = ShiftImm;
2885     Op->StartLoc = S;
2886     Op->EndLoc = E;
2887     return Op;
2888   }
2889 
2890   static std::unique_ptr<ARMOperand> CreateShifterImm(bool isASR, unsigned Imm,
2891                                                       SMLoc S, SMLoc E) {
2892     auto Op = make_unique<ARMOperand>(k_ShifterImmediate);
2893     Op->ShifterImm.isASR = isASR;
2894     Op->ShifterImm.Imm = Imm;
2895     Op->StartLoc = S;
2896     Op->EndLoc = E;
2897     return Op;
2898   }
2899 
2900   static std::unique_ptr<ARMOperand> CreateRotImm(unsigned Imm, SMLoc S,
2901                                                   SMLoc E) {
2902     auto Op = make_unique<ARMOperand>(k_RotateImmediate);
2903     Op->RotImm.Imm = Imm;
2904     Op->StartLoc = S;
2905     Op->EndLoc = E;
2906     return Op;
2907   }
2908 
2909   static std::unique_ptr<ARMOperand> CreateModImm(unsigned Bits, unsigned Rot,
2910                                                   SMLoc S, SMLoc E) {
2911     auto Op = make_unique<ARMOperand>(k_ModifiedImmediate);
2912     Op->ModImm.Bits = Bits;
2913     Op->ModImm.Rot = Rot;
2914     Op->StartLoc = S;
2915     Op->EndLoc = E;
2916     return Op;
2917   }
2918 
2919   static std::unique_ptr<ARMOperand>
2920   CreateConstantPoolImm(const MCExpr *Val, SMLoc S, SMLoc E) {
2921     auto Op = make_unique<ARMOperand>(k_ConstantPoolImmediate);
2922     Op->Imm.Val = Val;
2923     Op->StartLoc = S;
2924     Op->EndLoc = E;
2925     return Op;
2926   }
2927 
2928   static std::unique_ptr<ARMOperand>
2929   CreateBitfield(unsigned LSB, unsigned Width, SMLoc S, SMLoc E) {
2930     auto Op = make_unique<ARMOperand>(k_BitfieldDescriptor);
2931     Op->Bitfield.LSB = LSB;
2932     Op->Bitfield.Width = Width;
2933     Op->StartLoc = S;
2934     Op->EndLoc = E;
2935     return Op;
2936   }
2937 
2938   static std::unique_ptr<ARMOperand>
2939   CreateRegList(SmallVectorImpl<std::pair<unsigned, unsigned>> &Regs,
2940                 SMLoc StartLoc, SMLoc EndLoc) {
2941     assert(Regs.size() > 0 && "RegList contains no registers?");
2942     KindTy Kind = k_RegisterList;
2943 
2944     if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Regs.front().second))
2945       Kind = k_DPRRegisterList;
2946     else if (ARMMCRegisterClasses[ARM::SPRRegClassID].
2947              contains(Regs.front().second))
2948       Kind = k_SPRRegisterList;
2949 
2950     // Sort based on the register encoding values.
2951     array_pod_sort(Regs.begin(), Regs.end());
2952 
2953     auto Op = make_unique<ARMOperand>(Kind);
2954     for (SmallVectorImpl<std::pair<unsigned, unsigned>>::const_iterator
2955            I = Regs.begin(), E = Regs.end(); I != E; ++I)
2956       Op->Registers.push_back(I->second);
2957     Op->StartLoc = StartLoc;
2958     Op->EndLoc = EndLoc;
2959     return Op;
2960   }
2961 
2962   static std::unique_ptr<ARMOperand> CreateVectorList(unsigned RegNum,
2963                                                       unsigned Count,
2964                                                       bool isDoubleSpaced,
2965                                                       SMLoc S, SMLoc E) {
2966     auto Op = make_unique<ARMOperand>(k_VectorList);
2967     Op->VectorList.RegNum = RegNum;
2968     Op->VectorList.Count = Count;
2969     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
2970     Op->StartLoc = S;
2971     Op->EndLoc = E;
2972     return Op;
2973   }
2974 
2975   static std::unique_ptr<ARMOperand>
2976   CreateVectorListAllLanes(unsigned RegNum, unsigned Count, bool isDoubleSpaced,
2977                            SMLoc S, SMLoc E) {
2978     auto Op = make_unique<ARMOperand>(k_VectorListAllLanes);
2979     Op->VectorList.RegNum = RegNum;
2980     Op->VectorList.Count = Count;
2981     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
2982     Op->StartLoc = S;
2983     Op->EndLoc = E;
2984     return Op;
2985   }
2986 
2987   static std::unique_ptr<ARMOperand>
2988   CreateVectorListIndexed(unsigned RegNum, unsigned Count, unsigned Index,
2989                           bool isDoubleSpaced, SMLoc S, SMLoc E) {
2990     auto Op = make_unique<ARMOperand>(k_VectorListIndexed);
2991     Op->VectorList.RegNum = RegNum;
2992     Op->VectorList.Count = Count;
2993     Op->VectorList.LaneIndex = Index;
2994     Op->VectorList.isDoubleSpaced = isDoubleSpaced;
2995     Op->StartLoc = S;
2996     Op->EndLoc = E;
2997     return Op;
2998   }
2999 
3000   static std::unique_ptr<ARMOperand>
3001   CreateVectorIndex(unsigned Idx, SMLoc S, SMLoc E, MCContext &Ctx) {
3002     auto Op = make_unique<ARMOperand>(k_VectorIndex);
3003     Op->VectorIndex.Val = Idx;
3004     Op->StartLoc = S;
3005     Op->EndLoc = E;
3006     return Op;
3007   }
3008 
3009   static std::unique_ptr<ARMOperand> CreateImm(const MCExpr *Val, SMLoc S,
3010                                                SMLoc E) {
3011     auto Op = make_unique<ARMOperand>(k_Immediate);
3012     Op->Imm.Val = Val;
3013     Op->StartLoc = S;
3014     Op->EndLoc = E;
3015     return Op;
3016   }
3017 
3018   static std::unique_ptr<ARMOperand>
3019   CreateMem(unsigned BaseRegNum, const MCConstantExpr *OffsetImm,
3020             unsigned OffsetRegNum, ARM_AM::ShiftOpc ShiftType,
3021             unsigned ShiftImm, unsigned Alignment, bool isNegative, SMLoc S,
3022             SMLoc E, SMLoc AlignmentLoc = SMLoc()) {
3023     auto Op = make_unique<ARMOperand>(k_Memory);
3024     Op->Memory.BaseRegNum = BaseRegNum;
3025     Op->Memory.OffsetImm = OffsetImm;
3026     Op->Memory.OffsetRegNum = OffsetRegNum;
3027     Op->Memory.ShiftType = ShiftType;
3028     Op->Memory.ShiftImm = ShiftImm;
3029     Op->Memory.Alignment = Alignment;
3030     Op->Memory.isNegative = isNegative;
3031     Op->StartLoc = S;
3032     Op->EndLoc = E;
3033     Op->AlignmentLoc = AlignmentLoc;
3034     return Op;
3035   }
3036 
3037   static std::unique_ptr<ARMOperand>
3038   CreatePostIdxReg(unsigned RegNum, bool isAdd, ARM_AM::ShiftOpc ShiftTy,
3039                    unsigned ShiftImm, SMLoc S, SMLoc E) {
3040     auto Op = make_unique<ARMOperand>(k_PostIndexRegister);
3041     Op->PostIdxReg.RegNum = RegNum;
3042     Op->PostIdxReg.isAdd = isAdd;
3043     Op->PostIdxReg.ShiftTy = ShiftTy;
3044     Op->PostIdxReg.ShiftImm = ShiftImm;
3045     Op->StartLoc = S;
3046     Op->EndLoc = E;
3047     return Op;
3048   }
3049 
3050   static std::unique_ptr<ARMOperand> CreateMemBarrierOpt(ARM_MB::MemBOpt Opt,
3051                                                          SMLoc S) {
3052     auto Op = make_unique<ARMOperand>(k_MemBarrierOpt);
3053     Op->MBOpt.Val = Opt;
3054     Op->StartLoc = S;
3055     Op->EndLoc = S;
3056     return Op;
3057   }
3058 
3059   static std::unique_ptr<ARMOperand>
3060   CreateInstSyncBarrierOpt(ARM_ISB::InstSyncBOpt Opt, SMLoc S) {
3061     auto Op = make_unique<ARMOperand>(k_InstSyncBarrierOpt);
3062     Op->ISBOpt.Val = Opt;
3063     Op->StartLoc = S;
3064     Op->EndLoc = S;
3065     return Op;
3066   }
3067 
3068   static std::unique_ptr<ARMOperand> CreateProcIFlags(ARM_PROC::IFlags IFlags,
3069                                                       SMLoc S) {
3070     auto Op = make_unique<ARMOperand>(k_ProcIFlags);
3071     Op->IFlags.Val = IFlags;
3072     Op->StartLoc = S;
3073     Op->EndLoc = S;
3074     return Op;
3075   }
3076 
3077   static std::unique_ptr<ARMOperand> CreateMSRMask(unsigned MMask, SMLoc S) {
3078     auto Op = make_unique<ARMOperand>(k_MSRMask);
3079     Op->MMask.Val = MMask;
3080     Op->StartLoc = S;
3081     Op->EndLoc = S;
3082     return Op;
3083   }
3084 
3085   static std::unique_ptr<ARMOperand> CreateBankedReg(unsigned Reg, SMLoc S) {
3086     auto Op = make_unique<ARMOperand>(k_BankedReg);
3087     Op->BankedReg.Val = Reg;
3088     Op->StartLoc = S;
3089     Op->EndLoc = S;
3090     return Op;
3091   }
3092 };
3093 
3094 } // end anonymous namespace.
3095 
3096 void ARMOperand::print(raw_ostream &OS) const {
3097   switch (Kind) {
3098   case k_CondCode:
3099     OS << "<ARMCC::" << ARMCondCodeToString(getCondCode()) << ">";
3100     break;
3101   case k_CCOut:
3102     OS << "<ccout " << getReg() << ">";
3103     break;
3104   case k_ITCondMask: {
3105     static const char *const MaskStr[] = {
3106       "()", "(t)", "(e)", "(tt)", "(et)", "(te)", "(ee)", "(ttt)", "(ett)",
3107       "(tet)", "(eet)", "(tte)", "(ete)", "(tee)", "(eee)"
3108     };
3109     assert((ITMask.Mask & 0xf) == ITMask.Mask);
3110     OS << "<it-mask " << MaskStr[ITMask.Mask] << ">";
3111     break;
3112   }
3113   case k_CoprocNum:
3114     OS << "<coprocessor number: " << getCoproc() << ">";
3115     break;
3116   case k_CoprocReg:
3117     OS << "<coprocessor register: " << getCoproc() << ">";
3118     break;
3119   case k_CoprocOption:
3120     OS << "<coprocessor option: " << CoprocOption.Val << ">";
3121     break;
3122   case k_MSRMask:
3123     OS << "<mask: " << getMSRMask() << ">";
3124     break;
3125   case k_BankedReg:
3126     OS << "<banked reg: " << getBankedReg() << ">";
3127     break;
3128   case k_Immediate:
3129     OS << *getImm();
3130     break;
3131   case k_MemBarrierOpt:
3132     OS << "<ARM_MB::" << MemBOptToString(getMemBarrierOpt(), false) << ">";
3133     break;
3134   case k_InstSyncBarrierOpt:
3135     OS << "<ARM_ISB::" << InstSyncBOptToString(getInstSyncBarrierOpt()) << ">";
3136     break;
3137   case k_Memory:
3138     OS << "<memory "
3139        << " base:" << Memory.BaseRegNum;
3140     OS << ">";
3141     break;
3142   case k_PostIndexRegister:
3143     OS << "post-idx register " << (PostIdxReg.isAdd ? "" : "-")
3144        << PostIdxReg.RegNum;
3145     if (PostIdxReg.ShiftTy != ARM_AM::no_shift)
3146       OS << ARM_AM::getShiftOpcStr(PostIdxReg.ShiftTy) << " "
3147          << PostIdxReg.ShiftImm;
3148     OS << ">";
3149     break;
3150   case k_ProcIFlags: {
3151     OS << "<ARM_PROC::";
3152     unsigned IFlags = getProcIFlags();
3153     for (int i=2; i >= 0; --i)
3154       if (IFlags & (1 << i))
3155         OS << ARM_PROC::IFlagsToString(1 << i);
3156     OS << ">";
3157     break;
3158   }
3159   case k_Register:
3160     OS << "<register " << getReg() << ">";
3161     break;
3162   case k_ShifterImmediate:
3163     OS << "<shift " << (ShifterImm.isASR ? "asr" : "lsl")
3164        << " #" << ShifterImm.Imm << ">";
3165     break;
3166   case k_ShiftedRegister:
3167     OS << "<so_reg_reg "
3168        << RegShiftedReg.SrcReg << " "
3169        << ARM_AM::getShiftOpcStr(RegShiftedReg.ShiftTy)
3170        << " " << RegShiftedReg.ShiftReg << ">";
3171     break;
3172   case k_ShiftedImmediate:
3173     OS << "<so_reg_imm "
3174        << RegShiftedImm.SrcReg << " "
3175        << ARM_AM::getShiftOpcStr(RegShiftedImm.ShiftTy)
3176        << " #" << RegShiftedImm.ShiftImm << ">";
3177     break;
3178   case k_RotateImmediate:
3179     OS << "<ror " << " #" << (RotImm.Imm * 8) << ">";
3180     break;
3181   case k_ModifiedImmediate:
3182     OS << "<mod_imm #" << ModImm.Bits << ", #"
3183        <<  ModImm.Rot << ")>";
3184     break;
3185   case k_ConstantPoolImmediate:
3186     OS << "<constant_pool_imm #" << *getConstantPoolImm();
3187     break;
3188   case k_BitfieldDescriptor:
3189     OS << "<bitfield " << "lsb: " << Bitfield.LSB
3190        << ", width: " << Bitfield.Width << ">";
3191     break;
3192   case k_RegisterList:
3193   case k_DPRRegisterList:
3194   case k_SPRRegisterList: {
3195     OS << "<register_list ";
3196 
3197     const SmallVectorImpl<unsigned> &RegList = getRegList();
3198     for (SmallVectorImpl<unsigned>::const_iterator
3199            I = RegList.begin(), E = RegList.end(); I != E; ) {
3200       OS << *I;
3201       if (++I < E) OS << ", ";
3202     }
3203 
3204     OS << ">";
3205     break;
3206   }
3207   case k_VectorList:
3208     OS << "<vector_list " << VectorList.Count << " * "
3209        << VectorList.RegNum << ">";
3210     break;
3211   case k_VectorListAllLanes:
3212     OS << "<vector_list(all lanes) " << VectorList.Count << " * "
3213        << VectorList.RegNum << ">";
3214     break;
3215   case k_VectorListIndexed:
3216     OS << "<vector_list(lane " << VectorList.LaneIndex << ") "
3217        << VectorList.Count << " * " << VectorList.RegNum << ">";
3218     break;
3219   case k_Token:
3220     OS << "'" << getToken() << "'";
3221     break;
3222   case k_VectorIndex:
3223     OS << "<vectorindex " << getVectorIndex() << ">";
3224     break;
3225   }
3226 }
3227 
3228 /// @name Auto-generated Match Functions
3229 /// {
3230 
3231 static unsigned MatchRegisterName(StringRef Name);
3232 
3233 /// }
3234 
3235 bool ARMAsmParser::ParseRegister(unsigned &RegNo,
3236                                  SMLoc &StartLoc, SMLoc &EndLoc) {
3237   const AsmToken &Tok = getParser().getTok();
3238   StartLoc = Tok.getLoc();
3239   EndLoc = Tok.getEndLoc();
3240   RegNo = tryParseRegister();
3241 
3242   return (RegNo == (unsigned)-1);
3243 }
3244 
3245 /// Try to parse a register name.  The token must be an Identifier when called,
3246 /// and if it is a register name the token is eaten and the register number is
3247 /// returned.  Otherwise return -1.
3248 int ARMAsmParser::tryParseRegister() {
3249   MCAsmParser &Parser = getParser();
3250   const AsmToken &Tok = Parser.getTok();
3251   if (Tok.isNot(AsmToken::Identifier)) return -1;
3252 
3253   std::string lowerCase = Tok.getString().lower();
3254   unsigned RegNum = MatchRegisterName(lowerCase);
3255   if (!RegNum) {
3256     RegNum = StringSwitch<unsigned>(lowerCase)
3257       .Case("r13", ARM::SP)
3258       .Case("r14", ARM::LR)
3259       .Case("r15", ARM::PC)
3260       .Case("ip", ARM::R12)
3261       // Additional register name aliases for 'gas' compatibility.
3262       .Case("a1", ARM::R0)
3263       .Case("a2", ARM::R1)
3264       .Case("a3", ARM::R2)
3265       .Case("a4", ARM::R3)
3266       .Case("v1", ARM::R4)
3267       .Case("v2", ARM::R5)
3268       .Case("v3", ARM::R6)
3269       .Case("v4", ARM::R7)
3270       .Case("v5", ARM::R8)
3271       .Case("v6", ARM::R9)
3272       .Case("v7", ARM::R10)
3273       .Case("v8", ARM::R11)
3274       .Case("sb", ARM::R9)
3275       .Case("sl", ARM::R10)
3276       .Case("fp", ARM::R11)
3277       .Default(0);
3278   }
3279   if (!RegNum) {
3280     // Check for aliases registered via .req. Canonicalize to lower case.
3281     // That's more consistent since register names are case insensitive, and
3282     // it's how the original entry was passed in from MC/MCParser/AsmParser.
3283     StringMap<unsigned>::const_iterator Entry = RegisterReqs.find(lowerCase);
3284     // If no match, return failure.
3285     if (Entry == RegisterReqs.end())
3286       return -1;
3287     Parser.Lex(); // Eat identifier token.
3288     return Entry->getValue();
3289   }
3290 
3291   // Some FPUs only have 16 D registers, so D16-D31 are invalid
3292   if (hasD16() && RegNum >= ARM::D16 && RegNum <= ARM::D31)
3293     return -1;
3294 
3295   Parser.Lex(); // Eat identifier token.
3296 
3297   return RegNum;
3298 }
3299 
3300 // Try to parse a shifter  (e.g., "lsl <amt>"). On success, return 0.
3301 // If a recoverable error occurs, return 1. If an irrecoverable error
3302 // occurs, return -1. An irrecoverable error is one where tokens have been
3303 // consumed in the process of trying to parse the shifter (i.e., when it is
3304 // indeed a shifter operand, but malformed).
3305 int ARMAsmParser::tryParseShiftRegister(OperandVector &Operands) {
3306   MCAsmParser &Parser = getParser();
3307   SMLoc S = Parser.getTok().getLoc();
3308   const AsmToken &Tok = Parser.getTok();
3309   if (Tok.isNot(AsmToken::Identifier))
3310     return -1;
3311 
3312   std::string lowerCase = Tok.getString().lower();
3313   ARM_AM::ShiftOpc ShiftTy = StringSwitch<ARM_AM::ShiftOpc>(lowerCase)
3314       .Case("asl", ARM_AM::lsl)
3315       .Case("lsl", ARM_AM::lsl)
3316       .Case("lsr", ARM_AM::lsr)
3317       .Case("asr", ARM_AM::asr)
3318       .Case("ror", ARM_AM::ror)
3319       .Case("rrx", ARM_AM::rrx)
3320       .Default(ARM_AM::no_shift);
3321 
3322   if (ShiftTy == ARM_AM::no_shift)
3323     return 1;
3324 
3325   Parser.Lex(); // Eat the operator.
3326 
3327   // The source register for the shift has already been added to the
3328   // operand list, so we need to pop it off and combine it into the shifted
3329   // register operand instead.
3330   std::unique_ptr<ARMOperand> PrevOp(
3331       (ARMOperand *)Operands.pop_back_val().release());
3332   if (!PrevOp->isReg())
3333     return Error(PrevOp->getStartLoc(), "shift must be of a register");
3334   int SrcReg = PrevOp->getReg();
3335 
3336   SMLoc EndLoc;
3337   int64_t Imm = 0;
3338   int ShiftReg = 0;
3339   if (ShiftTy == ARM_AM::rrx) {
3340     // RRX Doesn't have an explicit shift amount. The encoder expects
3341     // the shift register to be the same as the source register. Seems odd,
3342     // but OK.
3343     ShiftReg = SrcReg;
3344   } else {
3345     // Figure out if this is shifted by a constant or a register (for non-RRX).
3346     if (Parser.getTok().is(AsmToken::Hash) ||
3347         Parser.getTok().is(AsmToken::Dollar)) {
3348       Parser.Lex(); // Eat hash.
3349       SMLoc ImmLoc = Parser.getTok().getLoc();
3350       const MCExpr *ShiftExpr = nullptr;
3351       if (getParser().parseExpression(ShiftExpr, EndLoc)) {
3352         Error(ImmLoc, "invalid immediate shift value");
3353         return -1;
3354       }
3355       // The expression must be evaluatable as an immediate.
3356       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftExpr);
3357       if (!CE) {
3358         Error(ImmLoc, "invalid immediate shift value");
3359         return -1;
3360       }
3361       // Range check the immediate.
3362       // lsl, ror: 0 <= imm <= 31
3363       // lsr, asr: 0 <= imm <= 32
3364       Imm = CE->getValue();
3365       if (Imm < 0 ||
3366           ((ShiftTy == ARM_AM::lsl || ShiftTy == ARM_AM::ror) && Imm > 31) ||
3367           ((ShiftTy == ARM_AM::lsr || ShiftTy == ARM_AM::asr) && Imm > 32)) {
3368         Error(ImmLoc, "immediate shift value out of range");
3369         return -1;
3370       }
3371       // shift by zero is a nop. Always send it through as lsl.
3372       // ('as' compatibility)
3373       if (Imm == 0)
3374         ShiftTy = ARM_AM::lsl;
3375     } else if (Parser.getTok().is(AsmToken::Identifier)) {
3376       SMLoc L = Parser.getTok().getLoc();
3377       EndLoc = Parser.getTok().getEndLoc();
3378       ShiftReg = tryParseRegister();
3379       if (ShiftReg == -1) {
3380         Error(L, "expected immediate or register in shift operand");
3381         return -1;
3382       }
3383     } else {
3384       Error(Parser.getTok().getLoc(),
3385             "expected immediate or register in shift operand");
3386       return -1;
3387     }
3388   }
3389 
3390   if (ShiftReg && ShiftTy != ARM_AM::rrx)
3391     Operands.push_back(ARMOperand::CreateShiftedRegister(ShiftTy, SrcReg,
3392                                                          ShiftReg, Imm,
3393                                                          S, EndLoc));
3394   else
3395     Operands.push_back(ARMOperand::CreateShiftedImmediate(ShiftTy, SrcReg, Imm,
3396                                                           S, EndLoc));
3397 
3398   return 0;
3399 }
3400 
3401 /// Try to parse a register name.  The token must be an Identifier when called.
3402 /// If it's a register, an AsmOperand is created. Another AsmOperand is created
3403 /// if there is a "writeback". 'true' if it's not a register.
3404 ///
3405 /// TODO this is likely to change to allow different register types and or to
3406 /// parse for a specific register type.
3407 bool ARMAsmParser::tryParseRegisterWithWriteBack(OperandVector &Operands) {
3408   MCAsmParser &Parser = getParser();
3409   SMLoc RegStartLoc = Parser.getTok().getLoc();
3410   SMLoc RegEndLoc = Parser.getTok().getEndLoc();
3411   int RegNo = tryParseRegister();
3412   if (RegNo == -1)
3413     return true;
3414 
3415   Operands.push_back(ARMOperand::CreateReg(RegNo, RegStartLoc, RegEndLoc));
3416 
3417   const AsmToken &ExclaimTok = Parser.getTok();
3418   if (ExclaimTok.is(AsmToken::Exclaim)) {
3419     Operands.push_back(ARMOperand::CreateToken(ExclaimTok.getString(),
3420                                                ExclaimTok.getLoc()));
3421     Parser.Lex(); // Eat exclaim token
3422     return false;
3423   }
3424 
3425   // Also check for an index operand. This is only legal for vector registers,
3426   // but that'll get caught OK in operand matching, so we don't need to
3427   // explicitly filter everything else out here.
3428   if (Parser.getTok().is(AsmToken::LBrac)) {
3429     SMLoc SIdx = Parser.getTok().getLoc();
3430     Parser.Lex(); // Eat left bracket token.
3431 
3432     const MCExpr *ImmVal;
3433     if (getParser().parseExpression(ImmVal))
3434       return true;
3435     const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(ImmVal);
3436     if (!MCE)
3437       return TokError("immediate value expected for vector index");
3438 
3439     if (Parser.getTok().isNot(AsmToken::RBrac))
3440       return Error(Parser.getTok().getLoc(), "']' expected");
3441 
3442     SMLoc E = Parser.getTok().getEndLoc();
3443     Parser.Lex(); // Eat right bracket token.
3444 
3445     Operands.push_back(ARMOperand::CreateVectorIndex(MCE->getValue(),
3446                                                      SIdx, E,
3447                                                      getContext()));
3448   }
3449 
3450   return false;
3451 }
3452 
3453 /// MatchCoprocessorOperandName - Try to parse an coprocessor related
3454 /// instruction with a symbolic operand name.
3455 /// We accept "crN" syntax for GAS compatibility.
3456 /// <operand-name> ::= <prefix><number>
3457 /// If CoprocOp is 'c', then:
3458 ///   <prefix> ::= c | cr
3459 /// If CoprocOp is 'p', then :
3460 ///   <prefix> ::= p
3461 /// <number> ::= integer in range [0, 15]
3462 static int MatchCoprocessorOperandName(StringRef Name, char CoprocOp) {
3463   // Use the same layout as the tablegen'erated register name matcher. Ugly,
3464   // but efficient.
3465   if (Name.size() < 2 || Name[0] != CoprocOp)
3466     return -1;
3467   Name = (Name[1] == 'r') ? Name.drop_front(2) : Name.drop_front();
3468 
3469   switch (Name.size()) {
3470   default: return -1;
3471   case 1:
3472     switch (Name[0]) {
3473     default:  return -1;
3474     case '0': return 0;
3475     case '1': return 1;
3476     case '2': return 2;
3477     case '3': return 3;
3478     case '4': return 4;
3479     case '5': return 5;
3480     case '6': return 6;
3481     case '7': return 7;
3482     case '8': return 8;
3483     case '9': return 9;
3484     }
3485   case 2:
3486     if (Name[0] != '1')
3487       return -1;
3488     switch (Name[1]) {
3489     default:  return -1;
3490     // CP10 and CP11 are VFP/NEON and so vector instructions should be used.
3491     // However, old cores (v5/v6) did use them in that way.
3492     case '0': return 10;
3493     case '1': return 11;
3494     case '2': return 12;
3495     case '3': return 13;
3496     case '4': return 14;
3497     case '5': return 15;
3498     }
3499   }
3500 }
3501 
3502 /// parseITCondCode - Try to parse a condition code for an IT instruction.
3503 OperandMatchResultTy
3504 ARMAsmParser::parseITCondCode(OperandVector &Operands) {
3505   MCAsmParser &Parser = getParser();
3506   SMLoc S = Parser.getTok().getLoc();
3507   const AsmToken &Tok = Parser.getTok();
3508   if (!Tok.is(AsmToken::Identifier))
3509     return MatchOperand_NoMatch;
3510   unsigned CC = ARMCondCodeFromString(Tok.getString());
3511   if (CC == ~0U)
3512     return MatchOperand_NoMatch;
3513   Parser.Lex(); // Eat the token.
3514 
3515   Operands.push_back(ARMOperand::CreateCondCode(ARMCC::CondCodes(CC), S));
3516 
3517   return MatchOperand_Success;
3518 }
3519 
3520 /// parseCoprocNumOperand - Try to parse an coprocessor number operand. The
3521 /// token must be an Identifier when called, and if it is a coprocessor
3522 /// number, the token is eaten and the operand is added to the operand list.
3523 OperandMatchResultTy
3524 ARMAsmParser::parseCoprocNumOperand(OperandVector &Operands) {
3525   MCAsmParser &Parser = getParser();
3526   SMLoc S = Parser.getTok().getLoc();
3527   const AsmToken &Tok = Parser.getTok();
3528   if (Tok.isNot(AsmToken::Identifier))
3529     return MatchOperand_NoMatch;
3530 
3531   int Num = MatchCoprocessorOperandName(Tok.getString(), 'p');
3532   if (Num == -1)
3533     return MatchOperand_NoMatch;
3534   // ARMv7 and v8 don't allow cp10/cp11 due to VFP/NEON specific instructions
3535   if ((hasV7Ops() || hasV8Ops()) && (Num == 10 || Num == 11))
3536     return MatchOperand_NoMatch;
3537 
3538   Parser.Lex(); // Eat identifier token.
3539   Operands.push_back(ARMOperand::CreateCoprocNum(Num, S));
3540   return MatchOperand_Success;
3541 }
3542 
3543 /// parseCoprocRegOperand - Try to parse an coprocessor register operand. The
3544 /// token must be an Identifier when called, and if it is a coprocessor
3545 /// number, the token is eaten and the operand is added to the operand list.
3546 OperandMatchResultTy
3547 ARMAsmParser::parseCoprocRegOperand(OperandVector &Operands) {
3548   MCAsmParser &Parser = getParser();
3549   SMLoc S = Parser.getTok().getLoc();
3550   const AsmToken &Tok = Parser.getTok();
3551   if (Tok.isNot(AsmToken::Identifier))
3552     return MatchOperand_NoMatch;
3553 
3554   int Reg = MatchCoprocessorOperandName(Tok.getString(), 'c');
3555   if (Reg == -1)
3556     return MatchOperand_NoMatch;
3557 
3558   Parser.Lex(); // Eat identifier token.
3559   Operands.push_back(ARMOperand::CreateCoprocReg(Reg, S));
3560   return MatchOperand_Success;
3561 }
3562 
3563 /// parseCoprocOptionOperand - Try to parse an coprocessor option operand.
3564 /// coproc_option : '{' imm0_255 '}'
3565 OperandMatchResultTy
3566 ARMAsmParser::parseCoprocOptionOperand(OperandVector &Operands) {
3567   MCAsmParser &Parser = getParser();
3568   SMLoc S = Parser.getTok().getLoc();
3569 
3570   // If this isn't a '{', this isn't a coprocessor immediate operand.
3571   if (Parser.getTok().isNot(AsmToken::LCurly))
3572     return MatchOperand_NoMatch;
3573   Parser.Lex(); // Eat the '{'
3574 
3575   const MCExpr *Expr;
3576   SMLoc Loc = Parser.getTok().getLoc();
3577   if (getParser().parseExpression(Expr)) {
3578     Error(Loc, "illegal expression");
3579     return MatchOperand_ParseFail;
3580   }
3581   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
3582   if (!CE || CE->getValue() < 0 || CE->getValue() > 255) {
3583     Error(Loc, "coprocessor option must be an immediate in range [0, 255]");
3584     return MatchOperand_ParseFail;
3585   }
3586   int Val = CE->getValue();
3587 
3588   // Check for and consume the closing '}'
3589   if (Parser.getTok().isNot(AsmToken::RCurly))
3590     return MatchOperand_ParseFail;
3591   SMLoc E = Parser.getTok().getEndLoc();
3592   Parser.Lex(); // Eat the '}'
3593 
3594   Operands.push_back(ARMOperand::CreateCoprocOption(Val, S, E));
3595   return MatchOperand_Success;
3596 }
3597 
3598 // For register list parsing, we need to map from raw GPR register numbering
3599 // to the enumeration values. The enumeration values aren't sorted by
3600 // register number due to our using "sp", "lr" and "pc" as canonical names.
3601 static unsigned getNextRegister(unsigned Reg) {
3602   // If this is a GPR, we need to do it manually, otherwise we can rely
3603   // on the sort ordering of the enumeration since the other reg-classes
3604   // are sane.
3605   if (!ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
3606     return Reg + 1;
3607   switch(Reg) {
3608   default: llvm_unreachable("Invalid GPR number!");
3609   case ARM::R0:  return ARM::R1;  case ARM::R1:  return ARM::R2;
3610   case ARM::R2:  return ARM::R3;  case ARM::R3:  return ARM::R4;
3611   case ARM::R4:  return ARM::R5;  case ARM::R5:  return ARM::R6;
3612   case ARM::R6:  return ARM::R7;  case ARM::R7:  return ARM::R8;
3613   case ARM::R8:  return ARM::R9;  case ARM::R9:  return ARM::R10;
3614   case ARM::R10: return ARM::R11; case ARM::R11: return ARM::R12;
3615   case ARM::R12: return ARM::SP;  case ARM::SP:  return ARM::LR;
3616   case ARM::LR:  return ARM::PC;  case ARM::PC:  return ARM::R0;
3617   }
3618 }
3619 
3620 /// Parse a register list.
3621 bool ARMAsmParser::parseRegisterList(OperandVector &Operands) {
3622   MCAsmParser &Parser = getParser();
3623   if (Parser.getTok().isNot(AsmToken::LCurly))
3624     return TokError("Token is not a Left Curly Brace");
3625   SMLoc S = Parser.getTok().getLoc();
3626   Parser.Lex(); // Eat '{' token.
3627   SMLoc RegLoc = Parser.getTok().getLoc();
3628 
3629   // Check the first register in the list to see what register class
3630   // this is a list of.
3631   int Reg = tryParseRegister();
3632   if (Reg == -1)
3633     return Error(RegLoc, "register expected");
3634 
3635   // The reglist instructions have at most 16 registers, so reserve
3636   // space for that many.
3637   int EReg = 0;
3638   SmallVector<std::pair<unsigned, unsigned>, 16> Registers;
3639 
3640   // Allow Q regs and just interpret them as the two D sub-registers.
3641   if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3642     Reg = getDRegFromQReg(Reg);
3643     EReg = MRI->getEncodingValue(Reg);
3644     Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3645     ++Reg;
3646   }
3647   const MCRegisterClass *RC;
3648   if (ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
3649     RC = &ARMMCRegisterClasses[ARM::GPRRegClassID];
3650   else if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Reg))
3651     RC = &ARMMCRegisterClasses[ARM::DPRRegClassID];
3652   else if (ARMMCRegisterClasses[ARM::SPRRegClassID].contains(Reg))
3653     RC = &ARMMCRegisterClasses[ARM::SPRRegClassID];
3654   else
3655     return Error(RegLoc, "invalid register in register list");
3656 
3657   // Store the register.
3658   EReg = MRI->getEncodingValue(Reg);
3659   Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3660 
3661   // This starts immediately after the first register token in the list,
3662   // so we can see either a comma or a minus (range separator) as a legal
3663   // next token.
3664   while (Parser.getTok().is(AsmToken::Comma) ||
3665          Parser.getTok().is(AsmToken::Minus)) {
3666     if (Parser.getTok().is(AsmToken::Minus)) {
3667       Parser.Lex(); // Eat the minus.
3668       SMLoc AfterMinusLoc = Parser.getTok().getLoc();
3669       int EndReg = tryParseRegister();
3670       if (EndReg == -1)
3671         return Error(AfterMinusLoc, "register expected");
3672       // Allow Q regs and just interpret them as the two D sub-registers.
3673       if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(EndReg))
3674         EndReg = getDRegFromQReg(EndReg) + 1;
3675       // If the register is the same as the start reg, there's nothing
3676       // more to do.
3677       if (Reg == EndReg)
3678         continue;
3679       // The register must be in the same register class as the first.
3680       if (!RC->contains(EndReg))
3681         return Error(AfterMinusLoc, "invalid register in register list");
3682       // Ranges must go from low to high.
3683       if (MRI->getEncodingValue(Reg) > MRI->getEncodingValue(EndReg))
3684         return Error(AfterMinusLoc, "bad range in register list");
3685 
3686       // Add all the registers in the range to the register list.
3687       while (Reg != EndReg) {
3688         Reg = getNextRegister(Reg);
3689         EReg = MRI->getEncodingValue(Reg);
3690         Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3691       }
3692       continue;
3693     }
3694     Parser.Lex(); // Eat the comma.
3695     RegLoc = Parser.getTok().getLoc();
3696     int OldReg = Reg;
3697     const AsmToken RegTok = Parser.getTok();
3698     Reg = tryParseRegister();
3699     if (Reg == -1)
3700       return Error(RegLoc, "register expected");
3701     // Allow Q regs and just interpret them as the two D sub-registers.
3702     bool isQReg = false;
3703     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3704       Reg = getDRegFromQReg(Reg);
3705       isQReg = true;
3706     }
3707     // The register must be in the same register class as the first.
3708     if (!RC->contains(Reg))
3709       return Error(RegLoc, "invalid register in register list");
3710     // List must be monotonically increasing.
3711     if (MRI->getEncodingValue(Reg) < MRI->getEncodingValue(OldReg)) {
3712       if (ARMMCRegisterClasses[ARM::GPRRegClassID].contains(Reg))
3713         Warning(RegLoc, "register list not in ascending order");
3714       else
3715         return Error(RegLoc, "register list not in ascending order");
3716     }
3717     if (MRI->getEncodingValue(Reg) == MRI->getEncodingValue(OldReg)) {
3718       Warning(RegLoc, "duplicated register (" + RegTok.getString() +
3719               ") in register list");
3720       continue;
3721     }
3722     // VFP register lists must also be contiguous.
3723     if (RC != &ARMMCRegisterClasses[ARM::GPRRegClassID] &&
3724         Reg != OldReg + 1)
3725       return Error(RegLoc, "non-contiguous register range");
3726     EReg = MRI->getEncodingValue(Reg);
3727     Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3728     if (isQReg) {
3729       EReg = MRI->getEncodingValue(++Reg);
3730       Registers.push_back(std::pair<unsigned, unsigned>(EReg, Reg));
3731     }
3732   }
3733 
3734   if (Parser.getTok().isNot(AsmToken::RCurly))
3735     return Error(Parser.getTok().getLoc(), "'}' expected");
3736   SMLoc E = Parser.getTok().getEndLoc();
3737   Parser.Lex(); // Eat '}' token.
3738 
3739   // Push the register list operand.
3740   Operands.push_back(ARMOperand::CreateRegList(Registers, S, E));
3741 
3742   // The ARM system instruction variants for LDM/STM have a '^' token here.
3743   if (Parser.getTok().is(AsmToken::Caret)) {
3744     Operands.push_back(ARMOperand::CreateToken("^",Parser.getTok().getLoc()));
3745     Parser.Lex(); // Eat '^' token.
3746   }
3747 
3748   return false;
3749 }
3750 
3751 // Helper function to parse the lane index for vector lists.
3752 OperandMatchResultTy ARMAsmParser::
3753 parseVectorLane(VectorLaneTy &LaneKind, unsigned &Index, SMLoc &EndLoc) {
3754   MCAsmParser &Parser = getParser();
3755   Index = 0; // Always return a defined index value.
3756   if (Parser.getTok().is(AsmToken::LBrac)) {
3757     Parser.Lex(); // Eat the '['.
3758     if (Parser.getTok().is(AsmToken::RBrac)) {
3759       // "Dn[]" is the 'all lanes' syntax.
3760       LaneKind = AllLanes;
3761       EndLoc = Parser.getTok().getEndLoc();
3762       Parser.Lex(); // Eat the ']'.
3763       return MatchOperand_Success;
3764     }
3765 
3766     // There's an optional '#' token here. Normally there wouldn't be, but
3767     // inline assemble puts one in, and it's friendly to accept that.
3768     if (Parser.getTok().is(AsmToken::Hash))
3769       Parser.Lex(); // Eat '#' or '$'.
3770 
3771     const MCExpr *LaneIndex;
3772     SMLoc Loc = Parser.getTok().getLoc();
3773     if (getParser().parseExpression(LaneIndex)) {
3774       Error(Loc, "illegal expression");
3775       return MatchOperand_ParseFail;
3776     }
3777     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(LaneIndex);
3778     if (!CE) {
3779       Error(Loc, "lane index must be empty or an integer");
3780       return MatchOperand_ParseFail;
3781     }
3782     if (Parser.getTok().isNot(AsmToken::RBrac)) {
3783       Error(Parser.getTok().getLoc(), "']' expected");
3784       return MatchOperand_ParseFail;
3785     }
3786     EndLoc = Parser.getTok().getEndLoc();
3787     Parser.Lex(); // Eat the ']'.
3788     int64_t Val = CE->getValue();
3789 
3790     // FIXME: Make this range check context sensitive for .8, .16, .32.
3791     if (Val < 0 || Val > 7) {
3792       Error(Parser.getTok().getLoc(), "lane index out of range");
3793       return MatchOperand_ParseFail;
3794     }
3795     Index = Val;
3796     LaneKind = IndexedLane;
3797     return MatchOperand_Success;
3798   }
3799   LaneKind = NoLanes;
3800   return MatchOperand_Success;
3801 }
3802 
3803 // parse a vector register list
3804 OperandMatchResultTy
3805 ARMAsmParser::parseVectorList(OperandVector &Operands) {
3806   MCAsmParser &Parser = getParser();
3807   VectorLaneTy LaneKind;
3808   unsigned LaneIndex;
3809   SMLoc S = Parser.getTok().getLoc();
3810   // As an extension (to match gas), support a plain D register or Q register
3811   // (without encosing curly braces) as a single or double entry list,
3812   // respectively.
3813   if (Parser.getTok().is(AsmToken::Identifier)) {
3814     SMLoc E = Parser.getTok().getEndLoc();
3815     int Reg = tryParseRegister();
3816     if (Reg == -1)
3817       return MatchOperand_NoMatch;
3818     if (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(Reg)) {
3819       OperandMatchResultTy Res = parseVectorLane(LaneKind, LaneIndex, E);
3820       if (Res != MatchOperand_Success)
3821         return Res;
3822       switch (LaneKind) {
3823       case NoLanes:
3824         Operands.push_back(ARMOperand::CreateVectorList(Reg, 1, false, S, E));
3825         break;
3826       case AllLanes:
3827         Operands.push_back(ARMOperand::CreateVectorListAllLanes(Reg, 1, false,
3828                                                                 S, E));
3829         break;
3830       case IndexedLane:
3831         Operands.push_back(ARMOperand::CreateVectorListIndexed(Reg, 1,
3832                                                                LaneIndex,
3833                                                                false, S, E));
3834         break;
3835       }
3836       return MatchOperand_Success;
3837     }
3838     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3839       Reg = getDRegFromQReg(Reg);
3840       OperandMatchResultTy Res = parseVectorLane(LaneKind, LaneIndex, E);
3841       if (Res != MatchOperand_Success)
3842         return Res;
3843       switch (LaneKind) {
3844       case NoLanes:
3845         Reg = MRI->getMatchingSuperReg(Reg, ARM::dsub_0,
3846                                    &ARMMCRegisterClasses[ARM::DPairRegClassID]);
3847         Operands.push_back(ARMOperand::CreateVectorList(Reg, 2, false, S, E));
3848         break;
3849       case AllLanes:
3850         Reg = MRI->getMatchingSuperReg(Reg, ARM::dsub_0,
3851                                    &ARMMCRegisterClasses[ARM::DPairRegClassID]);
3852         Operands.push_back(ARMOperand::CreateVectorListAllLanes(Reg, 2, false,
3853                                                                 S, E));
3854         break;
3855       case IndexedLane:
3856         Operands.push_back(ARMOperand::CreateVectorListIndexed(Reg, 2,
3857                                                                LaneIndex,
3858                                                                false, S, E));
3859         break;
3860       }
3861       return MatchOperand_Success;
3862     }
3863     Error(S, "vector register expected");
3864     return MatchOperand_ParseFail;
3865   }
3866 
3867   if (Parser.getTok().isNot(AsmToken::LCurly))
3868     return MatchOperand_NoMatch;
3869 
3870   Parser.Lex(); // Eat '{' token.
3871   SMLoc RegLoc = Parser.getTok().getLoc();
3872 
3873   int Reg = tryParseRegister();
3874   if (Reg == -1) {
3875     Error(RegLoc, "register expected");
3876     return MatchOperand_ParseFail;
3877   }
3878   unsigned Count = 1;
3879   int Spacing = 0;
3880   unsigned FirstReg = Reg;
3881   // The list is of D registers, but we also allow Q regs and just interpret
3882   // them as the two D sub-registers.
3883   if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3884     FirstReg = Reg = getDRegFromQReg(Reg);
3885     Spacing = 1; // double-spacing requires explicit D registers, otherwise
3886                  // it's ambiguous with four-register single spaced.
3887     ++Reg;
3888     ++Count;
3889   }
3890 
3891   SMLoc E;
3892   if (parseVectorLane(LaneKind, LaneIndex, E) != MatchOperand_Success)
3893     return MatchOperand_ParseFail;
3894 
3895   while (Parser.getTok().is(AsmToken::Comma) ||
3896          Parser.getTok().is(AsmToken::Minus)) {
3897     if (Parser.getTok().is(AsmToken::Minus)) {
3898       if (!Spacing)
3899         Spacing = 1; // Register range implies a single spaced list.
3900       else if (Spacing == 2) {
3901         Error(Parser.getTok().getLoc(),
3902               "sequential registers in double spaced list");
3903         return MatchOperand_ParseFail;
3904       }
3905       Parser.Lex(); // Eat the minus.
3906       SMLoc AfterMinusLoc = Parser.getTok().getLoc();
3907       int EndReg = tryParseRegister();
3908       if (EndReg == -1) {
3909         Error(AfterMinusLoc, "register expected");
3910         return MatchOperand_ParseFail;
3911       }
3912       // Allow Q regs and just interpret them as the two D sub-registers.
3913       if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(EndReg))
3914         EndReg = getDRegFromQReg(EndReg) + 1;
3915       // If the register is the same as the start reg, there's nothing
3916       // more to do.
3917       if (Reg == EndReg)
3918         continue;
3919       // The register must be in the same register class as the first.
3920       if (!ARMMCRegisterClasses[ARM::DPRRegClassID].contains(EndReg)) {
3921         Error(AfterMinusLoc, "invalid register in register list");
3922         return MatchOperand_ParseFail;
3923       }
3924       // Ranges must go from low to high.
3925       if (Reg > EndReg) {
3926         Error(AfterMinusLoc, "bad range in register list");
3927         return MatchOperand_ParseFail;
3928       }
3929       // Parse the lane specifier if present.
3930       VectorLaneTy NextLaneKind;
3931       unsigned NextLaneIndex;
3932       if (parseVectorLane(NextLaneKind, NextLaneIndex, E) !=
3933           MatchOperand_Success)
3934         return MatchOperand_ParseFail;
3935       if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
3936         Error(AfterMinusLoc, "mismatched lane index in register list");
3937         return MatchOperand_ParseFail;
3938       }
3939 
3940       // Add all the registers in the range to the register list.
3941       Count += EndReg - Reg;
3942       Reg = EndReg;
3943       continue;
3944     }
3945     Parser.Lex(); // Eat the comma.
3946     RegLoc = Parser.getTok().getLoc();
3947     int OldReg = Reg;
3948     Reg = tryParseRegister();
3949     if (Reg == -1) {
3950       Error(RegLoc, "register expected");
3951       return MatchOperand_ParseFail;
3952     }
3953     // vector register lists must be contiguous.
3954     // It's OK to use the enumeration values directly here rather, as the
3955     // VFP register classes have the enum sorted properly.
3956     //
3957     // The list is of D registers, but we also allow Q regs and just interpret
3958     // them as the two D sub-registers.
3959     if (ARMMCRegisterClasses[ARM::QPRRegClassID].contains(Reg)) {
3960       if (!Spacing)
3961         Spacing = 1; // Register range implies a single spaced list.
3962       else if (Spacing == 2) {
3963         Error(RegLoc,
3964               "invalid register in double-spaced list (must be 'D' register')");
3965         return MatchOperand_ParseFail;
3966       }
3967       Reg = getDRegFromQReg(Reg);
3968       if (Reg != OldReg + 1) {
3969         Error(RegLoc, "non-contiguous register range");
3970         return MatchOperand_ParseFail;
3971       }
3972       ++Reg;
3973       Count += 2;
3974       // Parse the lane specifier if present.
3975       VectorLaneTy NextLaneKind;
3976       unsigned NextLaneIndex;
3977       SMLoc LaneLoc = Parser.getTok().getLoc();
3978       if (parseVectorLane(NextLaneKind, NextLaneIndex, E) !=
3979           MatchOperand_Success)
3980         return MatchOperand_ParseFail;
3981       if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
3982         Error(LaneLoc, "mismatched lane index in register list");
3983         return MatchOperand_ParseFail;
3984       }
3985       continue;
3986     }
3987     // Normal D register.
3988     // Figure out the register spacing (single or double) of the list if
3989     // we don't know it already.
3990     if (!Spacing)
3991       Spacing = 1 + (Reg == OldReg + 2);
3992 
3993     // Just check that it's contiguous and keep going.
3994     if (Reg != OldReg + Spacing) {
3995       Error(RegLoc, "non-contiguous register range");
3996       return MatchOperand_ParseFail;
3997     }
3998     ++Count;
3999     // Parse the lane specifier if present.
4000     VectorLaneTy NextLaneKind;
4001     unsigned NextLaneIndex;
4002     SMLoc EndLoc = Parser.getTok().getLoc();
4003     if (parseVectorLane(NextLaneKind, NextLaneIndex, E) != MatchOperand_Success)
4004       return MatchOperand_ParseFail;
4005     if (NextLaneKind != LaneKind || LaneIndex != NextLaneIndex) {
4006       Error(EndLoc, "mismatched lane index in register list");
4007       return MatchOperand_ParseFail;
4008     }
4009   }
4010 
4011   if (Parser.getTok().isNot(AsmToken::RCurly)) {
4012     Error(Parser.getTok().getLoc(), "'}' expected");
4013     return MatchOperand_ParseFail;
4014   }
4015   E = Parser.getTok().getEndLoc();
4016   Parser.Lex(); // Eat '}' token.
4017 
4018   switch (LaneKind) {
4019   case NoLanes:
4020     // Two-register operands have been converted to the
4021     // composite register classes.
4022     if (Count == 2) {
4023       const MCRegisterClass *RC = (Spacing == 1) ?
4024         &ARMMCRegisterClasses[ARM::DPairRegClassID] :
4025         &ARMMCRegisterClasses[ARM::DPairSpcRegClassID];
4026       FirstReg = MRI->getMatchingSuperReg(FirstReg, ARM::dsub_0, RC);
4027     }
4028     Operands.push_back(ARMOperand::CreateVectorList(FirstReg, Count,
4029                                                     (Spacing == 2), S, E));
4030     break;
4031   case AllLanes:
4032     // Two-register operands have been converted to the
4033     // composite register classes.
4034     if (Count == 2) {
4035       const MCRegisterClass *RC = (Spacing == 1) ?
4036         &ARMMCRegisterClasses[ARM::DPairRegClassID] :
4037         &ARMMCRegisterClasses[ARM::DPairSpcRegClassID];
4038       FirstReg = MRI->getMatchingSuperReg(FirstReg, ARM::dsub_0, RC);
4039     }
4040     Operands.push_back(ARMOperand::CreateVectorListAllLanes(FirstReg, Count,
4041                                                             (Spacing == 2),
4042                                                             S, E));
4043     break;
4044   case IndexedLane:
4045     Operands.push_back(ARMOperand::CreateVectorListIndexed(FirstReg, Count,
4046                                                            LaneIndex,
4047                                                            (Spacing == 2),
4048                                                            S, E));
4049     break;
4050   }
4051   return MatchOperand_Success;
4052 }
4053 
4054 /// parseMemBarrierOptOperand - Try to parse DSB/DMB data barrier options.
4055 OperandMatchResultTy
4056 ARMAsmParser::parseMemBarrierOptOperand(OperandVector &Operands) {
4057   MCAsmParser &Parser = getParser();
4058   SMLoc S = Parser.getTok().getLoc();
4059   const AsmToken &Tok = Parser.getTok();
4060   unsigned Opt;
4061 
4062   if (Tok.is(AsmToken::Identifier)) {
4063     StringRef OptStr = Tok.getString();
4064 
4065     Opt = StringSwitch<unsigned>(OptStr.slice(0, OptStr.size()).lower())
4066       .Case("sy",    ARM_MB::SY)
4067       .Case("st",    ARM_MB::ST)
4068       .Case("ld",    ARM_MB::LD)
4069       .Case("sh",    ARM_MB::ISH)
4070       .Case("ish",   ARM_MB::ISH)
4071       .Case("shst",  ARM_MB::ISHST)
4072       .Case("ishst", ARM_MB::ISHST)
4073       .Case("ishld", ARM_MB::ISHLD)
4074       .Case("nsh",   ARM_MB::NSH)
4075       .Case("un",    ARM_MB::NSH)
4076       .Case("nshst", ARM_MB::NSHST)
4077       .Case("nshld", ARM_MB::NSHLD)
4078       .Case("unst",  ARM_MB::NSHST)
4079       .Case("osh",   ARM_MB::OSH)
4080       .Case("oshst", ARM_MB::OSHST)
4081       .Case("oshld", ARM_MB::OSHLD)
4082       .Default(~0U);
4083 
4084     // ishld, oshld, nshld and ld are only available from ARMv8.
4085     if (!hasV8Ops() && (Opt == ARM_MB::ISHLD || Opt == ARM_MB::OSHLD ||
4086                         Opt == ARM_MB::NSHLD || Opt == ARM_MB::LD))
4087       Opt = ~0U;
4088 
4089     if (Opt == ~0U)
4090       return MatchOperand_NoMatch;
4091 
4092     Parser.Lex(); // Eat identifier token.
4093   } else if (Tok.is(AsmToken::Hash) ||
4094              Tok.is(AsmToken::Dollar) ||
4095              Tok.is(AsmToken::Integer)) {
4096     if (Parser.getTok().isNot(AsmToken::Integer))
4097       Parser.Lex(); // Eat '#' or '$'.
4098     SMLoc Loc = Parser.getTok().getLoc();
4099 
4100     const MCExpr *MemBarrierID;
4101     if (getParser().parseExpression(MemBarrierID)) {
4102       Error(Loc, "illegal expression");
4103       return MatchOperand_ParseFail;
4104     }
4105 
4106     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(MemBarrierID);
4107     if (!CE) {
4108       Error(Loc, "constant expression expected");
4109       return MatchOperand_ParseFail;
4110     }
4111 
4112     int Val = CE->getValue();
4113     if (Val & ~0xf) {
4114       Error(Loc, "immediate value out of range");
4115       return MatchOperand_ParseFail;
4116     }
4117 
4118     Opt = ARM_MB::RESERVED_0 + Val;
4119   } else
4120     return MatchOperand_ParseFail;
4121 
4122   Operands.push_back(ARMOperand::CreateMemBarrierOpt((ARM_MB::MemBOpt)Opt, S));
4123   return MatchOperand_Success;
4124 }
4125 
4126 /// parseInstSyncBarrierOptOperand - Try to parse ISB inst sync barrier options.
4127 OperandMatchResultTy
4128 ARMAsmParser::parseInstSyncBarrierOptOperand(OperandVector &Operands) {
4129   MCAsmParser &Parser = getParser();
4130   SMLoc S = Parser.getTok().getLoc();
4131   const AsmToken &Tok = Parser.getTok();
4132   unsigned Opt;
4133 
4134   if (Tok.is(AsmToken::Identifier)) {
4135     StringRef OptStr = Tok.getString();
4136 
4137     if (OptStr.equals_lower("sy"))
4138       Opt = ARM_ISB::SY;
4139     else
4140       return MatchOperand_NoMatch;
4141 
4142     Parser.Lex(); // Eat identifier token.
4143   } else if (Tok.is(AsmToken::Hash) ||
4144              Tok.is(AsmToken::Dollar) ||
4145              Tok.is(AsmToken::Integer)) {
4146     if (Parser.getTok().isNot(AsmToken::Integer))
4147       Parser.Lex(); // Eat '#' or '$'.
4148     SMLoc Loc = Parser.getTok().getLoc();
4149 
4150     const MCExpr *ISBarrierID;
4151     if (getParser().parseExpression(ISBarrierID)) {
4152       Error(Loc, "illegal expression");
4153       return MatchOperand_ParseFail;
4154     }
4155 
4156     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ISBarrierID);
4157     if (!CE) {
4158       Error(Loc, "constant expression expected");
4159       return MatchOperand_ParseFail;
4160     }
4161 
4162     int Val = CE->getValue();
4163     if (Val & ~0xf) {
4164       Error(Loc, "immediate value out of range");
4165       return MatchOperand_ParseFail;
4166     }
4167 
4168     Opt = ARM_ISB::RESERVED_0 + Val;
4169   } else
4170     return MatchOperand_ParseFail;
4171 
4172   Operands.push_back(ARMOperand::CreateInstSyncBarrierOpt(
4173           (ARM_ISB::InstSyncBOpt)Opt, S));
4174   return MatchOperand_Success;
4175 }
4176 
4177 
4178 /// parseProcIFlagsOperand - Try to parse iflags from CPS instruction.
4179 OperandMatchResultTy
4180 ARMAsmParser::parseProcIFlagsOperand(OperandVector &Operands) {
4181   MCAsmParser &Parser = getParser();
4182   SMLoc S = Parser.getTok().getLoc();
4183   const AsmToken &Tok = Parser.getTok();
4184   if (!Tok.is(AsmToken::Identifier))
4185     return MatchOperand_NoMatch;
4186   StringRef IFlagsStr = Tok.getString();
4187 
4188   // An iflags string of "none" is interpreted to mean that none of the AIF
4189   // bits are set.  Not a terribly useful instruction, but a valid encoding.
4190   unsigned IFlags = 0;
4191   if (IFlagsStr != "none") {
4192         for (int i = 0, e = IFlagsStr.size(); i != e; ++i) {
4193       unsigned Flag = StringSwitch<unsigned>(IFlagsStr.substr(i, 1).lower())
4194         .Case("a", ARM_PROC::A)
4195         .Case("i", ARM_PROC::I)
4196         .Case("f", ARM_PROC::F)
4197         .Default(~0U);
4198 
4199       // If some specific iflag is already set, it means that some letter is
4200       // present more than once, this is not acceptable.
4201       if (Flag == ~0U || (IFlags & Flag))
4202         return MatchOperand_NoMatch;
4203 
4204       IFlags |= Flag;
4205     }
4206   }
4207 
4208   Parser.Lex(); // Eat identifier token.
4209   Operands.push_back(ARMOperand::CreateProcIFlags((ARM_PROC::IFlags)IFlags, S));
4210   return MatchOperand_Success;
4211 }
4212 
4213 /// parseMSRMaskOperand - Try to parse mask flags from MSR instruction.
4214 OperandMatchResultTy
4215 ARMAsmParser::parseMSRMaskOperand(OperandVector &Operands) {
4216   MCAsmParser &Parser = getParser();
4217   SMLoc S = Parser.getTok().getLoc();
4218   const AsmToken &Tok = Parser.getTok();
4219   if (!Tok.is(AsmToken::Identifier))
4220     return MatchOperand_NoMatch;
4221   StringRef Mask = Tok.getString();
4222 
4223   if (isMClass()) {
4224     auto TheReg = ARMSysReg::lookupMClassSysRegByName(Mask.lower());
4225     if (!TheReg || !TheReg->hasRequiredFeatures(getSTI().getFeatureBits()))
4226       return MatchOperand_NoMatch;
4227 
4228     unsigned SYSmvalue = TheReg->Encoding & 0xFFF;
4229 
4230     Parser.Lex(); // Eat identifier token.
4231     Operands.push_back(ARMOperand::CreateMSRMask(SYSmvalue, S));
4232     return MatchOperand_Success;
4233   }
4234 
4235   // Split spec_reg from flag, example: CPSR_sxf => "CPSR" and "sxf"
4236   size_t Start = 0, Next = Mask.find('_');
4237   StringRef Flags = "";
4238   std::string SpecReg = Mask.slice(Start, Next).lower();
4239   if (Next != StringRef::npos)
4240     Flags = Mask.slice(Next+1, Mask.size());
4241 
4242   // FlagsVal contains the complete mask:
4243   // 3-0: Mask
4244   // 4: Special Reg (cpsr, apsr => 0; spsr => 1)
4245   unsigned FlagsVal = 0;
4246 
4247   if (SpecReg == "apsr") {
4248     FlagsVal = StringSwitch<unsigned>(Flags)
4249     .Case("nzcvq",  0x8) // same as CPSR_f
4250     .Case("g",      0x4) // same as CPSR_s
4251     .Case("nzcvqg", 0xc) // same as CPSR_fs
4252     .Default(~0U);
4253 
4254     if (FlagsVal == ~0U) {
4255       if (!Flags.empty())
4256         return MatchOperand_NoMatch;
4257       else
4258         FlagsVal = 8; // No flag
4259     }
4260   } else if (SpecReg == "cpsr" || SpecReg == "spsr") {
4261     // cpsr_all is an alias for cpsr_fc, as is plain cpsr.
4262     if (Flags == "all" || Flags == "")
4263       Flags = "fc";
4264     for (int i = 0, e = Flags.size(); i != e; ++i) {
4265       unsigned Flag = StringSwitch<unsigned>(Flags.substr(i, 1))
4266       .Case("c", 1)
4267       .Case("x", 2)
4268       .Case("s", 4)
4269       .Case("f", 8)
4270       .Default(~0U);
4271 
4272       // If some specific flag is already set, it means that some letter is
4273       // present more than once, this is not acceptable.
4274       if (Flag == ~0U || (FlagsVal & Flag))
4275         return MatchOperand_NoMatch;
4276       FlagsVal |= Flag;
4277     }
4278   } else // No match for special register.
4279     return MatchOperand_NoMatch;
4280 
4281   // Special register without flags is NOT equivalent to "fc" flags.
4282   // NOTE: This is a divergence from gas' behavior.  Uncommenting the following
4283   // two lines would enable gas compatibility at the expense of breaking
4284   // round-tripping.
4285   //
4286   // if (!FlagsVal)
4287   //  FlagsVal = 0x9;
4288 
4289   // Bit 4: Special Reg (cpsr, apsr => 0; spsr => 1)
4290   if (SpecReg == "spsr")
4291     FlagsVal |= 16;
4292 
4293   Parser.Lex(); // Eat identifier token.
4294   Operands.push_back(ARMOperand::CreateMSRMask(FlagsVal, S));
4295   return MatchOperand_Success;
4296 }
4297 
4298 /// parseBankedRegOperand - Try to parse a banked register (e.g. "lr_irq") for
4299 /// use in the MRS/MSR instructions added to support virtualization.
4300 OperandMatchResultTy
4301 ARMAsmParser::parseBankedRegOperand(OperandVector &Operands) {
4302   MCAsmParser &Parser = getParser();
4303   SMLoc S = Parser.getTok().getLoc();
4304   const AsmToken &Tok = Parser.getTok();
4305   if (!Tok.is(AsmToken::Identifier))
4306     return MatchOperand_NoMatch;
4307   StringRef RegName = Tok.getString();
4308 
4309   auto TheReg = ARMBankedReg::lookupBankedRegByName(RegName.lower());
4310   if (!TheReg)
4311     return MatchOperand_NoMatch;
4312   unsigned Encoding = TheReg->Encoding;
4313 
4314   Parser.Lex(); // Eat identifier token.
4315   Operands.push_back(ARMOperand::CreateBankedReg(Encoding, S));
4316   return MatchOperand_Success;
4317 }
4318 
4319 OperandMatchResultTy
4320 ARMAsmParser::parsePKHImm(OperandVector &Operands, StringRef Op, int Low,
4321                           int High) {
4322   MCAsmParser &Parser = getParser();
4323   const AsmToken &Tok = Parser.getTok();
4324   if (Tok.isNot(AsmToken::Identifier)) {
4325     Error(Parser.getTok().getLoc(), Op + " operand expected.");
4326     return MatchOperand_ParseFail;
4327   }
4328   StringRef ShiftName = Tok.getString();
4329   std::string LowerOp = Op.lower();
4330   std::string UpperOp = Op.upper();
4331   if (ShiftName != LowerOp && ShiftName != UpperOp) {
4332     Error(Parser.getTok().getLoc(), Op + " operand expected.");
4333     return MatchOperand_ParseFail;
4334   }
4335   Parser.Lex(); // Eat shift type token.
4336 
4337   // There must be a '#' and a shift amount.
4338   if (Parser.getTok().isNot(AsmToken::Hash) &&
4339       Parser.getTok().isNot(AsmToken::Dollar)) {
4340     Error(Parser.getTok().getLoc(), "'#' expected");
4341     return MatchOperand_ParseFail;
4342   }
4343   Parser.Lex(); // Eat hash token.
4344 
4345   const MCExpr *ShiftAmount;
4346   SMLoc Loc = Parser.getTok().getLoc();
4347   SMLoc EndLoc;
4348   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
4349     Error(Loc, "illegal expression");
4350     return MatchOperand_ParseFail;
4351   }
4352   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
4353   if (!CE) {
4354     Error(Loc, "constant expression expected");
4355     return MatchOperand_ParseFail;
4356   }
4357   int Val = CE->getValue();
4358   if (Val < Low || Val > High) {
4359     Error(Loc, "immediate value out of range");
4360     return MatchOperand_ParseFail;
4361   }
4362 
4363   Operands.push_back(ARMOperand::CreateImm(CE, Loc, EndLoc));
4364 
4365   return MatchOperand_Success;
4366 }
4367 
4368 OperandMatchResultTy
4369 ARMAsmParser::parseSetEndImm(OperandVector &Operands) {
4370   MCAsmParser &Parser = getParser();
4371   const AsmToken &Tok = Parser.getTok();
4372   SMLoc S = Tok.getLoc();
4373   if (Tok.isNot(AsmToken::Identifier)) {
4374     Error(S, "'be' or 'le' operand expected");
4375     return MatchOperand_ParseFail;
4376   }
4377   int Val = StringSwitch<int>(Tok.getString().lower())
4378     .Case("be", 1)
4379     .Case("le", 0)
4380     .Default(-1);
4381   Parser.Lex(); // Eat the token.
4382 
4383   if (Val == -1) {
4384     Error(S, "'be' or 'le' operand expected");
4385     return MatchOperand_ParseFail;
4386   }
4387   Operands.push_back(ARMOperand::CreateImm(MCConstantExpr::create(Val,
4388                                                                   getContext()),
4389                                            S, Tok.getEndLoc()));
4390   return MatchOperand_Success;
4391 }
4392 
4393 /// parseShifterImm - Parse the shifter immediate operand for SSAT/USAT
4394 /// instructions. Legal values are:
4395 ///     lsl #n  'n' in [0,31]
4396 ///     asr #n  'n' in [1,32]
4397 ///             n == 32 encoded as n == 0.
4398 OperandMatchResultTy
4399 ARMAsmParser::parseShifterImm(OperandVector &Operands) {
4400   MCAsmParser &Parser = getParser();
4401   const AsmToken &Tok = Parser.getTok();
4402   SMLoc S = Tok.getLoc();
4403   if (Tok.isNot(AsmToken::Identifier)) {
4404     Error(S, "shift operator 'asr' or 'lsl' expected");
4405     return MatchOperand_ParseFail;
4406   }
4407   StringRef ShiftName = Tok.getString();
4408   bool isASR;
4409   if (ShiftName == "lsl" || ShiftName == "LSL")
4410     isASR = false;
4411   else if (ShiftName == "asr" || ShiftName == "ASR")
4412     isASR = true;
4413   else {
4414     Error(S, "shift operator 'asr' or 'lsl' expected");
4415     return MatchOperand_ParseFail;
4416   }
4417   Parser.Lex(); // Eat the operator.
4418 
4419   // A '#' and a shift amount.
4420   if (Parser.getTok().isNot(AsmToken::Hash) &&
4421       Parser.getTok().isNot(AsmToken::Dollar)) {
4422     Error(Parser.getTok().getLoc(), "'#' expected");
4423     return MatchOperand_ParseFail;
4424   }
4425   Parser.Lex(); // Eat hash token.
4426   SMLoc ExLoc = Parser.getTok().getLoc();
4427 
4428   const MCExpr *ShiftAmount;
4429   SMLoc EndLoc;
4430   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
4431     Error(ExLoc, "malformed shift expression");
4432     return MatchOperand_ParseFail;
4433   }
4434   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
4435   if (!CE) {
4436     Error(ExLoc, "shift amount must be an immediate");
4437     return MatchOperand_ParseFail;
4438   }
4439 
4440   int64_t Val = CE->getValue();
4441   if (isASR) {
4442     // Shift amount must be in [1,32]
4443     if (Val < 1 || Val > 32) {
4444       Error(ExLoc, "'asr' shift amount must be in range [1,32]");
4445       return MatchOperand_ParseFail;
4446     }
4447     // asr #32 encoded as asr #0, but is not allowed in Thumb2 mode.
4448     if (isThumb() && Val == 32) {
4449       Error(ExLoc, "'asr #32' shift amount not allowed in Thumb mode");
4450       return MatchOperand_ParseFail;
4451     }
4452     if (Val == 32) Val = 0;
4453   } else {
4454     // Shift amount must be in [1,32]
4455     if (Val < 0 || Val > 31) {
4456       Error(ExLoc, "'lsr' shift amount must be in range [0,31]");
4457       return MatchOperand_ParseFail;
4458     }
4459   }
4460 
4461   Operands.push_back(ARMOperand::CreateShifterImm(isASR, Val, S, EndLoc));
4462 
4463   return MatchOperand_Success;
4464 }
4465 
4466 /// parseRotImm - Parse the shifter immediate operand for SXTB/UXTB family
4467 /// of instructions. Legal values are:
4468 ///     ror #n  'n' in {0, 8, 16, 24}
4469 OperandMatchResultTy
4470 ARMAsmParser::parseRotImm(OperandVector &Operands) {
4471   MCAsmParser &Parser = getParser();
4472   const AsmToken &Tok = Parser.getTok();
4473   SMLoc S = Tok.getLoc();
4474   if (Tok.isNot(AsmToken::Identifier))
4475     return MatchOperand_NoMatch;
4476   StringRef ShiftName = Tok.getString();
4477   if (ShiftName != "ror" && ShiftName != "ROR")
4478     return MatchOperand_NoMatch;
4479   Parser.Lex(); // Eat the operator.
4480 
4481   // A '#' and a rotate amount.
4482   if (Parser.getTok().isNot(AsmToken::Hash) &&
4483       Parser.getTok().isNot(AsmToken::Dollar)) {
4484     Error(Parser.getTok().getLoc(), "'#' expected");
4485     return MatchOperand_ParseFail;
4486   }
4487   Parser.Lex(); // Eat hash token.
4488   SMLoc ExLoc = Parser.getTok().getLoc();
4489 
4490   const MCExpr *ShiftAmount;
4491   SMLoc EndLoc;
4492   if (getParser().parseExpression(ShiftAmount, EndLoc)) {
4493     Error(ExLoc, "malformed rotate expression");
4494     return MatchOperand_ParseFail;
4495   }
4496   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ShiftAmount);
4497   if (!CE) {
4498     Error(ExLoc, "rotate amount must be an immediate");
4499     return MatchOperand_ParseFail;
4500   }
4501 
4502   int64_t Val = CE->getValue();
4503   // Shift amount must be in {0, 8, 16, 24} (0 is undocumented extension)
4504   // normally, zero is represented in asm by omitting the rotate operand
4505   // entirely.
4506   if (Val != 8 && Val != 16 && Val != 24 && Val != 0) {
4507     Error(ExLoc, "'ror' rotate amount must be 8, 16, or 24");
4508     return MatchOperand_ParseFail;
4509   }
4510 
4511   Operands.push_back(ARMOperand::CreateRotImm(Val, S, EndLoc));
4512 
4513   return MatchOperand_Success;
4514 }
4515 
4516 OperandMatchResultTy
4517 ARMAsmParser::parseModImm(OperandVector &Operands) {
4518   MCAsmParser &Parser = getParser();
4519   MCAsmLexer &Lexer = getLexer();
4520   int64_t Imm1, Imm2;
4521 
4522   SMLoc S = Parser.getTok().getLoc();
4523 
4524   // 1) A mod_imm operand can appear in the place of a register name:
4525   //   add r0, #mod_imm
4526   //   add r0, r0, #mod_imm
4527   // to correctly handle the latter, we bail out as soon as we see an
4528   // identifier.
4529   //
4530   // 2) Similarly, we do not want to parse into complex operands:
4531   //   mov r0, #mod_imm
4532   //   mov r0, :lower16:(_foo)
4533   if (Parser.getTok().is(AsmToken::Identifier) ||
4534       Parser.getTok().is(AsmToken::Colon))
4535     return MatchOperand_NoMatch;
4536 
4537   // Hash (dollar) is optional as per the ARMARM
4538   if (Parser.getTok().is(AsmToken::Hash) ||
4539       Parser.getTok().is(AsmToken::Dollar)) {
4540     // Avoid parsing into complex operands (#:)
4541     if (Lexer.peekTok().is(AsmToken::Colon))
4542       return MatchOperand_NoMatch;
4543 
4544     // Eat the hash (dollar)
4545     Parser.Lex();
4546   }
4547 
4548   SMLoc Sx1, Ex1;
4549   Sx1 = Parser.getTok().getLoc();
4550   const MCExpr *Imm1Exp;
4551   if (getParser().parseExpression(Imm1Exp, Ex1)) {
4552     Error(Sx1, "malformed expression");
4553     return MatchOperand_ParseFail;
4554   }
4555 
4556   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Imm1Exp);
4557 
4558   if (CE) {
4559     // Immediate must fit within 32-bits
4560     Imm1 = CE->getValue();
4561     int Enc = ARM_AM::getSOImmVal(Imm1);
4562     if (Enc != -1 && Parser.getTok().is(AsmToken::EndOfStatement)) {
4563       // We have a match!
4564       Operands.push_back(ARMOperand::CreateModImm((Enc & 0xFF),
4565                                                   (Enc & 0xF00) >> 7,
4566                                                   Sx1, Ex1));
4567       return MatchOperand_Success;
4568     }
4569 
4570     // We have parsed an immediate which is not for us, fallback to a plain
4571     // immediate. This can happen for instruction aliases. For an example,
4572     // ARMInstrInfo.td defines the alias [mov <-> mvn] which can transform
4573     // a mov (mvn) with a mod_imm_neg/mod_imm_not operand into the opposite
4574     // instruction with a mod_imm operand. The alias is defined such that the
4575     // parser method is shared, that's why we have to do this here.
4576     if (Parser.getTok().is(AsmToken::EndOfStatement)) {
4577       Operands.push_back(ARMOperand::CreateImm(Imm1Exp, Sx1, Ex1));
4578       return MatchOperand_Success;
4579     }
4580   } else {
4581     // Operands like #(l1 - l2) can only be evaluated at a later stage (via an
4582     // MCFixup). Fallback to a plain immediate.
4583     Operands.push_back(ARMOperand::CreateImm(Imm1Exp, Sx1, Ex1));
4584     return MatchOperand_Success;
4585   }
4586 
4587   // From this point onward, we expect the input to be a (#bits, #rot) pair
4588   if (Parser.getTok().isNot(AsmToken::Comma)) {
4589     Error(Sx1, "expected modified immediate operand: #[0, 255], #even[0-30]");
4590     return MatchOperand_ParseFail;
4591   }
4592 
4593   if (Imm1 & ~0xFF) {
4594     Error(Sx1, "immediate operand must a number in the range [0, 255]");
4595     return MatchOperand_ParseFail;
4596   }
4597 
4598   // Eat the comma
4599   Parser.Lex();
4600 
4601   // Repeat for #rot
4602   SMLoc Sx2, Ex2;
4603   Sx2 = Parser.getTok().getLoc();
4604 
4605   // Eat the optional hash (dollar)
4606   if (Parser.getTok().is(AsmToken::Hash) ||
4607       Parser.getTok().is(AsmToken::Dollar))
4608     Parser.Lex();
4609 
4610   const MCExpr *Imm2Exp;
4611   if (getParser().parseExpression(Imm2Exp, Ex2)) {
4612     Error(Sx2, "malformed expression");
4613     return MatchOperand_ParseFail;
4614   }
4615 
4616   CE = dyn_cast<MCConstantExpr>(Imm2Exp);
4617 
4618   if (CE) {
4619     Imm2 = CE->getValue();
4620     if (!(Imm2 & ~0x1E)) {
4621       // We have a match!
4622       Operands.push_back(ARMOperand::CreateModImm(Imm1, Imm2, S, Ex2));
4623       return MatchOperand_Success;
4624     }
4625     Error(Sx2, "immediate operand must an even number in the range [0, 30]");
4626     return MatchOperand_ParseFail;
4627   } else {
4628     Error(Sx2, "constant expression expected");
4629     return MatchOperand_ParseFail;
4630   }
4631 }
4632 
4633 OperandMatchResultTy
4634 ARMAsmParser::parseBitfield(OperandVector &Operands) {
4635   MCAsmParser &Parser = getParser();
4636   SMLoc S = Parser.getTok().getLoc();
4637   // The bitfield descriptor is really two operands, the LSB and the width.
4638   if (Parser.getTok().isNot(AsmToken::Hash) &&
4639       Parser.getTok().isNot(AsmToken::Dollar)) {
4640     Error(Parser.getTok().getLoc(), "'#' expected");
4641     return MatchOperand_ParseFail;
4642   }
4643   Parser.Lex(); // Eat hash token.
4644 
4645   const MCExpr *LSBExpr;
4646   SMLoc E = Parser.getTok().getLoc();
4647   if (getParser().parseExpression(LSBExpr)) {
4648     Error(E, "malformed immediate expression");
4649     return MatchOperand_ParseFail;
4650   }
4651   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(LSBExpr);
4652   if (!CE) {
4653     Error(E, "'lsb' operand must be an immediate");
4654     return MatchOperand_ParseFail;
4655   }
4656 
4657   int64_t LSB = CE->getValue();
4658   // The LSB must be in the range [0,31]
4659   if (LSB < 0 || LSB > 31) {
4660     Error(E, "'lsb' operand must be in the range [0,31]");
4661     return MatchOperand_ParseFail;
4662   }
4663   E = Parser.getTok().getLoc();
4664 
4665   // Expect another immediate operand.
4666   if (Parser.getTok().isNot(AsmToken::Comma)) {
4667     Error(Parser.getTok().getLoc(), "too few operands");
4668     return MatchOperand_ParseFail;
4669   }
4670   Parser.Lex(); // Eat hash token.
4671   if (Parser.getTok().isNot(AsmToken::Hash) &&
4672       Parser.getTok().isNot(AsmToken::Dollar)) {
4673     Error(Parser.getTok().getLoc(), "'#' expected");
4674     return MatchOperand_ParseFail;
4675   }
4676   Parser.Lex(); // Eat hash token.
4677 
4678   const MCExpr *WidthExpr;
4679   SMLoc EndLoc;
4680   if (getParser().parseExpression(WidthExpr, EndLoc)) {
4681     Error(E, "malformed immediate expression");
4682     return MatchOperand_ParseFail;
4683   }
4684   CE = dyn_cast<MCConstantExpr>(WidthExpr);
4685   if (!CE) {
4686     Error(E, "'width' operand must be an immediate");
4687     return MatchOperand_ParseFail;
4688   }
4689 
4690   int64_t Width = CE->getValue();
4691   // The LSB must be in the range [1,32-lsb]
4692   if (Width < 1 || Width > 32 - LSB) {
4693     Error(E, "'width' operand must be in the range [1,32-lsb]");
4694     return MatchOperand_ParseFail;
4695   }
4696 
4697   Operands.push_back(ARMOperand::CreateBitfield(LSB, Width, S, EndLoc));
4698 
4699   return MatchOperand_Success;
4700 }
4701 
4702 OperandMatchResultTy
4703 ARMAsmParser::parsePostIdxReg(OperandVector &Operands) {
4704   // Check for a post-index addressing register operand. Specifically:
4705   // postidx_reg := '+' register {, shift}
4706   //              | '-' register {, shift}
4707   //              | register {, shift}
4708 
4709   // This method must return MatchOperand_NoMatch without consuming any tokens
4710   // in the case where there is no match, as other alternatives take other
4711   // parse methods.
4712   MCAsmParser &Parser = getParser();
4713   AsmToken Tok = Parser.getTok();
4714   SMLoc S = Tok.getLoc();
4715   bool haveEaten = false;
4716   bool isAdd = true;
4717   if (Tok.is(AsmToken::Plus)) {
4718     Parser.Lex(); // Eat the '+' token.
4719     haveEaten = true;
4720   } else if (Tok.is(AsmToken::Minus)) {
4721     Parser.Lex(); // Eat the '-' token.
4722     isAdd = false;
4723     haveEaten = true;
4724   }
4725 
4726   SMLoc E = Parser.getTok().getEndLoc();
4727   int Reg = tryParseRegister();
4728   if (Reg == -1) {
4729     if (!haveEaten)
4730       return MatchOperand_NoMatch;
4731     Error(Parser.getTok().getLoc(), "register expected");
4732     return MatchOperand_ParseFail;
4733   }
4734 
4735   ARM_AM::ShiftOpc ShiftTy = ARM_AM::no_shift;
4736   unsigned ShiftImm = 0;
4737   if (Parser.getTok().is(AsmToken::Comma)) {
4738     Parser.Lex(); // Eat the ','.
4739     if (parseMemRegOffsetShift(ShiftTy, ShiftImm))
4740       return MatchOperand_ParseFail;
4741 
4742     // FIXME: Only approximates end...may include intervening whitespace.
4743     E = Parser.getTok().getLoc();
4744   }
4745 
4746   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ShiftTy,
4747                                                   ShiftImm, S, E));
4748 
4749   return MatchOperand_Success;
4750 }
4751 
4752 OperandMatchResultTy
4753 ARMAsmParser::parseAM3Offset(OperandVector &Operands) {
4754   // Check for a post-index addressing register operand. Specifically:
4755   // am3offset := '+' register
4756   //              | '-' register
4757   //              | register
4758   //              | # imm
4759   //              | # + imm
4760   //              | # - imm
4761 
4762   // This method must return MatchOperand_NoMatch without consuming any tokens
4763   // in the case where there is no match, as other alternatives take other
4764   // parse methods.
4765   MCAsmParser &Parser = getParser();
4766   AsmToken Tok = Parser.getTok();
4767   SMLoc S = Tok.getLoc();
4768 
4769   // Do immediates first, as we always parse those if we have a '#'.
4770   if (Parser.getTok().is(AsmToken::Hash) ||
4771       Parser.getTok().is(AsmToken::Dollar)) {
4772     Parser.Lex(); // Eat '#' or '$'.
4773     // Explicitly look for a '-', as we need to encode negative zero
4774     // differently.
4775     bool isNegative = Parser.getTok().is(AsmToken::Minus);
4776     const MCExpr *Offset;
4777     SMLoc E;
4778     if (getParser().parseExpression(Offset, E))
4779       return MatchOperand_ParseFail;
4780     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
4781     if (!CE) {
4782       Error(S, "constant expression expected");
4783       return MatchOperand_ParseFail;
4784     }
4785     // Negative zero is encoded as the flag value
4786     // std::numeric_limits<int32_t>::min().
4787     int32_t Val = CE->getValue();
4788     if (isNegative && Val == 0)
4789       Val = std::numeric_limits<int32_t>::min();
4790 
4791     Operands.push_back(
4792       ARMOperand::CreateImm(MCConstantExpr::create(Val, getContext()), S, E));
4793 
4794     return MatchOperand_Success;
4795   }
4796 
4797   bool haveEaten = false;
4798   bool isAdd = true;
4799   if (Tok.is(AsmToken::Plus)) {
4800     Parser.Lex(); // Eat the '+' token.
4801     haveEaten = true;
4802   } else if (Tok.is(AsmToken::Minus)) {
4803     Parser.Lex(); // Eat the '-' token.
4804     isAdd = false;
4805     haveEaten = true;
4806   }
4807 
4808   Tok = Parser.getTok();
4809   int Reg = tryParseRegister();
4810   if (Reg == -1) {
4811     if (!haveEaten)
4812       return MatchOperand_NoMatch;
4813     Error(Tok.getLoc(), "register expected");
4814     return MatchOperand_ParseFail;
4815   }
4816 
4817   Operands.push_back(ARMOperand::CreatePostIdxReg(Reg, isAdd, ARM_AM::no_shift,
4818                                                   0, S, Tok.getEndLoc()));
4819 
4820   return MatchOperand_Success;
4821 }
4822 
4823 /// Convert parsed operands to MCInst.  Needed here because this instruction
4824 /// only has two register operands, but multiplication is commutative so
4825 /// assemblers should accept both "mul rD, rN, rD" and "mul rD, rD, rN".
4826 void ARMAsmParser::cvtThumbMultiply(MCInst &Inst,
4827                                     const OperandVector &Operands) {
4828   ((ARMOperand &)*Operands[3]).addRegOperands(Inst, 1);
4829   ((ARMOperand &)*Operands[1]).addCCOutOperands(Inst, 1);
4830   // If we have a three-operand form, make sure to set Rn to be the operand
4831   // that isn't the same as Rd.
4832   unsigned RegOp = 4;
4833   if (Operands.size() == 6 &&
4834       ((ARMOperand &)*Operands[4]).getReg() ==
4835           ((ARMOperand &)*Operands[3]).getReg())
4836     RegOp = 5;
4837   ((ARMOperand &)*Operands[RegOp]).addRegOperands(Inst, 1);
4838   Inst.addOperand(Inst.getOperand(0));
4839   ((ARMOperand &)*Operands[2]).addCondCodeOperands(Inst, 2);
4840 }
4841 
4842 void ARMAsmParser::cvtThumbBranches(MCInst &Inst,
4843                                     const OperandVector &Operands) {
4844   int CondOp = -1, ImmOp = -1;
4845   switch(Inst.getOpcode()) {
4846     case ARM::tB:
4847     case ARM::tBcc:  CondOp = 1; ImmOp = 2; break;
4848 
4849     case ARM::t2B:
4850     case ARM::t2Bcc: CondOp = 1; ImmOp = 3; break;
4851 
4852     default: llvm_unreachable("Unexpected instruction in cvtThumbBranches");
4853   }
4854   // first decide whether or not the branch should be conditional
4855   // by looking at it's location relative to an IT block
4856   if(inITBlock()) {
4857     // inside an IT block we cannot have any conditional branches. any
4858     // such instructions needs to be converted to unconditional form
4859     switch(Inst.getOpcode()) {
4860       case ARM::tBcc: Inst.setOpcode(ARM::tB); break;
4861       case ARM::t2Bcc: Inst.setOpcode(ARM::t2B); break;
4862     }
4863   } else {
4864     // outside IT blocks we can only have unconditional branches with AL
4865     // condition code or conditional branches with non-AL condition code
4866     unsigned Cond = static_cast<ARMOperand &>(*Operands[CondOp]).getCondCode();
4867     switch(Inst.getOpcode()) {
4868       case ARM::tB:
4869       case ARM::tBcc:
4870         Inst.setOpcode(Cond == ARMCC::AL ? ARM::tB : ARM::tBcc);
4871         break;
4872       case ARM::t2B:
4873       case ARM::t2Bcc:
4874         Inst.setOpcode(Cond == ARMCC::AL ? ARM::t2B : ARM::t2Bcc);
4875         break;
4876     }
4877   }
4878 
4879   // now decide on encoding size based on branch target range
4880   switch(Inst.getOpcode()) {
4881     // classify tB as either t2B or t1B based on range of immediate operand
4882     case ARM::tB: {
4883       ARMOperand &op = static_cast<ARMOperand &>(*Operands[ImmOp]);
4884       if (!op.isSignedOffset<11, 1>() && isThumb() && hasV8MBaseline())
4885         Inst.setOpcode(ARM::t2B);
4886       break;
4887     }
4888     // classify tBcc as either t2Bcc or t1Bcc based on range of immediate operand
4889     case ARM::tBcc: {
4890       ARMOperand &op = static_cast<ARMOperand &>(*Operands[ImmOp]);
4891       if (!op.isSignedOffset<8, 1>() && isThumb() && hasV8MBaseline())
4892         Inst.setOpcode(ARM::t2Bcc);
4893       break;
4894     }
4895   }
4896   ((ARMOperand &)*Operands[ImmOp]).addImmOperands(Inst, 1);
4897   ((ARMOperand &)*Operands[CondOp]).addCondCodeOperands(Inst, 2);
4898 }
4899 
4900 /// Parse an ARM memory expression, return false if successful else return true
4901 /// or an error.  The first token must be a '[' when called.
4902 bool ARMAsmParser::parseMemory(OperandVector &Operands) {
4903   MCAsmParser &Parser = getParser();
4904   SMLoc S, E;
4905   if (Parser.getTok().isNot(AsmToken::LBrac))
4906     return TokError("Token is not a Left Bracket");
4907   S = Parser.getTok().getLoc();
4908   Parser.Lex(); // Eat left bracket token.
4909 
4910   const AsmToken &BaseRegTok = Parser.getTok();
4911   int BaseRegNum = tryParseRegister();
4912   if (BaseRegNum == -1)
4913     return Error(BaseRegTok.getLoc(), "register expected");
4914 
4915   // The next token must either be a comma, a colon or a closing bracket.
4916   const AsmToken &Tok = Parser.getTok();
4917   if (!Tok.is(AsmToken::Colon) && !Tok.is(AsmToken::Comma) &&
4918       !Tok.is(AsmToken::RBrac))
4919     return Error(Tok.getLoc(), "malformed memory operand");
4920 
4921   if (Tok.is(AsmToken::RBrac)) {
4922     E = Tok.getEndLoc();
4923     Parser.Lex(); // Eat right bracket token.
4924 
4925     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, 0,
4926                                              ARM_AM::no_shift, 0, 0, false,
4927                                              S, E));
4928 
4929     // If there's a pre-indexing writeback marker, '!', just add it as a token
4930     // operand. It's rather odd, but syntactically valid.
4931     if (Parser.getTok().is(AsmToken::Exclaim)) {
4932       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
4933       Parser.Lex(); // Eat the '!'.
4934     }
4935 
4936     return false;
4937   }
4938 
4939   assert((Tok.is(AsmToken::Colon) || Tok.is(AsmToken::Comma)) &&
4940          "Lost colon or comma in memory operand?!");
4941   if (Tok.is(AsmToken::Comma)) {
4942     Parser.Lex(); // Eat the comma.
4943   }
4944 
4945   // If we have a ':', it's an alignment specifier.
4946   if (Parser.getTok().is(AsmToken::Colon)) {
4947     Parser.Lex(); // Eat the ':'.
4948     E = Parser.getTok().getLoc();
4949     SMLoc AlignmentLoc = Tok.getLoc();
4950 
4951     const MCExpr *Expr;
4952     if (getParser().parseExpression(Expr))
4953      return true;
4954 
4955     // The expression has to be a constant. Memory references with relocations
4956     // don't come through here, as they use the <label> forms of the relevant
4957     // instructions.
4958     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
4959     if (!CE)
4960       return Error (E, "constant expression expected");
4961 
4962     unsigned Align = 0;
4963     switch (CE->getValue()) {
4964     default:
4965       return Error(E,
4966                    "alignment specifier must be 16, 32, 64, 128, or 256 bits");
4967     case 16:  Align = 2; break;
4968     case 32:  Align = 4; break;
4969     case 64:  Align = 8; break;
4970     case 128: Align = 16; break;
4971     case 256: Align = 32; break;
4972     }
4973 
4974     // Now we should have the closing ']'
4975     if (Parser.getTok().isNot(AsmToken::RBrac))
4976       return Error(Parser.getTok().getLoc(), "']' expected");
4977     E = Parser.getTok().getEndLoc();
4978     Parser.Lex(); // Eat right bracket token.
4979 
4980     // Don't worry about range checking the value here. That's handled by
4981     // the is*() predicates.
4982     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, 0,
4983                                              ARM_AM::no_shift, 0, Align,
4984                                              false, S, E, AlignmentLoc));
4985 
4986     // If there's a pre-indexing writeback marker, '!', just add it as a token
4987     // operand.
4988     if (Parser.getTok().is(AsmToken::Exclaim)) {
4989       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
4990       Parser.Lex(); // Eat the '!'.
4991     }
4992 
4993     return false;
4994   }
4995 
4996   // If we have a '#', it's an immediate offset, else assume it's a register
4997   // offset. Be friendly and also accept a plain integer (without a leading
4998   // hash) for gas compatibility.
4999   if (Parser.getTok().is(AsmToken::Hash) ||
5000       Parser.getTok().is(AsmToken::Dollar) ||
5001       Parser.getTok().is(AsmToken::Integer)) {
5002     if (Parser.getTok().isNot(AsmToken::Integer))
5003       Parser.Lex(); // Eat '#' or '$'.
5004     E = Parser.getTok().getLoc();
5005 
5006     bool isNegative = getParser().getTok().is(AsmToken::Minus);
5007     const MCExpr *Offset;
5008     if (getParser().parseExpression(Offset))
5009      return true;
5010 
5011     // The expression has to be a constant. Memory references with relocations
5012     // don't come through here, as they use the <label> forms of the relevant
5013     // instructions.
5014     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Offset);
5015     if (!CE)
5016       return Error (E, "constant expression expected");
5017 
5018     // If the constant was #-0, represent it as
5019     // std::numeric_limits<int32_t>::min().
5020     int32_t Val = CE->getValue();
5021     if (isNegative && Val == 0)
5022       CE = MCConstantExpr::create(std::numeric_limits<int32_t>::min(),
5023                                   getContext());
5024 
5025     // Now we should have the closing ']'
5026     if (Parser.getTok().isNot(AsmToken::RBrac))
5027       return Error(Parser.getTok().getLoc(), "']' expected");
5028     E = Parser.getTok().getEndLoc();
5029     Parser.Lex(); // Eat right bracket token.
5030 
5031     // Don't worry about range checking the value here. That's handled by
5032     // the is*() predicates.
5033     Operands.push_back(ARMOperand::CreateMem(BaseRegNum, CE, 0,
5034                                              ARM_AM::no_shift, 0, 0,
5035                                              false, S, E));
5036 
5037     // If there's a pre-indexing writeback marker, '!', just add it as a token
5038     // operand.
5039     if (Parser.getTok().is(AsmToken::Exclaim)) {
5040       Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
5041       Parser.Lex(); // Eat the '!'.
5042     }
5043 
5044     return false;
5045   }
5046 
5047   // The register offset is optionally preceded by a '+' or '-'
5048   bool isNegative = false;
5049   if (Parser.getTok().is(AsmToken::Minus)) {
5050     isNegative = true;
5051     Parser.Lex(); // Eat the '-'.
5052   } else if (Parser.getTok().is(AsmToken::Plus)) {
5053     // Nothing to do.
5054     Parser.Lex(); // Eat the '+'.
5055   }
5056 
5057   E = Parser.getTok().getLoc();
5058   int OffsetRegNum = tryParseRegister();
5059   if (OffsetRegNum == -1)
5060     return Error(E, "register expected");
5061 
5062   // If there's a shift operator, handle it.
5063   ARM_AM::ShiftOpc ShiftType = ARM_AM::no_shift;
5064   unsigned ShiftImm = 0;
5065   if (Parser.getTok().is(AsmToken::Comma)) {
5066     Parser.Lex(); // Eat the ','.
5067     if (parseMemRegOffsetShift(ShiftType, ShiftImm))
5068       return true;
5069   }
5070 
5071   // Now we should have the closing ']'
5072   if (Parser.getTok().isNot(AsmToken::RBrac))
5073     return Error(Parser.getTok().getLoc(), "']' expected");
5074   E = Parser.getTok().getEndLoc();
5075   Parser.Lex(); // Eat right bracket token.
5076 
5077   Operands.push_back(ARMOperand::CreateMem(BaseRegNum, nullptr, OffsetRegNum,
5078                                            ShiftType, ShiftImm, 0, isNegative,
5079                                            S, E));
5080 
5081   // If there's a pre-indexing writeback marker, '!', just add it as a token
5082   // operand.
5083   if (Parser.getTok().is(AsmToken::Exclaim)) {
5084     Operands.push_back(ARMOperand::CreateToken("!",Parser.getTok().getLoc()));
5085     Parser.Lex(); // Eat the '!'.
5086   }
5087 
5088   return false;
5089 }
5090 
5091 /// parseMemRegOffsetShift - one of these two:
5092 ///   ( lsl | lsr | asr | ror ) , # shift_amount
5093 ///   rrx
5094 /// return true if it parses a shift otherwise it returns false.
5095 bool ARMAsmParser::parseMemRegOffsetShift(ARM_AM::ShiftOpc &St,
5096                                           unsigned &Amount) {
5097   MCAsmParser &Parser = getParser();
5098   SMLoc Loc = Parser.getTok().getLoc();
5099   const AsmToken &Tok = Parser.getTok();
5100   if (Tok.isNot(AsmToken::Identifier))
5101     return true;
5102   StringRef ShiftName = Tok.getString();
5103   if (ShiftName == "lsl" || ShiftName == "LSL" ||
5104       ShiftName == "asl" || ShiftName == "ASL")
5105     St = ARM_AM::lsl;
5106   else if (ShiftName == "lsr" || ShiftName == "LSR")
5107     St = ARM_AM::lsr;
5108   else if (ShiftName == "asr" || ShiftName == "ASR")
5109     St = ARM_AM::asr;
5110   else if (ShiftName == "ror" || ShiftName == "ROR")
5111     St = ARM_AM::ror;
5112   else if (ShiftName == "rrx" || ShiftName == "RRX")
5113     St = ARM_AM::rrx;
5114   else
5115     return Error(Loc, "illegal shift operator");
5116   Parser.Lex(); // Eat shift type token.
5117 
5118   // rrx stands alone.
5119   Amount = 0;
5120   if (St != ARM_AM::rrx) {
5121     Loc = Parser.getTok().getLoc();
5122     // A '#' and a shift amount.
5123     const AsmToken &HashTok = Parser.getTok();
5124     if (HashTok.isNot(AsmToken::Hash) &&
5125         HashTok.isNot(AsmToken::Dollar))
5126       return Error(HashTok.getLoc(), "'#' expected");
5127     Parser.Lex(); // Eat hash token.
5128 
5129     const MCExpr *Expr;
5130     if (getParser().parseExpression(Expr))
5131       return true;
5132     // Range check the immediate.
5133     // lsl, ror: 0 <= imm <= 31
5134     // lsr, asr: 0 <= imm <= 32
5135     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Expr);
5136     if (!CE)
5137       return Error(Loc, "shift amount must be an immediate");
5138     int64_t Imm = CE->getValue();
5139     if (Imm < 0 ||
5140         ((St == ARM_AM::lsl || St == ARM_AM::ror) && Imm > 31) ||
5141         ((St == ARM_AM::lsr || St == ARM_AM::asr) && Imm > 32))
5142       return Error(Loc, "immediate shift value out of range");
5143     // If <ShiftTy> #0, turn it into a no_shift.
5144     if (Imm == 0)
5145       St = ARM_AM::lsl;
5146     // For consistency, treat lsr #32 and asr #32 as having immediate value 0.
5147     if (Imm == 32)
5148       Imm = 0;
5149     Amount = Imm;
5150   }
5151 
5152   return false;
5153 }
5154 
5155 /// parseFPImm - A floating point immediate expression operand.
5156 OperandMatchResultTy
5157 ARMAsmParser::parseFPImm(OperandVector &Operands) {
5158   MCAsmParser &Parser = getParser();
5159   // Anything that can accept a floating point constant as an operand
5160   // needs to go through here, as the regular parseExpression is
5161   // integer only.
5162   //
5163   // This routine still creates a generic Immediate operand, containing
5164   // a bitcast of the 64-bit floating point value. The various operands
5165   // that accept floats can check whether the value is valid for them
5166   // via the standard is*() predicates.
5167 
5168   SMLoc S = Parser.getTok().getLoc();
5169 
5170   if (Parser.getTok().isNot(AsmToken::Hash) &&
5171       Parser.getTok().isNot(AsmToken::Dollar))
5172     return MatchOperand_NoMatch;
5173 
5174   // Disambiguate the VMOV forms that can accept an FP immediate.
5175   // vmov.f32 <sreg>, #imm
5176   // vmov.f64 <dreg>, #imm
5177   // vmov.f32 <dreg>, #imm  @ vector f32x2
5178   // vmov.f32 <qreg>, #imm  @ vector f32x4
5179   //
5180   // There are also the NEON VMOV instructions which expect an
5181   // integer constant. Make sure we don't try to parse an FPImm
5182   // for these:
5183   // vmov.i{8|16|32|64} <dreg|qreg>, #imm
5184   ARMOperand &TyOp = static_cast<ARMOperand &>(*Operands[2]);
5185   bool isVmovf = TyOp.isToken() &&
5186                  (TyOp.getToken() == ".f32" || TyOp.getToken() == ".f64" ||
5187                   TyOp.getToken() == ".f16");
5188   ARMOperand &Mnemonic = static_cast<ARMOperand &>(*Operands[0]);
5189   bool isFconst = Mnemonic.isToken() && (Mnemonic.getToken() == "fconstd" ||
5190                                          Mnemonic.getToken() == "fconsts");
5191   if (!(isVmovf || isFconst))
5192     return MatchOperand_NoMatch;
5193 
5194   Parser.Lex(); // Eat '#' or '$'.
5195 
5196   // Handle negation, as that still comes through as a separate token.
5197   bool isNegative = false;
5198   if (Parser.getTok().is(AsmToken::Minus)) {
5199     isNegative = true;
5200     Parser.Lex();
5201   }
5202   const AsmToken &Tok = Parser.getTok();
5203   SMLoc Loc = Tok.getLoc();
5204   if (Tok.is(AsmToken::Real) && isVmovf) {
5205     APFloat RealVal(APFloat::IEEEsingle(), Tok.getString());
5206     uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
5207     // If we had a '-' in front, toggle the sign bit.
5208     IntVal ^= (uint64_t)isNegative << 31;
5209     Parser.Lex(); // Eat the token.
5210     Operands.push_back(ARMOperand::CreateImm(
5211           MCConstantExpr::create(IntVal, getContext()),
5212           S, Parser.getTok().getLoc()));
5213     return MatchOperand_Success;
5214   }
5215   // Also handle plain integers. Instructions which allow floating point
5216   // immediates also allow a raw encoded 8-bit value.
5217   if (Tok.is(AsmToken::Integer) && isFconst) {
5218     int64_t Val = Tok.getIntVal();
5219     Parser.Lex(); // Eat the token.
5220     if (Val > 255 || Val < 0) {
5221       Error(Loc, "encoded floating point value out of range");
5222       return MatchOperand_ParseFail;
5223     }
5224     float RealVal = ARM_AM::getFPImmFloat(Val);
5225     Val = APFloat(RealVal).bitcastToAPInt().getZExtValue();
5226 
5227     Operands.push_back(ARMOperand::CreateImm(
5228         MCConstantExpr::create(Val, getContext()), S,
5229         Parser.getTok().getLoc()));
5230     return MatchOperand_Success;
5231   }
5232 
5233   Error(Loc, "invalid floating point immediate");
5234   return MatchOperand_ParseFail;
5235 }
5236 
5237 /// Parse a arm instruction operand.  For now this parses the operand regardless
5238 /// of the mnemonic.
5239 bool ARMAsmParser::parseOperand(OperandVector &Operands, StringRef Mnemonic) {
5240   MCAsmParser &Parser = getParser();
5241   SMLoc S, E;
5242 
5243   // Check if the current operand has a custom associated parser, if so, try to
5244   // custom parse the operand, or fallback to the general approach.
5245   OperandMatchResultTy ResTy = MatchOperandParserImpl(Operands, Mnemonic);
5246   if (ResTy == MatchOperand_Success)
5247     return false;
5248   // If there wasn't a custom match, try the generic matcher below. Otherwise,
5249   // there was a match, but an error occurred, in which case, just return that
5250   // the operand parsing failed.
5251   if (ResTy == MatchOperand_ParseFail)
5252     return true;
5253 
5254   switch (getLexer().getKind()) {
5255   default:
5256     Error(Parser.getTok().getLoc(), "unexpected token in operand");
5257     return true;
5258   case AsmToken::Identifier: {
5259     // If we've seen a branch mnemonic, the next operand must be a label.  This
5260     // is true even if the label is a register name.  So "br r1" means branch to
5261     // label "r1".
5262     bool ExpectLabel = Mnemonic == "b" || Mnemonic == "bl";
5263     if (!ExpectLabel) {
5264       if (!tryParseRegisterWithWriteBack(Operands))
5265         return false;
5266       int Res = tryParseShiftRegister(Operands);
5267       if (Res == 0) // success
5268         return false;
5269       else if (Res == -1) // irrecoverable error
5270         return true;
5271       // If this is VMRS, check for the apsr_nzcv operand.
5272       if (Mnemonic == "vmrs" &&
5273           Parser.getTok().getString().equals_lower("apsr_nzcv")) {
5274         S = Parser.getTok().getLoc();
5275         Parser.Lex();
5276         Operands.push_back(ARMOperand::CreateToken("APSR_nzcv", S));
5277         return false;
5278       }
5279     }
5280 
5281     // Fall though for the Identifier case that is not a register or a
5282     // special name.
5283     LLVM_FALLTHROUGH;
5284   }
5285   case AsmToken::LParen:  // parenthesized expressions like (_strcmp-4)
5286   case AsmToken::Integer: // things like 1f and 2b as a branch targets
5287   case AsmToken::String:  // quoted label names.
5288   case AsmToken::Dot: {   // . as a branch target
5289     // This was not a register so parse other operands that start with an
5290     // identifier (like labels) as expressions and create them as immediates.
5291     const MCExpr *IdVal;
5292     S = Parser.getTok().getLoc();
5293     if (getParser().parseExpression(IdVal))
5294       return true;
5295     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5296     Operands.push_back(ARMOperand::CreateImm(IdVal, S, E));
5297     return false;
5298   }
5299   case AsmToken::LBrac:
5300     return parseMemory(Operands);
5301   case AsmToken::LCurly:
5302     return parseRegisterList(Operands);
5303   case AsmToken::Dollar:
5304   case AsmToken::Hash:
5305     // #42 -> immediate.
5306     S = Parser.getTok().getLoc();
5307     Parser.Lex();
5308 
5309     if (Parser.getTok().isNot(AsmToken::Colon)) {
5310       bool isNegative = Parser.getTok().is(AsmToken::Minus);
5311       const MCExpr *ImmVal;
5312       if (getParser().parseExpression(ImmVal))
5313         return true;
5314       const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ImmVal);
5315       if (CE) {
5316         int32_t Val = CE->getValue();
5317         if (isNegative && Val == 0)
5318           ImmVal = MCConstantExpr::create(std::numeric_limits<int32_t>::min(),
5319                                           getContext());
5320       }
5321       E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5322       Operands.push_back(ARMOperand::CreateImm(ImmVal, S, E));
5323 
5324       // There can be a trailing '!' on operands that we want as a separate
5325       // '!' Token operand. Handle that here. For example, the compatibility
5326       // alias for 'srsdb sp!, #imm' is 'srsdb #imm!'.
5327       if (Parser.getTok().is(AsmToken::Exclaim)) {
5328         Operands.push_back(ARMOperand::CreateToken(Parser.getTok().getString(),
5329                                                    Parser.getTok().getLoc()));
5330         Parser.Lex(); // Eat exclaim token
5331       }
5332       return false;
5333     }
5334     // w/ a ':' after the '#', it's just like a plain ':'.
5335     LLVM_FALLTHROUGH;
5336 
5337   case AsmToken::Colon: {
5338     S = Parser.getTok().getLoc();
5339     // ":lower16:" and ":upper16:" expression prefixes
5340     // FIXME: Check it's an expression prefix,
5341     // e.g. (FOO - :lower16:BAR) isn't legal.
5342     ARMMCExpr::VariantKind RefKind;
5343     if (parsePrefix(RefKind))
5344       return true;
5345 
5346     const MCExpr *SubExprVal;
5347     if (getParser().parseExpression(SubExprVal))
5348       return true;
5349 
5350     const MCExpr *ExprVal = ARMMCExpr::create(RefKind, SubExprVal,
5351                                               getContext());
5352     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5353     Operands.push_back(ARMOperand::CreateImm(ExprVal, S, E));
5354     return false;
5355   }
5356   case AsmToken::Equal: {
5357     S = Parser.getTok().getLoc();
5358     if (Mnemonic != "ldr") // only parse for ldr pseudo (e.g. ldr r0, =val)
5359       return Error(S, "unexpected token in operand");
5360     Parser.Lex(); // Eat '='
5361     const MCExpr *SubExprVal;
5362     if (getParser().parseExpression(SubExprVal))
5363       return true;
5364     E = SMLoc::getFromPointer(Parser.getTok().getLoc().getPointer() - 1);
5365 
5366     // execute-only: we assume that assembly programmers know what they are
5367     // doing and allow literal pool creation here
5368     Operands.push_back(ARMOperand::CreateConstantPoolImm(SubExprVal, S, E));
5369     return false;
5370   }
5371   }
5372 }
5373 
5374 // parsePrefix - Parse ARM 16-bit relocations expression prefix, i.e.
5375 //  :lower16: and :upper16:.
5376 bool ARMAsmParser::parsePrefix(ARMMCExpr::VariantKind &RefKind) {
5377   MCAsmParser &Parser = getParser();
5378   RefKind = ARMMCExpr::VK_ARM_None;
5379 
5380   // consume an optional '#' (GNU compatibility)
5381   if (getLexer().is(AsmToken::Hash))
5382     Parser.Lex();
5383 
5384   // :lower16: and :upper16: modifiers
5385   assert(getLexer().is(AsmToken::Colon) && "expected a :");
5386   Parser.Lex(); // Eat ':'
5387 
5388   if (getLexer().isNot(AsmToken::Identifier)) {
5389     Error(Parser.getTok().getLoc(), "expected prefix identifier in operand");
5390     return true;
5391   }
5392 
5393   enum {
5394     COFF = (1 << MCObjectFileInfo::IsCOFF),
5395     ELF = (1 << MCObjectFileInfo::IsELF),
5396     MACHO = (1 << MCObjectFileInfo::IsMachO),
5397     WASM = (1 << MCObjectFileInfo::IsWasm),
5398   };
5399   static const struct PrefixEntry {
5400     const char *Spelling;
5401     ARMMCExpr::VariantKind VariantKind;
5402     uint8_t SupportedFormats;
5403   } PrefixEntries[] = {
5404     { "lower16", ARMMCExpr::VK_ARM_LO16, COFF | ELF | MACHO },
5405     { "upper16", ARMMCExpr::VK_ARM_HI16, COFF | ELF | MACHO },
5406   };
5407 
5408   StringRef IDVal = Parser.getTok().getIdentifier();
5409 
5410   const auto &Prefix =
5411       std::find_if(std::begin(PrefixEntries), std::end(PrefixEntries),
5412                    [&IDVal](const PrefixEntry &PE) {
5413                       return PE.Spelling == IDVal;
5414                    });
5415   if (Prefix == std::end(PrefixEntries)) {
5416     Error(Parser.getTok().getLoc(), "unexpected prefix in operand");
5417     return true;
5418   }
5419 
5420   uint8_t CurrentFormat;
5421   switch (getContext().getObjectFileInfo()->getObjectFileType()) {
5422   case MCObjectFileInfo::IsMachO:
5423     CurrentFormat = MACHO;
5424     break;
5425   case MCObjectFileInfo::IsELF:
5426     CurrentFormat = ELF;
5427     break;
5428   case MCObjectFileInfo::IsCOFF:
5429     CurrentFormat = COFF;
5430     break;
5431   case MCObjectFileInfo::IsWasm:
5432     CurrentFormat = WASM;
5433     break;
5434   }
5435 
5436   if (~Prefix->SupportedFormats & CurrentFormat) {
5437     Error(Parser.getTok().getLoc(),
5438           "cannot represent relocation in the current file format");
5439     return true;
5440   }
5441 
5442   RefKind = Prefix->VariantKind;
5443   Parser.Lex();
5444 
5445   if (getLexer().isNot(AsmToken::Colon)) {
5446     Error(Parser.getTok().getLoc(), "unexpected token after prefix");
5447     return true;
5448   }
5449   Parser.Lex(); // Eat the last ':'
5450 
5451   return false;
5452 }
5453 
5454 /// \brief Given a mnemonic, split out possible predication code and carry
5455 /// setting letters to form a canonical mnemonic and flags.
5456 //
5457 // FIXME: Would be nice to autogen this.
5458 // FIXME: This is a bit of a maze of special cases.
5459 StringRef ARMAsmParser::splitMnemonic(StringRef Mnemonic,
5460                                       unsigned &PredicationCode,
5461                                       bool &CarrySetting,
5462                                       unsigned &ProcessorIMod,
5463                                       StringRef &ITMask) {
5464   PredicationCode = ARMCC::AL;
5465   CarrySetting = false;
5466   ProcessorIMod = 0;
5467 
5468   // Ignore some mnemonics we know aren't predicated forms.
5469   //
5470   // FIXME: Would be nice to autogen this.
5471   if ((Mnemonic == "movs" && isThumb()) ||
5472       Mnemonic == "teq"   || Mnemonic == "vceq"   || Mnemonic == "svc"   ||
5473       Mnemonic == "mls"   || Mnemonic == "smmls"  || Mnemonic == "vcls"  ||
5474       Mnemonic == "vmls"  || Mnemonic == "vnmls"  || Mnemonic == "vacge" ||
5475       Mnemonic == "vcge"  || Mnemonic == "vclt"   || Mnemonic == "vacgt" ||
5476       Mnemonic == "vaclt" || Mnemonic == "vacle"  || Mnemonic == "hlt" ||
5477       Mnemonic == "vcgt"  || Mnemonic == "vcle"   || Mnemonic == "smlal" ||
5478       Mnemonic == "umaal" || Mnemonic == "umlal"  || Mnemonic == "vabal" ||
5479       Mnemonic == "vmlal" || Mnemonic == "vpadal" || Mnemonic == "vqdmlal" ||
5480       Mnemonic == "fmuls" || Mnemonic == "vmaxnm" || Mnemonic == "vminnm" ||
5481       Mnemonic == "vcvta" || Mnemonic == "vcvtn"  || Mnemonic == "vcvtp" ||
5482       Mnemonic == "vcvtm" || Mnemonic == "vrinta" || Mnemonic == "vrintn" ||
5483       Mnemonic == "vrintp" || Mnemonic == "vrintm" || Mnemonic == "hvc" ||
5484       Mnemonic.startswith("vsel") || Mnemonic == "vins" || Mnemonic == "vmovx" ||
5485       Mnemonic == "bxns"  || Mnemonic == "blxns" ||
5486       Mnemonic == "vudot" || Mnemonic == "vsdot" ||
5487       Mnemonic == "vcmla" || Mnemonic == "vcadd")
5488     return Mnemonic;
5489 
5490   // First, split out any predication code. Ignore mnemonics we know aren't
5491   // predicated but do have a carry-set and so weren't caught above.
5492   if (Mnemonic != "adcs" && Mnemonic != "bics" && Mnemonic != "movs" &&
5493       Mnemonic != "muls" && Mnemonic != "smlals" && Mnemonic != "smulls" &&
5494       Mnemonic != "umlals" && Mnemonic != "umulls" && Mnemonic != "lsls" &&
5495       Mnemonic != "sbcs" && Mnemonic != "rscs") {
5496     unsigned CC = ARMCondCodeFromString(Mnemonic.substr(Mnemonic.size()-2));
5497     if (CC != ~0U) {
5498       Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 2);
5499       PredicationCode = CC;
5500     }
5501   }
5502 
5503   // Next, determine if we have a carry setting bit. We explicitly ignore all
5504   // the instructions we know end in 's'.
5505   if (Mnemonic.endswith("s") &&
5506       !(Mnemonic == "cps" || Mnemonic == "mls" ||
5507         Mnemonic == "mrs" || Mnemonic == "smmls" || Mnemonic == "vabs" ||
5508         Mnemonic == "vcls" || Mnemonic == "vmls" || Mnemonic == "vmrs" ||
5509         Mnemonic == "vnmls" || Mnemonic == "vqabs" || Mnemonic == "vrecps" ||
5510         Mnemonic == "vrsqrts" || Mnemonic == "srs" || Mnemonic == "flds" ||
5511         Mnemonic == "fmrs" || Mnemonic == "fsqrts" || Mnemonic == "fsubs" ||
5512         Mnemonic == "fsts" || Mnemonic == "fcpys" || Mnemonic == "fdivs" ||
5513         Mnemonic == "fmuls" || Mnemonic == "fcmps" || Mnemonic == "fcmpzs" ||
5514         Mnemonic == "vfms" || Mnemonic == "vfnms" || Mnemonic == "fconsts" ||
5515         Mnemonic == "bxns" || Mnemonic == "blxns" ||
5516         (Mnemonic == "movs" && isThumb()))) {
5517     Mnemonic = Mnemonic.slice(0, Mnemonic.size() - 1);
5518     CarrySetting = true;
5519   }
5520 
5521   // The "cps" instruction can have a interrupt mode operand which is glued into
5522   // the mnemonic. Check if this is the case, split it and parse the imod op
5523   if (Mnemonic.startswith("cps")) {
5524     // Split out any imod code.
5525     unsigned IMod =
5526       StringSwitch<unsigned>(Mnemonic.substr(Mnemonic.size()-2, 2))
5527       .Case("ie", ARM_PROC::IE)
5528       .Case("id", ARM_PROC::ID)
5529       .Default(~0U);
5530     if (IMod != ~0U) {
5531       Mnemonic = Mnemonic.slice(0, Mnemonic.size()-2);
5532       ProcessorIMod = IMod;
5533     }
5534   }
5535 
5536   // The "it" instruction has the condition mask on the end of the mnemonic.
5537   if (Mnemonic.startswith("it")) {
5538     ITMask = Mnemonic.slice(2, Mnemonic.size());
5539     Mnemonic = Mnemonic.slice(0, 2);
5540   }
5541 
5542   return Mnemonic;
5543 }
5544 
5545 /// \brief Given a canonical mnemonic, determine if the instruction ever allows
5546 /// inclusion of carry set or predication code operands.
5547 //
5548 // FIXME: It would be nice to autogen this.
5549 void ARMAsmParser::getMnemonicAcceptInfo(StringRef Mnemonic, StringRef FullInst,
5550                                          bool &CanAcceptCarrySet,
5551                                          bool &CanAcceptPredicationCode) {
5552   CanAcceptCarrySet =
5553       Mnemonic == "and" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
5554       Mnemonic == "rrx" || Mnemonic == "ror" || Mnemonic == "sub" ||
5555       Mnemonic == "add" || Mnemonic == "adc" || Mnemonic == "mul" ||
5556       Mnemonic == "bic" || Mnemonic == "asr" || Mnemonic == "orr" ||
5557       Mnemonic == "mvn" || Mnemonic == "rsb" || Mnemonic == "rsc" ||
5558       Mnemonic == "orn" || Mnemonic == "sbc" || Mnemonic == "eor" ||
5559       Mnemonic == "neg" || Mnemonic == "vfm" || Mnemonic == "vfnm" ||
5560       (!isThumb() &&
5561        (Mnemonic == "smull" || Mnemonic == "mov" || Mnemonic == "mla" ||
5562         Mnemonic == "smlal" || Mnemonic == "umlal" || Mnemonic == "umull"));
5563 
5564   if (Mnemonic == "bkpt" || Mnemonic == "cbnz" || Mnemonic == "setend" ||
5565       Mnemonic == "cps" || Mnemonic == "it" || Mnemonic == "cbz" ||
5566       Mnemonic == "trap" || Mnemonic == "hlt" || Mnemonic == "udf" ||
5567       Mnemonic.startswith("crc32") || Mnemonic.startswith("cps") ||
5568       Mnemonic.startswith("vsel") || Mnemonic == "vmaxnm" ||
5569       Mnemonic == "vminnm" || Mnemonic == "vcvta" || Mnemonic == "vcvtn" ||
5570       Mnemonic == "vcvtp" || Mnemonic == "vcvtm" || Mnemonic == "vrinta" ||
5571       Mnemonic == "vrintn" || Mnemonic == "vrintp" || Mnemonic == "vrintm" ||
5572       Mnemonic.startswith("aes") || Mnemonic == "hvc" || Mnemonic == "setpan" ||
5573       Mnemonic.startswith("sha1") || Mnemonic.startswith("sha256") ||
5574       (FullInst.startswith("vmull") && FullInst.endswith(".p64")) ||
5575       Mnemonic == "vmovx" || Mnemonic == "vins" ||
5576       Mnemonic == "vudot" || Mnemonic == "vsdot" ||
5577       Mnemonic == "vcmla" || Mnemonic == "vcadd") {
5578     // These mnemonics are never predicable
5579     CanAcceptPredicationCode = false;
5580   } else if (!isThumb()) {
5581     // Some instructions are only predicable in Thumb mode
5582     CanAcceptPredicationCode =
5583         Mnemonic != "cdp2" && Mnemonic != "clrex" && Mnemonic != "mcr2" &&
5584         Mnemonic != "mcrr2" && Mnemonic != "mrc2" && Mnemonic != "mrrc2" &&
5585         Mnemonic != "dmb" && Mnemonic != "dsb" && Mnemonic != "isb" &&
5586         Mnemonic != "pld" && Mnemonic != "pli" && Mnemonic != "pldw" &&
5587         Mnemonic != "ldc2" && Mnemonic != "ldc2l" && Mnemonic != "stc2" &&
5588         Mnemonic != "stc2l" && !Mnemonic.startswith("rfe") &&
5589         !Mnemonic.startswith("srs");
5590   } else if (isThumbOne()) {
5591     if (hasV6MOps())
5592       CanAcceptPredicationCode = Mnemonic != "movs";
5593     else
5594       CanAcceptPredicationCode = Mnemonic != "nop" && Mnemonic != "movs";
5595   } else
5596     CanAcceptPredicationCode = true;
5597 }
5598 
5599 // \brief Some Thumb instructions have two operand forms that are not
5600 // available as three operand, convert to two operand form if possible.
5601 //
5602 // FIXME: We would really like to be able to tablegen'erate this.
5603 void ARMAsmParser::tryConvertingToTwoOperandForm(StringRef Mnemonic,
5604                                                  bool CarrySetting,
5605                                                  OperandVector &Operands) {
5606   if (Operands.size() != 6)
5607     return;
5608 
5609   const auto &Op3 = static_cast<ARMOperand &>(*Operands[3]);
5610         auto &Op4 = static_cast<ARMOperand &>(*Operands[4]);
5611   if (!Op3.isReg() || !Op4.isReg())
5612     return;
5613 
5614   auto Op3Reg = Op3.getReg();
5615   auto Op4Reg = Op4.getReg();
5616 
5617   // For most Thumb2 cases we just generate the 3 operand form and reduce
5618   // it in processInstruction(), but the 3 operand form of ADD (t2ADDrr)
5619   // won't accept SP or PC so we do the transformation here taking care
5620   // with immediate range in the 'add sp, sp #imm' case.
5621   auto &Op5 = static_cast<ARMOperand &>(*Operands[5]);
5622   if (isThumbTwo()) {
5623     if (Mnemonic != "add")
5624       return;
5625     bool TryTransform = Op3Reg == ARM::PC || Op4Reg == ARM::PC ||
5626                         (Op5.isReg() && Op5.getReg() == ARM::PC);
5627     if (!TryTransform) {
5628       TryTransform = (Op3Reg == ARM::SP || Op4Reg == ARM::SP ||
5629                       (Op5.isReg() && Op5.getReg() == ARM::SP)) &&
5630                      !(Op3Reg == ARM::SP && Op4Reg == ARM::SP &&
5631                        Op5.isImm() && !Op5.isImm0_508s4());
5632     }
5633     if (!TryTransform)
5634       return;
5635   } else if (!isThumbOne())
5636     return;
5637 
5638   if (!(Mnemonic == "add" || Mnemonic == "sub" || Mnemonic == "and" ||
5639         Mnemonic == "eor" || Mnemonic == "lsl" || Mnemonic == "lsr" ||
5640         Mnemonic == "asr" || Mnemonic == "adc" || Mnemonic == "sbc" ||
5641         Mnemonic == "ror" || Mnemonic == "orr" || Mnemonic == "bic"))
5642     return;
5643 
5644   // If first 2 operands of a 3 operand instruction are the same
5645   // then transform to 2 operand version of the same instruction
5646   // e.g. 'adds r0, r0, #1' transforms to 'adds r0, #1'
5647   bool Transform = Op3Reg == Op4Reg;
5648 
5649   // For communtative operations, we might be able to transform if we swap
5650   // Op4 and Op5.  The 'ADD Rdm, SP, Rdm' form is already handled specially
5651   // as tADDrsp.
5652   const ARMOperand *LastOp = &Op5;
5653   bool Swap = false;
5654   if (!Transform && Op5.isReg() && Op3Reg == Op5.getReg() &&
5655       ((Mnemonic == "add" && Op4Reg != ARM::SP) ||
5656        Mnemonic == "and" || Mnemonic == "eor" ||
5657        Mnemonic == "adc" || Mnemonic == "orr")) {
5658     Swap = true;
5659     LastOp = &Op4;
5660     Transform = true;
5661   }
5662 
5663   // If both registers are the same then remove one of them from
5664   // the operand list, with certain exceptions.
5665   if (Transform) {
5666     // Don't transform 'adds Rd, Rd, Rm' or 'sub{s} Rd, Rd, Rm' because the
5667     // 2 operand forms don't exist.
5668     if (((Mnemonic == "add" && CarrySetting) || Mnemonic == "sub") &&
5669         LastOp->isReg())
5670       Transform = false;
5671 
5672     // Don't transform 'add/sub{s} Rd, Rd, #imm' if the immediate fits into
5673     // 3-bits because the ARMARM says not to.
5674     if ((Mnemonic == "add" || Mnemonic == "sub") && LastOp->isImm0_7())
5675       Transform = false;
5676   }
5677 
5678   if (Transform) {
5679     if (Swap)
5680       std::swap(Op4, Op5);
5681     Operands.erase(Operands.begin() + 3);
5682   }
5683 }
5684 
5685 bool ARMAsmParser::shouldOmitCCOutOperand(StringRef Mnemonic,
5686                                           OperandVector &Operands) {
5687   // FIXME: This is all horribly hacky. We really need a better way to deal
5688   // with optional operands like this in the matcher table.
5689 
5690   // The 'mov' mnemonic is special. One variant has a cc_out operand, while
5691   // another does not. Specifically, the MOVW instruction does not. So we
5692   // special case it here and remove the defaulted (non-setting) cc_out
5693   // operand if that's the instruction we're trying to match.
5694   //
5695   // We do this as post-processing of the explicit operands rather than just
5696   // conditionally adding the cc_out in the first place because we need
5697   // to check the type of the parsed immediate operand.
5698   if (Mnemonic == "mov" && Operands.size() > 4 && !isThumb() &&
5699       !static_cast<ARMOperand &>(*Operands[4]).isModImm() &&
5700       static_cast<ARMOperand &>(*Operands[4]).isImm0_65535Expr() &&
5701       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0)
5702     return true;
5703 
5704   // Register-register 'add' for thumb does not have a cc_out operand
5705   // when there are only two register operands.
5706   if (isThumb() && Mnemonic == "add" && Operands.size() == 5 &&
5707       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5708       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5709       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0)
5710     return true;
5711   // Register-register 'add' for thumb does not have a cc_out operand
5712   // when it's an ADD Rdm, SP, {Rdm|#imm0_255} instruction. We do
5713   // have to check the immediate range here since Thumb2 has a variant
5714   // that can handle a different range and has a cc_out operand.
5715   if (((isThumb() && Mnemonic == "add") ||
5716        (isThumbTwo() && Mnemonic == "sub")) &&
5717       Operands.size() == 6 && static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5718       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5719       static_cast<ARMOperand &>(*Operands[4]).getReg() == ARM::SP &&
5720       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5721       ((Mnemonic == "add" && static_cast<ARMOperand &>(*Operands[5]).isReg()) ||
5722        static_cast<ARMOperand &>(*Operands[5]).isImm0_1020s4()))
5723     return true;
5724   // For Thumb2, add/sub immediate does not have a cc_out operand for the
5725   // imm0_4095 variant. That's the least-preferred variant when
5726   // selecting via the generic "add" mnemonic, so to know that we
5727   // should remove the cc_out operand, we have to explicitly check that
5728   // it's not one of the other variants. Ugh.
5729   if (isThumbTwo() && (Mnemonic == "add" || Mnemonic == "sub") &&
5730       Operands.size() == 6 && static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5731       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5732       static_cast<ARMOperand &>(*Operands[5]).isImm()) {
5733     // Nest conditions rather than one big 'if' statement for readability.
5734     //
5735     // If both registers are low, we're in an IT block, and the immediate is
5736     // in range, we should use encoding T1 instead, which has a cc_out.
5737     if (inITBlock() &&
5738         isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) &&
5739         isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) &&
5740         static_cast<ARMOperand &>(*Operands[5]).isImm0_7())
5741       return false;
5742     // Check against T3. If the second register is the PC, this is an
5743     // alternate form of ADR, which uses encoding T4, so check for that too.
5744     if (static_cast<ARMOperand &>(*Operands[4]).getReg() != ARM::PC &&
5745         static_cast<ARMOperand &>(*Operands[5]).isT2SOImm())
5746       return false;
5747 
5748     // Otherwise, we use encoding T4, which does not have a cc_out
5749     // operand.
5750     return true;
5751   }
5752 
5753   // The thumb2 multiply instruction doesn't have a CCOut register, so
5754   // if we have a "mul" mnemonic in Thumb mode, check if we'll be able to
5755   // use the 16-bit encoding or not.
5756   if (isThumbTwo() && Mnemonic == "mul" && Operands.size() == 6 &&
5757       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5758       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5759       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5760       static_cast<ARMOperand &>(*Operands[5]).isReg() &&
5761       // If the registers aren't low regs, the destination reg isn't the
5762       // same as one of the source regs, or the cc_out operand is zero
5763       // outside of an IT block, we have to use the 32-bit encoding, so
5764       // remove the cc_out operand.
5765       (!isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) ||
5766        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) ||
5767        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[5]).getReg()) ||
5768        !inITBlock() || (static_cast<ARMOperand &>(*Operands[3]).getReg() !=
5769                             static_cast<ARMOperand &>(*Operands[5]).getReg() &&
5770                         static_cast<ARMOperand &>(*Operands[3]).getReg() !=
5771                             static_cast<ARMOperand &>(*Operands[4]).getReg())))
5772     return true;
5773 
5774   // Also check the 'mul' syntax variant that doesn't specify an explicit
5775   // destination register.
5776   if (isThumbTwo() && Mnemonic == "mul" && Operands.size() == 5 &&
5777       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5778       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5779       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
5780       // If the registers aren't low regs  or the cc_out operand is zero
5781       // outside of an IT block, we have to use the 32-bit encoding, so
5782       // remove the cc_out operand.
5783       (!isARMLowRegister(static_cast<ARMOperand &>(*Operands[3]).getReg()) ||
5784        !isARMLowRegister(static_cast<ARMOperand &>(*Operands[4]).getReg()) ||
5785        !inITBlock()))
5786     return true;
5787 
5788   // Register-register 'add/sub' for thumb does not have a cc_out operand
5789   // when it's an ADD/SUB SP, #imm. Be lenient on count since there's also
5790   // the "add/sub SP, SP, #imm" version. If the follow-up operands aren't
5791   // right, this will result in better diagnostics (which operand is off)
5792   // anyway.
5793   if (isThumb() && (Mnemonic == "add" || Mnemonic == "sub") &&
5794       (Operands.size() == 5 || Operands.size() == 6) &&
5795       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
5796       static_cast<ARMOperand &>(*Operands[3]).getReg() == ARM::SP &&
5797       static_cast<ARMOperand &>(*Operands[1]).getReg() == 0 &&
5798       (static_cast<ARMOperand &>(*Operands[4]).isImm() ||
5799        (Operands.size() == 6 &&
5800         static_cast<ARMOperand &>(*Operands[5]).isImm())))
5801     return true;
5802 
5803   return false;
5804 }
5805 
5806 bool ARMAsmParser::shouldOmitPredicateOperand(StringRef Mnemonic,
5807                                               OperandVector &Operands) {
5808   // VRINT{Z, R, X} have a predicate operand in VFP, but not in NEON
5809   unsigned RegIdx = 3;
5810   if ((Mnemonic == "vrintz" || Mnemonic == "vrintx" || Mnemonic == "vrintr") &&
5811       (static_cast<ARMOperand &>(*Operands[2]).getToken() == ".f32" ||
5812        static_cast<ARMOperand &>(*Operands[2]).getToken() == ".f16")) {
5813     if (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
5814         (static_cast<ARMOperand &>(*Operands[3]).getToken() == ".f32" ||
5815          static_cast<ARMOperand &>(*Operands[3]).getToken() == ".f16"))
5816       RegIdx = 4;
5817 
5818     if (static_cast<ARMOperand &>(*Operands[RegIdx]).isReg() &&
5819         (ARMMCRegisterClasses[ARM::DPRRegClassID].contains(
5820              static_cast<ARMOperand &>(*Operands[RegIdx]).getReg()) ||
5821          ARMMCRegisterClasses[ARM::QPRRegClassID].contains(
5822              static_cast<ARMOperand &>(*Operands[RegIdx]).getReg())))
5823       return true;
5824   }
5825   return false;
5826 }
5827 
5828 static bool isDataTypeToken(StringRef Tok) {
5829   return Tok == ".8" || Tok == ".16" || Tok == ".32" || Tok == ".64" ||
5830     Tok == ".i8" || Tok == ".i16" || Tok == ".i32" || Tok == ".i64" ||
5831     Tok == ".u8" || Tok == ".u16" || Tok == ".u32" || Tok == ".u64" ||
5832     Tok == ".s8" || Tok == ".s16" || Tok == ".s32" || Tok == ".s64" ||
5833     Tok == ".p8" || Tok == ".p16" || Tok == ".f32" || Tok == ".f64" ||
5834     Tok == ".f" || Tok == ".d";
5835 }
5836 
5837 // FIXME: This bit should probably be handled via an explicit match class
5838 // in the .td files that matches the suffix instead of having it be
5839 // a literal string token the way it is now.
5840 static bool doesIgnoreDataTypeSuffix(StringRef Mnemonic, StringRef DT) {
5841   return Mnemonic.startswith("vldm") || Mnemonic.startswith("vstm");
5842 }
5843 
5844 static void applyMnemonicAliases(StringRef &Mnemonic, uint64_t Features,
5845                                  unsigned VariantID);
5846 
5847 static bool RequiresVFPRegListValidation(StringRef Inst,
5848                                          bool &AcceptSinglePrecisionOnly,
5849                                          bool &AcceptDoublePrecisionOnly) {
5850   if (Inst.size() < 7)
5851     return false;
5852 
5853   if (Inst.startswith("fldm") || Inst.startswith("fstm")) {
5854     StringRef AddressingMode = Inst.substr(4, 2);
5855     if (AddressingMode == "ia" || AddressingMode == "db" ||
5856         AddressingMode == "ea" || AddressingMode == "fd") {
5857       AcceptSinglePrecisionOnly = Inst[6] == 's';
5858       AcceptDoublePrecisionOnly = Inst[6] == 'd' || Inst[6] == 'x';
5859       return true;
5860     }
5861   }
5862 
5863   return false;
5864 }
5865 
5866 /// Parse an arm instruction mnemonic followed by its operands.
5867 bool ARMAsmParser::ParseInstruction(ParseInstructionInfo &Info, StringRef Name,
5868                                     SMLoc NameLoc, OperandVector &Operands) {
5869   MCAsmParser &Parser = getParser();
5870   // FIXME: Can this be done via tablegen in some fashion?
5871   bool RequireVFPRegisterListCheck;
5872   bool AcceptSinglePrecisionOnly;
5873   bool AcceptDoublePrecisionOnly;
5874   RequireVFPRegisterListCheck =
5875     RequiresVFPRegListValidation(Name, AcceptSinglePrecisionOnly,
5876                                  AcceptDoublePrecisionOnly);
5877 
5878   // Apply mnemonic aliases before doing anything else, as the destination
5879   // mnemonic may include suffices and we want to handle them normally.
5880   // The generic tblgen'erated code does this later, at the start of
5881   // MatchInstructionImpl(), but that's too late for aliases that include
5882   // any sort of suffix.
5883   uint64_t AvailableFeatures = getAvailableFeatures();
5884   unsigned AssemblerDialect = getParser().getAssemblerDialect();
5885   applyMnemonicAliases(Name, AvailableFeatures, AssemblerDialect);
5886 
5887   // First check for the ARM-specific .req directive.
5888   if (Parser.getTok().is(AsmToken::Identifier) &&
5889       Parser.getTok().getIdentifier() == ".req") {
5890     parseDirectiveReq(Name, NameLoc);
5891     // We always return 'error' for this, as we're done with this
5892     // statement and don't need to match the 'instruction."
5893     return true;
5894   }
5895 
5896   // Create the leading tokens for the mnemonic, split by '.' characters.
5897   size_t Start = 0, Next = Name.find('.');
5898   StringRef Mnemonic = Name.slice(Start, Next);
5899 
5900   // Split out the predication code and carry setting flag from the mnemonic.
5901   unsigned PredicationCode;
5902   unsigned ProcessorIMod;
5903   bool CarrySetting;
5904   StringRef ITMask;
5905   Mnemonic = splitMnemonic(Mnemonic, PredicationCode, CarrySetting,
5906                            ProcessorIMod, ITMask);
5907 
5908   // In Thumb1, only the branch (B) instruction can be predicated.
5909   if (isThumbOne() && PredicationCode != ARMCC::AL && Mnemonic != "b") {
5910     return Error(NameLoc, "conditional execution not supported in Thumb1");
5911   }
5912 
5913   Operands.push_back(ARMOperand::CreateToken(Mnemonic, NameLoc));
5914 
5915   // Handle the IT instruction ITMask. Convert it to a bitmask. This
5916   // is the mask as it will be for the IT encoding if the conditional
5917   // encoding has a '1' as it's bit0 (i.e. 't' ==> '1'). In the case
5918   // where the conditional bit0 is zero, the instruction post-processing
5919   // will adjust the mask accordingly.
5920   if (Mnemonic == "it") {
5921     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + 2);
5922     if (ITMask.size() > 3) {
5923       return Error(Loc, "too many conditions on IT instruction");
5924     }
5925     unsigned Mask = 8;
5926     for (unsigned i = ITMask.size(); i != 0; --i) {
5927       char pos = ITMask[i - 1];
5928       if (pos != 't' && pos != 'e') {
5929         return Error(Loc, "illegal IT block condition mask '" + ITMask + "'");
5930       }
5931       Mask >>= 1;
5932       if (ITMask[i - 1] == 't')
5933         Mask |= 8;
5934     }
5935     Operands.push_back(ARMOperand::CreateITMask(Mask, Loc));
5936   }
5937 
5938   // FIXME: This is all a pretty gross hack. We should automatically handle
5939   // optional operands like this via tblgen.
5940 
5941   // Next, add the CCOut and ConditionCode operands, if needed.
5942   //
5943   // For mnemonics which can ever incorporate a carry setting bit or predication
5944   // code, our matching model involves us always generating CCOut and
5945   // ConditionCode operands to match the mnemonic "as written" and then we let
5946   // the matcher deal with finding the right instruction or generating an
5947   // appropriate error.
5948   bool CanAcceptCarrySet, CanAcceptPredicationCode;
5949   getMnemonicAcceptInfo(Mnemonic, Name, CanAcceptCarrySet, CanAcceptPredicationCode);
5950 
5951   // If we had a carry-set on an instruction that can't do that, issue an
5952   // error.
5953   if (!CanAcceptCarrySet && CarrySetting) {
5954     return Error(NameLoc, "instruction '" + Mnemonic +
5955                  "' can not set flags, but 's' suffix specified");
5956   }
5957   // If we had a predication code on an instruction that can't do that, issue an
5958   // error.
5959   if (!CanAcceptPredicationCode && PredicationCode != ARMCC::AL) {
5960     return Error(NameLoc, "instruction '" + Mnemonic +
5961                  "' is not predicable, but condition code specified");
5962   }
5963 
5964   // Add the carry setting operand, if necessary.
5965   if (CanAcceptCarrySet) {
5966     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size());
5967     Operands.push_back(ARMOperand::CreateCCOut(CarrySetting ? ARM::CPSR : 0,
5968                                                Loc));
5969   }
5970 
5971   // Add the predication code operand, if necessary.
5972   if (CanAcceptPredicationCode) {
5973     SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Mnemonic.size() +
5974                                       CarrySetting);
5975     Operands.push_back(ARMOperand::CreateCondCode(
5976                          ARMCC::CondCodes(PredicationCode), Loc));
5977   }
5978 
5979   // Add the processor imod operand, if necessary.
5980   if (ProcessorIMod) {
5981     Operands.push_back(ARMOperand::CreateImm(
5982           MCConstantExpr::create(ProcessorIMod, getContext()),
5983                                  NameLoc, NameLoc));
5984   } else if (Mnemonic == "cps" && isMClass()) {
5985     return Error(NameLoc, "instruction 'cps' requires effect for M-class");
5986   }
5987 
5988   // Add the remaining tokens in the mnemonic.
5989   while (Next != StringRef::npos) {
5990     Start = Next;
5991     Next = Name.find('.', Start + 1);
5992     StringRef ExtraToken = Name.slice(Start, Next);
5993 
5994     // Some NEON instructions have an optional datatype suffix that is
5995     // completely ignored. Check for that.
5996     if (isDataTypeToken(ExtraToken) &&
5997         doesIgnoreDataTypeSuffix(Mnemonic, ExtraToken))
5998       continue;
5999 
6000     // For for ARM mode generate an error if the .n qualifier is used.
6001     if (ExtraToken == ".n" && !isThumb()) {
6002       SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Start);
6003       return Error(Loc, "instruction with .n (narrow) qualifier not allowed in "
6004                    "arm mode");
6005     }
6006 
6007     // The .n qualifier is always discarded as that is what the tables
6008     // and matcher expect.  In ARM mode the .w qualifier has no effect,
6009     // so discard it to avoid errors that can be caused by the matcher.
6010     if (ExtraToken != ".n" && (isThumb() || ExtraToken != ".w")) {
6011       SMLoc Loc = SMLoc::getFromPointer(NameLoc.getPointer() + Start);
6012       Operands.push_back(ARMOperand::CreateToken(ExtraToken, Loc));
6013     }
6014   }
6015 
6016   // Read the remaining operands.
6017   if (getLexer().isNot(AsmToken::EndOfStatement)) {
6018     // Read the first operand.
6019     if (parseOperand(Operands, Mnemonic)) {
6020       return true;
6021     }
6022 
6023     while (parseOptionalToken(AsmToken::Comma)) {
6024       // Parse and remember the operand.
6025       if (parseOperand(Operands, Mnemonic)) {
6026         return true;
6027       }
6028     }
6029   }
6030 
6031   if (parseToken(AsmToken::EndOfStatement, "unexpected token in argument list"))
6032     return true;
6033 
6034   if (RequireVFPRegisterListCheck) {
6035     ARMOperand &Op = static_cast<ARMOperand &>(*Operands.back());
6036     if (AcceptSinglePrecisionOnly && !Op.isSPRRegList())
6037       return Error(Op.getStartLoc(),
6038                    "VFP/Neon single precision register expected");
6039     if (AcceptDoublePrecisionOnly && !Op.isDPRRegList())
6040       return Error(Op.getStartLoc(),
6041                    "VFP/Neon double precision register expected");
6042   }
6043 
6044   tryConvertingToTwoOperandForm(Mnemonic, CarrySetting, Operands);
6045 
6046   // Some instructions, mostly Thumb, have forms for the same mnemonic that
6047   // do and don't have a cc_out optional-def operand. With some spot-checks
6048   // of the operand list, we can figure out which variant we're trying to
6049   // parse and adjust accordingly before actually matching. We shouldn't ever
6050   // try to remove a cc_out operand that was explicitly set on the
6051   // mnemonic, of course (CarrySetting == true). Reason number #317 the
6052   // table driven matcher doesn't fit well with the ARM instruction set.
6053   if (!CarrySetting && shouldOmitCCOutOperand(Mnemonic, Operands))
6054     Operands.erase(Operands.begin() + 1);
6055 
6056   // Some instructions have the same mnemonic, but don't always
6057   // have a predicate. Distinguish them here and delete the
6058   // predicate if needed.
6059   if (shouldOmitPredicateOperand(Mnemonic, Operands))
6060     Operands.erase(Operands.begin() + 1);
6061 
6062   // ARM mode 'blx' need special handling, as the register operand version
6063   // is predicable, but the label operand version is not. So, we can't rely
6064   // on the Mnemonic based checking to correctly figure out when to put
6065   // a k_CondCode operand in the list. If we're trying to match the label
6066   // version, remove the k_CondCode operand here.
6067   if (!isThumb() && Mnemonic == "blx" && Operands.size() == 3 &&
6068       static_cast<ARMOperand &>(*Operands[2]).isImm())
6069     Operands.erase(Operands.begin() + 1);
6070 
6071   // Adjust operands of ldrexd/strexd to MCK_GPRPair.
6072   // ldrexd/strexd require even/odd GPR pair. To enforce this constraint,
6073   // a single GPRPair reg operand is used in the .td file to replace the two
6074   // GPRs. However, when parsing from asm, the two GRPs cannot be automatically
6075   // expressed as a GPRPair, so we have to manually merge them.
6076   // FIXME: We would really like to be able to tablegen'erate this.
6077   if (!isThumb() && Operands.size() > 4 &&
6078       (Mnemonic == "ldrexd" || Mnemonic == "strexd" || Mnemonic == "ldaexd" ||
6079        Mnemonic == "stlexd")) {
6080     bool isLoad = (Mnemonic == "ldrexd" || Mnemonic == "ldaexd");
6081     unsigned Idx = isLoad ? 2 : 3;
6082     ARMOperand &Op1 = static_cast<ARMOperand &>(*Operands[Idx]);
6083     ARMOperand &Op2 = static_cast<ARMOperand &>(*Operands[Idx + 1]);
6084 
6085     const MCRegisterClass& MRC = MRI->getRegClass(ARM::GPRRegClassID);
6086     // Adjust only if Op1 and Op2 are GPRs.
6087     if (Op1.isReg() && Op2.isReg() && MRC.contains(Op1.getReg()) &&
6088         MRC.contains(Op2.getReg())) {
6089       unsigned Reg1 = Op1.getReg();
6090       unsigned Reg2 = Op2.getReg();
6091       unsigned Rt = MRI->getEncodingValue(Reg1);
6092       unsigned Rt2 = MRI->getEncodingValue(Reg2);
6093 
6094       // Rt2 must be Rt + 1 and Rt must be even.
6095       if (Rt + 1 != Rt2 || (Rt & 1)) {
6096         return Error(Op2.getStartLoc(),
6097                      isLoad ? "destination operands must be sequential"
6098                             : "source operands must be sequential");
6099       }
6100       unsigned NewReg = MRI->getMatchingSuperReg(Reg1, ARM::gsub_0,
6101           &(MRI->getRegClass(ARM::GPRPairRegClassID)));
6102       Operands[Idx] =
6103           ARMOperand::CreateReg(NewReg, Op1.getStartLoc(), Op2.getEndLoc());
6104       Operands.erase(Operands.begin() + Idx + 1);
6105     }
6106   }
6107 
6108   // GNU Assembler extension (compatibility)
6109   if ((Mnemonic == "ldrd" || Mnemonic == "strd")) {
6110     ARMOperand &Op2 = static_cast<ARMOperand &>(*Operands[2]);
6111     ARMOperand &Op3 = static_cast<ARMOperand &>(*Operands[3]);
6112     if (Op3.isMem()) {
6113       assert(Op2.isReg() && "expected register argument");
6114 
6115       unsigned SuperReg = MRI->getMatchingSuperReg(
6116           Op2.getReg(), ARM::gsub_0, &MRI->getRegClass(ARM::GPRPairRegClassID));
6117 
6118       assert(SuperReg && "expected register pair");
6119 
6120       unsigned PairedReg = MRI->getSubReg(SuperReg, ARM::gsub_1);
6121 
6122       Operands.insert(
6123           Operands.begin() + 3,
6124           ARMOperand::CreateReg(PairedReg, Op2.getStartLoc(), Op2.getEndLoc()));
6125     }
6126   }
6127 
6128   // FIXME: As said above, this is all a pretty gross hack.  This instruction
6129   // does not fit with other "subs" and tblgen.
6130   // Adjust operands of B9.3.19 SUBS PC, LR, #imm (Thumb2) system instruction
6131   // so the Mnemonic is the original name "subs" and delete the predicate
6132   // operand so it will match the table entry.
6133   if (isThumbTwo() && Mnemonic == "sub" && Operands.size() == 6 &&
6134       static_cast<ARMOperand &>(*Operands[3]).isReg() &&
6135       static_cast<ARMOperand &>(*Operands[3]).getReg() == ARM::PC &&
6136       static_cast<ARMOperand &>(*Operands[4]).isReg() &&
6137       static_cast<ARMOperand &>(*Operands[4]).getReg() == ARM::LR &&
6138       static_cast<ARMOperand &>(*Operands[5]).isImm()) {
6139     Operands.front() = ARMOperand::CreateToken(Name, NameLoc);
6140     Operands.erase(Operands.begin() + 1);
6141   }
6142   return false;
6143 }
6144 
6145 // Validate context-sensitive operand constraints.
6146 
6147 // return 'true' if register list contains non-low GPR registers,
6148 // 'false' otherwise. If Reg is in the register list or is HiReg, set
6149 // 'containsReg' to true.
6150 static bool checkLowRegisterList(const MCInst &Inst, unsigned OpNo,
6151                                  unsigned Reg, unsigned HiReg,
6152                                  bool &containsReg) {
6153   containsReg = false;
6154   for (unsigned i = OpNo; i < Inst.getNumOperands(); ++i) {
6155     unsigned OpReg = Inst.getOperand(i).getReg();
6156     if (OpReg == Reg)
6157       containsReg = true;
6158     // Anything other than a low register isn't legal here.
6159     if (!isARMLowRegister(OpReg) && (!HiReg || OpReg != HiReg))
6160       return true;
6161   }
6162   return false;
6163 }
6164 
6165 // Check if the specified regisgter is in the register list of the inst,
6166 // starting at the indicated operand number.
6167 static bool listContainsReg(const MCInst &Inst, unsigned OpNo, unsigned Reg) {
6168   for (unsigned i = OpNo, e = Inst.getNumOperands(); i < e; ++i) {
6169     unsigned OpReg = Inst.getOperand(i).getReg();
6170     if (OpReg == Reg)
6171       return true;
6172   }
6173   return false;
6174 }
6175 
6176 // Return true if instruction has the interesting property of being
6177 // allowed in IT blocks, but not being predicable.
6178 static bool instIsBreakpoint(const MCInst &Inst) {
6179     return Inst.getOpcode() == ARM::tBKPT ||
6180            Inst.getOpcode() == ARM::BKPT ||
6181            Inst.getOpcode() == ARM::tHLT ||
6182            Inst.getOpcode() == ARM::HLT;
6183 }
6184 
6185 bool ARMAsmParser::validatetLDMRegList(const MCInst &Inst,
6186                                        const OperandVector &Operands,
6187                                        unsigned ListNo, bool IsARPop) {
6188   const ARMOperand &Op = static_cast<const ARMOperand &>(*Operands[ListNo]);
6189   bool HasWritebackToken = Op.isToken() && Op.getToken() == "!";
6190 
6191   bool ListContainsSP = listContainsReg(Inst, ListNo, ARM::SP);
6192   bool ListContainsLR = listContainsReg(Inst, ListNo, ARM::LR);
6193   bool ListContainsPC = listContainsReg(Inst, ListNo, ARM::PC);
6194 
6195   if (!IsARPop && ListContainsSP)
6196     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6197                  "SP may not be in the register list");
6198   else if (ListContainsPC && ListContainsLR)
6199     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6200                  "PC and LR may not be in the register list simultaneously");
6201   return false;
6202 }
6203 
6204 bool ARMAsmParser::validatetSTMRegList(const MCInst &Inst,
6205                                        const OperandVector &Operands,
6206                                        unsigned ListNo) {
6207   const ARMOperand &Op = static_cast<const ARMOperand &>(*Operands[ListNo]);
6208   bool HasWritebackToken = Op.isToken() && Op.getToken() == "!";
6209 
6210   bool ListContainsSP = listContainsReg(Inst, ListNo, ARM::SP);
6211   bool ListContainsPC = listContainsReg(Inst, ListNo, ARM::PC);
6212 
6213   if (ListContainsSP && ListContainsPC)
6214     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6215                  "SP and PC may not be in the register list");
6216   else if (ListContainsSP)
6217     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6218                  "SP may not be in the register list");
6219   else if (ListContainsPC)
6220     return Error(Operands[ListNo + HasWritebackToken]->getStartLoc(),
6221                  "PC may not be in the register list");
6222   return false;
6223 }
6224 
6225 // FIXME: We would really like to be able to tablegen'erate this.
6226 bool ARMAsmParser::validateInstruction(MCInst &Inst,
6227                                        const OperandVector &Operands) {
6228   const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
6229   SMLoc Loc = Operands[0]->getStartLoc();
6230 
6231   // Check the IT block state first.
6232   // NOTE: BKPT and HLT instructions have the interesting property of being
6233   // allowed in IT blocks, but not being predicable. They just always execute.
6234   if (inITBlock() && !instIsBreakpoint(Inst)) {
6235     // The instruction must be predicable.
6236     if (!MCID.isPredicable())
6237       return Error(Loc, "instructions in IT block must be predicable");
6238     unsigned Cond = Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm();
6239     if (Cond != currentITCond()) {
6240       // Find the condition code Operand to get its SMLoc information.
6241       SMLoc CondLoc;
6242       for (unsigned I = 1; I < Operands.size(); ++I)
6243         if (static_cast<ARMOperand &>(*Operands[I]).isCondCode())
6244           CondLoc = Operands[I]->getStartLoc();
6245       return Error(CondLoc, "incorrect condition in IT block; got '" +
6246                    StringRef(ARMCondCodeToString(ARMCC::CondCodes(Cond))) +
6247                    "', but expected '" +
6248                    ARMCondCodeToString(ARMCC::CondCodes(currentITCond())) + "'");
6249     }
6250   // Check for non-'al' condition codes outside of the IT block.
6251   } else if (isThumbTwo() && MCID.isPredicable() &&
6252              Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm() !=
6253              ARMCC::AL && Inst.getOpcode() != ARM::tBcc &&
6254              Inst.getOpcode() != ARM::t2Bcc) {
6255     return Error(Loc, "predicated instructions must be in IT block");
6256   } else if (!isThumb() && !useImplicitITARM() && MCID.isPredicable() &&
6257              Inst.getOperand(MCID.findFirstPredOperandIdx()).getImm() !=
6258                  ARMCC::AL) {
6259     return Warning(Loc, "predicated instructions should be in IT block");
6260   }
6261 
6262   // PC-setting instructions in an IT block, but not the last instruction of
6263   // the block, are UNPREDICTABLE.
6264   if (inExplicitITBlock() && !lastInITBlock() && isITBlockTerminator(Inst)) {
6265     return Error(Loc, "instruction must be outside of IT block or the last instruction in an IT block");
6266   }
6267 
6268   const unsigned Opcode = Inst.getOpcode();
6269   switch (Opcode) {
6270   case ARM::LDRD:
6271   case ARM::LDRD_PRE:
6272   case ARM::LDRD_POST: {
6273     const unsigned RtReg = Inst.getOperand(0).getReg();
6274 
6275     // Rt can't be R14.
6276     if (RtReg == ARM::LR)
6277       return Error(Operands[3]->getStartLoc(),
6278                    "Rt can't be R14");
6279 
6280     const unsigned Rt = MRI->getEncodingValue(RtReg);
6281     // Rt must be even-numbered.
6282     if ((Rt & 1) == 1)
6283       return Error(Operands[3]->getStartLoc(),
6284                    "Rt must be even-numbered");
6285 
6286     // Rt2 must be Rt + 1.
6287     const unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6288     if (Rt2 != Rt + 1)
6289       return Error(Operands[3]->getStartLoc(),
6290                    "destination operands must be sequential");
6291 
6292     if (Opcode == ARM::LDRD_PRE || Opcode == ARM::LDRD_POST) {
6293       const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(3).getReg());
6294       // For addressing modes with writeback, the base register needs to be
6295       // different from the destination registers.
6296       if (Rn == Rt || Rn == Rt2)
6297         return Error(Operands[3]->getStartLoc(),
6298                      "base register needs to be different from destination "
6299                      "registers");
6300     }
6301 
6302     return false;
6303   }
6304   case ARM::t2LDRDi8:
6305   case ARM::t2LDRD_PRE:
6306   case ARM::t2LDRD_POST: {
6307     // Rt2 must be different from Rt.
6308     unsigned Rt = MRI->getEncodingValue(Inst.getOperand(0).getReg());
6309     unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6310     if (Rt2 == Rt)
6311       return Error(Operands[3]->getStartLoc(),
6312                    "destination operands can't be identical");
6313     return false;
6314   }
6315   case ARM::t2BXJ: {
6316     const unsigned RmReg = Inst.getOperand(0).getReg();
6317     // Rm = SP is no longer unpredictable in v8-A
6318     if (RmReg == ARM::SP && !hasV8Ops())
6319       return Error(Operands[2]->getStartLoc(),
6320                    "r13 (SP) is an unpredictable operand to BXJ");
6321     return false;
6322   }
6323   case ARM::STRD: {
6324     // Rt2 must be Rt + 1.
6325     unsigned Rt = MRI->getEncodingValue(Inst.getOperand(0).getReg());
6326     unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6327     if (Rt2 != Rt + 1)
6328       return Error(Operands[3]->getStartLoc(),
6329                    "source operands must be sequential");
6330     return false;
6331   }
6332   case ARM::STRD_PRE:
6333   case ARM::STRD_POST: {
6334     // Rt2 must be Rt + 1.
6335     unsigned Rt = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6336     unsigned Rt2 = MRI->getEncodingValue(Inst.getOperand(2).getReg());
6337     if (Rt2 != Rt + 1)
6338       return Error(Operands[3]->getStartLoc(),
6339                    "source operands must be sequential");
6340     return false;
6341   }
6342   case ARM::STR_PRE_IMM:
6343   case ARM::STR_PRE_REG:
6344   case ARM::STR_POST_IMM:
6345   case ARM::STR_POST_REG:
6346   case ARM::STRH_PRE:
6347   case ARM::STRH_POST:
6348   case ARM::STRB_PRE_IMM:
6349   case ARM::STRB_PRE_REG:
6350   case ARM::STRB_POST_IMM:
6351   case ARM::STRB_POST_REG: {
6352     // Rt must be different from Rn.
6353     const unsigned Rt = MRI->getEncodingValue(Inst.getOperand(1).getReg());
6354     const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(2).getReg());
6355 
6356     if (Rt == Rn)
6357       return Error(Operands[3]->getStartLoc(),
6358                    "source register and base register can't be identical");
6359     return false;
6360   }
6361   case ARM::LDR_PRE_IMM:
6362   case ARM::LDR_PRE_REG:
6363   case ARM::LDR_POST_IMM:
6364   case ARM::LDR_POST_REG:
6365   case ARM::LDRH_PRE:
6366   case ARM::LDRH_POST:
6367   case ARM::LDRSH_PRE:
6368   case ARM::LDRSH_POST:
6369   case ARM::LDRB_PRE_IMM:
6370   case ARM::LDRB_PRE_REG:
6371   case ARM::LDRB_POST_IMM:
6372   case ARM::LDRB_POST_REG:
6373   case ARM::LDRSB_PRE:
6374   case ARM::LDRSB_POST: {
6375     // Rt must be different from Rn.
6376     const unsigned Rt = MRI->getEncodingValue(Inst.getOperand(0).getReg());
6377     const unsigned Rn = MRI->getEncodingValue(Inst.getOperand(2).getReg());
6378 
6379     if (Rt == Rn)
6380       return Error(Operands[3]->getStartLoc(),
6381                    "destination register and base register can't be identical");
6382     return false;
6383   }
6384   case ARM::SBFX:
6385   case ARM::UBFX: {
6386     // Width must be in range [1, 32-lsb].
6387     unsigned LSB = Inst.getOperand(2).getImm();
6388     unsigned Widthm1 = Inst.getOperand(3).getImm();
6389     if (Widthm1 >= 32 - LSB)
6390       return Error(Operands[5]->getStartLoc(),
6391                    "bitfield width must be in range [1,32-lsb]");
6392     return false;
6393   }
6394   // Notionally handles ARM::tLDMIA_UPD too.
6395   case ARM::tLDMIA: {
6396     // If we're parsing Thumb2, the .w variant is available and handles
6397     // most cases that are normally illegal for a Thumb1 LDM instruction.
6398     // We'll make the transformation in processInstruction() if necessary.
6399     //
6400     // Thumb LDM instructions are writeback iff the base register is not
6401     // in the register list.
6402     unsigned Rn = Inst.getOperand(0).getReg();
6403     bool HasWritebackToken =
6404         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
6405          static_cast<ARMOperand &>(*Operands[3]).getToken() == "!");
6406     bool ListContainsBase;
6407     if (checkLowRegisterList(Inst, 3, Rn, 0, ListContainsBase) && !isThumbTwo())
6408       return Error(Operands[3 + HasWritebackToken]->getStartLoc(),
6409                    "registers must be in range r0-r7");
6410     // If we should have writeback, then there should be a '!' token.
6411     if (!ListContainsBase && !HasWritebackToken && !isThumbTwo())
6412       return Error(Operands[2]->getStartLoc(),
6413                    "writeback operator '!' expected");
6414     // If we should not have writeback, there must not be a '!'. This is
6415     // true even for the 32-bit wide encodings.
6416     if (ListContainsBase && HasWritebackToken)
6417       return Error(Operands[3]->getStartLoc(),
6418                    "writeback operator '!' not allowed when base register "
6419                    "in register list");
6420 
6421     if (validatetLDMRegList(Inst, Operands, 3))
6422       return true;
6423     break;
6424   }
6425   case ARM::LDMIA_UPD:
6426   case ARM::LDMDB_UPD:
6427   case ARM::LDMIB_UPD:
6428   case ARM::LDMDA_UPD:
6429     // ARM variants loading and updating the same register are only officially
6430     // UNPREDICTABLE on v7 upwards. Goodness knows what they did before.
6431     if (!hasV7Ops())
6432       break;
6433     if (listContainsReg(Inst, 3, Inst.getOperand(0).getReg()))
6434       return Error(Operands.back()->getStartLoc(),
6435                    "writeback register not allowed in register list");
6436     break;
6437   case ARM::t2LDMIA:
6438   case ARM::t2LDMDB:
6439     if (validatetLDMRegList(Inst, Operands, 3))
6440       return true;
6441     break;
6442   case ARM::t2STMIA:
6443   case ARM::t2STMDB:
6444     if (validatetSTMRegList(Inst, Operands, 3))
6445       return true;
6446     break;
6447   case ARM::t2LDMIA_UPD:
6448   case ARM::t2LDMDB_UPD:
6449   case ARM::t2STMIA_UPD:
6450   case ARM::t2STMDB_UPD:
6451     if (listContainsReg(Inst, 3, Inst.getOperand(0).getReg()))
6452       return Error(Operands.back()->getStartLoc(),
6453                    "writeback register not allowed in register list");
6454 
6455     if (Opcode == ARM::t2LDMIA_UPD || Opcode == ARM::t2LDMDB_UPD) {
6456       if (validatetLDMRegList(Inst, Operands, 3))
6457         return true;
6458     } else {
6459       if (validatetSTMRegList(Inst, Operands, 3))
6460         return true;
6461     }
6462     break;
6463 
6464   case ARM::sysLDMIA_UPD:
6465   case ARM::sysLDMDA_UPD:
6466   case ARM::sysLDMDB_UPD:
6467   case ARM::sysLDMIB_UPD:
6468     if (!listContainsReg(Inst, 3, ARM::PC))
6469       return Error(Operands[4]->getStartLoc(),
6470                    "writeback register only allowed on system LDM "
6471                    "if PC in register-list");
6472     break;
6473   case ARM::sysSTMIA_UPD:
6474   case ARM::sysSTMDA_UPD:
6475   case ARM::sysSTMDB_UPD:
6476   case ARM::sysSTMIB_UPD:
6477     return Error(Operands[2]->getStartLoc(),
6478                  "system STM cannot have writeback register");
6479   case ARM::tMUL:
6480     // The second source operand must be the same register as the destination
6481     // operand.
6482     //
6483     // In this case, we must directly check the parsed operands because the
6484     // cvtThumbMultiply() function is written in such a way that it guarantees
6485     // this first statement is always true for the new Inst.  Essentially, the
6486     // destination is unconditionally copied into the second source operand
6487     // without checking to see if it matches what we actually parsed.
6488     if (Operands.size() == 6 && (((ARMOperand &)*Operands[3]).getReg() !=
6489                                  ((ARMOperand &)*Operands[5]).getReg()) &&
6490         (((ARMOperand &)*Operands[3]).getReg() !=
6491          ((ARMOperand &)*Operands[4]).getReg())) {
6492       return Error(Operands[3]->getStartLoc(),
6493                    "destination register must match source register");
6494     }
6495     break;
6496 
6497   // Like for ldm/stm, push and pop have hi-reg handling version in Thumb2,
6498   // so only issue a diagnostic for thumb1. The instructions will be
6499   // switched to the t2 encodings in processInstruction() if necessary.
6500   case ARM::tPOP: {
6501     bool ListContainsBase;
6502     if (checkLowRegisterList(Inst, 2, 0, ARM::PC, ListContainsBase) &&
6503         !isThumbTwo())
6504       return Error(Operands[2]->getStartLoc(),
6505                    "registers must be in range r0-r7 or pc");
6506     if (validatetLDMRegList(Inst, Operands, 2, !isMClass()))
6507       return true;
6508     break;
6509   }
6510   case ARM::tPUSH: {
6511     bool ListContainsBase;
6512     if (checkLowRegisterList(Inst, 2, 0, ARM::LR, ListContainsBase) &&
6513         !isThumbTwo())
6514       return Error(Operands[2]->getStartLoc(),
6515                    "registers must be in range r0-r7 or lr");
6516     if (validatetSTMRegList(Inst, Operands, 2))
6517       return true;
6518     break;
6519   }
6520   case ARM::tSTMIA_UPD: {
6521     bool ListContainsBase, InvalidLowList;
6522     InvalidLowList = checkLowRegisterList(Inst, 4, Inst.getOperand(0).getReg(),
6523                                           0, ListContainsBase);
6524     if (InvalidLowList && !isThumbTwo())
6525       return Error(Operands[4]->getStartLoc(),
6526                    "registers must be in range r0-r7");
6527 
6528     // This would be converted to a 32-bit stm, but that's not valid if the
6529     // writeback register is in the list.
6530     if (InvalidLowList && ListContainsBase)
6531       return Error(Operands[4]->getStartLoc(),
6532                    "writeback operator '!' not allowed when base register "
6533                    "in register list");
6534 
6535     if (validatetSTMRegList(Inst, Operands, 4))
6536       return true;
6537     break;
6538   }
6539   case ARM::tADDrSP:
6540     // If the non-SP source operand and the destination operand are not the
6541     // same, we need thumb2 (for the wide encoding), or we have an error.
6542     if (!isThumbTwo() &&
6543         Inst.getOperand(0).getReg() != Inst.getOperand(2).getReg()) {
6544       return Error(Operands[4]->getStartLoc(),
6545                    "source register must be the same as destination");
6546     }
6547     break;
6548 
6549   // Final range checking for Thumb unconditional branch instructions.
6550   case ARM::tB:
6551     if (!(static_cast<ARMOperand &>(*Operands[2])).isSignedOffset<11, 1>())
6552       return Error(Operands[2]->getStartLoc(), "branch target out of range");
6553     break;
6554   case ARM::t2B: {
6555     int op = (Operands[2]->isImm()) ? 2 : 3;
6556     if (!static_cast<ARMOperand &>(*Operands[op]).isSignedOffset<24, 1>())
6557       return Error(Operands[op]->getStartLoc(), "branch target out of range");
6558     break;
6559   }
6560   // Final range checking for Thumb conditional branch instructions.
6561   case ARM::tBcc:
6562     if (!static_cast<ARMOperand &>(*Operands[2]).isSignedOffset<8, 1>())
6563       return Error(Operands[2]->getStartLoc(), "branch target out of range");
6564     break;
6565   case ARM::t2Bcc: {
6566     int Op = (Operands[2]->isImm()) ? 2 : 3;
6567     if (!static_cast<ARMOperand &>(*Operands[Op]).isSignedOffset<20, 1>())
6568       return Error(Operands[Op]->getStartLoc(), "branch target out of range");
6569     break;
6570   }
6571   case ARM::tCBZ:
6572   case ARM::tCBNZ: {
6573     if (!static_cast<ARMOperand &>(*Operands[2]).isUnsignedOffset<6, 1>())
6574       return Error(Operands[2]->getStartLoc(), "branch target out of range");
6575     break;
6576   }
6577   case ARM::MOVi16:
6578   case ARM::MOVTi16:
6579   case ARM::t2MOVi16:
6580   case ARM::t2MOVTi16:
6581     {
6582     // We want to avoid misleadingly allowing something like "mov r0, <symbol>"
6583     // especially when we turn it into a movw and the expression <symbol> does
6584     // not have a :lower16: or :upper16 as part of the expression.  We don't
6585     // want the behavior of silently truncating, which can be unexpected and
6586     // lead to bugs that are difficult to find since this is an easy mistake
6587     // to make.
6588     int i = (Operands[3]->isImm()) ? 3 : 4;
6589     ARMOperand &Op = static_cast<ARMOperand &>(*Operands[i]);
6590     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm());
6591     if (CE) break;
6592     const MCExpr *E = dyn_cast<MCExpr>(Op.getImm());
6593     if (!E) break;
6594     const ARMMCExpr *ARM16Expr = dyn_cast<ARMMCExpr>(E);
6595     if (!ARM16Expr || (ARM16Expr->getKind() != ARMMCExpr::VK_ARM_HI16 &&
6596                        ARM16Expr->getKind() != ARMMCExpr::VK_ARM_LO16))
6597       return Error(
6598           Op.getStartLoc(),
6599           "immediate expression for mov requires :lower16: or :upper16");
6600     break;
6601   }
6602   case ARM::HINT:
6603   case ARM::t2HINT:
6604     if (hasRAS()) {
6605       // ESB is not predicable (pred must be AL)
6606       unsigned Imm8 = Inst.getOperand(0).getImm();
6607       unsigned Pred = Inst.getOperand(1).getImm();
6608       if (Imm8 == 0x10 && Pred != ARMCC::AL)
6609         return Error(Operands[1]->getStartLoc(), "instruction 'esb' is not "
6610                                                  "predicable, but condition "
6611                                                  "code specified");
6612     }
6613     // Without the RAS extension, this behaves as any other unallocated hint.
6614     break;
6615   }
6616 
6617   return false;
6618 }
6619 
6620 static unsigned getRealVSTOpcode(unsigned Opc, unsigned &Spacing) {
6621   switch(Opc) {
6622   default: llvm_unreachable("unexpected opcode!");
6623   // VST1LN
6624   case ARM::VST1LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST1LNd8_UPD;
6625   case ARM::VST1LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST1LNd16_UPD;
6626   case ARM::VST1LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST1LNd32_UPD;
6627   case ARM::VST1LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST1LNd8_UPD;
6628   case ARM::VST1LNdWB_register_Asm_16: Spacing = 1; return ARM::VST1LNd16_UPD;
6629   case ARM::VST1LNdWB_register_Asm_32: Spacing = 1; return ARM::VST1LNd32_UPD;
6630   case ARM::VST1LNdAsm_8:  Spacing = 1; return ARM::VST1LNd8;
6631   case ARM::VST1LNdAsm_16: Spacing = 1; return ARM::VST1LNd16;
6632   case ARM::VST1LNdAsm_32: Spacing = 1; return ARM::VST1LNd32;
6633 
6634   // VST2LN
6635   case ARM::VST2LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST2LNd8_UPD;
6636   case ARM::VST2LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST2LNd16_UPD;
6637   case ARM::VST2LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST2LNd32_UPD;
6638   case ARM::VST2LNqWB_fixed_Asm_16: Spacing = 2; return ARM::VST2LNq16_UPD;
6639   case ARM::VST2LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST2LNq32_UPD;
6640 
6641   case ARM::VST2LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST2LNd8_UPD;
6642   case ARM::VST2LNdWB_register_Asm_16: Spacing = 1; return ARM::VST2LNd16_UPD;
6643   case ARM::VST2LNdWB_register_Asm_32: Spacing = 1; return ARM::VST2LNd32_UPD;
6644   case ARM::VST2LNqWB_register_Asm_16: Spacing = 2; return ARM::VST2LNq16_UPD;
6645   case ARM::VST2LNqWB_register_Asm_32: Spacing = 2; return ARM::VST2LNq32_UPD;
6646 
6647   case ARM::VST2LNdAsm_8:  Spacing = 1; return ARM::VST2LNd8;
6648   case ARM::VST2LNdAsm_16: Spacing = 1; return ARM::VST2LNd16;
6649   case ARM::VST2LNdAsm_32: Spacing = 1; return ARM::VST2LNd32;
6650   case ARM::VST2LNqAsm_16: Spacing = 2; return ARM::VST2LNq16;
6651   case ARM::VST2LNqAsm_32: Spacing = 2; return ARM::VST2LNq32;
6652 
6653   // VST3LN
6654   case ARM::VST3LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST3LNd8_UPD;
6655   case ARM::VST3LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST3LNd16_UPD;
6656   case ARM::VST3LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST3LNd32_UPD;
6657   case ARM::VST3LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VST3LNq16_UPD;
6658   case ARM::VST3LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST3LNq32_UPD;
6659   case ARM::VST3LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST3LNd8_UPD;
6660   case ARM::VST3LNdWB_register_Asm_16: Spacing = 1; return ARM::VST3LNd16_UPD;
6661   case ARM::VST3LNdWB_register_Asm_32: Spacing = 1; return ARM::VST3LNd32_UPD;
6662   case ARM::VST3LNqWB_register_Asm_16: Spacing = 2; return ARM::VST3LNq16_UPD;
6663   case ARM::VST3LNqWB_register_Asm_32: Spacing = 2; return ARM::VST3LNq32_UPD;
6664   case ARM::VST3LNdAsm_8:  Spacing = 1; return ARM::VST3LNd8;
6665   case ARM::VST3LNdAsm_16: Spacing = 1; return ARM::VST3LNd16;
6666   case ARM::VST3LNdAsm_32: Spacing = 1; return ARM::VST3LNd32;
6667   case ARM::VST3LNqAsm_16: Spacing = 2; return ARM::VST3LNq16;
6668   case ARM::VST3LNqAsm_32: Spacing = 2; return ARM::VST3LNq32;
6669 
6670   // VST3
6671   case ARM::VST3dWB_fixed_Asm_8:  Spacing = 1; return ARM::VST3d8_UPD;
6672   case ARM::VST3dWB_fixed_Asm_16: Spacing = 1; return ARM::VST3d16_UPD;
6673   case ARM::VST3dWB_fixed_Asm_32: Spacing = 1; return ARM::VST3d32_UPD;
6674   case ARM::VST3qWB_fixed_Asm_8:  Spacing = 2; return ARM::VST3q8_UPD;
6675   case ARM::VST3qWB_fixed_Asm_16: Spacing = 2; return ARM::VST3q16_UPD;
6676   case ARM::VST3qWB_fixed_Asm_32: Spacing = 2; return ARM::VST3q32_UPD;
6677   case ARM::VST3dWB_register_Asm_8:  Spacing = 1; return ARM::VST3d8_UPD;
6678   case ARM::VST3dWB_register_Asm_16: Spacing = 1; return ARM::VST3d16_UPD;
6679   case ARM::VST3dWB_register_Asm_32: Spacing = 1; return ARM::VST3d32_UPD;
6680   case ARM::VST3qWB_register_Asm_8:  Spacing = 2; return ARM::VST3q8_UPD;
6681   case ARM::VST3qWB_register_Asm_16: Spacing = 2; return ARM::VST3q16_UPD;
6682   case ARM::VST3qWB_register_Asm_32: Spacing = 2; return ARM::VST3q32_UPD;
6683   case ARM::VST3dAsm_8:  Spacing = 1; return ARM::VST3d8;
6684   case ARM::VST3dAsm_16: Spacing = 1; return ARM::VST3d16;
6685   case ARM::VST3dAsm_32: Spacing = 1; return ARM::VST3d32;
6686   case ARM::VST3qAsm_8:  Spacing = 2; return ARM::VST3q8;
6687   case ARM::VST3qAsm_16: Spacing = 2; return ARM::VST3q16;
6688   case ARM::VST3qAsm_32: Spacing = 2; return ARM::VST3q32;
6689 
6690   // VST4LN
6691   case ARM::VST4LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VST4LNd8_UPD;
6692   case ARM::VST4LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VST4LNd16_UPD;
6693   case ARM::VST4LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VST4LNd32_UPD;
6694   case ARM::VST4LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VST4LNq16_UPD;
6695   case ARM::VST4LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VST4LNq32_UPD;
6696   case ARM::VST4LNdWB_register_Asm_8:  Spacing = 1; return ARM::VST4LNd8_UPD;
6697   case ARM::VST4LNdWB_register_Asm_16: Spacing = 1; return ARM::VST4LNd16_UPD;
6698   case ARM::VST4LNdWB_register_Asm_32: Spacing = 1; return ARM::VST4LNd32_UPD;
6699   case ARM::VST4LNqWB_register_Asm_16: Spacing = 2; return ARM::VST4LNq16_UPD;
6700   case ARM::VST4LNqWB_register_Asm_32: Spacing = 2; return ARM::VST4LNq32_UPD;
6701   case ARM::VST4LNdAsm_8:  Spacing = 1; return ARM::VST4LNd8;
6702   case ARM::VST4LNdAsm_16: Spacing = 1; return ARM::VST4LNd16;
6703   case ARM::VST4LNdAsm_32: Spacing = 1; return ARM::VST4LNd32;
6704   case ARM::VST4LNqAsm_16: Spacing = 2; return ARM::VST4LNq16;
6705   case ARM::VST4LNqAsm_32: Spacing = 2; return ARM::VST4LNq32;
6706 
6707   // VST4
6708   case ARM::VST4dWB_fixed_Asm_8:  Spacing = 1; return ARM::VST4d8_UPD;
6709   case ARM::VST4dWB_fixed_Asm_16: Spacing = 1; return ARM::VST4d16_UPD;
6710   case ARM::VST4dWB_fixed_Asm_32: Spacing = 1; return ARM::VST4d32_UPD;
6711   case ARM::VST4qWB_fixed_Asm_8:  Spacing = 2; return ARM::VST4q8_UPD;
6712   case ARM::VST4qWB_fixed_Asm_16: Spacing = 2; return ARM::VST4q16_UPD;
6713   case ARM::VST4qWB_fixed_Asm_32: Spacing = 2; return ARM::VST4q32_UPD;
6714   case ARM::VST4dWB_register_Asm_8:  Spacing = 1; return ARM::VST4d8_UPD;
6715   case ARM::VST4dWB_register_Asm_16: Spacing = 1; return ARM::VST4d16_UPD;
6716   case ARM::VST4dWB_register_Asm_32: Spacing = 1; return ARM::VST4d32_UPD;
6717   case ARM::VST4qWB_register_Asm_8:  Spacing = 2; return ARM::VST4q8_UPD;
6718   case ARM::VST4qWB_register_Asm_16: Spacing = 2; return ARM::VST4q16_UPD;
6719   case ARM::VST4qWB_register_Asm_32: Spacing = 2; return ARM::VST4q32_UPD;
6720   case ARM::VST4dAsm_8:  Spacing = 1; return ARM::VST4d8;
6721   case ARM::VST4dAsm_16: Spacing = 1; return ARM::VST4d16;
6722   case ARM::VST4dAsm_32: Spacing = 1; return ARM::VST4d32;
6723   case ARM::VST4qAsm_8:  Spacing = 2; return ARM::VST4q8;
6724   case ARM::VST4qAsm_16: Spacing = 2; return ARM::VST4q16;
6725   case ARM::VST4qAsm_32: Spacing = 2; return ARM::VST4q32;
6726   }
6727 }
6728 
6729 static unsigned getRealVLDOpcode(unsigned Opc, unsigned &Spacing) {
6730   switch(Opc) {
6731   default: llvm_unreachable("unexpected opcode!");
6732   // VLD1LN
6733   case ARM::VLD1LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD1LNd8_UPD;
6734   case ARM::VLD1LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD1LNd16_UPD;
6735   case ARM::VLD1LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD1LNd32_UPD;
6736   case ARM::VLD1LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD1LNd8_UPD;
6737   case ARM::VLD1LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD1LNd16_UPD;
6738   case ARM::VLD1LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD1LNd32_UPD;
6739   case ARM::VLD1LNdAsm_8:  Spacing = 1; return ARM::VLD1LNd8;
6740   case ARM::VLD1LNdAsm_16: Spacing = 1; return ARM::VLD1LNd16;
6741   case ARM::VLD1LNdAsm_32: Spacing = 1; return ARM::VLD1LNd32;
6742 
6743   // VLD2LN
6744   case ARM::VLD2LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD2LNd8_UPD;
6745   case ARM::VLD2LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD2LNd16_UPD;
6746   case ARM::VLD2LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD2LNd32_UPD;
6747   case ARM::VLD2LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD2LNq16_UPD;
6748   case ARM::VLD2LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD2LNq32_UPD;
6749   case ARM::VLD2LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD2LNd8_UPD;
6750   case ARM::VLD2LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD2LNd16_UPD;
6751   case ARM::VLD2LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD2LNd32_UPD;
6752   case ARM::VLD2LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD2LNq16_UPD;
6753   case ARM::VLD2LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD2LNq32_UPD;
6754   case ARM::VLD2LNdAsm_8:  Spacing = 1; return ARM::VLD2LNd8;
6755   case ARM::VLD2LNdAsm_16: Spacing = 1; return ARM::VLD2LNd16;
6756   case ARM::VLD2LNdAsm_32: Spacing = 1; return ARM::VLD2LNd32;
6757   case ARM::VLD2LNqAsm_16: Spacing = 2; return ARM::VLD2LNq16;
6758   case ARM::VLD2LNqAsm_32: Spacing = 2; return ARM::VLD2LNq32;
6759 
6760   // VLD3DUP
6761   case ARM::VLD3DUPdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3DUPd8_UPD;
6762   case ARM::VLD3DUPdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3DUPd16_UPD;
6763   case ARM::VLD3DUPdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3DUPd32_UPD;
6764   case ARM::VLD3DUPqWB_fixed_Asm_8: Spacing = 1; return ARM::VLD3DUPq8_UPD;
6765   case ARM::VLD3DUPqWB_fixed_Asm_16: Spacing = 2; return ARM::VLD3DUPq16_UPD;
6766   case ARM::VLD3DUPqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3DUPq32_UPD;
6767   case ARM::VLD3DUPdWB_register_Asm_8:  Spacing = 1; return ARM::VLD3DUPd8_UPD;
6768   case ARM::VLD3DUPdWB_register_Asm_16: Spacing = 1; return ARM::VLD3DUPd16_UPD;
6769   case ARM::VLD3DUPdWB_register_Asm_32: Spacing = 1; return ARM::VLD3DUPd32_UPD;
6770   case ARM::VLD3DUPqWB_register_Asm_8: Spacing = 2; return ARM::VLD3DUPq8_UPD;
6771   case ARM::VLD3DUPqWB_register_Asm_16: Spacing = 2; return ARM::VLD3DUPq16_UPD;
6772   case ARM::VLD3DUPqWB_register_Asm_32: Spacing = 2; return ARM::VLD3DUPq32_UPD;
6773   case ARM::VLD3DUPdAsm_8:  Spacing = 1; return ARM::VLD3DUPd8;
6774   case ARM::VLD3DUPdAsm_16: Spacing = 1; return ARM::VLD3DUPd16;
6775   case ARM::VLD3DUPdAsm_32: Spacing = 1; return ARM::VLD3DUPd32;
6776   case ARM::VLD3DUPqAsm_8: Spacing = 2; return ARM::VLD3DUPq8;
6777   case ARM::VLD3DUPqAsm_16: Spacing = 2; return ARM::VLD3DUPq16;
6778   case ARM::VLD3DUPqAsm_32: Spacing = 2; return ARM::VLD3DUPq32;
6779 
6780   // VLD3LN
6781   case ARM::VLD3LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3LNd8_UPD;
6782   case ARM::VLD3LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3LNd16_UPD;
6783   case ARM::VLD3LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3LNd32_UPD;
6784   case ARM::VLD3LNqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3LNq16_UPD;
6785   case ARM::VLD3LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3LNq32_UPD;
6786   case ARM::VLD3LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD3LNd8_UPD;
6787   case ARM::VLD3LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD3LNd16_UPD;
6788   case ARM::VLD3LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD3LNd32_UPD;
6789   case ARM::VLD3LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD3LNq16_UPD;
6790   case ARM::VLD3LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD3LNq32_UPD;
6791   case ARM::VLD3LNdAsm_8:  Spacing = 1; return ARM::VLD3LNd8;
6792   case ARM::VLD3LNdAsm_16: Spacing = 1; return ARM::VLD3LNd16;
6793   case ARM::VLD3LNdAsm_32: Spacing = 1; return ARM::VLD3LNd32;
6794   case ARM::VLD3LNqAsm_16: Spacing = 2; return ARM::VLD3LNq16;
6795   case ARM::VLD3LNqAsm_32: Spacing = 2; return ARM::VLD3LNq32;
6796 
6797   // VLD3
6798   case ARM::VLD3dWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD3d8_UPD;
6799   case ARM::VLD3dWB_fixed_Asm_16: Spacing = 1; return ARM::VLD3d16_UPD;
6800   case ARM::VLD3dWB_fixed_Asm_32: Spacing = 1; return ARM::VLD3d32_UPD;
6801   case ARM::VLD3qWB_fixed_Asm_8:  Spacing = 2; return ARM::VLD3q8_UPD;
6802   case ARM::VLD3qWB_fixed_Asm_16: Spacing = 2; return ARM::VLD3q16_UPD;
6803   case ARM::VLD3qWB_fixed_Asm_32: Spacing = 2; return ARM::VLD3q32_UPD;
6804   case ARM::VLD3dWB_register_Asm_8:  Spacing = 1; return ARM::VLD3d8_UPD;
6805   case ARM::VLD3dWB_register_Asm_16: Spacing = 1; return ARM::VLD3d16_UPD;
6806   case ARM::VLD3dWB_register_Asm_32: Spacing = 1; return ARM::VLD3d32_UPD;
6807   case ARM::VLD3qWB_register_Asm_8:  Spacing = 2; return ARM::VLD3q8_UPD;
6808   case ARM::VLD3qWB_register_Asm_16: Spacing = 2; return ARM::VLD3q16_UPD;
6809   case ARM::VLD3qWB_register_Asm_32: Spacing = 2; return ARM::VLD3q32_UPD;
6810   case ARM::VLD3dAsm_8:  Spacing = 1; return ARM::VLD3d8;
6811   case ARM::VLD3dAsm_16: Spacing = 1; return ARM::VLD3d16;
6812   case ARM::VLD3dAsm_32: Spacing = 1; return ARM::VLD3d32;
6813   case ARM::VLD3qAsm_8:  Spacing = 2; return ARM::VLD3q8;
6814   case ARM::VLD3qAsm_16: Spacing = 2; return ARM::VLD3q16;
6815   case ARM::VLD3qAsm_32: Spacing = 2; return ARM::VLD3q32;
6816 
6817   // VLD4LN
6818   case ARM::VLD4LNdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4LNd8_UPD;
6819   case ARM::VLD4LNdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4LNd16_UPD;
6820   case ARM::VLD4LNdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4LNd32_UPD;
6821   case ARM::VLD4LNqWB_fixed_Asm_16: Spacing = 2; return ARM::VLD4LNq16_UPD;
6822   case ARM::VLD4LNqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4LNq32_UPD;
6823   case ARM::VLD4LNdWB_register_Asm_8:  Spacing = 1; return ARM::VLD4LNd8_UPD;
6824   case ARM::VLD4LNdWB_register_Asm_16: Spacing = 1; return ARM::VLD4LNd16_UPD;
6825   case ARM::VLD4LNdWB_register_Asm_32: Spacing = 1; return ARM::VLD4LNd32_UPD;
6826   case ARM::VLD4LNqWB_register_Asm_16: Spacing = 2; return ARM::VLD4LNq16_UPD;
6827   case ARM::VLD4LNqWB_register_Asm_32: Spacing = 2; return ARM::VLD4LNq32_UPD;
6828   case ARM::VLD4LNdAsm_8:  Spacing = 1; return ARM::VLD4LNd8;
6829   case ARM::VLD4LNdAsm_16: Spacing = 1; return ARM::VLD4LNd16;
6830   case ARM::VLD4LNdAsm_32: Spacing = 1; return ARM::VLD4LNd32;
6831   case ARM::VLD4LNqAsm_16: Spacing = 2; return ARM::VLD4LNq16;
6832   case ARM::VLD4LNqAsm_32: Spacing = 2; return ARM::VLD4LNq32;
6833 
6834   // VLD4DUP
6835   case ARM::VLD4DUPdWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4DUPd8_UPD;
6836   case ARM::VLD4DUPdWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4DUPd16_UPD;
6837   case ARM::VLD4DUPdWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4DUPd32_UPD;
6838   case ARM::VLD4DUPqWB_fixed_Asm_8: Spacing = 1; return ARM::VLD4DUPq8_UPD;
6839   case ARM::VLD4DUPqWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4DUPq16_UPD;
6840   case ARM::VLD4DUPqWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4DUPq32_UPD;
6841   case ARM::VLD4DUPdWB_register_Asm_8:  Spacing = 1; return ARM::VLD4DUPd8_UPD;
6842   case ARM::VLD4DUPdWB_register_Asm_16: Spacing = 1; return ARM::VLD4DUPd16_UPD;
6843   case ARM::VLD4DUPdWB_register_Asm_32: Spacing = 1; return ARM::VLD4DUPd32_UPD;
6844   case ARM::VLD4DUPqWB_register_Asm_8: Spacing = 2; return ARM::VLD4DUPq8_UPD;
6845   case ARM::VLD4DUPqWB_register_Asm_16: Spacing = 2; return ARM::VLD4DUPq16_UPD;
6846   case ARM::VLD4DUPqWB_register_Asm_32: Spacing = 2; return ARM::VLD4DUPq32_UPD;
6847   case ARM::VLD4DUPdAsm_8:  Spacing = 1; return ARM::VLD4DUPd8;
6848   case ARM::VLD4DUPdAsm_16: Spacing = 1; return ARM::VLD4DUPd16;
6849   case ARM::VLD4DUPdAsm_32: Spacing = 1; return ARM::VLD4DUPd32;
6850   case ARM::VLD4DUPqAsm_8: Spacing = 2; return ARM::VLD4DUPq8;
6851   case ARM::VLD4DUPqAsm_16: Spacing = 2; return ARM::VLD4DUPq16;
6852   case ARM::VLD4DUPqAsm_32: Spacing = 2; return ARM::VLD4DUPq32;
6853 
6854   // VLD4
6855   case ARM::VLD4dWB_fixed_Asm_8:  Spacing = 1; return ARM::VLD4d8_UPD;
6856   case ARM::VLD4dWB_fixed_Asm_16: Spacing = 1; return ARM::VLD4d16_UPD;
6857   case ARM::VLD4dWB_fixed_Asm_32: Spacing = 1; return ARM::VLD4d32_UPD;
6858   case ARM::VLD4qWB_fixed_Asm_8:  Spacing = 2; return ARM::VLD4q8_UPD;
6859   case ARM::VLD4qWB_fixed_Asm_16: Spacing = 2; return ARM::VLD4q16_UPD;
6860   case ARM::VLD4qWB_fixed_Asm_32: Spacing = 2; return ARM::VLD4q32_UPD;
6861   case ARM::VLD4dWB_register_Asm_8:  Spacing = 1; return ARM::VLD4d8_UPD;
6862   case ARM::VLD4dWB_register_Asm_16: Spacing = 1; return ARM::VLD4d16_UPD;
6863   case ARM::VLD4dWB_register_Asm_32: Spacing = 1; return ARM::VLD4d32_UPD;
6864   case ARM::VLD4qWB_register_Asm_8:  Spacing = 2; return ARM::VLD4q8_UPD;
6865   case ARM::VLD4qWB_register_Asm_16: Spacing = 2; return ARM::VLD4q16_UPD;
6866   case ARM::VLD4qWB_register_Asm_32: Spacing = 2; return ARM::VLD4q32_UPD;
6867   case ARM::VLD4dAsm_8:  Spacing = 1; return ARM::VLD4d8;
6868   case ARM::VLD4dAsm_16: Spacing = 1; return ARM::VLD4d16;
6869   case ARM::VLD4dAsm_32: Spacing = 1; return ARM::VLD4d32;
6870   case ARM::VLD4qAsm_8:  Spacing = 2; return ARM::VLD4q8;
6871   case ARM::VLD4qAsm_16: Spacing = 2; return ARM::VLD4q16;
6872   case ARM::VLD4qAsm_32: Spacing = 2; return ARM::VLD4q32;
6873   }
6874 }
6875 
6876 bool ARMAsmParser::processInstruction(MCInst &Inst,
6877                                       const OperandVector &Operands,
6878                                       MCStreamer &Out) {
6879   // Check if we have the wide qualifier, because if it's present we
6880   // must avoid selecting a 16-bit thumb instruction.
6881   bool HasWideQualifier = false;
6882   for (auto &Op : Operands) {
6883     ARMOperand &ARMOp = static_cast<ARMOperand&>(*Op);
6884     if (ARMOp.isToken() && ARMOp.getToken() == ".w") {
6885       HasWideQualifier = true;
6886       break;
6887     }
6888   }
6889 
6890   switch (Inst.getOpcode()) {
6891   // Alias for alternate form of 'ldr{,b}t Rt, [Rn], #imm' instruction.
6892   case ARM::LDRT_POST:
6893   case ARM::LDRBT_POST: {
6894     const unsigned Opcode =
6895       (Inst.getOpcode() == ARM::LDRT_POST) ? ARM::LDRT_POST_IMM
6896                                            : ARM::LDRBT_POST_IMM;
6897     MCInst TmpInst;
6898     TmpInst.setOpcode(Opcode);
6899     TmpInst.addOperand(Inst.getOperand(0));
6900     TmpInst.addOperand(Inst.getOperand(1));
6901     TmpInst.addOperand(Inst.getOperand(1));
6902     TmpInst.addOperand(MCOperand::createReg(0));
6903     TmpInst.addOperand(MCOperand::createImm(0));
6904     TmpInst.addOperand(Inst.getOperand(2));
6905     TmpInst.addOperand(Inst.getOperand(3));
6906     Inst = TmpInst;
6907     return true;
6908   }
6909   // Alias for alternate form of 'str{,b}t Rt, [Rn], #imm' instruction.
6910   case ARM::STRT_POST:
6911   case ARM::STRBT_POST: {
6912     const unsigned Opcode =
6913       (Inst.getOpcode() == ARM::STRT_POST) ? ARM::STRT_POST_IMM
6914                                            : ARM::STRBT_POST_IMM;
6915     MCInst TmpInst;
6916     TmpInst.setOpcode(Opcode);
6917     TmpInst.addOperand(Inst.getOperand(1));
6918     TmpInst.addOperand(Inst.getOperand(0));
6919     TmpInst.addOperand(Inst.getOperand(1));
6920     TmpInst.addOperand(MCOperand::createReg(0));
6921     TmpInst.addOperand(MCOperand::createImm(0));
6922     TmpInst.addOperand(Inst.getOperand(2));
6923     TmpInst.addOperand(Inst.getOperand(3));
6924     Inst = TmpInst;
6925     return true;
6926   }
6927   // Alias for alternate form of 'ADR Rd, #imm' instruction.
6928   case ARM::ADDri: {
6929     if (Inst.getOperand(1).getReg() != ARM::PC ||
6930         Inst.getOperand(5).getReg() != 0 ||
6931         !(Inst.getOperand(2).isExpr() || Inst.getOperand(2).isImm()))
6932       return false;
6933     MCInst TmpInst;
6934     TmpInst.setOpcode(ARM::ADR);
6935     TmpInst.addOperand(Inst.getOperand(0));
6936     if (Inst.getOperand(2).isImm()) {
6937       // Immediate (mod_imm) will be in its encoded form, we must unencode it
6938       // before passing it to the ADR instruction.
6939       unsigned Enc = Inst.getOperand(2).getImm();
6940       TmpInst.addOperand(MCOperand::createImm(
6941         ARM_AM::rotr32(Enc & 0xFF, (Enc & 0xF00) >> 7)));
6942     } else {
6943       // Turn PC-relative expression into absolute expression.
6944       // Reading PC provides the start of the current instruction + 8 and
6945       // the transform to adr is biased by that.
6946       MCSymbol *Dot = getContext().createTempSymbol();
6947       Out.EmitLabel(Dot);
6948       const MCExpr *OpExpr = Inst.getOperand(2).getExpr();
6949       const MCExpr *InstPC = MCSymbolRefExpr::create(Dot,
6950                                                      MCSymbolRefExpr::VK_None,
6951                                                      getContext());
6952       const MCExpr *Const8 = MCConstantExpr::create(8, getContext());
6953       const MCExpr *ReadPC = MCBinaryExpr::createAdd(InstPC, Const8,
6954                                                      getContext());
6955       const MCExpr *FixupAddr = MCBinaryExpr::createAdd(ReadPC, OpExpr,
6956                                                         getContext());
6957       TmpInst.addOperand(MCOperand::createExpr(FixupAddr));
6958     }
6959     TmpInst.addOperand(Inst.getOperand(3));
6960     TmpInst.addOperand(Inst.getOperand(4));
6961     Inst = TmpInst;
6962     return true;
6963   }
6964   // Aliases for alternate PC+imm syntax of LDR instructions.
6965   case ARM::t2LDRpcrel:
6966     // Select the narrow version if the immediate will fit.
6967     if (Inst.getOperand(1).getImm() > 0 &&
6968         Inst.getOperand(1).getImm() <= 0xff &&
6969         !HasWideQualifier)
6970       Inst.setOpcode(ARM::tLDRpci);
6971     else
6972       Inst.setOpcode(ARM::t2LDRpci);
6973     return true;
6974   case ARM::t2LDRBpcrel:
6975     Inst.setOpcode(ARM::t2LDRBpci);
6976     return true;
6977   case ARM::t2LDRHpcrel:
6978     Inst.setOpcode(ARM::t2LDRHpci);
6979     return true;
6980   case ARM::t2LDRSBpcrel:
6981     Inst.setOpcode(ARM::t2LDRSBpci);
6982     return true;
6983   case ARM::t2LDRSHpcrel:
6984     Inst.setOpcode(ARM::t2LDRSHpci);
6985     return true;
6986   case ARM::LDRConstPool:
6987   case ARM::tLDRConstPool:
6988   case ARM::t2LDRConstPool: {
6989     // Pseudo instruction ldr rt, =immediate is converted to a
6990     // MOV rt, immediate if immediate is known and representable
6991     // otherwise we create a constant pool entry that we load from.
6992     MCInst TmpInst;
6993     if (Inst.getOpcode() == ARM::LDRConstPool)
6994       TmpInst.setOpcode(ARM::LDRi12);
6995     else if (Inst.getOpcode() == ARM::tLDRConstPool)
6996       TmpInst.setOpcode(ARM::tLDRpci);
6997     else if (Inst.getOpcode() == ARM::t2LDRConstPool)
6998       TmpInst.setOpcode(ARM::t2LDRpci);
6999     const ARMOperand &PoolOperand =
7000       (HasWideQualifier ?
7001        static_cast<ARMOperand &>(*Operands[4]) :
7002        static_cast<ARMOperand &>(*Operands[3]));
7003     const MCExpr *SubExprVal = PoolOperand.getConstantPoolImm();
7004     // If SubExprVal is a constant we may be able to use a MOV
7005     if (isa<MCConstantExpr>(SubExprVal) &&
7006         Inst.getOperand(0).getReg() != ARM::PC &&
7007         Inst.getOperand(0).getReg() != ARM::SP) {
7008       int64_t Value =
7009         (int64_t) (cast<MCConstantExpr>(SubExprVal))->getValue();
7010       bool UseMov  = true;
7011       bool MovHasS = true;
7012       if (Inst.getOpcode() == ARM::LDRConstPool) {
7013         // ARM Constant
7014         if (ARM_AM::getSOImmVal(Value) != -1) {
7015           Value = ARM_AM::getSOImmVal(Value);
7016           TmpInst.setOpcode(ARM::MOVi);
7017         }
7018         else if (ARM_AM::getSOImmVal(~Value) != -1) {
7019           Value = ARM_AM::getSOImmVal(~Value);
7020           TmpInst.setOpcode(ARM::MVNi);
7021         }
7022         else if (hasV6T2Ops() &&
7023                  Value >=0 && Value < 65536) {
7024           TmpInst.setOpcode(ARM::MOVi16);
7025           MovHasS = false;
7026         }
7027         else
7028           UseMov = false;
7029       }
7030       else {
7031         // Thumb/Thumb2 Constant
7032         if (hasThumb2() &&
7033             ARM_AM::getT2SOImmVal(Value) != -1)
7034           TmpInst.setOpcode(ARM::t2MOVi);
7035         else if (hasThumb2() &&
7036                  ARM_AM::getT2SOImmVal(~Value) != -1) {
7037           TmpInst.setOpcode(ARM::t2MVNi);
7038           Value = ~Value;
7039         }
7040         else if (hasV8MBaseline() &&
7041                  Value >=0 && Value < 65536) {
7042           TmpInst.setOpcode(ARM::t2MOVi16);
7043           MovHasS = false;
7044         }
7045         else
7046           UseMov = false;
7047       }
7048       if (UseMov) {
7049         TmpInst.addOperand(Inst.getOperand(0));           // Rt
7050         TmpInst.addOperand(MCOperand::createImm(Value));  // Immediate
7051         TmpInst.addOperand(Inst.getOperand(2));           // CondCode
7052         TmpInst.addOperand(Inst.getOperand(3));           // CondCode
7053         if (MovHasS)
7054           TmpInst.addOperand(MCOperand::createReg(0));    // S
7055         Inst = TmpInst;
7056         return true;
7057       }
7058     }
7059     // No opportunity to use MOV/MVN create constant pool
7060     const MCExpr *CPLoc =
7061       getTargetStreamer().addConstantPoolEntry(SubExprVal,
7062                                                PoolOperand.getStartLoc());
7063     TmpInst.addOperand(Inst.getOperand(0));           // Rt
7064     TmpInst.addOperand(MCOperand::createExpr(CPLoc)); // offset to constpool
7065     if (TmpInst.getOpcode() == ARM::LDRi12)
7066       TmpInst.addOperand(MCOperand::createImm(0));    // unused offset
7067     TmpInst.addOperand(Inst.getOperand(2));           // CondCode
7068     TmpInst.addOperand(Inst.getOperand(3));           // CondCode
7069     Inst = TmpInst;
7070     return true;
7071   }
7072   // Handle NEON VST complex aliases.
7073   case ARM::VST1LNdWB_register_Asm_8:
7074   case ARM::VST1LNdWB_register_Asm_16:
7075   case ARM::VST1LNdWB_register_Asm_32: {
7076     MCInst TmpInst;
7077     // Shuffle the operands around so the lane index operand is in the
7078     // right place.
7079     unsigned Spacing;
7080     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7081     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7082     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7083     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7084     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7085     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7086     TmpInst.addOperand(Inst.getOperand(1)); // lane
7087     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7088     TmpInst.addOperand(Inst.getOperand(6));
7089     Inst = TmpInst;
7090     return true;
7091   }
7092 
7093   case ARM::VST2LNdWB_register_Asm_8:
7094   case ARM::VST2LNdWB_register_Asm_16:
7095   case ARM::VST2LNdWB_register_Asm_32:
7096   case ARM::VST2LNqWB_register_Asm_16:
7097   case ARM::VST2LNqWB_register_Asm_32: {
7098     MCInst TmpInst;
7099     // Shuffle the operands around so the lane index operand is in the
7100     // right place.
7101     unsigned Spacing;
7102     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7103     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7104     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7105     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7106     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7107     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7108     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7109                                             Spacing));
7110     TmpInst.addOperand(Inst.getOperand(1)); // lane
7111     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7112     TmpInst.addOperand(Inst.getOperand(6));
7113     Inst = TmpInst;
7114     return true;
7115   }
7116 
7117   case ARM::VST3LNdWB_register_Asm_8:
7118   case ARM::VST3LNdWB_register_Asm_16:
7119   case ARM::VST3LNdWB_register_Asm_32:
7120   case ARM::VST3LNqWB_register_Asm_16:
7121   case ARM::VST3LNqWB_register_Asm_32: {
7122     MCInst TmpInst;
7123     // Shuffle the operands around so the lane index operand is in the
7124     // right place.
7125     unsigned Spacing;
7126     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7127     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7128     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7129     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7130     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7131     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7132     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7133                                             Spacing));
7134     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7135                                             Spacing * 2));
7136     TmpInst.addOperand(Inst.getOperand(1)); // lane
7137     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7138     TmpInst.addOperand(Inst.getOperand(6));
7139     Inst = TmpInst;
7140     return true;
7141   }
7142 
7143   case ARM::VST4LNdWB_register_Asm_8:
7144   case ARM::VST4LNdWB_register_Asm_16:
7145   case ARM::VST4LNdWB_register_Asm_32:
7146   case ARM::VST4LNqWB_register_Asm_16:
7147   case ARM::VST4LNqWB_register_Asm_32: {
7148     MCInst TmpInst;
7149     // Shuffle the operands around so the lane index operand is in the
7150     // right place.
7151     unsigned Spacing;
7152     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7153     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7154     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7155     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7156     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7157     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7158     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7159                                             Spacing));
7160     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7161                                             Spacing * 2));
7162     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7163                                             Spacing * 3));
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::VST1LNdWB_fixed_Asm_8:
7172   case ARM::VST1LNdWB_fixed_Asm_16:
7173   case ARM::VST1LNdWB_fixed_Asm_32: {
7174     MCInst TmpInst;
7175     // Shuffle the operands around so the lane index operand is in the
7176     // right place.
7177     unsigned Spacing;
7178     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7179     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7180     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7181     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7182     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7183     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7184     TmpInst.addOperand(Inst.getOperand(1)); // lane
7185     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7186     TmpInst.addOperand(Inst.getOperand(5));
7187     Inst = TmpInst;
7188     return true;
7189   }
7190 
7191   case ARM::VST2LNdWB_fixed_Asm_8:
7192   case ARM::VST2LNdWB_fixed_Asm_16:
7193   case ARM::VST2LNdWB_fixed_Asm_32:
7194   case ARM::VST2LNqWB_fixed_Asm_16:
7195   case ARM::VST2LNqWB_fixed_Asm_32: {
7196     MCInst TmpInst;
7197     // Shuffle the operands around so the lane index operand is in the
7198     // right place.
7199     unsigned Spacing;
7200     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7201     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7202     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7203     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7204     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7205     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7206     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7207                                             Spacing));
7208     TmpInst.addOperand(Inst.getOperand(1)); // lane
7209     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7210     TmpInst.addOperand(Inst.getOperand(5));
7211     Inst = TmpInst;
7212     return true;
7213   }
7214 
7215   case ARM::VST3LNdWB_fixed_Asm_8:
7216   case ARM::VST3LNdWB_fixed_Asm_16:
7217   case ARM::VST3LNdWB_fixed_Asm_32:
7218   case ARM::VST3LNqWB_fixed_Asm_16:
7219   case ARM::VST3LNqWB_fixed_Asm_32: {
7220     MCInst TmpInst;
7221     // Shuffle the operands around so the lane index operand is in the
7222     // right place.
7223     unsigned Spacing;
7224     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7225     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7226     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7227     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7228     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7229     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7230     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7231                                             Spacing));
7232     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7233                                             Spacing * 2));
7234     TmpInst.addOperand(Inst.getOperand(1)); // lane
7235     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7236     TmpInst.addOperand(Inst.getOperand(5));
7237     Inst = TmpInst;
7238     return true;
7239   }
7240 
7241   case ARM::VST4LNdWB_fixed_Asm_8:
7242   case ARM::VST4LNdWB_fixed_Asm_16:
7243   case ARM::VST4LNdWB_fixed_Asm_32:
7244   case ARM::VST4LNqWB_fixed_Asm_16:
7245   case ARM::VST4LNqWB_fixed_Asm_32: {
7246     MCInst TmpInst;
7247     // Shuffle the operands around so the lane index operand is in the
7248     // right place.
7249     unsigned Spacing;
7250     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7251     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7252     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7253     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7254     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7255     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7256     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7257                                             Spacing));
7258     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7259                                             Spacing * 2));
7260     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7261                                             Spacing * 3));
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::VST1LNdAsm_8:
7270   case ARM::VST1LNdAsm_16:
7271   case ARM::VST1LNdAsm_32: {
7272     MCInst TmpInst;
7273     // Shuffle the operands around so the lane index operand is in the
7274     // right place.
7275     unsigned Spacing;
7276     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7277     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7278     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7279     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7280     TmpInst.addOperand(Inst.getOperand(1)); // lane
7281     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7282     TmpInst.addOperand(Inst.getOperand(5));
7283     Inst = TmpInst;
7284     return true;
7285   }
7286 
7287   case ARM::VST2LNdAsm_8:
7288   case ARM::VST2LNdAsm_16:
7289   case ARM::VST2LNdAsm_32:
7290   case ARM::VST2LNqAsm_16:
7291   case ARM::VST2LNqAsm_32: {
7292     MCInst TmpInst;
7293     // Shuffle the operands around so the lane index operand is in the
7294     // right place.
7295     unsigned Spacing;
7296     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7297     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7298     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7299     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7300     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7301                                             Spacing));
7302     TmpInst.addOperand(Inst.getOperand(1)); // lane
7303     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7304     TmpInst.addOperand(Inst.getOperand(5));
7305     Inst = TmpInst;
7306     return true;
7307   }
7308 
7309   case ARM::VST3LNdAsm_8:
7310   case ARM::VST3LNdAsm_16:
7311   case ARM::VST3LNdAsm_32:
7312   case ARM::VST3LNqAsm_16:
7313   case ARM::VST3LNqAsm_32: {
7314     MCInst TmpInst;
7315     // Shuffle the operands around so the lane index operand is in the
7316     // right place.
7317     unsigned Spacing;
7318     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7319     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7320     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7321     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7322     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7323                                             Spacing));
7324     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7325                                             Spacing * 2));
7326     TmpInst.addOperand(Inst.getOperand(1)); // lane
7327     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7328     TmpInst.addOperand(Inst.getOperand(5));
7329     Inst = TmpInst;
7330     return true;
7331   }
7332 
7333   case ARM::VST4LNdAsm_8:
7334   case ARM::VST4LNdAsm_16:
7335   case ARM::VST4LNdAsm_32:
7336   case ARM::VST4LNqAsm_16:
7337   case ARM::VST4LNqAsm_32: {
7338     MCInst TmpInst;
7339     // Shuffle the operands around so the lane index operand is in the
7340     // right place.
7341     unsigned Spacing;
7342     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
7343     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7344     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7345     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7346     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7347                                             Spacing));
7348     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7349                                             Spacing * 2));
7350     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7351                                             Spacing * 3));
7352     TmpInst.addOperand(Inst.getOperand(1)); // lane
7353     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7354     TmpInst.addOperand(Inst.getOperand(5));
7355     Inst = TmpInst;
7356     return true;
7357   }
7358 
7359   // Handle NEON VLD complex aliases.
7360   case ARM::VLD1LNdWB_register_Asm_8:
7361   case ARM::VLD1LNdWB_register_Asm_16:
7362   case ARM::VLD1LNdWB_register_Asm_32: {
7363     MCInst TmpInst;
7364     // Shuffle the operands around so the lane index operand is in the
7365     // right place.
7366     unsigned Spacing;
7367     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7368     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7369     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7370     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7371     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7372     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7373     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7374     TmpInst.addOperand(Inst.getOperand(1)); // lane
7375     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7376     TmpInst.addOperand(Inst.getOperand(6));
7377     Inst = TmpInst;
7378     return true;
7379   }
7380 
7381   case ARM::VLD2LNdWB_register_Asm_8:
7382   case ARM::VLD2LNdWB_register_Asm_16:
7383   case ARM::VLD2LNdWB_register_Asm_32:
7384   case ARM::VLD2LNqWB_register_Asm_16:
7385   case ARM::VLD2LNqWB_register_Asm_32: {
7386     MCInst TmpInst;
7387     // Shuffle the operands around so the lane index operand is in the
7388     // right place.
7389     unsigned Spacing;
7390     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7391     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7392     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7393                                             Spacing));
7394     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7395     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7396     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7397     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7398     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7399     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7400                                             Spacing));
7401     TmpInst.addOperand(Inst.getOperand(1)); // lane
7402     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7403     TmpInst.addOperand(Inst.getOperand(6));
7404     Inst = TmpInst;
7405     return true;
7406   }
7407 
7408   case ARM::VLD3LNdWB_register_Asm_8:
7409   case ARM::VLD3LNdWB_register_Asm_16:
7410   case ARM::VLD3LNdWB_register_Asm_32:
7411   case ARM::VLD3LNqWB_register_Asm_16:
7412   case ARM::VLD3LNqWB_register_Asm_32: {
7413     MCInst TmpInst;
7414     // Shuffle the operands around so the lane index operand is in the
7415     // right place.
7416     unsigned Spacing;
7417     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7418     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7419     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7420                                             Spacing));
7421     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7422                                             Spacing * 2));
7423     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7424     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7425     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7426     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7427     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7428     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7429                                             Spacing));
7430     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7431                                             Spacing * 2));
7432     TmpInst.addOperand(Inst.getOperand(1)); // lane
7433     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7434     TmpInst.addOperand(Inst.getOperand(6));
7435     Inst = TmpInst;
7436     return true;
7437   }
7438 
7439   case ARM::VLD4LNdWB_register_Asm_8:
7440   case ARM::VLD4LNdWB_register_Asm_16:
7441   case ARM::VLD4LNdWB_register_Asm_32:
7442   case ARM::VLD4LNqWB_register_Asm_16:
7443   case ARM::VLD4LNqWB_register_Asm_32: {
7444     MCInst TmpInst;
7445     // Shuffle the operands around so the lane index operand is in the
7446     // right place.
7447     unsigned Spacing;
7448     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7449     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7450     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7451                                             Spacing));
7452     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7453                                             Spacing * 2));
7454     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7455                                             Spacing * 3));
7456     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7457     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7458     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7459     TmpInst.addOperand(Inst.getOperand(4)); // Rm
7460     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7461     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7462                                             Spacing));
7463     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7464                                             Spacing * 2));
7465     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7466                                             Spacing * 3));
7467     TmpInst.addOperand(Inst.getOperand(1)); // lane
7468     TmpInst.addOperand(Inst.getOperand(5)); // CondCode
7469     TmpInst.addOperand(Inst.getOperand(6));
7470     Inst = TmpInst;
7471     return true;
7472   }
7473 
7474   case ARM::VLD1LNdWB_fixed_Asm_8:
7475   case ARM::VLD1LNdWB_fixed_Asm_16:
7476   case ARM::VLD1LNdWB_fixed_Asm_32: {
7477     MCInst TmpInst;
7478     // Shuffle the operands around so the lane index operand is in the
7479     // right place.
7480     unsigned Spacing;
7481     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7482     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7483     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7484     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7485     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7486     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7487     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7488     TmpInst.addOperand(Inst.getOperand(1)); // lane
7489     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7490     TmpInst.addOperand(Inst.getOperand(5));
7491     Inst = TmpInst;
7492     return true;
7493   }
7494 
7495   case ARM::VLD2LNdWB_fixed_Asm_8:
7496   case ARM::VLD2LNdWB_fixed_Asm_16:
7497   case ARM::VLD2LNdWB_fixed_Asm_32:
7498   case ARM::VLD2LNqWB_fixed_Asm_16:
7499   case ARM::VLD2LNqWB_fixed_Asm_32: {
7500     MCInst TmpInst;
7501     // Shuffle the operands around so the lane index operand is in the
7502     // right place.
7503     unsigned Spacing;
7504     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7505     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7506     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7507                                             Spacing));
7508     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7509     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7510     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7511     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7512     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7513     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7514                                             Spacing));
7515     TmpInst.addOperand(Inst.getOperand(1)); // lane
7516     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7517     TmpInst.addOperand(Inst.getOperand(5));
7518     Inst = TmpInst;
7519     return true;
7520   }
7521 
7522   case ARM::VLD3LNdWB_fixed_Asm_8:
7523   case ARM::VLD3LNdWB_fixed_Asm_16:
7524   case ARM::VLD3LNdWB_fixed_Asm_32:
7525   case ARM::VLD3LNqWB_fixed_Asm_16:
7526   case ARM::VLD3LNqWB_fixed_Asm_32: {
7527     MCInst TmpInst;
7528     // Shuffle the operands around so the lane index operand is in the
7529     // right place.
7530     unsigned Spacing;
7531     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7532     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7533     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7534                                             Spacing));
7535     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7536                                             Spacing * 2));
7537     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7538     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7539     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7540     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7541     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7542     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7543                                             Spacing));
7544     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7545                                             Spacing * 2));
7546     TmpInst.addOperand(Inst.getOperand(1)); // lane
7547     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7548     TmpInst.addOperand(Inst.getOperand(5));
7549     Inst = TmpInst;
7550     return true;
7551   }
7552 
7553   case ARM::VLD4LNdWB_fixed_Asm_8:
7554   case ARM::VLD4LNdWB_fixed_Asm_16:
7555   case ARM::VLD4LNdWB_fixed_Asm_32:
7556   case ARM::VLD4LNqWB_fixed_Asm_16:
7557   case ARM::VLD4LNqWB_fixed_Asm_32: {
7558     MCInst TmpInst;
7559     // Shuffle the operands around so the lane index operand is in the
7560     // right place.
7561     unsigned Spacing;
7562     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7563     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7564     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7565                                             Spacing));
7566     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7567                                             Spacing * 2));
7568     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7569                                             Spacing * 3));
7570     TmpInst.addOperand(Inst.getOperand(2)); // Rn_wb
7571     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7572     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7573     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7574     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7575     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7576                                             Spacing));
7577     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7578                                             Spacing * 2));
7579     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7580                                             Spacing * 3));
7581     TmpInst.addOperand(Inst.getOperand(1)); // lane
7582     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7583     TmpInst.addOperand(Inst.getOperand(5));
7584     Inst = TmpInst;
7585     return true;
7586   }
7587 
7588   case ARM::VLD1LNdAsm_8:
7589   case ARM::VLD1LNdAsm_16:
7590   case ARM::VLD1LNdAsm_32: {
7591     MCInst TmpInst;
7592     // Shuffle the operands around so the lane index operand is in the
7593     // right place.
7594     unsigned Spacing;
7595     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7596     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7597     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7598     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7599     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7600     TmpInst.addOperand(Inst.getOperand(1)); // lane
7601     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7602     TmpInst.addOperand(Inst.getOperand(5));
7603     Inst = TmpInst;
7604     return true;
7605   }
7606 
7607   case ARM::VLD2LNdAsm_8:
7608   case ARM::VLD2LNdAsm_16:
7609   case ARM::VLD2LNdAsm_32:
7610   case ARM::VLD2LNqAsm_16:
7611   case ARM::VLD2LNqAsm_32: {
7612     MCInst TmpInst;
7613     // Shuffle the operands around so the lane index operand is in the
7614     // right place.
7615     unsigned Spacing;
7616     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7617     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7618     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7619                                             Spacing));
7620     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7621     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7622     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7623     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7624                                             Spacing));
7625     TmpInst.addOperand(Inst.getOperand(1)); // lane
7626     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7627     TmpInst.addOperand(Inst.getOperand(5));
7628     Inst = TmpInst;
7629     return true;
7630   }
7631 
7632   case ARM::VLD3LNdAsm_8:
7633   case ARM::VLD3LNdAsm_16:
7634   case ARM::VLD3LNdAsm_32:
7635   case ARM::VLD3LNqAsm_16:
7636   case ARM::VLD3LNqAsm_32: {
7637     MCInst TmpInst;
7638     // Shuffle the operands around so the lane index operand is in the
7639     // right place.
7640     unsigned Spacing;
7641     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7642     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7643     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7644                                             Spacing));
7645     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7646                                             Spacing * 2));
7647     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7648     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7649     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7650     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7651                                             Spacing));
7652     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7653                                             Spacing * 2));
7654     TmpInst.addOperand(Inst.getOperand(1)); // lane
7655     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7656     TmpInst.addOperand(Inst.getOperand(5));
7657     Inst = TmpInst;
7658     return true;
7659   }
7660 
7661   case ARM::VLD4LNdAsm_8:
7662   case ARM::VLD4LNdAsm_16:
7663   case ARM::VLD4LNdAsm_32:
7664   case ARM::VLD4LNqAsm_16:
7665   case ARM::VLD4LNqAsm_32: {
7666     MCInst TmpInst;
7667     // Shuffle the operands around so the lane index operand is in the
7668     // right place.
7669     unsigned Spacing;
7670     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7671     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7672     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7673                                             Spacing));
7674     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7675                                             Spacing * 2));
7676     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7677                                             Spacing * 3));
7678     TmpInst.addOperand(Inst.getOperand(2)); // Rn
7679     TmpInst.addOperand(Inst.getOperand(3)); // alignment
7680     TmpInst.addOperand(Inst.getOperand(0)); // Tied operand src (== Vd)
7681     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7682                                             Spacing));
7683     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7684                                             Spacing * 2));
7685     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7686                                             Spacing * 3));
7687     TmpInst.addOperand(Inst.getOperand(1)); // lane
7688     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7689     TmpInst.addOperand(Inst.getOperand(5));
7690     Inst = TmpInst;
7691     return true;
7692   }
7693 
7694   // VLD3DUP single 3-element structure to all lanes instructions.
7695   case ARM::VLD3DUPdAsm_8:
7696   case ARM::VLD3DUPdAsm_16:
7697   case ARM::VLD3DUPdAsm_32:
7698   case ARM::VLD3DUPqAsm_8:
7699   case ARM::VLD3DUPqAsm_16:
7700   case ARM::VLD3DUPqAsm_32: {
7701     MCInst TmpInst;
7702     unsigned Spacing;
7703     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7704     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7705     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7706                                             Spacing));
7707     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7708                                             Spacing * 2));
7709     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7710     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7711     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7712     TmpInst.addOperand(Inst.getOperand(4));
7713     Inst = TmpInst;
7714     return true;
7715   }
7716 
7717   case ARM::VLD3DUPdWB_fixed_Asm_8:
7718   case ARM::VLD3DUPdWB_fixed_Asm_16:
7719   case ARM::VLD3DUPdWB_fixed_Asm_32:
7720   case ARM::VLD3DUPqWB_fixed_Asm_8:
7721   case ARM::VLD3DUPqWB_fixed_Asm_16:
7722   case ARM::VLD3DUPqWB_fixed_Asm_32: {
7723     MCInst TmpInst;
7724     unsigned Spacing;
7725     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7726     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7727     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7728                                             Spacing));
7729     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7730                                             Spacing * 2));
7731     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7732     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7733     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7734     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7735     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7736     TmpInst.addOperand(Inst.getOperand(4));
7737     Inst = TmpInst;
7738     return true;
7739   }
7740 
7741   case ARM::VLD3DUPdWB_register_Asm_8:
7742   case ARM::VLD3DUPdWB_register_Asm_16:
7743   case ARM::VLD3DUPdWB_register_Asm_32:
7744   case ARM::VLD3DUPqWB_register_Asm_8:
7745   case ARM::VLD3DUPqWB_register_Asm_16:
7746   case ARM::VLD3DUPqWB_register_Asm_32: {
7747     MCInst TmpInst;
7748     unsigned Spacing;
7749     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7750     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7751     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7752                                             Spacing));
7753     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7754                                             Spacing * 2));
7755     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7756     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7757     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7758     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7759     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7760     TmpInst.addOperand(Inst.getOperand(5));
7761     Inst = TmpInst;
7762     return true;
7763   }
7764 
7765   // VLD3 multiple 3-element structure instructions.
7766   case ARM::VLD3dAsm_8:
7767   case ARM::VLD3dAsm_16:
7768   case ARM::VLD3dAsm_32:
7769   case ARM::VLD3qAsm_8:
7770   case ARM::VLD3qAsm_16:
7771   case ARM::VLD3qAsm_32: {
7772     MCInst TmpInst;
7773     unsigned Spacing;
7774     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7775     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7776     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7777                                             Spacing));
7778     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7779                                             Spacing * 2));
7780     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7781     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7782     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7783     TmpInst.addOperand(Inst.getOperand(4));
7784     Inst = TmpInst;
7785     return true;
7786   }
7787 
7788   case ARM::VLD3dWB_fixed_Asm_8:
7789   case ARM::VLD3dWB_fixed_Asm_16:
7790   case ARM::VLD3dWB_fixed_Asm_32:
7791   case ARM::VLD3qWB_fixed_Asm_8:
7792   case ARM::VLD3qWB_fixed_Asm_16:
7793   case ARM::VLD3qWB_fixed_Asm_32: {
7794     MCInst TmpInst;
7795     unsigned Spacing;
7796     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7797     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7798     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7799                                             Spacing));
7800     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7801                                             Spacing * 2));
7802     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7803     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7804     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7805     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7806     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7807     TmpInst.addOperand(Inst.getOperand(4));
7808     Inst = TmpInst;
7809     return true;
7810   }
7811 
7812   case ARM::VLD3dWB_register_Asm_8:
7813   case ARM::VLD3dWB_register_Asm_16:
7814   case ARM::VLD3dWB_register_Asm_32:
7815   case ARM::VLD3qWB_register_Asm_8:
7816   case ARM::VLD3qWB_register_Asm_16:
7817   case ARM::VLD3qWB_register_Asm_32: {
7818     MCInst TmpInst;
7819     unsigned Spacing;
7820     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7821     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7822     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7823                                             Spacing));
7824     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7825                                             Spacing * 2));
7826     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7827     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7828     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7829     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7830     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7831     TmpInst.addOperand(Inst.getOperand(5));
7832     Inst = TmpInst;
7833     return true;
7834   }
7835 
7836   // VLD4DUP single 3-element structure to all lanes instructions.
7837   case ARM::VLD4DUPdAsm_8:
7838   case ARM::VLD4DUPdAsm_16:
7839   case ARM::VLD4DUPdAsm_32:
7840   case ARM::VLD4DUPqAsm_8:
7841   case ARM::VLD4DUPqAsm_16:
7842   case ARM::VLD4DUPqAsm_32: {
7843     MCInst TmpInst;
7844     unsigned Spacing;
7845     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7846     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7847     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7848                                             Spacing));
7849     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7850                                             Spacing * 2));
7851     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7852                                             Spacing * 3));
7853     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7854     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7855     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7856     TmpInst.addOperand(Inst.getOperand(4));
7857     Inst = TmpInst;
7858     return true;
7859   }
7860 
7861   case ARM::VLD4DUPdWB_fixed_Asm_8:
7862   case ARM::VLD4DUPdWB_fixed_Asm_16:
7863   case ARM::VLD4DUPdWB_fixed_Asm_32:
7864   case ARM::VLD4DUPqWB_fixed_Asm_8:
7865   case ARM::VLD4DUPqWB_fixed_Asm_16:
7866   case ARM::VLD4DUPqWB_fixed_Asm_32: {
7867     MCInst TmpInst;
7868     unsigned Spacing;
7869     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7870     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7871     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7872                                             Spacing));
7873     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7874                                             Spacing * 2));
7875     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7876                                             Spacing * 3));
7877     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7878     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7879     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7880     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7881     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7882     TmpInst.addOperand(Inst.getOperand(4));
7883     Inst = TmpInst;
7884     return true;
7885   }
7886 
7887   case ARM::VLD4DUPdWB_register_Asm_8:
7888   case ARM::VLD4DUPdWB_register_Asm_16:
7889   case ARM::VLD4DUPdWB_register_Asm_32:
7890   case ARM::VLD4DUPqWB_register_Asm_8:
7891   case ARM::VLD4DUPqWB_register_Asm_16:
7892   case ARM::VLD4DUPqWB_register_Asm_32: {
7893     MCInst TmpInst;
7894     unsigned Spacing;
7895     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7896     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7897     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7898                                             Spacing));
7899     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7900                                             Spacing * 2));
7901     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7902                                             Spacing * 3));
7903     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7904     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7905     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7906     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7907     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7908     TmpInst.addOperand(Inst.getOperand(5));
7909     Inst = TmpInst;
7910     return true;
7911   }
7912 
7913   // VLD4 multiple 4-element structure instructions.
7914   case ARM::VLD4dAsm_8:
7915   case ARM::VLD4dAsm_16:
7916   case ARM::VLD4dAsm_32:
7917   case ARM::VLD4qAsm_8:
7918   case ARM::VLD4qAsm_16:
7919   case ARM::VLD4qAsm_32: {
7920     MCInst TmpInst;
7921     unsigned Spacing;
7922     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7923     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7924     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7925                                             Spacing));
7926     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7927                                             Spacing * 2));
7928     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7929                                             Spacing * 3));
7930     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7931     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7932     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7933     TmpInst.addOperand(Inst.getOperand(4));
7934     Inst = TmpInst;
7935     return true;
7936   }
7937 
7938   case ARM::VLD4dWB_fixed_Asm_8:
7939   case ARM::VLD4dWB_fixed_Asm_16:
7940   case ARM::VLD4dWB_fixed_Asm_32:
7941   case ARM::VLD4qWB_fixed_Asm_8:
7942   case ARM::VLD4qWB_fixed_Asm_16:
7943   case ARM::VLD4qWB_fixed_Asm_32: {
7944     MCInst TmpInst;
7945     unsigned Spacing;
7946     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7947     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7948     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7949                                             Spacing));
7950     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7951                                             Spacing * 2));
7952     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7953                                             Spacing * 3));
7954     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7955     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7956     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7957     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
7958     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
7959     TmpInst.addOperand(Inst.getOperand(4));
7960     Inst = TmpInst;
7961     return true;
7962   }
7963 
7964   case ARM::VLD4dWB_register_Asm_8:
7965   case ARM::VLD4dWB_register_Asm_16:
7966   case ARM::VLD4dWB_register_Asm_32:
7967   case ARM::VLD4qWB_register_Asm_8:
7968   case ARM::VLD4qWB_register_Asm_16:
7969   case ARM::VLD4qWB_register_Asm_32: {
7970     MCInst TmpInst;
7971     unsigned Spacing;
7972     TmpInst.setOpcode(getRealVLDOpcode(Inst.getOpcode(), Spacing));
7973     TmpInst.addOperand(Inst.getOperand(0)); // Vd
7974     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7975                                             Spacing));
7976     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7977                                             Spacing * 2));
7978     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
7979                                             Spacing * 3));
7980     TmpInst.addOperand(Inst.getOperand(1)); // Rn
7981     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
7982     TmpInst.addOperand(Inst.getOperand(2)); // alignment
7983     TmpInst.addOperand(Inst.getOperand(3)); // Rm
7984     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
7985     TmpInst.addOperand(Inst.getOperand(5));
7986     Inst = TmpInst;
7987     return true;
7988   }
7989 
7990   // VST3 multiple 3-element structure instructions.
7991   case ARM::VST3dAsm_8:
7992   case ARM::VST3dAsm_16:
7993   case ARM::VST3dAsm_32:
7994   case ARM::VST3qAsm_8:
7995   case ARM::VST3qAsm_16:
7996   case ARM::VST3qAsm_32: {
7997     MCInst TmpInst;
7998     unsigned Spacing;
7999     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8000     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8001     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8002     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8003     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8004                                             Spacing));
8005     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8006                                             Spacing * 2));
8007     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8008     TmpInst.addOperand(Inst.getOperand(4));
8009     Inst = TmpInst;
8010     return true;
8011   }
8012 
8013   case ARM::VST3dWB_fixed_Asm_8:
8014   case ARM::VST3dWB_fixed_Asm_16:
8015   case ARM::VST3dWB_fixed_Asm_32:
8016   case ARM::VST3qWB_fixed_Asm_8:
8017   case ARM::VST3qWB_fixed_Asm_16:
8018   case ARM::VST3qWB_fixed_Asm_32: {
8019     MCInst TmpInst;
8020     unsigned Spacing;
8021     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8022     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8023     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8024     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8025     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8026     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8027     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8028                                             Spacing));
8029     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8030                                             Spacing * 2));
8031     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8032     TmpInst.addOperand(Inst.getOperand(4));
8033     Inst = TmpInst;
8034     return true;
8035   }
8036 
8037   case ARM::VST3dWB_register_Asm_8:
8038   case ARM::VST3dWB_register_Asm_16:
8039   case ARM::VST3dWB_register_Asm_32:
8040   case ARM::VST3qWB_register_Asm_8:
8041   case ARM::VST3qWB_register_Asm_16:
8042   case ARM::VST3qWB_register_Asm_32: {
8043     MCInst TmpInst;
8044     unsigned Spacing;
8045     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8046     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8047     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8048     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8049     TmpInst.addOperand(Inst.getOperand(3)); // Rm
8050     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8051     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8052                                             Spacing));
8053     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8054                                             Spacing * 2));
8055     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8056     TmpInst.addOperand(Inst.getOperand(5));
8057     Inst = TmpInst;
8058     return true;
8059   }
8060 
8061   // VST4 multiple 3-element structure instructions.
8062   case ARM::VST4dAsm_8:
8063   case ARM::VST4dAsm_16:
8064   case ARM::VST4dAsm_32:
8065   case ARM::VST4qAsm_8:
8066   case ARM::VST4qAsm_16:
8067   case ARM::VST4qAsm_32: {
8068     MCInst TmpInst;
8069     unsigned Spacing;
8070     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8071     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8072     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8073     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8074     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8075                                             Spacing));
8076     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8077                                             Spacing * 2));
8078     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8079                                             Spacing * 3));
8080     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8081     TmpInst.addOperand(Inst.getOperand(4));
8082     Inst = TmpInst;
8083     return true;
8084   }
8085 
8086   case ARM::VST4dWB_fixed_Asm_8:
8087   case ARM::VST4dWB_fixed_Asm_16:
8088   case ARM::VST4dWB_fixed_Asm_32:
8089   case ARM::VST4qWB_fixed_Asm_8:
8090   case ARM::VST4qWB_fixed_Asm_16:
8091   case ARM::VST4qWB_fixed_Asm_32: {
8092     MCInst TmpInst;
8093     unsigned Spacing;
8094     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8095     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8096     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8097     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8098     TmpInst.addOperand(MCOperand::createReg(0)); // Rm
8099     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8100     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8101                                             Spacing));
8102     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8103                                             Spacing * 2));
8104     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8105                                             Spacing * 3));
8106     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8107     TmpInst.addOperand(Inst.getOperand(4));
8108     Inst = TmpInst;
8109     return true;
8110   }
8111 
8112   case ARM::VST4dWB_register_Asm_8:
8113   case ARM::VST4dWB_register_Asm_16:
8114   case ARM::VST4dWB_register_Asm_32:
8115   case ARM::VST4qWB_register_Asm_8:
8116   case ARM::VST4qWB_register_Asm_16:
8117   case ARM::VST4qWB_register_Asm_32: {
8118     MCInst TmpInst;
8119     unsigned Spacing;
8120     TmpInst.setOpcode(getRealVSTOpcode(Inst.getOpcode(), Spacing));
8121     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8122     TmpInst.addOperand(Inst.getOperand(1)); // Rn_wb == tied Rn
8123     TmpInst.addOperand(Inst.getOperand(2)); // alignment
8124     TmpInst.addOperand(Inst.getOperand(3)); // Rm
8125     TmpInst.addOperand(Inst.getOperand(0)); // Vd
8126     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8127                                             Spacing));
8128     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8129                                             Spacing * 2));
8130     TmpInst.addOperand(MCOperand::createReg(Inst.getOperand(0).getReg() +
8131                                             Spacing * 3));
8132     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8133     TmpInst.addOperand(Inst.getOperand(5));
8134     Inst = TmpInst;
8135     return true;
8136   }
8137 
8138   // Handle encoding choice for the shift-immediate instructions.
8139   case ARM::t2LSLri:
8140   case ARM::t2LSRri:
8141   case ARM::t2ASRri:
8142     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8143         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8144         Inst.getOperand(5).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
8145         !HasWideQualifier) {
8146       unsigned NewOpc;
8147       switch (Inst.getOpcode()) {
8148       default: llvm_unreachable("unexpected opcode");
8149       case ARM::t2LSLri: NewOpc = ARM::tLSLri; break;
8150       case ARM::t2LSRri: NewOpc = ARM::tLSRri; break;
8151       case ARM::t2ASRri: NewOpc = ARM::tASRri; break;
8152       }
8153       // The Thumb1 operands aren't in the same order. Awesome, eh?
8154       MCInst TmpInst;
8155       TmpInst.setOpcode(NewOpc);
8156       TmpInst.addOperand(Inst.getOperand(0));
8157       TmpInst.addOperand(Inst.getOperand(5));
8158       TmpInst.addOperand(Inst.getOperand(1));
8159       TmpInst.addOperand(Inst.getOperand(2));
8160       TmpInst.addOperand(Inst.getOperand(3));
8161       TmpInst.addOperand(Inst.getOperand(4));
8162       Inst = TmpInst;
8163       return true;
8164     }
8165     return false;
8166 
8167   // Handle the Thumb2 mode MOV complex aliases.
8168   case ARM::t2MOVsr:
8169   case ARM::t2MOVSsr: {
8170     // Which instruction to expand to depends on the CCOut operand and
8171     // whether we're in an IT block if the register operands are low
8172     // registers.
8173     bool isNarrow = false;
8174     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8175         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8176         isARMLowRegister(Inst.getOperand(2).getReg()) &&
8177         Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() &&
8178         inITBlock() == (Inst.getOpcode() == ARM::t2MOVsr) &&
8179         !HasWideQualifier)
8180       isNarrow = true;
8181     MCInst TmpInst;
8182     unsigned newOpc;
8183     switch(ARM_AM::getSORegShOp(Inst.getOperand(3).getImm())) {
8184     default: llvm_unreachable("unexpected opcode!");
8185     case ARM_AM::asr: newOpc = isNarrow ? ARM::tASRrr : ARM::t2ASRrr; break;
8186     case ARM_AM::lsr: newOpc = isNarrow ? ARM::tLSRrr : ARM::t2LSRrr; break;
8187     case ARM_AM::lsl: newOpc = isNarrow ? ARM::tLSLrr : ARM::t2LSLrr; break;
8188     case ARM_AM::ror: newOpc = isNarrow ? ARM::tROR   : ARM::t2RORrr; break;
8189     }
8190     TmpInst.setOpcode(newOpc);
8191     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8192     if (isNarrow)
8193       TmpInst.addOperand(MCOperand::createReg(
8194           Inst.getOpcode() == ARM::t2MOVSsr ? ARM::CPSR : 0));
8195     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8196     TmpInst.addOperand(Inst.getOperand(2)); // Rm
8197     TmpInst.addOperand(Inst.getOperand(4)); // CondCode
8198     TmpInst.addOperand(Inst.getOperand(5));
8199     if (!isNarrow)
8200       TmpInst.addOperand(MCOperand::createReg(
8201           Inst.getOpcode() == ARM::t2MOVSsr ? ARM::CPSR : 0));
8202     Inst = TmpInst;
8203     return true;
8204   }
8205   case ARM::t2MOVsi:
8206   case ARM::t2MOVSsi: {
8207     // Which instruction to expand to depends on the CCOut operand and
8208     // whether we're in an IT block if the register operands are low
8209     // registers.
8210     bool isNarrow = false;
8211     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8212         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8213         inITBlock() == (Inst.getOpcode() == ARM::t2MOVsi) &&
8214         !HasWideQualifier)
8215       isNarrow = true;
8216     MCInst TmpInst;
8217     unsigned newOpc;
8218     unsigned Shift = ARM_AM::getSORegShOp(Inst.getOperand(2).getImm());
8219     unsigned Amount = ARM_AM::getSORegOffset(Inst.getOperand(2).getImm());
8220     bool isMov = false;
8221     // MOV rd, rm, LSL #0 is actually a MOV instruction
8222     if (Shift == ARM_AM::lsl && Amount == 0) {
8223       isMov = true;
8224       // The 16-bit encoding of MOV rd, rm, LSL #N is explicitly encoding T2 of
8225       // MOV (register) in the ARMv8-A and ARMv8-M manuals, and immediate 0 is
8226       // unpredictable in an IT block so the 32-bit encoding T3 has to be used
8227       // instead.
8228       if (inITBlock()) {
8229         isNarrow = false;
8230       }
8231       newOpc = isNarrow ? ARM::tMOVSr : ARM::t2MOVr;
8232     } else {
8233       switch(Shift) {
8234       default: llvm_unreachable("unexpected opcode!");
8235       case ARM_AM::asr: newOpc = isNarrow ? ARM::tASRri : ARM::t2ASRri; break;
8236       case ARM_AM::lsr: newOpc = isNarrow ? ARM::tLSRri : ARM::t2LSRri; break;
8237       case ARM_AM::lsl: newOpc = isNarrow ? ARM::tLSLri : ARM::t2LSLri; break;
8238       case ARM_AM::ror: newOpc = ARM::t2RORri; isNarrow = false; break;
8239       case ARM_AM::rrx: isNarrow = false; newOpc = ARM::t2RRX; break;
8240       }
8241     }
8242     if (Amount == 32) Amount = 0;
8243     TmpInst.setOpcode(newOpc);
8244     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8245     if (isNarrow && !isMov)
8246       TmpInst.addOperand(MCOperand::createReg(
8247           Inst.getOpcode() == ARM::t2MOVSsi ? ARM::CPSR : 0));
8248     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8249     if (newOpc != ARM::t2RRX && !isMov)
8250       TmpInst.addOperand(MCOperand::createImm(Amount));
8251     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8252     TmpInst.addOperand(Inst.getOperand(4));
8253     if (!isNarrow)
8254       TmpInst.addOperand(MCOperand::createReg(
8255           Inst.getOpcode() == ARM::t2MOVSsi ? ARM::CPSR : 0));
8256     Inst = TmpInst;
8257     return true;
8258   }
8259   // Handle the ARM mode MOV complex aliases.
8260   case ARM::ASRr:
8261   case ARM::LSRr:
8262   case ARM::LSLr:
8263   case ARM::RORr: {
8264     ARM_AM::ShiftOpc ShiftTy;
8265     switch(Inst.getOpcode()) {
8266     default: llvm_unreachable("unexpected opcode!");
8267     case ARM::ASRr: ShiftTy = ARM_AM::asr; break;
8268     case ARM::LSRr: ShiftTy = ARM_AM::lsr; break;
8269     case ARM::LSLr: ShiftTy = ARM_AM::lsl; break;
8270     case ARM::RORr: ShiftTy = ARM_AM::ror; break;
8271     }
8272     unsigned Shifter = ARM_AM::getSORegOpc(ShiftTy, 0);
8273     MCInst TmpInst;
8274     TmpInst.setOpcode(ARM::MOVsr);
8275     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8276     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8277     TmpInst.addOperand(Inst.getOperand(2)); // Rm
8278     TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
8279     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8280     TmpInst.addOperand(Inst.getOperand(4));
8281     TmpInst.addOperand(Inst.getOperand(5)); // cc_out
8282     Inst = TmpInst;
8283     return true;
8284   }
8285   case ARM::ASRi:
8286   case ARM::LSRi:
8287   case ARM::LSLi:
8288   case ARM::RORi: {
8289     ARM_AM::ShiftOpc ShiftTy;
8290     switch(Inst.getOpcode()) {
8291     default: llvm_unreachable("unexpected opcode!");
8292     case ARM::ASRi: ShiftTy = ARM_AM::asr; break;
8293     case ARM::LSRi: ShiftTy = ARM_AM::lsr; break;
8294     case ARM::LSLi: ShiftTy = ARM_AM::lsl; break;
8295     case ARM::RORi: ShiftTy = ARM_AM::ror; break;
8296     }
8297     // A shift by zero is a plain MOVr, not a MOVsi.
8298     unsigned Amt = Inst.getOperand(2).getImm();
8299     unsigned Opc = Amt == 0 ? ARM::MOVr : ARM::MOVsi;
8300     // A shift by 32 should be encoded as 0 when permitted
8301     if (Amt == 32 && (ShiftTy == ARM_AM::lsr || ShiftTy == ARM_AM::asr))
8302       Amt = 0;
8303     unsigned Shifter = ARM_AM::getSORegOpc(ShiftTy, Amt);
8304     MCInst TmpInst;
8305     TmpInst.setOpcode(Opc);
8306     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8307     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8308     if (Opc == ARM::MOVsi)
8309       TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
8310     TmpInst.addOperand(Inst.getOperand(3)); // CondCode
8311     TmpInst.addOperand(Inst.getOperand(4));
8312     TmpInst.addOperand(Inst.getOperand(5)); // cc_out
8313     Inst = TmpInst;
8314     return true;
8315   }
8316   case ARM::RRXi: {
8317     unsigned Shifter = ARM_AM::getSORegOpc(ARM_AM::rrx, 0);
8318     MCInst TmpInst;
8319     TmpInst.setOpcode(ARM::MOVsi);
8320     TmpInst.addOperand(Inst.getOperand(0)); // Rd
8321     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8322     TmpInst.addOperand(MCOperand::createImm(Shifter)); // Shift value and ty
8323     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8324     TmpInst.addOperand(Inst.getOperand(3));
8325     TmpInst.addOperand(Inst.getOperand(4)); // cc_out
8326     Inst = TmpInst;
8327     return true;
8328   }
8329   case ARM::t2LDMIA_UPD: {
8330     // If this is a load of a single register, then we should use
8331     // a post-indexed LDR instruction instead, per the ARM ARM.
8332     if (Inst.getNumOperands() != 5)
8333       return false;
8334     MCInst TmpInst;
8335     TmpInst.setOpcode(ARM::t2LDR_POST);
8336     TmpInst.addOperand(Inst.getOperand(4)); // Rt
8337     TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8338     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8339     TmpInst.addOperand(MCOperand::createImm(4));
8340     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8341     TmpInst.addOperand(Inst.getOperand(3));
8342     Inst = TmpInst;
8343     return true;
8344   }
8345   case ARM::t2STMDB_UPD: {
8346     // If this is a store of a single register, then we should use
8347     // a pre-indexed STR instruction instead, per the ARM ARM.
8348     if (Inst.getNumOperands() != 5)
8349       return false;
8350     MCInst TmpInst;
8351     TmpInst.setOpcode(ARM::t2STR_PRE);
8352     TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8353     TmpInst.addOperand(Inst.getOperand(4)); // Rt
8354     TmpInst.addOperand(Inst.getOperand(1)); // Rn
8355     TmpInst.addOperand(MCOperand::createImm(-4));
8356     TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8357     TmpInst.addOperand(Inst.getOperand(3));
8358     Inst = TmpInst;
8359     return true;
8360   }
8361   case ARM::LDMIA_UPD:
8362     // If this is a load of a single register via a 'pop', then we should use
8363     // a post-indexed LDR instruction instead, per the ARM ARM.
8364     if (static_cast<ARMOperand &>(*Operands[0]).getToken() == "pop" &&
8365         Inst.getNumOperands() == 5) {
8366       MCInst TmpInst;
8367       TmpInst.setOpcode(ARM::LDR_POST_IMM);
8368       TmpInst.addOperand(Inst.getOperand(4)); // Rt
8369       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8370       TmpInst.addOperand(Inst.getOperand(1)); // Rn
8371       TmpInst.addOperand(MCOperand::createReg(0));  // am2offset
8372       TmpInst.addOperand(MCOperand::createImm(4));
8373       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8374       TmpInst.addOperand(Inst.getOperand(3));
8375       Inst = TmpInst;
8376       return true;
8377     }
8378     break;
8379   case ARM::STMDB_UPD:
8380     // If this is a store of a single register via a 'push', then we should use
8381     // a pre-indexed STR instruction instead, per the ARM ARM.
8382     if (static_cast<ARMOperand &>(*Operands[0]).getToken() == "push" &&
8383         Inst.getNumOperands() == 5) {
8384       MCInst TmpInst;
8385       TmpInst.setOpcode(ARM::STR_PRE_IMM);
8386       TmpInst.addOperand(Inst.getOperand(0)); // Rn_wb
8387       TmpInst.addOperand(Inst.getOperand(4)); // Rt
8388       TmpInst.addOperand(Inst.getOperand(1)); // addrmode_imm12
8389       TmpInst.addOperand(MCOperand::createImm(-4));
8390       TmpInst.addOperand(Inst.getOperand(2)); // CondCode
8391       TmpInst.addOperand(Inst.getOperand(3));
8392       Inst = TmpInst;
8393     }
8394     break;
8395   case ARM::t2ADDri12:
8396     // If the immediate fits for encoding T3 (t2ADDri) and the generic "add"
8397     // mnemonic was used (not "addw"), encoding T3 is preferred.
8398     if (static_cast<ARMOperand &>(*Operands[0]).getToken() != "add" ||
8399         ARM_AM::getT2SOImmVal(Inst.getOperand(2).getImm()) == -1)
8400       break;
8401     Inst.setOpcode(ARM::t2ADDri);
8402     Inst.addOperand(MCOperand::createReg(0)); // cc_out
8403     break;
8404   case ARM::t2SUBri12:
8405     // If the immediate fits for encoding T3 (t2SUBri) and the generic "sub"
8406     // mnemonic was used (not "subw"), encoding T3 is preferred.
8407     if (static_cast<ARMOperand &>(*Operands[0]).getToken() != "sub" ||
8408         ARM_AM::getT2SOImmVal(Inst.getOperand(2).getImm()) == -1)
8409       break;
8410     Inst.setOpcode(ARM::t2SUBri);
8411     Inst.addOperand(MCOperand::createReg(0)); // cc_out
8412     break;
8413   case ARM::tADDi8:
8414     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
8415     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
8416     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
8417     // to encoding T1 if <Rd> is omitted."
8418     if ((unsigned)Inst.getOperand(3).getImm() < 8 && Operands.size() == 6) {
8419       Inst.setOpcode(ARM::tADDi3);
8420       return true;
8421     }
8422     break;
8423   case ARM::tSUBi8:
8424     // If the immediate is in the range 0-7, we want tADDi3 iff Rd was
8425     // explicitly specified. From the ARM ARM: "Encoding T1 is preferred
8426     // to encoding T2 if <Rd> is specified and encoding T2 is preferred
8427     // to encoding T1 if <Rd> is omitted."
8428     if ((unsigned)Inst.getOperand(3).getImm() < 8 && Operands.size() == 6) {
8429       Inst.setOpcode(ARM::tSUBi3);
8430       return true;
8431     }
8432     break;
8433   case ARM::t2ADDri:
8434   case ARM::t2SUBri: {
8435     // If the destination and first source operand are the same, and
8436     // the flags are compatible with the current IT status, use encoding T2
8437     // instead of T3. For compatibility with the system 'as'. Make sure the
8438     // wide encoding wasn't explicit.
8439     if (Inst.getOperand(0).getReg() != Inst.getOperand(1).getReg() ||
8440         !isARMLowRegister(Inst.getOperand(0).getReg()) ||
8441         (Inst.getOperand(2).isImm() &&
8442          (unsigned)Inst.getOperand(2).getImm() > 255) ||
8443         Inst.getOperand(5).getReg() != (inITBlock() ? 0 : ARM::CPSR) ||
8444         HasWideQualifier)
8445       break;
8446     MCInst TmpInst;
8447     TmpInst.setOpcode(Inst.getOpcode() == ARM::t2ADDri ?
8448                       ARM::tADDi8 : ARM::tSUBi8);
8449     TmpInst.addOperand(Inst.getOperand(0));
8450     TmpInst.addOperand(Inst.getOperand(5));
8451     TmpInst.addOperand(Inst.getOperand(0));
8452     TmpInst.addOperand(Inst.getOperand(2));
8453     TmpInst.addOperand(Inst.getOperand(3));
8454     TmpInst.addOperand(Inst.getOperand(4));
8455     Inst = TmpInst;
8456     return true;
8457   }
8458   case ARM::t2ADDrr: {
8459     // If the destination and first source operand are the same, and
8460     // there's no setting of the flags, use encoding T2 instead of T3.
8461     // Note that this is only for ADD, not SUB. This mirrors the system
8462     // 'as' behaviour.  Also take advantage of ADD being commutative.
8463     // Make sure the wide encoding wasn't explicit.
8464     bool Swap = false;
8465     auto DestReg = Inst.getOperand(0).getReg();
8466     bool Transform = DestReg == Inst.getOperand(1).getReg();
8467     if (!Transform && DestReg == Inst.getOperand(2).getReg()) {
8468       Transform = true;
8469       Swap = true;
8470     }
8471     if (!Transform ||
8472         Inst.getOperand(5).getReg() != 0 ||
8473         HasWideQualifier)
8474       break;
8475     MCInst TmpInst;
8476     TmpInst.setOpcode(ARM::tADDhirr);
8477     TmpInst.addOperand(Inst.getOperand(0));
8478     TmpInst.addOperand(Inst.getOperand(0));
8479     TmpInst.addOperand(Inst.getOperand(Swap ? 1 : 2));
8480     TmpInst.addOperand(Inst.getOperand(3));
8481     TmpInst.addOperand(Inst.getOperand(4));
8482     Inst = TmpInst;
8483     return true;
8484   }
8485   case ARM::tADDrSP:
8486     // If the non-SP source operand and the destination operand are not the
8487     // same, we need to use the 32-bit encoding if it's available.
8488     if (Inst.getOperand(0).getReg() != Inst.getOperand(2).getReg()) {
8489       Inst.setOpcode(ARM::t2ADDrr);
8490       Inst.addOperand(MCOperand::createReg(0)); // cc_out
8491       return true;
8492     }
8493     break;
8494   case ARM::tB:
8495     // A Thumb conditional branch outside of an IT block is a tBcc.
8496     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock()) {
8497       Inst.setOpcode(ARM::tBcc);
8498       return true;
8499     }
8500     break;
8501   case ARM::t2B:
8502     // A Thumb2 conditional branch outside of an IT block is a t2Bcc.
8503     if (Inst.getOperand(1).getImm() != ARMCC::AL && !inITBlock()){
8504       Inst.setOpcode(ARM::t2Bcc);
8505       return true;
8506     }
8507     break;
8508   case ARM::t2Bcc:
8509     // If the conditional is AL or we're in an IT block, we really want t2B.
8510     if (Inst.getOperand(1).getImm() == ARMCC::AL || inITBlock()) {
8511       Inst.setOpcode(ARM::t2B);
8512       return true;
8513     }
8514     break;
8515   case ARM::tBcc:
8516     // If the conditional is AL, we really want tB.
8517     if (Inst.getOperand(1).getImm() == ARMCC::AL) {
8518       Inst.setOpcode(ARM::tB);
8519       return true;
8520     }
8521     break;
8522   case ARM::tLDMIA: {
8523     // If the register list contains any high registers, or if the writeback
8524     // doesn't match what tLDMIA can do, we need to use the 32-bit encoding
8525     // instead if we're in Thumb2. Otherwise, this should have generated
8526     // an error in validateInstruction().
8527     unsigned Rn = Inst.getOperand(0).getReg();
8528     bool hasWritebackToken =
8529         (static_cast<ARMOperand &>(*Operands[3]).isToken() &&
8530          static_cast<ARMOperand &>(*Operands[3]).getToken() == "!");
8531     bool listContainsBase;
8532     if (checkLowRegisterList(Inst, 3, Rn, 0, listContainsBase) ||
8533         (!listContainsBase && !hasWritebackToken) ||
8534         (listContainsBase && hasWritebackToken)) {
8535       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
8536       assert(isThumbTwo());
8537       Inst.setOpcode(hasWritebackToken ? ARM::t2LDMIA_UPD : ARM::t2LDMIA);
8538       // If we're switching to the updating version, we need to insert
8539       // the writeback tied operand.
8540       if (hasWritebackToken)
8541         Inst.insert(Inst.begin(),
8542                     MCOperand::createReg(Inst.getOperand(0).getReg()));
8543       return true;
8544     }
8545     break;
8546   }
8547   case ARM::tSTMIA_UPD: {
8548     // If the register list contains any high registers, we need to use
8549     // the 32-bit encoding instead if we're in Thumb2. Otherwise, this
8550     // should have generated an error in validateInstruction().
8551     unsigned Rn = Inst.getOperand(0).getReg();
8552     bool listContainsBase;
8553     if (checkLowRegisterList(Inst, 4, Rn, 0, listContainsBase)) {
8554       // 16-bit encoding isn't sufficient. Switch to the 32-bit version.
8555       assert(isThumbTwo());
8556       Inst.setOpcode(ARM::t2STMIA_UPD);
8557       return true;
8558     }
8559     break;
8560   }
8561   case ARM::tPOP: {
8562     bool listContainsBase;
8563     // If the register list contains any high registers, we need to use
8564     // the 32-bit encoding instead if we're in Thumb2. Otherwise, this
8565     // should have generated an error in validateInstruction().
8566     if (!checkLowRegisterList(Inst, 2, 0, ARM::PC, listContainsBase))
8567       return false;
8568     assert(isThumbTwo());
8569     Inst.setOpcode(ARM::t2LDMIA_UPD);
8570     // Add the base register and writeback operands.
8571     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8572     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8573     return true;
8574   }
8575   case ARM::tPUSH: {
8576     bool listContainsBase;
8577     if (!checkLowRegisterList(Inst, 2, 0, ARM::LR, listContainsBase))
8578       return false;
8579     assert(isThumbTwo());
8580     Inst.setOpcode(ARM::t2STMDB_UPD);
8581     // Add the base register and writeback operands.
8582     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8583     Inst.insert(Inst.begin(), MCOperand::createReg(ARM::SP));
8584     return true;
8585   }
8586   case ARM::t2MOVi:
8587     // If we can use the 16-bit encoding and the user didn't explicitly
8588     // request the 32-bit variant, transform it here.
8589     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8590         (Inst.getOperand(1).isImm() &&
8591          (unsigned)Inst.getOperand(1).getImm() <= 255) &&
8592         Inst.getOperand(4).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
8593         !HasWideQualifier) {
8594       // The operands aren't in the same order for tMOVi8...
8595       MCInst TmpInst;
8596       TmpInst.setOpcode(ARM::tMOVi8);
8597       TmpInst.addOperand(Inst.getOperand(0));
8598       TmpInst.addOperand(Inst.getOperand(4));
8599       TmpInst.addOperand(Inst.getOperand(1));
8600       TmpInst.addOperand(Inst.getOperand(2));
8601       TmpInst.addOperand(Inst.getOperand(3));
8602       Inst = TmpInst;
8603       return true;
8604     }
8605     break;
8606 
8607   case ARM::t2MOVr:
8608     // If we can use the 16-bit encoding and the user didn't explicitly
8609     // request the 32-bit variant, transform it here.
8610     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8611         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8612         Inst.getOperand(2).getImm() == ARMCC::AL &&
8613         Inst.getOperand(4).getReg() == ARM::CPSR &&
8614         !HasWideQualifier) {
8615       // The operands aren't the same for tMOV[S]r... (no cc_out)
8616       MCInst TmpInst;
8617       TmpInst.setOpcode(Inst.getOperand(4).getReg() ? ARM::tMOVSr : ARM::tMOVr);
8618       TmpInst.addOperand(Inst.getOperand(0));
8619       TmpInst.addOperand(Inst.getOperand(1));
8620       TmpInst.addOperand(Inst.getOperand(2));
8621       TmpInst.addOperand(Inst.getOperand(3));
8622       Inst = TmpInst;
8623       return true;
8624     }
8625     break;
8626 
8627   case ARM::t2SXTH:
8628   case ARM::t2SXTB:
8629   case ARM::t2UXTH:
8630   case ARM::t2UXTB:
8631     // If we can use the 16-bit encoding and the user didn't explicitly
8632     // request the 32-bit variant, transform it here.
8633     if (isARMLowRegister(Inst.getOperand(0).getReg()) &&
8634         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8635         Inst.getOperand(2).getImm() == 0 &&
8636         !HasWideQualifier) {
8637       unsigned NewOpc;
8638       switch (Inst.getOpcode()) {
8639       default: llvm_unreachable("Illegal opcode!");
8640       case ARM::t2SXTH: NewOpc = ARM::tSXTH; break;
8641       case ARM::t2SXTB: NewOpc = ARM::tSXTB; break;
8642       case ARM::t2UXTH: NewOpc = ARM::tUXTH; break;
8643       case ARM::t2UXTB: NewOpc = ARM::tUXTB; break;
8644       }
8645       // The operands aren't the same for thumb1 (no rotate operand).
8646       MCInst TmpInst;
8647       TmpInst.setOpcode(NewOpc);
8648       TmpInst.addOperand(Inst.getOperand(0));
8649       TmpInst.addOperand(Inst.getOperand(1));
8650       TmpInst.addOperand(Inst.getOperand(3));
8651       TmpInst.addOperand(Inst.getOperand(4));
8652       Inst = TmpInst;
8653       return true;
8654     }
8655     break;
8656 
8657   case ARM::MOVsi: {
8658     ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(Inst.getOperand(2).getImm());
8659     // rrx shifts and asr/lsr of #32 is encoded as 0
8660     if (SOpc == ARM_AM::rrx || SOpc == ARM_AM::asr || SOpc == ARM_AM::lsr)
8661       return false;
8662     if (ARM_AM::getSORegOffset(Inst.getOperand(2).getImm()) == 0) {
8663       // Shifting by zero is accepted as a vanilla 'MOVr'
8664       MCInst TmpInst;
8665       TmpInst.setOpcode(ARM::MOVr);
8666       TmpInst.addOperand(Inst.getOperand(0));
8667       TmpInst.addOperand(Inst.getOperand(1));
8668       TmpInst.addOperand(Inst.getOperand(3));
8669       TmpInst.addOperand(Inst.getOperand(4));
8670       TmpInst.addOperand(Inst.getOperand(5));
8671       Inst = TmpInst;
8672       return true;
8673     }
8674     return false;
8675   }
8676   case ARM::ANDrsi:
8677   case ARM::ORRrsi:
8678   case ARM::EORrsi:
8679   case ARM::BICrsi:
8680   case ARM::SUBrsi:
8681   case ARM::ADDrsi: {
8682     unsigned newOpc;
8683     ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(Inst.getOperand(3).getImm());
8684     if (SOpc == ARM_AM::rrx) return false;
8685     switch (Inst.getOpcode()) {
8686     default: llvm_unreachable("unexpected opcode!");
8687     case ARM::ANDrsi: newOpc = ARM::ANDrr; break;
8688     case ARM::ORRrsi: newOpc = ARM::ORRrr; break;
8689     case ARM::EORrsi: newOpc = ARM::EORrr; break;
8690     case ARM::BICrsi: newOpc = ARM::BICrr; break;
8691     case ARM::SUBrsi: newOpc = ARM::SUBrr; break;
8692     case ARM::ADDrsi: newOpc = ARM::ADDrr; break;
8693     }
8694     // If the shift is by zero, use the non-shifted instruction definition.
8695     // The exception is for right shifts, where 0 == 32
8696     if (ARM_AM::getSORegOffset(Inst.getOperand(3).getImm()) == 0 &&
8697         !(SOpc == ARM_AM::lsr || SOpc == ARM_AM::asr)) {
8698       MCInst TmpInst;
8699       TmpInst.setOpcode(newOpc);
8700       TmpInst.addOperand(Inst.getOperand(0));
8701       TmpInst.addOperand(Inst.getOperand(1));
8702       TmpInst.addOperand(Inst.getOperand(2));
8703       TmpInst.addOperand(Inst.getOperand(4));
8704       TmpInst.addOperand(Inst.getOperand(5));
8705       TmpInst.addOperand(Inst.getOperand(6));
8706       Inst = TmpInst;
8707       return true;
8708     }
8709     return false;
8710   }
8711   case ARM::ITasm:
8712   case ARM::t2IT: {
8713     MCOperand &MO = Inst.getOperand(1);
8714     unsigned Mask = MO.getImm();
8715     ARMCC::CondCodes Cond = ARMCC::CondCodes(Inst.getOperand(0).getImm());
8716 
8717     // Set up the IT block state according to the IT instruction we just
8718     // matched.
8719     assert(!inITBlock() && "nested IT blocks?!");
8720     startExplicitITBlock(Cond, Mask);
8721     MO.setImm(getITMaskEncoding());
8722     break;
8723   }
8724   case ARM::t2LSLrr:
8725   case ARM::t2LSRrr:
8726   case ARM::t2ASRrr:
8727   case ARM::t2SBCrr:
8728   case ARM::t2RORrr:
8729   case ARM::t2BICrr:
8730     // Assemblers should use the narrow encodings of these instructions when permissible.
8731     if ((isARMLowRegister(Inst.getOperand(1).getReg()) &&
8732          isARMLowRegister(Inst.getOperand(2).getReg())) &&
8733         Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() &&
8734         Inst.getOperand(5).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
8735         !HasWideQualifier) {
8736       unsigned NewOpc;
8737       switch (Inst.getOpcode()) {
8738         default: llvm_unreachable("unexpected opcode");
8739         case ARM::t2LSLrr: NewOpc = ARM::tLSLrr; break;
8740         case ARM::t2LSRrr: NewOpc = ARM::tLSRrr; break;
8741         case ARM::t2ASRrr: NewOpc = ARM::tASRrr; break;
8742         case ARM::t2SBCrr: NewOpc = ARM::tSBC; break;
8743         case ARM::t2RORrr: NewOpc = ARM::tROR; break;
8744         case ARM::t2BICrr: NewOpc = ARM::tBIC; break;
8745       }
8746       MCInst TmpInst;
8747       TmpInst.setOpcode(NewOpc);
8748       TmpInst.addOperand(Inst.getOperand(0));
8749       TmpInst.addOperand(Inst.getOperand(5));
8750       TmpInst.addOperand(Inst.getOperand(1));
8751       TmpInst.addOperand(Inst.getOperand(2));
8752       TmpInst.addOperand(Inst.getOperand(3));
8753       TmpInst.addOperand(Inst.getOperand(4));
8754       Inst = TmpInst;
8755       return true;
8756     }
8757     return false;
8758 
8759   case ARM::t2ANDrr:
8760   case ARM::t2EORrr:
8761   case ARM::t2ADCrr:
8762   case ARM::t2ORRrr:
8763     // Assemblers should use the narrow encodings of these instructions when permissible.
8764     // These instructions are special in that they are commutable, so shorter encodings
8765     // are available more often.
8766     if ((isARMLowRegister(Inst.getOperand(1).getReg()) &&
8767          isARMLowRegister(Inst.getOperand(2).getReg())) &&
8768         (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg() ||
8769          Inst.getOperand(0).getReg() == Inst.getOperand(2).getReg()) &&
8770         Inst.getOperand(5).getReg() == (inITBlock() ? 0 : ARM::CPSR) &&
8771         !HasWideQualifier) {
8772       unsigned NewOpc;
8773       switch (Inst.getOpcode()) {
8774         default: llvm_unreachable("unexpected opcode");
8775         case ARM::t2ADCrr: NewOpc = ARM::tADC; break;
8776         case ARM::t2ANDrr: NewOpc = ARM::tAND; break;
8777         case ARM::t2EORrr: NewOpc = ARM::tEOR; break;
8778         case ARM::t2ORRrr: NewOpc = ARM::tORR; break;
8779       }
8780       MCInst TmpInst;
8781       TmpInst.setOpcode(NewOpc);
8782       TmpInst.addOperand(Inst.getOperand(0));
8783       TmpInst.addOperand(Inst.getOperand(5));
8784       if (Inst.getOperand(0).getReg() == Inst.getOperand(1).getReg()) {
8785         TmpInst.addOperand(Inst.getOperand(1));
8786         TmpInst.addOperand(Inst.getOperand(2));
8787       } else {
8788         TmpInst.addOperand(Inst.getOperand(2));
8789         TmpInst.addOperand(Inst.getOperand(1));
8790       }
8791       TmpInst.addOperand(Inst.getOperand(3));
8792       TmpInst.addOperand(Inst.getOperand(4));
8793       Inst = TmpInst;
8794       return true;
8795     }
8796     return false;
8797   }
8798   return false;
8799 }
8800 
8801 unsigned ARMAsmParser::checkTargetMatchPredicate(MCInst &Inst) {
8802   // 16-bit thumb arithmetic instructions either require or preclude the 'S'
8803   // suffix depending on whether they're in an IT block or not.
8804   unsigned Opc = Inst.getOpcode();
8805   const MCInstrDesc &MCID = MII.get(Opc);
8806   if (MCID.TSFlags & ARMII::ThumbArithFlagSetting) {
8807     assert(MCID.hasOptionalDef() &&
8808            "optionally flag setting instruction missing optional def operand");
8809     assert(MCID.NumOperands == Inst.getNumOperands() &&
8810            "operand count mismatch!");
8811     // Find the optional-def operand (cc_out).
8812     unsigned OpNo;
8813     for (OpNo = 0;
8814          !MCID.OpInfo[OpNo].isOptionalDef() && OpNo < MCID.NumOperands;
8815          ++OpNo)
8816       ;
8817     // If we're parsing Thumb1, reject it completely.
8818     if (isThumbOne() && Inst.getOperand(OpNo).getReg() != ARM::CPSR)
8819       return Match_RequiresFlagSetting;
8820     // If we're parsing Thumb2, which form is legal depends on whether we're
8821     // in an IT block.
8822     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() != ARM::CPSR &&
8823         !inITBlock())
8824       return Match_RequiresITBlock;
8825     if (isThumbTwo() && Inst.getOperand(OpNo).getReg() == ARM::CPSR &&
8826         inITBlock())
8827       return Match_RequiresNotITBlock;
8828     // LSL with zero immediate is not allowed in an IT block
8829     if (Opc == ARM::tLSLri && Inst.getOperand(3).getImm() == 0 && inITBlock())
8830       return Match_RequiresNotITBlock;
8831   } else if (isThumbOne()) {
8832     // Some high-register supporting Thumb1 encodings only allow both registers
8833     // to be from r0-r7 when in Thumb2.
8834     if (Opc == ARM::tADDhirr && !hasV6MOps() &&
8835         isARMLowRegister(Inst.getOperand(1).getReg()) &&
8836         isARMLowRegister(Inst.getOperand(2).getReg()))
8837       return Match_RequiresThumb2;
8838     // Others only require ARMv6 or later.
8839     else if (Opc == ARM::tMOVr && !hasV6Ops() &&
8840              isARMLowRegister(Inst.getOperand(0).getReg()) &&
8841              isARMLowRegister(Inst.getOperand(1).getReg()))
8842       return Match_RequiresV6;
8843   }
8844 
8845   // Before ARMv8 the rules for when SP is allowed in t2MOVr are more complex
8846   // than the loop below can handle, so it uses the GPRnopc register class and
8847   // we do SP handling here.
8848   if (Opc == ARM::t2MOVr && !hasV8Ops())
8849   {
8850     // SP as both source and destination is not allowed
8851     if (Inst.getOperand(0).getReg() == ARM::SP &&
8852         Inst.getOperand(1).getReg() == ARM::SP)
8853       return Match_RequiresV8;
8854     // When flags-setting SP as either source or destination is not allowed
8855     if (Inst.getOperand(4).getReg() == ARM::CPSR &&
8856         (Inst.getOperand(0).getReg() == ARM::SP ||
8857          Inst.getOperand(1).getReg() == ARM::SP))
8858       return Match_RequiresV8;
8859   }
8860 
8861   // Use of SP for VMRS/VMSR is only allowed in ARM mode with the exception of
8862   // ARMv8-A.
8863   if ((Inst.getOpcode() == ARM::VMRS || Inst.getOpcode() == ARM::VMSR) &&
8864       Inst.getOperand(0).getReg() == ARM::SP && (isThumb() && !hasV8Ops()))
8865     return Match_InvalidOperand;
8866 
8867   for (unsigned I = 0; I < MCID.NumOperands; ++I)
8868     if (MCID.OpInfo[I].RegClass == ARM::rGPRRegClassID) {
8869       // rGPRRegClass excludes PC, and also excluded SP before ARMv8
8870       if ((Inst.getOperand(I).getReg() == ARM::SP) && !hasV8Ops())
8871         return Match_RequiresV8;
8872       else if (Inst.getOperand(I).getReg() == ARM::PC)
8873         return Match_InvalidOperand;
8874     }
8875 
8876   return Match_Success;
8877 }
8878 
8879 namespace llvm {
8880 
8881 template <> inline bool IsCPSRDead<MCInst>(const MCInst *Instr) {
8882   return true; // In an assembly source, no need to second-guess
8883 }
8884 
8885 } // end namespace llvm
8886 
8887 // Returns true if Inst is unpredictable if it is in and IT block, but is not
8888 // the last instruction in the block.
8889 bool ARMAsmParser::isITBlockTerminator(MCInst &Inst) const {
8890   const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
8891 
8892   // All branch & call instructions terminate IT blocks with the exception of
8893   // SVC.
8894   if (MCID.isTerminator() || (MCID.isCall() && Inst.getOpcode() != ARM::tSVC) ||
8895       MCID.isReturn() || MCID.isBranch() || MCID.isIndirectBranch())
8896     return true;
8897 
8898   // Any arithmetic instruction which writes to the PC also terminates the IT
8899   // block.
8900   for (unsigned OpIdx = 0; OpIdx < MCID.getNumDefs(); ++OpIdx) {
8901     MCOperand &Op = Inst.getOperand(OpIdx);
8902     if (Op.isReg() && Op.getReg() == ARM::PC)
8903       return true;
8904   }
8905 
8906   if (MCID.hasImplicitDefOfPhysReg(ARM::PC, MRI))
8907     return true;
8908 
8909   // Instructions with variable operand lists, which write to the variable
8910   // operands. We only care about Thumb instructions here, as ARM instructions
8911   // obviously can't be in an IT block.
8912   switch (Inst.getOpcode()) {
8913   case ARM::tLDMIA:
8914   case ARM::t2LDMIA:
8915   case ARM::t2LDMIA_UPD:
8916   case ARM::t2LDMDB:
8917   case ARM::t2LDMDB_UPD:
8918     if (listContainsReg(Inst, 3, ARM::PC))
8919       return true;
8920     break;
8921   case ARM::tPOP:
8922     if (listContainsReg(Inst, 2, ARM::PC))
8923       return true;
8924     break;
8925   }
8926 
8927   return false;
8928 }
8929 
8930 unsigned ARMAsmParser::MatchInstruction(OperandVector &Operands, MCInst &Inst,
8931                                           SmallVectorImpl<NearMissInfo> &NearMisses,
8932                                           bool MatchingInlineAsm,
8933                                           bool &EmitInITBlock,
8934                                           MCStreamer &Out) {
8935   // If we can't use an implicit IT block here, just match as normal.
8936   if (inExplicitITBlock() || !isThumbTwo() || !useImplicitITThumb())
8937     return MatchInstructionImpl(Operands, Inst, &NearMisses, MatchingInlineAsm);
8938 
8939   // Try to match the instruction in an extension of the current IT block (if
8940   // there is one).
8941   if (inImplicitITBlock()) {
8942     extendImplicitITBlock(ITState.Cond);
8943     if (MatchInstructionImpl(Operands, Inst, nullptr, MatchingInlineAsm) ==
8944             Match_Success) {
8945       // The match succeded, but we still have to check that the instruction is
8946       // valid in this implicit IT block.
8947       const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
8948       if (MCID.isPredicable()) {
8949         ARMCC::CondCodes InstCond =
8950             (ARMCC::CondCodes)Inst.getOperand(MCID.findFirstPredOperandIdx())
8951                 .getImm();
8952         ARMCC::CondCodes ITCond = currentITCond();
8953         if (InstCond == ITCond) {
8954           EmitInITBlock = true;
8955           return Match_Success;
8956         } else if (InstCond == ARMCC::getOppositeCondition(ITCond)) {
8957           invertCurrentITCondition();
8958           EmitInITBlock = true;
8959           return Match_Success;
8960         }
8961       }
8962     }
8963     rewindImplicitITPosition();
8964   }
8965 
8966   // Finish the current IT block, and try to match outside any IT block.
8967   flushPendingInstructions(Out);
8968   unsigned PlainMatchResult =
8969       MatchInstructionImpl(Operands, Inst, &NearMisses, MatchingInlineAsm);
8970   if (PlainMatchResult == Match_Success) {
8971     const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
8972     if (MCID.isPredicable()) {
8973       ARMCC::CondCodes InstCond =
8974           (ARMCC::CondCodes)Inst.getOperand(MCID.findFirstPredOperandIdx())
8975               .getImm();
8976       // Some forms of the branch instruction have their own condition code
8977       // fields, so can be conditionally executed without an IT block.
8978       if (Inst.getOpcode() == ARM::tBcc || Inst.getOpcode() == ARM::t2Bcc) {
8979         EmitInITBlock = false;
8980         return Match_Success;
8981       }
8982       if (InstCond == ARMCC::AL) {
8983         EmitInITBlock = false;
8984         return Match_Success;
8985       }
8986     } else {
8987       EmitInITBlock = false;
8988       return Match_Success;
8989     }
8990   }
8991 
8992   // Try to match in a new IT block. The matcher doesn't check the actual
8993   // condition, so we create an IT block with a dummy condition, and fix it up
8994   // once we know the actual condition.
8995   startImplicitITBlock();
8996   if (MatchInstructionImpl(Operands, Inst, nullptr, MatchingInlineAsm) ==
8997       Match_Success) {
8998     const MCInstrDesc &MCID = MII.get(Inst.getOpcode());
8999     if (MCID.isPredicable()) {
9000       ITState.Cond =
9001           (ARMCC::CondCodes)Inst.getOperand(MCID.findFirstPredOperandIdx())
9002               .getImm();
9003       EmitInITBlock = true;
9004       return Match_Success;
9005     }
9006   }
9007   discardImplicitITBlock();
9008 
9009   // If none of these succeed, return the error we got when trying to match
9010   // outside any IT blocks.
9011   EmitInITBlock = false;
9012   return PlainMatchResult;
9013 }
9014 
9015 std::string ARMMnemonicSpellCheck(StringRef S, uint64_t FBS);
9016 
9017 static const char *getSubtargetFeatureName(uint64_t Val);
9018 bool ARMAsmParser::MatchAndEmitInstruction(SMLoc IDLoc, unsigned &Opcode,
9019                                            OperandVector &Operands,
9020                                            MCStreamer &Out, uint64_t &ErrorInfo,
9021                                            bool MatchingInlineAsm) {
9022   MCInst Inst;
9023   unsigned MatchResult;
9024   bool PendConditionalInstruction = false;
9025 
9026   SmallVector<NearMissInfo, 4> NearMisses;
9027   MatchResult = MatchInstruction(Operands, Inst, NearMisses, MatchingInlineAsm,
9028                                  PendConditionalInstruction, Out);
9029 
9030   switch (MatchResult) {
9031   case Match_Success:
9032     // Context sensitive operand constraints aren't handled by the matcher,
9033     // so check them here.
9034     if (validateInstruction(Inst, Operands)) {
9035       // Still progress the IT block, otherwise one wrong condition causes
9036       // nasty cascading errors.
9037       forwardITPosition();
9038       return true;
9039     }
9040 
9041     { // processInstruction() updates inITBlock state, we need to save it away
9042       bool wasInITBlock = inITBlock();
9043 
9044       // Some instructions need post-processing to, for example, tweak which
9045       // encoding is selected. Loop on it while changes happen so the
9046       // individual transformations can chain off each other. E.g.,
9047       // tPOP(r8)->t2LDMIA_UPD(sp,r8)->t2STR_POST(sp,r8)
9048       while (processInstruction(Inst, Operands, Out))
9049         ;
9050 
9051       // Only after the instruction is fully processed, we can validate it
9052       if (wasInITBlock && hasV8Ops() && isThumb() &&
9053           !isV8EligibleForIT(&Inst)) {
9054         Warning(IDLoc, "deprecated instruction in IT block");
9055       }
9056     }
9057 
9058     // Only move forward at the very end so that everything in validate
9059     // and process gets a consistent answer about whether we're in an IT
9060     // block.
9061     forwardITPosition();
9062 
9063     // ITasm is an ARM mode pseudo-instruction that just sets the ITblock and
9064     // doesn't actually encode.
9065     if (Inst.getOpcode() == ARM::ITasm)
9066       return false;
9067 
9068     Inst.setLoc(IDLoc);
9069     if (PendConditionalInstruction) {
9070       PendingConditionalInsts.push_back(Inst);
9071       if (isITBlockFull() || isITBlockTerminator(Inst))
9072         flushPendingInstructions(Out);
9073     } else {
9074       Out.EmitInstruction(Inst, getSTI());
9075     }
9076     return false;
9077   case Match_NearMisses:
9078     ReportNearMisses(NearMisses, IDLoc, Operands);
9079     return true;
9080   case Match_MnemonicFail: {
9081     uint64_t FBS = ComputeAvailableFeatures(getSTI().getFeatureBits());
9082     std::string Suggestion = ARMMnemonicSpellCheck(
9083       ((ARMOperand &)*Operands[0]).getToken(), FBS);
9084     return Error(IDLoc, "invalid instruction" + Suggestion,
9085                  ((ARMOperand &)*Operands[0]).getLocRange());
9086   }
9087   }
9088 
9089   llvm_unreachable("Implement any new match types added!");
9090 }
9091 
9092 /// parseDirective parses the arm specific directives
9093 bool ARMAsmParser::ParseDirective(AsmToken DirectiveID) {
9094   const MCObjectFileInfo::Environment Format =
9095     getContext().getObjectFileInfo()->getObjectFileType();
9096   bool IsMachO = Format == MCObjectFileInfo::IsMachO;
9097   bool IsCOFF = Format == MCObjectFileInfo::IsCOFF;
9098 
9099   StringRef IDVal = DirectiveID.getIdentifier();
9100   if (IDVal == ".word")
9101     parseLiteralValues(4, DirectiveID.getLoc());
9102   else if (IDVal == ".short" || IDVal == ".hword")
9103     parseLiteralValues(2, DirectiveID.getLoc());
9104   else if (IDVal == ".thumb")
9105     parseDirectiveThumb(DirectiveID.getLoc());
9106   else if (IDVal == ".arm")
9107     parseDirectiveARM(DirectiveID.getLoc());
9108   else if (IDVal == ".thumb_func")
9109     parseDirectiveThumbFunc(DirectiveID.getLoc());
9110   else if (IDVal == ".code")
9111     parseDirectiveCode(DirectiveID.getLoc());
9112   else if (IDVal == ".syntax")
9113     parseDirectiveSyntax(DirectiveID.getLoc());
9114   else if (IDVal == ".unreq")
9115     parseDirectiveUnreq(DirectiveID.getLoc());
9116   else if (IDVal == ".fnend")
9117     parseDirectiveFnEnd(DirectiveID.getLoc());
9118   else if (IDVal == ".cantunwind")
9119     parseDirectiveCantUnwind(DirectiveID.getLoc());
9120   else if (IDVal == ".personality")
9121     parseDirectivePersonality(DirectiveID.getLoc());
9122   else if (IDVal == ".handlerdata")
9123     parseDirectiveHandlerData(DirectiveID.getLoc());
9124   else if (IDVal == ".setfp")
9125     parseDirectiveSetFP(DirectiveID.getLoc());
9126   else if (IDVal == ".pad")
9127     parseDirectivePad(DirectiveID.getLoc());
9128   else if (IDVal == ".save")
9129     parseDirectiveRegSave(DirectiveID.getLoc(), false);
9130   else if (IDVal == ".vsave")
9131     parseDirectiveRegSave(DirectiveID.getLoc(), true);
9132   else if (IDVal == ".ltorg" || IDVal == ".pool")
9133     parseDirectiveLtorg(DirectiveID.getLoc());
9134   else if (IDVal == ".even")
9135     parseDirectiveEven(DirectiveID.getLoc());
9136   else if (IDVal == ".personalityindex")
9137     parseDirectivePersonalityIndex(DirectiveID.getLoc());
9138   else if (IDVal == ".unwind_raw")
9139     parseDirectiveUnwindRaw(DirectiveID.getLoc());
9140   else if (IDVal == ".movsp")
9141     parseDirectiveMovSP(DirectiveID.getLoc());
9142   else if (IDVal == ".arch_extension")
9143     parseDirectiveArchExtension(DirectiveID.getLoc());
9144   else if (IDVal == ".align")
9145     return parseDirectiveAlign(DirectiveID.getLoc()); // Use Generic on failure.
9146   else if (IDVal == ".thumb_set")
9147     parseDirectiveThumbSet(DirectiveID.getLoc());
9148   else if (!IsMachO && !IsCOFF) {
9149     if (IDVal == ".arch")
9150       parseDirectiveArch(DirectiveID.getLoc());
9151     else if (IDVal == ".cpu")
9152       parseDirectiveCPU(DirectiveID.getLoc());
9153     else if (IDVal == ".eabi_attribute")
9154       parseDirectiveEabiAttr(DirectiveID.getLoc());
9155     else if (IDVal == ".fpu")
9156       parseDirectiveFPU(DirectiveID.getLoc());
9157     else if (IDVal == ".fnstart")
9158       parseDirectiveFnStart(DirectiveID.getLoc());
9159     else if (IDVal == ".inst")
9160       parseDirectiveInst(DirectiveID.getLoc());
9161     else if (IDVal == ".inst.n")
9162       parseDirectiveInst(DirectiveID.getLoc(), 'n');
9163     else if (IDVal == ".inst.w")
9164       parseDirectiveInst(DirectiveID.getLoc(), 'w');
9165     else if (IDVal == ".object_arch")
9166       parseDirectiveObjectArch(DirectiveID.getLoc());
9167     else if (IDVal == ".tlsdescseq")
9168       parseDirectiveTLSDescSeq(DirectiveID.getLoc());
9169     else
9170       return true;
9171   } else
9172     return true;
9173   return false;
9174 }
9175 
9176 /// parseLiteralValues
9177 ///  ::= .hword expression [, expression]*
9178 ///  ::= .short expression [, expression]*
9179 ///  ::= .word expression [, expression]*
9180 bool ARMAsmParser::parseLiteralValues(unsigned Size, SMLoc L) {
9181   auto parseOne = [&]() -> bool {
9182     const MCExpr *Value;
9183     if (getParser().parseExpression(Value))
9184       return true;
9185     getParser().getStreamer().EmitValue(Value, Size, L);
9186     return false;
9187   };
9188   return (parseMany(parseOne));
9189 }
9190 
9191 /// parseDirectiveThumb
9192 ///  ::= .thumb
9193 bool ARMAsmParser::parseDirectiveThumb(SMLoc L) {
9194   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive") ||
9195       check(!hasThumb(), L, "target does not support Thumb mode"))
9196     return true;
9197 
9198   if (!isThumb())
9199     SwitchMode();
9200 
9201   getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
9202   return false;
9203 }
9204 
9205 /// parseDirectiveARM
9206 ///  ::= .arm
9207 bool ARMAsmParser::parseDirectiveARM(SMLoc L) {
9208   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive") ||
9209       check(!hasARM(), L, "target does not support ARM mode"))
9210     return true;
9211 
9212   if (isThumb())
9213     SwitchMode();
9214   getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
9215   return false;
9216 }
9217 
9218 void ARMAsmParser::onLabelParsed(MCSymbol *Symbol) {
9219   // We need to flush the current implicit IT block on a label, because it is
9220   // not legal to branch into an IT block.
9221   flushPendingInstructions(getStreamer());
9222   if (NextSymbolIsThumb) {
9223     getParser().getStreamer().EmitThumbFunc(Symbol);
9224     NextSymbolIsThumb = false;
9225   }
9226 }
9227 
9228 /// parseDirectiveThumbFunc
9229 ///  ::= .thumbfunc symbol_name
9230 bool ARMAsmParser::parseDirectiveThumbFunc(SMLoc L) {
9231   MCAsmParser &Parser = getParser();
9232   const auto Format = getContext().getObjectFileInfo()->getObjectFileType();
9233   bool IsMachO = Format == MCObjectFileInfo::IsMachO;
9234 
9235   // Darwin asm has (optionally) function name after .thumb_func direction
9236   // ELF doesn't
9237 
9238   if (IsMachO) {
9239     if (Parser.getTok().is(AsmToken::Identifier) ||
9240         Parser.getTok().is(AsmToken::String)) {
9241       MCSymbol *Func = getParser().getContext().getOrCreateSymbol(
9242           Parser.getTok().getIdentifier());
9243       getParser().getStreamer().EmitThumbFunc(Func);
9244       Parser.Lex();
9245       if (parseToken(AsmToken::EndOfStatement,
9246                      "unexpected token in '.thumb_func' directive"))
9247         return true;
9248       return false;
9249     }
9250   }
9251 
9252   if (parseToken(AsmToken::EndOfStatement,
9253                  "unexpected token in '.thumb_func' directive"))
9254     return true;
9255 
9256   NextSymbolIsThumb = true;
9257   return false;
9258 }
9259 
9260 /// parseDirectiveSyntax
9261 ///  ::= .syntax unified | divided
9262 bool ARMAsmParser::parseDirectiveSyntax(SMLoc L) {
9263   MCAsmParser &Parser = getParser();
9264   const AsmToken &Tok = Parser.getTok();
9265   if (Tok.isNot(AsmToken::Identifier)) {
9266     Error(L, "unexpected token in .syntax directive");
9267     return false;
9268   }
9269 
9270   StringRef Mode = Tok.getString();
9271   Parser.Lex();
9272   if (check(Mode == "divided" || Mode == "DIVIDED", L,
9273             "'.syntax divided' arm assembly not supported") ||
9274       check(Mode != "unified" && Mode != "UNIFIED", L,
9275             "unrecognized syntax mode in .syntax directive") ||
9276       parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
9277     return true;
9278 
9279   // TODO tell the MC streamer the mode
9280   // getParser().getStreamer().Emit???();
9281   return false;
9282 }
9283 
9284 /// parseDirectiveCode
9285 ///  ::= .code 16 | 32
9286 bool ARMAsmParser::parseDirectiveCode(SMLoc L) {
9287   MCAsmParser &Parser = getParser();
9288   const AsmToken &Tok = Parser.getTok();
9289   if (Tok.isNot(AsmToken::Integer))
9290     return Error(L, "unexpected token in .code directive");
9291   int64_t Val = Parser.getTok().getIntVal();
9292   if (Val != 16 && Val != 32) {
9293     Error(L, "invalid operand to .code directive");
9294     return false;
9295   }
9296   Parser.Lex();
9297 
9298   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
9299     return true;
9300 
9301   if (Val == 16) {
9302     if (!hasThumb())
9303       return Error(L, "target does not support Thumb mode");
9304 
9305     if (!isThumb())
9306       SwitchMode();
9307     getParser().getStreamer().EmitAssemblerFlag(MCAF_Code16);
9308   } else {
9309     if (!hasARM())
9310       return Error(L, "target does not support ARM mode");
9311 
9312     if (isThumb())
9313       SwitchMode();
9314     getParser().getStreamer().EmitAssemblerFlag(MCAF_Code32);
9315   }
9316 
9317   return false;
9318 }
9319 
9320 /// parseDirectiveReq
9321 ///  ::= name .req registername
9322 bool ARMAsmParser::parseDirectiveReq(StringRef Name, SMLoc L) {
9323   MCAsmParser &Parser = getParser();
9324   Parser.Lex(); // Eat the '.req' token.
9325   unsigned Reg;
9326   SMLoc SRegLoc, ERegLoc;
9327   if (check(ParseRegister(Reg, SRegLoc, ERegLoc), SRegLoc,
9328             "register name expected") ||
9329       parseToken(AsmToken::EndOfStatement,
9330                  "unexpected input in .req directive."))
9331     return true;
9332 
9333   if (RegisterReqs.insert(std::make_pair(Name, Reg)).first->second != Reg)
9334     return Error(SRegLoc,
9335                  "redefinition of '" + Name + "' does not match original.");
9336 
9337   return false;
9338 }
9339 
9340 /// parseDirectiveUneq
9341 ///  ::= .unreq registername
9342 bool ARMAsmParser::parseDirectiveUnreq(SMLoc L) {
9343   MCAsmParser &Parser = getParser();
9344   if (Parser.getTok().isNot(AsmToken::Identifier))
9345     return Error(L, "unexpected input in .unreq directive.");
9346   RegisterReqs.erase(Parser.getTok().getIdentifier().lower());
9347   Parser.Lex(); // Eat the identifier.
9348   if (parseToken(AsmToken::EndOfStatement,
9349                  "unexpected input in '.unreq' directive"))
9350     return true;
9351   return false;
9352 }
9353 
9354 // After changing arch/CPU, try to put the ARM/Thumb mode back to what it was
9355 // before, if supported by the new target, or emit mapping symbols for the mode
9356 // switch.
9357 void ARMAsmParser::FixModeAfterArchChange(bool WasThumb, SMLoc Loc) {
9358   if (WasThumb != isThumb()) {
9359     if (WasThumb && hasThumb()) {
9360       // Stay in Thumb mode
9361       SwitchMode();
9362     } else if (!WasThumb && hasARM()) {
9363       // Stay in ARM mode
9364       SwitchMode();
9365     } else {
9366       // Mode switch forced, because the new arch doesn't support the old mode.
9367       getParser().getStreamer().EmitAssemblerFlag(isThumb() ? MCAF_Code16
9368                                                             : MCAF_Code32);
9369       // Warn about the implcit mode switch. GAS does not switch modes here,
9370       // but instead stays in the old mode, reporting an error on any following
9371       // instructions as the mode does not exist on the target.
9372       Warning(Loc, Twine("new target does not support ") +
9373                        (WasThumb ? "thumb" : "arm") + " mode, switching to " +
9374                        (!WasThumb ? "thumb" : "arm") + " mode");
9375     }
9376   }
9377 }
9378 
9379 /// parseDirectiveArch
9380 ///  ::= .arch token
9381 bool ARMAsmParser::parseDirectiveArch(SMLoc L) {
9382   StringRef Arch = getParser().parseStringToEndOfStatement().trim();
9383   ARM::ArchKind ID = ARM::parseArch(Arch);
9384 
9385   if (ID == ARM::ArchKind::INVALID)
9386     return Error(L, "Unknown arch name");
9387 
9388   bool WasThumb = isThumb();
9389   Triple T;
9390   MCSubtargetInfo &STI = copySTI();
9391   STI.setDefaultFeatures("", ("+" + ARM::getArchName(ID)).str());
9392   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
9393   FixModeAfterArchChange(WasThumb, L);
9394 
9395   getTargetStreamer().emitArch(ID);
9396   return false;
9397 }
9398 
9399 /// parseDirectiveEabiAttr
9400 ///  ::= .eabi_attribute int, int [, "str"]
9401 ///  ::= .eabi_attribute Tag_name, int [, "str"]
9402 bool ARMAsmParser::parseDirectiveEabiAttr(SMLoc L) {
9403   MCAsmParser &Parser = getParser();
9404   int64_t Tag;
9405   SMLoc TagLoc;
9406   TagLoc = Parser.getTok().getLoc();
9407   if (Parser.getTok().is(AsmToken::Identifier)) {
9408     StringRef Name = Parser.getTok().getIdentifier();
9409     Tag = ARMBuildAttrs::AttrTypeFromString(Name);
9410     if (Tag == -1) {
9411       Error(TagLoc, "attribute name not recognised: " + Name);
9412       return false;
9413     }
9414     Parser.Lex();
9415   } else {
9416     const MCExpr *AttrExpr;
9417 
9418     TagLoc = Parser.getTok().getLoc();
9419     if (Parser.parseExpression(AttrExpr))
9420       return true;
9421 
9422     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(AttrExpr);
9423     if (check(!CE, TagLoc, "expected numeric constant"))
9424       return true;
9425 
9426     Tag = CE->getValue();
9427   }
9428 
9429   if (Parser.parseToken(AsmToken::Comma, "comma expected"))
9430     return true;
9431 
9432   StringRef StringValue = "";
9433   bool IsStringValue = false;
9434 
9435   int64_t IntegerValue = 0;
9436   bool IsIntegerValue = false;
9437 
9438   if (Tag == ARMBuildAttrs::CPU_raw_name || Tag == ARMBuildAttrs::CPU_name)
9439     IsStringValue = true;
9440   else if (Tag == ARMBuildAttrs::compatibility) {
9441     IsStringValue = true;
9442     IsIntegerValue = true;
9443   } else if (Tag < 32 || Tag % 2 == 0)
9444     IsIntegerValue = true;
9445   else if (Tag % 2 == 1)
9446     IsStringValue = true;
9447   else
9448     llvm_unreachable("invalid tag type");
9449 
9450   if (IsIntegerValue) {
9451     const MCExpr *ValueExpr;
9452     SMLoc ValueExprLoc = Parser.getTok().getLoc();
9453     if (Parser.parseExpression(ValueExpr))
9454       return true;
9455 
9456     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(ValueExpr);
9457     if (!CE)
9458       return Error(ValueExprLoc, "expected numeric constant");
9459     IntegerValue = CE->getValue();
9460   }
9461 
9462   if (Tag == ARMBuildAttrs::compatibility) {
9463     if (Parser.parseToken(AsmToken::Comma, "comma expected"))
9464       return true;
9465   }
9466 
9467   if (IsStringValue) {
9468     if (Parser.getTok().isNot(AsmToken::String))
9469       return Error(Parser.getTok().getLoc(), "bad string constant");
9470 
9471     StringValue = Parser.getTok().getStringContents();
9472     Parser.Lex();
9473   }
9474 
9475   if (Parser.parseToken(AsmToken::EndOfStatement,
9476                         "unexpected token in '.eabi_attribute' directive"))
9477     return true;
9478 
9479   if (IsIntegerValue && IsStringValue) {
9480     assert(Tag == ARMBuildAttrs::compatibility);
9481     getTargetStreamer().emitIntTextAttribute(Tag, IntegerValue, StringValue);
9482   } else if (IsIntegerValue)
9483     getTargetStreamer().emitAttribute(Tag, IntegerValue);
9484   else if (IsStringValue)
9485     getTargetStreamer().emitTextAttribute(Tag, StringValue);
9486   return false;
9487 }
9488 
9489 /// parseDirectiveCPU
9490 ///  ::= .cpu str
9491 bool ARMAsmParser::parseDirectiveCPU(SMLoc L) {
9492   StringRef CPU = getParser().parseStringToEndOfStatement().trim();
9493   getTargetStreamer().emitTextAttribute(ARMBuildAttrs::CPU_name, CPU);
9494 
9495   // FIXME: This is using table-gen data, but should be moved to
9496   // ARMTargetParser once that is table-gen'd.
9497   if (!getSTI().isCPUStringValid(CPU))
9498     return Error(L, "Unknown CPU name");
9499 
9500   bool WasThumb = isThumb();
9501   MCSubtargetInfo &STI = copySTI();
9502   STI.setDefaultFeatures(CPU, "");
9503   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
9504   FixModeAfterArchChange(WasThumb, L);
9505 
9506   return false;
9507 }
9508 
9509 /// parseDirectiveFPU
9510 ///  ::= .fpu str
9511 bool ARMAsmParser::parseDirectiveFPU(SMLoc L) {
9512   SMLoc FPUNameLoc = getTok().getLoc();
9513   StringRef FPU = getParser().parseStringToEndOfStatement().trim();
9514 
9515   unsigned ID = ARM::parseFPU(FPU);
9516   std::vector<StringRef> Features;
9517   if (!ARM::getFPUFeatures(ID, Features))
9518     return Error(FPUNameLoc, "Unknown FPU name");
9519 
9520   MCSubtargetInfo &STI = copySTI();
9521   for (auto Feature : Features)
9522     STI.ApplyFeatureFlag(Feature);
9523   setAvailableFeatures(ComputeAvailableFeatures(STI.getFeatureBits()));
9524 
9525   getTargetStreamer().emitFPU(ID);
9526   return false;
9527 }
9528 
9529 /// parseDirectiveFnStart
9530 ///  ::= .fnstart
9531 bool ARMAsmParser::parseDirectiveFnStart(SMLoc L) {
9532   if (parseToken(AsmToken::EndOfStatement,
9533                  "unexpected token in '.fnstart' directive"))
9534     return true;
9535 
9536   if (UC.hasFnStart()) {
9537     Error(L, ".fnstart starts before the end of previous one");
9538     UC.emitFnStartLocNotes();
9539     return true;
9540   }
9541 
9542   // Reset the unwind directives parser state
9543   UC.reset();
9544 
9545   getTargetStreamer().emitFnStart();
9546 
9547   UC.recordFnStart(L);
9548   return false;
9549 }
9550 
9551 /// parseDirectiveFnEnd
9552 ///  ::= .fnend
9553 bool ARMAsmParser::parseDirectiveFnEnd(SMLoc L) {
9554   if (parseToken(AsmToken::EndOfStatement,
9555                  "unexpected token in '.fnend' directive"))
9556     return true;
9557   // Check the ordering of unwind directives
9558   if (!UC.hasFnStart())
9559     return Error(L, ".fnstart must precede .fnend directive");
9560 
9561   // Reset the unwind directives parser state
9562   getTargetStreamer().emitFnEnd();
9563 
9564   UC.reset();
9565   return false;
9566 }
9567 
9568 /// parseDirectiveCantUnwind
9569 ///  ::= .cantunwind
9570 bool ARMAsmParser::parseDirectiveCantUnwind(SMLoc L) {
9571   if (parseToken(AsmToken::EndOfStatement,
9572                  "unexpected token in '.cantunwind' directive"))
9573     return true;
9574 
9575   UC.recordCantUnwind(L);
9576   // Check the ordering of unwind directives
9577   if (check(!UC.hasFnStart(), L, ".fnstart must precede .cantunwind directive"))
9578     return true;
9579 
9580   if (UC.hasHandlerData()) {
9581     Error(L, ".cantunwind can't be used with .handlerdata directive");
9582     UC.emitHandlerDataLocNotes();
9583     return true;
9584   }
9585   if (UC.hasPersonality()) {
9586     Error(L, ".cantunwind can't be used with .personality directive");
9587     UC.emitPersonalityLocNotes();
9588     return true;
9589   }
9590 
9591   getTargetStreamer().emitCantUnwind();
9592   return false;
9593 }
9594 
9595 /// parseDirectivePersonality
9596 ///  ::= .personality name
9597 bool ARMAsmParser::parseDirectivePersonality(SMLoc L) {
9598   MCAsmParser &Parser = getParser();
9599   bool HasExistingPersonality = UC.hasPersonality();
9600 
9601   // Parse the name of the personality routine
9602   if (Parser.getTok().isNot(AsmToken::Identifier))
9603     return Error(L, "unexpected input in .personality directive.");
9604   StringRef Name(Parser.getTok().getIdentifier());
9605   Parser.Lex();
9606 
9607   if (parseToken(AsmToken::EndOfStatement,
9608                  "unexpected token in '.personality' directive"))
9609     return true;
9610 
9611   UC.recordPersonality(L);
9612 
9613   // Check the ordering of unwind directives
9614   if (!UC.hasFnStart())
9615     return Error(L, ".fnstart must precede .personality directive");
9616   if (UC.cantUnwind()) {
9617     Error(L, ".personality can't be used with .cantunwind directive");
9618     UC.emitCantUnwindLocNotes();
9619     return true;
9620   }
9621   if (UC.hasHandlerData()) {
9622     Error(L, ".personality must precede .handlerdata directive");
9623     UC.emitHandlerDataLocNotes();
9624     return true;
9625   }
9626   if (HasExistingPersonality) {
9627     Error(L, "multiple personality directives");
9628     UC.emitPersonalityLocNotes();
9629     return true;
9630   }
9631 
9632   MCSymbol *PR = getParser().getContext().getOrCreateSymbol(Name);
9633   getTargetStreamer().emitPersonality(PR);
9634   return false;
9635 }
9636 
9637 /// parseDirectiveHandlerData
9638 ///  ::= .handlerdata
9639 bool ARMAsmParser::parseDirectiveHandlerData(SMLoc L) {
9640   if (parseToken(AsmToken::EndOfStatement,
9641                  "unexpected token in '.handlerdata' directive"))
9642     return true;
9643 
9644   UC.recordHandlerData(L);
9645   // Check the ordering of unwind directives
9646   if (!UC.hasFnStart())
9647     return Error(L, ".fnstart must precede .personality directive");
9648   if (UC.cantUnwind()) {
9649     Error(L, ".handlerdata can't be used with .cantunwind directive");
9650     UC.emitCantUnwindLocNotes();
9651     return true;
9652   }
9653 
9654   getTargetStreamer().emitHandlerData();
9655   return false;
9656 }
9657 
9658 /// parseDirectiveSetFP
9659 ///  ::= .setfp fpreg, spreg [, offset]
9660 bool ARMAsmParser::parseDirectiveSetFP(SMLoc L) {
9661   MCAsmParser &Parser = getParser();
9662   // Check the ordering of unwind directives
9663   if (check(!UC.hasFnStart(), L, ".fnstart must precede .setfp directive") ||
9664       check(UC.hasHandlerData(), L,
9665             ".setfp must precede .handlerdata directive"))
9666     return true;
9667 
9668   // Parse fpreg
9669   SMLoc FPRegLoc = Parser.getTok().getLoc();
9670   int FPReg = tryParseRegister();
9671 
9672   if (check(FPReg == -1, FPRegLoc, "frame pointer register expected") ||
9673       Parser.parseToken(AsmToken::Comma, "comma expected"))
9674     return true;
9675 
9676   // Parse spreg
9677   SMLoc SPRegLoc = Parser.getTok().getLoc();
9678   int SPReg = tryParseRegister();
9679   if (check(SPReg == -1, SPRegLoc, "stack pointer register expected") ||
9680       check(SPReg != ARM::SP && SPReg != UC.getFPReg(), SPRegLoc,
9681             "register should be either $sp or the latest fp register"))
9682     return true;
9683 
9684   // Update the frame pointer register
9685   UC.saveFPReg(FPReg);
9686 
9687   // Parse offset
9688   int64_t Offset = 0;
9689   if (Parser.parseOptionalToken(AsmToken::Comma)) {
9690     if (Parser.getTok().isNot(AsmToken::Hash) &&
9691         Parser.getTok().isNot(AsmToken::Dollar))
9692       return Error(Parser.getTok().getLoc(), "'#' expected");
9693     Parser.Lex(); // skip hash token.
9694 
9695     const MCExpr *OffsetExpr;
9696     SMLoc ExLoc = Parser.getTok().getLoc();
9697     SMLoc EndLoc;
9698     if (getParser().parseExpression(OffsetExpr, EndLoc))
9699       return Error(ExLoc, "malformed setfp offset");
9700     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
9701     if (check(!CE, ExLoc, "setfp offset must be an immediate"))
9702       return true;
9703     Offset = CE->getValue();
9704   }
9705 
9706   if (Parser.parseToken(AsmToken::EndOfStatement))
9707     return true;
9708 
9709   getTargetStreamer().emitSetFP(static_cast<unsigned>(FPReg),
9710                                 static_cast<unsigned>(SPReg), Offset);
9711   return false;
9712 }
9713 
9714 /// parseDirective
9715 ///  ::= .pad offset
9716 bool ARMAsmParser::parseDirectivePad(SMLoc L) {
9717   MCAsmParser &Parser = getParser();
9718   // Check the ordering of unwind directives
9719   if (!UC.hasFnStart())
9720     return Error(L, ".fnstart must precede .pad directive");
9721   if (UC.hasHandlerData())
9722     return Error(L, ".pad must precede .handlerdata directive");
9723 
9724   // Parse the offset
9725   if (Parser.getTok().isNot(AsmToken::Hash) &&
9726       Parser.getTok().isNot(AsmToken::Dollar))
9727     return Error(Parser.getTok().getLoc(), "'#' expected");
9728   Parser.Lex(); // skip hash token.
9729 
9730   const MCExpr *OffsetExpr;
9731   SMLoc ExLoc = Parser.getTok().getLoc();
9732   SMLoc EndLoc;
9733   if (getParser().parseExpression(OffsetExpr, EndLoc))
9734     return Error(ExLoc, "malformed pad offset");
9735   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
9736   if (!CE)
9737     return Error(ExLoc, "pad offset must be an immediate");
9738 
9739   if (parseToken(AsmToken::EndOfStatement,
9740                  "unexpected token in '.pad' directive"))
9741     return true;
9742 
9743   getTargetStreamer().emitPad(CE->getValue());
9744   return false;
9745 }
9746 
9747 /// parseDirectiveRegSave
9748 ///  ::= .save  { registers }
9749 ///  ::= .vsave { registers }
9750 bool ARMAsmParser::parseDirectiveRegSave(SMLoc L, bool IsVector) {
9751   // Check the ordering of unwind directives
9752   if (!UC.hasFnStart())
9753     return Error(L, ".fnstart must precede .save or .vsave directives");
9754   if (UC.hasHandlerData())
9755     return Error(L, ".save or .vsave must precede .handlerdata directive");
9756 
9757   // RAII object to make sure parsed operands are deleted.
9758   SmallVector<std::unique_ptr<MCParsedAsmOperand>, 1> Operands;
9759 
9760   // Parse the register list
9761   if (parseRegisterList(Operands) ||
9762       parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
9763     return true;
9764   ARMOperand &Op = (ARMOperand &)*Operands[0];
9765   if (!IsVector && !Op.isRegList())
9766     return Error(L, ".save expects GPR registers");
9767   if (IsVector && !Op.isDPRRegList())
9768     return Error(L, ".vsave expects DPR registers");
9769 
9770   getTargetStreamer().emitRegSave(Op.getRegList(), IsVector);
9771   return false;
9772 }
9773 
9774 /// parseDirectiveInst
9775 ///  ::= .inst opcode [, ...]
9776 ///  ::= .inst.n opcode [, ...]
9777 ///  ::= .inst.w opcode [, ...]
9778 bool ARMAsmParser::parseDirectiveInst(SMLoc Loc, char Suffix) {
9779   int Width = 4;
9780 
9781   if (isThumb()) {
9782     switch (Suffix) {
9783     case 'n':
9784       Width = 2;
9785       break;
9786     case 'w':
9787       break;
9788     default:
9789       return Error(Loc, "cannot determine Thumb instruction size, "
9790                         "use inst.n/inst.w instead");
9791     }
9792   } else {
9793     if (Suffix)
9794       return Error(Loc, "width suffixes are invalid in ARM mode");
9795   }
9796 
9797   auto parseOne = [&]() -> bool {
9798     const MCExpr *Expr;
9799     if (getParser().parseExpression(Expr))
9800       return true;
9801     const MCConstantExpr *Value = dyn_cast_or_null<MCConstantExpr>(Expr);
9802     if (!Value) {
9803       return Error(Loc, "expected constant expression");
9804     }
9805 
9806     switch (Width) {
9807     case 2:
9808       if (Value->getValue() > 0xffff)
9809         return Error(Loc, "inst.n operand is too big, use inst.w instead");
9810       break;
9811     case 4:
9812       if (Value->getValue() > 0xffffffff)
9813         return Error(Loc, StringRef(Suffix ? "inst.w" : "inst") +
9814                               " operand is too big");
9815       break;
9816     default:
9817       llvm_unreachable("only supported widths are 2 and 4");
9818     }
9819 
9820     getTargetStreamer().emitInst(Value->getValue(), Suffix);
9821     return false;
9822   };
9823 
9824   if (parseOptionalToken(AsmToken::EndOfStatement))
9825     return Error(Loc, "expected expression following directive");
9826   if (parseMany(parseOne))
9827     return true;
9828   return false;
9829 }
9830 
9831 /// parseDirectiveLtorg
9832 ///  ::= .ltorg | .pool
9833 bool ARMAsmParser::parseDirectiveLtorg(SMLoc L) {
9834   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
9835     return true;
9836   getTargetStreamer().emitCurrentConstantPool();
9837   return false;
9838 }
9839 
9840 bool ARMAsmParser::parseDirectiveEven(SMLoc L) {
9841   const MCSection *Section = getStreamer().getCurrentSectionOnly();
9842 
9843   if (parseToken(AsmToken::EndOfStatement, "unexpected token in directive"))
9844     return true;
9845 
9846   if (!Section) {
9847     getStreamer().InitSections(false);
9848     Section = getStreamer().getCurrentSectionOnly();
9849   }
9850 
9851   assert(Section && "must have section to emit alignment");
9852   if (Section->UseCodeAlign())
9853     getStreamer().EmitCodeAlignment(2);
9854   else
9855     getStreamer().EmitValueToAlignment(2);
9856 
9857   return false;
9858 }
9859 
9860 /// parseDirectivePersonalityIndex
9861 ///   ::= .personalityindex index
9862 bool ARMAsmParser::parseDirectivePersonalityIndex(SMLoc L) {
9863   MCAsmParser &Parser = getParser();
9864   bool HasExistingPersonality = UC.hasPersonality();
9865 
9866   const MCExpr *IndexExpression;
9867   SMLoc IndexLoc = Parser.getTok().getLoc();
9868   if (Parser.parseExpression(IndexExpression) ||
9869       parseToken(AsmToken::EndOfStatement,
9870                  "unexpected token in '.personalityindex' directive")) {
9871     return true;
9872   }
9873 
9874   UC.recordPersonalityIndex(L);
9875 
9876   if (!UC.hasFnStart()) {
9877     return Error(L, ".fnstart must precede .personalityindex directive");
9878   }
9879   if (UC.cantUnwind()) {
9880     Error(L, ".personalityindex cannot be used with .cantunwind");
9881     UC.emitCantUnwindLocNotes();
9882     return true;
9883   }
9884   if (UC.hasHandlerData()) {
9885     Error(L, ".personalityindex must precede .handlerdata directive");
9886     UC.emitHandlerDataLocNotes();
9887     return true;
9888   }
9889   if (HasExistingPersonality) {
9890     Error(L, "multiple personality directives");
9891     UC.emitPersonalityLocNotes();
9892     return true;
9893   }
9894 
9895   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(IndexExpression);
9896   if (!CE)
9897     return Error(IndexLoc, "index must be a constant number");
9898   if (CE->getValue() < 0 || CE->getValue() >= ARM::EHABI::NUM_PERSONALITY_INDEX)
9899     return Error(IndexLoc,
9900                  "personality routine index should be in range [0-3]");
9901 
9902   getTargetStreamer().emitPersonalityIndex(CE->getValue());
9903   return false;
9904 }
9905 
9906 /// parseDirectiveUnwindRaw
9907 ///   ::= .unwind_raw offset, opcode [, opcode...]
9908 bool ARMAsmParser::parseDirectiveUnwindRaw(SMLoc L) {
9909   MCAsmParser &Parser = getParser();
9910   int64_t StackOffset;
9911   const MCExpr *OffsetExpr;
9912   SMLoc OffsetLoc = getLexer().getLoc();
9913 
9914   if (!UC.hasFnStart())
9915     return Error(L, ".fnstart must precede .unwind_raw directives");
9916   if (getParser().parseExpression(OffsetExpr))
9917     return Error(OffsetLoc, "expected expression");
9918 
9919   const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
9920   if (!CE)
9921     return Error(OffsetLoc, "offset must be a constant");
9922 
9923   StackOffset = CE->getValue();
9924 
9925   if (Parser.parseToken(AsmToken::Comma, "expected comma"))
9926     return true;
9927 
9928   SmallVector<uint8_t, 16> Opcodes;
9929 
9930   auto parseOne = [&]() -> bool {
9931     const MCExpr *OE;
9932     SMLoc OpcodeLoc = getLexer().getLoc();
9933     if (check(getLexer().is(AsmToken::EndOfStatement) ||
9934                   Parser.parseExpression(OE),
9935               OpcodeLoc, "expected opcode expression"))
9936       return true;
9937     const MCConstantExpr *OC = dyn_cast<MCConstantExpr>(OE);
9938     if (!OC)
9939       return Error(OpcodeLoc, "opcode value must be a constant");
9940     const int64_t Opcode = OC->getValue();
9941     if (Opcode & ~0xff)
9942       return Error(OpcodeLoc, "invalid opcode");
9943     Opcodes.push_back(uint8_t(Opcode));
9944     return false;
9945   };
9946 
9947   // Must have at least 1 element
9948   SMLoc OpcodeLoc = getLexer().getLoc();
9949   if (parseOptionalToken(AsmToken::EndOfStatement))
9950     return Error(OpcodeLoc, "expected opcode expression");
9951   if (parseMany(parseOne))
9952     return true;
9953 
9954   getTargetStreamer().emitUnwindRaw(StackOffset, Opcodes);
9955   return false;
9956 }
9957 
9958 /// parseDirectiveTLSDescSeq
9959 ///   ::= .tlsdescseq tls-variable
9960 bool ARMAsmParser::parseDirectiveTLSDescSeq(SMLoc L) {
9961   MCAsmParser &Parser = getParser();
9962 
9963   if (getLexer().isNot(AsmToken::Identifier))
9964     return TokError("expected variable after '.tlsdescseq' directive");
9965 
9966   const MCSymbolRefExpr *SRE =
9967     MCSymbolRefExpr::create(Parser.getTok().getIdentifier(),
9968                             MCSymbolRefExpr::VK_ARM_TLSDESCSEQ, getContext());
9969   Lex();
9970 
9971   if (parseToken(AsmToken::EndOfStatement,
9972                  "unexpected token in '.tlsdescseq' directive"))
9973     return true;
9974 
9975   getTargetStreamer().AnnotateTLSDescriptorSequence(SRE);
9976   return false;
9977 }
9978 
9979 /// parseDirectiveMovSP
9980 ///  ::= .movsp reg [, #offset]
9981 bool ARMAsmParser::parseDirectiveMovSP(SMLoc L) {
9982   MCAsmParser &Parser = getParser();
9983   if (!UC.hasFnStart())
9984     return Error(L, ".fnstart must precede .movsp directives");
9985   if (UC.getFPReg() != ARM::SP)
9986     return Error(L, "unexpected .movsp directive");
9987 
9988   SMLoc SPRegLoc = Parser.getTok().getLoc();
9989   int SPReg = tryParseRegister();
9990   if (SPReg == -1)
9991     return Error(SPRegLoc, "register expected");
9992   if (SPReg == ARM::SP || SPReg == ARM::PC)
9993     return Error(SPRegLoc, "sp and pc are not permitted in .movsp directive");
9994 
9995   int64_t Offset = 0;
9996   if (Parser.parseOptionalToken(AsmToken::Comma)) {
9997     if (Parser.parseToken(AsmToken::Hash, "expected #constant"))
9998       return true;
9999 
10000     const MCExpr *OffsetExpr;
10001     SMLoc OffsetLoc = Parser.getTok().getLoc();
10002 
10003     if (Parser.parseExpression(OffsetExpr))
10004       return Error(OffsetLoc, "malformed offset expression");
10005 
10006     const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(OffsetExpr);
10007     if (!CE)
10008       return Error(OffsetLoc, "offset must be an immediate constant");
10009 
10010     Offset = CE->getValue();
10011   }
10012 
10013   if (parseToken(AsmToken::EndOfStatement,
10014                  "unexpected token in '.movsp' directive"))
10015     return true;
10016 
10017   getTargetStreamer().emitMovSP(SPReg, Offset);
10018   UC.saveFPReg(SPReg);
10019 
10020   return false;
10021 }
10022 
10023 /// parseDirectiveObjectArch
10024 ///   ::= .object_arch name
10025 bool ARMAsmParser::parseDirectiveObjectArch(SMLoc L) {
10026   MCAsmParser &Parser = getParser();
10027   if (getLexer().isNot(AsmToken::Identifier))
10028     return Error(getLexer().getLoc(), "unexpected token");
10029 
10030   StringRef Arch = Parser.getTok().getString();
10031   SMLoc ArchLoc = Parser.getTok().getLoc();
10032   Lex();
10033 
10034   ARM::ArchKind ID = ARM::parseArch(Arch);
10035 
10036   if (ID == ARM::ArchKind::INVALID)
10037     return Error(ArchLoc, "unknown architecture '" + Arch + "'");
10038   if (parseToken(AsmToken::EndOfStatement))
10039     return true;
10040 
10041   getTargetStreamer().emitObjectArch(ID);
10042   return false;
10043 }
10044 
10045 /// parseDirectiveAlign
10046 ///   ::= .align
10047 bool ARMAsmParser::parseDirectiveAlign(SMLoc L) {
10048   // NOTE: if this is not the end of the statement, fall back to the target
10049   // agnostic handling for this directive which will correctly handle this.
10050   if (parseOptionalToken(AsmToken::EndOfStatement)) {
10051     // '.align' is target specifically handled to mean 2**2 byte alignment.
10052     const MCSection *Section = getStreamer().getCurrentSectionOnly();
10053     assert(Section && "must have section to emit alignment");
10054     if (Section->UseCodeAlign())
10055       getStreamer().EmitCodeAlignment(4, 0);
10056     else
10057       getStreamer().EmitValueToAlignment(4, 0, 1, 0);
10058     return false;
10059   }
10060   return true;
10061 }
10062 
10063 /// parseDirectiveThumbSet
10064 ///  ::= .thumb_set name, value
10065 bool ARMAsmParser::parseDirectiveThumbSet(SMLoc L) {
10066   MCAsmParser &Parser = getParser();
10067 
10068   StringRef Name;
10069   if (check(Parser.parseIdentifier(Name),
10070             "expected identifier after '.thumb_set'") ||
10071       parseToken(AsmToken::Comma, "expected comma after name '" + Name + "'"))
10072     return true;
10073 
10074   MCSymbol *Sym;
10075   const MCExpr *Value;
10076   if (MCParserUtils::parseAssignmentExpression(Name, /* allow_redef */ true,
10077                                                Parser, Sym, Value))
10078     return true;
10079 
10080   getTargetStreamer().emitThumbSet(Sym, Value);
10081   return false;
10082 }
10083 
10084 /// Force static initialization.
10085 extern "C" void LLVMInitializeARMAsmParser() {
10086   RegisterMCAsmParser<ARMAsmParser> X(getTheARMLETarget());
10087   RegisterMCAsmParser<ARMAsmParser> Y(getTheARMBETarget());
10088   RegisterMCAsmParser<ARMAsmParser> A(getTheThumbLETarget());
10089   RegisterMCAsmParser<ARMAsmParser> B(getTheThumbBETarget());
10090 }
10091 
10092 #define GET_REGISTER_MATCHER
10093 #define GET_SUBTARGET_FEATURE_NAME
10094 #define GET_MATCHER_IMPLEMENTATION
10095 #include "ARMGenAsmMatcher.inc"
10096 
10097 // Process the list of near-misses, throwing away ones we don't want to report
10098 // to the user, and converting the rest to a source location and string that
10099 // should be reported.
10100 void
10101 ARMAsmParser::FilterNearMisses(SmallVectorImpl<NearMissInfo> &NearMissesIn,
10102                                SmallVectorImpl<NearMissMessage> &NearMissesOut,
10103                                SMLoc IDLoc, OperandVector &Operands) {
10104   // TODO: If operand didn't match, sub in a dummy one and run target
10105   // predicate, so that we can avoid reporting near-misses that are invalid?
10106   // TODO: Many operand types dont have SuperClasses set, so we report
10107   // redundant ones.
10108   // TODO: Some operands are superclasses of registers (e.g.
10109   // MCK_RegShiftedImm), we don't have any way to represent that currently.
10110   // TODO: This is not all ARM-specific, can some of it be factored out?
10111 
10112   // Record some information about near-misses that we have already seen, so
10113   // that we can avoid reporting redundant ones. For example, if there are
10114   // variants of an instruction that take 8- and 16-bit immediates, we want
10115   // to only report the widest one.
10116   std::multimap<unsigned, unsigned> OperandMissesSeen;
10117   SmallSet<uint64_t, 4> FeatureMissesSeen;
10118 
10119   // Process the near-misses in reverse order, so that we see more general ones
10120   // first, and so can avoid emitting more specific ones.
10121   for (NearMissInfo &I : reverse(NearMissesIn)) {
10122     switch (I.getKind()) {
10123     case NearMissInfo::NearMissOperand: {
10124       SMLoc OperandLoc =
10125           ((ARMOperand &)*Operands[I.getOperandIndex()]).getStartLoc();
10126       const char *OperandDiag =
10127           getMatchKindDiag((ARMMatchResultTy)I.getOperandError());
10128 
10129       // If we have already emitted a message for a superclass, don't also report
10130       // the sub-class. We consider all operand classes that we don't have a
10131       // specialised diagnostic for to be equal for the propose of this check,
10132       // so that we don't report the generic error multiple times on the same
10133       // operand.
10134       unsigned DupCheckMatchClass = OperandDiag ? I.getOperandClass() : ~0U;
10135       auto PrevReports = OperandMissesSeen.equal_range(I.getOperandIndex());
10136       if (std::any_of(PrevReports.first, PrevReports.second,
10137                       [DupCheckMatchClass](
10138                           const std::pair<unsigned, unsigned> Pair) {
10139             if (DupCheckMatchClass == ~0U || Pair.second == ~0U)
10140               return Pair.second == DupCheckMatchClass;
10141             else
10142               return isSubclass((MatchClassKind)DupCheckMatchClass,
10143                                 (MatchClassKind)Pair.second);
10144           }))
10145         break;
10146       OperandMissesSeen.insert(
10147           std::make_pair(I.getOperandIndex(), DupCheckMatchClass));
10148 
10149       NearMissMessage Message;
10150       Message.Loc = OperandLoc;
10151       raw_svector_ostream OS(Message.Message);
10152       if (OperandDiag) {
10153         OS << OperandDiag;
10154       } else if (I.getOperandClass() == InvalidMatchClass) {
10155         OS << "too many operands for instruction";
10156       } else {
10157         OS << "invalid operand for instruction";
10158         if (DevDiags) {
10159           OS << " class" << I.getOperandClass() << ", error "
10160              << I.getOperandError() << ", opcode "
10161              << MII.getName(I.getOpcode());
10162         }
10163       }
10164       NearMissesOut.emplace_back(Message);
10165       break;
10166     }
10167     case NearMissInfo::NearMissFeature: {
10168       uint64_t MissingFeatures = I.getFeatures();
10169       // Don't report the same set of features twice.
10170       if (FeatureMissesSeen.count(MissingFeatures))
10171         break;
10172       FeatureMissesSeen.insert(MissingFeatures);
10173 
10174       // Special case: don't report a feature set which includes arm-mode for
10175       // targets that don't have ARM mode.
10176       if ((MissingFeatures & Feature_IsARM) && !hasARM())
10177         break;
10178       // Don't report any near-misses that both require switching instruction
10179       // set, and adding other subtarget features.
10180       if (isThumb() && (MissingFeatures & Feature_IsARM) &&
10181           (MissingFeatures & ~Feature_IsARM))
10182         break;
10183       if (!isThumb() && (MissingFeatures & Feature_IsThumb) &&
10184           (MissingFeatures & ~Feature_IsThumb))
10185         break;
10186       if (!isThumb() && (MissingFeatures & Feature_IsThumb2) &&
10187           (MissingFeatures & ~(Feature_IsThumb2 | Feature_IsThumb)))
10188         break;
10189 
10190       NearMissMessage Message;
10191       Message.Loc = IDLoc;
10192       raw_svector_ostream OS(Message.Message);
10193 
10194       OS << "instruction requires:";
10195       uint64_t Mask = 1;
10196       for (unsigned MaskPos = 0; MaskPos < (sizeof(MissingFeatures) * 8 - 1);
10197            ++MaskPos) {
10198         if (MissingFeatures & Mask) {
10199           OS << " " << getSubtargetFeatureName(MissingFeatures & Mask);
10200         }
10201         Mask <<= 1;
10202       }
10203       NearMissesOut.emplace_back(Message);
10204 
10205       break;
10206     }
10207     case NearMissInfo::NearMissPredicate: {
10208       NearMissMessage Message;
10209       Message.Loc = IDLoc;
10210       switch (I.getPredicateError()) {
10211       case Match_RequiresNotITBlock:
10212         Message.Message = "flag setting instruction only valid outside IT block";
10213         break;
10214       case Match_RequiresITBlock:
10215         Message.Message = "instruction only valid inside IT block";
10216         break;
10217       case Match_RequiresV6:
10218         Message.Message = "instruction variant requires ARMv6 or later";
10219         break;
10220       case Match_RequiresThumb2:
10221         Message.Message = "instruction variant requires Thumb2";
10222         break;
10223       case Match_RequiresV8:
10224         Message.Message = "instruction variant requires ARMv8 or later";
10225         break;
10226       case Match_RequiresFlagSetting:
10227         Message.Message = "no flag-preserving variant of this instruction available";
10228         break;
10229       case Match_InvalidOperand:
10230         Message.Message = "invalid operand for instruction";
10231         break;
10232       default:
10233         llvm_unreachable("Unhandled target predicate error");
10234         break;
10235       }
10236       NearMissesOut.emplace_back(Message);
10237       break;
10238     }
10239     case NearMissInfo::NearMissTooFewOperands: {
10240       SMLoc EndLoc = ((ARMOperand &)*Operands.back()).getEndLoc();
10241       NearMissesOut.emplace_back(
10242           NearMissMessage{ EndLoc, StringRef("too few operands for instruction") });
10243       break;
10244     }
10245     case NearMissInfo::NoNearMiss:
10246       // This should never leave the matcher.
10247       llvm_unreachable("not a near-miss");
10248       break;
10249     }
10250   }
10251 }
10252 
10253 void ARMAsmParser::ReportNearMisses(SmallVectorImpl<NearMissInfo> &NearMisses,
10254                                     SMLoc IDLoc, OperandVector &Operands) {
10255   SmallVector<NearMissMessage, 4> Messages;
10256   FilterNearMisses(NearMisses, Messages, IDLoc, Operands);
10257 
10258   if (Messages.size() == 0) {
10259     // No near-misses were found, so the best we can do is "invalid
10260     // instruction".
10261     Error(IDLoc, "invalid instruction");
10262   } else if (Messages.size() == 1) {
10263     // One near miss was found, report it as the sole error.
10264     Error(Messages[0].Loc, Messages[0].Message);
10265   } else {
10266     // More than one near miss, so report a generic "invalid instruction"
10267     // error, followed by notes for each of the near-misses.
10268     Error(IDLoc, "invalid instruction, any one of the following would fix this:");
10269     for (auto &M : Messages) {
10270       Note(M.Loc, M.Message);
10271     }
10272   }
10273 }
10274 
10275 // FIXME: This structure should be moved inside ARMTargetParser
10276 // when we start to table-generate them, and we can use the ARM
10277 // flags below, that were generated by table-gen.
10278 static const struct {
10279   const unsigned Kind;
10280   const uint64_t ArchCheck;
10281   const FeatureBitset Features;
10282 } Extensions[] = {
10283   { ARM::AEK_CRC, Feature_HasV8, {ARM::FeatureCRC} },
10284   { ARM::AEK_CRYPTO,  Feature_HasV8,
10285     {ARM::FeatureCrypto, ARM::FeatureNEON, ARM::FeatureFPARMv8} },
10286   { ARM::AEK_FP, Feature_HasV8, {ARM::FeatureFPARMv8} },
10287   { (ARM::AEK_HWDIVTHUMB | ARM::AEK_HWDIVARM), Feature_HasV7 | Feature_IsNotMClass,
10288     {ARM::FeatureHWDivThumb, ARM::FeatureHWDivARM} },
10289   { ARM::AEK_MP, Feature_HasV7 | Feature_IsNotMClass, {ARM::FeatureMP} },
10290   { ARM::AEK_SIMD, Feature_HasV8, {ARM::FeatureNEON, ARM::FeatureFPARMv8} },
10291   { ARM::AEK_SEC, Feature_HasV6K, {ARM::FeatureTrustZone} },
10292   // FIXME: Only available in A-class, isel not predicated
10293   { ARM::AEK_VIRT, Feature_HasV7, {ARM::FeatureVirtualization} },
10294   { ARM::AEK_FP16, Feature_HasV8_2a, {ARM::FeatureFPARMv8, ARM::FeatureFullFP16} },
10295   { ARM::AEK_RAS, Feature_HasV8, {ARM::FeatureRAS} },
10296   // FIXME: Unsupported extensions.
10297   { ARM::AEK_OS, Feature_None, {} },
10298   { ARM::AEK_IWMMXT, Feature_None, {} },
10299   { ARM::AEK_IWMMXT2, Feature_None, {} },
10300   { ARM::AEK_MAVERICK, Feature_None, {} },
10301   { ARM::AEK_XSCALE, Feature_None, {} },
10302 };
10303 
10304 /// parseDirectiveArchExtension
10305 ///   ::= .arch_extension [no]feature
10306 bool ARMAsmParser::parseDirectiveArchExtension(SMLoc L) {
10307   MCAsmParser &Parser = getParser();
10308 
10309   if (getLexer().isNot(AsmToken::Identifier))
10310     return Error(getLexer().getLoc(), "expected architecture extension name");
10311 
10312   StringRef Name = Parser.getTok().getString();
10313   SMLoc ExtLoc = Parser.getTok().getLoc();
10314   Lex();
10315 
10316   if (parseToken(AsmToken::EndOfStatement,
10317                  "unexpected token in '.arch_extension' directive"))
10318     return true;
10319 
10320   bool EnableFeature = true;
10321   if (Name.startswith_lower("no")) {
10322     EnableFeature = false;
10323     Name = Name.substr(2);
10324   }
10325   unsigned FeatureKind = ARM::parseArchExt(Name);
10326   if (FeatureKind == ARM::AEK_INVALID)
10327     return Error(ExtLoc, "unknown architectural extension: " + Name);
10328 
10329   for (const auto &Extension : Extensions) {
10330     if (Extension.Kind != FeatureKind)
10331       continue;
10332 
10333     if (Extension.Features.none())
10334       return Error(ExtLoc, "unsupported architectural extension: " + Name);
10335 
10336     if ((getAvailableFeatures() & Extension.ArchCheck) != Extension.ArchCheck)
10337       return Error(ExtLoc, "architectural extension '" + Name +
10338                                "' is not "
10339                                "allowed for the current base architecture");
10340 
10341     MCSubtargetInfo &STI = copySTI();
10342     FeatureBitset ToggleFeatures = EnableFeature
10343       ? (~STI.getFeatureBits() & Extension.Features)
10344       : ( STI.getFeatureBits() & Extension.Features);
10345 
10346     uint64_t Features =
10347         ComputeAvailableFeatures(STI.ToggleFeature(ToggleFeatures));
10348     setAvailableFeatures(Features);
10349     return false;
10350   }
10351 
10352   return Error(ExtLoc, "unknown architectural extension: " + Name);
10353 }
10354 
10355 // Define this matcher function after the auto-generated include so we
10356 // have the match class enum definitions.
10357 unsigned ARMAsmParser::validateTargetOperandClass(MCParsedAsmOperand &AsmOp,
10358                                                   unsigned Kind) {
10359   ARMOperand &Op = static_cast<ARMOperand &>(AsmOp);
10360   // If the kind is a token for a literal immediate, check if our asm
10361   // operand matches. This is for InstAliases which have a fixed-value
10362   // immediate in the syntax.
10363   switch (Kind) {
10364   default: break;
10365   case MCK__35_0:
10366     if (Op.isImm())
10367       if (const MCConstantExpr *CE = dyn_cast<MCConstantExpr>(Op.getImm()))
10368         if (CE->getValue() == 0)
10369           return Match_Success;
10370     break;
10371   case MCK_ModImm:
10372     if (Op.isImm()) {
10373       const MCExpr *SOExpr = Op.getImm();
10374       int64_t Value;
10375       if (!SOExpr->evaluateAsAbsolute(Value))
10376         return Match_Success;
10377       assert((Value >= std::numeric_limits<int32_t>::min() &&
10378               Value <= std::numeric_limits<uint32_t>::max()) &&
10379              "expression value must be representable in 32 bits");
10380     }
10381     break;
10382   case MCK_rGPR:
10383     if (hasV8Ops() && Op.isReg() && Op.getReg() == ARM::SP)
10384       return Match_Success;
10385     break;
10386   case MCK_GPRPair:
10387     if (Op.isReg() &&
10388         MRI->getRegClass(ARM::GPRRegClassID).contains(Op.getReg()))
10389       return Match_Success;
10390     break;
10391   }
10392   return Match_InvalidOperand;
10393 }
10394